草稿
[WIP]MoonEP rank 去重使用同机 MTE 与跨机 URMA #2
szm_thomas创建于 5 天前
[WIP]MoonEP rank 去重使用同机 MTE 与跨机 URMA #2
草稿
共 47 个文件变更+16359-699
| @@ -275,6 +275,19 @@ ShmemRuntime.init_with_buffer(group=dist.group.WORLD, enable_udma=False, qp_coun | |||
| 275 | `buffer.reduce_grad(...)`。端到端参考:`test_npu/mte/test_e2e.py`(ubmem)与 | 275 | `buffer.reduce_grad(...)`。端到端参考:`test_npu/mte/test_e2e.py`(ubmem)与 |
| 276 | `test_npu/urma/test_e2e_urma.py`(urma)。 | 276 | `test_npu/urma/test_e2e_urma.py`(urma)。 |
| 277 | 277 | ||
| 278 | +### URMA server dedup | ||
| 279 | + | ||
| 280 | +Pass `dedup_mode="server"` together with `use_udma=True` when constructing | ||
| 281 | +a Buffer on Ascend950. Server dedup groups eight consecutive ranks and | ||
| 282 | +uses two UDMA QPs per peer. Planning builds the server Combine execution plan | ||
| 283 | +alongside routing. Call `Buffer.prepare_combine_plan(plan)` collectively before | ||
| 284 | +using a manually constructed server plan for Combine. | ||
| 285 | + | ||
| 286 | +```bash | ||
| 287 | +bash npu_patch/scripts/run_test.sh --use_urma --dedup-mode server | ||
| 288 | +bash npu_patch/benchmarks/run_bench.sh bench_comm.py "--engine urma --dedup-mode server --prod" | ||
| 289 | +``` | ||
| 290 | + | ||
| 278 | ### 框架层要创建的对象:Full Weight / Full Grad / Reduce Buffer | 291 | ### 框架层要创建的对象:Full Weight / Full Grad / Reduce Buffer |
| 279 | 292 | ||
| 280 | 调度侧(dispatch/combine)的通信 chunk 与 plan 由 `Buffer` 内部管理;框架层 | 293 | 调度侧(dispatch/combine)的通信 chunk 与 plan 由 `Buffer` 内部管理;框架层 |
| @@ -24,6 +24,8 @@ import os | |||
| 24 | 24 | ||
| 25 | import torch | 25 | import torch |
| 26 | 26 | ||
| 27 | +from .planning import RANKS_PER_SERVER | ||
| 28 | + | ||
| 27 | from ._C import ( | 29 | from ._C import ( |
| 28 | acl_shmem_putmem, | 30 | acl_shmem_putmem, |
| 29 | acl_shmem_getmem, | 31 | acl_shmem_getmem, |
| @@ -83,7 +85,9 @@ BARRIER_SLOTS = 3 | |||
| 83 | OP_WS_BYTES_DEFAULT = 16 * 1024 * 1024 | 85 | OP_WS_BYTES_DEFAULT = 16 * 1024 * 1024 |
| 84 | 86 | ||
| 85 | 87 | ||
| 86 | -def planning_symmetric_workspace_nbytes(E: int, NvS: int, R: int) -> int: | 88 | +def planning_symmetric_workspace_nbytes( |
| 89 | + E: int, NvS: int, R: int, *, server_dedup: bool = False, | ||
| 90 | +) -> int: | ||
| 87 | """Bytes of Planning's per-rank symmetric communication workspace. | 91 | """Bytes of Planning's per-rank symmetric communication workspace. |
| 88 | 92 | ||
| 89 | The regions hold local TPE, source-side duplicate payload metadata and the | 93 | The regions hold local TPE, source-side duplicate payload metadata and the |
| @@ -101,7 +105,31 @@ def planning_symmetric_workspace_nbytes(E: int, NvS: int, R: int) -> int: | |||
| 101 | dup_payload_done_off = dup_rank_counts_off + 2 * R * align_elems | 105 | dup_payload_done_off = dup_rank_counts_off + 2 * R * align_elems |
| 102 | dup_groups_off = dup_payload_done_off + align_up(R) | 106 | dup_groups_off = dup_payload_done_off + align_up(R) |
| 103 | dup_loffs_off = dup_groups_off + align_up(NvS * 3) | 107 | dup_loffs_off = dup_groups_off + align_up(NvS * 3) |
| 104 | - return (dup_loffs_off + align_up(NvS)) * 4 | 108 | + dup_capacity = RANKS_PER_SERVER * NvS if server_dedup else NvS |
| 109 | + required_ints = dup_loffs_off + align_up(dup_capacity) | ||
| 110 | + assert required_ints <= 2**31 - 1, "planning symmetric workspace exceeds int32 device offsets" | ||
| 111 | + return required_ints * 4 | ||
| 112 | + | ||
| 113 | + | ||
| 114 | +# Weight aggregation gives each source an exclusive inbox and each worker AIV an exclusive local staging. | ||
| 115 | +WEIGHT_AGG_REGION_BYTES = 256 * 1024 | ||
| 116 | +WEIGHT_AGG_STAGING_AIVS = 16 | ||
| 117 | +WEIGHT_AGG_STAGING_BYTES = 256 * 1024 | ||
| 118 | +WEIGHT_AGG_DEBUG_BYTES = 1024 | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def weight_agg_capacity_entries() -> int: | ||
| 122 | + # Keep in sync with the kernel region header, segment header, and per-record byte size. | ||
| 123 | + return (WEIGHT_AGG_REGION_BYTES - 64) // 8 | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def dispatch_sync_buffer_nbytes(R: int, *, server_dedup: bool = False) -> int: | ||
| 127 | + # Region order matches the address computation in the Dispatch UDMA kernel. | ||
| 128 | + token_control = R * 16 * 6 * 512 + 16 * 4 * 512 | ||
| 129 | + if not server_dedup: | ||
| 130 | + return token_control | ||
| 131 | + return (token_control + R * WEIGHT_AGG_REGION_BYTES | ||
| 132 | + + WEIGHT_AGG_STAGING_AIVS * WEIGHT_AGG_STAGING_BYTES + WEIGHT_AGG_DEBUG_BYTES) | ||
| 105 | 133 | ||
| 106 | 134 | ||
| 107 | def compute_shmem_mem_size( | 135 | def compute_shmem_mem_size( |
| @@ -25,6 +25,7 @@ from ._common import ( | |||
| 25 | BARRIER_SLOTS, | 25 | BARRIER_SLOTS, |
| 26 | OP_WS_BYTES_DEFAULT, | 26 | OP_WS_BYTES_DEFAULT, |
| 27 | cross_rank_barrier, | 27 | cross_rank_barrier, |
| 28 | + dispatch_sync_buffer_nbytes, | ||
| 28 | record_streams, | 29 | record_streams, |
| 29 | ) | 30 | ) |
| 30 | from .buffer_c import ( | 31 | from .buffer_c import ( |
| @@ -35,7 +36,7 @@ from .buffer_c import ( | |||
| 35 | create_vmm_physical, | 36 | create_vmm_physical, |
| 36 | map_to_sym_ptr, | 37 | map_to_sym_ptr, |
| 37 | ) | 38 | ) |
| 38 | -from .planning import MoonEPCommPlan, allocate_planning_outputs | 39 | +from .planning import RANKS_PER_SERVER, MoonEPCommPlan, allocate_planning_outputs |
| 39 | from .ops import ( | 40 | from .ops import ( |
| 40 | CombineOp, | 41 | CombineOp, |
| 41 | DispatchOp, | 42 | DispatchOp, |
| @@ -44,7 +45,8 @@ from .ops import ( | |||
| 44 | PrefetchOp, | 45 | PrefetchOp, |
| 45 | ) | 46 | ) |
| 46 | from .launchers import planning_workspace_sizes | 47 | from .launchers import planning_workspace_sizes |
| 47 | -from .shmem_runtime import ShmemRuntime | 48 | +from .combine import combine_put_workspace_bytes |
| 49 | +from .shmem_runtime import ShmemRuntime, publish_dedup_env | ||
| 48 | from .buffer_bindings import ( | 50 | from .buffer_bindings import ( |
| 49 | CommBuffers, ExpertPointerBinding, comm_context, overlaps, symmetric_source, | 51 | CommBuffers, ExpertPointerBinding, comm_context, overlaps, symmetric_source, |
| 50 | tensor_signature, validate_unchanged, | 52 | tensor_signature, validate_unchanged, |
| @@ -53,6 +55,8 @@ from .buffer_bindings import ( | |||
| 53 | logger = logging.getLogger(__name__) | 55 | logger = logging.getLogger(__name__) |
| 54 | 56 | ||
| 55 | _COMBINE_SYNC_BYTES_PER_RANK = 16 * 2 * 512 | 57 | _COMBINE_SYNC_BYTES_PER_RANK = 16 * 2 * 512 |
| 58 | +_SERVER_COMBINE_SYNC_BYTES_PER_RANK = 16 * 6 * 512 | ||
| 59 | +_SERVER_COMBINE_LOCAL_SYNC_BYTES = 16 * 4 * 512 | ||
| 56 | 60 | ||
| 57 | def _is_ascend950(device: int, props) -> bool: | 61 | def _is_ascend950(device: int, props) -> bool: |
| 58 | names = [os.environ.get("SOC_VERSION", ""), os.environ.get("ASCEND_SOC_VERSION", ""), | 62 | names = [os.environ.get("SOC_VERSION", ""), os.environ.get("ASCEND_SOC_VERSION", ""), |
| @@ -102,10 +106,59 @@ def _op_ws_bytes_from_env(default: int = OP_WS_BYTES_DEFAULT) -> int: | |||
| 102 | return int(raw) | 106 | return int(raw) |
| 103 | 107 | ||
| 104 | 108 | ||
| 109 | +def _validate_dedup_config( | ||
| 110 | + dedup_mode: str, | ||
| 111 | + ranks_per_server: int, | ||
| 112 | + R: int, | ||
| 113 | + udma_supported: bool, | ||
| 114 | +) -> None: | ||
| 115 | + """Validate the Buffer-level dedup domain. | ||
| 116 | + | ||
| 117 | + The dedup domain is fixed once, at Buffer construction. Rank-level dedup is | ||
| 118 | + the default and reproduces the local code path; server-level dedup groups | ||
| 119 | + ``ranks_per_server`` consecutive ranks (8, the compiled kernel ABI) into one | ||
| 120 | + board. Per-op UDMA requirements are intentionally *not* checked here: a | ||
| 121 | + server plan can be used by Combine-only workloads (``use_udma=False`` with | ||
| 122 | + ``combine_use_udma=True``), and dispatch/combine validate their own engine | ||
| 123 | + at the call site. | ||
| 124 | + """ | ||
| 125 | + if dedup_mode not in ("rank", "server"): | ||
| 126 | + raise ValueError( | ||
| 127 | + f"dedup_mode must be 'rank' or 'server', got {dedup_mode!r}") | ||
| 128 | + if isinstance(ranks_per_server, bool) or not isinstance(ranks_per_server, int): | ||
| 129 | + raise TypeError( | ||
| 130 | + "ranks_per_server must be an int, got " | ||
| 131 | + f"{type(ranks_per_server).__name__}") | ||
| 132 | + if ranks_per_server <= 0: | ||
| 133 | + raise ValueError( | ||
| 134 | + f"ranks_per_server must be positive, got {ranks_per_server}") | ||
| 135 | + if dedup_mode != "server": | ||
| 136 | + return | ||
| 137 | + if ranks_per_server != RANKS_PER_SERVER: | ||
| 138 | + raise NotImplementedError( | ||
| 139 | + "server dedup kernels are compiled for " | ||
| 140 | + f"{RANKS_PER_SERVER} ranks/server; got ranks_per_server=" | ||
| 141 | + f"{ranks_per_server}. Changing this requires the kernel ABI to " | ||
| 142 | + "carry the server size (tiling), which is out of scope here.") | ||
| 143 | + if R <= 0 or R % ranks_per_server != 0: | ||
| 144 | + raise ValueError( | ||
| 145 | + f"server dedup requires num_ep_ranks divisible by " | ||
| 146 | + f"{ranks_per_server}, got {R}") | ||
| 147 | + if not udma_supported: | ||
| 148 | + raise RuntimeError( | ||
| 149 | + "server dedup requires the UDMA (Ascend 950) backend; this device " | ||
| 150 | + "does not support it") | ||
| 151 | + | ||
| 152 | + | ||
| 105 | def _validate_plan_layout(ctx: dict, plan: MoonEPCommPlan) -> None: | 153 | def _validate_plan_layout(ctx: dict, plan: MoonEPCommPlan) -> None: |
| 106 | - """Require a saved plan to match the Buffer's fixed token layout.""" | 154 | + """Require a saved plan to match the Buffer's layout and dedup domain.""" |
| 107 | if not isinstance(plan, MoonEPCommPlan): | 155 | if not isinstance(plan, MoonEPCommPlan): |
| 108 | raise TypeError("expected a MoonEPCommPlan") | 156 | raise TypeError("expected a MoonEPCommPlan") |
| 157 | + dedup_mode = ctx.get('dedup_mode', 'rank') | ||
| 158 | + if plan.dedup_mode != dedup_mode: | ||
| 159 | + raise ValueError( | ||
| 160 | + f"plan uses {plan.dedup_mode} dedup, but this Buffer was " | ||
| 161 | + f"constructed with dedup_mode={dedup_mode!r}") | ||
| 109 | identity = (plan.N, plan.R, plan.E, plan.B, plan.NvS, plan.K) | 162 | identity = (plan.N, plan.R, plan.E, plan.B, plan.NvS, plan.K) |
| 110 | expected = tuple(int(ctx[name]) for name in ('N', 'R', 'E', 'B', 'NvS', 'K')) | 163 | expected = tuple(int(ctx[name]) for name in ('N', 'R', 'E', 'B', 'NvS', 'K')) |
| 111 | if tuple(int(value) for value in identity) != expected: | 164 | if tuple(int(value) for value in identity) != expected: |
| @@ -179,6 +232,8 @@ def _create_context( | |||
| 179 | rank: int | None = None, | 232 | rank: int | None = None, |
| 180 | use_udma: bool = True, | 233 | use_udma: bool = True, |
| 181 | udma_flags: dict | None = None, | 234 | udma_flags: dict | None = None, |
| 235 | + dedup_mode: str = "rank", | ||
| 236 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 182 | ) -> dict: | 237 | ) -> dict: |
| 183 | """Pre-allocate all shmem symmetric chunks and local temp buffers. | 238 | """Pre-allocate all shmem symmetric chunks and local temp buffers. |
| 184 | 239 | ||
| @@ -213,6 +268,16 @@ def _create_context( | |||
| 213 | max_sms = getattr(props, "multi_processor_count", 32) | 268 | max_sms = getattr(props, "multi_processor_count", 32) |
| 214 | num_sms_dedup = _num_sms_dedup_from_env(max_sms) | 269 | num_sms_dedup = _num_sms_dedup_from_env(max_sms) |
| 215 | udma_supported = _is_ascend950(device, props) | 270 | udma_supported = _is_ascend950(device, props) |
| 271 | + _validate_dedup_config(dedup_mode, ranks_per_server, R, udma_supported) | ||
| 272 | + server_dedup = dedup_mode == "server" | ||
| 273 | + | ||
| 274 | + ctx_udma_flags = {'planning': False, 'dispatch': True, 'combine': True, | ||
| 275 | + 'prefetch': True, 'grad_reduce': True} | ||
| 276 | + requested_udma = {name: bool(use_udma) for name in ctx_udma_flags} | ||
| 277 | + if udma_flags: | ||
| 278 | + requested_udma.update({name: bool(value) for name, value in udma_flags.items()}) | ||
| 279 | + effective_udma = {name: bool(udma_supported and ctx_udma_flags[name] and requested_udma[name]) | ||
| 280 | + for name in ctx_udma_flags} | ||
| 216 | 281 | ||
| 217 | epn = E // R | 282 | epn = E // R |
| 218 | assert E % R == 0, f"E ({E}) must be divisible by R ({R})" | 283 | assert E % R == 0, f"E ({E}) must be divisible by R ({R})" |
| @@ -236,7 +301,7 @@ def _create_context( | |||
| 236 | f"S={S}, K={K}, S*K={N}, int32_max={int32_max}" | 301 | f"S={S}, K={K}, S*K={N}, int32_max={int32_max}" |
| 237 | ) | 302 | ) |
| 238 | planning_local_elems, planning_symmetric_bytes = planning_workspace_sizes( | 303 | planning_local_elems, planning_symmetric_bytes = planning_workspace_sizes( |
| 239 | - S, K, E, NvS, R, num_sms | 304 | + S, K, E, NvS, R, num_sms, server_dedup=server_dedup |
| 240 | ) | 305 | ) |
| 241 | # ================================================================ | 306 | # ================================================================ |
| 242 | # Allocate communication chunks as CANN VMM physical chunks (collective). | 307 | # Allocate communication chunks as CANN VMM physical chunks (collective). |
| @@ -261,17 +326,25 @@ def _create_context( | |||
| 261 | # Combine owns a separate grant/done cacheline pool. Keeping this distinct | 326 | # Combine owns a separate grant/done cacheline pool. Keeping this distinct |
| 262 | # from dispatch prevents the two protocols from sharing flag generations or | 327 | # from dispatch prevents the two protocols from sharing flag generations or |
| 263 | # becoming coupled through their unrelated layouts. | 328 | # becoming coupled through their unrelated layouts. |
| 264 | - combine_sync_buffer, _, _ = create_vmm_physical( | 329 | + combine_sync_bytes = R * _COMBINE_SYNC_BYTES_PER_RANK |
| 265 | - [R * _COMBINE_SYNC_BYTES_PER_RANK], torch.uint8, device) | 330 | + if server_dedup: |
| 331 | + combine_sync_bytes = R * _SERVER_COMBINE_SYNC_BYTES_PER_RANK + _SERVER_COMBINE_LOCAL_SYNC_BYTES | ||
| 332 | + combine_sync_buffer, _, _ = create_vmm_physical([combine_sync_bytes], torch.uint8, device) | ||
| 266 | combine_sync_buffer.zero_() | 333 | combine_sync_buffer.zero_() |
| 267 | vmm_chunks['combine_sync_buffer'] = combine_sync_buffer._vmm_allocation | 334 | vmm_chunks['combine_sync_buffer'] = combine_sync_buffer._vmm_allocation |
| 268 | 335 | ||
| 269 | # Dispatch sync_buffer: Token control region followed by the four-round | 336 | # Dispatch sync_buffer: Token control region followed by the four-round |
| 270 | # local sync region for the 16 Token AIVs. | 337 | # local sync region for the 16 Token AIVs. |
| 271 | dispatch_sync_buffer, _, _ = create_vmm_physical( | 338 | dispatch_sync_buffer, _, _ = create_vmm_physical( |
| 272 | - [R * 16 * 6 * 512 + 16 * 4 * 512], torch.uint8, device) | 339 | + [dispatch_sync_buffer_nbytes(R, server_dedup=server_dedup)], torch.uint8, device) |
| 273 | dispatch_sync_buffer.zero_() | 340 | dispatch_sync_buffer.zero_() |
| 274 | vmm_chunks['dispatch_sync_buffer'] = dispatch_sync_buffer._vmm_allocation | 341 | vmm_chunks['dispatch_sync_buffer'] = dispatch_sync_buffer._vmm_allocation |
| 342 | + if server_dedup and effective_udma['combine']: | ||
| 343 | + combine_workspace, _, _ = create_vmm_physical( | ||
| 344 | + [combine_put_workspace_bytes(NvS, H, R, K)], torch.uint8, device) | ||
| 345 | + vmm_chunks['combine_workspace'] = combine_workspace._vmm_allocation | ||
| 346 | + else: | ||
| 347 | + combine_workspace = None | ||
| 275 | # Zero this rank's barrier words (writes through to the VMM source VA). | 348 | # Zero this rank's barrier words (writes through to the VMM source VA). |
| 276 | barrier_buf.zero_() | 349 | barrier_buf.zero_() |
| 277 | 350 | ||
| @@ -290,13 +363,6 @@ def _create_context( | |||
| 290 | 'prefetch': PrefetchOp(ws_bytes=0, num_sms=num_sms), | 363 | 'prefetch': PrefetchOp(ws_bytes=0, num_sms=num_sms), |
| 291 | 'grad_reduce': GradReduceOp(ws_bytes=0, num_sms=num_sms), | 364 | 'grad_reduce': GradReduceOp(ws_bytes=0, num_sms=num_sms), |
| 292 | } | 365 | } |
| 293 | - ctx_udma_flags = {'planning': False, 'dispatch': True, 'combine': True, | ||
| 294 | - 'prefetch': True, 'grad_reduce': True} | ||
| 295 | - requested_udma = {name: bool(use_udma) for name in ctx_udma_flags} | ||
| 296 | - if udma_flags: | ||
| 297 | - requested_udma.update({name: bool(value) for name, value in udma_flags.items()}) | ||
| 298 | - effective_udma = {name: bool(udma_supported and ctx_udma_flags[name] and requested_udma[name]) | ||
| 299 | - for name in ctx_udma_flags} | ||
| 300 | os.environ['ASCEND_MOONEP_USE_UDMA'] = '1' if any(effective_udma.values()) else '0' | 366 | os.environ['ASCEND_MOONEP_USE_UDMA'] = '1' if any(effective_udma.values()) else '0' |
| 301 | for name, enabled in effective_udma.items(): | 367 | for name, enabled in effective_udma.items(): |
| 302 | os.environ[f'ASCEND_MOONEP_{name.upper()}_USE_UDMA'] = '1' if enabled else '0' | 368 | os.environ[f'ASCEND_MOONEP_{name.upper()}_USE_UDMA'] = '1' if enabled else '0' |
| @@ -310,6 +376,8 @@ def _create_context( | |||
| 310 | 'N': N, 'NvS': NvS, | 376 | 'N': N, 'NvS': NvS, |
| 311 | 'num_sms': num_sms, | 377 | 'num_sms': num_sms, |
| 312 | 'num_sms_dedup': num_sms_dedup, | 378 | 'num_sms_dedup': num_sms_dedup, |
| 379 | + 'dedup_mode': dedup_mode, | ||
| 380 | + 'ranks_per_server': ranks_per_server, | ||
| 313 | 'device': device, | 381 | 'device': device, |
| 314 | '_udma_supported': udma_supported, | 382 | '_udma_supported': udma_supported, |
| 315 | '_udma_ctx_flags': ctx_udma_flags, | 383 | '_udma_ctx_flags': ctx_udma_flags, |
| @@ -325,6 +393,7 @@ def _create_context( | |||
| 325 | 'weights_buf': weights_buf, | 393 | 'weights_buf': weights_buf, |
| 326 | 'barrier_buf': barrier_buf, | 394 | 'barrier_buf': barrier_buf, |
| 327 | 'combine_sync_buffer': combine_sync_buffer, | 395 | 'combine_sync_buffer': combine_sync_buffer, |
| 396 | + 'combine_workspace': combine_workspace, | ||
| 328 | 'dispatch_sync_buffer': dispatch_sync_buffer, | 397 | 'dispatch_sync_buffer': dispatch_sync_buffer, |
| 329 | 'shmem_chunks': [ | 398 | 'shmem_chunks': [ |
| 330 | hidden_buf, | 399 | hidden_buf, |
| @@ -332,7 +401,7 @@ def _create_context( | |||
| 332 | barrier_buf, | 401 | barrier_buf, |
| 333 | combine_sync_buffer, | 402 | combine_sync_buffer, |
| 334 | dispatch_sync_buffer, | 403 | dispatch_sync_buffer, |
| 335 | - ], | 404 | + ] + ([combine_workspace] if combine_workspace is not None else []), |
| 336 | # CANN VMM allocations (source_va + mem_handle + shareable_va): | 405 | # CANN VMM allocations (source_va + mem_handle + shareable_va): |
| 337 | # collected by the framework for buffer-backed shmem init | 406 | # collected by the framework for buffer-backed shmem init |
| 338 | # (ShmemRuntime.init_with_buffer); Buffer.destroy reverses the VMM ops. | 407 | # (ShmemRuntime.init_with_buffer); Buffer.destroy reverses the VMM ops. |
| @@ -364,6 +433,7 @@ def _create_context( | |||
| 364 | ), | 433 | ), |
| 365 | } | 434 | } |
| 366 | _log_context_buffer_size(ctx) | 435 | _log_context_buffer_size(ctx) |
| 436 | + publish_dedup_env(dedup_mode) | ||
| 367 | return ctx | 437 | return ctx |
| 368 | 438 | ||
| 369 | 439 | ||
| @@ -425,6 +495,9 @@ class Buffer: | |||
| 425 | enable_pdl: bool = True, | 495 | enable_pdl: bool = True, |
| 426 | explicitly_destroy: bool = False, | 496 | explicitly_destroy: bool = False, |
| 427 | rank: int | None = None, | 497 | rank: int | None = None, |
| 498 | + *, | ||
| 499 | + dedup_mode: str = "rank", | ||
| 500 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 428 | **kwargs, | 501 | **kwargs, |
| 429 | ): | 502 | ): |
| 430 | """Allocate and hold all communication buffers. | 503 | """Allocate and hold all communication buffers. |
| @@ -481,6 +554,8 @@ class Buffer: | |||
| 481 | rank=rank, | 554 | rank=rank, |
| 482 | use_udma=use_udma, | 555 | use_udma=use_udma, |
| 483 | udma_flags=udma_flags, | 556 | udma_flags=udma_flags, |
| 557 | + dedup_mode=dedup_mode, | ||
| 558 | + ranks_per_server=ranks_per_server, | ||
| 484 | ) | 559 | ) |
| 485 | # Buffer-backed: set True by _ensure_shmem_views after init_with_buffer. | 560 | # Buffer-backed: set True by _ensure_shmem_views after init_with_buffer. |
| 486 | self._shmem_ready = False | 561 | self._shmem_ready = False |
| @@ -493,6 +568,19 @@ class Buffer: | |||
| 493 | priority=self.comm_stream_priority, | 568 | priority=self.comm_stream_priority, |
| 494 | ) | 569 | ) |
| 495 | 570 | ||
| 571 | + @property | ||
| 572 | + def dedup_mode(self) -> str: | ||
| 573 | + """Dedup domain of this Buffer (``"rank"`` or ``"server"``). | ||
| 574 | + | ||
| 575 | + Fixed at construction; no Buffer method takes a dedup argument. | ||
| 576 | + """ | ||
| 577 | + return self._require_ctx()['dedup_mode'] | ||
| 578 | + | ||
| 579 | + @property | ||
| 580 | + def ranks_per_server(self) -> int: | ||
| 581 | + """Number of cards in one server for server-level dedup (8).""" | ||
| 582 | + return int(self._require_ctx()['ranks_per_server']) | ||
| 583 | + | ||
| 496 | @property | 584 | @property |
| 497 | def destroyed(self) -> bool: | 585 | def destroyed(self) -> bool: |
| 498 | return self._destroyed | 586 | return self._destroyed |
| @@ -540,8 +628,11 @@ class Buffer: | |||
| 540 | 'barrier_buf', | 628 | 'barrier_buf', |
| 541 | 'combine_sync_buffer', | 629 | 'combine_sync_buffer', |
| 542 | 'dispatch_sync_buffer', | 630 | 'dispatch_sync_buffer', |
| 631 | + 'combine_workspace', | ||
| 543 | ): | 632 | ): |
| 544 | - allocation = ctx['vmm_chunks'][name] | 633 | + allocation = ctx['vmm_chunks'].get(name) |
| 634 | + if allocation is None: | ||
| 635 | + continue | ||
| 545 | sym = map_to_sym_ptr(allocation.source_va, name) | 636 | sym = map_to_sym_ptr(allocation.source_va, name) |
| 546 | src = ctx[name] | 637 | src = ctx[name] |
| 547 | ctx[name] = create_sym_tensor_from_ptr( | 638 | ctx[name] = create_sym_tensor_from_ptr( |
| @@ -600,6 +691,7 @@ class Buffer: | |||
| 600 | 'barrier_buf', | 691 | 'barrier_buf', |
| 601 | 'combine_sync_buffer', | 692 | 'combine_sync_buffer', |
| 602 | 'dispatch_sync_buffer', | 693 | 'dispatch_sync_buffer', |
| 694 | + 'combine_workspace', | ||
| 603 | ): | 695 | ): |
| 604 | allocation = ctx['vmm_chunks'].get(name) | 696 | allocation = ctx['vmm_chunks'].get(name) |
| 605 | if allocation is not None: | 697 | if allocation is not None: |
| @@ -618,6 +710,7 @@ class Buffer: | |||
| 618 | 'combine_sync_buffer', | 710 | 'combine_sync_buffer', |
| 619 | 'planning_workspace', | 711 | 'planning_workspace', |
| 620 | 'dispatch_sync_buffer', | 712 | 'dispatch_sync_buffer', |
| 713 | + 'combine_workspace', | ||
| 621 | ): | 714 | ): |
| 622 | ctx.pop(key, None) | 715 | ctx.pop(key, None) |
| 623 | ctx.clear() | 716 | ctx.clear() |
| @@ -831,7 +924,7 @@ class Buffer: | |||
| 831 | if planning_args is not None: | 924 | if planning_args is not None: |
| 832 | topk_flat, tokens_per_expert, cu_seqlens = planning_args | 925 | topk_flat, tokens_per_expert, cu_seqlens = planning_args |
| 833 | ctx['kernels']['planning'].compute( | 926 | ctx['kernels']['planning'].compute( |
| 834 | - ctx, topk_flat, tokens_per_expert, cu_seqlens, plan, | 927 | + ctx.get('_comm_owner_ctx', ctx), topk_flat, tokens_per_expert, cu_seqlens, plan, |
| 835 | shmem_instance_id=0) | 928 | shmem_instance_id=0) |
| 836 | 929 | ||
| 837 | ctx['kernels']['dispatch'].compute( | 930 | ctx['kernels']['dispatch'].compute( |
| @@ -960,6 +1053,9 @@ class Buffer: | |||
| 960 | ``source = (expert%epn)*H*Hp`` (analysis §4.2). | 1053 | ``source = (expert%epn)*H*Hp`` (analysis §4.2). |
| 961 | """ | 1054 | """ |
| 962 | self._ensure_shmem_views() | 1055 | self._ensure_shmem_views() |
| 1056 | + server_dedup = ctx['dedup_mode'] == 'server' | ||
| 1057 | + if server_dedup: | ||
| 1058 | + cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream) | ||
| 963 | E = int(ctx['E']) | 1059 | E = int(ctx['E']) |
| 964 | local_experts = experts_to_copy[int(ctx['rank'])] # this rank's [B] row | 1060 | local_experts = experts_to_copy[int(ctx['rank'])] # this rank's [B] row |
| 965 | # The op layer requires shmem tensors pointing at the "local part of | 1061 | # The op layer requires shmem tensors pointing at the "local part of |
| @@ -1003,6 +1099,8 @@ class Buffer: | |||
| 1003 | local_experts, | 1099 | local_experts, |
| 1004 | shmem_instance_id=0, | 1100 | shmem_instance_id=0, |
| 1005 | ) | 1101 | ) |
| 1102 | + if server_dedup: | ||
| 1103 | + cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream) | ||
| 1006 | 1104 | ||
| 1007 | def _run_reduce_grad_on_current_stream( | 1105 | def _run_reduce_grad_on_current_stream( |
| 1008 | self, | 1106 | self, |
| @@ -1025,6 +1123,8 @@ class Buffer: | |||
| 1025 | ``experts_to_copy`` still carries the full ``[R, B]`` plan. | 1123 | ``experts_to_copy`` still carries the full ``[R, B]`` plan. |
| 1026 | """ | 1124 | """ |
| 1027 | self._ensure_shmem_views() | 1125 | self._ensure_shmem_views() |
| 1126 | + if ctx['dedup_mode'] == 'server': | ||
| 1127 | + cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream) | ||
| 1028 | rank = int(ctx['rank']) | 1128 | rank = int(ctx['rank']) |
| 1029 | E = int(ctx['E']) | 1129 | E = int(ctx['E']) |
| 1030 | R = int(ctx['R']) | 1130 | R = int(ctx['R']) |
| @@ -1109,6 +1209,9 @@ class Buffer: | |||
| 1109 | comm_buffers = getattr(self, '_comm_buffers', None) | 1209 | comm_buffers = getattr(self, '_comm_buffers', None) |
| 1110 | self._ensure_shmem_views() | 1210 | self._ensure_shmem_views() |
| 1111 | 1211 | ||
| 1212 | + if ctx['dedup_mode'] == 'server' and not ctx['_dispatch_use_udma']: | ||
| 1213 | + raise ValueError('server dedup requires UDMA dispatch') | ||
| 1214 | + | ||
| 1112 | if plan is None: | 1215 | if plan is None: |
| 1113 | assert topk_experts_sk is not None and tokens_per_expert is not None | 1216 | assert topk_experts_sk is not None and tokens_per_expert is not None |
| 1114 | topk_flat = topk_experts_sk.reshape(-1) | 1217 | topk_flat = topk_experts_sk.reshape(-1) |
| @@ -1263,6 +1366,21 @@ class Buffer: | |||
| 1263 | 1366 | ||
| 1264 | return done | 1367 | return done |
| 1265 | 1368 | ||
| 1369 | + def prepare_combine_plan(self, plan: MoonEPCommPlan): | ||
| 1370 | + """Collectively prepare manually built routes before UDMA combine. | ||
| 1371 | + | ||
| 1372 | + All ranks call after dst is ready. Ordinary dispatch planning does this | ||
| 1373 | + automatically, and plan.clone() preserves those prepared tables locally. | ||
| 1374 | + No preparation is hidden inside the combine timed loop. | ||
| 1375 | + """ | ||
| 1376 | + ctx = self._require_ctx() | ||
| 1377 | + self._ensure_shmem_views() | ||
| 1378 | + if not ctx['_combine_use_udma']: | ||
| 1379 | + raise RuntimeError('prepare_combine_plan requires UDMA combine') | ||
| 1380 | + _validate_plan_layout(ctx, plan) | ||
| 1381 | + from .planning import prepare_combine_plan | ||
| 1382 | + return prepare_combine_plan(ctx, plan) | ||
| 1383 | + | ||
| 1266 | def combine( | 1384 | def combine( |
| 1267 | self, | 1385 | self, |
| 1268 | plan: MoonEPCommPlan | None = None, | 1386 | plan: MoonEPCommPlan | None = None, |
| @@ -247,6 +247,23 @@ def apply_engine(engine: str) -> bool: | |||
| 247 | return want | 247 | return want |
| 248 | 248 | ||
| 249 | 249 | ||
| 250 | +def add_dedup_mode_arg(parser: argparse.ArgumentParser) -> None: | ||
| 251 | + parser.add_argument( | ||
| 252 | + "--dedup-mode", choices=("rank", "server"), default="rank", | ||
| 253 | + help="Deduplicate by rank or by a group of eight ranks (requires URMA).", | ||
| 254 | + ) | ||
| 255 | + | ||
| 256 | + | ||
| 257 | +def validate_dedup_mode(dedup_mode: str, use_udma: bool, ranks: int) -> None: | ||
| 258 | + if dedup_mode != "server": | ||
| 259 | + return | ||
| 260 | + from npu_patch.planning import RANKS_PER_SERVER | ||
| 261 | + | ||
| 262 | + local_ranks = min(ranks, int(os.environ.get("LOCAL_WORLD_SIZE", ranks))) | ||
| 263 | + if not use_udma or ranks % RANKS_PER_SERVER or local_ranks % RANKS_PER_SERVER: | ||
| 264 | + raise SystemExit("--dedup-mode server requires URMA and complete eight-rank servers") | ||
| 265 | + | ||
| 266 | + | ||
| 250 | def add_common_args(parser: argparse.ArgumentParser) -> None: | 267 | def add_common_args(parser: argparse.ArgumentParser) -> None: |
| 251 | """Arguments shared by all benchmarks.""" | 268 | """Arguments shared by all benchmarks.""" |
| 252 | add_engine_args(parser) | 269 | add_engine_args(parser) |
| @@ -7,6 +7,11 @@ per-route ``dst`` -> duplicate encoding), but is vectorized: the Python-loop | |||
| 7 | reference needs ~1 minute per MaxVio point at benchmark scale | 7 | reference needs ~1 minute per MaxVio point at benchmark scale |
| 8 | (R=8, S=8192, K=16, E=1024), while these models run in ~1 s. | 8 | (R=8, S=8192, K=16, E=1024), while these models run in ~1 s. |
| 9 | 9 | ||
| 10 | +The dedup domain is a parameter (``dedup_mode``): ``rank`` dedups per | ||
| 11 | +destination rank (the Buffer default) and ``server`` dedups per 8-rank server, | ||
| 12 | +where groups are owned by the primary's rank and the duplicate table stores | ||
| 13 | +full ``dest * NvS + loff`` addresses so members may live on sibling ranks. | ||
| 14 | + | ||
| 10 | ``plan_expectation`` returns the full expected plan for every rank; | 15 | ``plan_expectation`` returns the full expected plan for every rank; |
| 11 | ``dispatch_expectation`` maps the gathered ``dst``/weights/hidden fingerprints | 16 | ``dispatch_expectation`` maps the gathered ``dst``/weights/hidden fingerprints |
| 12 | to the slot layout of one destination rank. | 17 | to the slot layout of one destination rank. |
| @@ -18,6 +23,9 @@ from dataclasses import dataclass | |||
| 18 | 23 | ||
| 19 | import torch | 24 | import torch |
| 20 | 25 | ||
| 26 | +# An Ascend server is 8 consecutive ranks; see npu_patch.planning.RANKS_PER_SERVER. | ||
| 27 | +RANKS_PER_SERVER = 8 | ||
| 28 | + | ||
| 21 | # Bound the [chunk, R] destination-search workspace of the route model: a | 29 | # Bound the [chunk, R] destination-search workspace of the route model: a |
| 22 | # 65536-route chunk is 4 MiB of int64 boundaries for R=8. | 30 | # 65536-route chunk is 4 MiB of int64 boundaries for R=8. |
| 23 | _ROUTE_CHUNK = 65536 | 31 | _ROUTE_CHUNK = 65536 |
| @@ -163,38 +171,75 @@ def plan_layout( | |||
| 163 | return cu, expert_off | 171 | return cu, expert_off |
| 164 | 172 | ||
| 165 | 173 | ||
| 166 | -def _first_route_per_destination(dest_sk: torch.Tensor) -> torch.Tensor: | 174 | +def _first_route_per_domain( |
| 167 | - """``[S, K]`` bool: first top-k route of each token to a destination rank. | 175 | + dest_sk: torch.Tensor, ranks_per_server: int = 1 |
| 176 | +) -> torch.Tensor: | ||
| 177 | + """``[S, K]`` bool: first top-k route of each token into a dedup domain. | ||
| 168 | 178 | ||
| 169 | - Stable: the first entry in top-k order is canonical; later routes to the | 179 | + Stable: the first entry in top-k order is canonical; later routes into the |
| 170 | - same destination rank are duplicates. | 180 | + same domain (one rank, or one 8-rank server) are duplicates. Matches the |
| 181 | + planning kernel's ``DedupRouteTileSimt`` (first positive route per token and | ||
| 182 | + domain wins, later ones are encoded as ``~raw``). | ||
| 171 | """ | 183 | """ |
| 172 | - order = torch.argsort(dest_sk, dim=1, stable=True) | 184 | + domain = dest_sk if ranks_per_server == 1 else dest_sk // ranks_per_server |
| 173 | - sorted_dest = dest_sk.gather(1, order) | 185 | + order = torch.argsort(domain, dim=1, stable=True) |
| 174 | - first_sorted = torch.ones_like(sorted_dest, dtype=torch.bool) | 186 | + sorted_domain = domain.gather(1, order) |
| 175 | - first_sorted[:, 1:] = sorted_dest[:, 1:] != sorted_dest[:, :-1] | 187 | + first_sorted = torch.ones_like(sorted_domain, dtype=torch.bool) |
| 188 | + first_sorted[:, 1:] = sorted_domain[:, 1:] != sorted_domain[:, :-1] | ||
| 176 | first = torch.empty_like(first_sorted) | 189 | first = torch.empty_like(first_sorted) |
| 177 | first.scatter_(1, order, first_sorted) | 190 | first.scatter_(1, order, first_sorted) |
| 178 | return first | 191 | return first |
| 179 | 192 | ||
| 180 | 193 | ||
| 194 | +def _first_route_per_destination(dest_sk: torch.Tensor) -> torch.Tensor: | ||
| 195 | + """Rank-level shorthand for :func:`_first_route_per_domain`.""" | ||
| 196 | + return _first_route_per_domain(dest_sk, 1) | ||
| 197 | + | ||
| 198 | + | ||
| 199 | +def stripe_rank_routes(boundaries, ordinals, dest, NvS, width=RANKS_PER_SERVER): | ||
| 200 | + """Permute hot expert ordinals and reselect their rank within the server.""" | ||
| 201 | + rows = torch.arange(dest.numel(), device=dest.device) | ||
| 202 | + first = (dest // width) * width | ||
| 203 | + begin = torch.where(first > 0, boundaries[rows, (first - 1).clamp_min(0)], 0) | ||
| 204 | + end = boundaries[rows, first + width - 1] | ||
| 205 | + prev = torch.where(dest > 0, boundaries[rows, (dest - 1).clamp_min(0)], 0) | ||
| 206 | + count = end - begin | ||
| 207 | + active = (count >= NvS // 4) & ((prev != begin) | (boundaries[rows, dest] != end)) | ||
| 208 | + relative = ordinals[active] - begin[active] | ||
| 209 | + count = count[active] | ||
| 210 | + lane = relative % 64 | ||
| 211 | + striped = begin[active] + lane * (count // 64) + torch.minimum(lane, count % 64) + relative // 64 | ||
| 212 | + ordinals = ordinals.clone() | ||
| 213 | + dest = dest.clone() | ||
| 214 | + ordinals[active] = striped | ||
| 215 | + dest[active] = (boundaries[active] <= striped[:, None]).sum(1) | ||
| 216 | + return ordinals, dest | ||
| 217 | + | ||
| 218 | + | ||
| 181 | def _route_destinations( | 219 | def _route_destinations( |
| 182 | topk_all: torch.Tensor, | 220 | topk_all: torch.Tensor, |
| 183 | tpe_all: torch.Tensor, | 221 | tpe_all: torch.Tensor, |
| 184 | alloc: torch.Tensor, | 222 | alloc: torch.Tensor, |
| 185 | expert_off: torch.Tensor, | 223 | expert_off: torch.Tensor, |
| 186 | NvS: int, | 224 | NvS: int, |
| 225 | + *, | ||
| 226 | + dedup_mode: str = "rank", | ||
| 227 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 228 | + stripe_rank_placement: bool = False, | ||
| 187 | ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: | 229 | ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: |
| 188 | """Expected per-route destination/loff/canonical flags for every rank. | 230 | """Expected per-route destination/loff/canonical flags for every rank. |
| 189 | 231 | ||
| 190 | Returns ``(dest, loff, canonical, raw)``, each ``[R, N]`` with | 232 | Returns ``(dest, loff, canonical, raw)``, each ``[R, N]`` with |
| 191 | ``N = S * K``: destination rank, offset inside the destination layout, | 233 | ``N = S * K``: destination rank, offset inside the destination layout, |
| 192 | - first-route-to-destination flag (canonical vs duplicate) and the | 234 | + first-route-to-dedup-domain flag (canonical vs duplicate) and the |
| 193 | un-encoded ``dest * NvS + loff``. | 235 | un-encoded ``dest * NvS + loff``. |
| 194 | """ | 236 | """ |
| 195 | R, S, K = topk_all.shape | 237 | R, S, K = topk_all.shape |
| 196 | N = S * K | 238 | N = S * K |
| 197 | E = alloc.shape[0] | 239 | E = alloc.shape[0] |
| 240 | + domain_width = ranks_per_server if dedup_mode == "server" else 1 | ||
| 241 | + stripe = (stripe_rank_placement and dedup_mode == "rank" and | ||
| 242 | + R > ranks_per_server and R % ranks_per_server == 0) | ||
| 198 | alloc_cumsum = alloc.cumsum(1) | 243 | alloc_cumsum = alloc.cumsum(1) |
| 199 | tpe_cumsum = tpe_all.to(torch.int64).cumsum(0) | 244 | tpe_cumsum = tpe_all.to(torch.int64).cumsum(0) |
| 200 | prev_count = torch.zeros(R, E, dtype=torch.int64) | 245 | prev_count = torch.zeros(R, E, dtype=torch.int64) |
| @@ -216,7 +261,12 @@ def _route_destinations( | |||
| 216 | for base in range(0, N, _ROUTE_CHUNK): | 261 | for base in range(0, N, _ROUTE_CHUNK): |
| 217 | end = min(base + _ROUTE_CHUNK, N) | 262 | end = min(base + _ROUTE_CHUNK, N) |
| 218 | boundaries = alloc_cumsum[experts[base:end]] | 263 | boundaries = alloc_cumsum[experts[base:end]] |
| 219 | - d[base:end] = (boundaries <= g[base:end, None]).sum(1) | 264 | + ranks = (boundaries <= g[base:end, None]).sum(1) |
| 265 | + if stripe: | ||
| 266 | + ordinals, ranks = stripe_rank_routes( | ||
| 267 | + boundaries, g[base:end], ranks, NvS, ranks_per_server) | ||
| 268 | + g[base:end] = ordinals | ||
| 269 | + d[base:end] = ranks | ||
| 220 | dest[r] = d | 270 | dest[r] = d |
| 221 | 271 | ||
| 222 | prev_alloc = torch.where( | 272 | prev_alloc = torch.where( |
| @@ -225,7 +275,9 @@ def _route_destinations( | |||
| 225 | torch.zeros_like(d), | 275 | torch.zeros_like(d), |
| 226 | ) | 276 | ) |
| 227 | loff[r] = expert_off[d, experts] + g - prev_alloc | 277 | loff[r] = expert_off[d, experts] + g - prev_alloc |
| 228 | - canonical[r] = _first_route_per_destination(d.view(S, K)).reshape(-1) | 278 | + canonical[r] = _first_route_per_domain( |
| 279 | + d.view(S, K), domain_width | ||
| 280 | + ).reshape(-1) | ||
| 229 | 281 | ||
| 230 | raw = dest * NvS + loff | 282 | raw = dest * NvS + loff |
| 231 | return dest, loff, canonical, raw | 283 | return dest, loff, canonical, raw |
| @@ -243,16 +295,34 @@ def dedup_pairs( | |||
| 243 | rank: int, | 295 | rank: int, |
| 244 | S: int, | 296 | S: int, |
| 245 | NvS: int, | 297 | NvS: int, |
| 246 | -) -> tuple[torch.Tensor, tuple[int, int]]: | 298 | + *, |
| 299 | + dedup_mode: str = "rank", | ||
| 300 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 301 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 247 | """Expected dedup table for one destination rank, as semantic pairs. | 302 | """Expected dedup table for one destination rank, as semantic pairs. |
| 248 | 303 | ||
| 249 | - Returns ``(pairs, (n_groups, n_dups))`` where ``pairs`` is a lexicographically | 304 | + Returns ``(pairs, counts)``. ``pairs`` is a ``[n_dups, 2]`` int64 tensor of |
| 250 | - sorted ``[n_dups, 2]`` int64 tensor of ``(primary_loff, duplicate_loff)``. | 305 | + ``(primary_loff, duplicate_address)`` sorted by ``(primary, address)``. |
| 251 | Group order is irrelevant (the kernel assigns it with atomics), so only the | 306 | Group order is irrelevant (the kernel assigns it with atomics), so only the |
| 252 | - ``primary -> {dups}`` mapping is compared. | 307 | + ``primary -> {dups}`` mapping is compared. ``counts`` is |
| 308 | + ``[n_groups, n_dups]`` for ``rank`` dedup and | ||
| 309 | + ``[n_groups, n_dups, P_0 .. P_{R-1}]`` for ``server`` dedup, where ``P_src`` | ||
| 310 | + counts this rank's groups whose token source is below ``src`` (the dispatch | ||
| 311 | + kernel waits on that prefix). | ||
| 312 | + | ||
| 313 | + ``duplicate_address`` is the in-rank loff for ``rank`` dedup and the full | ||
| 314 | + ``dest * NvS + loff`` address for ``server`` dedup, because a server group | ||
| 315 | + may own members on sibling ranks. | ||
| 253 | """ | 316 | """ |
| 254 | R, N = dest.shape | 317 | R, N = dest.shape |
| 255 | K = N // S | 318 | K = N // S |
| 319 | + if dedup_mode == "server": | ||
| 320 | + return _server_dedup_pairs( | ||
| 321 | + dest, loff, canonical, rank, S, NvS, ranks_per_server | ||
| 322 | + ) | ||
| 323 | + if dedup_mode != "rank": | ||
| 324 | + raise ValueError(f"unsupported dedup_mode: {dedup_mode!r}") | ||
| 325 | + | ||
| 256 | src = torch.arange(R, dtype=torch.int64).view(R, 1).expand(R, N) | 326 | src = torch.arange(R, dtype=torch.int64).view(R, 1).expand(R, N) |
| 257 | token = torch.arange(N, dtype=torch.int64).view(1, N) // K | 327 | token = torch.arange(N, dtype=torch.int64).view(1, N) // K |
| 258 | # Group id: (src rank, token, destination rank). | 328 | # Group id: (src rank, token, destination rank). |
| @@ -271,14 +341,79 @@ def dedup_pairs( | |||
| 271 | dup_loffs = loff[dup_mask] | 341 | dup_loffs = loff[dup_mask] |
| 272 | n_dups = int(dup_keys.numel()) | 342 | n_dups = int(dup_keys.numel()) |
| 273 | if n_dups == 0: | 343 | if n_dups == 0: |
| 274 | - empty = torch.zeros(0, 2, dtype=torch.int64) | 344 | + return (torch.zeros(0, 2, dtype=torch.int64), |
| 275 | - return empty, (0, 0) | 345 | + torch.tensor([0, 0], dtype=torch.int64)) |
| 276 | 346 | ||
| 277 | uniq, inverse = torch.unique(dup_keys, return_inverse=True) | 347 | uniq, inverse = torch.unique(dup_keys, return_inverse=True) |
| 278 | pair_primary = primary[uniq][inverse] | 348 | pair_primary = primary[uniq][inverse] |
| 279 | pairs = torch.stack((pair_primary, dup_loffs), dim=1) | 349 | pairs = torch.stack((pair_primary, dup_loffs), dim=1) |
| 280 | pairs = pairs[torch.argsort(pairs[:, 0] * NvS + pairs[:, 1])] | 350 | pairs = pairs[torch.argsort(pairs[:, 0] * NvS + pairs[:, 1])] |
| 281 | - return pairs, (int(uniq.numel()), n_dups) | 351 | + counts = torch.tensor([int(uniq.numel()), n_dups], dtype=torch.int64) |
| 352 | + return pairs, counts | ||
| 353 | + | ||
| 354 | + | ||
| 355 | +def _server_dedup_pairs( | ||
| 356 | + dest: torch.Tensor, | ||
| 357 | + loff: torch.Tensor, | ||
| 358 | + canonical: torch.Tensor, | ||
| 359 | + rank: int, | ||
| 360 | + S: int, | ||
| 361 | + NvS: int, | ||
| 362 | + ranks_per_server: int, | ||
| 363 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 364 | + """Server-dedup tables for one destination rank (see :func:`dedup_pairs`). | ||
| 365 | + | ||
| 366 | + Groups are keyed by ``(source rank, token, destination server)`` and owned | ||
| 367 | + by the group's primary destination rank; every non-primary member of an | ||
| 368 | + owned group appears in ``dup_loffs`` as a full address, including members | ||
| 369 | + that live on sibling ranks. | ||
| 370 | + """ | ||
| 371 | + R, N = dest.shape | ||
| 372 | + K = N // S | ||
| 373 | + num_domains = (R + ranks_per_server - 1) // ranks_per_server | ||
| 374 | + domain = dest // ranks_per_server | ||
| 375 | + token = torch.arange(N, dtype=torch.int64).view(1, N) // K | ||
| 376 | + full = (dest * NvS + loff).reshape(-1) | ||
| 377 | + | ||
| 378 | + per_source_groups = torch.zeros(R, dtype=torch.int64) | ||
| 379 | + pieces: list[torch.Tensor] = [] | ||
| 380 | + for source in range(R): | ||
| 381 | + canon = canonical[source].reshape(-1) | ||
| 382 | + # Group key inside one source: (local token, destination server). | ||
| 383 | + key = token[0] * num_domains + domain[source].reshape(-1) | ||
| 384 | + size = S * num_domains | ||
| 385 | + prim_loff = torch.zeros(size, dtype=torch.int64) | ||
| 386 | + prim_dest = torch.zeros(size, dtype=torch.int64) | ||
| 387 | + prim_seen = torch.zeros(size, dtype=torch.bool) | ||
| 388 | + prim_loff[key[canon]] = loff[source].reshape(-1)[canon] | ||
| 389 | + prim_dest[key[canon]] = dest[source].reshape(-1)[canon] | ||
| 390 | + prim_seen[key[canon]] = True | ||
| 391 | + | ||
| 392 | + dups = torch.nonzero(~canon, as_tuple=False).flatten() | ||
| 393 | + if dups.numel() == 0: | ||
| 394 | + continue | ||
| 395 | + dup_key = key[dups] | ||
| 396 | + owned = prim_seen[dup_key] & (prim_dest[dup_key] == rank) | ||
| 397 | + if not bool(owned.any()): | ||
| 398 | + continue | ||
| 399 | + dup_key = dup_key[owned] | ||
| 400 | + dup_index = source * N + dups[owned] | ||
| 401 | + pieces.append(torch.stack( | ||
| 402 | + (prim_loff[dup_key], full[dup_index]), dim=1)) | ||
| 403 | + per_source_groups[source] = int(torch.unique(dup_key).numel()) | ||
| 404 | + | ||
| 405 | + if pieces: | ||
| 406 | + pairs = torch.cat(pieces) | ||
| 407 | + pairs = pairs[torch.argsort(pairs[:, 0] * (NvS * R) + pairs[:, 1])] | ||
| 408 | + else: | ||
| 409 | + pairs = torch.zeros(0, 2, dtype=torch.int64) | ||
| 410 | + prefixes = per_source_groups.cumsum(0) - per_source_groups | ||
| 411 | + counts = torch.cat(( | ||
| 412 | + torch.tensor([int(per_source_groups.sum()), int(pairs.shape[0])], | ||
| 413 | + dtype=torch.int64), | ||
| 414 | + prefixes, | ||
| 415 | + )) | ||
| 416 | + return pairs, counts | ||
| 282 | 417 | ||
| 283 | 418 | ||
| 284 | def plan_dedup_pairs( | 419 | def plan_dedup_pairs( |
| @@ -286,21 +421,59 @@ def plan_dedup_pairs( | |||
| 286 | dup_loffs: torch.Tensor, | 421 | dup_loffs: torch.Tensor, |
| 287 | dup_counts: torch.Tensor, | 422 | dup_counts: torch.Tensor, |
| 288 | NvS: int, | 423 | NvS: int, |
| 289 | -) -> tuple[torch.Tensor, tuple[int, int], list[str]]: | 424 | + *, |
| 425 | + R: int | None = None, | ||
| 426 | + dedup_mode: str = "rank", | ||
| 427 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 428 | +) -> tuple[torch.Tensor, torch.Tensor, list[str]]: | ||
| 290 | """Normalize a kernel-plan dedup table to the same semantic pair form. | 429 | """Normalize a kernel-plan dedup table to the same semantic pair form. |
| 291 | 430 | ||
| 292 | Also validates the table's structure (compact prefixes, group ranges, | 431 | Also validates the table's structure (compact prefixes, group ranges, |
| 293 | - duplicate offsets in range), returning human-readable errors. | 432 | + duplicate addresses in range) and returns the full count row, so both |
| 433 | + dedup modes compare with the reference model: ``[G, D]`` for ``rank`` and | ||
| 434 | + ``[G, D, P_0 .. P_{R-1}]`` for ``server``. | ||
| 294 | """ | 435 | """ |
| 295 | errors: list[str] = [] | 436 | errors: list[str] = [] |
| 296 | - n_groups = int(dup_counts[0]) | 437 | + counts_all = dup_counts.to(torch.int64) |
| 297 | - n_dups = int(dup_counts[1]) | 438 | + empty = torch.zeros(0, 2, dtype=torch.int64) |
| 298 | - if not 0 <= n_groups <= NvS: | 439 | + if dedup_mode == "rank": |
| 299 | - errors.append(f"dup group count {n_groups} out of [0, {NvS}]") | 440 | + if counts_all.numel() != 2: |
| 300 | - if not 0 <= n_dups <= NvS: | 441 | + errors.append( |
| 301 | - errors.append(f"dup loff count {n_dups} out of [0, {NvS}]") | 442 | + f"rank dedup dup_counts must have 2 entries, got {counts_all.numel()}") |
| 443 | + return empty, counts_all, errors | ||
| 444 | + group_capacity = NvS | ||
| 445 | + dup_capacity = NvS | ||
| 446 | + address_limit = NvS | ||
| 447 | + elif dedup_mode == "server": | ||
| 448 | + if R is None: | ||
| 449 | + raise ValueError("server dedup table checks require R") | ||
| 450 | + if counts_all.numel() != R + 2: | ||
| 451 | + errors.append( | ||
| 452 | + f"server dedup dup_counts must have R+2={R + 2} entries, " | ||
| 453 | + f"got {counts_all.numel()}") | ||
| 454 | + return empty, counts_all, errors | ||
| 455 | + group_capacity = NvS | ||
| 456 | + dup_capacity = ranks_per_server * NvS | ||
| 457 | + address_limit = R * NvS | ||
| 458 | + else: | ||
| 459 | + raise ValueError(f"unsupported dedup_mode: {dedup_mode!r}") | ||
| 460 | + | ||
| 461 | + n_groups = int(counts_all[0]) | ||
| 462 | + n_dups = int(counts_all[1]) | ||
| 463 | + if not 0 <= n_groups <= group_capacity: | ||
| 464 | + errors.append(f"dup group count {n_groups} out of [0, {group_capacity}]") | ||
| 465 | + if not 0 <= n_dups <= dup_capacity: | ||
| 466 | + errors.append(f"dup loff count {n_dups} out of [0, {dup_capacity}]") | ||
| 467 | + if dedup_mode == "server": | ||
| 468 | + prefixes = counts_all[2:] | ||
| 469 | + if int(prefixes[0]) != 0: | ||
| 470 | + errors.append("server dup source prefixes must start at 0") | ||
| 471 | + if bool((prefixes[1:] < prefixes[:-1]).any()): | ||
| 472 | + errors.append("server dup source prefixes are not monotonic") | ||
| 473 | + if int(prefixes[-1]) > max(n_groups, 0): | ||
| 474 | + errors.append("server dup source prefix exceeds the group count") | ||
| 302 | if errors: | 475 | if errors: |
| 303 | - return torch.zeros(0, 2, dtype=torch.int64), (n_groups, n_dups), errors | 476 | + return empty, counts_all, errors |
| 304 | 477 | ||
| 305 | groups = dup_groups[:n_groups].to(torch.int64) | 478 | groups = dup_groups[:n_groups].to(torch.int64) |
| 306 | prim = groups[:, 0] | 479 | prim = groups[:, 0] |
| @@ -327,14 +500,17 @@ def plan_dedup_pairs( | |||
| 327 | errors.append("dup group references loffs outside the compact prefix") | 500 | errors.append("dup group references loffs outside the compact prefix") |
| 328 | dup_idx = dup_idx.clamp(0, max(n_dups - 1, 0)) | 501 | dup_idx = dup_idx.clamp(0, max(n_dups - 1, 0)) |
| 329 | dup_values = dup_loffs[dup_idx].to(torch.int64) | 502 | dup_values = dup_loffs[dup_idx].to(torch.int64) |
| 503 | + if bool(((dup_values < 0) | (dup_values >= address_limit)).any()): | ||
| 504 | + errors.append( | ||
| 505 | + f"dup addresses out of [0, {address_limit}) for {dedup_mode} dedup") | ||
| 330 | pairs = torch.stack((torch.repeat_interleave(prim, counts), dup_values), 1) | 506 | pairs = torch.stack((torch.repeat_interleave(prim, counts), dup_values), 1) |
| 331 | if int(torch.unique(dup_values).numel()) != total: | 507 | if int(torch.unique(dup_values).numel()) != total: |
| 332 | errors.append("dup_loffs lists the same duplicate row twice") | 508 | errors.append("dup_loffs lists the same duplicate row twice") |
| 333 | - pairs = pairs[torch.argsort(pairs[:, 0] * NvS + pairs[:, 1])] | 509 | + pairs = pairs[torch.argsort(pairs[:, 0] * address_limit + pairs[:, 1])] |
| 334 | else: | 510 | else: |
| 335 | - pairs = torch.zeros(0, 2, dtype=torch.int64) | 511 | + pairs = empty |
| 336 | 512 | ||
| 337 | - return pairs, (n_groups, n_dups), errors | 513 | + return pairs, counts_all, errors |
| 338 | 514 | ||
| 339 | 515 | ||
| 340 | @dataclass(frozen=True) | 516 | @dataclass(frozen=True) |
| @@ -350,7 +526,8 @@ class PlanExpectation: | |||
| 350 | canonical: torch.Tensor # [R, N] bool | 526 | canonical: torch.Tensor # [R, N] bool |
| 351 | dst: torch.Tensor # [R, N] expected encoded dst | 527 | dst: torch.Tensor # [R, N] expected encoded dst |
| 352 | dedup_pairs: torch.Tensor # [n_dups, 2] for this rank's destination | 528 | dedup_pairs: torch.Tensor # [n_dups, 2] for this rank's destination |
| 353 | - dedup_counts: tuple[int, int] | 529 | + dedup_counts: torch.Tensor # [2] rank / [R+2] server count row |
| 530 | + dedup_mode: str | ||
| 354 | tpe_global: torch.Tensor # [E] | 531 | tpe_global: torch.Tensor # [E] |
| 355 | 532 | ||
| 356 | 533 | ||
| @@ -360,6 +537,9 @@ def plan_expectation( | |||
| 360 | *, | 537 | *, |
| 361 | rank: int, | 538 | rank: int, |
| 362 | NvS: int, | 539 | NvS: int, |
| 540 | + dedup_mode: str = "rank", | ||
| 541 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 542 | + stripe_rank_placement: bool = False, | ||
| 363 | ) -> PlanExpectation: | 543 | ) -> PlanExpectation: |
| 364 | """Build the expected plan for every rank from the full routing.""" | 544 | """Build the expected plan for every rank from the full routing.""" |
| 365 | topk_all = topk_all.to(torch.int64) | 545 | topk_all = topk_all.to(torch.int64) |
| @@ -372,10 +552,15 @@ def plan_expectation( | |||
| 372 | experts_to_copy = prefetch_experts(alloc, R, E, B) | 552 | experts_to_copy = prefetch_experts(alloc, R, E, B) |
| 373 | cu_seqlens, expert_off = plan_layout(alloc, experts_to_copy, R, E, B) | 553 | cu_seqlens, expert_off = plan_layout(alloc, experts_to_copy, R, E, B) |
| 374 | dest, loff, canonical, raw = _route_destinations( | 554 | dest, loff, canonical, raw = _route_destinations( |
| 375 | - topk_all, tpe_all, alloc, expert_off, NvS | 555 | + topk_all, tpe_all, alloc, expert_off, NvS, |
| 556 | + dedup_mode=dedup_mode, ranks_per_server=ranks_per_server, | ||
| 557 | + stripe_rank_placement=stripe_rank_placement, | ||
| 376 | ) | 558 | ) |
| 377 | dst = encode_dst(raw, canonical) | 559 | dst = encode_dst(raw, canonical) |
| 378 | - pairs, counts = dedup_pairs(dest, loff, canonical, rank, S, NvS) | 560 | + pairs, counts = dedup_pairs( |
| 561 | + dest, loff, canonical, rank, S, NvS, | ||
| 562 | + dedup_mode=dedup_mode, ranks_per_server=ranks_per_server, | ||
| 563 | + ) | ||
| 379 | return PlanExpectation( | 564 | return PlanExpectation( |
| 380 | alloc=alloc, | 565 | alloc=alloc, |
| 381 | experts_to_copy=experts_to_copy, | 566 | experts_to_copy=experts_to_copy, |
| @@ -387,6 +572,7 @@ def plan_expectation( | |||
| 387 | dst=dst, | 572 | dst=dst, |
| 388 | dedup_pairs=pairs, | 573 | dedup_pairs=pairs, |
| 389 | dedup_counts=counts, | 574 | dedup_counts=counts, |
| 575 | + dedup_mode=dedup_mode, | ||
| 390 | tpe_global=tpe_all.sum(0), | 576 | tpe_global=tpe_all.sum(0), |
| 391 | ) | 577 | ) |
| 392 | 578 | ||
| @@ -474,4 +660,4 @@ def row_fingerprint( | |||
| 474 | out[base:end, 1] = block.abs().sum(1) | 660 | out[base:end, 1] = block.abs().sum(1) |
| 475 | out[base:end, 2] = (block * ramp).sum(1) | 661 | out[base:end, 2] = (block * ramp).sum(1) |
| 476 | out[base:end, 3] = (block * block).sum(1) | 662 | out[base:end, 3] = (block * block).sum(1) |
| 477 | - return out | 663 | + return out |
| @@ -32,6 +32,14 @@ size defaults to the launched world size (8 on a single node, 16 across two | |||
| 32 | nodes) — override with ``--ep-size`` for a subgroup of ranks [0, ep). ``--prod`` | 32 | nodes) — override with ``--ep-size`` for a subgroup of ranks [0, ep). ``--prod`` |
| 33 | runs just the production 8-card config (S=4096, K=16, E=896, H=7168). | 33 | runs just the production 8-card config (S=4096, K=16, E=896, H=7168). |
| 34 | 34 | ||
| 35 | +``--dedup-mode {rank,server}`` selects the Buffer's dedup domain, fixed at | ||
| 36 | +construction (same rule as bench_vs.py). ``server`` groups 8 consecutive ranks | ||
| 37 | +into one domain, needs ``--engine urma`` (effective UDMA), ``ep % 8 == 0`` and | ||
| 38 | +``K >= 2``, and allocates the multi-GiB symmetric PUT combine workspace. The | ||
| 39 | +planner emits the fused combine execution plan, so this benchmark can time the | ||
| 40 | +server combine flow without an extra preparation step; a missing plan fails fast | ||
| 41 | +before timing. | ||
| 42 | + | ||
| 35 | Every flow runs a live Ascend kernel and reports a cross-rank mean latency. | 43 | Every flow runs a live Ascend kernel and reports a cross-rank mean latency. |
| 36 | 44 | ||
| 37 | Run: | 45 | Run: |
| @@ -59,7 +67,9 @@ from _bench_common import ( | |||
| 59 | PROD_K, | 67 | PROD_K, |
| 60 | PROD_S, | 68 | PROD_S, |
| 61 | add_common_args, | 69 | add_common_args, |
| 70 | + add_dedup_mode_arg, | ||
| 62 | apply_engine, | 71 | apply_engine, |
| 72 | + validate_dedup_mode, | ||
| 63 | fmt4, | 73 | fmt4, |
| 64 | measure_flow, | 74 | measure_flow, |
| 65 | setup, | 75 | setup, |
| @@ -111,7 +121,8 @@ def bench_one(group, group_rank, R, S, K, E, H, bias_ratio, args, flows): | |||
| 111 | # capability and writes ASCEND_MOONEP_*_USE_UDMA, so init_with_buffer | 121 | # capability and writes ASCEND_MOONEP_*_USE_UDMA, so init_with_buffer |
| 112 | # below just inherits that policy. | 122 | # below just inherits that policy. |
| 113 | buffer = Buffer(S, H, K, E, R, num_sms=args.num_sms, group=group, | 123 | buffer = Buffer(S, H, K, E, R, num_sms=args.num_sms, group=group, |
| 114 | - use_udma=use_udma, explicitly_destroy=True) | 124 | + use_udma=use_udma, explicitly_destroy=True, |
| 125 | + dedup_mode=args.dedup_mode) | ||
| 115 | ctx = buffer._require_ctx() | 126 | ctx = buffer._require_ctx() |
| 116 | if not ShmemRuntime.is_initialized(): | 127 | if not ShmemRuntime.is_initialized(): |
| 117 | ShmemRuntime.init_with_buffer(group=group, enable_udma=use_udma) | 128 | ShmemRuntime.init_with_buffer(group=group, enable_udma=use_udma) |
| @@ -133,6 +144,18 @@ def bench_one(group, group_rank, R, S, K, E, H, bias_ratio, args, flows): | |||
| 133 | output_sh = torch.empty(S, H, dtype=torch.bfloat16, device=dev) | 144 | output_sh = torch.empty(S, H, dtype=torch.bfloat16, device=dev) |
| 134 | output_sk = torch.empty(S, K, dtype=torch.float32, device=dev) | 145 | output_sk = torch.empty(S, K, dtype=torch.float32, device=dev) |
| 135 | 146 | ||
| 147 | + # Server dedup combine consumes the planning-produced execution plan. Run | ||
| 148 | + # one untimed planning here so an unsupported/missing plan fails fast with a | ||
| 149 | + # clear message instead of an ABI error inside the timed combine loop. | ||
| 150 | + if args.dedup_mode == "server" and any( | ||
| 151 | + flow.startswith("combine") for flow in flows): | ||
| 152 | + launch_planning(ctx, topk_flat, tpe, cu_seqlens, plan) | ||
| 153 | + torch_npu.npu.synchronize() | ||
| 154 | + if plan.combine_execution_plan is None: | ||
| 155 | + raise RuntimeError( | ||
| 156 | + "server dedup planning did not produce a combine execution " | ||
| 157 | + "plan; check that combine UDMA is enabled for this Buffer") | ||
| 158 | + | ||
| 136 | # Global expert-load imbalance (max / mean over experts, all ranks summed). | 159 | # Global expert-load imbalance (max / mean over experts, all ranks summed). |
| 137 | global_tpe = tpe.to(torch.int64) | 160 | global_tpe = tpe.to(torch.int64) |
| 138 | dist.all_reduce(global_tpe, group=group) | 161 | dist.all_reduce(global_tpe, group=group) |
| @@ -224,6 +247,7 @@ def parse_args(): | |||
| 224 | ap.add_argument("--prod", action="store_true", | 247 | ap.add_argument("--prod", action="store_true", |
| 225 | help="Run only the production 8-card config: " | 248 | help="Run only the production 8-card config: " |
| 226 | "S=4096, K=16, E=896, H=7168, unbalance_ratio=1.0.") | 249 | "S=4096, K=16, E=896, H=7168, unbalance_ratio=1.0.") |
| 250 | + add_dedup_mode_arg(ap) | ||
| 227 | return ap.parse_args() | 251 | return ap.parse_args() |
| 228 | 252 | ||
| 229 | 253 | ||
| @@ -235,6 +259,12 @@ def main(): | |||
| 235 | ep = args.ep_size if args.ep_size is not None else world_size | 259 | ep = args.ep_size if args.ep_size is not None else world_size |
| 236 | assert ep >= 1, f"--ep-size must be >= 1, got {ep}" | 260 | assert ep >= 1, f"--ep-size must be >= 1, got {ep}" |
| 237 | assert ep <= world_size, f"--ep-size {ep} exceeds world size {world_size}" | 261 | assert ep <= world_size, f"--ep-size {ep} exceeds world size {world_size}" |
| 262 | + validate_dedup_mode(args.dedup_mode, args.use_udma, ep) | ||
| 263 | + if args.dedup_mode == "server": | ||
| 264 | + if args.topk is not None and args.topk < 2: | ||
| 265 | + raise SystemExit( | ||
| 266 | + "--dedup-mode server requires K >= 2 to exercise the " | ||
| 267 | + "intra-server forwarding path") | ||
| 238 | in_group = rank < ep | 268 | in_group = rank < ep |
| 239 | 269 | ||
| 240 | # Subgroup over ranks [0, ep); every world rank participates in new_group. | 270 | # Subgroup over ranks [0, ep); every world rank participates in new_group. |
| @@ -262,7 +292,8 @@ def main(): | |||
| 262 | 292 | ||
| 263 | if rank == 0: | 293 | if rank == 0: |
| 264 | print(f"=== bench_comm: world={world_size} ep={ep} nodesize={local_rank} " | 294 | print(f"=== bench_comm: world={world_size} ep={ep} nodesize={local_rank} " |
| 265 | - f"flows={flows} configs={len(configs)} ===", flush=True) | 295 | + f"flows={flows} configs={len(configs)} " |
| 296 | + f"dedup={args.dedup_mode} engine={args.engine} ===", flush=True) | ||
| 266 | 297 | ||
| 267 | # shmem init lives inside each config's bench_one: construct Buffer -> | 298 | # shmem init lives inside each config's bench_one: construct Buffer -> |
| 268 | # ShmemRuntime.init_with_buffer -> run -> destroy -> finalize -> reset | 299 | # ShmemRuntime.init_with_buffer -> run -> destroy -> finalize -> reset |
| @@ -43,7 +43,9 @@ import torch.distributed as dist | |||
| 43 | 43 | ||
| 44 | from _bench_common import ( | 44 | from _bench_common import ( |
| 45 | add_engine_args, | 45 | add_engine_args, |
| 46 | + add_dedup_mode_arg, | ||
| 46 | apply_engine, | 47 | apply_engine, |
| 48 | + validate_dedup_mode, | ||
| 47 | generate_topk_routing, | 49 | generate_topk_routing, |
| 48 | setup, | 50 | setup, |
| 49 | ) | 51 | ) |
| @@ -146,7 +148,7 @@ class DispatchRunner: | |||
| 146 | """Own the Buffer, plan, and fixed dispatch inputs for one benchmark.""" | 148 | """Own the Buffer, plan, and fixed dispatch inputs for one benchmark.""" |
| 147 | 149 | ||
| 148 | def __init__(self, group, R, S, K, E, H, num_sms, local_rank, with_weights, | 150 | def __init__(self, group, R, S, K, E, H, num_sms, local_rank, with_weights, |
| 149 | - rank=None, use_udma=False): | 151 | + rank=None, use_udma=False, dedup_mode="rank"): |
| 150 | self.group = group | 152 | self.group = group |
| 151 | self.rank = rank if rank is not None else dist.get_rank(group=group) | 153 | self.rank = rank if rank is not None else dist.get_rank(group=group) |
| 152 | self.R = R | 154 | self.R = R |
| @@ -164,6 +166,7 @@ class DispatchRunner: | |||
| 164 | num_sms=num_sms, | 166 | num_sms=num_sms, |
| 165 | group=group, | 167 | group=group, |
| 166 | use_udma=use_udma, | 168 | use_udma=use_udma, |
| 169 | + dedup_mode=dedup_mode, | ||
| 167 | explicitly_destroy=True, | 170 | explicitly_destroy=True, |
| 168 | rank=rank, | 171 | rank=rank, |
| 169 | ) | 172 | ) |
| @@ -311,6 +314,7 @@ def setup_no_dist(): | |||
| 311 | def main(): | 314 | def main(): |
| 312 | parser = argparse.ArgumentParser(description=__doc__) | 315 | parser = argparse.ArgumentParser(description=__doc__) |
| 313 | add_engine_args(parser) | 316 | add_engine_args(parser) |
| 317 | + add_dedup_mode_arg(parser) | ||
| 314 | parser.add_argument( | 318 | parser.add_argument( |
| 315 | "--out", | 319 | "--out", |
| 316 | default="bench_dispatch_maxvio_results.csv", | 320 | default="bench_dispatch_maxvio_results.csv", |
| @@ -362,6 +366,7 @@ def main(): | |||
| 362 | local_rank = local_device_index(local_rank) | 366 | local_rank = local_device_index(local_rank) |
| 363 | use_udma = apply_engine(args.engine) | 367 | use_udma = apply_engine(args.engine) |
| 364 | R = world_size | 368 | R = world_size |
| 369 | + validate_dedup_mode(args.dedup_mode, use_udma, R) | ||
| 365 | S, K, E, H = args.tokens, args.topk, args.experts, args.hidden | 370 | S, K, E, H = args.tokens, args.topk, args.experts, args.hidden |
| 366 | dev = f"npu:{local_rank}" | 371 | dev = f"npu:{local_rank}" |
| 367 | assert R >= 2, f"dispatch benchmark requires at least 2 ranks, got {R}" | 372 | assert R >= 2, f"dispatch benchmark requires at least 2 ranks, got {R}" |
| @@ -386,6 +391,7 @@ def main(): | |||
| 386 | with_weights=not args.no_weights, | 391 | with_weights=not args.no_weights, |
| 387 | rank=rank if args.no_dist else None, | 392 | rank=rank if args.no_dist else None, |
| 388 | use_udma=use_udma, | 393 | use_udma=use_udma, |
| 394 | + dedup_mode=args.dedup_mode, | ||
| 389 | ) | 395 | ) |
| 390 | if not ShmemRuntime.is_initialized(): | 396 | if not ShmemRuntime.is_initialized(): |
| 391 | if args.no_dist: | 397 | if args.no_dist: |
| @@ -65,10 +65,12 @@ import torch_npu | |||
| 65 | import torch.distributed as dist | 65 | import torch.distributed as dist |
| 66 | 66 | ||
| 67 | from _bench_common import ( | 67 | from _bench_common import ( |
| 68 | + add_dedup_mode_arg, | ||
| 68 | add_engine_args, | 69 | add_engine_args, |
| 69 | apply_engine, | 70 | apply_engine, |
| 70 | setup, | 71 | setup, |
| 71 | time_kernel, | 72 | time_kernel, |
| 73 | + validate_dedup_mode, | ||
| 72 | ) | 74 | ) |
| 73 | from _bench_common import generate_topk_routing # re-export | 75 | from _bench_common import generate_topk_routing # re-export |
| 74 | from _verify_reference import ( | 76 | from _verify_reference import ( |
| @@ -88,6 +90,7 @@ from npu_patch.buffer_c import ( | |||
| 88 | sym_tensor, | 90 | sym_tensor, |
| 89 | ) | 91 | ) |
| 90 | from npu_patch.launchers import ( | 92 | from npu_patch.launchers import ( |
| 93 | + _env_use_udma, | ||
| 91 | launch_combine, | 94 | launch_combine, |
| 92 | launch_dispatch, | 95 | launch_dispatch, |
| 93 | launch_grad_reduce, | 96 | launch_grad_reduce, |
| @@ -213,7 +216,7 @@ class MoonEPRunner: | |||
| 213 | 216 | ||
| 214 | def __init__(self, group, R, S, K, E, H, num_sms, local_rank, hp=2048, | 217 | def __init__(self, group, R, S, K, E, H, num_sms, local_rank, hp=2048, |
| 215 | use_udma=False, pf_overlap=False, verify=False, | 218 | use_udma=False, pf_overlap=False, verify=False, |
| 216 | - verify_stages=None, verify_trace=False): | 219 | + verify_stages=None, verify_trace=False, dedup_mode="rank"): |
| 217 | if pf_overlap and not _PREFETCH_HAS_RANK_BARRIERS: | 220 | if pf_overlap and not _PREFETCH_HAS_RANK_BARRIERS: |
| 218 | raise RuntimeError( | 221 | raise RuntimeError( |
| 219 | '--pf-overlap requires launch_prefetch rank_barriers support') | 222 | '--pf-overlap requires launch_prefetch rank_barriers support') |
| @@ -240,7 +243,8 @@ class MoonEPRunner: | |||
| 240 | self.pf_overlap = pf_overlap | 243 | self.pf_overlap = pf_overlap |
| 241 | self.pf_stream = torch.npu.Stream() if pf_overlap else None | 244 | self.pf_stream = torch.npu.Stream() if pf_overlap else None |
| 242 | self.buffer = Buffer(S, H, K, E, R, num_sms=num_sms, group=group, | 245 | self.buffer = Buffer(S, H, K, E, R, num_sms=num_sms, group=group, |
| 243 | - use_udma=use_udma, explicitly_destroy=True) | 246 | + use_udma=use_udma, dedup_mode=dedup_mode, |
| 247 | + explicitly_destroy=True) | ||
| 244 | self.ctx = self.buffer._require_ctx() | 248 | self.ctx = self.buffer._require_ctx() |
| 245 | # Pre-allocate the plan + outputs once (test_planning.py pattern): the | 249 | # Pre-allocate the plan + outputs once (test_planning.py pattern): the |
| 246 | # timed ops reuse these instead of allocating per call. | 250 | # timed ops reuse these instead of allocating per call. |
| @@ -512,8 +516,11 @@ class MoonEPRunner: | |||
| 512 | for r in range(R) | 516 | for r in range(R) |
| 513 | ]) | 517 | ]) |
| 514 | try: | 518 | try: |
| 515 | - exp = plan_expectation(topk_all, tpe_from_topk, rank=self.rank, | 519 | + exp = plan_expectation( |
| 516 | - NvS=NvS) | 520 | + topk_all, tpe_from_topk, rank=self.rank, NvS=NvS, |
| 521 | + dedup_mode=self.buffer.dedup_mode, | ||
| 522 | + stripe_rank_placement=_env_use_udma('dispatch'), | ||
| 523 | + ) | ||
| 517 | except Exception as exc: # local reference model; deterministic per rank | 524 | except Exception as exc: # local reference model; deterministic per rank |
| 518 | return _report_ok(f'plan (model error: {exc!r})', False, | 525 | return _report_ok(f'plan (model error: {exc!r})', False, |
| 519 | self.rank, self.group, dev) | 526 | self.rank, self.group, dev) |
| @@ -543,7 +550,7 @@ class MoonEPRunner: | |||
| 543 | 550 | ||
| 544 | dedup_pairs_plan, dedup_counts_plan, dedup_errors = plan_dedup_pairs( | 551 | dedup_pairs_plan, dedup_counts_plan, dedup_errors = plan_dedup_pairs( |
| 545 | self.plan.dup_groups.cpu(), self.plan.dup_loffs.cpu(), | 552 | self.plan.dup_groups.cpu(), self.plan.dup_loffs.cpu(), |
| 546 | - self.plan.dup_counts.cpu(), NvS) | 553 | + self.plan.dup_counts.cpu(), NvS, R=R, dedup_mode=self.buffer.dedup_mode) |
| 547 | 554 | ||
| 548 | checks = { | 555 | checks = { |
| 549 | 'routing': torch.equal(tpe_all.to(torch.int64), tpe_from_topk), | 556 | 'routing': torch.equal(tpe_all.to(torch.int64), tpe_from_topk), |
| @@ -554,7 +561,7 @@ class MoonEPRunner: | |||
| 554 | 'prefetch': torch.equal(etc_all, | 561 | 'prefetch': torch.equal(etc_all, |
| 555 | exp.experts_to_copy.expand_as(etc_all)), | 562 | exp.experts_to_copy.expand_as(etc_all)), |
| 556 | 'slots': slots_ok, | 563 | 'slots': slots_ok, |
| 557 | - 'dedup': (not dedup_errors and dedup_counts_plan == exp.dedup_counts | 564 | + 'dedup': (not dedup_errors and torch.equal(dedup_counts_plan, exp.dedup_counts) |
| 558 | and torch.equal(dedup_pairs_plan, exp.dedup_pairs)), | 565 | and torch.equal(dedup_pairs_plan, exp.dedup_pairs)), |
| 559 | } | 566 | } |
| 560 | ok = all(checks.values()) | 567 | ok = all(checks.values()) |
| @@ -783,6 +790,7 @@ class MoonEPRunner: | |||
| 783 | def main(): | 790 | def main(): |
| 784 | ap = argparse.ArgumentParser(description=__doc__) | 791 | ap = argparse.ArgumentParser(description=__doc__) |
| 785 | add_engine_args(ap) | 792 | add_engine_args(ap) |
| 793 | + add_dedup_mode_arg(ap) | ||
| 786 | ap.add_argument('--libs', nargs='+', default=['moonep'], choices=['moonep'], | 794 | ap.add_argument('--libs', nargs='+', default=['moonep'], choices=['moonep'], |
| 787 | help='Libraries to benchmark (Ascend: only moonep).') | 795 | help='Libraries to benchmark (Ascend: only moonep).') |
| 788 | ap.add_argument('--out', default='bench_vs_results.csv', | 796 | ap.add_argument('--out', default='bench_vs_results.csv', |
| @@ -832,6 +840,7 @@ def main(): | |||
| 832 | rank, world_size, local_rank = setup() | 840 | rank, world_size, local_rank = setup() |
| 833 | local_rank = local_device_index(local_rank) | 841 | local_rank = local_device_index(local_rank) |
| 834 | use_udma = apply_engine(args.engine) | 842 | use_udma = apply_engine(args.engine) |
| 843 | + validate_dedup_mode(args.dedup_mode, use_udma, world_size) | ||
| 835 | R = world_size | 844 | R = world_size |
| 836 | group = dist.group.WORLD | 845 | group = dist.group.WORLD |
| 837 | dev = f"npu:{local_rank}" | 846 | dev = f"npu:{local_rank}" |
| @@ -855,7 +864,7 @@ def main(): | |||
| 855 | hp=args.hp, use_udma=use_udma, | 864 | hp=args.hp, use_udma=use_udma, |
| 856 | pf_overlap=args.pf_overlap, verify=args.verify, | 865 | pf_overlap=args.pf_overlap, verify=args.verify, |
| 857 | verify_stages=args.verify_stages.split(','), | 866 | verify_stages=args.verify_stages.split(','), |
| 858 | - verify_trace=args.verify_trace) | 867 | + verify_trace=args.verify_trace, dedup_mode=args.dedup_mode) |
| 859 | if not ShmemRuntime.is_initialized(): | 868 | if not ShmemRuntime.is_initialized(): |
| 860 | if args.ip_port is not None or multi_node: | 869 | if args.ip_port is not None or multi_node: |
| 861 | # Multi-node: ip_port/DEFAULT bootstrap; when ip_port is omitted it | 870 | # Multi-node: ip_port/DEFAULT bootstrap; when ip_port is omitted it |
| @@ -902,8 +911,8 @@ def main(): | |||
| 902 | runner.prepare(topk, tpe, hidden, weights) | 911 | runner.prepare(topk, tpe, hidden, weights) |
| 903 | 912 | ||
| 904 | # Correctness self-check. | 913 | # Correctness self-check. |
| 905 | - if args.verify: | 914 | + if args.verify and not runner.verify_precision(hidden, weights): |
| 906 | - runner.verify_precision(hidden, weights) | 915 | + raise AssertionError(f'precision check failed at MaxVio {target:g}') |
| 907 | 916 | ||
| 908 | d_f = time_op(runner.dispatch_fwd, group, rank, args.warmup, | 917 | d_f = time_op(runner.dispatch_fwd, group, rank, args.warmup, |
| 909 | args.iters, cudagraph=args.cudagraph) | 918 | args.iters, cudagraph=args.cudagraph) |
| @@ -130,10 +130,12 @@ import torch_npu | |||
| 130 | import torch.distributed as dist | 130 | import torch.distributed as dist |
| 131 | 131 | ||
| 132 | from _bench_common import ( | 132 | from _bench_common import ( |
| 133 | + add_dedup_mode_arg, | ||
| 133 | add_engine_args, | 134 | add_engine_args, |
| 134 | apply_engine, | 135 | apply_engine, |
| 135 | setup, | 136 | setup, |
| 136 | time_kernel, | 137 | time_kernel, |
| 138 | + validate_dedup_mode, | ||
| 137 | ) | 139 | ) |
| 138 | from _bench_common import generate_topk_routing # re-export | 140 | from _bench_common import generate_topk_routing # re-export |
| 139 | 141 | ||
| @@ -221,7 +223,7 @@ class MoonEPRunner: | |||
| 221 | NAME = 'moonep' | 223 | NAME = 'moonep' |
| 222 | 224 | ||
| 223 | def __init__(self, group, R, S, K, E, H, num_sms, local_rank, | 225 | def __init__(self, group, R, S, K, E, H, num_sms, local_rank, |
| 224 | - use_udma=False, hp=3072): | 226 | + use_udma=False, hp=3072, dedup_mode="rank"): |
| 225 | self.group = group | 227 | self.group = group |
| 226 | self.num_sms = num_sms | 228 | self.num_sms = num_sms |
| 227 | self.rank = dist.get_rank(group) | 229 | self.rank = dist.get_rank(group) |
| @@ -230,7 +232,8 @@ class MoonEPRunner: | |||
| 230 | self.use_udma = use_udma | 232 | self.use_udma = use_udma |
| 231 | self.hp = hp | 233 | self.hp = hp |
| 232 | self.buffer = Buffer(S, H, K, E, R, num_sms=num_sms, group=group, | 234 | self.buffer = Buffer(S, H, K, E, R, num_sms=num_sms, group=group, |
| 233 | - use_udma=use_udma, explicitly_destroy=True) | 235 | + use_udma=use_udma, dedup_mode=dedup_mode, |
| 236 | + explicitly_destroy=True) | ||
| 234 | self.ctx = self.buffer._require_ctx() | 237 | self.ctx = self.buffer._require_ctx() |
| 235 | # Pre-allocate the plan + outputs once (test_planning.py pattern): the | 238 | # Pre-allocate the plan + outputs once (test_planning.py pattern): the |
| 236 | # timed ops reuse these instead of allocating per call. | 239 | # timed ops reuse these instead of allocating per call. |
| @@ -605,6 +608,7 @@ RUNNERS = { | |||
| 605 | def main(): | 608 | def main(): |
| 606 | ap = argparse.ArgumentParser(description=__doc__) | 609 | ap = argparse.ArgumentParser(description=__doc__) |
| 607 | add_engine_args(ap) | 610 | add_engine_args(ap) |
| 611 | + add_dedup_mode_arg(ap) | ||
| 608 | ap.add_argument('--libs', nargs='+', default=['moonep', 'all2all'], | 612 | ap.add_argument('--libs', nargs='+', default=['moonep', 'all2all'], |
| 609 | choices=list(RUNNERS), | 613 | choices=list(RUNNERS), |
| 610 | help='Libraries to benchmark (default: both). "all2all" ' | 614 | help='Libraries to benchmark (default: both). "all2all" ' |
| @@ -650,6 +654,7 @@ def main(): | |||
| 650 | rank, world_size, local_rank = setup() | 654 | rank, world_size, local_rank = setup() |
| 651 | local_rank = local_device_index(local_rank) | 655 | local_rank = local_device_index(local_rank) |
| 652 | use_udma = apply_engine(args.engine) | 656 | use_udma = apply_engine(args.engine) |
| 657 | + validate_dedup_mode(args.dedup_mode, use_udma, world_size) | ||
| 653 | R = world_size | 658 | R = world_size |
| 654 | group = dist.group.WORLD | 659 | group = dist.group.WORLD |
| 655 | dev = f"npu:{local_rank}" | 660 | dev = f"npu:{local_rank}" |
| @@ -672,7 +677,7 @@ def main(): | |||
| 672 | if 'moonep' in args.libs: | 677 | if 'moonep' in args.libs: |
| 673 | runners['moonep'] = MoonEPRunner(group, R, S, K, E, H, args.num_sms, | 678 | runners['moonep'] = MoonEPRunner(group, R, S, K, E, H, args.num_sms, |
| 674 | local_rank, use_udma=use_udma, | 679 | local_rank, use_udma=use_udma, |
| 675 | - hp=args.hp) | 680 | + hp=args.hp, dedup_mode=args.dedup_mode) |
| 676 | if 'all2all' in args.libs: | 681 | if 'all2all' in args.libs: |
| 677 | runners['all2all'] = All2AllRunner(group, R, S, K, E, H, | 682 | runners['all2all'] = All2AllRunner(group, R, S, K, E, H, |
| 678 | args.num_sms, local_rank) | 683 | args.num_sms, local_rank) |
| @@ -90,6 +90,7 @@ def comm_context(ctx, buffers): | |||
| 90 | if not isinstance(buffers, CommBuffers): | 90 | if not isinstance(buffers, CommBuffers): |
| 91 | raise TypeError("buffers must be CommBuffers") | 91 | raise TypeError("buffers must be CommBuffers") |
| 92 | local = dict(ctx) | 92 | local = dict(ctx) |
| 93 | + local['_comm_owner_ctx'] = ctx | ||
| 93 | local['hidden_buf'] = local['hidden_buf_local'] = buffers.hidden | 94 | local['hidden_buf'] = local['hidden_buf_local'] = buffers.hidden |
| 94 | local['weights_buf'] = local['weights_buf_local'] = buffers.route | 95 | local['weights_buf'] = local['weights_buf_local'] = buffers.route |
| 95 | return local | 96 | return local |
| @@ -8,10 +8,91 @@ and K-sum into one launch. | |||
| 8 | 8 | ||
| 9 | from __future__ import annotations | 9 | from __future__ import annotations |
| 10 | 10 | ||
| 11 | -import torch | 11 | +from typing import TYPE_CHECKING |
| 12 | 12 | ||
| 13 | -from .launchers import _env_use_udma | 13 | +# Workspace sizing remains usable without loading the NPU runtime. |
| 14 | -from .planning import MoonEPCommPlan | 14 | +# Runtime dependencies are imported only by launch and input-validation helpers. |
| 15 | +if TYPE_CHECKING: | ||
| 16 | + import torch | ||
| 17 | + from .planning import MoonEPCommPlan | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +# ---- Workspace ABI and core roles (mirrors kernels/types.h) ---- | ||
| 21 | +# Combine only; does not change num_sms or launch core counts for dispatch/planning. | ||
| 22 | +COMBINE_PUT_CORES = 64 | ||
| 23 | +COMBINE_PUT_SOURCE_LANES = 16 | ||
| 24 | +COMBINE_RING_STREAMS = 8 | ||
| 25 | +COMBINE_RING_DEPTH = 4 | ||
| 26 | +COMBINE_RING_GROUPS_PER_PAGE = 64 | ||
| 27 | +COMBINE_RING_PLAN_ABI = 6 | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def combine_put_roles(ranks: int) -> list: | ||
| 31 | + """Core ownership in the production kernel: relay/reduce/sender/final-only.""" | ||
| 32 | + if ranks >= 128: | ||
| 33 | + return [0] * 8 + [1] * 16 + [2] * 32 + [3] * 8 | ||
| 34 | + return [0] * 8 + [1] * 32 + [2] * 24 | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def combine_ring_geometry(n: int, h: int, ranks: int, topk: int = 16) -> dict: | ||
| 38 | + """Bounded relay geometry; no user-provided row-capacity override. | ||
| 39 | + | ||
| 40 | + Each page holds up to 64 * topk contributor rows, packed as complete groups. | ||
| 41 | + Small groups can allow more than 64 groups to fit in one page. | ||
| 42 | + Planning may borrow the same phase arena before any payload becomes live. | ||
| 43 | + Reserve for either dedup mode because a Buffer may prepare both kinds. | ||
| 44 | + """ | ||
| 45 | + if min(n, h, ranks, topk) <= 0 or topk > 16: | ||
| 46 | + raise ValueError("n/h/ranks must be positive and topk must be in [1,16]") | ||
| 47 | + align = lambda value: (value + 511) & ~511 | ||
| 48 | + page_rows = COMBINE_RING_GROUPS_PER_PAGE * topk | ||
| 49 | + input_rows = COMBINE_RING_STREAMS * COMBINE_RING_DEPTH * page_rows | ||
| 50 | + input_bytes = align(input_rows * h * 2) | ||
| 51 | + result_bytes = align(n * h * 2) | ||
| 52 | + staging = max((ranks * n * (32 + 8 * width) | ||
| 53 | + for width in (1, 8) | ||
| 54 | + if ranks <= 128 and ranks * (32 + 8 * width) <= h * 16), | ||
| 55 | + default=0) | ||
| 56 | + return dict(page_rows=page_rows, input_rows=input_rows, | ||
| 57 | + input_bytes=input_bytes, result_bytes=result_bytes, | ||
| 58 | + planning_stage_bytes=staging, | ||
| 59 | + phase_bytes=align(max(staging, input_bytes + result_bytes)), | ||
| 60 | + max_pages=(n + 63) // 64 + ranks) | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +def combine_put_workspace_bytes(n: int, h: int, ranks: int, topk: int = 16) -> int: | ||
| 64 | + # Total symmetric workspace bytes per rank; N=n=S*K, H=h, R=ranks. | ||
| 65 | + # Matches the order and capacities in MakeCombinePutLayout in | ||
| 66 | + # include/ascend_moonep/kernels/types.h; reserves maximum slots regardless of deduplication or weights. | ||
| 67 | + ring = combine_ring_geometry(n, h, ranks, topk) | ||
| 68 | + align = lambda value: (value + 511) & ~511 | ||
| 69 | + batches = (n + 63) // 64 | ||
| 70 | + return ( | ||
| 71 | +# Final return data plus phase-exclusive Planning / input-ring+result arena. | ||
| 72 | + align(n * h * 2) + ring['phase_bytes'] | ||
| 73 | + # Float weights[N]; N entries each for reverse/reverse_send/final_map/group_of_loff/tx_rows. | ||
| 74 | + + align(n * 4) + 5 * align(n * 64) | ||
| 75 | + # R entries each for source_counts/counts_send; 8*N each for contributor/relay_send/relay_publish. | ||
| 76 | + + 2 * align(ranks * 64) + 2 * align(8 * n * 64) | ||
| 77 | + + max(align(8 * n * 64), align(ranks * 64) + align(ring['max_pages'] * 64)) | ||
| 78 | + # Two reserved count tables; source/reduce/final ready have 8*R/R*B/2*R slots, respectively. | ||
| 79 | + + 1024 + (8 * ranks + ranks * batches + 2 * ranks) * 512 | ||
| 80 | + # R weight_ready slots and 64 core-private magic source slots; 512 bytes per slot, first 8 used. | ||
| 81 | + + ranks * 512 + COMBINE_PUT_CORES * 512 | ||
| 82 | + + 2 * align(8 * ranks * 64) + ranks * 512 | ||
| 83 | + # One rank-local final gate: core 0 fans in final_ready then broadcasts it. | ||
| 84 | + + 512 | ||
| 85 | + # N independent 128-byte final descriptors; N/K are active, N covers K=1. | ||
| 86 | + + align(n * 128) | ||
| 87 | + # Per-stream epoch, producer-ready, credits, reducer-done, stable | ||
| 88 | + # PUT-source tickets, and persistent logical-page result readiness. | ||
| 89 | + + (COMBINE_RING_STREAMS | ||
| 90 | + + COMBINE_RING_STREAMS * COMBINE_RING_DEPTH * 8 | ||
| 91 | + + COMBINE_RING_STREAMS * COMBINE_RING_DEPTH | ||
| 92 | + + COMBINE_RING_STREAMS * COMBINE_RING_DEPTH * 4 | ||
| 93 | + + 8 * COMBINE_RING_STREAMS * COMBINE_RING_DEPTH | ||
| 94 | + + ring['max_pages']) * 512 | ||
| 95 | + ) | ||
| 15 | 96 | ||
| 16 | 97 | ||
| 17 | def _check_tensor( | 98 | def _check_tensor( |
| @@ -35,10 +116,17 @@ def _check_combine_inputs( | |||
| 35 | plan: MoonEPCommPlan, | 116 | plan: MoonEPCommPlan, |
| 36 | output_sk: torch.Tensor | None, | 117 | output_sk: torch.Tensor | None, |
| 37 | ) -> None: | 118 | ) -> None: |
| 119 | + import torch | ||
| 120 | + from .launchers import _env_use_udma | ||
| 121 | + from .planning import MoonEPCommPlan | ||
| 122 | + | ||
| 38 | if not isinstance(plan, MoonEPCommPlan): | 123 | if not isinstance(plan, MoonEPCommPlan): |
| 39 | raise TypeError("plan must be a MoonEPCommPlan") | 124 | raise TypeError("plan must be a MoonEPCommPlan") |
| 40 | 125 | ||
| 41 | use_udma = _env_use_udma("combine") | 126 | use_udma = _env_use_udma("combine") |
| 127 | + # Server dedup consumes the Buffer's symmetric PUT workspace; the legacy | ||
| 128 | + # rank-level kernel keeps its own rank-local gather workspace in the op. | ||
| 129 | + server_dedup = plan.dedup_mode == "server" | ||
| 42 | required_ctx_keys = [ | 130 | required_ctx_keys = [ |
| 43 | "rank", "R", "E", "B", "S", "H", "K", "NvS", "kernels", | 131 | "rank", "R", "E", "B", "S", "H", "K", "NvS", "kernels", |
| 44 | ] | 132 | ] |
| @@ -46,6 +134,8 @@ def _check_combine_inputs( | |||
| 46 | required_ctx_keys.extend(( | 134 | required_ctx_keys.extend(( |
| 47 | "hidden_buf_local", "weights_buf_local", "combine_sync_buffer", | 135 | "hidden_buf_local", "weights_buf_local", "combine_sync_buffer", |
| 48 | )) | 136 | )) |
| 137 | + if server_dedup: | ||
| 138 | + required_ctx_keys.append("combine_workspace") | ||
| 49 | else: | 139 | else: |
| 50 | required_ctx_keys.extend(("hidden_buf", "weights_buf")) | 140 | required_ctx_keys.extend(("hidden_buf", "weights_buf")) |
| 51 | missing = [key for key in required_ctx_keys if key not in ctx] | 141 | missing = [key for key in required_ctx_keys if key not in ctx] |
| @@ -67,12 +157,10 @@ def _check_combine_inputs( | |||
| 67 | if use_udma: | 157 | if use_udma: |
| 68 | if H % 8 != 0: | 158 | if H % 8 != 0: |
| 69 | raise ValueError("UDMA combine requires H to be a multiple of 8") | 159 | raise ValueError("UDMA combine requires H to be a multiple of 8") |
| 70 | - # Four bf16 rows plus fp32 accumulator/temp use 16 bytes per hidden | 160 | + # Phase 1/3 tile large rows through UB; cap one bf16 token row at 8 MiB. |
| 71 | - # element in the UDMA kernel's 128 KiB full-row double buffer. | 161 | + if H * torch.bfloat16.itemsize > 8 * 1024 * 1024: |
| 72 | - if H * 16 > 128 * 1024: | ||
| 73 | raise ValueError( | 162 | raise ValueError( |
| 74 | - "UDMA combine requires H<=8192 so its full-row double " | 163 | + "UDMA combine requires one bf16 token row to be <=8 MiB" |
| 75 | - "buffer fits in 128 KiB of UB" | ||
| 76 | ) | 164 | ) |
| 77 | else: | 165 | else: |
| 78 | if H % 16 != 0: | 166 | if H % 16 != 0: |
| @@ -119,14 +207,14 @@ def _check_combine_inputs( | |||
| 119 | _check_tensor( | 207 | _check_tensor( |
| 120 | plan.dup_loffs, | 208 | plan.dup_loffs, |
| 121 | "plan.dup_loffs", | 209 | "plan.dup_loffs", |
| 122 | - (NvS,), | 210 | + (8 * NvS if plan.dup_counts.numel() == plan.R + 2 else NvS,), |
| 123 | torch.int32, | 211 | torch.int32, |
| 124 | output_sh.device, | 212 | output_sh.device, |
| 125 | ) | 213 | ) |
| 126 | _check_tensor( | 214 | _check_tensor( |
| 127 | plan.dup_counts, | 215 | plan.dup_counts, |
| 128 | "plan.dup_counts", | 216 | "plan.dup_counts", |
| 129 | - (2,), | 217 | + (plan.R + 2 if plan.dup_counts.numel() == plan.R + 2 else 2,), |
| 130 | torch.int32, | 218 | torch.int32, |
| 131 | output_sh.device, | 219 | output_sh.device, |
| 132 | ) | 220 | ) |
| @@ -150,6 +238,14 @@ def _check_combine_inputs( | |||
| 150 | ) | 238 | ) |
| 151 | 239 | ||
| 152 | if use_udma: | 240 | if use_udma: |
| 241 | + if server_dedup: | ||
| 242 | + _check_tensor( | ||
| 243 | + ctx["combine_workspace"], | ||
| 244 | + "ctx.combine_workspace", | ||
| 245 | + (combine_put_workspace_bytes(NvS, H, plan.R, plan.K),), | ||
| 246 | + torch.uint8, | ||
| 247 | + output_sh.device, | ||
| 248 | + ) | ||
| 153 | sync_buffer = ctx["combine_sync_buffer"] | 249 | sync_buffer = ctx["combine_sync_buffer"] |
| 154 | if sync_buffer.dtype != torch.uint8 or not sync_buffer.is_contiguous(): | 250 | if sync_buffer.dtype != torch.uint8 or not sync_buffer.is_contiguous(): |
| 155 | raise ValueError( | 251 | raise ValueError( |
| @@ -188,3 +284,33 @@ def launch_combine( | |||
| 188 | plan, | 284 | plan, |
| 189 | output_sk=output_sk, | 285 | output_sk=output_sk, |
| 190 | ) | 286 | ) |
| 287 | + | ||
| 288 | + | ||
| 289 | +# ---- Launch an immutable execution plan produced by planning.py ---- | ||
| 290 | +def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None): | ||
| 291 | + import torch | ||
| 292 | + import torch_npu | ||
| 293 | + from .planning import CombineExecutionPlan, _routes, _key | ||
| 294 | + | ||
| 295 | + if not isinstance(execution_plan, CombineExecutionPlan): | ||
| 296 | + raise TypeError('execution_plan must be returned by prepare_combine_plan') | ||
| 297 | + from .launchers import _env_use_udma | ||
| 298 | + if not _env_use_udma('combine'): | ||
| 299 | + raise ValueError('execution plans require UDMA combine') | ||
| 300 | + execution_plan.validate(ctx, plan) | ||
| 301 | + stream = torch_npu.npu.current_stream() | ||
| 302 | + stream.wait_event(execution_plan.ready) | ||
| 303 | + weights = ctx['weights_buf_local'].view(torch.float32) if output_sk is not None else None | ||
| 304 | + torch.classes.AscendMoonEP.CombineUrma().compute_prepared( | ||
| 305 | + ctx['hidden_buf_local'], weights, ctx['combine_sync_buffer'], ctx['combine_workspace'], | ||
| 306 | + *_routes(plan), output_sh, output_sk, execution_plan.storage, *_key(ctx)) | ||
| 307 | + for tensor in (execution_plan.storage, *_routes(plan), ctx['hidden_buf_local'], weights, | ||
| 308 | + ctx['combine_workspace'], ctx['combine_sync_buffer'], output_sh, | ||
| 309 | + output_sk): | ||
| 310 | + if tensor is not None: | ||
| 311 | + tensor.record_stream(stream) | ||
| 312 | + # Also orders subsequent reuse on another stream. Overlapping calls sharing | ||
| 313 | + # the Buffer workspace remain unsupported, just like legacy combine. | ||
| 314 | + last_use = torch_npu.npu.Event() | ||
| 315 | + last_use.record(stream) | ||
| 316 | + execution_plan.ready = last_use | ||
| @@ -10,7 +10,7 @@ from __future__ import annotations | |||
| 10 | 10 | ||
| 11 | import torch | 11 | import torch |
| 12 | 12 | ||
| 13 | -from .planning import MoonEPCommPlan | 13 | +from .planning import MoonEPCommPlan, RANKS_PER_SERVER |
| 14 | 14 | ||
| 15 | 15 | ||
| 16 | def _check_tensor( | 16 | def _check_tensor( |
| @@ -95,17 +95,25 @@ def _check_dispatch_inputs( | |||
| 95 | torch.int32, | 95 | torch.int32, |
| 96 | hidden_sh.device, | 96 | hidden_sh.device, |
| 97 | ) | 97 | ) |
| 98 | + # The source prefix in counts marks the server protocol; rank plans keep their original capacity. | ||
| 99 | + server_dedup = plan.dedup_mode == "server" | ||
| 100 | + if server_dedup and R % RANKS_PER_SERVER != 0: | ||
| 101 | + raise ValueError("server dedup requires R divisible by 8") | ||
| 102 | + if server_dedup and not ctx.get("_dispatch_use_udma", False): | ||
| 103 | + raise ValueError("server dedup requires UDMA dispatch") | ||
| 104 | + dup_capacity = RANKS_PER_SERVER * NvS if server_dedup else NvS | ||
| 105 | + count_size = R + 2 if server_dedup else 2 | ||
| 98 | _check_tensor( | 106 | _check_tensor( |
| 99 | plan.dup_loffs, | 107 | plan.dup_loffs, |
| 100 | "plan.dup_loffs", | 108 | "plan.dup_loffs", |
| 101 | - (NvS,), | 109 | + (dup_capacity,), |
| 102 | torch.int32, | 110 | torch.int32, |
| 103 | hidden_sh.device, | 111 | hidden_sh.device, |
| 104 | ) | 112 | ) |
| 105 | _check_tensor( | 113 | _check_tensor( |
| 106 | plan.dup_counts, | 114 | plan.dup_counts, |
| 107 | "plan.dup_counts", | 115 | "plan.dup_counts", |
| 108 | - (2,), | 116 | + (count_size,), |
| 109 | torch.int32, | 117 | torch.int32, |
| 110 | hidden_sh.device, | 118 | hidden_sh.device, |
| 111 | ) | 119 | ) |
| @@ -44,6 +44,8 @@ def planning_workspace_sizes( | |||
| 44 | num_max_tokens_per_rank: int, | 44 | num_max_tokens_per_rank: int, |
| 45 | world_size: int, | 45 | world_size: int, |
| 46 | core_num: int, | 46 | core_num: int, |
| 47 | + *, | ||
| 48 | + server_dedup: bool = False, | ||
| 47 | ) -> tuple[int, int]: | 49 | ) -> tuple[int, int]: |
| 48 | global _PLANNING | 50 | global _PLANNING |
| 49 | if _PLANNING is None: | 51 | if _PLANNING is None: |
| @@ -55,6 +57,7 @@ def planning_workspace_sizes( | |||
| 55 | num_experts, | 57 | num_experts, |
| 56 | world_size, | 58 | world_size, |
| 57 | core_num, | 59 | core_num, |
| 60 | + server_dedup, | ||
| 58 | ) | 61 | ) |
| 59 | ) | 62 | ) |
| 60 | symmetric_bytes = int( | 63 | symmetric_bytes = int( |
| @@ -62,6 +65,7 @@ def planning_workspace_sizes( | |||
| 62 | num_experts, | 65 | num_experts, |
| 63 | num_max_tokens_per_rank, | 66 | num_max_tokens_per_rank, |
| 64 | world_size, | 67 | world_size, |
| 68 | + server_dedup, | ||
| 65 | ) | 69 | ) |
| 66 | ) | 70 | ) |
| 67 | return local_elements, symmetric_bytes | 71 | return local_elements, symmetric_bytes |
| @@ -86,11 +90,25 @@ def launch_planning_op( | |||
| 86 | core_num: int, | 90 | core_num: int, |
| 87 | rank: int, | 91 | rank: int, |
| 88 | world_size: int, | 92 | world_size: int, |
| 89 | -) -> None: | 93 | + server_dedup: bool = False, |
| 94 | + combine_workspace: torch.Tensor | None = None, | ||
| 95 | + hidden_size: int = 0, | ||
| 96 | + *, | ||
| 97 | + use_udma: bool = False, | ||
| 98 | +) -> torch.Tensor | None: | ||
| 99 | + """Launch planning. | ||
| 100 | + | ||
| 101 | + ``server_dedup`` selects the kernel family: ``True`` runs the server-level | ||
| 102 | + dedup planner (which can also emit the fused combine execution plan when | ||
| 103 | + ``combine_workspace`` is given), ``False`` runs the legacy rank-level | ||
| 104 | + planner and never produces a combine plan. | ||
| 105 | + | ||
| 106 | + ``use_udma`` is the dispatch transport flag used for rank placement. | ||
| 107 | + """ | ||
| 90 | global _PLANNING | 108 | global _PLANNING |
| 91 | if _PLANNING is None: | 109 | if _PLANNING is None: |
| 92 | _PLANNING = torch.classes.AscendMoonEP.Planning() | 110 | _PLANNING = torch.classes.AscendMoonEP.Planning() |
| 93 | - _PLANNING.compute( | 111 | + args = ( |
| 94 | topk_idx, | 112 | topk_idx, |
| 95 | dst, | 113 | dst, |
| 96 | cu_seqlens, | 114 | cu_seqlens, |
| @@ -109,8 +127,13 @@ def launch_planning_op( | |||
| 109 | core_num, | 127 | core_num, |
| 110 | rank, | 128 | rank, |
| 111 | world_size, | 129 | world_size, |
| 112 | - _env_use_udma('planning'), | 130 | + use_udma, |
| 131 | + bool(server_dedup), | ||
| 113 | ) | 132 | ) |
| 133 | + if combine_workspace is not None: | ||
| 134 | + return _PLANNING.compute_fused(*args, combine_workspace, hidden_size) | ||
| 135 | + _PLANNING.compute(*args) | ||
| 136 | + return None | ||
| 114 | 137 | ||
| 115 | 138 | ||
| 116 | def launch_dispatch_op( | 139 | def launch_dispatch_op( |
| @@ -129,6 +152,7 @@ def launch_dispatch_op( | |||
| 129 | world_size: int, | 152 | world_size: int, |
| 130 | rank: int, | 153 | rank: int, |
| 131 | num_sms: int = 32, | 154 | num_sms: int = 32, |
| 155 | + server_dedup: bool = False, | ||
| 132 | ) -> None: | 156 | ) -> None: |
| 133 | """Launch dispatch; num_sms controls only the MTE AIV launch width.""" | 157 | """Launch dispatch; num_sms controls only the MTE AIV launch width.""" |
| 134 | global _DISPATCH | 158 | global _DISPATCH |
| @@ -152,9 +176,7 @@ def launch_dispatch_op( | |||
| 152 | rank, | 176 | rank, |
| 153 | use_udma, | 177 | use_udma, |
| 154 | ) | 178 | ) |
| 155 | - if not use_udma: | 179 | + _DISPATCH.compute(*args, num_sms, bool(server_dedup)) |
| 156 | - args += (num_sms,) | ||
| 157 | - _DISPATCH.compute(*args) | ||
| 158 | 180 | ||
| 159 | 181 | ||
| 160 | def launch_dispatch_profile_op( | 182 | def launch_dispatch_profile_op( |
| @@ -173,6 +195,7 @@ def launch_dispatch_profile_op( | |||
| 173 | num_topk: int, | 195 | num_topk: int, |
| 174 | world_size: int, | 196 | world_size: int, |
| 175 | rank: int, | 197 | rank: int, |
| 198 | + server_dedup: bool = False, | ||
| 176 | ) -> None: | 199 | ) -> None: |
| 177 | global _DISPATCH | 200 | global _DISPATCH |
| 178 | if _DISPATCH is None: | 201 | if _DISPATCH is None: |
| @@ -194,6 +217,7 @@ def launch_dispatch_profile_op( | |||
| 194 | world_size, | 217 | world_size, |
| 195 | rank, | 218 | rank, |
| 196 | _env_use_udma('dispatch'), | 219 | _env_use_udma('dispatch'), |
| 220 | + bool(server_dedup), | ||
| 197 | ) | 221 | ) |
| 198 | 222 | ||
| 199 | 223 | ||
| @@ -327,7 +351,6 @@ def launch_combine( | |||
| 327 | def launch_inter_rank_sync(ctx: dict) -> None: | 351 | def launch_inter_rank_sync(ctx: dict) -> None: |
| 328 | """Ascend replacement for the CuTe DSL rank sync kernel: a host-side | 352 | """Ascend replacement for the CuTe DSL rank sync kernel: a host-side |
| 329 | cross-rank signal barrier on the current stream.""" | 353 | cross-rank signal barrier on the current stream.""" |
| 330 | - from ._common import cross_rank_barrier | ||
| 331 | 354 | ||
| 332 | cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream) | 355 | cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream) |
| 333 | return None | 356 | return None |
| @@ -160,5 +160,27 @@ ascend_moonep_add_kernel_library( | |||
| 160 | ${ASCEND_MOONEP_ARCH_DEFINITIONS} | 160 | ${ASCEND_MOONEP_ARCH_DEFINITIONS} |
| 161 | ) | 161 | ) |
| 162 | 162 | ||
| 163 | +if(ASCEND_MOONEP_UDMA) | ||
| 164 | + # Keep the rank and server implementations in separate unity builds. | ||
| 165 | + # Their device kernels use overlapping file-local helper names. | ||
| 166 | + ascend_moonep_add_kernel_library( | ||
| 167 | + ascend_moonep_kernels_server_dedup | ||
| 168 | + SOURCES | ||
| 169 | + kernels/moonep_combine_udma_server_dedup.cpp | ||
| 170 | + kernels/moonep_dispatch_udma_server_dedup.cpp | ||
| 171 | + kernels/planning_server_dedup.cpp | ||
| 172 | + INCLUDES | ||
| 173 | + include | ||
| 174 | + kernels | ||
| 175 | + ../3rdparty/catlass/include | ||
| 176 | + ../3rdparty/catlass | ||
| 177 | + COMPILE_DEFINITIONS | ||
| 178 | + CATLASS_ARCH=${ASCEND_MOONEP_CATLASS_ARCH} | ||
| 179 | + ${ASCEND_MOONEP_ARCH_DEFINITIONS} | ||
| 180 | + ) | ||
| 181 | + | ||
| 182 | + message(STATUS "ascend-moonep server-dedup kernel library: ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libascend_moonep_kernels_server_dedup.so") | ||
| 183 | +endif() | ||
| 184 | + | ||
| 163 | message(STATUS "ascend-moonep kernel library: ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libascend_moonep_kernels.so") | 185 | message(STATUS "ascend-moonep kernel library: ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libascend_moonep_kernels.so") |
| 164 | message(STATUS "SHMEM installation: ${SHMEM_HOME_PATH}") | 186 | message(STATUS "SHMEM installation: ${SHMEM_HOME_PATH}") |
| @@ -79,7 +79,7 @@ void LaunchMoonEPDispatchKernel( | |||
| 79 | const_cast<ascend_moonep::MoonEPDispatchTilingData*>(&tiling))); | 79 | const_cast<ascend_moonep::MoonEPDispatchTilingData*>(&tiling))); |
| 80 | } | 80 | } |
| 81 | 81 | ||
| 82 | -void LaunchMoonEPDispatchUdmaKernel( | 82 | +void LaunchMoonEPDispatchUdmaLegacyKernel( |
| 83 | torch::Tensor hidden_sh, | 83 | torch::Tensor hidden_sh, |
| 84 | torch::Tensor route_weights, | 84 | torch::Tensor route_weights, |
| 85 | torch::Tensor dst, | 85 | torch::Tensor dst, |
| @@ -117,7 +117,7 @@ void LaunchMoonEPDispatchUdmaKernel( | |||
| 117 | #endif | 117 | #endif |
| 118 | } | 118 | } |
| 119 | 119 | ||
| 120 | -void LaunchMoonEPDispatchUdmaProfileKernel( | 120 | +void LaunchMoonEPDispatchUdmaLegacyProfileKernel( |
| 121 | torch::Tensor hidden_sh, | 121 | torch::Tensor hidden_sh, |
| 122 | torch::Tensor route_weights, | 122 | torch::Tensor route_weights, |
| 123 | torch::Tensor dst, | 123 | torch::Tensor dst, |
| @@ -158,7 +158,140 @@ void LaunchMoonEPDispatchUdmaProfileKernel( | |||
| 158 | #endif | 158 | #endif |
| 159 | } | 159 | } |
| 160 | 160 | ||
| 161 | -void LaunchPlanningKernel( | 161 | +void LaunchMoonEPDispatchUdmaServerDedupKernel( |
| 162 | + torch::Tensor hidden_sh, | ||
| 163 | + torch::Tensor route_weights, | ||
| 164 | + torch::Tensor dst, | ||
| 165 | + torch::Tensor dup_groups, | ||
| 166 | + torch::Tensor dup_loffs, | ||
| 167 | + torch::Tensor dup_counts, | ||
| 168 | + torch::Tensor hidden_buf, | ||
| 169 | + torch::Tensor route_weights_buf, | ||
| 170 | + torch::Tensor sync_buffer, | ||
| 171 | + const ascend_moonep::MoonEPDispatchTilingData& tiling, | ||
| 172 | + uint64_t magic) { | ||
| 173 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 174 | + aclrtStream stream = GetCurrentAclStream(); | ||
| 175 | + moonep_dispatch_udma_server_dedup_kernel_do( | ||
| 176 | + stream, | ||
| 177 | + BytePtr(hidden_sh.data_ptr()), | ||
| 178 | + BytePtr(route_weights.data_ptr()), | ||
| 179 | + BytePtr(dst.data_ptr()), | ||
| 180 | + BytePtr(dup_groups.data_ptr()), | ||
| 181 | + BytePtr(dup_loffs.data_ptr()), | ||
| 182 | + BytePtr(dup_counts.data_ptr()), | ||
| 183 | + BytePtr(hidden_buf.data_ptr()), | ||
| 184 | + BytePtr(route_weights_buf.data_ptr()), | ||
| 185 | + BytePtr(sync_buffer.data_ptr()), | ||
| 186 | + reinterpret_cast<uint8_t*>( | ||
| 187 | + const_cast<ascend_moonep::MoonEPDispatchTilingData*>(&tiling)), | ||
| 188 | + magic); | ||
| 189 | +#else | ||
| 190 | + (void)hidden_sh; (void)route_weights; (void)dst; (void)dup_groups; | ||
| 191 | + (void)dup_loffs; (void)dup_counts; (void)hidden_buf; (void)route_weights_buf; | ||
| 192 | + (void)sync_buffer; (void)tiling; (void)magic; | ||
| 193 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); | ||
| 194 | +#endif | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +void LaunchMoonEPDispatchUdmaServerDedupProfileKernel( | ||
| 198 | + torch::Tensor hidden_sh, | ||
| 199 | + torch::Tensor route_weights, | ||
| 200 | + torch::Tensor dst, | ||
| 201 | + torch::Tensor dup_groups, | ||
| 202 | + torch::Tensor dup_loffs, | ||
| 203 | + torch::Tensor dup_counts, | ||
| 204 | + torch::Tensor hidden_buf, | ||
| 205 | + torch::Tensor route_weights_buf, | ||
| 206 | + torch::Tensor sync_buffer, | ||
| 207 | + torch::Tensor profile_cycles, | ||
| 208 | + const ascend_moonep::MoonEPDispatchTilingData& tiling, | ||
| 209 | + uint64_t magic) { | ||
| 210 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 211 | + aclrtStream stream = GetCurrentAclStream(); | ||
| 212 | + moonep_dispatch_udma_server_dedup_profile_kernel_do( | ||
| 213 | + stream, | ||
| 214 | + BytePtr(hidden_sh.data_ptr()), | ||
| 215 | + BytePtr(route_weights.data_ptr()), | ||
| 216 | + BytePtr(dst.data_ptr()), | ||
| 217 | + BytePtr(dup_groups.data_ptr()), | ||
| 218 | + BytePtr(dup_loffs.data_ptr()), | ||
| 219 | + BytePtr(dup_counts.data_ptr()), | ||
| 220 | + BytePtr(hidden_buf.data_ptr()), | ||
| 221 | + BytePtr(route_weights_buf.data_ptr()), | ||
| 222 | + BytePtr(sync_buffer.data_ptr()), | ||
| 223 | + BytePtr(profile_cycles.data_ptr()), | ||
| 224 | + reinterpret_cast<uint8_t*>( | ||
| 225 | + const_cast<ascend_moonep::MoonEPDispatchTilingData*>(&tiling)), | ||
| 226 | + magic); | ||
| 227 | +#else | ||
| 228 | + (void)hidden_sh; (void)route_weights; (void)dst; (void)dup_groups; | ||
| 229 | + (void)dup_loffs; (void)dup_counts; (void)hidden_buf; (void)route_weights_buf; | ||
| 230 | + (void)sync_buffer; (void)profile_cycles; (void)tiling; (void)magic; | ||
| 231 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); | ||
| 232 | +#endif | ||
| 233 | +} | ||
| 234 | + | ||
| 235 | +void LaunchPlanningLegacyKernel( | ||
| 236 | + torch::Tensor topk_idx, | ||
| 237 | + torch::Tensor dst, | ||
| 238 | + torch::Tensor cu_seqlens, | ||
| 239 | + torch::Tensor experts_to_copy, | ||
| 240 | + torch::Tensor dup_groups, | ||
| 241 | + torch::Tensor dup_loffs, | ||
| 242 | + torch::Tensor dup_counts, | ||
| 243 | + torch::Tensor tpe_all, | ||
| 244 | + torch::Tensor tpe_prefix, | ||
| 245 | + torch::Tensor balance, | ||
| 246 | + torch::Tensor z_tensor, | ||
| 247 | + torch::Tensor alloc_tensor, | ||
| 248 | + torch::Tensor alloc_cumsum, | ||
| 249 | + torch::Tensor expert_offsets, | ||
| 250 | + torch::Tensor core_expert_counts, | ||
| 251 | + torch::Tensor dup_workspace, | ||
| 252 | + torch::Tensor dup_key_workspace, | ||
| 253 | + const ascend_moonep::PlanningTilingData& tiling, | ||
| 254 | + void* symmetric_buffer, | ||
| 255 | + uint64_t ffts_addr, | ||
| 256 | + uint32_t stripe_rank_placement) { | ||
| 257 | + TORCH_CHECK(symmetric_buffer != nullptr, | ||
| 258 | + "planning symmetric_buffer must not be null"); | ||
| 259 | + aclrtStream stream = GetCurrentAclStream(); | ||
| 260 | + const auto launch = [&](auto kernel, auto... extra_args) { | ||
| 261 | + kernel( | ||
| 262 | + stream, | ||
| 263 | + BytePtr(topk_idx.data_ptr()), | ||
| 264 | + BytePtr(symmetric_buffer), | ||
| 265 | + BytePtr(dst.data_ptr()), | ||
| 266 | + BytePtr(cu_seqlens.data_ptr()), | ||
| 267 | + BytePtr(experts_to_copy.data_ptr()), | ||
| 268 | + BytePtr(dup_groups.data_ptr()), | ||
| 269 | + BytePtr(dup_loffs.data_ptr()), | ||
| 270 | + BytePtr(dup_counts.data_ptr()), | ||
| 271 | + BytePtr(tpe_all.data_ptr()), | ||
| 272 | + BytePtr(tpe_prefix.data_ptr()), | ||
| 273 | + BytePtr(balance.data_ptr()), | ||
| 274 | + BytePtr(z_tensor.data_ptr()), | ||
| 275 | + BytePtr(alloc_tensor.data_ptr()), | ||
| 276 | + BytePtr(alloc_cumsum.data_ptr()), | ||
| 277 | + BytePtr(expert_offsets.data_ptr()), | ||
| 278 | + BytePtr(core_expert_counts.data_ptr()), | ||
| 279 | + BytePtr(dup_workspace.data_ptr()), | ||
| 280 | + BytePtr(dup_key_workspace.data_ptr()), | ||
| 281 | + reinterpret_cast<uint8_t*>( | ||
| 282 | + const_cast<ascend_moonep::PlanningTilingData*>(&tiling)), | ||
| 283 | + ffts_addr, | ||
| 284 | + extra_args...); | ||
| 285 | + }; | ||
| 286 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 287 | + launch(planning_kernel_do_with_rank_stripe, stripe_rank_placement); | ||
| 288 | +#else | ||
| 289 | + (void)stripe_rank_placement; | ||
| 290 | + launch(planning_kernel_do); | ||
| 291 | +#endif | ||
| 292 | +} | ||
| 293 | + | ||
| 294 | +void LaunchPlanningServerDedupKernel( | ||
| 162 | torch::Tensor topk_idx, | 295 | torch::Tensor topk_idx, |
| 163 | torch::Tensor dst, | 296 | torch::Tensor dst, |
| 164 | torch::Tensor cu_seqlens, | 297 | torch::Tensor cu_seqlens, |
| @@ -179,10 +312,11 @@ void LaunchPlanningKernel( | |||
| 179 | const ascend_moonep::PlanningTilingData& tiling, | 312 | const ascend_moonep::PlanningTilingData& tiling, |
| 180 | void* symmetric_buffer, | 313 | void* symmetric_buffer, |
| 181 | uint64_t ffts_addr) { | 314 | uint64_t ffts_addr) { |
| 315 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 182 | TORCH_CHECK(symmetric_buffer != nullptr, | 316 | TORCH_CHECK(symmetric_buffer != nullptr, |
| 183 | "planning symmetric_buffer must not be null"); | 317 | "planning symmetric_buffer must not be null"); |
| 184 | aclrtStream stream = GetCurrentAclStream(); | 318 | aclrtStream stream = GetCurrentAclStream(); |
| 185 | - planning_kernel_do( | 319 | + planning_server_dedup_kernel_do( |
| 186 | stream, | 320 | stream, |
| 187 | BytePtr(topk_idx.data_ptr()), | 321 | BytePtr(topk_idx.data_ptr()), |
| 188 | BytePtr(symmetric_buffer), | 322 | BytePtr(symmetric_buffer), |
| @@ -205,51 +339,78 @@ void LaunchPlanningKernel( | |||
| 205 | reinterpret_cast<uint8_t*>( | 339 | reinterpret_cast<uint8_t*>( |
| 206 | const_cast<ascend_moonep::PlanningTilingData*>(&tiling)), | 340 | const_cast<ascend_moonep::PlanningTilingData*>(&tiling)), |
| 207 | ffts_addr); | 341 | ffts_addr); |
| 208 | -} | ||
| 209 | - | ||
| 210 | -void LaunchMoonEPUdmaCombineKernel( | ||
| 211 | - torch::Tensor hidden_nvsh, | ||
| 212 | - torch::Tensor route_weights_nvs, | ||
| 213 | - torch::Tensor sync_buffer, | ||
| 214 | - torch::Tensor dst, | ||
| 215 | - torch::Tensor dup_groups, | ||
| 216 | - torch::Tensor dup_loffs, | ||
| 217 | - torch::Tensor dup_counts, | ||
| 218 | - torch::Tensor output_sh, | ||
| 219 | - torch::Tensor output_sk, | ||
| 220 | - void* bandwidth_scratch, | ||
| 221 | - const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | ||
| 222 | - void* local_workspace, | ||
| 223 | - uint64_t invocation_magic) { | ||
| 224 | -#if defined(ASCEND_MOONEP_UDMA) | ||
| 225 | - TORCH_CHECK(local_workspace != nullptr, "local_workspace must not be null"); | ||
| 226 | - TORCH_CHECK(bandwidth_scratch != nullptr, | ||
| 227 | - "bandwidth_scratch must not be null"); | ||
| 228 | - | ||
| 229 | - aclrtStream stream = GetCurrentAclStream(); | ||
| 230 | - moonep_udma_combine_kernel_do( | ||
| 231 | - stream, | ||
| 232 | - BytePtr(hidden_nvsh.data_ptr()), | ||
| 233 | - BytePtr(route_weights_nvs.data_ptr()), | ||
| 234 | - BytePtr(sync_buffer.data_ptr()), | ||
| 235 | - BytePtr(dst.data_ptr()), | ||
| 236 | - BytePtr(dup_groups.data_ptr()), | ||
| 237 | - BytePtr(dup_loffs.data_ptr()), | ||
| 238 | - BytePtr(dup_counts.data_ptr()), | ||
| 239 | - BytePtr(output_sh.data_ptr()), | ||
| 240 | - BytePtr(output_sk.data_ptr()), | ||
| 241 | - BytePtr(local_workspace), | ||
| 242 | - BytePtr(bandwidth_scratch), | ||
| 243 | - reinterpret_cast<uint8_t*>( | ||
| 244 | - const_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(&tiling)), | ||
| 245 | - invocation_magic); | ||
| 246 | #else | 342 | #else |
| 247 | - (void)hidden_nvsh; (void)route_weights_nvs; (void)sync_buffer; (void)dst; | 343 | + (void)topk_idx; (void)dst; (void)cu_seqlens; (void)experts_to_copy; |
| 248 | - (void)dup_groups; (void)dup_loffs; (void)dup_counts; (void)output_sh; | 344 | + (void)dup_groups; (void)dup_loffs; (void)dup_counts; (void)tpe_all; |
| 249 | - (void)output_sk; (void)bandwidth_scratch; (void)tiling; | 345 | + (void)tpe_prefix; (void)balance; (void)z_tensor; (void)alloc_tensor; |
| 250 | - (void)local_workspace; (void)invocation_magic; | 346 | + (void)alloc_cumsum; (void)expert_offsets; (void)core_expert_counts; (void)dup_workspace; |
| 251 | - TORCH_CHECK(false, | 347 | + (void)dup_key_workspace; (void)tiling; (void)symmetric_buffer; (void)ffts_addr; |
| 252 | - "combine UDMA kernel support is not enabled in this build; " | 348 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); |
| 253 | - "A2/A3 do not provide the UDMA combine kernel"); | 349 | +#endif |
| 350 | +} | ||
| 351 | + | ||
| 352 | +void LaunchMoonEPUdmaCombineServerDedupKernel( | ||
| 353 | + torch::Tensor hidden, torch::Tensor weights, torch::Tensor dst, | ||
| 354 | + torch::Tensor groups, torch::Tensor dups, torch::Tensor counts, | ||
| 355 | + torch::Tensor out, torch::Tensor outw, torch::Tensor workspace, | ||
| 356 | + torch::Tensor plan, | ||
| 357 | + const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | ||
| 358 | + uint64_t magic) { | ||
| 359 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 360 | + moonep_udma_combine_server_dedup_kernel_do( | ||
| 361 | + GetCurrentAclStream(), BytePtr(hidden.data_ptr()), BytePtr(weights.data_ptr()), | ||
| 362 | + BytePtr(dst.data_ptr()), BytePtr(groups.data_ptr()), BytePtr(dups.data_ptr()), | ||
| 363 | + BytePtr(counts.data_ptr()), BytePtr(out.data_ptr()), BytePtr(outw.data_ptr()), | ||
| 364 | + BytePtr(workspace.data_ptr()), BytePtr(plan.data_ptr()), | ||
| 365 | + reinterpret_cast<uint8_t*>(const_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(&tiling)), | ||
| 366 | + magic); | ||
| 367 | +#else | ||
| 368 | + (void)hidden; (void)weights; (void)dst; (void)groups; | ||
| 369 | + (void)dups; (void)counts; (void)out; (void)outw; | ||
| 370 | + (void)workspace; (void)plan; (void)tiling; (void)magic; | ||
| 371 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); | ||
| 372 | +#endif | ||
| 373 | +} | ||
| 374 | + | ||
| 375 | +void LaunchMoonEPUdmaCombineLegacyKernel( | ||
| 376 | + torch::Tensor hidden, torch::Tensor weights, torch::Tensor sync_buffer, | ||
| 377 | + torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, | ||
| 378 | + torch::Tensor counts, torch::Tensor out, torch::Tensor outw, | ||
| 379 | + void* bandwidth_scratch, void* local_workspace, | ||
| 380 | + const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | ||
| 381 | + uint64_t magic) { | ||
| 382 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 383 | + TORCH_CHECK(bandwidth_scratch != nullptr, | ||
| 384 | + "bandwidth_scratch must not be null"); | ||
| 385 | + TORCH_CHECK(local_workspace != nullptr, "local_workspace must not be null"); | ||
| 386 | + moonep_udma_combine_kernel_do( | ||
| 387 | + GetCurrentAclStream(), BytePtr(hidden.data_ptr()), BytePtr(weights.data_ptr()), | ||
| 388 | + BytePtr(sync_buffer.data_ptr()), | ||
| 389 | + BytePtr(dst.data_ptr()), BytePtr(groups.data_ptr()), BytePtr(dups.data_ptr()), | ||
| 390 | + BytePtr(counts.data_ptr()), BytePtr(out.data_ptr()), BytePtr(outw.data_ptr()), | ||
| 391 | + BytePtr(local_workspace), BytePtr(bandwidth_scratch), | ||
| 392 | + reinterpret_cast<uint8_t*>(const_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(&tiling)), | ||
| 393 | + magic); | ||
| 394 | +#else | ||
| 395 | + (void)hidden; (void)weights; (void)sync_buffer; (void)dst; | ||
| 396 | + (void)groups; (void)dups; (void)counts; (void)out; | ||
| 397 | + (void)outw; (void)bandwidth_scratch; (void)local_workspace; (void)tiling; | ||
| 398 | + (void)magic; | ||
| 399 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); | ||
| 400 | +#endif | ||
| 401 | +} | ||
| 402 | + | ||
| 403 | +void LaunchPlanningMetadataOnly( | ||
| 404 | + torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, torch::Tensor counts, | ||
| 405 | + const ascend_moonep::PlanningTilingData& tiling) { | ||
| 406 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 407 | + planning_server_dedup_kernel_do(GetCurrentAclStream(), nullptr, nullptr, BytePtr(dst.data_ptr()), | ||
| 408 | + nullptr, nullptr, BytePtr(groups.data_ptr()), BytePtr(dups.data_ptr()), BytePtr(counts.data_ptr()), | ||
| 409 | + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, | ||
| 410 | + reinterpret_cast<uint8_t*>(const_cast<ascend_moonep::PlanningTilingData*>(&tiling)), 0); | ||
| 411 | +#else | ||
| 412 | + (void)dst; (void)groups; (void)dups; (void)counts; | ||
| 413 | + (void)tiling; | ||
| 414 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); | ||
| 254 | #endif | 415 | #endif |
| 255 | } | 416 | } |
| @@ -31,7 +31,7 @@ void LaunchMoonEPDispatchKernel( | |||
| 31 | torch::Tensor route_weights_buf, | 31 | torch::Tensor route_weights_buf, |
| 32 | const ascend_moonep::MoonEPDispatchTilingData& tiling); | 32 | const ascend_moonep::MoonEPDispatchTilingData& tiling); |
| 33 | 33 | ||
| 34 | -void LaunchMoonEPDispatchUdmaKernel( | 34 | +void LaunchMoonEPDispatchUdmaLegacyKernel( |
| 35 | torch::Tensor hidden_sh, | 35 | torch::Tensor hidden_sh, |
| 36 | torch::Tensor route_weights, | 36 | torch::Tensor route_weights, |
| 37 | torch::Tensor dst, | 37 | torch::Tensor dst, |
| @@ -44,7 +44,7 @@ void LaunchMoonEPDispatchUdmaKernel( | |||
| 44 | const ascend_moonep::MoonEPDispatchTilingData& tiling, | 44 | const ascend_moonep::MoonEPDispatchTilingData& tiling, |
| 45 | uint64_t magic); | 45 | uint64_t magic); |
| 46 | 46 | ||
| 47 | -void LaunchMoonEPDispatchUdmaProfileKernel( | 47 | +void LaunchMoonEPDispatchUdmaLegacyProfileKernel( |
| 48 | torch::Tensor hidden_sh, | 48 | torch::Tensor hidden_sh, |
| 49 | torch::Tensor route_weights, | 49 | torch::Tensor route_weights, |
| 50 | torch::Tensor dst, | 50 | torch::Tensor dst, |
| @@ -58,7 +58,59 @@ void LaunchMoonEPDispatchUdmaProfileKernel( | |||
| 58 | const ascend_moonep::MoonEPDispatchTilingData& tiling, | 58 | const ascend_moonep::MoonEPDispatchTilingData& tiling, |
| 59 | uint64_t magic); | 59 | uint64_t magic); |
| 60 | 60 | ||
| 61 | -void LaunchPlanningKernel( | 61 | +void LaunchMoonEPDispatchUdmaServerDedupKernel( |
| 62 | + torch::Tensor hidden_sh, | ||
| 63 | + torch::Tensor route_weights, | ||
| 64 | + torch::Tensor dst, | ||
| 65 | + torch::Tensor dup_groups, | ||
| 66 | + torch::Tensor dup_loffs, | ||
| 67 | + torch::Tensor dup_counts, | ||
| 68 | + torch::Tensor hidden_buf, | ||
| 69 | + torch::Tensor route_weights_buf, | ||
| 70 | + torch::Tensor sync_buffer, | ||
| 71 | + const ascend_moonep::MoonEPDispatchTilingData& tiling, | ||
| 72 | + uint64_t magic); | ||
| 73 | + | ||
| 74 | +void LaunchMoonEPDispatchUdmaServerDedupProfileKernel( | ||
| 75 | + torch::Tensor hidden_sh, | ||
| 76 | + torch::Tensor route_weights, | ||
| 77 | + torch::Tensor dst, | ||
| 78 | + torch::Tensor dup_groups, | ||
| 79 | + torch::Tensor dup_loffs, | ||
| 80 | + torch::Tensor dup_counts, | ||
| 81 | + torch::Tensor hidden_buf, | ||
| 82 | + torch::Tensor route_weights_buf, | ||
| 83 | + torch::Tensor sync_buffer, | ||
| 84 | + torch::Tensor profile_cycles, | ||
| 85 | + const ascend_moonep::MoonEPDispatchTilingData& tiling, | ||
| 86 | + uint64_t magic); | ||
| 87 | + | ||
| 88 | +// Legacy rank-level dedup planner (writes routing + rank dedup tables only). | ||
| 89 | +void LaunchPlanningLegacyKernel( | ||
| 90 | + torch::Tensor topk_idx, | ||
| 91 | + torch::Tensor dst, | ||
| 92 | + torch::Tensor cu_seqlens, | ||
| 93 | + torch::Tensor experts_to_copy, | ||
| 94 | + torch::Tensor dup_groups, | ||
| 95 | + torch::Tensor dup_loffs, | ||
| 96 | + torch::Tensor dup_counts, | ||
| 97 | + torch::Tensor tpe_all, | ||
| 98 | + torch::Tensor tpe_prefix, | ||
| 99 | + torch::Tensor balance, | ||
| 100 | + torch::Tensor z_tensor, | ||
| 101 | + torch::Tensor alloc_tensor, | ||
| 102 | + torch::Tensor alloc_cumsum, | ||
| 103 | + torch::Tensor expert_offsets, | ||
| 104 | + torch::Tensor core_expert_counts, | ||
| 105 | + torch::Tensor dup_workspace, | ||
| 106 | + torch::Tensor dup_key_workspace, | ||
| 107 | + const ascend_moonep::PlanningTilingData& tiling, | ||
| 108 | + void* symmetric_buffer, | ||
| 109 | + uint64_t ffts_addr, | ||
| 110 | + uint32_t stripe_rank_placement); | ||
| 111 | + | ||
| 112 | +// Server-level dedup planner (routing + server dedup tables + combine plan). | ||
| 113 | +void LaunchPlanningServerDedupKernel( | ||
| 62 | torch::Tensor topk_idx, | 114 | torch::Tensor topk_idx, |
| 63 | torch::Tensor dst, | 115 | torch::Tensor dst, |
| 64 | torch::Tensor cu_seqlens, | 116 | torch::Tensor cu_seqlens, |
| @@ -80,17 +132,24 @@ void LaunchPlanningKernel( | |||
| 80 | void* symmetric_buffer, | 132 | void* symmetric_buffer, |
| 81 | uint64_t ffts_addr); | 133 | uint64_t ffts_addr); |
| 82 | 134 | ||
| 83 | -void LaunchMoonEPUdmaCombineKernel( | 135 | +void LaunchMoonEPUdmaCombineServerDedupKernel( |
| 84 | - torch::Tensor hidden_nvsh, | 136 | + torch::Tensor hidden, torch::Tensor weights, torch::Tensor dst, |
| 85 | - torch::Tensor route_weights_nvs, | 137 | + torch::Tensor groups, torch::Tensor dups, torch::Tensor counts, |
| 86 | - torch::Tensor sync_buffer, | 138 | + torch::Tensor out, torch::Tensor outw, torch::Tensor workspace, |
| 87 | - torch::Tensor dst, | 139 | + torch::Tensor plan, |
| 88 | - torch::Tensor dup_groups, | ||
| 89 | - torch::Tensor dup_loffs, | ||
| 90 | - torch::Tensor dup_counts, | ||
| 91 | - torch::Tensor output_sh, | ||
| 92 | - torch::Tensor output_sk, | ||
| 93 | - void* bandwidth_scratch, | ||
| 94 | const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | 140 | const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, |
| 95 | - void* local_workspace, | 141 | + uint64_t magic); |
| 96 | - uint64_t invocation_magic); | 142 | + |
| 143 | +// Legacy rank-level dedup combine: workspace and its bandwidth scratch tail are | ||
| 144 | +// rank-local host tensors, not the symmetric PUT workspace. | ||
| 145 | +void LaunchMoonEPUdmaCombineLegacyKernel( | ||
| 146 | + torch::Tensor hidden, torch::Tensor weights, torch::Tensor sync_buffer, | ||
| 147 | + torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, | ||
| 148 | + torch::Tensor counts, torch::Tensor out, torch::Tensor outw, | ||
| 149 | + void* bandwidth_scratch, void* local_workspace, | ||
| 150 | + const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | ||
| 151 | + uint64_t magic); | ||
| 152 | + | ||
| 153 | +void LaunchPlanningMetadataOnly( | ||
| 154 | + torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, torch::Tensor counts, | ||
| 155 | + const ascend_moonep::PlanningTilingData& tiling); | ||
| @@ -48,7 +48,8 @@ void MoonEPUdmaCombine( | |||
| 48 | int64_t K, | 48 | int64_t K, |
| 49 | int64_t R, | 49 | int64_t R, |
| 50 | int64_t rank, | 50 | int64_t rank, |
| 51 | - torch::Tensor local_workspace) { | 51 | + torch::Tensor local_workspace, |
| 52 | + c10::optional<torch::Tensor> execution_plan) { | ||
| 52 | 53 | ||
| 53 | CheckNpuContiguous(hidden_nvsh, "hidden_nvsh"); | 54 | CheckNpuContiguous(hidden_nvsh, "hidden_nvsh"); |
| 54 | CheckNpuContiguous(sync_buffer, "sync_buffer"); | 55 | CheckNpuContiguous(sync_buffer, "sync_buffer"); |
| @@ -61,19 +62,23 @@ void MoonEPUdmaCombine( | |||
| 61 | "S/H/K/R must be positive"); | 62 | "S/H/K/R must be positive"); |
| 62 | TORCH_CHECK(rank >= 0 && rank < R, "rank must be in [0, R)"); | 63 | TORCH_CHECK(rank >= 0 && rank < R, "rank must be in [0, R)"); |
| 63 | TORCH_CHECK(K <= 16, "K must be <= 16"); | 64 | TORCH_CHECK(K <= 16, "K must be <= 16"); |
| 65 | + constexpr int64_t kSmallWorldGroupWidth = 8; | ||
| 66 | + constexpr int64_t kTwoFrameWorldSize = 128; | ||
| 64 | constexpr int64_t kMaxGroupWidth = 16; | 67 | constexpr int64_t kMaxGroupWidth = 16; |
| 65 | TORCH_CHECK( | 68 | TORCH_CHECK( |
| 66 | R == 1 || | 69 | R == 1 || |
| 67 | (R % 2 == 0 && | 70 | (R % 2 == 0 && |
| 68 | - (R <= kMaxGroupWidth || R % kMaxGroupWidth == 0)), | 71 | + ((R < kTwoFrameWorldSize && |
| 69 | - "grouped MoonEP UDMA combine requires R=1, an even R<=16, " | 72 | + (R <= kSmallWorldGroupWidth || |
| 70 | - "or an R divisible by 16"); | 73 | + R % kSmallWorldGroupWidth == 0)) || |
| 71 | - constexpr int64_t kHiddenUbBytes = 128 * 1024; | 74 | + (R >= kTwoFrameWorldSize && R % kMaxGroupWidth == 0))), |
| 72 | - constexpr int64_t kFullRowDbBytesPerElement = 16; | 75 | + "grouped MoonEP UDMA combine requires R=1, an even R<=8, " |
| 76 | + "an R<128 divisible by 8, or an R>=128 divisible by 16"); | ||
| 77 | + constexpr uint64_t kMaxTokenBytes = 8ULL * 1024ULL * 1024ULL; | ||
| 73 | TORCH_CHECK( | 78 | TORCH_CHECK( |
| 74 | - H <= kHiddenUbBytes / kFullRowDbBytesPerElement, | 79 | + static_cast<uint64_t>(H) <= |
| 75 | - "MoonEP UDMA combine requires H<=8192 so its full-row " | 80 | + kMaxTokenBytes / sizeof(c10::BFloat16), |
| 76 | - "double buffer fits in 128 KiB of UB"); | 81 | + "MoonEP UDMA combine requires one bf16 token row to be <=8 MiB"); |
| 77 | TORCH_CHECK(static_cast<uint64_t>(S) <= std::numeric_limits<uint32_t>::max() && | 82 | TORCH_CHECK(static_cast<uint64_t>(S) <= std::numeric_limits<uint32_t>::max() && |
| 78 | static_cast<uint64_t>(H) <= std::numeric_limits<uint32_t>::max() && | 83 | static_cast<uint64_t>(H) <= std::numeric_limits<uint32_t>::max() && |
| 79 | static_cast<uint64_t>(K) <= std::numeric_limits<uint32_t>::max() && | 84 | static_cast<uint64_t>(K) <= std::numeric_limits<uint32_t>::max() && |
| @@ -85,8 +90,10 @@ void MoonEPUdmaCombine( | |||
| 85 | "S*K must fit in uint32"); | 90 | "S*K must fit in uint32"); |
| 86 | TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max() / 3, | 91 | TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max() / 3, |
| 87 | "S*K is too large for dup_groups indexing"); | 92 | "S*K is too large for dup_groups indexing"); |
| 88 | - TORCH_CHECK(static_cast<uint64_t>(R) * num_output_slots_u64 < (1ull << 31), | 93 | + TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max() / 8, |
| 89 | - "MoonEP combine requires R*NvS to fit in positive int32 encoding"); | 94 | + "S*K is too large for contiguous 8*N contributor scratch indexing"); |
| 95 | + TORCH_CHECK(static_cast<uint64_t>(R) * num_output_slots_u64 < (1ull << 30), | ||
| 96 | + "PUT combine requires R*NvS < 2^30 for disjoint route tags"); | ||
| 90 | const int64_t NvS = static_cast<int64_t>(num_output_slots_u64); | 97 | const int64_t NvS = static_cast<int64_t>(num_output_slots_u64); |
| 91 | 98 | ||
| 92 | TORCH_CHECK(hidden_nvsh.dim() == 2, "hidden_nvsh must be [NvS, H]"); | 99 | TORCH_CHECK(hidden_nvsh.dim() == 2, "hidden_nvsh must be [NvS, H]"); |
| @@ -98,9 +105,13 @@ void MoonEPUdmaCombine( | |||
| 98 | CheckSameDevice(sync_buffer, hidden_nvsh, "sync_buffer"); | 105 | CheckSameDevice(sync_buffer, hidden_nvsh, "sync_buffer"); |
| 99 | TORCH_CHECK(sync_buffer.scalar_type() == torch::kUInt8, | 106 | TORCH_CHECK(sync_buffer.scalar_type() == torch::kUInt8, |
| 100 | "sync_buffer must be uint8"); | 107 | "sync_buffer must be uint8"); |
| 101 | - constexpr uint64_t kGroupSyncBytesPerRank = 16ULL * 2ULL * 512ULL; | 108 | + constexpr uint64_t kGroupSignalBytesPerRank = 16ULL * 6ULL * 512ULL; |
| 109 | + constexpr uint64_t kLocalAivSyncBytes = 16ULL * 4ULL * 512ULL; | ||
| 110 | + const uint64_t required_sync_bytes = | ||
| 111 | + static_cast<uint64_t>(R) * kGroupSignalBytesPerRank + | ||
| 112 | + kLocalAivSyncBytes; | ||
| 102 | TORCH_CHECK(static_cast<uint64_t>(sync_buffer.numel()) >= | 113 | TORCH_CHECK(static_cast<uint64_t>(sync_buffer.numel()) >= |
| 103 | - static_cast<uint64_t>(R) * kGroupSyncBytesPerRank, | 114 | + required_sync_bytes, |
| 104 | "sync_buffer is too small for grouped combine"); | 115 | "sync_buffer is too small for grouped combine"); |
| 105 | CheckSameDevice(dup_groups, hidden_nvsh, "dup_groups"); | 116 | CheckSameDevice(dup_groups, hidden_nvsh, "dup_groups"); |
| 106 | CheckSameDevice(dup_loffs, hidden_nvsh, "dup_loffs"); | 117 | CheckSameDevice(dup_loffs, hidden_nvsh, "dup_loffs"); |
| @@ -137,12 +148,29 @@ void MoonEPUdmaCombine( | |||
| 137 | dup_groups.dim() == 2 && | 148 | dup_groups.dim() == 2 && |
| 138 | dup_groups.size(0) == NvS && dup_groups.size(1) == 3, | 149 | dup_groups.size(0) == NvS && dup_groups.size(1) == 3, |
| 139 | "dup_groups must be int32 [NvS, 3]"); | 150 | "dup_groups must be int32 [NvS, 3]"); |
| 151 | + // Server plans store full rank*NvS+loff addresses for same-server | ||
| 152 | + // secondaries. Preserve the compact rank-plan format alongside them. | ||
| 153 | + const bool server_dedup = | ||
| 154 | + dup_counts.dim() == 1 && dup_counts.size(0) == R + 2; | ||
| 155 | + TORCH_CHECK(!server_dedup || R % kMoonEPDispatchRanksPerServer == 0, | ||
| 156 | + "server dedup combine requires R divisible by 8"); | ||
| 157 | + TORCH_CHECK( | ||
| 158 | + !server_dedup || num_output_slots_u64 <= kMoonEPServerDupRouteLimit, | ||
| 159 | + "server dedup source route exceeds packed route capacity"); | ||
| 160 | + TORCH_CHECK( | ||
| 161 | + !server_dedup || | ||
| 162 | + static_cast<uint64_t>(R) * num_output_slots_u64 < (1ULL << 30), | ||
| 163 | + "server dedup requires R*NvS < 2^30 for streamed-primary dst encoding"); | ||
| 164 | + const int64_t dup_capacity = server_dedup | ||
| 165 | + ? kMoonEPDispatchRanksPerServer * NvS : NvS; | ||
| 140 | TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 && | 166 | TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 && |
| 141 | - dup_loffs.dim() == 1 && dup_loffs.size(0) == NvS, | 167 | + dup_loffs.dim() == 1 && dup_loffs.size(0) == dup_capacity, |
| 142 | - "dup_loffs must be int32 [NvS]"); | 168 | + "dup_loffs must be int32 [", dup_capacity, |
| 169 | + "] for the selected dedup format"); | ||
| 143 | TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 && | 170 | TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 && |
| 144 | - dup_counts.dim() == 1 && dup_counts.size(0) == 2, | 171 | + dup_counts.dim() == 1 && |
| 145 | - "dup_counts must be int32 [2]"); | 172 | + dup_counts.size(0) == (server_dedup ? R + 2 : 2), |
| 173 | + "dup_counts must be int32 [2] or [R+2]"); | ||
| 146 | TORCH_CHECK(H % 8 == 0, "H must be multiple of 8"); | 174 | TORCH_CHECK(H % 8 == 0, "H must be multiple of 8"); |
| 147 | CheckNpuContiguous(local_workspace, "local_workspace"); | 175 | CheckNpuContiguous(local_workspace, "local_workspace"); |
| 148 | CheckSameDevice(local_workspace, hidden_nvsh, "local_workspace"); | 176 | CheckSameDevice(local_workspace, hidden_nvsh, "local_workspace"); |
| @@ -155,38 +183,27 @@ void MoonEPUdmaCombine( | |||
| 155 | "MoonEP UDMA combine hidden workspace size overflows uint64_t"); | 183 | "MoonEP UDMA combine hidden workspace size overflows uint64_t"); |
| 156 | const uint64_t hidden_bytes = | 184 | const uint64_t hidden_bytes = |
| 157 | num_output_slots_u64 * static_cast<uint64_t>(H) * sizeof(c10::BFloat16); | 185 | num_output_slots_u64 * static_cast<uint64_t>(H) * sizeof(c10::BFloat16); |
| 158 | - const uint64_t weight_regions = static_cast<uint64_t>(R); | 186 | + const uint64_t ready_bytes = |
| 187 | + num_output_slots_u64 * sizeof(uint64_t); | ||
| 188 | + const uint64_t scratch_bytes = | ||
| 189 | + static_cast<uint64_t>(kCombinePutCores) * | ||
| 190 | + kMoonEPUdmaCombineScratchTilesPerAiv * | ||
| 191 | + kMoonEPUdmaCombineScratchTileElements * sizeof(c10::BFloat16); | ||
| 159 | TORCH_CHECK( | 192 | TORCH_CHECK( |
| 160 | - num_output_slots_u64 <= | 193 | + hidden_bytes <= std::numeric_limits<uint64_t>::max() - ready_bytes && |
| 161 | - std::numeric_limits<uint64_t>::max() / | 194 | + hidden_bytes + ready_bytes <= |
| 162 | - weight_regions / sizeof(float), | 195 | + std::numeric_limits<uint64_t>::max() - scratch_bytes, |
| 163 | - "MoonEP UDMA combine gathered weight workspace size overflows uint64_t"); | ||
| 164 | - const uint64_t weight_bytes = | ||
| 165 | - weight_regions * num_output_slots_u64 * sizeof(float); | ||
| 166 | - TORCH_CHECK( | ||
| 167 | - hidden_bytes <= | ||
| 168 | - std::numeric_limits<uint64_t>::max() - weight_bytes, | ||
| 169 | "MoonEP UDMA combine workspace size overflows uint64_t"); | 196 | "MoonEP UDMA combine workspace size overflows uint64_t"); |
| 170 | - const uint64_t bandwidth_alignment = | 197 | + TORCH_CHECK(hidden_bytes <= (std::numeric_limits<uint64_t>::max() / 16U), |
| 171 | - ascend_moonep::kMoonEPUdmaCombineBandwidthScratchAlign; | 198 | + "PUT combine workspace payload size overflows uint64_t"); |
| 172 | - TORCH_CHECK( | 199 | + const uint64_t required_workspace_bytes = MakeCombinePutLayout( |
| 173 | - hidden_bytes + weight_bytes <= | 200 | + static_cast<uint32_t>(NvS), static_cast<uint32_t>(H), |
| 174 | - std::numeric_limits<uint64_t>::max() - (bandwidth_alignment - 1), | 201 | + static_cast<uint32_t>(R), static_cast<uint32_t>(K)).bytes; |
| 175 | - "MoonEP UDMA combine workspace alignment overflows uint64_t"); | ||
| 176 | - const uint64_t bandwidth_offset = | ||
| 177 | - (hidden_bytes + weight_bytes + bandwidth_alignment - 1) & | ||
| 178 | - ~(bandwidth_alignment - 1); | ||
| 179 | - TORCH_CHECK( | ||
| 180 | - bandwidth_offset <= std::numeric_limits<uint64_t>::max() - | ||
| 181 | - ascend_moonep::kMoonEPUdmaCombineBandwidthScratchBytes, | ||
| 182 | - "MoonEP UDMA combine bandwidth scratch size overflows uint64_t"); | ||
| 183 | - const uint64_t required_workspace_bytes = bandwidth_offset + | ||
| 184 | - ascend_moonep::kMoonEPUdmaCombineBandwidthScratchBytes; | ||
| 185 | const uint64_t local_workspace_bytes = | 202 | const uint64_t local_workspace_bytes = |
| 186 | static_cast<uint64_t>(local_workspace.numel()) * | 203 | static_cast<uint64_t>(local_workspace.numel()) * |
| 187 | static_cast<uint64_t>(local_workspace.element_size()); | 204 | static_cast<uint64_t>(local_workspace.element_size()); |
| 188 | TORCH_CHECK(required_workspace_bytes <= local_workspace_bytes, | 205 | TORCH_CHECK(required_workspace_bytes <= local_workspace_bytes, |
| 189 | - "local workspace is too small: need ", | 206 | + "combine workspace is too small: need ", |
| 190 | required_workspace_bytes, " bytes, got ", | 207 | required_workspace_bytes, " bytes, got ", |
| 191 | local_workspace_bytes, " bytes"); | 208 | local_workspace_bytes, " bytes"); |
| 192 | 209 | ||
| @@ -202,17 +219,206 @@ void MoonEPUdmaCombine( | |||
| 202 | tiling.R = static_cast<uint32_t>(R); | 219 | tiling.R = static_cast<uint32_t>(R); |
| 203 | tiling.rank = static_cast<uint32_t>(rank); | 220 | tiling.rank = static_cast<uint32_t>(rank); |
| 204 | tiling.with_weights = with_weights ? 1u : 0u; | 221 | tiling.with_weights = with_weights ? 1u : 0u; |
| 205 | - tiling.reserved = 0; | 222 | + tiling.server_dedup = server_dedup ? 1u : 0u; |
| 206 | 223 | ||
| 207 | - auto* workspace_ptr = static_cast<uint8_t*>(local_workspace.data_ptr()); | 224 | + TORCH_CHECK(execution_plan.has_value(), "UDMA combine requires the execution plan generated by PlanningOp"); |
| 225 | + if (execution_plan.has_value()) { | ||
| 226 | + CheckNpuContiguous(*execution_plan, "execution_plan"); | ||
| 227 | + CheckSameDevice(*execution_plan, hidden_nvsh, "execution_plan"); | ||
| 228 | + const auto required = MakeCombineExecutionPlanLayout(NvS, R).bytes; | ||
| 229 | + TORCH_CHECK(execution_plan->scalar_type() == torch::kUInt8 && | ||
| 230 | + execution_plan->dim() == 1 && | ||
| 231 | + static_cast<uint64_t>(execution_plan->numel()) == required, | ||
| 232 | + "execution_plan has wrong dtype/shape/layout"); | ||
| 233 | + TORCH_CHECK(!execution_plan->is_alias_of(local_workspace) && | ||
| 234 | + !execution_plan->is_alias_of(hidden_nvsh) && | ||
| 235 | + !execution_plan->is_alias_of(output_sh), | ||
| 236 | + "execution_plan must not alias mutable workspace/input/output"); | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + | ||
| 240 | + LaunchMoonEPUdmaCombineServerDedupKernel( | ||
| 241 | + hidden_nvsh, route_weights_arg, dst, dup_groups, dup_loffs, dup_counts, | ||
| 242 | + output_sh, output_sk_arg, local_workspace, *execution_plan, | ||
| 243 | + tiling, NextCombineMagic()); | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +namespace { | ||
| 247 | + | ||
| 248 | +// The legacy rank-level combined op mirrors the workspace ABI of the frozen | ||
| 249 | +// 2802271 kernel: gathered payload for the hidden rows, then one fp32 weight | ||
| 250 | +// region per source rank, then a bandwidth-diagnostics tail. These constants | ||
| 251 | +// are intentionally local so the server-dedup PUT layout stays independent. | ||
| 252 | +constexpr uint64_t kLegacyCombineBandwidthScratchAlign = 64; | ||
| 253 | +constexpr uint64_t kLegacyCombineBandwidthScratchBytes = | ||
| 254 | + uint64_t{32} * 8 * sizeof(int64_t); // 32 AIVs, 8 int64 counters each | ||
| 255 | + | ||
| 256 | +} // namespace | ||
| 257 | + | ||
| 258 | +void MoonEPUdmaCombineLegacy( | ||
| 259 | + torch::Tensor hidden_nvsh, | ||
| 260 | + c10::optional<torch::Tensor> route_weights_nvs, | ||
| 261 | + torch::Tensor sync_buffer, | ||
| 262 | + torch::Tensor dst, | ||
| 263 | + torch::Tensor dup_groups, | ||
| 264 | + torch::Tensor dup_loffs, | ||
| 265 | + torch::Tensor dup_counts, | ||
| 266 | + torch::Tensor output_sh, | ||
| 267 | + c10::optional<torch::Tensor> output_sk, | ||
| 268 | + int64_t S, | ||
| 269 | + int64_t H, | ||
| 270 | + int64_t K, | ||
| 271 | + int64_t R, | ||
| 272 | + int64_t rank, | ||
| 273 | + torch::Tensor workspace) { | ||
| 274 | + | ||
| 275 | + CheckNpuContiguous(hidden_nvsh, "hidden_nvsh"); | ||
| 276 | + CheckNpuContiguous(sync_buffer, "sync_buffer"); | ||
| 277 | + CheckNpuContiguous(dst, "dst"); | ||
| 278 | + CheckNpuContiguous(dup_groups, "dup_groups"); | ||
| 279 | + CheckNpuContiguous(dup_loffs, "dup_loffs"); | ||
| 280 | + CheckNpuContiguous(dup_counts, "dup_counts"); | ||
| 281 | + | ||
| 282 | + TORCH_CHECK(S > 0 && H > 0 && K > 0 && R > 0, | ||
| 283 | + "S/H/K/R must be positive"); | ||
| 284 | + TORCH_CHECK(rank >= 0 && rank < R, "rank must be in [0, R)"); | ||
| 285 | + TORCH_CHECK(K <= 16, "K must be <= 16"); | ||
| 286 | + constexpr int64_t kMaxGroupWidth = 16; | ||
| 287 | + TORCH_CHECK( | ||
| 288 | + R == 1 || | ||
| 289 | + (R % 2 == 0 && (R <= kMaxGroupWidth || R % kMaxGroupWidth == 0)), | ||
| 290 | + "grouped MoonEP UDMA combine requires R=1, an even R<=16, " | ||
| 291 | + "or an R divisible by 16"); | ||
| 292 | + constexpr int64_t kHiddenUbBytes = 128 * 1024; | ||
| 293 | + constexpr int64_t kFullRowDbBytesPerElement = 16; | ||
| 294 | + TORCH_CHECK( | ||
| 295 | + H <= kHiddenUbBytes / kFullRowDbBytesPerElement, | ||
| 296 | + "MoonEP UDMA combine requires H<=8192 so its full-row " | ||
| 297 | + "double buffer fits in 128 KiB of UB"); | ||
| 298 | + TORCH_CHECK(static_cast<uint64_t>(S) <= std::numeric_limits<uint32_t>::max() && | ||
| 299 | + static_cast<uint64_t>(H) <= std::numeric_limits<uint32_t>::max() && | ||
| 300 | + static_cast<uint64_t>(K) <= std::numeric_limits<uint32_t>::max() && | ||
| 301 | + static_cast<uint64_t>(R) <= std::numeric_limits<uint32_t>::max(), | ||
| 302 | + "S/H/K/R must fit in uint32 tiling fields"); | ||
| 303 | + const uint64_t num_output_slots_u64 = | ||
| 304 | + static_cast<uint64_t>(S) * static_cast<uint64_t>(K); | ||
| 305 | + TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max(), | ||
| 306 | + "S*K must fit in uint32"); | ||
| 307 | + TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max() / 3, | ||
| 308 | + "S*K is too large for dup_groups indexing"); | ||
| 309 | + TORCH_CHECK(static_cast<uint64_t>(R) * num_output_slots_u64 < (1ull << 31), | ||
| 310 | + "MoonEP combine requires R*NvS to fit in positive int32 encoding"); | ||
| 311 | + const int64_t NvS = static_cast<int64_t>(num_output_slots_u64); | ||
| 312 | + | ||
| 313 | + TORCH_CHECK(hidden_nvsh.dim() == 2, "hidden_nvsh must be [NvS, H]"); | ||
| 314 | + TORCH_CHECK(hidden_nvsh.scalar_type() == torch::kBFloat16, | ||
| 315 | + "hidden_nvsh must be bf16"); | ||
| 316 | + TORCH_CHECK(hidden_nvsh.size(0) == NvS && hidden_nvsh.size(1) == H, | ||
| 317 | + "hidden_nvsh shape mismatch"); | ||
| 318 | + CheckSameDevice(dst, hidden_nvsh, "dst"); | ||
| 319 | + CheckSameDevice(sync_buffer, hidden_nvsh, "sync_buffer"); | ||
| 320 | + TORCH_CHECK(sync_buffer.scalar_type() == torch::kUInt8, | ||
| 321 | + "sync_buffer must be uint8"); | ||
| 322 | + // The legacy kernel indexes 16x2 512-byte slots per rank; the Buffer's | ||
| 323 | + // group grant/done pool is a superset of that. | ||
| 324 | + constexpr uint64_t kLegacyGroupSyncBytesPerRank = 16ULL * 2ULL * 512ULL; | ||
| 325 | + TORCH_CHECK(static_cast<uint64_t>(sync_buffer.numel()) >= | ||
| 326 | + static_cast<uint64_t>(R) * kLegacyGroupSyncBytesPerRank, | ||
| 327 | + "sync_buffer is too small for the rank-level combine"); | ||
| 328 | + CheckSameDevice(dup_groups, hidden_nvsh, "dup_groups"); | ||
| 329 | + CheckSameDevice(dup_loffs, hidden_nvsh, "dup_loffs"); | ||
| 330 | + CheckSameDevice(dup_counts, hidden_nvsh, "dup_counts"); | ||
| 331 | + CheckNpuContiguous(output_sh, "output_sh"); | ||
| 332 | + CheckSameDevice(output_sh, hidden_nvsh, "output_sh"); | ||
| 333 | + TORCH_CHECK(output_sh.scalar_type() == torch::kBFloat16 && | ||
| 334 | + output_sh.dim() == 2 && | ||
| 335 | + output_sh.size(0) == S && output_sh.size(1) == H, | ||
| 336 | + "output_sh must be bf16 [S, H]"); | ||
| 337 | + | ||
| 338 | + const bool with_weights = route_weights_nvs.has_value(); | ||
| 339 | + TORCH_CHECK(output_sk.has_value() == with_weights, | ||
| 340 | + "output_sk must be provided exactly when route_weights_nvs is provided"); | ||
| 341 | + if (with_weights) { | ||
| 342 | + CheckNpuContiguous(*route_weights_nvs, "route_weights_nvs"); | ||
| 343 | + CheckSameDevice(*route_weights_nvs, hidden_nvsh, "route_weights_nvs"); | ||
| 344 | + TORCH_CHECK(route_weights_nvs->scalar_type() == torch::kFloat32, | ||
| 345 | + "route_weights_nvs must be fp32 when with_weights is true"); | ||
| 346 | + TORCH_CHECK(route_weights_nvs->dim() == 1 && | ||
| 347 | + route_weights_nvs->size(0) == NvS, | ||
| 348 | + "route_weights_nvs shape mismatch"); | ||
| 349 | + CheckNpuContiguous(*output_sk, "output_sk"); | ||
| 350 | + CheckSameDevice(*output_sk, hidden_nvsh, "output_sk"); | ||
| 351 | + TORCH_CHECK(output_sk->scalar_type() == torch::kFloat32 && | ||
| 352 | + output_sk->dim() == 2 && | ||
| 353 | + output_sk->size(0) == S && output_sk->size(1) == K, | ||
| 354 | + "output_sk must be fp32 [S, K]"); | ||
| 355 | + } | ||
| 356 | + TORCH_CHECK(dst.scalar_type() == torch::kInt32, "dst must be int32"); | ||
| 357 | + TORCH_CHECK(dst.dim() == 1 && dst.size(0) == NvS, "dst must be int32 [S*K]"); | ||
| 358 | + TORCH_CHECK(dup_groups.scalar_type() == torch::kInt32 && | ||
| 359 | + dup_groups.dim() == 2 && | ||
| 360 | + dup_groups.size(0) == NvS && dup_groups.size(1) == 3, | ||
| 361 | + "dup_groups must be int32 [NvS, 3]"); | ||
| 362 | + TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 && | ||
| 363 | + dup_loffs.dim() == 1 && dup_loffs.size(0) == NvS, | ||
| 364 | + "dup_loffs must be int32 [NvS]"); | ||
| 365 | + TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 && | ||
| 366 | + dup_counts.dim() == 1 && dup_counts.size(0) == 2, | ||
| 367 | + "dup_counts must be int32 [2]"); | ||
| 368 | + TORCH_CHECK(H % 8 == 0, "H must be multiple of 8"); | ||
| 369 | + | ||
| 370 | + CheckNpuContiguous(workspace, "local_workspace"); | ||
| 371 | + CheckSameDevice(workspace, hidden_nvsh, "local_workspace"); | ||
| 372 | + TORCH_CHECK(workspace.scalar_type() == torch::kUInt8, | ||
| 373 | + "local_workspace must be uint8"); | ||
| 374 | + TORCH_CHECK( | ||
| 375 | + num_output_slots_u64 <= | ||
| 376 | + std::numeric_limits<uint64_t>::max() / | ||
| 377 | + static_cast<uint64_t>(H) / sizeof(c10::BFloat16), | ||
| 378 | + "MoonEP UDMA combine hidden workspace size overflows uint64_t"); | ||
| 379 | + const uint64_t hidden_bytes = | ||
| 380 | + num_output_slots_u64 * static_cast<uint64_t>(H) * sizeof(c10::BFloat16); | ||
| 381 | + const uint64_t weight_regions = static_cast<uint64_t>(R); | ||
| 382 | + TORCH_CHECK( | ||
| 383 | + num_output_slots_u64 <= | ||
| 384 | + std::numeric_limits<uint64_t>::max() / weight_regions / sizeof(float), | ||
| 385 | + "MoonEP UDMA combine gathered weight workspace size overflows uint64_t"); | ||
| 386 | + const uint64_t weight_bytes = weight_regions * num_output_slots_u64 * sizeof(float); | ||
| 387 | + const uint64_t bandwidth_offset = | ||
| 388 | + (hidden_bytes + weight_bytes + kLegacyCombineBandwidthScratchAlign - 1) & | ||
| 389 | + ~(kLegacyCombineBandwidthScratchAlign - 1); | ||
| 390 | + const uint64_t required_workspace_bytes = | ||
| 391 | + bandwidth_offset + kLegacyCombineBandwidthScratchBytes; | ||
| 392 | + const uint64_t local_workspace_bytes = | ||
| 393 | + static_cast<uint64_t>(workspace.numel()) * | ||
| 394 | + static_cast<uint64_t>(workspace.element_size()); | ||
| 395 | + TORCH_CHECK(required_workspace_bytes <= local_workspace_bytes, | ||
| 396 | + "local workspace is too small: need ", required_workspace_bytes, | ||
| 397 | + " bytes, got ", local_workspace_bytes, " bytes"); | ||
| 398 | + | ||
| 399 | + const torch::Tensor& route_weights_arg = | ||
| 400 | + with_weights ? *route_weights_nvs : hidden_nvsh; | ||
| 401 | + const torch::Tensor& output_sk_arg = | ||
| 402 | + with_weights ? *output_sk : output_sh; | ||
| 403 | + | ||
| 404 | + MoonEPUdmaCombineTilingData tiling{}; | ||
| 405 | + tiling.S = static_cast<uint32_t>(S); | ||
| 406 | + tiling.H = static_cast<uint32_t>(H); | ||
| 407 | + tiling.K = static_cast<uint32_t>(K); | ||
| 408 | + tiling.R = static_cast<uint32_t>(R); | ||
| 409 | + tiling.rank = static_cast<uint32_t>(rank); | ||
| 410 | + tiling.with_weights = with_weights ? 1u : 0u; | ||
| 411 | + tiling.server_dedup = 0; | ||
| 412 | + | ||
| 413 | + auto* workspace_ptr = static_cast<uint8_t*>(workspace.data_ptr()); | ||
| 208 | void* bandwidth_scratch = workspace_ptr + bandwidth_offset; | 414 | void* bandwidth_scratch = workspace_ptr + bandwidth_offset; |
| 209 | 415 | ||
| 210 | - LaunchMoonEPUdmaCombineKernel( | 416 | + LaunchMoonEPUdmaCombineLegacyKernel( |
| 211 | hidden_nvsh, route_weights_arg, sync_buffer, dst, | 417 | hidden_nvsh, route_weights_arg, sync_buffer, dst, |
| 212 | dup_groups, dup_loffs, dup_counts, | 418 | dup_groups, dup_loffs, dup_counts, |
| 213 | output_sh, output_sk_arg, | 419 | output_sh, output_sk_arg, |
| 214 | - bandwidth_scratch, | 420 | + bandwidth_scratch, workspace_ptr, |
| 215 | - tiling, local_workspace.data_ptr(), NextCombineMagic()); | 421 | + tiling, NextCombineMagic()); |
| 216 | } | 422 | } |
| 217 | 423 | ||
| 218 | } // namespace ascend_moonep::ops | 424 | } // namespace ascend_moonep::ops |
| @@ -5,8 +5,8 @@ | |||
| 5 | namespace ascend_moonep::ops { | 5 | namespace ascend_moonep::ops { |
| 6 | 6 | ||
| 7 | // Caller-owned-output overload selected by ASCEND_MOONEP_COMBINE_USE_UDMA. | 7 | // Caller-owned-output overload selected by ASCEND_MOONEP_COMBINE_USE_UDMA. |
| 8 | -// local_workspace is | 8 | +// local_workspace is a Buffer-owned symmetric tensor used as this rank's |
| 9 | -// ordinary rank-local NPU memory; only the inputs are symmetric. | 9 | +// gathered payload staging area, allocated in the same SHMEM heap as inputs. |
| 10 | void MoonEPUdmaCombine( | 10 | void MoonEPUdmaCombine( |
| 11 | torch::Tensor hidden_nvsh, | 11 | torch::Tensor hidden_nvsh, |
| 12 | c10::optional<torch::Tensor> route_weights_nvs, | 12 | c10::optional<torch::Tensor> route_weights_nvs, |
| @@ -22,6 +22,27 @@ void MoonEPUdmaCombine( | |||
| 22 | int64_t K, | 22 | int64_t K, |
| 23 | int64_t R, | 23 | int64_t R, |
| 24 | int64_t rank, | 24 | int64_t rank, |
| 25 | - torch::Tensor local_workspace); | 25 | + torch::Tensor local_workspace, |
| 26 | + c10::optional<torch::Tensor> execution_plan = c10::nullopt); | ||
| 27 | + | ||
| 28 | +// Legacy rank-level dedup combine. `workspace` is one rank-local byte tensor | ||
| 29 | +// that holds the gathered payload plus its bandwidth-scratch tail; the host op | ||
| 30 | +// splits it, so the Buffer's symmetric PUT workspace is not used. | ||
| 31 | +void MoonEPUdmaCombineLegacy( | ||
| 32 | + torch::Tensor hidden_nvsh, | ||
| 33 | + c10::optional<torch::Tensor> route_weights_nvs, | ||
| 34 | + torch::Tensor sync_buffer, | ||
| 35 | + torch::Tensor dst, | ||
| 36 | + torch::Tensor dup_groups, | ||
| 37 | + torch::Tensor dup_loffs, | ||
| 38 | + torch::Tensor dup_counts, | ||
| 39 | + torch::Tensor output_sh, | ||
| 40 | + c10::optional<torch::Tensor> output_sk, | ||
| 41 | + int64_t S, | ||
| 42 | + int64_t H, | ||
| 43 | + int64_t K, | ||
| 44 | + int64_t R, | ||
| 45 | + int64_t rank, | ||
| 46 | + torch::Tensor workspace); | ||
| 26 | 47 | ||
| 27 | } // namespace ascend_moonep::ops | 48 | } // namespace ascend_moonep::ops |
| @@ -47,7 +47,9 @@ CheckedDispatchArgs CheckDispatchArgs( | |||
| 47 | int64_t H, | 47 | int64_t H, |
| 48 | int64_t K, | 48 | int64_t K, |
| 49 | int64_t R, | 49 | int64_t R, |
| 50 | - int64_t rank) { | 50 | + int64_t rank, |
| 51 | + bool use_udma, | ||
| 52 | + bool server_dedup) { | ||
| 51 | 53 | ||
| 52 | CheckNpuContiguous(hidden_sh, "hidden_sh"); | 54 | CheckNpuContiguous(hidden_sh, "hidden_sh"); |
| 53 | CheckNpuContiguous(dst, "dst"); | 55 | CheckNpuContiguous(dst, "dst"); |
| @@ -118,12 +120,24 @@ CheckedDispatchArgs CheckDispatchArgs( | |||
| 118 | dup_groups.dim() == 2 && | 120 | dup_groups.dim() == 2 && |
| 119 | dup_groups.size(0) == NvS && dup_groups.size(1) == 3, | 121 | dup_groups.size(0) == NvS && dup_groups.size(1) == 3, |
| 120 | "dup_groups must be int32 [NvS, 3]"); | 122 | "dup_groups must be int32 [NvS, 3]"); |
| 123 | + // Detect the protocol from the counts length; server plans go only to the already-adapted UDMA operator. | ||
| 124 | + const bool counts_server_dedup = dup_counts.dim() == 1 && dup_counts.size(0) == R + 2; | ||
| 125 | + TORCH_CHECK(server_dedup == counts_server_dedup, | ||
| 126 | + "dispatch dedup mode must match the plan tables: plan has ", | ||
| 127 | + counts_server_dedup ? "server" : "rank", | ||
| 128 | + " dedup tables"); | ||
| 129 | + const bool server_dedup_tables = counts_server_dedup; | ||
| 130 | + TORCH_CHECK(!server_dedup_tables || use_udma, "server dedup requires UDMA dispatch"); | ||
| 131 | + TORCH_CHECK(!server_dedup_tables || R % kMoonEPDispatchRanksPerServer == 0, | ||
| 132 | + "server dedup requires R divisible by 8"); | ||
| 133 | + const int64_t dup_capacity = server_dedup_tables ? kMoonEPDispatchRanksPerServer * NvS : NvS; | ||
| 134 | + const int64_t count_size = server_dedup_tables ? R + 2 : 2; | ||
| 121 | TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 && | 135 | TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 && |
| 122 | - dup_loffs.dim() == 1 && dup_loffs.size(0) == NvS, | 136 | + dup_loffs.dim() == 1 && dup_loffs.size(0) == dup_capacity, |
| 123 | - "dup_loffs must be int32 [NvS]"); | 137 | + "dup_loffs must be int32 [", dup_capacity, "] for the selected dup format"); |
| 124 | TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 && | 138 | TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 && |
| 125 | - dup_counts.dim() == 1 && dup_counts.size(0) == 2, | 139 | + dup_counts.dim() == 1 && dup_counts.size(0) == count_size, |
| 126 | - "dup_counts must be int32 [2]"); | 140 | + "dup_counts must be int32 [2] or [R+2]"); |
| 127 | TORCH_CHECK(H % 8 == 0, "H must be multiple of 8"); | 141 | TORCH_CHECK(H % 8 == 0, "H must be multiple of 8"); |
| 128 | TORCH_CHECK(static_cast<uint64_t>(H) * 2 <= 128ull * 1024ull, | 142 | TORCH_CHECK(static_cast<uint64_t>(H) * 2 <= 128ull * 1024ull, |
| 129 | "H row bytes exceed MoonEP dispatch UB row capacity"); | 143 | "H row bytes exceed MoonEP dispatch UB row capacity"); |
| @@ -139,7 +153,7 @@ CheckedDispatchArgs CheckDispatchArgs( | |||
| 139 | tiling.R = static_cast<uint32_t>(R); | 153 | tiling.R = static_cast<uint32_t>(R); |
| 140 | tiling.rank = static_cast<uint32_t>(rank); | 154 | tiling.rank = static_cast<uint32_t>(rank); |
| 141 | tiling.with_weights = with_weights ? 1u : 0u; | 155 | tiling.with_weights = with_weights ? 1u : 0u; |
| 142 | - tiling.reserved = 0; | 156 | + tiling.server_dedup = server_dedup ? 1u : 0u; |
| 143 | 157 | ||
| 144 | return {route_weights_arg, route_weights_buf_arg, tiling}; | 158 | return {route_weights_arg, route_weights_buf_arg, tiling}; |
| 145 | } | 159 | } |
| @@ -171,19 +185,15 @@ MoonEPDispatch( | |||
| 171 | int64_t R, | 185 | int64_t R, |
| 172 | int64_t rank, | 186 | int64_t rank, |
| 173 | bool use_udma, | 187 | bool use_udma, |
| 174 | - int64_t num_sms) { | 188 | + int64_t num_sms, |
| 189 | + bool server_dedup) { | ||
| 175 | 190 | ||
| 176 | auto args = CheckDispatchArgs( | 191 | auto args = CheckDispatchArgs( |
| 177 | hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts, | 192 | hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts, |
| 178 | - hidden_buf, route_weights_buf, S, H, K, R, rank); | 193 | + hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup); |
| 179 | 194 | ||
| 180 | - if (use_udma) { | 195 | + if (!use_udma) { |
| 181 | - LaunchMoonEPDispatchUdmaKernel( | 196 | + // Peer-to-peer MTE path: rank-level dedup only, no UDMA messaging. |
| 182 | - hidden_sh, args.route_weights, dst, | ||
| 183 | - dup_groups, dup_loffs, dup_counts, | ||
| 184 | - hidden_buf, args.route_weights_buf, sync_buffer, | ||
| 185 | - args.tiling, NextDispatchMagic()); | ||
| 186 | - } else { | ||
| 187 | TORCH_CHECK(num_sms > 0 && | 197 | TORCH_CHECK(num_sms > 0 && |
| 188 | static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(), | 198 | static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(), |
| 189 | "num_sms must be a positive uint32 launch width"); | 199 | "num_sms must be a positive uint32 launch width"); |
| @@ -193,6 +203,22 @@ MoonEPDispatch( | |||
| 193 | dup_groups, dup_loffs, dup_counts, | 203 | dup_groups, dup_loffs, dup_counts, |
| 194 | hidden_buf, args.route_weights_buf, | 204 | hidden_buf, args.route_weights_buf, |
| 195 | args.tiling); | 205 | args.tiling); |
| 206 | + } else if (server_dedup) { | ||
| 207 | + // Server-level dedup: the optimized kernel that forwards secondaries | ||
| 208 | + // inside an eight-rank board. | ||
| 209 | + LaunchMoonEPDispatchUdmaServerDedupKernel( | ||
| 210 | + hidden_sh, args.route_weights, dst, | ||
| 211 | + dup_groups, dup_loffs, dup_counts, | ||
| 212 | + hidden_buf, args.route_weights_buf, sync_buffer, | ||
| 213 | + args.tiling, NextDispatchMagic()); | ||
| 214 | + } else { | ||
| 215 | + // Rank-level dedup: the legacy kernel, frozen before the server dedup | ||
| 216 | + // optimization so that rank-level results stay on the old baseline. | ||
| 217 | + LaunchMoonEPDispatchUdmaLegacyKernel( | ||
| 218 | + hidden_sh, args.route_weights, dst, | ||
| 219 | + dup_groups, dup_loffs, dup_counts, | ||
| 220 | + hidden_buf, args.route_weights_buf, sync_buffer, | ||
| 221 | + args.tiling, NextDispatchMagic()); | ||
| 196 | } | 222 | } |
| 197 | } | 223 | } |
| 198 | 224 | ||
| @@ -213,11 +239,12 @@ MoonEPDispatchProfile( | |||
| 213 | int64_t K, | 239 | int64_t K, |
| 214 | int64_t R, | 240 | int64_t R, |
| 215 | int64_t rank, | 241 | int64_t rank, |
| 216 | - bool use_udma) { | 242 | + bool use_udma, |
| 243 | + bool server_dedup) { | ||
| 217 | 244 | ||
| 218 | auto args = CheckDispatchArgs( | 245 | auto args = CheckDispatchArgs( |
| 219 | hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts, | 246 | hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts, |
| 220 | - hidden_buf, route_weights_buf, S, H, K, R, rank); | 247 | + hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup); |
| 221 | CheckNpuContiguous(profile_cycles, "profile_cycles"); | 248 | CheckNpuContiguous(profile_cycles, "profile_cycles"); |
| 222 | CheckSameDevice(profile_cycles, hidden_sh, "profile_cycles"); | 249 | CheckSameDevice(profile_cycles, hidden_sh, "profile_cycles"); |
| 223 | 250 | ||
| @@ -229,11 +256,19 @@ MoonEPDispatchProfile( | |||
| 229 | "profile_cycles must be int64 [32, ", | 256 | "profile_cycles must be int64 [32, ", |
| 230 | kMoonEPDispatchUdmaProfileFields, "]"); | 257 | kMoonEPDispatchUdmaProfileFields, "]"); |
| 231 | 258 | ||
| 232 | - LaunchMoonEPDispatchUdmaProfileKernel( | 259 | + if (server_dedup) { |
| 233 | - hidden_sh, args.route_weights, dst, | 260 | + LaunchMoonEPDispatchUdmaServerDedupProfileKernel( |
| 234 | - dup_groups, dup_loffs, dup_counts, | 261 | + hidden_sh, args.route_weights, dst, |
| 235 | - hidden_buf, args.route_weights_buf, sync_buffer, profile_cycles, | 262 | + dup_groups, dup_loffs, dup_counts, |
| 236 | - args.tiling, NextDispatchMagic()); | 263 | + hidden_buf, args.route_weights_buf, sync_buffer, profile_cycles, |
| 264 | + args.tiling, NextDispatchMagic()); | ||
| 265 | + } else { | ||
| 266 | + LaunchMoonEPDispatchUdmaLegacyProfileKernel( | ||
| 267 | + hidden_sh, args.route_weights, dst, | ||
| 268 | + dup_groups, dup_loffs, dup_counts, | ||
| 269 | + hidden_buf, args.route_weights_buf, sync_buffer, profile_cycles, | ||
| 270 | + args.tiling, NextDispatchMagic()); | ||
| 271 | + } | ||
| 237 | } | 272 | } |
| 238 | } | 273 | } |
| 239 | 274 | ||
| @@ -23,7 +23,8 @@ MoonEPDispatch( | |||
| 23 | int64_t R, | 23 | int64_t R, |
| 24 | int64_t rank, | 24 | int64_t rank, |
| 25 | bool use_udma, | 25 | bool use_udma, |
| 26 | - int64_t num_sms = 32); | 26 | + int64_t num_sms = 32, |
| 27 | + bool server_dedup = false); | ||
| 27 | 28 | ||
| 28 | void | 29 | void |
| 29 | MoonEPDispatchProfile( | 30 | MoonEPDispatchProfile( |
| @@ -42,6 +43,7 @@ MoonEPDispatchProfile( | |||
| 42 | int64_t K, | 43 | int64_t K, |
| 43 | int64_t R, | 44 | int64_t R, |
| 44 | int64_t rank, | 45 | int64_t rank, |
| 45 | - bool use_udma); | 46 | + bool use_udma, |
| 47 | + bool server_dedup); | ||
| 46 | 48 | ||
| 47 | } // namespace ascend_moonep::ops | 49 | } // namespace ascend_moonep::ops |
| @@ -14,6 +14,7 @@ namespace { | |||
| 14 | constexpr int64_t kMinPlanningCores = 8; | 14 | constexpr int64_t kMinPlanningCores = 8; |
| 15 | constexpr int64_t kMaxPlanningCores = 56; | 15 | constexpr int64_t kMaxPlanningCores = 56; |
| 16 | constexpr int64_t kMaxPlanningRanks = 1024; | 16 | constexpr int64_t kMaxPlanningRanks = 1024; |
| 17 | +constexpr int64_t kPlanningRanksPerServer = ascend_moonep::kMoonEPDispatchRanksPerServer; | ||
| 17 | constexpr int64_t kInt32Bytes = 4; | 18 | constexpr int64_t kInt32Bytes = 4; |
| 18 | constexpr int64_t kUbAlignBytes = 32; | 19 | constexpr int64_t kUbAlignBytes = 32; |
| 19 | constexpr int64_t kAlignElems = kUbAlignBytes / kInt32Bytes; | 20 | constexpr int64_t kAlignElems = kUbAlignBytes / kInt32Bytes; |
| @@ -128,7 +129,8 @@ int64_t SourceDupPackChunkGroups(int64_t world_size, int64_t num_topk) { | |||
| 128 | int64_t SourceDupUbBytes( | 129 | int64_t SourceDupUbBytes( |
| 129 | int64_t world_size, | 130 | int64_t world_size, |
| 130 | int64_t num_topk, | 131 | int64_t num_topk, |
| 131 | - int64_t tokens_per_tile) { | 132 | + int64_t tokens_per_tile, |
| 133 | + bool server_dedup) { | ||
| 132 | const int64_t route_tile_elems = CheckedMul(tokens_per_tile, num_topk, "route tile"); | 134 | const int64_t route_tile_elems = CheckedMul(tokens_per_tile, num_topk, "route tile"); |
| 133 | const int64_t staging_elems = std::max(route_tile_elems + world_size * 7, world_size * 2); | 135 | const int64_t staging_elems = std::max(route_tile_elems + world_size * 7, world_size * 2); |
| 134 | const int64_t prefix_bytes = | 136 | const int64_t prefix_bytes = |
| @@ -163,13 +165,18 @@ int64_t SourceDupUbBytes( | |||
| 163 | const int64_t materialize_bytes = | 165 | const int64_t materialize_bytes = |
| 164 | AlignUp(world_size * 2 * kInt32Bytes, kUbAlignBytes) + | 166 | AlignUp(world_size * 2 * kInt32Bytes, kUbAlignBytes) + |
| 165 | 2 * AlignUp(kDupSrcTileElems * kInt32Bytes, kUbAlignBytes); | 167 | 2 * AlignUp(kDupSrcTileElems * kInt32Bytes, kUbAlignBytes); |
| 166 | - return std::max({prefix_bytes, group_bytes, materialize_bytes}); | 168 | + // The source prefix and the [G,D,P...] outputs occupy separate partitions in UB and must not overwrite each other. |
| 169 | + const int64_t destination_prefix_bytes = world_size * kSourceDupInboxSlotElems * kInt32Bytes + | ||
| 170 | + AlignUp((world_size + 2) * kInt32Bytes, kUbAlignBytes); | ||
| 171 | + return std::max({prefix_bytes, group_bytes, materialize_bytes, | ||
| 172 | + server_dedup ? destination_prefix_bytes : 0}); | ||
| 167 | } | 173 | } |
| 168 | 174 | ||
| 169 | uint32_t SelectSourceDupTokensPerTile( | 175 | uint32_t SelectSourceDupTokensPerTile( |
| 170 | int64_t world_size, | 176 | int64_t world_size, |
| 171 | int64_t num_topk, | 177 | int64_t num_topk, |
| 172 | - uint64_t ub_size) { | 178 | + uint64_t ub_size, |
| 179 | + bool server_dedup) { | ||
| 173 | int64_t preferred_tokens = std::max(kSourceDupPreferredTokens, kDupSrcTileElems / num_topk); | 180 | int64_t preferred_tokens = std::max(kSourceDupPreferredTokens, kDupSrcTileElems / num_topk); |
| 174 | preferred_tokens = std::min(preferred_tokens, kSourceDupSimtMaxThreads); | 181 | preferred_tokens = std::min(preferred_tokens, kSourceDupSimtMaxThreads); |
| 175 | if (preferred_tokens >= kSourceDupThreadAlign) { | 182 | if (preferred_tokens >= kSourceDupThreadAlign) { |
| @@ -178,14 +185,14 @@ uint32_t SelectSourceDupTokensPerTile( | |||
| 178 | for (int64_t tokens = preferred_tokens; | 185 | for (int64_t tokens = preferred_tokens; |
| 179 | tokens >= kSourceDupThreadAlign; | 186 | tokens >= kSourceDupThreadAlign; |
| 180 | tokens -= kSourceDupThreadAlign) { | 187 | tokens -= kSourceDupThreadAlign) { |
| 181 | - if (SourceDupUbBytes(world_size, num_topk, tokens) <= static_cast<int64_t>(ub_size)) { | 188 | + if (SourceDupUbBytes(world_size, num_topk, tokens, server_dedup) <= static_cast<int64_t>(ub_size)) { |
| 182 | return static_cast<uint32_t>(tokens); | 189 | return static_cast<uint32_t>(tokens); |
| 183 | } | 190 | } |
| 184 | } | 191 | } |
| 185 | for (int64_t tokens = std::min(preferred_tokens, kSourceDupThreadAlign - 1); | 192 | for (int64_t tokens = std::min(preferred_tokens, kSourceDupThreadAlign - 1); |
| 186 | tokens > 0; | 193 | tokens > 0; |
| 187 | --tokens) { | 194 | --tokens) { |
| 188 | - if (SourceDupUbBytes(world_size, num_topk, tokens) <= static_cast<int64_t>(ub_size)) { | 195 | + if (SourceDupUbBytes(world_size, num_topk, tokens, server_dedup) <= static_cast<int64_t>(ub_size)) { |
| 189 | return static_cast<uint32_t>(tokens); | 196 | return static_cast<uint32_t>(tokens); |
| 190 | } | 197 | } |
| 191 | } | 198 | } |
| @@ -203,7 +210,8 @@ PlanningWorkspaceLayout MakePlanningWorkspaceLayout( | |||
| 203 | int64_t num_topk, | 210 | int64_t num_topk, |
| 204 | int64_t num_experts, | 211 | int64_t num_experts, |
| 205 | int64_t world_size, | 212 | int64_t world_size, |
| 206 | - int64_t core_num) { | 213 | + int64_t core_num, |
| 214 | + bool server_dedup) { | ||
| 207 | TORCH_CHECK(num_tokens > 0, "num_tokens must be positive"); | 215 | TORCH_CHECK(num_tokens > 0, "num_tokens must be positive"); |
| 208 | TORCH_CHECK(num_topk > 0, "num_topk must be positive"); | 216 | TORCH_CHECK(num_topk > 0, "num_topk must be positive"); |
| 209 | TORCH_CHECK(num_experts > 0, "num_experts must be positive"); | 217 | TORCH_CHECK(num_experts > 0, "num_experts must be positive"); |
| @@ -290,7 +298,7 @@ PlanningWorkspaceLayout MakePlanningWorkspaceLayout( | |||
| 290 | core_num, | 298 | core_num, |
| 291 | static_cast<int64_t>(kPlanningUbSizeBytes)); | 299 | static_cast<int64_t>(kPlanningUbSizeBytes)); |
| 292 | const int64_t source_dup_tokens_per_tile = | 300 | const int64_t source_dup_tokens_per_tile = |
| 293 | - SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes); | 301 | + SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes, server_dedup); |
| 294 | const int64_t max_tokens_per_core = (num_tokens + core_num - 1) / core_num; | 302 | const int64_t max_tokens_per_core = (num_tokens + core_num - 1) / core_num; |
| 295 | const int64_t max_tiles_per_core = | 303 | const int64_t max_tiles_per_core = |
| 296 | (max_tokens_per_core + source_dup_tokens_per_tile - 1) / | 304 | (max_tokens_per_core + source_dup_tokens_per_tile - 1) / |
| @@ -404,10 +412,14 @@ namespace ascend_moonep::ops { | |||
| 404 | int64_t PlanningSymmetricWorkspaceBytes( | 412 | int64_t PlanningSymmetricWorkspaceBytes( |
| 405 | int64_t num_experts, | 413 | int64_t num_experts, |
| 406 | int64_t num_max_tokens_per_rank, | 414 | int64_t num_max_tokens_per_rank, |
| 407 | - int64_t world_size) { | 415 | + int64_t world_size, |
| 416 | + bool server_dedup) { | ||
| 408 | TORCH_CHECK(num_experts > 0, "num_experts must be positive"); | 417 | TORCH_CHECK(num_experts > 0, "num_experts must be positive"); |
| 409 | TORCH_CHECK(num_max_tokens_per_rank > 0, "num_max_tokens_per_rank must be positive"); | 418 | TORCH_CHECK(num_max_tokens_per_rank > 0, "num_max_tokens_per_rank must be positive"); |
| 410 | TORCH_CHECK(world_size > 0, "world_size must be positive"); | 419 | TORCH_CHECK(world_size > 0, "world_size must be positive"); |
| 420 | + TORCH_CHECK(world_size <= kMaxPlanningRanks && num_experts <= std::numeric_limits<int32_t>::max() && | ||
| 421 | + num_max_tokens_per_rank <= std::numeric_limits<int32_t>::max(), | ||
| 422 | + "planning workspace dimensions must fit device indices"); | ||
| 411 | const int64_t dup_rank_counts_off = AlignUp(num_experts, kAlignElems); | 423 | const int64_t dup_rank_counts_off = AlignUp(num_experts, kAlignElems); |
| 412 | const int64_t dup_payload_done_off = dup_rank_counts_off + | 424 | const int64_t dup_payload_done_off = dup_rank_counts_off + |
| 413 | CheckedMul( | 425 | CheckedMul( |
| @@ -418,8 +430,12 @@ int64_t PlanningSymmetricWorkspaceBytes( | |||
| 418 | dup_payload_done_off + AlignUp(world_size, kAlignElems); | 430 | dup_payload_done_off + AlignUp(world_size, kAlignElems); |
| 419 | const int64_t dup_loffs_off = | 431 | const int64_t dup_loffs_off = |
| 420 | dup_groups_off + AlignUp(num_max_tokens_per_rank * 3, kAlignElems); | 432 | dup_groups_off + AlignUp(num_max_tokens_per_rank * 3, kAlignElems); |
| 421 | - const int64_t required_ints = | 433 | + const int64_t dup_capacity = server_dedup |
| 422 | - dup_loffs_off + AlignUp(num_max_tokens_per_rank, kAlignElems); | 434 | + ? CheckedMul(kPlanningRanksPerServer, num_max_tokens_per_rank, "server dup capacity") |
| 435 | + : num_max_tokens_per_rank; | ||
| 436 | + const int64_t required_ints = dup_loffs_off + AlignUp(dup_capacity, kAlignElems); | ||
| 437 | + TORCH_CHECK(required_ints <= std::numeric_limits<int32_t>::max(), | ||
| 438 | + "planning symmetric workspace exceeds int32 device offsets"); | ||
| 423 | return CheckedMul(required_ints, kInt32Bytes, "planning symmetric workspace"); | 439 | return CheckedMul(required_ints, kInt32Bytes, "planning symmetric workspace"); |
| 424 | } | 440 | } |
| 425 | 441 | ||
| @@ -428,12 +444,13 @@ int64_t PlanningLocalWorkspaceElements( | |||
| 428 | int64_t num_topk, | 444 | int64_t num_topk, |
| 429 | int64_t num_experts, | 445 | int64_t num_experts, |
| 430 | int64_t world_size, | 446 | int64_t world_size, |
| 431 | - int64_t core_num) { | 447 | + int64_t core_num, |
| 448 | + bool server_dedup) { | ||
| 432 | return MakePlanningWorkspaceLayout( | 449 | return MakePlanningWorkspaceLayout( |
| 433 | - num_tokens, num_topk, num_experts, world_size, core_num).total_elems; | 450 | + num_tokens, num_topk, num_experts, world_size, core_num, server_dedup).total_elems; |
| 434 | } | 451 | } |
| 435 | 452 | ||
| 436 | -void Planning( | 453 | +torch::Tensor Planning( |
| 437 | torch::Tensor topk_idx, | 454 | torch::Tensor topk_idx, |
| 438 | torch::Tensor dst, | 455 | torch::Tensor dst, |
| 439 | torch::Tensor cu_seqlens, | 456 | torch::Tensor cu_seqlens, |
| @@ -452,8 +469,7 @@ void Planning( | |||
| 452 | int64_t core_num, | 469 | int64_t core_num, |
| 453 | int64_t rank, | 470 | int64_t rank, |
| 454 | int64_t world_size, | 471 | int64_t world_size, |
| 455 | - bool use_udma) { | 472 | + bool server_dedup, bool use_udma, torch::Tensor combine_workspace, int64_t hidden_size) { |
| 456 | - (void)use_udma; | ||
| 457 | CheckNpuInt32(topk_idx, "topk_idx"); | 473 | CheckNpuInt32(topk_idx, "topk_idx"); |
| 458 | CheckNpuInt32(dst, "dst"); | 474 | CheckNpuInt32(dst, "dst"); |
| 459 | CheckNpuInt32(cu_seqlens, "cu_seqlens"); | 475 | CheckNpuInt32(cu_seqlens, "cu_seqlens"); |
| @@ -497,8 +513,15 @@ void Planning( | |||
| 497 | CheckedMul(world_size, num_experts, "rank-expert table") <= | 513 | CheckedMul(world_size, num_experts, "rank-expert table") <= |
| 498 | std::numeric_limits<int32_t>::max(), | 514 | std::numeric_limits<int32_t>::max(), |
| 499 | "planning requires world_size * num_experts to fit int32 indexing"); | 515 | "planning requires world_size * num_experts to fit int32 indexing"); |
| 500 | - TORCH_CHECK(num_max_tokens_per_rank >= route_count, | 516 | + // Detect the protocol from the counts length; rank mode still lets legacy callers reserve NvS larger than S*K. |
| 501 | - "num_max_tokens_per_rank must be at least num_tokens * num_topk"); | 517 | + const bool counts_server_dedup = dup_counts.dim() == 1 && dup_counts.numel() == world_size + 2; |
| 518 | + TORCH_CHECK(server_dedup == counts_server_dedup, | ||
| 519 | + "planning dedup mode must match the plan tables: plan has ", | ||
| 520 | + counts_server_dedup ? "server" : "rank", " dedup tables"); | ||
| 521 | + TORCH_CHECK(!server_dedup || world_size % kPlanningRanksPerServer == 0, | ||
| 522 | + "server planning requires world_size divisible by 8"); | ||
| 523 | + TORCH_CHECK(num_max_tokens_per_rank >= route_count && (!server_dedup || num_max_tokens_per_rank == route_count), | ||
| 524 | + "server planning requires NvS == S*K; rank planning requires NvS >= S*K"); | ||
| 502 | TORCH_CHECK(topk_idx.numel() == route_count, | 525 | TORCH_CHECK(topk_idx.numel() == route_count, |
| 503 | "topk_idx numel must equal num_tokens * num_topk"); | 526 | "topk_idx numel must equal num_tokens * num_topk"); |
| 504 | TORCH_CHECK(dst.numel() == route_count, "dst shape mismatch"); | 527 | TORCH_CHECK(dst.numel() == route_count, "dst shape mismatch"); |
| @@ -506,11 +529,15 @@ void Planning( | |||
| 506 | "cu_seqlens shape mismatch"); | 529 | "cu_seqlens shape mismatch"); |
| 507 | TORCH_CHECK(experts_to_copy.numel() == world_size * num_prefetch_slots, | 530 | TORCH_CHECK(experts_to_copy.numel() == world_size * num_prefetch_slots, |
| 508 | "experts_to_copy shape mismatch"); | 531 | "experts_to_copy shape mismatch"); |
| 509 | - TORCH_CHECK(dup_groups.numel() == num_max_tokens_per_rank * 3, | 532 | + const int64_t dup_capacity = server_dedup ? kPlanningRanksPerServer * num_max_tokens_per_rank : |
| 510 | - "dup_groups shape mismatch"); | 533 | + num_max_tokens_per_rank; |
| 511 | - TORCH_CHECK(dup_loffs.numel() == num_max_tokens_per_rank, | 534 | + const int64_t count_size = server_dedup ? world_size + 2 : 2; |
| 512 | - "dup_loffs shape mismatch"); | 535 | + TORCH_CHECK(dup_groups.dim() == 2 && dup_groups.size(0) == num_max_tokens_per_rank && |
| 513 | - TORCH_CHECK(dup_counts.numel() == 2, "dup_counts shape mismatch"); | 536 | + dup_groups.size(1) == 3, "dup_groups must be int32 [NvS, 3]"); |
| 537 | + TORCH_CHECK(dup_loffs.dim() == 1 && dup_loffs.numel() == dup_capacity, | ||
| 538 | + "dup_loffs must be int32 [", dup_capacity, "] for the selected dup format"); | ||
| 539 | + TORCH_CHECK(dup_counts.dim() == 1 && dup_counts.numel() == count_size, | ||
| 540 | + "dup_counts must be int32 [2] or [R+2]"); | ||
| 514 | TORCH_CHECK(symmetric_workspace_addr != 0, | 541 | TORCH_CHECK(symmetric_workspace_addr != 0, |
| 515 | "planning symmetric workspace address must not be zero"); | 542 | "planning symmetric workspace address must not be zero"); |
| 516 | TORCH_CHECK( | 543 | TORCH_CHECK( |
| @@ -518,12 +545,12 @@ void Planning( | |||
| 518 | "planning local workspace base must be 32-byte aligned"); | 545 | "planning local workspace base must be 32-byte aligned"); |
| 519 | 546 | ||
| 520 | const auto layout = MakePlanningWorkspaceLayout( | 547 | const auto layout = MakePlanningWorkspaceLayout( |
| 521 | - num_tokens, num_topk, num_experts, world_size, core_num); | 548 | + num_tokens, num_topk, num_experts, world_size, core_num, server_dedup); |
| 522 | TORCH_CHECK(local_workspace.numel() >= layout.total_elems, | 549 | TORCH_CHECK(local_workspace.numel() >= layout.total_elems, |
| 523 | "planning local workspace is too small: need ", | 550 | "planning local workspace is too small: need ", |
| 524 | layout.total_elems, " int32 elements, got ", local_workspace.numel()); | 551 | layout.total_elems, " int32 elements, got ", local_workspace.numel()); |
| 525 | const int64_t required_symmetric_bytes = PlanningSymmetricWorkspaceBytes( | 552 | const int64_t required_symmetric_bytes = PlanningSymmetricWorkspaceBytes( |
| 526 | - num_experts, num_max_tokens_per_rank, world_size); | 553 | + num_experts, num_max_tokens_per_rank, world_size, server_dedup); |
| 527 | TORCH_CHECK(symmetric_workspace_bytes >= required_symmetric_bytes, | 554 | TORCH_CHECK(symmetric_workspace_bytes >= required_symmetric_bytes, |
| 528 | "planning symmetric workspace is too small: need ", | 555 | "planning symmetric workspace is too small: need ", |
| 529 | required_symmetric_bytes, " bytes, got ", symmetric_workspace_bytes); | 556 | required_symmetric_bytes, " bytes, got ", symmetric_workspace_bytes); |
| @@ -541,14 +568,29 @@ void Planning( | |||
| 541 | tiling.symmetric_dup_rank_counts_offset = | 568 | tiling.symmetric_dup_rank_counts_offset = |
| 542 | static_cast<uint32_t>(AlignUp(num_experts, kAlignElems)); | 569 | static_cast<uint32_t>(AlignUp(num_experts, kAlignElems)); |
| 543 | tiling.source_dup_tokens_per_tile = | 570 | tiling.source_dup_tokens_per_tile = |
| 544 | - SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes); | 571 | + SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes, server_dedup); |
| 545 | tiling.owner_reduce_tile_elems = static_cast<uint32_t>( | 572 | tiling.owner_reduce_tile_elems = static_cast<uint32_t>( |
| 546 | SelectOwnerReduceTileElems( | 573 | SelectOwnerReduceTileElems( |
| 547 | world_size, | 574 | world_size, |
| 548 | num_experts / world_size, | 575 | num_experts / world_size, |
| 549 | core_num, | 576 | core_num, |
| 550 | static_cast<int64_t>(kPlanningUbSizeBytes))); | 577 | static_cast<int64_t>(kPlanningUbSizeBytes))); |
| 551 | - tiling.reserved = 0; | 578 | + tiling.server_dedup = server_dedup ? 1U : 0U; |
| 579 | + constexpr int64_t ranks_per_server = ascend_moonep::kMoonEPDispatchRanksPerServer; | ||
| 580 | + const uint32_t stripe_rank_placement = use_udma && !server_dedup && | ||
| 581 | + world_size > ranks_per_server && world_size % ranks_per_server == 0; | ||
| 582 | + torch::Tensor combine_plan; | ||
| 583 | + TORCH_CHECK(server_dedup || !combine_workspace.defined(), | ||
| 584 | + "the legacy rank-level planner does not produce a combine " | ||
| 585 | + "execution plan; construct the Buffer with dedup_mode='server'"); | ||
| 586 | + if (server_dedup && combine_workspace.defined()) { | ||
| 587 | + combine_plan = AllocateCombinePlan(combine_workspace, dst, dup_groups, | ||
| 588 | + dup_loffs, dup_counts, num_tokens, hidden_size, num_topk, world_size, rank); | ||
| 589 | + tiling.combine_mode = 1U; | ||
| 590 | + tiling.combine_h = hidden_size; | ||
| 591 | + tiling.combine_workspace = reinterpret_cast<uint64_t>(combine_workspace.data_ptr()); | ||
| 592 | + tiling.combine_plan = reinterpret_cast<uint64_t>(combine_plan.data_ptr()); | ||
| 593 | + } | ||
| 552 | 594 | ||
| 553 | auto tpe_all = SliceWorkspace(local_workspace, layout.tpe_all); | 595 | auto tpe_all = SliceWorkspace(local_workspace, layout.tpe_all); |
| 554 | auto tpe_prefix = SliceWorkspace(local_workspace, layout.tpe_prefix); | 596 | auto tpe_prefix = SliceWorkspace(local_workspace, layout.tpe_prefix); |
| @@ -563,28 +605,94 @@ void Planning( | |||
| 563 | 605 | ||
| 564 | // SHMEM initializes FFTS where required; A5 legitimately returns zero. | 606 | // SHMEM initializes FFTS where required; A5 legitimately returns zero. |
| 565 | const uint64_t ffts_addr = shmemx_get_ffts_config(); | 607 | const uint64_t ffts_addr = shmemx_get_ffts_config(); |
| 608 | + const auto launch_planning = [&](auto launcher, auto... extra_args) { | ||
| 609 | + launcher( | ||
| 610 | + topk_idx, | ||
| 611 | + dst, | ||
| 612 | + cu_seqlens, | ||
| 613 | + experts_to_copy, | ||
| 614 | + dup_groups, | ||
| 615 | + dup_loffs, | ||
| 616 | + dup_counts, | ||
| 617 | + tpe_all, | ||
| 618 | + tpe_prefix, | ||
| 619 | + balance, | ||
| 620 | + z, | ||
| 621 | + alloc, | ||
| 622 | + alloc_cumsum, | ||
| 623 | + expert_offsets, | ||
| 624 | + core_expert_counts, | ||
| 625 | + dup_workspace, | ||
| 626 | + dup_key_workspace, | ||
| 627 | + tiling, | ||
| 628 | + reinterpret_cast<void*>(static_cast<uintptr_t>(symmetric_workspace_addr)), | ||
| 629 | + ffts_addr, | ||
| 630 | + extra_args...); | ||
| 631 | + }; | ||
| 632 | + if (server_dedup) { | ||
| 633 | + launch_planning(LaunchPlanningServerDedupKernel); | ||
| 634 | + } else { | ||
| 635 | + launch_planning(LaunchPlanningLegacyKernel, stripe_rank_placement); | ||
| 636 | + } | ||
| 637 | + return combine_plan; | ||
| 638 | +} | ||
| 566 | 639 | ||
| 567 | - LaunchPlanningKernel( | 640 | +torch::Tensor AllocateCombinePlan( |
| 568 | - topk_idx, | 641 | + torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups, |
| 569 | - dst, | 642 | + torch::Tensor dups, torch::Tensor counts, |
| 570 | - cu_seqlens, | 643 | + int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) { |
| 571 | - experts_to_copy, | 644 | + TORCH_CHECK(S > 0 && H > 0 && H % 8 == 0 && H <= 4 * 1024 * 1024 && |
| 572 | - dup_groups, | 645 | + K > 0 && K <= 16 && R > 0 && R <= 1024 && rank >= 0 && rank < R && |
| 573 | - dup_loffs, | 646 | + uint64_t(S) <= ((1ULL << 30) - 1) / uint64_t(K) / uint64_t(R), |
| 574 | - dup_counts, | 647 | + "invalid combine execution-plan dimensions"); |
| 575 | - tpe_all, | 648 | + TORCH_CHECK(R == 1 || (R % 2 == 0 && |
| 576 | - tpe_prefix, | 649 | + (R < 128 ? (R <= 8 || R % 8 == 0) : R % 16 == 0)), |
| 577 | - balance, | 650 | + "unsupported combine topology"); |
| 578 | - z, | 651 | + const int64_t n = S * K; |
| 579 | - alloc, | 652 | + TORCH_CHECK(n <= std::numeric_limits<uint32_t>::max() / 8U, |
| 580 | - alloc_cumsum, | 653 | + "combine scratch index exceeds uint32"); |
| 581 | - expert_offsets, | 654 | + for (const auto& tensor : {workspace, dst, groups, dups, counts}) { |
| 582 | - core_expert_counts, | 655 | + TORCH_CHECK(tensor.device().type() == c10::DeviceType::PrivateUse1 && |
| 583 | - dup_workspace, | 656 | + tensor.device() == dst.device() && tensor.is_contiguous(), |
| 584 | - dup_key_workspace, | 657 | + "combine planning tensors must be contiguous on the same NPU"); |
| 585 | - tiling, | 658 | + } |
| 586 | - reinterpret_cast<void*>(static_cast<uintptr_t>(symmetric_workspace_addr)), | 659 | + TORCH_CHECK(dst.scalar_type() == torch::kInt32 && dst.dim() == 1 && dst.numel() == n, |
| 587 | - ffts_addr); | 660 | + "dst must be int32 [S*K]"); |
| 661 | + TORCH_CHECK(groups.scalar_type() == torch::kInt32 && groups.dim() == 2 && | ||
| 662 | + groups.size(0) == n && groups.size(1) == 3, "groups must be int32 [S*K,3]"); | ||
| 663 | + TORCH_CHECK(counts.scalar_type() == torch::kInt32 && counts.dim() == 1 && | ||
| 664 | + (counts.numel() == 2 || counts.numel() == R + 2), "invalid dup counts"); | ||
| 665 | + const bool server = counts.numel() == R + 2; | ||
| 666 | + TORCH_CHECK(!server || R % 8 == 0, "server planning requires full 8-rank servers"); | ||
| 667 | + TORCH_CHECK(!server || uint64_t(n) <= kMoonEPServerDupRouteLimit, | ||
| 668 | + "server planning route exceeds packed capacity"); | ||
| 669 | + TORCH_CHECK(dups.scalar_type() == torch::kInt32 && dups.dim() == 1 && | ||
| 670 | + dups.numel() == (server ? 8 * n : n), "invalid dup member capacity"); | ||
| 671 | + const auto p = MakeCombinePutLayout(n, H, R, K); | ||
| 672 | + TORCH_CHECK(workspace.scalar_type() == torch::kUInt8 && workspace.dim() == 1 && | ||
| 673 | + uint64_t(workspace.numel()) >= p.bytes, "combine planning workspace too small"); | ||
| 674 | + for (const auto& tensor : {dst, groups, dups, counts}) | ||
| 675 | + TORCH_CHECK(!workspace.is_alias_of(tensor), "planning input must not alias exchange workspace"); | ||
| 676 | + const auto q = MakeCombineExecutionPlanLayout(n, R); | ||
| 677 | + auto plan = torch::empty({static_cast<int64_t>(q.bytes)}, dst.options().dtype(torch::kUInt8)); | ||
| 678 | + return plan; | ||
| 679 | +} | ||
| 680 | + | ||
| 681 | +torch::Tensor PlanningPrepareCombinePlan( | ||
| 682 | + torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups, | ||
| 683 | + torch::Tensor dups, torch::Tensor counts, | ||
| 684 | + int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) { | ||
| 685 | + auto plan = AllocateCombinePlan(workspace, dst, groups, dups, counts, S, H, K, R, rank); | ||
| 686 | + PlanningTilingData tiling{}; | ||
| 687 | + tiling.num_tokens = S; tiling.num_topk = K; tiling.world_size = R; | ||
| 688 | + tiling.rank = rank; tiling.server_dedup = counts.numel() == R + 2; | ||
| 689 | + tiling.block_dim = kCombinePutCores; | ||
| 690 | + tiling.combine_mode = 2U; // Synthetic/precomputed routes: same planning entry. | ||
| 691 | + tiling.combine_h = H; | ||
| 692 | + tiling.combine_workspace = reinterpret_cast<uint64_t>(workspace.data_ptr()); | ||
| 693 | + tiling.combine_plan = reinterpret_cast<uint64_t>(plan.data_ptr()); | ||
| 694 | + LaunchPlanningMetadataOnly(dst, groups, dups, counts, tiling); | ||
| 695 | + return plan; | ||
| 588 | } | 696 | } |
| 589 | 697 | ||
| 590 | } // namespace ascend_moonep::ops | 698 | } // namespace ascend_moonep::ops |
| @@ -9,16 +9,18 @@ namespace ascend_moonep::ops { | |||
| 9 | int64_t PlanningSymmetricWorkspaceBytes( | 9 | int64_t PlanningSymmetricWorkspaceBytes( |
| 10 | int64_t num_experts, | 10 | int64_t num_experts, |
| 11 | int64_t num_max_tokens_per_rank, | 11 | int64_t num_max_tokens_per_rank, |
| 12 | - int64_t world_size); | 12 | + int64_t world_size, |
| 13 | + bool server_dedup = false); | ||
| 13 | 14 | ||
| 14 | int64_t PlanningLocalWorkspaceElements( | 15 | int64_t PlanningLocalWorkspaceElements( |
| 15 | int64_t num_tokens, | 16 | int64_t num_tokens, |
| 16 | int64_t num_topk, | 17 | int64_t num_topk, |
| 17 | int64_t num_experts, | 18 | int64_t num_experts, |
| 18 | int64_t world_size, | 19 | int64_t world_size, |
| 19 | - int64_t core_num); | 20 | + int64_t core_num, |
| 21 | + bool server_dedup = false); | ||
| 20 | 22 | ||
| 21 | -void Planning( | 23 | +torch::Tensor Planning( |
| 22 | torch::Tensor topk_idx, | 24 | torch::Tensor topk_idx, |
| 23 | torch::Tensor dst, | 25 | torch::Tensor dst, |
| 24 | torch::Tensor cu_seqlens, | 26 | torch::Tensor cu_seqlens, |
| @@ -37,6 +39,18 @@ void Planning( | |||
| 37 | int64_t core_num, | 39 | int64_t core_num, |
| 38 | int64_t rank, | 40 | int64_t rank, |
| 39 | int64_t world_size, | 41 | int64_t world_size, |
| 40 | - bool use_udma); | 42 | + bool server_dedup, |
| 43 | + bool use_udma, | ||
| 44 | + torch::Tensor combine_workspace = {}, int64_t hidden_size = 0); | ||
| 45 | + | ||
| 46 | +torch::Tensor AllocateCombinePlan( | ||
| 47 | + torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups, | ||
| 48 | + torch::Tensor dups, torch::Tensor counts, | ||
| 49 | + int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank); | ||
| 50 | + | ||
| 51 | +torch::Tensor PlanningPrepareCombinePlan( | ||
| 52 | + torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups, | ||
| 53 | + torch::Tensor dups, torch::Tensor counts, | ||
| 54 | + int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank); | ||
| 41 | 55 | ||
| 42 | } // namespace ascend_moonep::ops | 56 | } // namespace ascend_moonep::ops |
| @@ -46,6 +46,7 @@ void CheckShmem(const c10::intrusive_ptr<ShmemInstance>& shmem) { | |||
| 46 | TORCH_CHECK(shmem->Initialized(), "ShmemInstance is not initialized"); | 46 | TORCH_CHECK(shmem->Initialized(), "ShmemInstance is not initialized"); |
| 47 | } | 47 | } |
| 48 | 48 | ||
| 49 | + | ||
| 49 | std::size_t MoonEPUdmaCombineWorkspaceBytes( | 50 | std::size_t MoonEPUdmaCombineWorkspaceBytes( |
| 50 | int64_t S, | 51 | int64_t S, |
| 51 | int64_t H, | 52 | int64_t H, |
| @@ -228,14 +229,45 @@ class Planning : public torch::jit::CustomClassHolder { | |||
| 228 | public: | 229 | public: |
| 229 | Planning() = default; | 230 | Planning() = default; |
| 230 | 231 | ||
| 232 | + torch::Tensor compute_fused( | ||
| 233 | + torch::Tensor topk_idx, torch::Tensor dst, torch::Tensor cu_seqlens, | ||
| 234 | + torch::Tensor experts_to_copy, torch::Tensor dup_groups, torch::Tensor dup_loffs, | ||
| 235 | + torch::Tensor dup_counts, torch::Tensor local_workspace, | ||
| 236 | + int64_t symmetric_workspace_addr, int64_t symmetric_workspace_bytes, | ||
| 237 | + int64_t num_tokens, int64_t num_topk, int64_t num_experts, | ||
| 238 | + int64_t num_max_tokens_per_rank, int64_t num_prefetch_slots, | ||
| 239 | + int64_t core_num, int64_t rank, int64_t world_size, bool use_udma, | ||
| 240 | + bool server_dedup, torch::Tensor combine_workspace, int64_t hidden_size) { | ||
| 241 | + TORCH_CHECK(rank == aclshmem_my_pe() && world_size == aclshmem_n_pes(), | ||
| 242 | + "planning topology must match the active SHMEM runtime"); | ||
| 243 | + return ascend_moonep::ops::Planning(topk_idx, dst, cu_seqlens, experts_to_copy, | ||
| 244 | + dup_groups, dup_loffs, dup_counts, local_workspace, | ||
| 245 | + symmetric_workspace_addr, symmetric_workspace_bytes, | ||
| 246 | + num_tokens, num_topk, num_experts, num_max_tokens_per_rank, | ||
| 247 | + num_prefetch_slots, core_num, rank, world_size, server_dedup, use_udma, | ||
| 248 | + combine_workspace, hidden_size); | ||
| 249 | + } | ||
| 250 | + | ||
| 251 | + torch::Tensor prepare_combine_plan( | ||
| 252 | + torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups, | ||
| 253 | + torch::Tensor dups, torch::Tensor counts, | ||
| 254 | + int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) { | ||
| 255 | + TORCH_CHECK(rank == aclshmem_my_pe() && R == aclshmem_n_pes(), | ||
| 256 | + "planning topology must match the active SHMEM runtime"); | ||
| 257 | + return ascend_moonep::ops::PlanningPrepareCombinePlan( | ||
| 258 | + workspace, dst, groups, dups, counts, S, H, K, R, rank); | ||
| 259 | + } | ||
| 260 | + | ||
| 231 | int64_t symmetric_workspace_bytes( | 261 | int64_t symmetric_workspace_bytes( |
| 232 | int64_t num_experts, | 262 | int64_t num_experts, |
| 233 | int64_t num_max_tokens_per_rank, | 263 | int64_t num_max_tokens_per_rank, |
| 234 | - int64_t world_size) const { | 264 | + int64_t world_size, |
| 265 | + bool server_dedup) const { | ||
| 235 | return ascend_moonep::ops::PlanningSymmetricWorkspaceBytes( | 266 | return ascend_moonep::ops::PlanningSymmetricWorkspaceBytes( |
| 236 | num_experts, | 267 | num_experts, |
| 237 | num_max_tokens_per_rank, | 268 | num_max_tokens_per_rank, |
| 238 | - world_size); | 269 | + world_size, |
| 270 | + server_dedup); | ||
| 239 | } | 271 | } |
| 240 | 272 | ||
| 241 | int64_t local_workspace_elements( | 273 | int64_t local_workspace_elements( |
| @@ -243,13 +275,15 @@ public: | |||
| 243 | int64_t num_topk, | 275 | int64_t num_topk, |
| 244 | int64_t num_experts, | 276 | int64_t num_experts, |
| 245 | int64_t world_size, | 277 | int64_t world_size, |
| 246 | - int64_t core_num) const { | 278 | + int64_t core_num, |
| 279 | + bool server_dedup) const { | ||
| 247 | return ascend_moonep::ops::PlanningLocalWorkspaceElements( | 280 | return ascend_moonep::ops::PlanningLocalWorkspaceElements( |
| 248 | num_tokens, | 281 | num_tokens, |
| 249 | num_topk, | 282 | num_topk, |
| 250 | num_experts, | 283 | num_experts, |
| 251 | world_size, | 284 | world_size, |
| 252 | - core_num); | 285 | + core_num, |
| 286 | + server_dedup); | ||
| 253 | } | 287 | } |
| 254 | 288 | ||
| 255 | void compute( | 289 | void compute( |
| @@ -271,7 +305,8 @@ public: | |||
| 271 | int64_t core_num, | 305 | int64_t core_num, |
| 272 | int64_t rank, | 306 | int64_t rank, |
| 273 | int64_t world_size, | 307 | int64_t world_size, |
| 274 | - bool use_udma) { | 308 | + bool use_udma, |
| 309 | + bool server_dedup) { | ||
| 275 | TORCH_CHECK( | 310 | TORCH_CHECK( |
| 276 | rank == aclshmem_my_pe(), | 311 | rank == aclshmem_my_pe(), |
| 277 | "rank does not match the active CANN-SHMEM PE"); | 312 | "rank does not match the active CANN-SHMEM PE"); |
| @@ -294,6 +329,7 @@ public: | |||
| 294 | core_num, | 329 | core_num, |
| 295 | rank, | 330 | rank, |
| 296 | world_size, | 331 | world_size, |
| 332 | + server_dedup, | ||
| 297 | use_udma); | 333 | use_udma); |
| 298 | } | 334 | } |
| 299 | }; | 335 | }; |
| @@ -318,7 +354,8 @@ public: | |||
| 318 | int64_t world_size, | 354 | int64_t world_size, |
| 319 | int64_t rank, | 355 | int64_t rank, |
| 320 | bool use_udma, | 356 | bool use_udma, |
| 321 | - int64_t num_sms = 32) { | 357 | + int64_t num_sms, |
| 358 | + bool server_dedup) { | ||
| 322 | TORCH_CHECK( | 359 | TORCH_CHECK( |
| 323 | rank == aclshmem_my_pe(), | 360 | rank == aclshmem_my_pe(), |
| 324 | "rank does not match the active CANN-SHMEM PE"); | 361 | "rank does not match the active CANN-SHMEM PE"); |
| @@ -338,7 +375,8 @@ public: | |||
| 338 | world_size, | 375 | world_size, |
| 339 | rank, | 376 | rank, |
| 340 | use_udma, | 377 | use_udma, |
| 341 | - num_sms); | 378 | + num_sms, |
| 379 | + server_dedup); | ||
| 342 | } | 380 | } |
| 343 | 381 | ||
| 344 | void compute_profile( | 382 | void compute_profile( |
| @@ -357,7 +395,8 @@ public: | |||
| 357 | int64_t num_topk, | 395 | int64_t num_topk, |
| 358 | int64_t world_size, | 396 | int64_t world_size, |
| 359 | int64_t rank, | 397 | int64_t rank, |
| 360 | - bool use_udma) { | 398 | + bool use_udma, |
| 399 | + bool server_dedup) { | ||
| 361 | TORCH_CHECK( | 400 | TORCH_CHECK( |
| 362 | rank == aclshmem_my_pe(), | 401 | rank == aclshmem_my_pe(), |
| 363 | "rank does not match the active CANN-SHMEM PE"); | 402 | "rank does not match the active CANN-SHMEM PE"); |
| @@ -377,7 +416,8 @@ public: | |||
| 377 | num_topk, | 416 | num_topk, |
| 378 | world_size, | 417 | world_size, |
| 379 | rank, | 418 | rank, |
| 380 | - use_udma); | 419 | + use_udma, |
| 420 | + server_dedup); | ||
| 381 | } | 421 | } |
| 382 | }; | 422 | }; |
| 383 | 423 | ||
| @@ -423,8 +463,6 @@ public: | |||
| 423 | } | 463 | } |
| 424 | }; | 464 | }; |
| 425 | 465 | ||
| 426 | -// Buffer-facing UDMA combine. Inputs are symmetric; gather scratch is an | ||
| 427 | -// ordinary rank-local NPU tensor cached by this class instance. | ||
| 428 | class CombineUrma : public torch::jit::CustomClassHolder { | 466 | class CombineUrma : public torch::jit::CustomClassHolder { |
| 429 | public: | 467 | public: |
| 430 | CombineUrma() = default; | 468 | CombineUrma() = default; |
| @@ -481,7 +519,7 @@ public: | |||
| 481 | .dtype(torch::kUInt8)); | 519 | .dtype(torch::kUInt8)); |
| 482 | } | 520 | } |
| 483 | 521 | ||
| 484 | - ascend_moonep::ops::MoonEPUdmaCombine( | 522 | + ascend_moonep::ops::MoonEPUdmaCombineLegacy( |
| 485 | hidden_nvsh, | 523 | hidden_nvsh, |
| 486 | route_weights_nvs, | 524 | route_weights_nvs, |
| 487 | sync_buffer, | 525 | sync_buffer, |
| @@ -499,6 +537,18 @@ public: | |||
| 499 | local_workspace_); | 537 | local_workspace_); |
| 500 | } | 538 | } |
| 501 | 539 | ||
| 540 | + void compute_prepared( | ||
| 541 | + torch::Tensor hidden, c10::optional<torch::Tensor> weights, | ||
| 542 | + torch::Tensor sync, torch::Tensor workspace, | ||
| 543 | + torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, torch::Tensor counts, | ||
| 544 | + torch::Tensor out, c10::optional<torch::Tensor> outw, torch::Tensor plan, | ||
| 545 | + int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) { | ||
| 546 | + TORCH_CHECK(rank == aclshmem_my_pe() && R == aclshmem_n_pes(), | ||
| 547 | + "plan topology must match the active SHMEM runtime"); | ||
| 548 | + ascend_moonep::ops::MoonEPUdmaCombine(hidden, weights, sync, dst, groups, | ||
| 549 | + dups, counts, out, outw, S, H, K, R, rank, workspace, plan); | ||
| 550 | + } | ||
| 551 | + | ||
| 502 | private: | 552 | private: |
| 503 | torch::Tensor local_workspace_; | 553 | torch::Tensor local_workspace_; |
| 504 | }; | 554 | }; |
| @@ -539,11 +589,26 @@ static auto planning_registry = | |||
| 539 | .def(torch::jit::init<>()) | 589 | .def(torch::jit::init<>()) |
| 540 | .def( | 590 | .def( |
| 541 | "symmetric_workspace_bytes", | 591 | "symmetric_workspace_bytes", |
| 542 | - &ascend_moonep::torch_classes::Planning::symmetric_workspace_bytes) | 592 | + &ascend_moonep::torch_classes::Planning::symmetric_workspace_bytes, |
| 593 | + "", {torch::arg("num_experts"), torch::arg("num_max_tokens_per_rank"), | ||
| 594 | + torch::arg("world_size"), torch::arg("server_dedup") = false}) | ||
| 543 | .def( | 595 | .def( |
| 544 | "local_workspace_elements", | 596 | "local_workspace_elements", |
| 545 | - &ascend_moonep::torch_classes::Planning::local_workspace_elements) | 597 | + &ascend_moonep::torch_classes::Planning::local_workspace_elements, |
| 546 | - .def("compute", &ascend_moonep::torch_classes::Planning::compute); | 598 | + "", {torch::arg("num_tokens"), torch::arg("num_topk"), torch::arg("num_experts"), |
| 599 | + torch::arg("world_size"), torch::arg("core_num"), | ||
| 600 | + torch::arg("server_dedup") = false}) | ||
| 601 | + .def("prepare_combine_plan", &ascend_moonep::torch_classes::Planning::prepare_combine_plan) | ||
| 602 | + .def("compute_fused", &ascend_moonep::torch_classes::Planning::compute_fused) | ||
| 603 | + .def("compute", &ascend_moonep::torch_classes::Planning::compute, | ||
| 604 | + "", {torch::arg("topk_idx"), torch::arg("dst"), torch::arg("cu_seqlens"), | ||
| 605 | + torch::arg("experts_to_copy"), torch::arg("dup_groups"), torch::arg("dup_loffs"), | ||
| 606 | + torch::arg("dup_counts"), torch::arg("local_workspace"), | ||
| 607 | + torch::arg("symmetric_workspace_addr"), torch::arg("symmetric_workspace_bytes"), | ||
| 608 | + torch::arg("num_tokens"), torch::arg("num_topk"), torch::arg("num_experts"), | ||
| 609 | + torch::arg("num_max_tokens_per_rank"), torch::arg("num_prefetch_slots"), | ||
| 610 | + torch::arg("core_num"), torch::arg("rank"), torch::arg("world_size"), | ||
| 611 | + torch::arg("use_udma"), torch::arg("server_dedup") = false}); | ||
| 547 | 612 | ||
| 548 | static auto dispatch_registry = | 613 | static auto dispatch_registry = |
| 549 | torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch") | 614 | torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch") |
| @@ -555,8 +620,14 @@ static auto dispatch_registry = | |||
| 555 | torch::arg("route_weights_buf"), torch::arg("sync_buffer"), | 620 | torch::arg("route_weights_buf"), torch::arg("sync_buffer"), |
| 556 | torch::arg("num_tokens"), torch::arg("hidden_size"), torch::arg("num_topk"), | 621 | torch::arg("num_tokens"), torch::arg("hidden_size"), torch::arg("num_topk"), |
| 557 | torch::arg("world_size"), torch::arg("rank"), torch::arg("use_udma"), | 622 | torch::arg("world_size"), torch::arg("rank"), torch::arg("use_udma"), |
| 558 | - torch::arg("num_sms") = 32}) | 623 | + torch::arg("num_sms") = 32, torch::arg("server_dedup") = false}) |
| 559 | - .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile); | 624 | + .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile, |
| 625 | + "", {torch::arg("hidden_sh"), torch::arg("route_weights"), torch::arg("dst"), | ||
| 626 | + torch::arg("dup_groups"), torch::arg("dup_loffs"), torch::arg("dup_counts"), | ||
| 627 | + torch::arg("hidden_buf"), torch::arg("route_weights_buf"), torch::arg("sync_buffer"), | ||
| 628 | + torch::arg("profile_cycles"), torch::arg("num_tokens"), torch::arg("hidden_size"), | ||
| 629 | + torch::arg("num_topk"), torch::arg("world_size"), torch::arg("rank"), | ||
| 630 | + torch::arg("use_udma"), torch::arg("server_dedup") = false}); | ||
| 560 | 631 | ||
| 561 | static auto combine_registry = | 632 | static auto combine_registry = |
| 562 | torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine") | 633 | torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine") |
| @@ -572,5 +643,6 @@ static auto combine_registry = | |||
| 572 | static auto combine_urma_registry = | 643 | static auto combine_urma_registry = |
| 573 | torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma") | 644 | torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma") |
| 574 | .def(torch::jit::init<>()) | 645 | .def(torch::jit::init<>()) |
| 646 | + .def("compute_prepared", &ascend_moonep::torch_classes::CombineUrma::compute_prepared) | ||
| 575 | .def("compute", &ascend_moonep::torch_classes::CombineUrma::compute) | 647 | .def("compute", &ascend_moonep::torch_classes::CombineUrma::compute) |
| 576 | .def("destroy", &ascend_moonep::torch_classes::CombineUrma::destroy); | 648 | .def("destroy", &ascend_moonep::torch_classes::CombineUrma::destroy); |
| @@ -29,21 +29,21 @@ ASCEND_MOONEP_EXPORT void moonep_combine_kernel_do( | |||
| 29 | uint8_t* route_weights_sk_out, | 29 | uint8_t* route_weights_sk_out, |
| 30 | uint8_t* tiling_host); | 30 | uint8_t* tiling_host); |
| 31 | 31 | ||
| 32 | +// Legacy rank-level dedup combine: gather scratch and bandwidth diagnostics are | ||
| 33 | +// split out of one rank-local workspace by the host op. | ||
| 32 | ASCEND_MOONEP_EXPORT void moonep_udma_combine_kernel_do( | 34 | ASCEND_MOONEP_EXPORT void moonep_udma_combine_kernel_do( |
| 33 | - void* stream, | 35 | + void* stream, uint8_t* hidden, uint8_t* weights, uint8_t* sync_buffer, |
| 34 | - uint8_t* hidden_nvsh, | 36 | + uint8_t* dst, uint8_t* groups, uint8_t* dups, uint8_t* counts, |
| 35 | - uint8_t* route_weights_nvs, | 37 | + uint8_t* out, uint8_t* outw, uint8_t* workspace, uint8_t* bandwidth_scratch, |
| 36 | - uint8_t* sync_buffer, | 38 | + uint8_t* tiling, uint64_t magic); |
| 37 | - uint8_t* dst, | 39 | + |
| 38 | - uint8_t* dup_groups, | 40 | +// Server-level dedup combine: consumes the execution plan produced by |
| 39 | - uint8_t* dup_loffs, | 41 | +// planning_server_dedup_kernel_do. |
| 40 | - uint8_t* dup_counts, | 42 | +ASCEND_MOONEP_EXPORT void moonep_udma_combine_server_dedup_kernel_do( |
| 41 | - uint8_t* output_sh, | 43 | + void* stream, uint8_t* hidden, uint8_t* weights, uint8_t* dst, |
| 42 | - uint8_t* output_sk, | 44 | + uint8_t* groups, uint8_t* dups, uint8_t* counts, uint8_t* out, uint8_t* outw, |
| 43 | - uint8_t* local_workspace, | 45 | + uint8_t* workspace, uint8_t* plan, uint8_t* tiling, |
| 44 | - uint8_t* bandwidth_scratch, | 46 | + uint64_t magic); |
| 45 | - uint8_t* tiling_host, | ||
| 46 | - uint64_t invocation_magic); | ||
| 47 | 47 | ||
| 48 | ASCEND_MOONEP_EXPORT void moonep_dispatch_kernel_do( | 48 | ASCEND_MOONEP_EXPORT void moonep_dispatch_kernel_do( |
| 49 | void* stream, | 49 | void* stream, |
| @@ -86,6 +86,35 @@ ASCEND_MOONEP_EXPORT void moonep_dispatch_udma_profile_kernel_do( | |||
| 86 | uint8_t* tiling_host, | 86 | uint8_t* tiling_host, |
| 87 | uint64_t magic); | 87 | uint64_t magic); |
| 88 | 88 | ||
| 89 | +ASCEND_MOONEP_EXPORT void moonep_dispatch_udma_server_dedup_kernel_do( | ||
| 90 | + void* stream, | ||
| 91 | + uint8_t* hidden_sh, | ||
| 92 | + uint8_t* route_weights, | ||
| 93 | + uint8_t* dst, | ||
| 94 | + uint8_t* dup_groups, | ||
| 95 | + uint8_t* dup_loffs, | ||
| 96 | + uint8_t* dup_counts, | ||
| 97 | + uint8_t* hidden_buf, | ||
| 98 | + uint8_t* weights_buf, | ||
| 99 | + uint8_t* sync_buffer, | ||
| 100 | + uint8_t* tiling_host, | ||
| 101 | + uint64_t magic); | ||
| 102 | + | ||
| 103 | +ASCEND_MOONEP_EXPORT void moonep_dispatch_udma_server_dedup_profile_kernel_do( | ||
| 104 | + void* stream, | ||
| 105 | + uint8_t* hidden_sh, | ||
| 106 | + uint8_t* route_weights, | ||
| 107 | + uint8_t* dst, | ||
| 108 | + uint8_t* dup_groups, | ||
| 109 | + uint8_t* dup_loffs, | ||
| 110 | + uint8_t* dup_counts, | ||
| 111 | + uint8_t* hidden_buf, | ||
| 112 | + uint8_t* weights_buf, | ||
| 113 | + uint8_t* sync_buffer, | ||
| 114 | + uint8_t* profile_cycles, | ||
| 115 | + uint8_t* tiling_host, | ||
| 116 | + uint64_t magic); | ||
| 117 | + | ||
| 89 | ASCEND_MOONEP_EXPORT void planning_kernel_do( | 118 | ASCEND_MOONEP_EXPORT void planning_kernel_do( |
| 90 | void* stream, | 119 | void* stream, |
| 91 | uint8_t* topk_idx, | 120 | uint8_t* topk_idx, |
| @@ -109,6 +138,56 @@ ASCEND_MOONEP_EXPORT void planning_kernel_do( | |||
| 109 | uint8_t* tiling_host, | 138 | uint8_t* tiling_host, |
| 110 | uint64_t ffts_addr); | 139 | uint64_t ffts_addr); |
| 111 | 140 | ||
| 141 | +// A5 rank planner with explicit route placement control. | ||
| 142 | +ASCEND_MOONEP_EXPORT void planning_kernel_do_with_rank_stripe( | ||
| 143 | + void* stream, | ||
| 144 | + uint8_t* topk_idx, | ||
| 145 | + uint8_t* symmetric_buffer, | ||
| 146 | + uint8_t* dst, | ||
| 147 | + uint8_t* cu_seqlens, | ||
| 148 | + uint8_t* experts_to_copy, | ||
| 149 | + uint8_t* dup_groups, | ||
| 150 | + uint8_t* dup_loffs, | ||
| 151 | + uint8_t* dup_counts, | ||
| 152 | + uint8_t* tpe_all, | ||
| 153 | + uint8_t* tpe_prefix, | ||
| 154 | + uint8_t* balance, | ||
| 155 | + uint8_t* z_tensor, | ||
| 156 | + uint8_t* alloc_tensor, | ||
| 157 | + uint8_t* alloc_cumsum, | ||
| 158 | + uint8_t* expert_offsets, | ||
| 159 | + uint8_t* core_expert_counts, | ||
| 160 | + uint8_t* dup_workspace, | ||
| 161 | + uint8_t* dup_key_workspace, | ||
| 162 | + uint8_t* tiling_host, | ||
| 163 | + uint64_t ffts_addr, | ||
| 164 | + uint32_t stripe_rank_placement); | ||
| 165 | + | ||
| 166 | +// Server-level dedup planner: also materializes the combine execution plan when | ||
| 167 | +// the tiling requests the fused mode. | ||
| 168 | +ASCEND_MOONEP_EXPORT void planning_server_dedup_kernel_do( | ||
| 169 | + void* stream, | ||
| 170 | + uint8_t* topk_idx, | ||
| 171 | + uint8_t* symmetric_buffer, | ||
| 172 | + uint8_t* dst, | ||
| 173 | + uint8_t* cu_seqlens, | ||
| 174 | + uint8_t* experts_to_copy, | ||
| 175 | + uint8_t* dup_groups, | ||
| 176 | + uint8_t* dup_loffs, | ||
| 177 | + uint8_t* dup_counts, | ||
| 178 | + uint8_t* tpe_all, | ||
| 179 | + uint8_t* tpe_prefix, | ||
| 180 | + uint8_t* balance, | ||
| 181 | + uint8_t* z_tensor, | ||
| 182 | + uint8_t* alloc_tensor, | ||
| 183 | + uint8_t* alloc_cumsum, | ||
| 184 | + uint8_t* expert_offsets, | ||
| 185 | + uint8_t* core_expert_counts, | ||
| 186 | + uint8_t* dup_workspace, | ||
| 187 | + uint8_t* dup_key_workspace, | ||
| 188 | + uint8_t* tiling_host, | ||
| 189 | + uint64_t ffts_addr); | ||
| 190 | + | ||
| 112 | ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | 191 | ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( |
| 113 | void* stream, | 192 | void* stream, |
| 114 | void* expert_grads, | 193 | void* expert_grads, |
| @@ -4,9 +4,18 @@ | |||
| 4 | 4 | ||
| 5 | namespace ascend_moonep { | 5 | namespace ascend_moonep { |
| 6 | 6 | ||
| 7 | -// Shared host/device launch width. Lives here so unity builds of multiple | 7 | +#if defined(__CCE_AICORE__) || defined(__CCE_KT_TEST__) |
| 8 | -// kernels do not redefine a file-local kMoonEPAivNum. | 8 | +#define MOONEP_DEVICE_INLINE __forceinline__ __aicore__ |
| 9 | +#else | ||
| 10 | +#define MOONEP_DEVICE_INLINE static inline constexpr | ||
| 11 | +#endif | ||
| 12 | + | ||
| 13 | +// Default host/device launch width for the other operators. PUT UDMA combine | ||
| 14 | +// uses its own 64-AIV schedule in moonep_combine_udma.cpp; do not change this | ||
| 15 | +// shared default when tuning combine. | ||
| 9 | inline constexpr uint32_t kMoonEPAivNum = 32; | 16 | inline constexpr uint32_t kMoonEPAivNum = 32; |
| 17 | +// Server dedup groups 8 globally consecutive ranks into one board. | ||
| 18 | +inline constexpr uint32_t kMoonEPDispatchRanksPerServer = 8; | ||
| 10 | inline constexpr uint32_t kMoonEPUdmaCombineQpCount = 2; | 19 | inline constexpr uint32_t kMoonEPUdmaCombineQpCount = 2; |
| 11 | inline constexpr uint32_t kMoonEPUdmaCombineBandwidthScratchAlign = 64; | 20 | inline constexpr uint32_t kMoonEPUdmaCombineBandwidthScratchAlign = 64; |
| 12 | inline constexpr uint32_t kMoonEPUdmaCombineBandwidthStatsStride = 8; | 21 | inline constexpr uint32_t kMoonEPUdmaCombineBandwidthStatsStride = 8; |
| @@ -15,6 +24,48 @@ inline constexpr uint32_t kMoonEPUdmaCombineBandwidthStatsElems = | |||
| 15 | inline constexpr uint32_t kMoonEPUdmaCombineBandwidthScratchBytes = | 24 | inline constexpr uint32_t kMoonEPUdmaCombineBandwidthScratchBytes = |
| 16 | kMoonEPUdmaCombineBandwidthStatsElems * sizeof(int64_t); | 25 | kMoonEPUdmaCombineBandwidthStatsElems * sizeof(int64_t); |
| 17 | 26 | ||
| 27 | +// Plan dedup tables are identical in both dedup domains; the domain only | ||
| 28 | +// changes the capacities and the duplicate address encoding: | ||
| 29 | +// dup_groups[NvS, 3] = {primary loff on its owning rank, dup_start, dup_n}. | ||
| 30 | +// dup_n counts the non-primary members (<= K-1); a group is owned and | ||
| 31 | +// materialized by the primary route's destination rank. | ||
| 32 | +// dup_loffs: rank domain has NvS entries holding the in-rank loff; server | ||
| 33 | +// domain has 8*NvS entries holding the full destination address | ||
| 34 | +// rank*NvS + loff, so a group may list members on sibling ranks of the | ||
| 35 | +// same server. There is no packed count word. | ||
| 36 | +// dup_counts: rank [n_groups, n_dups]; server appends R per-source group | ||
| 37 | +// prefixes [P_0 .. P_{R-1}], where P_src counts this rank's groups whose | ||
| 38 | +// token source rank is below src (dispatch waits on that prefix). | ||
| 39 | +inline constexpr uint32_t kMoonEPServerDupRouteLimit = 1U << 26; | ||
| 40 | + | ||
| 41 | +// Combine-plan internal route tag: the fused planner's per-token packed tables | ||
| 42 | +// (contributors / relays) mark a representative that lives on the reading rank | ||
| 43 | +// with 0x80000000 | raw. It is disjoint from the public dst encoding (positive | ||
| 44 | +// canonical route, ~raw duplicate) while R*NvS < 2^30, and public dst never | ||
| 45 | +// carries it: dispatch and the metric tests only ever see the two-state form. | ||
| 46 | +inline constexpr uint32_t kMoonEPServerForwardedRouteTag = 0x80000000U; | ||
| 47 | +inline constexpr uint32_t kMoonEPServerRoutePayloadMask = 0x3fffffffU; | ||
| 48 | + | ||
| 49 | +MOONEP_DEVICE_INLINE int32_t EncodeMoonEPServerForwardedRoute(uint32_t raw) { | ||
| 50 | + return static_cast<int32_t>(kMoonEPServerForwardedRouteTag | raw); | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +MOONEP_DEVICE_INLINE bool IsMoonEPServerForwardedRoute(int32_t encoded) { | ||
| 54 | + return (static_cast<uint32_t>(encoded) & 0xc0000000U) == | ||
| 55 | + kMoonEPServerForwardedRouteTag; | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +MOONEP_DEVICE_INLINE uint32_t DecodeMoonEPServerForwardedRoute(int32_t encoded) { | ||
| 59 | + return static_cast<uint32_t>(encoded) & kMoonEPServerRoutePayloadMask; | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +// Legacy GET scratch constants retained for compatibility. The current PUT | ||
| 63 | +// workspace ABI is defined by MakeCombinePutLayout in types.h. | ||
| 64 | +inline constexpr uint32_t kMoonEPUdmaCombineScratchTileElements = 8192; | ||
| 65 | +inline constexpr uint32_t kMoonEPUdmaCombineScratchTilesPerAiv = 2; | ||
| 66 | + | ||
| 67 | +#undef MOONEP_DEVICE_INLINE | ||
| 68 | + | ||
| 18 | struct alignas(8) MoonEPCombineTilingData { | 69 | struct alignas(8) MoonEPCombineTilingData { |
| 19 | uint32_t rank; // current rank | 70 | uint32_t rank; // current rank |
| 20 | uint32_t world_size; // EP size | 71 | uint32_t world_size; // EP size |
| @@ -33,7 +84,8 @@ struct alignas(8) MoonEPUdmaCombineTilingData { | |||
| 33 | uint32_t R; | 84 | uint32_t R; |
| 34 | uint32_t rank; | 85 | uint32_t rank; |
| 35 | uint32_t with_weights; | 86 | uint32_t with_weights; |
| 36 | - uint32_t reserved; | 87 | + uint32_t server_dedup; |
| 88 | + uint32_t reserved; // Preserve the 32-byte host/device tiling structure size. | ||
| 37 | }; | 89 | }; |
| 38 | 90 | ||
| 39 | struct alignas(8) MoonEPDispatchTilingData { | 91 | struct alignas(8) MoonEPDispatchTilingData { |
| @@ -43,7 +95,7 @@ struct alignas(8) MoonEPDispatchTilingData { | |||
| 43 | uint32_t R; | 95 | uint32_t R; |
| 44 | uint32_t rank; | 96 | uint32_t rank; |
| 45 | uint32_t with_weights; | 97 | uint32_t with_weights; |
| 46 | - uint32_t reserved; | 98 | + uint32_t server_dedup; |
| 47 | uint32_t block_dim; // MTE only; occupies the former tail padding | 99 | uint32_t block_dim; // MTE only; occupies the former tail padding |
| 48 | }; | 100 | }; |
| 49 | 101 | ||
| @@ -83,10 +135,242 @@ struct alignas(8) PlanningTilingData { | |||
| 83 | uint32_t symmetric_dup_rank_counts_offset; | 135 | uint32_t symmetric_dup_rank_counts_offset; |
| 84 | uint32_t source_dup_tokens_per_tile; | 136 | uint32_t source_dup_tokens_per_tile; |
| 85 | uint32_t owner_reduce_tile_elems; | 137 | uint32_t owner_reduce_tile_elems; |
| 86 | - uint32_t reserved; | 138 | + uint32_t server_dedup; |
| 139 | + uint32_t combine_mode; // 0: base only; 1: fused tail; 2: precomputed-dst only. | ||
| 140 | + uint32_t combine_h; | ||
| 141 | + uint32_t combine_reserved; | ||
| 142 | + uint64_t combine_workspace; | ||
| 143 | + uint64_t combine_plan; | ||
| 87 | }; | 144 | }; |
| 88 | 145 | ||
| 89 | -static_assert(sizeof(PlanningTilingData) == 56, | 146 | +static_assert(sizeof(PlanningTilingData) == 80, |
| 90 | - "PlanningTilingData ABI must remain 56 bytes"); | 147 | + "PlanningTilingData fused ABI must remain 80 bytes"); |
| 91 | 148 | ||
| 92 | } // namespace ascend_moonep | 149 | } // namespace ascend_moonep |
| 150 | + | ||
| 151 | +// Shared combine ABI: launch/batch sizes, workspace/plan layouts and trace capacity. | ||
| 152 | +// Used by host launchers, planning.cpp and moonep_combine_udma.cpp. | ||
| 153 | + | ||
| 154 | +// Shared launch/workspace capacities, also consumed by host and planning. | ||
| 155 | +namespace ascend_moonep { | ||
| 156 | +inline constexpr uint32_t kCombinePutCores = 64; | ||
| 157 | +inline constexpr uint32_t kCombinePutBatchRows = 64; | ||
| 158 | +// Capacity factor only: runtime pages are packed by actual contributor rows. | ||
| 159 | +inline constexpr uint32_t kCombineRingGroupsPerPage = 64; | ||
| 160 | +inline constexpr uint32_t kCombineRingDepth = 4; | ||
| 161 | +inline constexpr uint32_t kCombineRingStreams = 8; | ||
| 162 | +inline constexpr uint32_t kCombineRingMaxShards = 4; | ||
| 163 | +} // namespace ascend_moonep | ||
| 164 | + | ||
| 165 | +// ---- Communication workspace layout ---- | ||
| 166 | +namespace ascend_moonep { | ||
| 167 | +#if defined(__CCE_AICORE__) || defined(__CCE_KT_TEST__) | ||
| 168 | +#define MOONEP_PUT_INLINE __forceinline__ __aicore__ | ||
| 169 | +#else | ||
| 170 | +#define MOONEP_PUT_INLINE inline constexpr | ||
| 171 | +#endif | ||
| 172 | + | ||
| 173 | +// Aligned PUT workspace ABI. All uint64 members except bytes are byte offsets | ||
| 174 | +// relative to symmetric ws, NOT pointers or lengths. Host and Python mirror it. | ||
| 175 | +// N=S*K, H=hidden, R=ranks, B=ceil(N/64), A(x)=ceil(x/512)*512. | ||
| 176 | +// Meta(base,i) uses independent 64-byte records; Flag(base,i) uses 512-byte slots. | ||
| 177 | +// Only the first uint64 of a flag carries magic; reducer MTE3 writes 32 bytes. | ||
| 178 | +// | ||
| 179 | +// Source=original token owner/final destination; producer=expert-output holder; | ||
| 180 | +// ingress=server group reducer. The same rank can have all three roles. | ||
| 181 | +// Workspace offsets are shared by Planning and Combine. Host, Python and | ||
| 182 | +// device kernels MUST be rebuilt and installed together after layout changes. | ||
| 183 | +struct CombinePutLayout { | ||
| 184 | + uint64_t final_hidden; // BF16[N,H], compact producer segments at each source. | ||
| 185 | + // Local-server routes include suppressed members too. | ||
| 186 | + uint64_t relay_hidden; // Phase pool: Planning staging, then BF16 input ring. | ||
| 187 | + // 8 streams * 4 pages * (64*K) rows; groups never cross pages. | ||
| 188 | + uint64_t relay_result; // BF16[N,H], stable sums indexed by the original TX index. | ||
| 189 | + uint64_t weights; // float[N], every original source route, no weight dedup. | ||
| 190 | + | ||
| 191 | + uint64_t reverse; // Retired reverse-route records; offset reserved for ABI stability. | ||
| 192 | + uint64_t reverse_send;// Reserved N*64B arena; planner publishes contiguous dst[N] | ||
| 193 | + // in its first N*4B. Peers read it, never PUT reverse requests. | ||
| 194 | + uint64_t final_map; // Retired scalar final mapping arena, offset reserved. | ||
| 195 | + // Planner now builds final descriptors by partition prefixes. | ||
| 196 | + uint64_t group_of_loff;// Retired group lookup arena; offset reserved. | ||
| 197 | + uint64_t tx_rows; // N records in source/ordinal order: | ||
| 198 | + // {loff,group,scratchHead(-1 for DIRECT),contributorCount}. | ||
| 199 | + // DIRECT count=1; send original hidden without server reduction. | ||
| 200 | + uint64_t source_counts;// R records: | ||
| 201 | + // [0]=active result count, [1]=remote final segment base, | ||
| 202 | + // [2]=local tx base, [3]=DIRECT count, | ||
| 203 | + // [4]=scratch range start, [5]=scratch slot count, | ||
| 204 | + // [6]=ring page count, [7]=first logical ring page. | ||
| 205 | + // Scratch slots INCLUDE contributor holes; <=N/source. | ||
| 206 | + uint64_t counts_send; // Planner-local R records: {groupCount,groupPrefix} per source. | ||
| 207 | + uint64_t contributor; // 8*N records: word0 is {count:high32,txIndex:low32}, | ||
| 208 | + // word1 is original global contributor address. | ||
| 209 | + // Only a group head has count>0; interior slots are zero. | ||
| 210 | + // 64-byte spacing prevents concurrent planner cacheline | ||
| 211 | + // writeback races. Reducer gathers 64 entries into UB. | ||
| 212 | + uint64_t relay_send; // 8*N requests at producer: [ingressLocal*N+ordinal] | ||
| 213 | + // -> {input loff,remote scratch slot}. Includes ingress | ||
| 214 | + // self contributors for planning; payload skips them because | ||
| 215 | + // Reduce reads their original input directly. | ||
| 216 | + uint64_t relay_publish;// Retired relay request PUT arena; offset reserved. | ||
| 217 | + uint64_t relay_counts, relay_counts_send; // Legacy reserved 8-record tables. | ||
| 218 | + | ||
| 219 | + uint64_t relay_ready; // 8*R slots, producerLocal*R+source, source-level SO ready. | ||
| 220 | + // Empty producer streams MUST publish as well. | ||
| 221 | + uint64_t reduce_ready;// R*B slots, source*B+scratchBatch; MTE3-ordered after sum. | ||
| 222 | + // B uses N, NOT N/R: nonuniform input must fit safely. | ||
| 223 | + uint64_t final_ready; // 2*R slots, producer*2+QP lane. Both remote lanes close | ||
| 224 | + // DIRECT+RELAY even when empty. Local Phase A uses lane0. | ||
| 225 | + uint64_t weight_ready;// R slots, producer -> complete all original route weights. | ||
| 226 | + uint64_t magic; // 64 stable per-core SHMEM PUT-source flag slots. | ||
| 227 | + uint64_t relay_ranges;// 8*R records at producer: ingressLocal*R+source | ||
| 228 | + // -> {requestBegin,requestCount,receiverSourcePageCount}. | ||
| 229 | + uint64_t relay_ranges_send; // Planner-local 8*R stats records: | ||
| 230 | + // {scratchCount,requestCount,scratchPrefix,requestPrefix}. | ||
| 231 | + // After metadata completion, reused as R*512B final | ||
| 232 | + // histograms: 64 partition counts/prefixes + peer total. | ||
| 233 | + uint64_t source_input_ready;// R slots, shard1 waits all producers, wakes shard0. | ||
| 234 | + uint64_t final_gate; // One local slot: core0 publishes after it has | ||
| 235 | + // observed every final_ready; all other cores wait here. | ||
| 236 | + uint64_t final_routes; // N independent 128-byte source-final descriptors. | ||
| 237 | + // Each output token owns {count, route[16]}; route is either | ||
| 238 | + // local hidden loff (bit31 set) or final_hidden row. N records | ||
| 239 | + // reserve for K=1 too; the active prefix is N/K records. | ||
| 240 | + uint64_t ring_epoch; // 8 receiver/peer invocation epochs. | ||
| 241 | + uint64_t ring_ready; // [stream,slot,producerLocal], 8*4*8 flags. | ||
| 242 | + uint64_t ring_credit; // [stream,slot], 8*4 reusable input-page credits. | ||
| 243 | + uint64_t ring_done; // [stream,slot,shard], 8*4*4 reducer completion flags. | ||
| 244 | + uint64_t ring_ready_source; // [ingressLocal,stream,slot], 8*8*4 SO source flags. | ||
| 245 | + uint64_t ring_result_ready; // Persistent logical-page ready flags, never ring-indexed. | ||
| 246 | + uint64_t bytes; // Total bytes including all alignment/reserved arenas. | ||
| 247 | + uint32_t batches; // ceil(N/64), worst per-source scratch batch capacity. | ||
| 248 | + uint32_t ring_page_rows, ring_page_capacity; | ||
| 249 | +}; | ||
| 250 | + | ||
| 251 | +MOONEP_PUT_INLINE uint64_t CombinePutAlign(uint64_t bytes) { | ||
| 252 | + return (bytes + 511U) & ~uint64_t(511U); | ||
| 253 | +} | ||
| 254 | +MOONEP_PUT_INLINE uint32_t CombineRingPageCapacity(uint32_t n, uint32_t ranks) { | ||
| 255 | + // Each nonempty source can contribute a separate partial final page. | ||
| 256 | + return static_cast<uint32_t>((uint64_t(n) + kCombineRingGroupsPerPage - 1U) / | ||
| 257 | + kCombineRingGroupsPerPage + ranks); | ||
| 258 | +} | ||
| 259 | +MOONEP_PUT_INLINE uint64_t CombineRingLayoutFingerprint(uint32_t k) { | ||
| 260 | + // Bit 40 distinguishes row-packed plans from legacy 64-group pages. | ||
| 261 | + return (uint64_t(1U) << 40U) | (uint64_t(kCombineRingStreams) << 56U) | | ||
| 262 | + (uint64_t(kCombineRingDepth) << 48U) | | ||
| 263 | + (uint64_t(kCombineRingGroupsPerPage) << 32U) | | ||
| 264 | + uint64_t(kCombineRingGroupsPerPage) * k; | ||
| 265 | +} | ||
| 266 | +MOONEP_PUT_INLINE uint64_t CombinePlanningStageBytes( | ||
| 267 | + uint32_t n, uint32_t h, uint32_t ranks) { | ||
| 268 | + // Preserve the original rank/server staged eligibility. Buffer allocation | ||
| 269 | + // precedes the plan's mode, so reserve the largest eligible mode's staging. | ||
| 270 | + if (ranks > 128U) return 0U; | ||
| 271 | + const uint64_t server = 32U + 8U * 8U, rank = 32U + 8U; | ||
| 272 | + if (uint64_t(ranks) * server <= uint64_t(h) * 16U) | ||
| 273 | + return uint64_t(ranks) * n * server; | ||
| 274 | + if (uint64_t(ranks) * rank <= uint64_t(h) * 16U) | ||
| 275 | + return uint64_t(ranks) * n * rank; | ||
| 276 | + return 0U; | ||
| 277 | +} | ||
| 278 | +MOONEP_PUT_INLINE uint64_t CombineRingPublishBytes(uint32_t n, uint32_t ranks) { | ||
| 279 | + const uint64_t legacy = uint64_t(n) * 8U * 64U; | ||
| 280 | + const uint64_t mirror = CombinePutAlign(uint64_t(ranks) * 64U) + | ||
| 281 | + CombinePutAlign(uint64_t(CombineRingPageCapacity(n, ranks)) * 64U); | ||
| 282 | + return CombinePutAlign(legacy > mirror ? legacy : mirror); | ||
| 283 | +} | ||
| 284 | +MOONEP_PUT_INLINE CombinePutLayout MakeCombinePutLayout( | ||
| 285 | + uint32_t n, uint32_t h, uint32_t ranks, uint32_t k = 16U) { | ||
| 286 | + CombinePutLayout p{}; | ||
| 287 | + const uint64_t row_bytes = uint64_t(n) * h * 2U; // all N rows, not one row | ||
| 288 | + const uint64_t meta = uint64_t(n) * 64U; | ||
| 289 | + p.batches = (uint64_t(n) + 63U) / 64U; | ||
| 290 | + p.ring_page_rows = kCombineRingGroupsPerPage * k; | ||
| 291 | + p.ring_page_capacity = CombineRingPageCapacity(n, ranks); | ||
| 292 | + p.final_hidden = 0; | ||
| 293 | + p.relay_hidden = CombinePutAlign(row_bytes); | ||
| 294 | + const uint64_t ring_bytes = CombinePutAlign(uint64_t(kCombineRingStreams) * | ||
| 295 | + kCombineRingDepth * p.ring_page_rows * h * 2U); | ||
| 296 | + p.relay_result = p.relay_hidden + ring_bytes; | ||
| 297 | + const uint64_t runtime_bytes = ring_bytes + CombinePutAlign(row_bytes); | ||
| 298 | + const uint64_t stage_bytes = CombinePutAlign(CombinePlanningStageBytes(n, h, ranks)); | ||
| 299 | + p.weights = p.relay_hidden + (stage_bytes > runtime_bytes ? stage_bytes : runtime_bytes); | ||
| 300 | + p.reverse = p.weights + CombinePutAlign(uint64_t(n) * 4U); | ||
| 301 | + p.reverse_send = p.reverse + CombinePutAlign(meta); | ||
| 302 | + p.final_map = p.reverse_send + CombinePutAlign(meta); | ||
| 303 | + p.group_of_loff = p.final_map + CombinePutAlign(meta); | ||
| 304 | + p.tx_rows = p.group_of_loff + CombinePutAlign(meta); | ||
| 305 | + p.source_counts = p.tx_rows + CombinePutAlign(meta); | ||
| 306 | + p.counts_send = p.source_counts + CombinePutAlign(uint64_t(ranks) * 64U); | ||
| 307 | + p.contributor = p.counts_send + CombinePutAlign(uint64_t(ranks) * 64U); | ||
| 308 | + p.relay_send = p.contributor + CombinePutAlign(8U * meta); | ||
| 309 | + p.relay_publish = p.relay_send + CombinePutAlign(8U * meta); | ||
| 310 | + p.relay_counts = p.relay_publish + CombineRingPublishBytes(n, ranks); | ||
| 311 | + p.relay_counts_send = p.relay_counts + 512U; | ||
| 312 | + p.relay_ready = p.relay_counts_send + 512U; | ||
| 313 | + p.reduce_ready = p.relay_ready + uint64_t(8U) * ranks * 512U; | ||
| 314 | + p.final_ready = p.reduce_ready + uint64_t(ranks) * p.batches * 512U; | ||
| 315 | + p.weight_ready = p.final_ready + uint64_t(ranks) * 2U * 512U; | ||
| 316 | + p.magic = p.weight_ready + uint64_t(ranks) * 512U; | ||
| 317 | + p.relay_ranges = p.magic + uint64_t(kCombinePutCores) * 512U; | ||
| 318 | + p.relay_ranges_send = p.relay_ranges + CombinePutAlign(uint64_t(8U) * ranks * 64U); | ||
| 319 | + p.source_input_ready = p.relay_ranges_send + CombinePutAlign(uint64_t(8U) * ranks * 64U); | ||
| 320 | + p.final_gate = p.source_input_ready + uint64_t(ranks) * 512U; | ||
| 321 | + p.final_routes = p.final_gate + 512U; | ||
| 322 | + p.ring_epoch = p.final_routes + CombinePutAlign(uint64_t(n) * 128U); | ||
| 323 | + p.ring_ready = p.ring_epoch + uint64_t(8U) * 512U; | ||
| 324 | + p.ring_credit = p.ring_ready + uint64_t(kCombineRingStreams) * kCombineRingDepth * 8U * 512U; | ||
| 325 | + p.ring_done = p.ring_credit + uint64_t(kCombineRingStreams) * kCombineRingDepth * 512U; | ||
| 326 | + p.ring_ready_source = p.ring_done + uint64_t(kCombineRingStreams) * | ||
| 327 | + kCombineRingDepth * kCombineRingMaxShards * 512U; | ||
| 328 | + p.ring_result_ready = p.ring_ready_source + uint64_t(8U) * | ||
| 329 | + kCombineRingStreams * kCombineRingDepth * 512U; | ||
| 330 | + p.bytes = p.ring_result_ready + uint64_t(p.ring_page_capacity) * 512U; | ||
| 331 | + return p; | ||
| 332 | +} | ||
| 333 | +#undef MOONEP_PUT_INLINE | ||
| 334 | +} // namespace ascend_moonep | ||
| 335 | + | ||
| 336 | +// ---- Immutable execution-plan layout ---- | ||
| 337 | +namespace ascend_moonep { | ||
| 338 | +#if defined(__CCE_AICORE__) || defined(__CCE_KT_TEST__) | ||
| 339 | +#define MOONEP_PLAN_INLINE __forceinline__ __aicore__ | ||
| 340 | +#else | ||
| 341 | +#define MOONEP_PLAN_INLINE inline constexpr | ||
| 342 | +#endif | ||
| 343 | +// Rank-local immutable snapshot. No payload, ready flags, magic or QP state. | ||
| 344 | +// Offsets are relative to this tensor, not the symmetric communication workspace. | ||
| 345 | +// v6: append immutable whole-group input pages and producer request mappings. | ||
| 346 | +// Existing TX/contributor/relay record strides are unchanged. Ready flags, | ||
| 347 | +// invocation epochs and ring credits remain in the communication workspace. | ||
| 348 | +// Regenerate plans and deploy host/device together; older snapshots are incompatible. | ||
| 349 | +inline constexpr uint64_t kCombineExecutionPlanVersion = 0x4d45504300000006ULL; | ||
| 350 | +inline constexpr uint32_t kCombinePlanTxBytes = 16U; | ||
| 351 | +inline constexpr uint32_t kCombinePlanContributorBytes = 16U; | ||
| 352 | +inline constexpr uint32_t kCombinePlanRelayBytes = 8U; | ||
| 353 | +struct CombineExecutionPlanLayout { | ||
| 354 | + uint64_t tx_rows, source_counts, contributor, relay_send, relay_ranges; | ||
| 355 | + uint64_t final_routes, ring_pages, relay_page_map, bytes; | ||
| 356 | +}; | ||
| 357 | +MOONEP_PLAN_INLINE CombineExecutionPlanLayout MakeCombineExecutionPlanLayout( | ||
| 358 | + uint32_t n, uint32_t ranks) { | ||
| 359 | + CombineExecutionPlanLayout q{}; | ||
| 360 | + q.tx_rows = 512U; // Header: version,N,H,K,R,rank,server_dedup,ring fingerprint. | ||
| 361 | + q.source_counts = q.tx_rows + CombinePutAlign(uint64_t(n) * kCombinePlanTxBytes); | ||
| 362 | + q.contributor = q.source_counts + CombinePutAlign(uint64_t(ranks) * 64U); | ||
| 363 | + q.relay_send = q.contributor + CombinePutAlign(uint64_t(n) * 8U * kCombinePlanContributorBytes); | ||
| 364 | + q.relay_ranges = q.relay_send + CombinePutAlign(uint64_t(n) * 8U * kCombinePlanRelayBytes); | ||
| 365 | + q.final_routes = q.relay_ranges + CombinePutAlign(uint64_t(ranks) * 8U * 64U); | ||
| 366 | + // Weights read the existing dst directly; no dedicated weights table. | ||
| 367 | + q.ring_pages = q.final_routes + CombinePutAlign(uint64_t(n) * 128U); | ||
| 368 | + // Each 64B page begins {scratchBegin,scratchCount,groupCount,source}. | ||
| 369 | + q.relay_page_map = q.ring_pages + | ||
| 370 | + CombinePutAlign(uint64_t(CombineRingPageCapacity(n, ranks)) * 64U); | ||
| 371 | + // Parallel to relay_send[8*N], each packed 8B entry is {sourcePageSeq,rowOffset}. | ||
| 372 | + q.bytes = q.relay_page_map + CombinePutAlign(uint64_t(n) * 8U * 8U); | ||
| 373 | + return q; | ||
| 374 | +} | ||
| 375 | +#undef MOONEP_PLAN_INLINE | ||
| 376 | +} // namespace ascend_moonep | ||
| @@ -943,6 +943,21 @@ __aicore__ void AssembleWeightsFromStagingPhase( | |||
| 943 | WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID3); | 943 | WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID3); |
| 944 | } | 944 | } |
| 945 | 945 | ||
| 946 | +template <typename HiddenT> | ||
| 947 | +__aicore__ inline __gm__ HiddenT* GetPeerMteHidden( | ||
| 948 | + __gm__ HiddenT* local, uint32_t rank, uint32_t peer) | ||
| 949 | +{ | ||
| 950 | + constexpr auto ranks_per_server = ascend_moonep::kMoonEPDispatchRanksPerServer; | ||
| 951 | + if (peer == rank) { | ||
| 952 | + return local; | ||
| 953 | + } | ||
| 954 | + if (rank / ranks_per_server != peer / ranks_per_server || | ||
| 955 | + aclshmemi_get_state()->p2p_device_heap_base[peer] == nullptr) { | ||
| 956 | + return nullptr; | ||
| 957 | + } | ||
| 958 | + return reinterpret_cast<__gm__ HiddenT*>(aclshmem_ptr(local, static_cast<int32_t>(peer))); | ||
| 959 | +} | ||
| 960 | + | ||
| 946 | template <typename HiddenT> | 961 | template <typename HiddenT> |
| 947 | __aicore__ CombineGatherResult GatherToStagingPhase( | 962 | __aicore__ CombineGatherResult GatherToStagingPhase( |
| 948 | LocalTensor<uint8_t> ub_base, | 963 | LocalTensor<uint8_t> ub_base, |
| @@ -1031,8 +1046,10 @@ __aicore__ CombineGatherResult GatherToStagingPhase( | |||
| 1031 | kCombineGrantSignalSlot, | 1046 | kCombineGrantSignalSlot, |
| 1032 | group_token); | 1047 | group_token); |
| 1033 | 1048 | ||
| 1034 | - // Self occupies one balanced group slot but does not consume UDMA. | 1049 | + // The final reduction can read same-server hidden rows directly. |
| 1035 | - if (dest_rank != rank) { | 1050 | + const bool gather_hidden = dest_rank != rank && |
| 1051 | + GetPeerMteHidden(published_hidden, rank, dest_rank) == nullptr; | ||
| 1052 | + if (gather_hidden) { | ||
| 1036 | if (use_vector_slot_select) { | 1053 | if (use_vector_slot_select) { |
| 1037 | // NvS is a power of two, so encoded rank is dst >> log2(NvS). | 1054 | // NvS is a power of two, so encoded rank is dst >> log2(NvS). |
| 1038 | // Negative duplicate encodings remain negative after the shift | 1055 | // Negative duplicate encodings remain negative after the shift |
| @@ -1276,7 +1293,7 @@ __aicore__ CombineGatherResult GatherToStagingPhase( | |||
| 1276 | } | 1293 | } |
| 1277 | } | 1294 | } |
| 1278 | 1295 | ||
| 1279 | - // Weight GET overlaps the already submitted hidden GETs for this peer. | 1296 | + // Weight GET can overlap cross-server hidden GETs for this peer. |
| 1280 | // done is not returned until both UDMA QPs and MTE are complete. | 1297 | // done is not returned until both UDMA QPs and MTE are complete. |
| 1281 | if (dest_rank != rank && with_weights && NvS != 0U) { | 1298 | if (dest_rank != rank && with_weights && NvS != 0U) { |
| 1282 | aclshmemx_mte_get_nbi<float>( | 1299 | aclshmemx_mte_get_nbi<float>( |
| @@ -1288,16 +1305,16 @@ __aicore__ CombineGatherResult GatherToStagingPhase( | |||
| 1288 | static_cast<int32_t>(dest_rank), | 1305 | static_cast<int32_t>(dest_rank), |
| 1289 | EVENT_ID0); | 1306 | EVENT_ID0); |
| 1290 | } | 1307 | } |
| 1291 | - if (dest_rank != rank) { | 1308 | + if (gather_hidden) { |
| 1292 | for (uint32_t qp_idx = 0; | 1309 | for (uint32_t qp_idx = 0; |
| 1293 | qp_idx < kCombineUdmaQpNum; | 1310 | qp_idx < kCombineUdmaQpNum; |
| 1294 | ++qp_idx) { | 1311 | ++qp_idx) { |
| 1295 | aclshmemx_udma_qp_quiet( | 1312 | aclshmemx_udma_qp_quiet( |
| 1296 | static_cast<int32_t>(dest_rank), qp_idx); | 1313 | static_cast<int32_t>(dest_rank), qp_idx); |
| 1297 | } | 1314 | } |
| 1298 | - if (with_weights && NvS != 0U) { | 1315 | + } |
| 1299 | - aclshmemx_mte_quiet(); | 1316 | + if (dest_rank != rank && with_weights && NvS != 0U) { |
| 1300 | - } | 1317 | + aclshmemx_mte_quiet(); |
| 1301 | } | 1318 | } |
| 1302 | 1319 | ||
| 1303 | CombinePublishGroupSignal( | 1320 | CombinePublishGroupSignal( |
| @@ -1383,7 +1400,7 @@ __aicore__ CombineGatherResult GatherToStagingPhase( | |||
| 1383 | template <typename HiddenT> | 1400 | template <typename HiddenT> |
| 1384 | __forceinline__ __aicore__ void Phase3IssueHiddenLoad( | 1401 | __forceinline__ __aicore__ void Phase3IssueHiddenLoad( |
| 1385 | LocalTensor<HiddenT> row, | 1402 | LocalTensor<HiddenT> row, |
| 1386 | - __gm__ HiddenT* published_hidden, | 1403 | + const __gm__ HiddenT* const* local_hidden, |
| 1387 | const __gm__ HiddenT* gathered_hidden, | 1404 | const __gm__ HiddenT* gathered_hidden, |
| 1388 | uint32_t dest_rank, | 1405 | uint32_t dest_rank, |
| 1389 | uint32_t loff, | 1406 | uint32_t loff, |
| @@ -1391,9 +1408,12 @@ __forceinline__ __aicore__ void Phase3IssueHiddenLoad( | |||
| 1391 | uint32_t H, | 1408 | uint32_t H, |
| 1392 | uint32_t rank, | 1409 | uint32_t rank, |
| 1393 | TEventID event_id) { | 1410 | TEventID event_id) { |
| 1411 | + constexpr uint32_t ranks_per_server = ascend_moonep::kMoonEPDispatchRanksPerServer; | ||
| 1412 | + const __gm__ HiddenT* peer_hidden = dest_rank / ranks_per_server == rank / ranks_per_server | ||
| 1413 | + ? local_hidden[dest_rank % ranks_per_server] : nullptr; | ||
| 1394 | const __gm__ HiddenT* source_row = | 1414 | const __gm__ HiddenT* source_row = |
| 1395 | - dest_rank == rank | 1415 | + peer_hidden != nullptr |
| 1396 | - ? published_hidden + static_cast<uint64_t>(loff) * H | 1416 | + ? peer_hidden + static_cast<uint64_t>(loff) * H |
| 1397 | : gathered_hidden + static_cast<uint64_t>(route_idx) * H; | 1417 | : gathered_hidden + static_cast<uint64_t>(route_idx) * H; |
| 1398 | CombineCopyGmToUb(row, source_row, H); | 1418 | CombineCopyGmToUb(row, source_row, H); |
| 1399 | SetFlag<HardEvent::MTE2_V>(event_id); | 1419 | SetFlag<HardEvent::MTE2_V>(event_id); |
| @@ -1485,6 +1505,12 @@ __aicore__ void GatherAccumulatePhase( | |||
| 1485 | 1505 | ||
| 1486 | const __gm__ HiddenT* gathered_hidden = reinterpret_cast<const __gm__ HiddenT*>( | 1506 | const __gm__ HiddenT* gathered_hidden = reinterpret_cast<const __gm__ HiddenT*>( |
| 1487 | workspace); | 1507 | workspace); |
| 1508 | + constexpr uint32_t ranks_per_server = ascend_moonep::kMoonEPDispatchRanksPerServer; | ||
| 1509 | + const uint32_t first_local_rank = rank / ranks_per_server * ranks_per_server; | ||
| 1510 | + const __gm__ HiddenT* local_hidden[ranks_per_server]{}; | ||
| 1511 | + for (uint32_t lane = 0; lane < ranks_per_server && first_local_rank + lane < R; ++lane) { | ||
| 1512 | + local_hidden[lane] = GetPeerMteHidden(published_hidden, rank, first_local_rank + lane); | ||
| 1513 | + } | ||
| 1488 | 1514 | ||
| 1489 | SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID2); | 1515 | SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID2); |
| 1490 | SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID3); | 1516 | SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID3); |
| @@ -1535,7 +1561,7 @@ __aicore__ void GatherAccumulatePhase( | |||
| 1535 | SetFlag<HardEvent::S_MTE2>(EVENT_ID0); | 1561 | SetFlag<HardEvent::S_MTE2>(EVENT_ID0); |
| 1536 | WaitFlag<HardEvent::S_MTE2>(EVENT_ID0); | 1562 | WaitFlag<HardEvent::S_MTE2>(EVENT_ID0); |
| 1537 | Phase3IssueHiddenLoad<HiddenT>( | 1563 | Phase3IssueHiddenLoad<HiddenT>( |
| 1538 | - row0, published_hidden, gathered_hidden, | 1564 | + row0, local_hidden, gathered_hidden, |
| 1539 | src_rank[0], src_loff[0], src_route[0], H, rank, | 1565 | src_rank[0], src_loff[0], src_route[0], H, rank, |
| 1540 | EVENT_ID0); | 1566 | EVENT_ID0); |
| 1541 | } | 1567 | } |
| @@ -1562,7 +1588,7 @@ __aicore__ void GatherAccumulatePhase( | |||
| 1562 | pong_pending = false; | 1588 | pong_pending = false; |
| 1563 | } | 1589 | } |
| 1564 | Phase3IssueHiddenLoad<HiddenT>( | 1590 | Phase3IssueHiddenLoad<HiddenT>( |
| 1565 | - next_row, published_hidden, gathered_hidden, | 1591 | + next_row, local_hidden, gathered_hidden, |
| 1566 | src_rank[next_i], src_loff[next_i], | 1592 | src_rank[next_i], src_loff[next_i], |
| 1567 | src_route[next_i], H, rank, next_ev); | 1593 | src_route[next_i], H, rank, next_ev); |
| 1568 | } | 1594 | } |
| @@ -1613,7 +1639,7 @@ __aicore__ void GatherAccumulatePhase( | |||
| 1613 | SetFlag<HardEvent::S_MTE2>(EVENT_ID0); | 1639 | SetFlag<HardEvent::S_MTE2>(EVENT_ID0); |
| 1614 | WaitFlag<HardEvent::S_MTE2>(EVENT_ID0); | 1640 | WaitFlag<HardEvent::S_MTE2>(EVENT_ID0); |
| 1615 | Phase3IssueHiddenLoad<HiddenT>( | 1641 | Phase3IssueHiddenLoad<HiddenT>( |
| 1616 | - row0, published_hidden, gathered_hidden, | 1642 | + row0, local_hidden, gathered_hidden, |
| 1617 | src_rank[0], src_loff[0], src_route[0], H, rank, | 1643 | src_rank[0], src_loff[0], src_route[0], H, rank, |
| 1618 | EVENT_ID0); | 1644 | EVENT_ID0); |
| 1619 | preload_issued = true; | 1645 | preload_issued = true; |
| @@ -1,6 +1,6 @@ | |||
| 1 | // MoonEP dispatch UDMA kernel with SIMT weight scatter — migrated from shmem_dev_moonep dispatch_moonep. | 1 | // MoonEP dispatch UDMA kernel with SIMT weight scatter — migrated from shmem_dev_moonep dispatch_moonep. |
| 2 | -// Multi-QP UDMA path: scatter hidden via aclshmemx_udma_qp_put_nbi directly | 2 | +// Scatter hidden via MTE within a server and multi-QP UDMA between servers. |
| 3 | -// into hidden_buf; weights are scattered directly to the destination rank's | 3 | +// Weights are scattered directly to the destination rank's |
| 4 | // weights_buf by SIMT threads. DispatchEpilogue expands duplicates in place on | 4 | // weights_buf by SIMT threads. DispatchEpilogue expands duplicates in place on |
| 5 | // hidden_buf; QP signals use a dedicated sync_buffer. | 5 | // hidden_buf; QP signals use a dedicated sync_buffer. |
| 6 | // | 6 | // |
| @@ -58,6 +58,7 @@ constexpr uint32_t kWeightSimtThreadCount = kWeightsPerGmConflictGroup; | |||
| 58 | // Epilogue metadata tile stays a fixed 16KiB, independent of Weight slot size. | 58 | // Epilogue metadata tile stays a fixed 16KiB, independent of Weight slot size. |
| 59 | constexpr uint32_t kMteUbBytes = 16 * 1024; | 59 | constexpr uint32_t kMteUbBytes = 16 * 1024; |
| 60 | constexpr uint32_t kLocalCopyTileBytes = 16 * 1024; | 60 | constexpr uint32_t kLocalCopyTileBytes = 16 * 1024; |
| 61 | +constexpr uint32_t kLocalCopyBufferBytes = 24 * 1024; | ||
| 61 | constexpr uint32_t slotChunkCount = 8192; | 62 | constexpr uint32_t slotChunkCount = 8192; |
| 62 | constexpr uint32_t kSlotTensorBytes = slotChunkCount * sizeof(int32_t); | 63 | constexpr uint32_t kSlotTensorBytes = slotChunkCount * sizeof(int32_t); |
| 63 | constexpr uint32_t kSlotCompareMaskBytes = ((slotChunkCount / 8 + 31) / 32) * 32; | 64 | constexpr uint32_t kSlotCompareMaskBytes = ((slotChunkCount / 8 + 31) / 32) * 32; |
| @@ -111,10 +112,6 @@ constexpr uint32_t kMaxDispatchAivCount = 32; | |||
| 111 | constexpr bool kEnableParallelTokenWeight = true; | 112 | constexpr bool kEnableParallelTokenWeight = true; |
| 112 | constexpr int64_t kGroupSyncFlagBytes = 512; | 113 | constexpr int64_t kGroupSyncFlagBytes = 512; |
| 113 | constexpr uint32_t kGroupSyncRoundCount = 4; | 114 | constexpr uint32_t kGroupSyncRoundCount = 4; |
| 114 | -constexpr uint32_t kGroupSyncPhasesPerGroup = 2; | ||
| 115 | -constexpr uint32_t kGroupSyncCompletionPhase = 0; | ||
| 116 | -constexpr uint32_t kGroupSyncDonePhase = 1; | ||
| 117 | -constexpr int32_t kStrictGroupSyncMaxWorldSize = 64; | ||
| 118 | static_assert(kPeerSyncFlagBytes >= sizeof(uint64_t)); | 115 | static_assert(kPeerSyncFlagBytes >= sizeof(uint64_t)); |
| 119 | static_assert(kPeerSyncFlagBytes % sizeof(uint64_t) == 0); | 116 | static_assert(kPeerSyncFlagBytes % sizeof(uint64_t) == 0); |
| 120 | static_assert(kGroupSyncFlagBytes >= sizeof(uint64_t)); | 117 | static_assert(kGroupSyncFlagBytes >= sizeof(uint64_t)); |
| @@ -135,7 +132,7 @@ static_assert(kWeightGmConflictGroupBytes % sizeof(float) == 0); | |||
| 135 | static_assert(kWeightSimtThreadCount == 128); | 132 | static_assert(kWeightSimtThreadCount == 128); |
| 136 | static_assert(kDuplicateHiddenStagingBytes <= kSlotSelectUbBytes); | 133 | static_assert(kDuplicateHiddenStagingBytes <= kSlotSelectUbBytes); |
| 137 | // SIMT VF also needs the framework-reserved 8KiB immediate data UB. | 134 | // SIMT VF also needs the framework-reserved 8KiB immediate data UB. |
| 138 | -static_assert(kUdmaWqeScratchBytes + kMteUbBytes + kLocalCopyTileBytes + kSlotSelectUbBytes <= | 135 | +static_assert(kUdmaWqeScratchBytes + kMteUbBytes + kLocalCopyBufferBytes + kSlotSelectUbBytes <= |
| 139 | kAivUbCapacityBytes - 8 * 1024); | 136 | kAivUbCapacityBytes - 8 * 1024); |
| 140 | 137 | ||
| 141 | // Alignment of the routes processed per chunk. | 138 | // Alignment of the routes processed per chunk. |
| @@ -237,22 +234,6 @@ __aicore__ inline __gm__ uint64_t *GetGroupSyncFlag( | |||
| 237 | return reinterpret_cast<__gm__ uint64_t *>(group_sync_buffer + flag_index * kGroupSyncFlagBytes); | 234 | return reinterpret_cast<__gm__ uint64_t *>(group_sync_buffer + flag_index * kGroupSyncFlagBytes); |
| 238 | } | 235 | } |
| 239 | 236 | ||
| 240 | -// Group sync tokens increase monotonically: init, then per-group completion, then per-group done. | ||
| 241 | -__aicore__ inline uint64_t GetGroupSyncInitToken(uint64_t magic, uint32_t group_count) | ||
| 242 | -{ | ||
| 243 | - const uint64_t token_count = static_cast<uint64_t>(group_count) * kGroupSyncPhasesPerGroup + 1U; | ||
| 244 | - return magic * token_count + 1U; | ||
| 245 | -} | ||
| 246 | - | ||
| 247 | -__aicore__ inline uint64_t GetGroupSyncPhaseToken( | ||
| 248 | - uint64_t magic, uint32_t group, uint32_t group_count, uint32_t phase) | ||
| 249 | -{ | ||
| 250 | - const uint64_t token_count = static_cast<uint64_t>(group_count) * kGroupSyncPhasesPerGroup + 1U; | ||
| 251 | - const uint64_t group_token_offset = | ||
| 252 | - static_cast<uint64_t>(group) * kGroupSyncPhasesPerGroup + phase + 2U; | ||
| 253 | - return magic * token_count + group_token_offset; | ||
| 254 | -} | ||
| 255 | - | ||
| 256 | // Active AIVs use a four-round dissemination barrier; every flag always has one writer and one reader. | 237 | // Active AIVs use a four-round dissemination barrier; every flag always has one writer and one reader. |
| 257 | __aicore__ inline void SyncActiveAivs(uint32_t aiv_index, uint32_t active_aiv_count, | 238 | __aicore__ inline void SyncActiveAivs(uint32_t aiv_index, uint32_t active_aiv_count, |
| 258 | uint64_t sync_token, __gm__ uint8_t *group_sync_buffer) | 239 | uint64_t sync_token, __gm__ uint8_t *group_sync_buffer) |
| @@ -567,10 +548,10 @@ __aicore__ inline void IssueUbBytesToGm(GM_ADDR destination_gm, | |||
| 567 | AscendC::DataCopyPad(destination_tensor, source_ub, copy_parameters); | 548 | AscendC::DataCopyPad(destination_tensor, source_ub, copy_parameters); |
| 568 | } | 549 | } |
| 569 | 550 | ||
| 570 | -// Each Token AIV initializes its own completion/credit cachelines, then does one local strict sync. | 551 | +// Join the token AIVs once after initializing the completion and credit cachelines. |
| 571 | __aicore__ inline void PrepareTokenScatterPeerSignals(int32_t current_rank, | 552 | __aicore__ inline void PrepareTokenScatterPeerSignals(int32_t current_rank, |
| 572 | uint32_t group_rank_index, uint64_t magic, uint32_t active_qp_count, | 553 | uint32_t group_rank_index, uint64_t magic, uint32_t active_qp_count, |
| 573 | - uint32_t active_aiv_count, uint32_t group_count, | 554 | + uint32_t active_aiv_count, |
| 574 | __gm__ uint8_t *sync_buffer, __gm__ uint8_t *group_sync_buffer) | 555 | __gm__ uint8_t *sync_buffer, __gm__ uint8_t *group_sync_buffer) |
| 575 | { | 556 | { |
| 576 | // Each active QP gets its own completion cacheline. | 557 | // Each active QP gets its own completion cacheline. |
| @@ -584,8 +565,7 @@ __aicore__ inline void PrepareTokenScatterPeerSignals(int32_t current_rank, | |||
| 584 | *credit_flag = 0; | 565 | *credit_flag = 0; |
| 585 | dcci_cacheline(reinterpret_cast<__gm__ uint8_t *>(credit_flag)); | 566 | dcci_cacheline(reinterpret_cast<__gm__ uint8_t *>(credit_flag)); |
| 586 | 567 | ||
| 587 | - SyncActiveAivs(group_rank_index, active_aiv_count, | 568 | + SyncActiveAivs(group_rank_index, active_aiv_count, magic, group_sync_buffer); |
| 588 | - GetGroupSyncInitToken(magic, group_count), group_sync_buffer); | ||
| 589 | } | 569 | } |
| 590 | 570 | ||
| 591 | // Each active AIV polls only the credit its current target peer published for this source rank. | 571 | // Each active AIV polls only the credit its current target peer published for this source rank. |
| @@ -615,24 +595,30 @@ __aicore__ inline void WaitPeerCompletionSignal(int32_t incoming_peer, | |||
| 615 | } | 595 | } |
| 616 | } | 596 | } |
| 617 | 597 | ||
| 618 | -// This AIV appends SO on every active QP of the current dst using its own completion cachelines. | 598 | +// Use the same completion slots for local MTE and cross-server UDMA. |
| 619 | __aicore__ inline void PublishPeerCompletionSignal(int32_t dst_rank, | 599 | __aicore__ inline void PublishPeerCompletionSignal(int32_t dst_rank, |
| 620 | - int32_t current_rank, uint32_t group_rank_index, uint32_t active_qp_count, | 600 | + int32_t current_rank, uint32_t group_rank_index, uint32_t active_qp_count, bool mte_peer, |
| 621 | - __gm__ uint8_t *sync_buffer, __ubuf__ uint8_t *udma_wqe_buffer) | 601 | + __gm__ uint8_t *sync_buffer, __ubuf__ uint8_t *udma_wqe_buffer, |
| 602 | + AscendC::TBuf<AscendC::QuePosition::VECCALC> &local_copy_buffer) | ||
| 622 | { | 603 | { |
| 623 | - // Append one SO per active QP so that QP's RO puts become visible to the destination peer. | 604 | + if (dst_rank == current_rank) { |
| 605 | + return; | ||
| 606 | + } | ||
| 607 | + // Cross-server SO puts make the corresponding QP's RO data puts visible. | ||
| 624 | for (uint32_t i = 0; i < active_qp_count; ++i) { | 608 | for (uint32_t i = 0; i < active_qp_count; ++i) { |
| 625 | const uint32_t qp_idx = kActiveUdmaQpIndices[i]; | 609 | const uint32_t qp_idx = kActiveUdmaQpIndices[i]; |
| 626 | __gm__ uint64_t *signal_flag = GetPeerCompletionFlag( | 610 | __gm__ uint64_t *signal_flag = GetPeerCompletionFlag( |
| 627 | current_rank, group_rank_index, qp_idx, sync_buffer); | 611 | current_rank, group_rank_index, qp_idx, sync_buffer); |
| 628 | 612 | ||
| 629 | - // UDMA has no self put; local data is already done by this AIV. | 613 | + if (mte_peer) { |
| 630 | - if (dst_rank == current_rank) { | 614 | + auto remote_flag = aclshmem_ptr(signal_flag, dst_rank); |
| 631 | - continue; | 615 | + CopyLocalBytes(reinterpret_cast<GM_ADDR>(remote_flag), |
| 616 | + reinterpret_cast<GM_ADDR>(signal_flag), kPeerSyncFlagBytes, local_copy_buffer); | ||
| 617 | + } else { | ||
| 618 | + aclshmemx_udma_qp_put_nbi<uint64_t, PIPE_MTE3, kUdmaSyncSoCqeConfig>( | ||
| 619 | + signal_flag, signal_flag, reinterpret_cast<__ubuf__ uint64_t *>(udma_wqe_buffer), | ||
| 620 | + 1, dst_rank, qp_idx, EVENT_ID0); | ||
| 632 | } | 621 | } |
| 633 | - aclshmemx_udma_qp_put_nbi<uint64_t, PIPE_MTE3, kUdmaSyncSoCqeConfig>( | ||
| 634 | - signal_flag, signal_flag, reinterpret_cast<__ubuf__ uint64_t *>(udma_wqe_buffer), | ||
| 635 | - 1, dst_rank, qp_idx, EVENT_ID0); | ||
| 636 | } | 622 | } |
| 637 | } | 623 | } |
| 638 | 624 | ||
| @@ -670,18 +656,23 @@ __aicore__ inline void PublishNextPeerCredit(uint32_t group, | |||
| 670 | AscendC::WaitFlag<AscendC::HardEvent::MTE3_S>(EVENT_ID0); | 656 | AscendC::WaitFlag<AscendC::HardEvent::MTE3_S>(EVENT_ID0); |
| 671 | } | 657 | } |
| 672 | 658 | ||
| 673 | -// Each active AIV completes its current peer; at <=64P all lock-step at completion and group end. | 659 | +// Each active AIV completes its current peer and releases the next round. |
| 674 | __aicore__ inline void CompleteTokenScatterPeerWithSignal(uint32_t group, int32_t dst_rank, | 660 | __aicore__ inline void CompleteTokenScatterPeerWithSignal(uint32_t group, int32_t dst_rank, |
| 675 | int32_t current_rank, int32_t world_size, uint32_t group_rank_index, | 661 | int32_t current_rank, int32_t world_size, uint32_t group_rank_index, |
| 676 | - uint32_t current_rank_index, uint64_t magic, uint32_t active_qp_count, bool enable_strict_group_sync, | 662 | + uint32_t current_rank_index, uint64_t magic, uint32_t active_qp_count, |
| 677 | - __gm__ uint8_t *sync_buffer, __gm__ uint8_t *group_sync_buffer, | 663 | + bool mte_peer, __gm__ uint8_t *sync_buffer, |
| 678 | __ubuf__ uint8_t *udma_wqe_buffer, | 664 | __ubuf__ uint8_t *udma_wqe_buffer, |
| 679 | AscendC::TBuf<AscendC::QuePosition::VECCALC> &local_copy_buffer) | 665 | AscendC::TBuf<AscendC::QuePosition::VECCALC> &local_copy_buffer) |
| 680 | { | 666 | { |
| 681 | const uint32_t active_aiv_count = GetDispatchGroupWidth(world_size); | 667 | const uint32_t active_aiv_count = GetDispatchGroupWidth(world_size); |
| 682 | const uint32_t group_count = static_cast<uint32_t>(world_size) / active_aiv_count; | 668 | const uint32_t group_count = static_cast<uint32_t>(world_size) / active_aiv_count; |
| 669 | + if (mte_peer && dst_rank != current_rank) { | ||
| 670 | + // The receiver may consume the hidden rows as soon as it sees the signal. | ||
| 671 | + aclshmemx_mte_quiet(); | ||
| 672 | + } | ||
| 683 | PublishPeerCompletionSignal( | 673 | PublishPeerCompletionSignal( |
| 684 | - dst_rank, current_rank, group_rank_index, active_qp_count, sync_buffer, udma_wqe_buffer); | 674 | + dst_rank, current_rank, group_rank_index, active_qp_count, mte_peer, |
| 675 | + sync_buffer, udma_wqe_buffer, local_copy_buffer); | ||
| 685 | 676 | ||
| 686 | // This AIV's index determines the incoming source peer; the current rank's in-group | 677 | // This AIV's index determines the incoming source peer; the current rank's in-group |
| 687 | // index determines the completion slot the remote sender uses. | 678 | // index determines the completion slot the remote sender uses. |
| @@ -689,13 +680,6 @@ __aicore__ inline void CompleteTokenScatterPeerWithSignal(uint32_t group, int32_ | |||
| 689 | WaitPeerCompletionSignal( | 680 | WaitPeerCompletionSignal( |
| 690 | incoming_peer, current_rank_index, magic, active_qp_count, sync_buffer); | 681 | incoming_peer, current_rank_index, magic, active_qp_count, sync_buffer); |
| 691 | 682 | ||
| 692 | - // At <=64P, wait for all of this rank's Token AIVs before any may publish the next-round credit. | ||
| 693 | - if (enable_strict_group_sync) { | ||
| 694 | - SyncActiveAivs(group_rank_index, active_aiv_count, | ||
| 695 | - GetGroupSyncPhaseToken(magic, group, group_count, kGroupSyncCompletionPhase), | ||
| 696 | - group_sync_buffer); | ||
| 697 | - } | ||
| 698 | - | ||
| 699 | // The last group starts no next round, so only the current incoming SO acknowledgement is needed. | 683 | // The last group starts no next round, so only the current incoming SO acknowledgement is needed. |
| 700 | if (group + 1U < group_count) { | 684 | if (group + 1U < group_count) { |
| 701 | PublishNextPeerCredit( | 685 | PublishNextPeerCredit( |
| @@ -703,21 +687,13 @@ __aicore__ inline void CompleteTokenScatterPeerWithSignal(uint32_t group, int32_ | |||
| 703 | sync_buffer, local_copy_buffer); | 687 | sync_buffer, local_copy_buffer); |
| 704 | } | 688 | } |
| 705 | 689 | ||
| 706 | - // The self path has no UDMA WQE and never touches self QP context. | 690 | + if (dst_rank != current_rank && !mte_peer) { |
| 707 | - if (dst_rank != current_rank) { | ||
| 708 | // Incoming completion is done and the next peer released when needed; now reclaim | 691 | // Incoming completion is done and the next peer released when needed; now reclaim |
| 709 | // all CQEs of the current outgoing peer at once. | 692 | // all CQEs of the current outgoing peer at once. |
| 710 | for (uint32_t qp_i = 0; qp_i < active_qp_count; ++qp_i) { | 693 | for (uint32_t qp_i = 0; qp_i < active_qp_count; ++qp_i) { |
| 711 | aclshmemx_udma_qp_quiet(dst_rank, kActiveUdmaQpIndices[qp_i]); | 694 | aclshmemx_udma_qp_quiet(dst_rank, kActiveUdmaQpIndices[qp_i]); |
| 712 | } | 695 | } |
| 713 | } | 696 | } |
| 714 | - | ||
| 715 | - // At <=64P, align credit publish and CQE reclaim at the group tail; larger sizes keep AIVs advancing async. | ||
| 716 | - if (enable_strict_group_sync) { | ||
| 717 | - SyncActiveAivs(group_rank_index, active_aiv_count, | ||
| 718 | - GetGroupSyncPhaseToken(magic, group, group_count, kGroupSyncDonePhase), | ||
| 719 | - group_sync_buffer); | ||
| 720 | - } | ||
| 721 | } | 697 | } |
| 722 | 698 | ||
| 723 | // Enable chunked vector rank select only when the encoded slot count satisfies the shift-decode constraint. | 699 | // Enable chunked vector rank select only when the encoded slot count satisfies the shift-decode constraint. |
| @@ -733,9 +709,68 @@ __aicore__ inline bool CanUseVectorSlotSelect(int64_t route_count) | |||
| 733 | return slot_shift <= 31; | 709 | return slot_shift <= 31; |
| 734 | } | 710 | } |
| 735 | 711 | ||
| 736 | -// Phase 1: vector-select the primary dst and batch-issue token WQEs. | 712 | +__aicore__ inline __gm__ uint8_t *GetPeerMteWindow( |
| 737 | -// template <bool Profile>, matching the UBMEM version, replaces the constexpr switch; | 713 | + __gm__ uint8_t *local, uint32_t rank, uint32_t peer) |
| 738 | -// with Profile=false the GetSystemCycle timing compiles to no-op, counters come via reference params. | 714 | +{ |
| 715 | + constexpr auto ranks_per_server = ascend_moonep::kMoonEPDispatchRanksPerServer; | ||
| 716 | + if (peer == rank) { | ||
| 717 | + return local; | ||
| 718 | + } | ||
| 719 | + if (rank / ranks_per_server != peer / ranks_per_server || | ||
| 720 | + aclshmemi_get_state()->p2p_device_heap_base[peer] == nullptr) { | ||
| 721 | + return nullptr; | ||
| 722 | + } | ||
| 723 | + return reinterpret_cast<__gm__ uint8_t *>(aclshmem_ptr(local, static_cast<int32_t>(peer))); | ||
| 724 | +} | ||
| 725 | + | ||
| 726 | +// Caller supplies an MTE-accessible window and publishes completion after | ||
| 727 | +// the MTE writes are visible to peers. | ||
| 728 | +__aicore__ inline void CopySelectedHiddenMte( | ||
| 729 | + AscendC::LocalTensor<int32_t> selected_routes, AscendC::LocalTensor<int32_t> destinations, | ||
| 730 | + uint32_t selected_count, int64_t chunk_start, int64_t route_count, int64_t topk, uint32_t row_bytes, | ||
| 731 | + __gm__ uint8_t *hidden, __gm__ uint8_t *receive_window, | ||
| 732 | + AscendC::LocalTensor<uint8_t> staging, uint32_t staging_bytes) | ||
| 733 | +{ | ||
| 734 | + if (selected_count == 0) { | ||
| 735 | + return; | ||
| 736 | + } | ||
| 737 | + const uint32_t stride = (row_bytes + 31U) & ~31U; | ||
| 738 | + const bool double_buffer = stride <= staging_bytes / 2U; | ||
| 739 | + const uint32_t bank_bytes = double_buffer ? staging_bytes / 2U : staging_bytes; | ||
| 740 | + const uint32_t rows_per_batch = bank_bytes / stride; | ||
| 741 | + AscendC::GlobalTensor<uint8_t> src, dst; | ||
| 742 | + src.SetGlobalBuffer(hidden); | ||
| 743 | + dst.SetGlobalBuffer(receive_window); | ||
| 744 | + const AscendC::DataCopyExtParams copy{1, row_bytes, 0, 0, 0}; | ||
| 745 | + const AscendC::DataCopyPadExtParams<uint8_t> pad{false, 0, 0, 0}; | ||
| 746 | + AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0); | ||
| 747 | + AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1); | ||
| 748 | + uint32_t bank = 0; | ||
| 749 | + for (uint32_t first = 0; first < selected_count; first += rows_per_batch) { | ||
| 750 | + const uint32_t remaining = selected_count - first; | ||
| 751 | + const uint32_t count = remaining < rows_per_batch ? remaining : rows_per_batch; | ||
| 752 | + const AscendC::TEventID event = bank == 0 ? EVENT_ID0 : EVENT_ID1; | ||
| 753 | + auto buffer = staging[bank * bank_bytes]; | ||
| 754 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(event); | ||
| 755 | + for (uint32_t row = 0; row < count; ++row) { | ||
| 756 | + const int64_t route = selected_routes.GetValue(first + row); | ||
| 757 | + AscendC::DataCopyPad(buffer[row * stride], src[(route / topk) * row_bytes], copy, pad); | ||
| 758 | + } | ||
| 759 | + AscendC::SetFlag<AscendC::HardEvent::MTE2_MTE3>(event); | ||
| 760 | + AscendC::WaitFlag<AscendC::HardEvent::MTE2_MTE3>(event); | ||
| 761 | + for (uint32_t row = 0; row < count; ++row) { | ||
| 762 | + const int64_t route = selected_routes.GetValue(first + row); | ||
| 763 | + const int64_t offset = destinations.GetValue(route - chunk_start) % route_count; | ||
| 764 | + AscendC::DataCopyPad(dst[offset * row_bytes], buffer[row * stride], copy); | ||
| 765 | + } | ||
| 766 | + AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(event); | ||
| 767 | + bank ^= static_cast<uint32_t>(double_buffer); | ||
| 768 | + } | ||
| 769 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0); | ||
| 770 | + AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1); | ||
| 771 | +} | ||
| 772 | + | ||
| 773 | +// Phase 1: vector-select the primary dst and scatter the hidden rows. | ||
| 739 | template <bool Profile> | 774 | template <bool Profile> |
| 740 | __aicore__ inline uint64_t DispatchScatterToken( | 775 | __aicore__ inline uint64_t DispatchScatterToken( |
| 741 | GM_ADDR hidden_gm, | 776 | GM_ADDR hidden_gm, |
| @@ -767,14 +802,12 @@ __aicore__ inline uint64_t DispatchScatterToken( | |||
| 767 | sync_buffer + static_cast<uint64_t>(world_size) * kRankSyncSlotBytes; | 802 | sync_buffer + static_cast<uint64_t>(world_size) * kRankSyncSlotBytes; |
| 768 | const uint32_t group_rank_index = static_cast<uint32_t>(aiv_index) % group_width; | 803 | const uint32_t group_rank_index = static_cast<uint32_t>(aiv_index) % group_width; |
| 769 | const uint32_t current_rank_index = GetGroupRankIndex(current_rank, world_size); | 804 | const uint32_t current_rank_index = GetGroupRankIndex(current_rank, world_size); |
| 770 | - // Rank count is fixed for the kernel run, so compute the strict group sync switch once. | ||
| 771 | - const bool enable_strict_group_sync = world_size <= kStrictGroupSyncMaxWorldSize; | ||
| 772 | uint64_t transferred_bytes = 0; | 805 | uint64_t transferred_bytes = 0; |
| 773 | 806 | ||
| 774 | // Step 0: Token AIVs init their dedicated signals and start issuing after the local strict sync. | 807 | // Step 0: Token AIVs init their dedicated signals and start issuing after the local strict sync. |
| 775 | PrepareTokenScatterPeerSignals( | 808 | PrepareTokenScatterPeerSignals( |
| 776 | current_rank, group_rank_index, magic, active_qp_count, | 809 | current_rank, group_rank_index, magic, active_qp_count, |
| 777 | - group_width, group_count, sync_buffer, group_sync_buffer); | 810 | + group_width, sync_buffer, group_sync_buffer); |
| 778 | 811 | ||
| 779 | if (CanUseVectorSlotSelect(route_count)) { | 812 | if (CanUseVectorSlotSelect(route_count)) { |
| 780 | // Step 1: load dst into UB in chunks, keeping a separate index region for select results so raw dst is not overwritten. | 813 | // Step 1: load dst into UB in chunks, keeping a separate index region for select results so raw dst is not overwritten. |
| @@ -802,6 +835,8 @@ __aicore__ inline uint64_t DispatchScatterToken( | |||
| 802 | for (uint32_t group = 0; group < group_count; ++group) { | 835 | for (uint32_t group = 0; group < group_count; ++group) { |
| 803 | const int32_t dst_rank = GetGroupDstRank(current_rank, world_size, group, group_rank_index); | 836 | const int32_t dst_rank = GetGroupDstRank(current_rank, world_size, group, group_rank_index); |
| 804 | 837 | ||
| 838 | + auto mte_window = GetPeerMteWindow(hidden_window, current_rank, dst_rank); | ||
| 839 | + | ||
| 805 | // Later peers consume only the current-generation credit the destination published for this source rank. | 840 | // Later peers consume only the current-generation credit the destination published for this source rank. |
| 806 | if (group > 0U) { | 841 | if (group > 0U) { |
| 807 | WaitPeerCredit( | 842 | WaitPeerCredit( |
| @@ -856,7 +891,8 @@ __aicore__ inline uint64_t DispatchScatterToken( | |||
| 856 | transferred_bytes += local_selected_count * static_cast<uint64_t>(hidden_row_bytes); | 891 | transferred_bytes += local_selected_count * static_cast<uint64_t>(hidden_row_bytes); |
| 857 | 892 | ||
| 858 | // Step 4: one QP for the whole chunk; the select list only generates and batch-submits WQEs. | 893 | // Step 4: one QP for the whole chunk; the select list only generates and batch-submits WQEs. |
| 859 | - const bool profile_wqe_submit = dst_rank != current_rank && local_selected_count > 0; | 894 | + const bool profile_wqe_submit = mte_window == nullptr && |
| 895 | + dst_rank != current_rank && local_selected_count > 0; | ||
| 860 | uint64_t wqe_submit_start_cycle = UdmaDetailedProfileStart<Profile>(); | 896 | uint64_t wqe_submit_start_cycle = UdmaDetailedProfileStart<Profile>(); |
| 861 | if constexpr (Profile && kEnableDetailedProfile) { | 897 | if constexpr (Profile && kEnableDetailedProfile) { |
| 862 | // Count only remote WQE generation/submission; local copies are not on the send path. | 898 | // Count only remote WQE generation/submission; local copies are not on the send path. |
| @@ -866,9 +902,12 @@ __aicore__ inline uint64_t DispatchScatterToken( | |||
| 866 | } | 902 | } |
| 867 | 903 | ||
| 868 | // dst_rank is constant across the select list; branch once instead of per route. | 904 | // dst_rank is constant across the select list; branch once instead of per route. |
| 869 | - if (dst_rank == current_rank) { | 905 | + if (mte_window != nullptr && hidden_row_bytes <= kLocalCopyTileBytes) { |
| 870 | - // Local copy. Could be folded into the duplicate phase, but kept separate: | 906 | + CopySelectedHiddenMte(selected_route_indices, dst_local, local_selected_count, chunk_start, |
| 871 | - // single-core UB copies there would drag bandwidth down. | 907 | + route_count, num_topk, hidden_row_bytes, hidden, mte_window, local_copy_buffer.Get<uint8_t>(), |
| 908 | + kLocalCopyBufferBytes); | ||
| 909 | + } else if (mte_window != nullptr) { | ||
| 910 | + // Tile hidden rows that are too large for batched MTE. | ||
| 872 | for (uint64_t selected = 0; selected < local_selected_count; ++selected) { | 911 | for (uint64_t selected = 0; selected < local_selected_count; ++selected) { |
| 873 | const int64_t route_index = selected_route_indices.GetValue(selected); | 912 | const int64_t route_index = selected_route_indices.GetValue(selected); |
| 874 | const int64_t token_index = route_index / num_topk; | 913 | const int64_t token_index = route_index / num_topk; |
| @@ -876,7 +915,7 @@ __aicore__ inline uint64_t DispatchScatterToken( | |||
| 876 | const int64_t output_offset = | 915 | const int64_t output_offset = |
| 877 | dst_local.GetValue(route_index - chunk_start) % route_count; | 916 | dst_local.GetValue(route_index - chunk_start) % route_count; |
| 878 | __gm__ uint8_t *hidden_destination = | 917 | __gm__ uint8_t *hidden_destination = |
| 879 | - hidden_window + output_offset * hidden_row_bytes; | 918 | + mte_window + output_offset * hidden_row_bytes; |
| 880 | // The hidden memory type depends on host allocation; the kernel always reads the real token row. | 919 | // The hidden memory type depends on host allocation; the kernel always reads the real token row. |
| 881 | __gm__ uint8_t *hidden_source = hidden + token_index * hidden_row_bytes; | 920 | __gm__ uint8_t *hidden_source = hidden + token_index * hidden_row_bytes; |
| 882 | CopyLocalBytes(reinterpret_cast<GM_ADDR>(hidden_destination), | 921 | CopyLocalBytes(reinterpret_cast<GM_ADDR>(hidden_destination), |
| @@ -935,12 +974,11 @@ __aicore__ inline uint64_t DispatchScatterToken( | |||
| 935 | } | 974 | } |
| 936 | } | 975 | } |
| 937 | 976 | ||
| 938 | - // Step 5: append completion SO on the same dst/QP; after waiting the incoming | 977 | + // Step 5: publish completion with the peer's transport, then release credit. |
| 939 | - // completion and forwarding the next-round credit, reclaim CQEs together. | ||
| 940 | uint64_t sync_start_cycle = UdmaDetailedProfileStart<Profile>(); | 978 | uint64_t sync_start_cycle = UdmaDetailedProfileStart<Profile>(); |
| 941 | CompleteTokenScatterPeerWithSignal(group, dst_rank, | 979 | CompleteTokenScatterPeerWithSignal(group, dst_rank, |
| 942 | current_rank, world_size, group_rank_index, current_rank_index, | 980 | current_rank, world_size, group_rank_index, current_rank_index, |
| 943 | - magic, active_qp_count, enable_strict_group_sync, sync_buffer, group_sync_buffer, | 981 | + magic, active_qp_count, mte_window != nullptr, sync_buffer, |
| 944 | udma_wqe_buffer, local_copy_buffer); | 982 | udma_wqe_buffer, local_copy_buffer); |
| 945 | UdmaDetailedProfileAccumulate<Profile>(sync_start_cycle, sync_cycles); | 983 | UdmaDetailedProfileAccumulate<Profile>(sync_start_cycle, sync_cycles); |
| 946 | } | 984 | } |
| @@ -951,6 +989,7 @@ __aicore__ inline uint64_t DispatchScatterToken( | |||
| 951 | // The scalar path likewise has each active AIV walk its target peers independently. | 989 | // The scalar path likewise has each active AIV walk its target peers independently. |
| 952 | for (uint32_t group = 0; group < group_count; ++group) { | 990 | for (uint32_t group = 0; group < group_count; ++group) { |
| 953 | const int32_t dst_rank = GetGroupDstRank(current_rank, world_size, group, group_rank_index); | 991 | const int32_t dst_rank = GetGroupDstRank(current_rank, world_size, group, group_rank_index); |
| 992 | + auto mte_window = GetPeerMteWindow(hidden_window, current_rank, dst_rank); | ||
| 954 | // Later peers must first consume the dedicated credit the destination forwarded after finishing the previous incoming round. | 993 | // Later peers must first consume the dedicated credit the destination forwarded after finishing the previous incoming round. |
| 955 | if (group > 0U) { | 994 | if (group > 0U) { |
| 956 | WaitPeerCredit( | 995 | WaitPeerCredit( |
| @@ -975,10 +1014,11 @@ __aicore__ inline uint64_t DispatchScatterToken( | |||
| 975 | // Scalar path: once the target rank owned by this core is hit, accumulate the bytes this core actually handles. | 1014 | // Scalar path: once the target rank owned by this core is hit, accumulate the bytes this core actually handles. |
| 976 | transferred_bytes += static_cast<uint64_t>(hidden_row_bytes); | 1015 | transferred_bytes += static_cast<uint64_t>(hidden_row_bytes); |
| 977 | 1016 | ||
| 1017 | + __gm__ uint8_t *destination_window = mte_window != nullptr ? mte_window : hidden_window; | ||
| 978 | __gm__ uint8_t *hidden_destination = | 1018 | __gm__ uint8_t *hidden_destination = |
| 979 | - hidden_window + destination_local_offset * hidden_row_bytes; | 1019 | + destination_window + destination_local_offset * hidden_row_bytes; |
| 980 | __gm__ uint8_t *hidden_source = hidden + token_index * hidden_row_bytes; | 1020 | __gm__ uint8_t *hidden_source = hidden + token_index * hidden_row_bytes; |
| 981 | - if (route_dst_rank == current_rank) { | 1021 | + if (mte_window != nullptr) { |
| 982 | CopyLocalBytes(reinterpret_cast<GM_ADDR>(hidden_destination), | 1022 | CopyLocalBytes(reinterpret_cast<GM_ADDR>(hidden_destination), |
| 983 | reinterpret_cast<GM_ADDR>(hidden_source), hidden_row_bytes, local_copy_buffer); | 1023 | reinterpret_cast<GM_ADDR>(hidden_source), hidden_row_bytes, local_copy_buffer); |
| 984 | } else { | 1024 | } else { |
| @@ -994,11 +1034,11 @@ __aicore__ inline uint64_t DispatchScatterToken( | |||
| 994 | } | 1034 | } |
| 995 | } | 1035 | } |
| 996 | 1036 | ||
| 997 | - // The scalar path keeps the same two-phase sync: completion SO plus dedicated credit. | 1037 | + // The scalar path uses the same completion and credit protocol. |
| 998 | uint64_t sync_start_cycle = UdmaDetailedProfileStart<Profile>(); | 1038 | uint64_t sync_start_cycle = UdmaDetailedProfileStart<Profile>(); |
| 999 | CompleteTokenScatterPeerWithSignal(group, dst_rank, | 1039 | CompleteTokenScatterPeerWithSignal(group, dst_rank, |
| 1000 | current_rank, world_size, group_rank_index, current_rank_index, | 1040 | current_rank, world_size, group_rank_index, current_rank_index, |
| 1001 | - magic, active_qp_count, enable_strict_group_sync, sync_buffer, group_sync_buffer, | 1041 | + magic, active_qp_count, mte_window != nullptr, sync_buffer, |
| 1002 | udma_wqe_buffer, local_copy_buffer); | 1042 | udma_wqe_buffer, local_copy_buffer); |
| 1003 | UdmaDetailedProfileAccumulate<Profile>(sync_start_cycle, sync_cycles); | 1043 | UdmaDetailedProfileAccumulate<Profile>(sync_start_cycle, sync_cycles); |
| 1004 | } | 1044 | } |
| @@ -1317,7 +1357,7 @@ __forceinline__ __aicore__ void MoonEPDispatchUdmaKernelImpl( | |||
| 1317 | AscendC::TBuf<AscendC::QuePosition::VECCALC> slot_select_buffer; | 1357 | AscendC::TBuf<AscendC::QuePosition::VECCALC> slot_select_buffer; |
| 1318 | pipe.InitBuffer(udma_wqe_buffer, DispatchMoonep::kUdmaWqeScratchBytes); | 1358 | pipe.InitBuffer(udma_wqe_buffer, DispatchMoonep::kUdmaWqeScratchBytes); |
| 1319 | pipe.InitBuffer(mte_buffer, DispatchMoonep::kMteUbBytes); | 1359 | pipe.InitBuffer(mte_buffer, DispatchMoonep::kMteUbBytes); |
| 1320 | - pipe.InitBuffer(local_copy_buffer, DispatchMoonep::kLocalCopyTileBytes); | 1360 | + pipe.InitBuffer(local_copy_buffer, DispatchMoonep::kLocalCopyBufferBytes); |
| 1321 | pipe.InitBuffer(slot_select_buffer, DispatchMoonep::kSlotSelectUbBytes); | 1361 | pipe.InitBuffer(slot_select_buffer, DispatchMoonep::kSlotSelectUbBytes); |
| 1322 | __ubuf__ uint8_t *udma_wqe = | 1362 | __ubuf__ uint8_t *udma_wqe = |
| 1323 | reinterpret_cast<__ubuf__ uint8_t *>(udma_wqe_buffer.Get<uint8_t>().GetPhyAddr()); | 1363 | reinterpret_cast<__ubuf__ uint8_t *>(udma_wqe_buffer.Get<uint8_t>().GetPhyAddr()); |
| @@ -657,12 +657,45 @@ BuildSourceDupCorePrefixesSimt( | |||
| 657 | } | 657 | } |
| 658 | } | 658 | } |
| 659 | 659 | ||
| 660 | +template <typename BoundaryPtr> | ||
| 661 | +__simt_callee__ inline void StripeRankPlacement(BoundaryPtr boundaries, int32_t min_rows, | ||
| 662 | + int32_t &ordinal, int32_t &rank, int32_t &previous) { | ||
| 663 | + constexpr int32_t width = ascend_moonep::kMoonEPDispatchRanksPerServer; | ||
| 664 | + const int32_t first = rank / width * width; | ||
| 665 | + const int32_t last = first + width - 1; | ||
| 666 | + const int32_t begin = first == 0 ? 0 : boundaries[first - 1]; | ||
| 667 | + const int32_t end = boundaries[last]; | ||
| 668 | + const int32_t count = end - begin; | ||
| 669 | + if (count < min_rows || (previous == begin && boundaries[rank] == end)) { | ||
| 670 | + return; | ||
| 671 | + } | ||
| 672 | + | ||
| 673 | + // Interleave source ordinals within this server, keeping each rank's | ||
| 674 | + // assigned capacity and each token's destination server unchanged. | ||
| 675 | + constexpr int32_t lanes = 64; | ||
| 676 | + const int32_t relative = ordinal - begin; | ||
| 677 | + const int32_t lane = relative % lanes; | ||
| 678 | + const int32_t remainder = count % lanes; | ||
| 679 | + ordinal = begin + lane * (count / lanes) + (lane < remainder ? lane : remainder) + relative / lanes; | ||
| 680 | + int32_t low = first; | ||
| 681 | + int32_t high = last; | ||
| 682 | + while (low < high) { | ||
| 683 | + const int32_t middle = low + (high - low) / 2; | ||
| 684 | + if (ordinal < boundaries[middle]) { | ||
| 685 | + high = middle; | ||
| 686 | + } else { | ||
| 687 | + low = middle + 1; | ||
| 688 | + } | ||
| 689 | + } | ||
| 690 | + rank = low; | ||
| 691 | + previous = rank == first ? begin : boundaries[rank - 1]; | ||
| 692 | +} | ||
| 693 | + | ||
| 660 | __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileSimt( | 694 | __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileSimt( |
| 661 | __ubuf__ int32_t* workspace, | 695 | __ubuf__ int32_t* workspace, |
| 662 | int32_t context_offset, | 696 | int32_t context_offset, |
| 663 | - int32_t tile_base, | 697 | + uint32_t stripe_rank_placement, |
| 664 | int32_t tile_len) { | 698 | int32_t tile_len) { |
| 665 | - (void)tile_base; | ||
| 666 | const int32_t thread = static_cast<int32_t>(threadIdx.x); | 699 | const int32_t thread = static_cast<int32_t>(threadIdx.x); |
| 667 | __ubuf__ int32_t* context = workspace + context_offset; | 700 | __ubuf__ int32_t* context = workspace + context_offset; |
| 668 | __ubuf__ int32_t* topk_tile = workspace + context[kDstSimtTopkOffset]; | 701 | __ubuf__ int32_t* topk_tile = workspace + context[kDstSimtTopkOffset]; |
| @@ -712,7 +745,7 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileSimt( | |||
| 712 | 745 | ||
| 713 | const int32_t prior_chunk_count = | 746 | const int32_t prior_chunk_count = |
| 714 | chunk == 0 ? 0 : chunk_prefix[(chunk - 1) * hist_stride + expert]; | 747 | chunk == 0 ? 0 : chunk_prefix[(chunk - 1) * hist_stride + expert]; |
| 715 | - const int32_t global_ordinal = | 748 | + int32_t global_ordinal = |
| 716 | ordinal_base[expert] + prior_chunk_count + rank_in_chunk; | 749 | ordinal_base[expert] + prior_chunk_count + rank_in_chunk; |
| 717 | 750 | ||
| 718 | int32_t dst_rank = rank_count - 1; | 751 | int32_t dst_rank = rank_count - 1; |
| @@ -725,6 +758,10 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileSimt( | |||
| 725 | } | 758 | } |
| 726 | previous_boundary = current_boundary; | 759 | previous_boundary = current_boundary; |
| 727 | } | 760 | } |
| 761 | + if (stripe_rank_placement) { | ||
| 762 | + StripeRankPlacement(alloc_cumsum + expert * rank_count, max_tokens_per_rank / 4, | ||
| 763 | + global_ordinal, dst_rank, previous_boundary); | ||
| 764 | + } | ||
| 728 | const int32_t dst_base = expert_offsets[dst_rank * expert_count + expert]; | 765 | const int32_t dst_base = expert_offsets[dst_rank * expert_count + expert]; |
| 729 | dst_tile[route] = dst_rank * max_tokens_per_rank + dst_base + | 766 | dst_tile[route] = dst_rank * max_tokens_per_rank + dst_base + |
| 730 | (global_ordinal - previous_boundary); | 767 | (global_ordinal - previous_boundary); |
| @@ -741,7 +778,8 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileFromGm | |||
| 741 | int32_t tile_len, | 778 | int32_t tile_len, |
| 742 | int32_t rank_count, | 779 | int32_t rank_count, |
| 743 | int32_t expert_count, | 780 | int32_t expert_count, |
| 744 | - int32_t max_tokens_per_rank) { | 781 | + int32_t max_tokens_per_rank, |
| 782 | + uint32_t stripe_rank_placement) { | ||
| 745 | const int32_t thread = static_cast<int32_t>(threadIdx.x); | 783 | const int32_t thread = static_cast<int32_t>(threadIdx.x); |
| 746 | 784 | ||
| 747 | // A single thread assigns stable ordinals in input-route order. The | 785 | // A single thread assigns stable ordinals in input-route order. The |
| @@ -759,7 +797,7 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileFromGm | |||
| 759 | for (int32_t route = thread; route < tile_len; | 797 | for (int32_t route = thread; route < tile_len; |
| 760 | route += kDstSimtMaxThreads) { | 798 | route += kDstSimtMaxThreads) { |
| 761 | const int32_t expert = topk_tile[route]; | 799 | const int32_t expert = topk_tile[route]; |
| 762 | - const int32_t global_ordinal = dst_tile[route]; | 800 | + int32_t global_ordinal = dst_tile[route]; |
| 763 | const int32_t cumsum_base = expert * rank_count; | 801 | const int32_t cumsum_base = expert * rank_count; |
| 764 | 802 | ||
| 765 | int32_t low = 0; | 803 | int32_t low = 0; |
| @@ -773,10 +811,14 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileFromGm | |||
| 773 | } | 811 | } |
| 774 | } | 812 | } |
| 775 | 813 | ||
| 776 | - const int32_t dst_rank = low < rank_count ? low : rank_count - 1; | 814 | + int32_t dst_rank = low < rank_count ? low : rank_count - 1; |
| 777 | - const int32_t previous_boundary = dst_rank == 0 | 815 | + int32_t previous_boundary = dst_rank == 0 |
| 778 | ? 0 | 816 | ? 0 |
| 779 | : alloc_cumsum[cumsum_base + dst_rank - 1]; | 817 | : alloc_cumsum[cumsum_base + dst_rank - 1]; |
| 818 | + if (stripe_rank_placement) { | ||
| 819 | + StripeRankPlacement(alloc_cumsum + cumsum_base, max_tokens_per_rank / 4, | ||
| 820 | + global_ordinal, dst_rank, previous_boundary); | ||
| 821 | + } | ||
| 780 | const int32_t dst_base = | 822 | const int32_t dst_base = |
| 781 | expert_offsets[dst_rank * expert_count + expert]; | 823 | expert_offsets[dst_rank * expert_count + expert]; |
| 782 | dst_tile[route] = dst_rank * max_tokens_per_rank + dst_base + | 824 | dst_tile[route] = dst_rank * max_tokens_per_rank + dst_base + |
| @@ -1588,7 +1630,8 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void planning_ker | |||
| 1588 | GM_ADDR dup_workspace, | 1630 | GM_ADDR dup_workspace, |
| 1589 | GM_ADDR dup_key_workspace, | 1631 | GM_ADDR dup_key_workspace, |
| 1590 | ascend_moonep::PlanningTilingData tiling, | 1632 | ascend_moonep::PlanningTilingData tiling, |
| 1591 | - uint64_t ffts_addr) { | 1633 | + uint64_t ffts_addr, |
| 1634 | + uint32_t stripe_rank_placement) { | ||
| 1592 | (void)ffts_addr; | 1635 | (void)ffts_addr; |
| 1593 | 1636 | ||
| 1594 | const int32_t core_idx = get_block_idx() * get_subblockdim() + get_subblockid(); | 1637 | const int32_t core_idx = get_block_idx() * get_subblockdim() + get_subblockid(); |
| @@ -2757,7 +2800,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void planning_ker | |||
| 2757 | dim3(static_cast<uint32_t>(kDstSimtMaxThreads)), | 2800 | dim3(static_cast<uint32_t>(kDstSimtMaxThreads)), |
| 2758 | (__ubuf__ int32_t*)work_ub.GetPhyAddr(), | 2801 | (__ubuf__ int32_t*)work_ub.GetPhyAddr(), |
| 2759 | dst_layout.context_offset / kInt32Bytes, | 2802 | dst_layout.context_offset / kInt32Bytes, |
| 2760 | - base, | 2803 | + stripe_rank_placement, |
| 2761 | len); | 2804 | len); |
| 2762 | AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID1); | 2805 | AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID1); |
| 2763 | AscendC::PipeBarrier<PIPE_V>(); | 2806 | AscendC::PipeBarrier<PIPE_V>(); |
| @@ -2828,7 +2871,8 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void planning_ker | |||
| 2828 | len, | 2871 | len, |
| 2829 | R, | 2872 | R, |
| 2830 | E, | 2873 | E, |
| 2831 | - NvS); | 2874 | + NvS, |
| 2875 | + stripe_rank_placement); | ||
| 2832 | AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0); | 2876 | AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0); |
| 2833 | AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0); | 2877 | AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0); |
| 2834 | 2878 | ||
| @@ -2975,6 +3019,54 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void planning_ker | |||
| 2975 | 3019 | ||
| 2976 | } | 3020 | } |
| 2977 | 3021 | ||
| 3022 | +extern "C" ASCEND_MOONEP_EXPORT void planning_kernel_do_with_rank_stripe( | ||
| 3023 | + void* stream, | ||
| 3024 | + uint8_t* topk_idx, | ||
| 3025 | + uint8_t* symmetric_buffer, | ||
| 3026 | + uint8_t* dst, | ||
| 3027 | + uint8_t* cu_seqlens, | ||
| 3028 | + uint8_t* experts_to_copy, | ||
| 3029 | + uint8_t* dup_groups, | ||
| 3030 | + uint8_t* dup_loffs, | ||
| 3031 | + uint8_t* dup_counts, | ||
| 3032 | + uint8_t* tpe_all, | ||
| 3033 | + uint8_t* tpe_prefix, | ||
| 3034 | + uint8_t* balance, | ||
| 3035 | + uint8_t* z_tensor, | ||
| 3036 | + uint8_t* alloc_tensor, | ||
| 3037 | + uint8_t* alloc_cumsum, | ||
| 3038 | + uint8_t* expert_offsets, | ||
| 3039 | + uint8_t* core_expert_counts, | ||
| 3040 | + uint8_t* dup_workspace, | ||
| 3041 | + uint8_t* dup_key_workspace, | ||
| 3042 | + uint8_t* tiling_host, | ||
| 3043 | + uint64_t ffts_addr, | ||
| 3044 | + uint32_t stripe_rank_placement) { | ||
| 3045 | + auto* td = reinterpret_cast<ascend_moonep::PlanningTilingData*>(tiling_host); | ||
| 3046 | + planning_kernel<<<td->block_dim, kPlanningUbSizeBytes, stream>>>( | ||
| 3047 | + topk_idx, | ||
| 3048 | + symmetric_buffer, | ||
| 3049 | + dst, | ||
| 3050 | + cu_seqlens, | ||
| 3051 | + experts_to_copy, | ||
| 3052 | + dup_groups, | ||
| 3053 | + dup_loffs, | ||
| 3054 | + dup_counts, | ||
| 3055 | + tpe_all, | ||
| 3056 | + tpe_prefix, | ||
| 3057 | + balance, | ||
| 3058 | + z_tensor, | ||
| 3059 | + alloc_tensor, | ||
| 3060 | + alloc_cumsum, | ||
| 3061 | + expert_offsets, | ||
| 3062 | + core_expert_counts, | ||
| 3063 | + dup_workspace, | ||
| 3064 | + dup_key_workspace, | ||
| 3065 | + *td, | ||
| 3066 | + ffts_addr, | ||
| 3067 | + stripe_rank_placement); | ||
| 3068 | +} | ||
| 3069 | + | ||
| 2978 | extern "C" ASCEND_MOONEP_EXPORT void planning_kernel_do( | 3070 | extern "C" ASCEND_MOONEP_EXPORT void planning_kernel_do( |
| 2979 | void* stream, | 3071 | void* stream, |
| 2980 | uint8_t* topk_idx, | 3072 | uint8_t* topk_idx, |
| @@ -2997,26 +3089,9 @@ extern "C" ASCEND_MOONEP_EXPORT void planning_kernel_do( | |||
| 2997 | uint8_t* dup_key_workspace, | 3089 | uint8_t* dup_key_workspace, |
| 2998 | uint8_t* tiling_host, | 3090 | uint8_t* tiling_host, |
| 2999 | uint64_t ffts_addr) { | 3091 | uint64_t ffts_addr) { |
| 3000 | - auto* td = reinterpret_cast<ascend_moonep::PlanningTilingData*>(tiling_host); | 3092 | + planning_kernel_do_with_rank_stripe( |
| 3001 | - planning_kernel<<<td->block_dim, kPlanningUbSizeBytes, stream>>>( | 3093 | + stream, topk_idx, symmetric_buffer, dst, cu_seqlens, experts_to_copy, |
| 3002 | - topk_idx, | 3094 | + dup_groups, dup_loffs, dup_counts, tpe_all, tpe_prefix, balance, z_tensor, |
| 3003 | - symmetric_buffer, | 3095 | + alloc_tensor, alloc_cumsum, expert_offsets, core_expert_counts, |
| 3004 | - dst, | 3096 | + dup_workspace, dup_key_workspace, tiling_host, ffts_addr, 0); |
| 3005 | - cu_seqlens, | ||
| 3006 | - experts_to_copy, | ||
| 3007 | - dup_groups, | ||
| 3008 | - dup_loffs, | ||
| 3009 | - dup_counts, | ||
| 3010 | - tpe_all, | ||
| 3011 | - tpe_prefix, | ||
| 3012 | - balance, | ||
| 3013 | - z_tensor, | ||
| 3014 | - alloc_tensor, | ||
| 3015 | - alloc_cumsum, | ||
| 3016 | - expert_offsets, | ||
| 3017 | - core_expert_counts, | ||
| 3018 | - dup_workspace, | ||
| 3019 | - dup_key_workspace, | ||
| 3020 | - *td, | ||
| 3021 | - ffts_addr); | ||
| 3022 | } | 3097 | } |
| @@ -11,7 +11,9 @@ dispatch-epilogue / combine-prologue steps are folded into ``DispatchOp`` and | |||
| 11 | import torch | 11 | import torch |
| 12 | 12 | ||
| 13 | from .kernel_op import KernelOp | 13 | from .kernel_op import KernelOp |
| 14 | +from .planning import RANKS_PER_SERVER | ||
| 14 | from .launchers import ( | 15 | from .launchers import ( |
| 16 | + _env_use_udma, | ||
| 15 | launch_combine_op, | 17 | launch_combine_op, |
| 16 | launch_dispatch_op, | 18 | launch_dispatch_op, |
| 17 | launch_dispatch_profile_op, | 19 | launch_dispatch_profile_op, |
| @@ -71,6 +73,10 @@ class PlanningOp(KernelOp): | |||
| 71 | B = int(ctx["B"]) | 73 | B = int(ctx["B"]) |
| 72 | N = S * K | 74 | N = S * K |
| 73 | NvS = int(ctx["NvS"]) | 75 | NvS = int(ctx["NvS"]) |
| 76 | + # Planning output capacity depends on the dedup domain; rank and server share the same operator entry. | ||
| 77 | + server_dedup = plan.dedup_mode == "server" | ||
| 78 | + dup_capacity = RANKS_PER_SERVER * NvS if server_dedup else NvS | ||
| 79 | + count_size = R + 2 if server_dedup else 2 | ||
| 74 | _collect_inputs( | 80 | _collect_inputs( |
| 75 | "PlanningOp", | 81 | "PlanningOp", |
| 76 | tensors=( | 82 | tensors=( |
| @@ -82,8 +88,8 @@ class PlanningOp(KernelOp): | |||
| 82 | ("plan.zero_fill_ranges", plan.zero_fill_ranges, [E + B, 2], torch.int32), | 88 | ("plan.zero_fill_ranges", plan.zero_fill_ranges, [E + B, 2], torch.int32), |
| 83 | ("plan.remote_stats", plan.remote_stats, [2], torch.int32), | 89 | ("plan.remote_stats", plan.remote_stats, [2], torch.int32), |
| 84 | ("plan.dup_groups", plan.dup_groups, [NvS, 3], torch.int32), | 90 | ("plan.dup_groups", plan.dup_groups, [NvS, 3], torch.int32), |
| 85 | - ("plan.dup_loffs", plan.dup_loffs, [NvS], torch.int32), | 91 | + ("plan.dup_loffs", plan.dup_loffs, [dup_capacity], torch.int32), |
| 86 | - ("plan.dup_counts", plan.dup_counts, [2], torch.int32), | 92 | + ("plan.dup_counts", plan.dup_counts, [count_size], torch.int32), |
| 87 | ("ctx.planning_workspace", ctx["planning_workspace"], None, torch.int32), | 93 | ("ctx.planning_workspace", ctx["planning_workspace"], None, torch.int32), |
| 88 | ), | 94 | ), |
| 89 | scalars=(("shmem_instance_id", shmem_instance_id),), | 95 | scalars=(("shmem_instance_id", shmem_instance_id),), |
| @@ -92,7 +98,22 @@ class PlanningOp(KernelOp): | |||
| 92 | workspace = self.sym_workspace() | 98 | workspace = self.sym_workspace() |
| 93 | if workspace is None: | 99 | if workspace is None: |
| 94 | raise RuntimeError("PlanningOp requires a symmetric workspace") | 100 | raise RuntimeError("PlanningOp requires a symmetric workspace") |
| 95 | - launch_planning_op( | 101 | + # Custom NPU writes do not bump Tensor._version; invalidate prepared plans |
| 102 | + # explicitly whenever the supported planner rebuilds this plan's routing. | ||
| 103 | + if server_dedup: | ||
| 104 | + ctx['_combine_plan_generation'] = ctx.get('_combine_plan_generation', 0) + 1 | ||
| 105 | + object.__setattr__(plan, '_planning_generation', ctx['_combine_plan_generation']) | ||
| 106 | + object.__setattr__(plan, 'combine_execution_plan', None) | ||
| 107 | + ctx.pop('_planning_timing_events', None) | ||
| 108 | + if ctx.get('_planning_timing_enabled', False): | ||
| 109 | + from .planning import begin_base_planning_timing | ||
| 110 | + begin_base_planning_timing(ctx, plan) | ||
| 111 | + fused = server_dedup and ctx['_combine_use_udma'] | ||
| 112 | + fused_timing = None | ||
| 113 | + if fused: | ||
| 114 | + from .planning import begin_fused_combine_plan | ||
| 115 | + fused_timing = begin_fused_combine_plan() | ||
| 116 | + storage = launch_planning_op( | ||
| 96 | topk_flat, | 117 | topk_flat, |
| 97 | plan.dst, | 118 | plan.dst, |
| 98 | cu_seqlens, | 119 | cu_seqlens, |
| @@ -111,7 +132,19 @@ class PlanningOp(KernelOp): | |||
| 111 | int(self.num_sms), | 132 | int(self.num_sms), |
| 112 | rank, | 133 | rank, |
| 113 | R, | 134 | R, |
| 135 | + server_dedup, | ||
| 136 | + combine_workspace=ctx['combine_workspace'] if fused else None, | ||
| 137 | + hidden_size=int(ctx['H']) if fused else 0, | ||
| 138 | + use_udma=_env_use_udma('dispatch'), | ||
| 114 | ) | 139 | ) |
| 140 | + # One planning kernel produces routing AND combine tables. This only | ||
| 141 | + # attaches its output/event; it does not launch a second kernel. | ||
| 142 | + if ctx.get('_planning_timing_enabled', False): | ||
| 143 | + from .planning import end_base_planning_timing | ||
| 144 | + end_base_planning_timing(ctx) | ||
| 145 | + if fused: | ||
| 146 | + from .planning import prepare_combine_plan | ||
| 147 | + prepare_combine_plan(ctx, plan, storage=storage, fused_timing=fused_timing) | ||
| 115 | 148 | ||
| 116 | 149 | ||
| 117 | class DispatchOp(KernelOp): | 150 | class DispatchOp(KernelOp): |
| @@ -152,6 +185,7 @@ class DispatchOp(KernelOp): | |||
| 152 | int(ctx["R"]), | 185 | int(ctx["R"]), |
| 153 | int(ctx["rank"]), | 186 | int(ctx["rank"]), |
| 154 | num_sms=self.num_sms, | 187 | num_sms=self.num_sms, |
| 188 | + server_dedup=plan.dedup_mode == "server", | ||
| 155 | ) | 189 | ) |
| 156 | 190 | ||
| 157 | def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan, | 191 | def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan, |
| @@ -177,6 +211,7 @@ class DispatchOp(KernelOp): | |||
| 177 | int(ctx["K"]), | 211 | int(ctx["K"]), |
| 178 | int(ctx["R"]), | 212 | int(ctx["R"]), |
| 179 | int(ctx["rank"]), | 213 | int(ctx["rank"]), |
| 214 | + plan.dedup_mode == "server", | ||
| 180 | ) | 215 | ) |
| 181 | 216 | ||
| 182 | 217 | ||
| @@ -189,12 +224,22 @@ class CombineOp(KernelOp): | |||
| 189 | - reads remote rows from symmetric ``ctx['hidden_buf']`` via shmem_ptr | 224 | - reads remote rows from symmetric ``ctx['hidden_buf']`` via shmem_ptr |
| 190 | - optional weight gather from ``ctx['weights_buf']`` into user-facing | 225 | - optional weight gather from ``ctx['weights_buf']`` into user-facing |
| 191 | output_sk [S, K] fp32 | 226 | output_sk [S, K] fp32 |
| 192 | - - launcher selects native/UDMA from ASCEND_MOONEP_COMBINE_USE_UDMA | 227 | + - launcher selects native / legacy-rank UDMA / server-dedup UDMA |
| 228 | + from the environment and the plan's dedup mode | ||
| 193 | - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule | 229 | - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule |
| 194 | """ | 230 | """ |
| 195 | 231 | ||
| 196 | def compute(self, ctx, output_sh, plan, output_sk=None, | 232 | def compute(self, ctx, output_sh, plan, output_sk=None, |
| 197 | shmem_instance_id: int = 0): | 233 | shmem_instance_id: int = 0): |
| 234 | + server_dedup = plan.dedup_mode == "server" | ||
| 235 | + if server_dedup: | ||
| 236 | + if not ctx['_combine_use_udma']: | ||
| 237 | + raise ValueError('server dedup requires UDMA combine') | ||
| 238 | + from .combine import launch_combine_prepared | ||
| 239 | + if plan.combine_execution_plan is None: | ||
| 240 | + raise ValueError('UDMA combine requires PlanningOp to generate its execution plan first') | ||
| 241 | + return launch_combine_prepared(ctx, output_sh, plan, | ||
| 242 | + plan.combine_execution_plan, output_sk) | ||
| 198 | weight_buf = ( | 243 | weight_buf = ( |
| 199 | ctx["weights_buf"].view(torch.float32) | 244 | ctx["weights_buf"].view(torch.float32) |
| 200 | if output_sk is not None else None | 245 | if output_sk is not None else None |
| @@ -217,6 +262,7 @@ class CombineOp(KernelOp): | |||
| 217 | num_sms=self.num_sms, | 262 | num_sms=self.num_sms, |
| 218 | ) | 263 | ) |
| 219 | 264 | ||
| 265 | + | ||
| 220 | class PrefetchOp(KernelOp): | 266 | class PrefetchOp(KernelOp): |
| 221 | """Corresponds to ``moonep.launch_prefetch``. | 267 | """Corresponds to ``moonep.launch_prefetch``. |
| 222 | 268 | ||
| @@ -5,12 +5,17 @@ Local, CUDA-free mirror of the ``moonep/planning.py`` data structures. | |||
| 5 | they depend only on torch (device comes from ``ctx``), so this module imports | 5 | they depend only on torch (device comes from ``ctx``), so this module imports |
| 6 | cleanly without CUDA/CuTe. The planning *kernel* itself is provided by the | 6 | cleanly without CUDA/CuTe. The planning *kernel* itself is provided by the |
| 7 | ``PlanningOp`` (AscendC kernel migration). | 7 | ``PlanningOp`` (AscendC kernel migration). |
| 8 | + | ||
| 9 | +This module also defines the shape conventions of the Ascend rank/server dedup plans. | ||
| 8 | """ | 10 | """ |
| 9 | 11 | ||
| 10 | -from dataclasses import dataclass | 12 | +from dataclasses import dataclass, field |
| 11 | 13 | ||
| 12 | import torch | 14 | import torch |
| 13 | 15 | ||
| 16 | +# An Ascend server contains 8 ranks; the server dedup protocol sizes its capacity accordingly. | ||
| 17 | +RANKS_PER_SERVER = 8 | ||
| 18 | + | ||
| 14 | 19 | ||
| 15 | @dataclass(frozen=True, slots=True) | 20 | @dataclass(frozen=True, slots=True) |
| 16 | class MoonEPCommPlan: | 21 | class MoonEPCommPlan: |
| @@ -28,9 +33,15 @@ class MoonEPCommPlan: | |||
| 28 | # Dedup structures materialized by the dispatch builder and consumed by the | 33 | # Dedup structures materialized by the dispatch builder and consumed by the |
| 29 | # dispatch epilogue / combine prologue. dup_counts = [n_groups, n_dup_loffs]; | 34 | # dispatch epilogue / combine prologue. dup_counts = [n_groups, n_dup_loffs]; |
| 30 | # only the compact prefix of dup_groups/dup_loffs is valid. | 35 | # only the compact prefix of dup_groups/dup_loffs is valid. |
| 36 | + # Server mode additionally stores full destination encodings and [G,D,P...]; the counts shape tells the modes apart. | ||
| 31 | dup_groups: torch.Tensor | 37 | dup_groups: torch.Tensor |
| 32 | dup_loffs: torch.Tensor | 38 | dup_loffs: torch.Tensor |
| 33 | dup_counts: torch.Tensor | 39 | dup_counts: torch.Tensor |
| 40 | + # Produced by PlanningOp for UDMA combine; clone() copies its immutable tables. | ||
| 41 | + combine_execution_plan: object | None = field(default=None, repr=False, compare=False) | ||
| 42 | + # Native routing writes do not advance Tensor._version. Track this plan only, | ||
| 43 | + # so rebuilding a different plan does not invalidate independent snapshots. | ||
| 44 | + _planning_generation: int = field(default=0, repr=False, compare=False) | ||
| 34 | 45 | ||
| 35 | def __post_init__(self) -> None: | 46 | def __post_init__(self) -> None: |
| 36 | N = int(self.N) | 47 | N = int(self.N) |
| @@ -38,6 +49,11 @@ class MoonEPCommPlan: | |||
| 38 | E = int(self.E) | 49 | E = int(self.E) |
| 39 | B = int(self.B) | 50 | B = int(self.B) |
| 40 | NvS = int(self.NvS) | 51 | NvS = int(self.NvS) |
| 52 | + server_dedup = self.dedup_mode == "server" | ||
| 53 | + assert NvS >= N and (not server_dedup or NvS == N), "invalid NvS for the selected dedup mode" | ||
| 54 | + # Server mode requires a complete 8-rank board; rank mode keeps the original small-scale test capability. | ||
| 55 | + if server_dedup: | ||
| 56 | + assert R > 0 and R % RANKS_PER_SERVER == 0 | ||
| 41 | assert self.dst.dtype == torch.int32 and self.dst.is_contiguous() | 57 | assert self.dst.dtype == torch.int32 and self.dst.is_contiguous() |
| 42 | assert self.dst.numel() == N | 58 | assert self.dst.numel() == N |
| 43 | assert self.experts_to_copy.dtype == torch.int32 and self.experts_to_copy.is_contiguous() | 59 | assert self.experts_to_copy.dtype == torch.int32 and self.experts_to_copy.is_contiguous() |
| @@ -49,14 +65,30 @@ class MoonEPCommPlan: | |||
| 49 | assert self.dup_groups.dtype == torch.int32 and self.dup_groups.is_contiguous() | 65 | assert self.dup_groups.dtype == torch.int32 and self.dup_groups.is_contiguous() |
| 50 | assert tuple(self.dup_groups.shape) == (NvS, 3) | 66 | assert tuple(self.dup_groups.shape) == (NvS, 3) |
| 51 | assert self.dup_loffs.dtype == torch.int32 and self.dup_loffs.is_contiguous() | 67 | assert self.dup_loffs.dtype == torch.int32 and self.dup_loffs.is_contiguous() |
| 52 | - assert tuple(self.dup_loffs.shape) == (NvS,) | 68 | + dup_capacity = RANKS_PER_SERVER * NvS if server_dedup else NvS |
| 69 | + count_size = R + 2 if server_dedup else 2 | ||
| 70 | + assert tuple(self.dup_loffs.shape) == (dup_capacity,) | ||
| 53 | assert self.dup_counts.dtype == torch.int32 and self.dup_counts.is_contiguous() | 71 | assert self.dup_counts.dtype == torch.int32 and self.dup_counts.is_contiguous() |
| 54 | - assert tuple(self.dup_counts.shape) == (2,) | 72 | + assert tuple(self.dup_counts.shape) == (count_size,) |
| 73 | + | ||
| 74 | + @property | ||
| 75 | + def dedup_mode(self) -> str: | ||
| 76 | + """Distinguish the protocol from the counts shape, avoiding a separate mode field that could go stale.""" | ||
| 77 | + return "server" if tuple(self.dup_counts.shape) == (self.R + 2,) else "rank" | ||
| 55 | 78 | ||
| 56 | def clone(self) -> "MoonEPCommPlan": | 79 | def clone(self) -> "MoonEPCommPlan": |
| 57 | - """Deep-clone every plan tensor (mirrors ``moonep.planning``; the tests | 80 | + """Copy routing and any prepared combine tables locally, without communication. |
| 58 | - snapshot plans with ``plan.clone()``).""" | 81 | + |
| 59 | - return type(self)( | 82 | + The snapshot remains bound to the same Buffer and its reusable workspace; |
| 83 | + overlapping combine calls on that workspace are still unsupported. | ||
| 84 | + """ | ||
| 85 | + execution = self.combine_execution_plan | ||
| 86 | + if execution is not None: | ||
| 87 | + execution.validate(execution.owner_ctx, self) | ||
| 88 | + import torch_npu | ||
| 89 | + stream = torch_npu.npu.current_stream() | ||
| 90 | + stream.wait_event(execution.ready) | ||
| 91 | + snapshot = type(self)( | ||
| 60 | dst=self.dst.clone(), | 92 | dst=self.dst.clone(), |
| 61 | experts_to_copy=self.experts_to_copy.clone(), | 93 | experts_to_copy=self.experts_to_copy.clone(), |
| 62 | zero_fill_ranges=self.zero_fill_ranges.clone(), | 94 | zero_fill_ranges=self.zero_fill_ranges.clone(), |
| @@ -70,7 +102,148 @@ class MoonEPCommPlan: | |||
| 70 | B=self.B, | 102 | B=self.B, |
| 71 | NvS=self.NvS, | 103 | NvS=self.NvS, |
| 72 | K=self.K, | 104 | K=self.K, |
| 105 | + _planning_generation=self._planning_generation, | ||
| 73 | ) | 106 | ) |
| 107 | + if execution is not None: | ||
| 108 | + storage = execution.storage.clone() | ||
| 109 | + ready = torch_npu.npu.Event() | ||
| 110 | + ready.record(stream) | ||
| 111 | + for plan in (self, snapshot): | ||
| 112 | + for tensor in (plan.dst, plan.experts_to_copy, plan.zero_fill_ranges, | ||
| 113 | + plan.remote_stats, plan.dup_groups, plan.dup_loffs, | ||
| 114 | + plan.dup_counts): | ||
| 115 | + tensor.record_stream(stream) | ||
| 116 | + execution.storage.record_stream(stream) | ||
| 117 | + storage.record_stream(stream) | ||
| 118 | + copied_execution = CombineExecutionPlan( | ||
| 119 | + storage=storage, routing_id=id(snapshot), workspace=execution.workspace, | ||
| 120 | + key=execution.key, route_stamps=tuple(map(_stamp, _routes(snapshot))), | ||
| 121 | + storage_stamp=_stamp(storage), generation=snapshot._planning_generation, | ||
| 122 | + ready=ready, owner_ctx=execution.owner_ctx, | ||
| 123 | + prepare_begin=execution.prepare_begin, prepare_end=execution.prepare_end, | ||
| 124 | + fused=execution.fused, | ||
| 125 | + ) | ||
| 126 | + object.__setattr__(snapshot, 'combine_execution_plan', copied_execution) | ||
| 127 | + return snapshot | ||
| 128 | + | ||
| 129 | + | ||
| 130 | +# ---- Immutable combine execution-plan ownership and validation ---- | ||
| 131 | +# Reuse across hidden/weight updates is allowed; routing changes require all | ||
| 132 | +# ranks to prepare again, in the same collective order. | ||
| 133 | +def _routes(plan): | ||
| 134 | + return (plan.dst, plan.dup_groups, plan.dup_loffs, plan.dup_counts) | ||
| 135 | + | ||
| 136 | + | ||
| 137 | +def _stamp(tensor): | ||
| 138 | + try: | ||
| 139 | + version = tensor._version | ||
| 140 | + except RuntimeError: # Inference tensors have no version counter. | ||
| 141 | + version = None | ||
| 142 | + return (tensor.data_ptr(), tuple(tensor.shape), tensor.dtype, tensor.device, version) | ||
| 143 | + | ||
| 144 | + | ||
| 145 | +def _key(ctx): | ||
| 146 | + return tuple(int(ctx[name]) for name in ('S', 'H', 'K', 'R', 'rank')) | ||
| 147 | + | ||
| 148 | + | ||
| 149 | +def _execution_key(ctx): | ||
| 150 | + # Keep the five native launch arguments stable. The local cached-plan key | ||
| 151 | + # also binds the private ring ABI and workspace geometry. | ||
| 152 | + from .combine import (COMBINE_RING_PLAN_ABI, COMBINE_RING_STREAMS, | ||
| 153 | + COMBINE_RING_DEPTH, COMBINE_RING_GROUPS_PER_PAGE) | ||
| 154 | + return (*_key(ctx), COMBINE_RING_PLAN_ABI, COMBINE_RING_STREAMS, | ||
| 155 | + COMBINE_RING_DEPTH, COMBINE_RING_GROUPS_PER_PAGE, | ||
| 156 | + int(ctx['combine_workspace'].numel())) | ||
| 157 | + | ||
| 158 | + | ||
| 159 | +@dataclass | ||
| 160 | +class CombineExecutionPlan: | ||
| 161 | + storage: torch.Tensor | ||
| 162 | + routing_id: int # Avoid plan -> execution -> plan cycles retaining large tensors. | ||
| 163 | + workspace: torch.Tensor | ||
| 164 | + key: tuple | ||
| 165 | + route_stamps: tuple | ||
| 166 | + storage_stamp: tuple | ||
| 167 | + generation: int | ||
| 168 | + ready: object | ||
| 169 | + owner_ctx: dict | ||
| 170 | + prepare_begin: object = None | ||
| 171 | + prepare_end: object = None | ||
| 172 | + fused: bool = False | ||
| 173 | + | ||
| 174 | + def validate(self, ctx, plan): | ||
| 175 | + if (ctx.get('_comm_owner_ctx', ctx) is not self.owner_ctx | ||
| 176 | + or _execution_key(ctx) != self.key): | ||
| 177 | + raise ValueError('execution plan belongs to a different Buffer/topology/shape') | ||
| 178 | + if ctx['combine_workspace'].data_ptr() != self.workspace.data_ptr(): | ||
| 179 | + raise ValueError('combine workspace changed; collectively prepare a new plan') | ||
| 180 | + if id(plan) != self.routing_id or tuple(map(_stamp, _routes(plan))) != self.route_stamps: | ||
| 181 | + raise ValueError('routing changed; all ranks must prepare a new execution plan') | ||
| 182 | + if plan._planning_generation != self.generation: | ||
| 183 | + raise ValueError('planning was rerun; all ranks must prepare a new execution plan') | ||
| 184 | + if _stamp(self.storage) != self.storage_stamp: | ||
| 185 | + raise ValueError('execution plan storage was modified') | ||
| 186 | + | ||
| 187 | + | ||
| 188 | +# Optional timing hooks: record on the current stream without synchronizing. | ||
| 189 | +# Benchmark code reads and reports the samples outside timed combine calls. | ||
| 190 | +def begin_base_planning_timing(ctx, plan): | ||
| 191 | + import torch_npu | ||
| 192 | + stream = torch_npu.npu.current_stream() | ||
| 193 | + begin = torch_npu.npu.Event(enable_timing=True) | ||
| 194 | + end = torch_npu.npu.Event(enable_timing=True) | ||
| 195 | + ctx['_planning_timing_events'] = dict( | ||
| 196 | + begin=begin, end=end, stream=stream, routing_id=id(plan), | ||
| 197 | + generation=ctx.get('_combine_plan_generation', 0)) | ||
| 198 | + begin.record(stream) | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +def end_base_planning_timing(ctx): | ||
| 202 | + events = ctx['_planning_timing_events'] | ||
| 203 | + events['end'].record(events['stream']) | ||
| 204 | + | ||
| 205 | + | ||
| 206 | +def begin_fused_combine_plan(): | ||
| 207 | + import torch_npu | ||
| 208 | + stream = torch_npu.npu.current_stream() | ||
| 209 | + begin = torch_npu.npu.Event(enable_timing=True) | ||
| 210 | + end = torch_npu.npu.Event(enable_timing=True) | ||
| 211 | + begin.record(stream) | ||
| 212 | + return begin, end, stream | ||
| 213 | + | ||
| 214 | + | ||
| 215 | +def prepare_combine_plan(ctx, plan, *, storage=None, fused_timing=None): | ||
| 216 | + """Attach fused planning output, or prepare explicitly hand-built routes. | ||
| 217 | + | ||
| 218 | + Also available for callers which construct dst/dup_* manually. All ranks | ||
| 219 | + must call after routing changes; this reads metadata only, not hidden/weights. | ||
| 220 | + """ | ||
| 221 | + from .launchers import _env_use_udma | ||
| 222 | + if not _env_use_udma('combine'): | ||
| 223 | + raise ValueError('execution plans require UDMA combine') | ||
| 224 | + if plan.dedup_mode != "server": | ||
| 225 | + raise ValueError( | ||
| 226 | + 'combine execution plans are a server-level dedup feature; ' | ||
| 227 | + 'rank-level dedup uses the legacy combine kernel') | ||
| 228 | + object.__setattr__(plan, 'combine_execution_plan', None) | ||
| 229 | + fused = fused_timing is not None | ||
| 230 | + begin, end, stream = fused_timing if fused else begin_fused_combine_plan() | ||
| 231 | + tensors = _routes(plan) | ||
| 232 | + if fused: | ||
| 233 | + if storage is None: | ||
| 234 | + raise ValueError('fused planner did not return execution storage') | ||
| 235 | + else: | ||
| 236 | + storage = torch.classes.AscendMoonEP.Planning().prepare_combine_plan( | ||
| 237 | + ctx['combine_workspace'], *tensors, *_key(ctx)) | ||
| 238 | + end.record(stream) | ||
| 239 | + for tensor in (storage, *tensors, ctx['combine_workspace']): | ||
| 240 | + tensor.record_stream(stream) | ||
| 241 | + execution = CombineExecutionPlan(storage, id(plan), ctx['combine_workspace'], _execution_key(ctx), | ||
| 242 | + tuple(map(_stamp, tensors)), _stamp(storage), | ||
| 243 | + plan._planning_generation, end, ctx, begin, end) | ||
| 244 | + execution.fused = fused | ||
| 245 | + object.__setattr__(plan, 'combine_execution_plan', execution) | ||
| 246 | + return execution | ||
| 74 | 247 | ||
| 75 | 248 | ||
| 76 | def _round4(n: int) -> int: | 249 | def _round4(n: int) -> int: |
| @@ -82,6 +255,14 @@ def allocate_planning_outputs(ctx: dict): | |||
| 82 | 255 | ||
| 83 | The plan-owned dedup tensors are allocated here; the Ascend Planning kernel | 256 | The plan-owned dedup tensors are allocated here; the Ascend Planning kernel |
| 84 | materializes their compact prefixes together with ``dup_counts``. | 257 | materializes their compact prefixes together with ``dup_counts``. |
| 258 | + | ||
| 259 | + The dedup domain is a property of the Buffer, fixed at construction: | ||
| 260 | + ``ctx['dedup_mode']`` is ``"rank"`` (the default, same as the local | ||
| 261 | + rank-level code path) or ``"server"``, and ``ctx['ranks_per_server']`` is | ||
| 262 | + the server size (8 by default and currently the only compiled value). | ||
| 263 | + There is deliberately no per-call override: dispatching with a dedup mode | ||
| 264 | + that differs from the Buffer's would mix two workspace/layout contracts. | ||
| 265 | + Synthetic contexts that predate these keys keep the rank-level behavior. | ||
| 85 | """ | 266 | """ |
| 86 | E = ctx['E'] | 267 | E = ctx['E'] |
| 87 | B = ctx.get('B', 0) | 268 | B = ctx.get('B', 0) |
| @@ -89,6 +270,27 @@ def allocate_planning_outputs(ctx: dict): | |||
| 89 | K = ctx['K'] | 270 | K = ctx['K'] |
| 90 | N = S * K | 271 | N = S * K |
| 91 | NvS = ctx['NvS'] | 272 | NvS = ctx['NvS'] |
| 273 | + R = ctx['R'] | ||
| 274 | + dedup_mode = ctx.get('dedup_mode', 'rank') | ||
| 275 | + ranks_per_server = ctx.get('ranks_per_server', RANKS_PER_SERVER) | ||
| 276 | + if dedup_mode not in ('rank', 'server'): | ||
| 277 | + raise ValueError("dedup_mode must be 'rank' or 'server'") | ||
| 278 | + if isinstance(ranks_per_server, bool) or not isinstance(ranks_per_server, int): | ||
| 279 | + raise TypeError("ranks_per_server must be an int") | ||
| 280 | + if ranks_per_server <= 0: | ||
| 281 | + raise ValueError("ranks_per_server must be positive") | ||
| 282 | + server_dedup = dedup_mode == 'server' | ||
| 283 | + # Server mode addresses physical boards; an incomplete board cannot be treated as one dedup domain. | ||
| 284 | + if server_dedup: | ||
| 285 | + if ranks_per_server != RANKS_PER_SERVER: | ||
| 286 | + raise NotImplementedError( | ||
| 287 | + "server dedup kernels are compiled for " | ||
| 288 | + f"{RANKS_PER_SERVER} ranks/server, got {ranks_per_server}") | ||
| 289 | + if R <= 0 or R % ranks_per_server != 0: | ||
| 290 | + raise ValueError( | ||
| 291 | + f"server planning requires R divisible by {ranks_per_server}") | ||
| 292 | + if NvS < N or (server_dedup and NvS != N): | ||
| 293 | + raise ValueError("invalid NvS for the selected dedup mode") | ||
| 92 | dev = ctx['weights_buf'].device | 294 | dev = ctx['weights_buf'].device |
| 93 | 295 | ||
| 94 | # Over-allocate output tensors to a multiple of 4 and then slice, avoiding | 296 | # Over-allocate output tensors to a multiple of 4 and then slice, avoiding |
| @@ -105,8 +307,11 @@ def allocate_planning_outputs(ctx: dict): | |||
| 105 | dup_groups = torch.empty( | 307 | dup_groups = torch.empty( |
| 106 | _round4(NvS * 3), dtype=torch.int32, device=dev | 308 | _round4(NvS * 3), dtype=torch.int32, device=dev |
| 107 | )[:NvS * 3].view(NvS, 3) | 309 | )[:NvS * 3].view(NvS, 3) |
| 108 | - dup_loffs = torch.empty(_round4(NvS), dtype=torch.int32, device=dev)[:NvS] | 310 | + # Only server mode enlarges the secondary list and reserves a group start for each source. |
| 109 | - dup_counts = torch.empty(_round4(2), dtype=torch.int32, device=dev)[:2] | 311 | + dup_capacity = ranks_per_server * NvS if server_dedup else NvS |
| 312 | + count_size = R + 2 if server_dedup else 2 | ||
| 313 | + dup_loffs = torch.empty(_round4(dup_capacity), dtype=torch.int32, device=dev)[:dup_capacity] | ||
| 314 | + dup_counts = torch.empty(_round4(count_size), dtype=torch.int32, device=dev)[:count_size] | ||
| 110 | 315 | ||
| 111 | plan = MoonEPCommPlan( | 316 | plan = MoonEPCommPlan( |
| 112 | dst=dst, | 317 | dst=dst, |
| @@ -0,0 +1,3 @@ | |||
| 1 | +[build-system] | ||
| 2 | +requires = ["setuptools>=64", "wheel"] | ||
| 3 | +build-backend = "setuptools.build_meta" | ||
| @@ -11,6 +11,7 @@ | |||
| 11 | # 2. git submodule update --init --recursive (cann/shmem, catlass) | 11 | # 2. git submodule update --init --recursive (cann/shmem, catlass) |
| 12 | # 3. build cann/shmem for the SoC -> npu_patch/3rdparty/shmem/install | 12 | # 3. build cann/shmem for the SoC -> npu_patch/3rdparty/shmem/install |
| 13 | # 4. cmake -S npu_patch/native -B <build dir> -> ascend_moonep_kernels | 13 | # 4. cmake -S npu_patch/native -B <build dir> -> ascend_moonep_kernels |
| 14 | +# plus ascend_moonep_kernels_server_dedup on Ascend950 | ||
| 14 | # 5. stage the kernel + shmem .so into npu_patch/lib | 15 | # 5. stage the kernel + shmem .so into npu_patch/lib |
| 15 | # 6. pip install -e . (compiles the npu_patch._C NPU extension) | 16 | # 6. pip install -e . (compiles the npu_patch._C NPU extension) |
| 16 | # | 17 | # |
| @@ -136,7 +137,7 @@ if [[ ! -f "${RUNTIME_INCLUDE_DIR}/rt.h" ]]; then | |||
| 136 | fi | 137 | fi |
| 137 | 138 | ||
| 138 | # 2. Dependency trees (git submodules). | 139 | # 2. Dependency trees (git submodules). |
| 139 | -if [[ -d "${ROOT_DIR}/.git" ]]; then | 140 | +if [[ -e "${ROOT_DIR}/.git" ]]; then |
| 140 | echo "[INFO] git submodule update --init --recursive" | 141 | echo "[INFO] git submodule update --init --recursive" |
| 141 | git -C "${ROOT_DIR}" submodule update --init --recursive || \ | 142 | git -C "${ROOT_DIR}" submodule update --init --recursive || \ |
| 142 | echo "[WARN] submodule update failed; continue if 3rdparty is already present." | 143 | echo "[WARN] submodule update failed; continue if 3rdparty is already present." |
| @@ -179,10 +180,16 @@ if [[ -n "${ASCEND_MOONEP_RUNTIME_INCLUDE_DIR:-}" ]]; then | |||
| 179 | CMAKE_ARGS+=(-DASCEND_MOONEP_RUNTIME_INCLUDE_DIR="${ASCEND_MOONEP_RUNTIME_INCLUDE_DIR}") | 180 | CMAKE_ARGS+=(-DASCEND_MOONEP_RUNTIME_INCLUDE_DIR="${ASCEND_MOONEP_RUNTIME_INCLUDE_DIR}") |
| 180 | fi | 181 | fi |
| 181 | cmake "${CMAKE_ARGS[@]}" | 182 | cmake "${CMAKE_ARGS[@]}" |
| 182 | -cmake --build "${BUILD_DIR}" --target ascend_moonep_kernels --parallel | 183 | +kernel_targets=(ascend_moonep_kernels) |
| 184 | +if [[ "${ARCH}" == "a5" ]]; then | ||
| 185 | + kernel_targets+=(ascend_moonep_kernels_server_dedup) | ||
| 186 | +fi | ||
| 187 | +cmake --build "${BUILD_DIR}" --target "${kernel_targets[@]}" --parallel | ||
| 183 | 188 | ||
| 184 | mkdir -p "${LIB_TARGET}" | 189 | mkdir -p "${LIB_TARGET}" |
| 185 | -cp "${BUILD_DIR}/lib/libascend_moonep_kernels.so" "${LIB_TARGET}/" | 190 | +for target in "${kernel_targets[@]}"; do |
| 191 | + cp "${BUILD_DIR}/lib/lib${target}.so" "${LIB_TARGET}/" | ||
| 192 | +done | ||
| 186 | find "${SHMEM_HOME_PATH}/shmem/lib" \ | 193 | find "${SHMEM_HOME_PATH}/shmem/lib" \ |
| 187 | -maxdepth 1 \( -type f -o -type l \) \( -name "*.so" -o -name "*.so.*" \) \ | 194 | -maxdepth 1 \( -type f -o -type l \) \( -name "*.so" -o -name "*.so.*" \) \ |
| 188 | -exec cp -P {} "${LIB_TARGET}/" \; | 195 | -exec cp -P {} "${LIB_TARGET}/" \; |
| @@ -210,4 +217,6 @@ python -m pip install -e . --no-build-isolation --no-deps | |||
| 210 | popd >/dev/null | 217 | popd >/dev/null |
| 211 | 218 | ||
| 212 | echo "[INFO] Build completed." | 219 | echo "[INFO] Build completed." |
| 213 | -echo "[INFO] Kernel library: ${LIB_TARGET}/libascend_moonep_kernels.so" | 220 | +for target in "${kernel_targets[@]}"; do |
| 221 | + echo "[INFO] Kernel library: ${LIB_TARGET}/lib${target}.so" | ||
| 222 | +done | ||
| @@ -4,6 +4,7 @@ | |||
| 4 | # Usage (the script locates itself; run from the repo root): | 4 | # Usage (the script locates itself; run from the repo root): |
| 5 | # bash npu_patch/scripts/run_test.sh # mte/ubmem engine (default) | 5 | # bash npu_patch/scripts/run_test.sh # mte/ubmem engine (default) |
| 6 | # bash npu_patch/scripts/run_test.sh --use_urma # urma engine (A5/Ascend950 only) | 6 | # bash npu_patch/scripts/run_test.sh --use_urma # urma engine (A5/Ascend950 only) |
| 7 | +# bash npu_patch/scripts/run_test.sh --use_urma --dedup-mode server | ||
| 7 | # bash npu_patch/scripts/run_test.sh --soc_type Ascend910_93 # A3 | 8 | # bash npu_patch/scripts/run_test.sh --soc_type Ascend910_93 # A3 |
| 8 | # BUILD=1 bash npu_patch/scripts/run_test.sh # rebuild _C before running tests | 9 | # BUILD=1 bash npu_patch/scripts/run_test.sh # rebuild _C before running tests |
| 9 | # NPROC=4 RANK_N=4 bash npu_patch/scripts/run_test.sh # set card count | 10 | # NPROC=4 RANK_N=4 bash npu_patch/scripts/run_test.sh # set card count |
| @@ -62,10 +63,16 @@ cd "$REPO_ROOT" | |||
| 62 | # Args / environment | 63 | # Args / environment |
| 63 | # --------------------------------------------------------------------------- | 64 | # --------------------------------------------------------------------------- |
| 64 | USE_URMA=0 | 65 | USE_URMA=0 |
| 66 | +DEDUP_MODE=rank | ||
| 65 | SOC_TYPE="${SOC_TYPE:-Ascend950}" | 67 | SOC_TYPE="${SOC_TYPE:-Ascend950}" |
| 66 | while [[ $# -gt 0 ]]; do | 68 | while [[ $# -gt 0 ]]; do |
| 67 | case "$1" in | 69 | case "$1" in |
| 68 | --use_urma) USE_URMA=1; shift ;; | 70 | --use_urma) USE_URMA=1; shift ;; |
| 71 | + --dedup-mode) | ||
| 72 | + case "${2:-}" in | ||
| 73 | + rank|server) DEDUP_MODE="$2"; shift 2 ;; | ||
| 74 | + *) echo "[ERROR] --dedup-mode requires rank or server"; exit 1 ;; | ||
| 75 | + esac ;; | ||
| 69 | --soc_type|-soc_type) | 76 | --soc_type|-soc_type) |
| 70 | if [[ $# -lt 2 ]]; then | 77 | if [[ $# -lt 2 ]]; then |
| 71 | echo "[ERROR] --soc_type requires a value, for example: --soc_type Ascend950" | 78 | echo "[ERROR] --soc_type requires a value, for example: --soc_type Ascend950" |
| @@ -74,7 +81,7 @@ while [[ $# -gt 0 ]]; do | |||
| 74 | SOC_TYPE="$2"; shift 2 ;; | 81 | SOC_TYPE="$2"; shift 2 ;; |
| 75 | *) | 82 | *) |
| 76 | echo "[ERROR] Unknown argument: $1" | 83 | echo "[ERROR] Unknown argument: $1" |
| 77 | - echo "Usage: bash npu_patch/scripts/run_test.sh [--use_urma] [--soc_type {Ascend910B|Ascend910_93|Ascend950}]" | 84 | + echo "Usage: bash npu_patch/scripts/run_test.sh [--use_urma] [--dedup-mode rank|server] [--soc_type {Ascend910B|Ascend910_93|Ascend950}]" |
| 78 | exit 1 ;; | 85 | exit 1 ;; |
| 79 | esac | 86 | esac |
| 80 | done | 87 | done |
| @@ -87,6 +94,11 @@ case "${SOC_TYPE}" in | |||
| 87 | exit 1 ;; | 94 | exit 1 ;; |
| 88 | esac | 95 | esac |
| 89 | 96 | ||
| 97 | +if [[ "$DEDUP_MODE" == server && "$USE_URMA" != 1 ]]; then | ||
| 98 | + echo "[ERROR] --dedup-mode server requires --use_urma" | ||
| 99 | + exit 1 | ||
| 100 | +fi | ||
| 101 | + | ||
| 90 | # urma/udma ops are A5(SIMT)-only: dispatch_udma uses __simt_vf__ + | 102 | # urma/udma ops are A5(SIMT)-only: dispatch_udma uses __simt_vf__ + |
| 91 | # simt_api/device_sync_functions.h; A2/A3 do not define ASCEND_MOONEP_UDMA. | 103 | # simt_api/device_sync_functions.h; A2/A3 do not define ASCEND_MOONEP_UDMA. |
| 92 | if [ "$USE_URMA" = 1 ] && [ "$SOC_TYPE" != "Ascend950" ]; then | 104 | if [ "$USE_URMA" = 1 ] && [ "$SOC_TYPE" != "Ascend950" ]; then |
| @@ -121,6 +133,10 @@ _count_visible_devices() { | |||
| 121 | VISIBLE="$(_count_visible_devices)" | 133 | VISIBLE="$(_count_visible_devices)" |
| 122 | NPROC="${NPROC:-$VISIBLE}" | 134 | NPROC="${NPROC:-$VISIBLE}" |
| 123 | RANK_N="${RANK_N:-$NPROC}" | 135 | RANK_N="${RANK_N:-$NPROC}" |
| 136 | +if [[ "$DEDUP_MODE" == server ]] && (( NPROC % 8 != 0 || RANK_N % 8 != 0 )); then | ||
| 137 | + echo "[ERROR] Server dedup requires complete eight-rank servers" | ||
| 138 | + exit 1 | ||
| 139 | +fi | ||
| 124 | FAILED=0 | 140 | FAILED=0 |
| 125 | PASSED=0 | 141 | PASSED=0 |
| 126 | 142 | ||
| @@ -205,13 +221,23 @@ if [ "$USE_URMA" = 1 ]; then | |||
| 205 | # dispatch_udma has no --B; dispatch_combine_udma_joint has no --mode/--B. | 221 | # dispatch_udma has no --B; dispatch_combine_udma_joint has no --mode/--B. |
| 206 | # R is RANK_N for all. | 222 | # R is RANK_N for all. |
| 207 | run_cmd "test_moonep_combine_udma_with_plan (kernel)" \ | 223 | run_cmd "test_moonep_combine_udma_with_plan (kernel)" \ |
| 208 | - python test_npu/urma/test_moonep_combine_udma_with_plan.py --mode kernel --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic | 224 | + python test_npu/urma/test_moonep_combine_udma_with_plan.py --mode kernel --combine-engine udma \ |
| 209 | - run_cmd "test_moonep_dispatch_udma_with_plan (kernel)" \ | 225 | + --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic --dedup-mode "$DEDUP_MODE" |
| 210 | - python test_npu/urma/test_moonep_dispatch_udma_with_plan.py --mode kernel --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic | 226 | + for plan_source in golden kernel; do |
| 227 | + run_cmd "test_moonep_dispatch_udma_with_plan ($plan_source plan)" \ | ||
| 228 | + python test_npu/urma/test_moonep_dispatch_udma_with_plan.py --mode kernel --plan-source "$plan_source" \ | ||
| 229 | + --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic --dedup-mode "$DEDUP_MODE" | ||
| 230 | + done | ||
| 211 | run_cmd "test_dispatch_combine_udma_joint" \ | 231 | run_cmd "test_dispatch_combine_udma_joint" \ |
| 212 | - python test_npu/urma/test_dispatch_combine_udma_joint.py --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic | 232 | + python test_npu/urma/test_dispatch_combine_udma_joint.py --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic --dedup-mode "$DEDUP_MODE" |
| 213 | run_cmd "pytest test_npu/urma/test_e2e_urma.py (NPROC=$NPROC)" \ | 233 | run_cmd "pytest test_npu/urma/test_e2e_urma.py (NPROC=$NPROC)" \ |
| 214 | - torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/urma/test_e2e_urma.py | 234 | + torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/urma/test_e2e_urma.py -k "$DEDUP_MODE" |
| 235 | + if [[ "$DEDUP_MODE" == server ]]; then | ||
| 236 | + run_cmd "pytest server dedup QP policy" \ | ||
| 237 | + python -m pytest -q test_npu/buffer_test/test_dedup_env_qp.py | ||
| 238 | + run_cmd "pytest prepared communication buffers (server)" \ | ||
| 239 | + torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/buffer_test/test_buffer_comm_buffers.py -k server | ||
| 240 | + fi | ||
| 215 | else | 241 | else |
| 216 | run_cmd "pytest test_npu/mte/test_grad_reduce.py (NPROC=$NPROC)" \ | 242 | run_cmd "pytest test_npu/mte/test_grad_reduce.py (NPROC=$NPROC)" \ |
| 217 | torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/mte/test_grad_reduce.py | 243 | torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/mte/test_grad_reduce.py |
| @@ -254,4 +280,4 @@ fi | |||
| 254 | 280 | ||
| 255 | log "Summary" | 281 | log "Summary" |
| 256 | echo "PASSED=$PASSED FAILED=$FAILED ENGINE=$ENGINE_KW SOC_TYPE=$SOC_TYPE NPROC=$NPROC" | 282 | echo "PASSED=$PASSED FAILED=$FAILED ENGINE=$ENGINE_KW SOC_TYPE=$SOC_TYPE NPROC=$NPROC" |
| 257 | -[ "$FAILED" -eq 0 ] | 283 | +[ "$FAILED" -eq 0 ] |