Open
feat(npu): merge server dedup to dev_npu #22
szm_thomasAdd on 11 days ago
feat(npu): merge server dedup to dev_npu #22
Open
Total: 42 files changed+15978-551
| @@ -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,52 @@ 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 | + | ||
| 181 | def _route_destinations( | 199 | def _route_destinations( |
| 182 | topk_all: torch.Tensor, | 200 | topk_all: torch.Tensor, |
| 183 | tpe_all: torch.Tensor, | 201 | tpe_all: torch.Tensor, |
| 184 | alloc: torch.Tensor, | 202 | alloc: torch.Tensor, |
| 185 | expert_off: torch.Tensor, | 203 | expert_off: torch.Tensor, |
| 186 | NvS: int, | 204 | NvS: int, |
| 205 | + *, | ||
| 206 | + dedup_mode: str = "rank", | ||
| 207 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 187 | ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: | 208 | ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: |
| 188 | """Expected per-route destination/loff/canonical flags for every rank. | 209 | """Expected per-route destination/loff/canonical flags for every rank. |
| 189 | 210 | ||
| 190 | Returns ``(dest, loff, canonical, raw)``, each ``[R, N]`` with | 211 | Returns ``(dest, loff, canonical, raw)``, each ``[R, N]`` with |
| 191 | ``N = S * K``: destination rank, offset inside the destination layout, | 212 | ``N = S * K``: destination rank, offset inside the destination layout, |
| 192 | - first-route-to-destination flag (canonical vs duplicate) and the | 213 | + first-route-to-dedup-domain flag (canonical vs duplicate) and the |
| 193 | un-encoded ``dest * NvS + loff``. | 214 | un-encoded ``dest * NvS + loff``. |
| 194 | """ | 215 | """ |
| 195 | R, S, K = topk_all.shape | 216 | R, S, K = topk_all.shape |
| 196 | N = S * K | 217 | N = S * K |
| 197 | E = alloc.shape[0] | 218 | E = alloc.shape[0] |
| 219 | + domain_width = ranks_per_server if dedup_mode == "server" else 1 | ||
| 198 | alloc_cumsum = alloc.cumsum(1) | 220 | alloc_cumsum = alloc.cumsum(1) |
| 199 | tpe_cumsum = tpe_all.to(torch.int64).cumsum(0) | 221 | tpe_cumsum = tpe_all.to(torch.int64).cumsum(0) |
| 200 | prev_count = torch.zeros(R, E, dtype=torch.int64) | 222 | prev_count = torch.zeros(R, E, dtype=torch.int64) |
| @@ -225,7 +247,9 @@ def _route_destinations( | |||
| 225 | torch.zeros_like(d), | 247 | torch.zeros_like(d), |
| 226 | ) | 248 | ) |
| 227 | loff[r] = expert_off[d, experts] + g - prev_alloc | 249 | loff[r] = expert_off[d, experts] + g - prev_alloc |
| 228 | - canonical[r] = _first_route_per_destination(d.view(S, K)).reshape(-1) | 250 | + canonical[r] = _first_route_per_domain( |
| 251 | + d.view(S, K), domain_width | ||
| 252 | + ).reshape(-1) | ||
| 229 | 253 | ||
| 230 | raw = dest * NvS + loff | 254 | raw = dest * NvS + loff |
| 231 | return dest, loff, canonical, raw | 255 | return dest, loff, canonical, raw |
| @@ -243,16 +267,34 @@ def dedup_pairs( | |||
| 243 | rank: int, | 267 | rank: int, |
| 244 | S: int, | 268 | S: int, |
| 245 | NvS: int, | 269 | NvS: int, |
| 246 | -) -> tuple[torch.Tensor, tuple[int, int]]: | 270 | + *, |
| 271 | + dedup_mode: str = "rank", | ||
| 272 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 273 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 247 | """Expected dedup table for one destination rank, as semantic pairs. | 274 | """Expected dedup table for one destination rank, as semantic pairs. |
| 248 | 275 | ||
| 249 | - Returns ``(pairs, (n_groups, n_dups))`` where ``pairs`` is a lexicographically | 276 | + Returns ``(pairs, counts)``. ``pairs`` is a ``[n_dups, 2]`` int64 tensor of |
| 250 | - sorted ``[n_dups, 2]`` int64 tensor of ``(primary_loff, duplicate_loff)``. | 277 | + ``(primary_loff, duplicate_address)`` sorted by ``(primary, address)``. |
| 251 | Group order is irrelevant (the kernel assigns it with atomics), so only the | 278 | Group order is irrelevant (the kernel assigns it with atomics), so only the |
| 252 | - ``primary -> {dups}`` mapping is compared. | 279 | + ``primary -> {dups}`` mapping is compared. ``counts`` is |
| 280 | + ``[n_groups, n_dups]`` for ``rank`` dedup and | ||
| 281 | + ``[n_groups, n_dups, P_0 .. P_{R-1}]`` for ``server`` dedup, where ``P_src`` | ||
| 282 | + counts this rank's groups whose token source is below ``src`` (the dispatch | ||
| 283 | + kernel waits on that prefix). | ||
| 284 | + | ||
| 285 | + ``duplicate_address`` is the in-rank loff for ``rank`` dedup and the full | ||
| 286 | + ``dest * NvS + loff`` address for ``server`` dedup, because a server group | ||
| 287 | + may own members on sibling ranks. | ||
| 253 | """ | 288 | """ |
| 254 | R, N = dest.shape | 289 | R, N = dest.shape |
| 255 | K = N // S | 290 | K = N // S |
| 291 | + if dedup_mode == "server": | ||
| 292 | + return _server_dedup_pairs( | ||
| 293 | + dest, loff, canonical, rank, S, NvS, ranks_per_server | ||
| 294 | + ) | ||
| 295 | + if dedup_mode != "rank": | ||
| 296 | + raise ValueError(f"unsupported dedup_mode: {dedup_mode!r}") | ||
| 297 | + | ||
| 256 | src = torch.arange(R, dtype=torch.int64).view(R, 1).expand(R, N) | 298 | 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 | 299 | token = torch.arange(N, dtype=torch.int64).view(1, N) // K |
| 258 | # Group id: (src rank, token, destination rank). | 300 | # Group id: (src rank, token, destination rank). |
| @@ -271,14 +313,79 @@ def dedup_pairs( | |||
| 271 | dup_loffs = loff[dup_mask] | 313 | dup_loffs = loff[dup_mask] |
| 272 | n_dups = int(dup_keys.numel()) | 314 | n_dups = int(dup_keys.numel()) |
| 273 | if n_dups == 0: | 315 | if n_dups == 0: |
| 274 | - empty = torch.zeros(0, 2, dtype=torch.int64) | 316 | + return (torch.zeros(0, 2, dtype=torch.int64), |
| 275 | - return empty, (0, 0) | 317 | + torch.tensor([0, 0], dtype=torch.int64)) |
| 276 | 318 | ||
| 277 | uniq, inverse = torch.unique(dup_keys, return_inverse=True) | 319 | uniq, inverse = torch.unique(dup_keys, return_inverse=True) |
| 278 | pair_primary = primary[uniq][inverse] | 320 | pair_primary = primary[uniq][inverse] |
| 279 | pairs = torch.stack((pair_primary, dup_loffs), dim=1) | 321 | pairs = torch.stack((pair_primary, dup_loffs), dim=1) |
| 280 | pairs = pairs[torch.argsort(pairs[:, 0] * NvS + pairs[:, 1])] | 322 | pairs = pairs[torch.argsort(pairs[:, 0] * NvS + pairs[:, 1])] |
| 281 | - return pairs, (int(uniq.numel()), n_dups) | 323 | + counts = torch.tensor([int(uniq.numel()), n_dups], dtype=torch.int64) |
| 324 | + return pairs, counts | ||
| 325 | + | ||
| 326 | + | ||
| 327 | +def _server_dedup_pairs( | ||
| 328 | + dest: torch.Tensor, | ||
| 329 | + loff: torch.Tensor, | ||
| 330 | + canonical: torch.Tensor, | ||
| 331 | + rank: int, | ||
| 332 | + S: int, | ||
| 333 | + NvS: int, | ||
| 334 | + ranks_per_server: int, | ||
| 335 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 336 | + """Server-dedup tables for one destination rank (see :func:`dedup_pairs`). | ||
| 337 | + | ||
| 338 | + Groups are keyed by ``(source rank, token, destination server)`` and owned | ||
| 339 | + by the group's primary destination rank; every non-primary member of an | ||
| 340 | + owned group appears in ``dup_loffs`` as a full address, including members | ||
| 341 | + that live on sibling ranks. | ||
| 342 | + """ | ||
| 343 | + R, N = dest.shape | ||
| 344 | + K = N // S | ||
| 345 | + num_domains = (R + ranks_per_server - 1) // ranks_per_server | ||
| 346 | + domain = dest // ranks_per_server | ||
| 347 | + token = torch.arange(N, dtype=torch.int64).view(1, N) // K | ||
| 348 | + full = (dest * NvS + loff).reshape(-1) | ||
| 349 | + | ||
| 350 | + per_source_groups = torch.zeros(R, dtype=torch.int64) | ||
| 351 | + pieces: list[torch.Tensor] = [] | ||
| 352 | + for source in range(R): | ||
| 353 | + canon = canonical[source].reshape(-1) | ||
| 354 | + # Group key inside one source: (local token, destination server). | ||
| 355 | + key = token[0] * num_domains + domain[source].reshape(-1) | ||
| 356 | + size = S * num_domains | ||
| 357 | + prim_loff = torch.zeros(size, dtype=torch.int64) | ||
| 358 | + prim_dest = torch.zeros(size, dtype=torch.int64) | ||
| 359 | + prim_seen = torch.zeros(size, dtype=torch.bool) | ||
| 360 | + prim_loff[key[canon]] = loff[source].reshape(-1)[canon] | ||
| 361 | + prim_dest[key[canon]] = dest[source].reshape(-1)[canon] | ||
| 362 | + prim_seen[key[canon]] = True | ||
| 363 | + | ||
| 364 | + dups = torch.nonzero(~canon, as_tuple=False).flatten() | ||
| 365 | + if dups.numel() == 0: | ||
| 366 | + continue | ||
| 367 | + dup_key = key[dups] | ||
| 368 | + owned = prim_seen[dup_key] & (prim_dest[dup_key] == rank) | ||
| 369 | + if not bool(owned.any()): | ||
| 370 | + continue | ||
| 371 | + dup_key = dup_key[owned] | ||
| 372 | + dup_index = source * N + dups[owned] | ||
| 373 | + pieces.append(torch.stack( | ||
| 374 | + (prim_loff[dup_key], full[dup_index]), dim=1)) | ||
| 375 | + per_source_groups[source] = int(torch.unique(dup_key).numel()) | ||
| 376 | + | ||
| 377 | + if pieces: | ||
| 378 | + pairs = torch.cat(pieces) | ||
| 379 | + pairs = pairs[torch.argsort(pairs[:, 0] * (NvS * R) + pairs[:, 1])] | ||
| 380 | + else: | ||
| 381 | + pairs = torch.zeros(0, 2, dtype=torch.int64) | ||
| 382 | + prefixes = per_source_groups.cumsum(0) - per_source_groups | ||
| 383 | + counts = torch.cat(( | ||
| 384 | + torch.tensor([int(per_source_groups.sum()), int(pairs.shape[0])], | ||
| 385 | + dtype=torch.int64), | ||
| 386 | + prefixes, | ||
| 387 | + )) | ||
| 388 | + return pairs, counts | ||
| 282 | 389 | ||
| 283 | 390 | ||
| 284 | def plan_dedup_pairs( | 391 | def plan_dedup_pairs( |
| @@ -286,21 +393,59 @@ def plan_dedup_pairs( | |||
| 286 | dup_loffs: torch.Tensor, | 393 | dup_loffs: torch.Tensor, |
| 287 | dup_counts: torch.Tensor, | 394 | dup_counts: torch.Tensor, |
| 288 | NvS: int, | 395 | NvS: int, |
| 289 | -) -> tuple[torch.Tensor, tuple[int, int], list[str]]: | 396 | + *, |
| 397 | + R: int | None = None, | ||
| 398 | + dedup_mode: str = "rank", | ||
| 399 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 400 | +) -> tuple[torch.Tensor, torch.Tensor, list[str]]: | ||
| 290 | """Normalize a kernel-plan dedup table to the same semantic pair form. | 401 | """Normalize a kernel-plan dedup table to the same semantic pair form. |
| 291 | 402 | ||
| 292 | Also validates the table's structure (compact prefixes, group ranges, | 403 | Also validates the table's structure (compact prefixes, group ranges, |
| 293 | - duplicate offsets in range), returning human-readable errors. | 404 | + duplicate addresses in range) and returns the full count row, so both |
| 405 | + dedup modes compare with the reference model: ``[G, D]`` for ``rank`` and | ||
| 406 | + ``[G, D, P_0 .. P_{R-1}]`` for ``server``. | ||
| 294 | """ | 407 | """ |
| 295 | errors: list[str] = [] | 408 | errors: list[str] = [] |
| 296 | - n_groups = int(dup_counts[0]) | 409 | + counts_all = dup_counts.to(torch.int64) |
| 297 | - n_dups = int(dup_counts[1]) | 410 | + empty = torch.zeros(0, 2, dtype=torch.int64) |
| 298 | - if not 0 <= n_groups <= NvS: | 411 | + if dedup_mode == "rank": |
| 299 | - errors.append(f"dup group count {n_groups} out of [0, {NvS}]") | 412 | + if counts_all.numel() != 2: |
| 300 | - if not 0 <= n_dups <= NvS: | 413 | + errors.append( |
| 301 | - errors.append(f"dup loff count {n_dups} out of [0, {NvS}]") | 414 | + f"rank dedup dup_counts must have 2 entries, got {counts_all.numel()}") |
| 415 | + return empty, counts_all, errors | ||
| 416 | + group_capacity = NvS | ||
| 417 | + dup_capacity = NvS | ||
| 418 | + address_limit = NvS | ||
| 419 | + elif dedup_mode == "server": | ||
| 420 | + if R is None: | ||
| 421 | + raise ValueError("server dedup table checks require R") | ||
| 422 | + if counts_all.numel() != R + 2: | ||
| 423 | + errors.append( | ||
| 424 | + f"server dedup dup_counts must have R+2={R + 2} entries, " | ||
| 425 | + f"got {counts_all.numel()}") | ||
| 426 | + return empty, counts_all, errors | ||
| 427 | + group_capacity = NvS | ||
| 428 | + dup_capacity = ranks_per_server * NvS | ||
| 429 | + address_limit = R * NvS | ||
| 430 | + else: | ||
| 431 | + raise ValueError(f"unsupported dedup_mode: {dedup_mode!r}") | ||
| 432 | + | ||
| 433 | + n_groups = int(counts_all[0]) | ||
| 434 | + n_dups = int(counts_all[1]) | ||
| 435 | + if not 0 <= n_groups <= group_capacity: | ||
| 436 | + errors.append(f"dup group count {n_groups} out of [0, {group_capacity}]") | ||
| 437 | + if not 0 <= n_dups <= dup_capacity: | ||
| 438 | + errors.append(f"dup loff count {n_dups} out of [0, {dup_capacity}]") | ||
| 439 | + if dedup_mode == "server": | ||
| 440 | + prefixes = counts_all[2:] | ||
| 441 | + if int(prefixes[0]) != 0: | ||
| 442 | + errors.append("server dup source prefixes must start at 0") | ||
| 443 | + if bool((prefixes[1:] < prefixes[:-1]).any()): | ||
| 444 | + errors.append("server dup source prefixes are not monotonic") | ||
| 445 | + if int(prefixes[-1]) > max(n_groups, 0): | ||
| 446 | + errors.append("server dup source prefix exceeds the group count") | ||
| 302 | if errors: | 447 | if errors: |
| 303 | - return torch.zeros(0, 2, dtype=torch.int64), (n_groups, n_dups), errors | 448 | + return empty, counts_all, errors |
| 304 | 449 | ||
| 305 | groups = dup_groups[:n_groups].to(torch.int64) | 450 | groups = dup_groups[:n_groups].to(torch.int64) |
| 306 | prim = groups[:, 0] | 451 | prim = groups[:, 0] |
| @@ -327,14 +472,17 @@ def plan_dedup_pairs( | |||
| 327 | errors.append("dup group references loffs outside the compact prefix") | 472 | errors.append("dup group references loffs outside the compact prefix") |
| 328 | dup_idx = dup_idx.clamp(0, max(n_dups - 1, 0)) | 473 | dup_idx = dup_idx.clamp(0, max(n_dups - 1, 0)) |
| 329 | dup_values = dup_loffs[dup_idx].to(torch.int64) | 474 | dup_values = dup_loffs[dup_idx].to(torch.int64) |
| 475 | + if bool(((dup_values < 0) | (dup_values >= address_limit)).any()): | ||
| 476 | + errors.append( | ||
| 477 | + f"dup addresses out of [0, {address_limit}) for {dedup_mode} dedup") | ||
| 330 | pairs = torch.stack((torch.repeat_interleave(prim, counts), dup_values), 1) | 478 | pairs = torch.stack((torch.repeat_interleave(prim, counts), dup_values), 1) |
| 331 | if int(torch.unique(dup_values).numel()) != total: | 479 | if int(torch.unique(dup_values).numel()) != total: |
| 332 | errors.append("dup_loffs lists the same duplicate row twice") | 480 | errors.append("dup_loffs lists the same duplicate row twice") |
| 333 | - pairs = pairs[torch.argsort(pairs[:, 0] * NvS + pairs[:, 1])] | 481 | + pairs = pairs[torch.argsort(pairs[:, 0] * address_limit + pairs[:, 1])] |
| 334 | else: | 482 | else: |
| 335 | - pairs = torch.zeros(0, 2, dtype=torch.int64) | 483 | + pairs = empty |
| 336 | 484 | ||
| 337 | - return pairs, (n_groups, n_dups), errors | 485 | + return pairs, counts_all, errors |
| 338 | 486 | ||
| 339 | 487 | ||
| 340 | @dataclass(frozen=True) | 488 | @dataclass(frozen=True) |
| @@ -350,7 +498,8 @@ class PlanExpectation: | |||
| 350 | canonical: torch.Tensor # [R, N] bool | 498 | canonical: torch.Tensor # [R, N] bool |
| 351 | dst: torch.Tensor # [R, N] expected encoded dst | 499 | dst: torch.Tensor # [R, N] expected encoded dst |
| 352 | dedup_pairs: torch.Tensor # [n_dups, 2] for this rank's destination | 500 | dedup_pairs: torch.Tensor # [n_dups, 2] for this rank's destination |
| 353 | - dedup_counts: tuple[int, int] | 501 | + dedup_counts: torch.Tensor # [2] rank / [R+2] server count row |
| 502 | + dedup_mode: str | ||
| 354 | tpe_global: torch.Tensor # [E] | 503 | tpe_global: torch.Tensor # [E] |
| 355 | 504 | ||
| 356 | 505 | ||
| @@ -360,6 +509,8 @@ def plan_expectation( | |||
| 360 | *, | 509 | *, |
| 361 | rank: int, | 510 | rank: int, |
| 362 | NvS: int, | 511 | NvS: int, |
| 512 | + dedup_mode: str = "rank", | ||
| 513 | + ranks_per_server: int = RANKS_PER_SERVER, | ||
| 363 | ) -> PlanExpectation: | 514 | ) -> PlanExpectation: |
| 364 | """Build the expected plan for every rank from the full routing.""" | 515 | """Build the expected plan for every rank from the full routing.""" |
| 365 | topk_all = topk_all.to(torch.int64) | 516 | topk_all = topk_all.to(torch.int64) |
| @@ -372,10 +523,14 @@ def plan_expectation( | |||
| 372 | experts_to_copy = prefetch_experts(alloc, R, E, B) | 523 | experts_to_copy = prefetch_experts(alloc, R, E, B) |
| 373 | cu_seqlens, expert_off = plan_layout(alloc, experts_to_copy, R, E, B) | 524 | cu_seqlens, expert_off = plan_layout(alloc, experts_to_copy, R, E, B) |
| 374 | dest, loff, canonical, raw = _route_destinations( | 525 | dest, loff, canonical, raw = _route_destinations( |
| 375 | - topk_all, tpe_all, alloc, expert_off, NvS | 526 | + topk_all, tpe_all, alloc, expert_off, NvS, |
| 527 | + dedup_mode=dedup_mode, ranks_per_server=ranks_per_server, | ||
| 376 | ) | 528 | ) |
| 377 | dst = encode_dst(raw, canonical) | 529 | dst = encode_dst(raw, canonical) |
| 378 | - pairs, counts = dedup_pairs(dest, loff, canonical, rank, S, NvS) | 530 | + pairs, counts = dedup_pairs( |
| 531 | + dest, loff, canonical, rank, S, NvS, | ||
| 532 | + dedup_mode=dedup_mode, ranks_per_server=ranks_per_server, | ||
| 533 | + ) | ||
| 379 | return PlanExpectation( | 534 | return PlanExpectation( |
| 380 | alloc=alloc, | 535 | alloc=alloc, |
| 381 | experts_to_copy=experts_to_copy, | 536 | experts_to_copy=experts_to_copy, |
| @@ -387,6 +542,7 @@ def plan_expectation( | |||
| 387 | dst=dst, | 542 | dst=dst, |
| 388 | dedup_pairs=pairs, | 543 | dedup_pairs=pairs, |
| 389 | dedup_counts=counts, | 544 | dedup_counts=counts, |
| 545 | + dedup_mode=dedup_mode, | ||
| 390 | tpe_global=tpe_all.sum(0), | 546 | tpe_global=tpe_all.sum(0), |
| 391 | ) | 547 | ) |
| 392 | 548 | ||
| @@ -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 ( |
| @@ -213,7 +215,7 @@ class MoonEPRunner: | |||
| 213 | 215 | ||
| 214 | def __init__(self, group, R, S, K, E, H, num_sms, local_rank, hp=2048, | 216 | def __init__(self, group, R, S, K, E, H, num_sms, local_rank, hp=2048, |
| 215 | use_udma=False, pf_overlap=False, verify=False, | 217 | use_udma=False, pf_overlap=False, verify=False, |
| 216 | - verify_stages=None, verify_trace=False): | 218 | + verify_stages=None, verify_trace=False, dedup_mode="rank"): |
| 217 | if pf_overlap and not _PREFETCH_HAS_RANK_BARRIERS: | 219 | if pf_overlap and not _PREFETCH_HAS_RANK_BARRIERS: |
| 218 | raise RuntimeError( | 220 | raise RuntimeError( |
| 219 | '--pf-overlap requires launch_prefetch rank_barriers support') | 221 | '--pf-overlap requires launch_prefetch rank_barriers support') |
| @@ -240,7 +242,8 @@ class MoonEPRunner: | |||
| 240 | self.pf_overlap = pf_overlap | 242 | self.pf_overlap = pf_overlap |
| 241 | self.pf_stream = torch.npu.Stream() if pf_overlap else None | 243 | 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, | 244 | self.buffer = Buffer(S, H, K, E, R, num_sms=num_sms, group=group, |
| 243 | - use_udma=use_udma, explicitly_destroy=True) | 245 | + use_udma=use_udma, dedup_mode=dedup_mode, |
| 246 | + explicitly_destroy=True) | ||
| 244 | self.ctx = self.buffer._require_ctx() | 247 | self.ctx = self.buffer._require_ctx() |
| 245 | # Pre-allocate the plan + outputs once (test_planning.py pattern): the | 248 | # Pre-allocate the plan + outputs once (test_planning.py pattern): the |
| 246 | # timed ops reuse these instead of allocating per call. | 249 | # timed ops reuse these instead of allocating per call. |
| @@ -513,7 +516,7 @@ class MoonEPRunner: | |||
| 513 | ]) | 516 | ]) |
| 514 | try: | 517 | try: |
| 515 | exp = plan_expectation(topk_all, tpe_from_topk, rank=self.rank, | 518 | exp = plan_expectation(topk_all, tpe_from_topk, rank=self.rank, |
| 516 | - NvS=NvS) | 519 | + NvS=NvS, dedup_mode=self.buffer.dedup_mode) |
| 517 | except Exception as exc: # local reference model; deterministic per rank | 520 | except Exception as exc: # local reference model; deterministic per rank |
| 518 | return _report_ok(f'plan (model error: {exc!r})', False, | 521 | return _report_ok(f'plan (model error: {exc!r})', False, |
| 519 | self.rank, self.group, dev) | 522 | self.rank, self.group, dev) |
| @@ -543,7 +546,7 @@ class MoonEPRunner: | |||
| 543 | 546 | ||
| 544 | dedup_pairs_plan, dedup_counts_plan, dedup_errors = plan_dedup_pairs( | 547 | dedup_pairs_plan, dedup_counts_plan, dedup_errors = plan_dedup_pairs( |
| 545 | self.plan.dup_groups.cpu(), self.plan.dup_loffs.cpu(), | 548 | self.plan.dup_groups.cpu(), self.plan.dup_loffs.cpu(), |
| 546 | - self.plan.dup_counts.cpu(), NvS) | 549 | + self.plan.dup_counts.cpu(), NvS, R=R, dedup_mode=self.buffer.dedup_mode) |
| 547 | 550 | ||
| 548 | checks = { | 551 | checks = { |
| 549 | 'routing': torch.equal(tpe_all.to(torch.int64), tpe_from_topk), | 552 | 'routing': torch.equal(tpe_all.to(torch.int64), tpe_from_topk), |
| @@ -554,7 +557,7 @@ class MoonEPRunner: | |||
| 554 | 'prefetch': torch.equal(etc_all, | 557 | 'prefetch': torch.equal(etc_all, |
| 555 | exp.experts_to_copy.expand_as(etc_all)), | 558 | exp.experts_to_copy.expand_as(etc_all)), |
| 556 | 'slots': slots_ok, | 559 | 'slots': slots_ok, |
| 557 | - 'dedup': (not dedup_errors and dedup_counts_plan == exp.dedup_counts | 560 | + 'dedup': (not dedup_errors and torch.equal(dedup_counts_plan, exp.dedup_counts) |
| 558 | and torch.equal(dedup_pairs_plan, exp.dedup_pairs)), | 561 | and torch.equal(dedup_pairs_plan, exp.dedup_pairs)), |
| 559 | } | 562 | } |
| 560 | ok = all(checks.values()) | 563 | ok = all(checks.values()) |
| @@ -783,6 +786,7 @@ class MoonEPRunner: | |||
| 783 | def main(): | 786 | def main(): |
| 784 | ap = argparse.ArgumentParser(description=__doc__) | 787 | ap = argparse.ArgumentParser(description=__doc__) |
| 785 | add_engine_args(ap) | 788 | add_engine_args(ap) |
| 789 | + add_dedup_mode_arg(ap) | ||
| 786 | ap.add_argument('--libs', nargs='+', default=['moonep'], choices=['moonep'], | 790 | ap.add_argument('--libs', nargs='+', default=['moonep'], choices=['moonep'], |
| 787 | help='Libraries to benchmark (Ascend: only moonep).') | 791 | help='Libraries to benchmark (Ascend: only moonep).') |
| 788 | ap.add_argument('--out', default='bench_vs_results.csv', | 792 | ap.add_argument('--out', default='bench_vs_results.csv', |
| @@ -832,6 +836,7 @@ def main(): | |||
| 832 | rank, world_size, local_rank = setup() | 836 | rank, world_size, local_rank = setup() |
| 833 | local_rank = local_device_index(local_rank) | 837 | local_rank = local_device_index(local_rank) |
| 834 | use_udma = apply_engine(args.engine) | 838 | use_udma = apply_engine(args.engine) |
| 839 | + validate_dedup_mode(args.dedup_mode, use_udma, world_size) | ||
| 835 | R = world_size | 840 | R = world_size |
| 836 | group = dist.group.WORLD | 841 | group = dist.group.WORLD |
| 837 | dev = f"npu:{local_rank}" | 842 | dev = f"npu:{local_rank}" |
| @@ -855,7 +860,7 @@ def main(): | |||
| 855 | hp=args.hp, use_udma=use_udma, | 860 | hp=args.hp, use_udma=use_udma, |
| 856 | pf_overlap=args.pf_overlap, verify=args.verify, | 861 | pf_overlap=args.pf_overlap, verify=args.verify, |
| 857 | verify_stages=args.verify_stages.split(','), | 862 | verify_stages=args.verify_stages.split(','), |
| 858 | - verify_trace=args.verify_trace) | 863 | + verify_trace=args.verify_trace, dedup_mode=args.dedup_mode) |
| 859 | if not ShmemRuntime.is_initialized(): | 864 | if not ShmemRuntime.is_initialized(): |
| 860 | if args.ip_port is not None or multi_node: | 865 | if args.ip_port is not None or multi_node: |
| 861 | # Multi-node: ip_port/DEFAULT bootstrap; when ip_port is omitted it | 866 | # Multi-node: ip_port/DEFAULT bootstrap; when ip_port is omitted it |
| @@ -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,21 @@ 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 | +) -> torch.Tensor | None: | ||
| 97 | + """Launch planning. | ||
| 98 | + | ||
| 99 | + ``server_dedup`` selects the kernel family: ``True`` runs the server-level | ||
| 100 | + dedup planner (which can also emit the fused combine execution plan when | ||
| 101 | + ``combine_workspace`` is given), ``False`` runs the legacy rank-level | ||
| 102 | + planner and never produces a combine plan. | ||
| 103 | + """ | ||
| 90 | global _PLANNING | 104 | global _PLANNING |
| 91 | if _PLANNING is None: | 105 | if _PLANNING is None: |
| 92 | _PLANNING = torch.classes.AscendMoonEP.Planning() | 106 | _PLANNING = torch.classes.AscendMoonEP.Planning() |
| 93 | - _PLANNING.compute( | 107 | + args = ( |
| 94 | topk_idx, | 108 | topk_idx, |
| 95 | dst, | 109 | dst, |
| 96 | cu_seqlens, | 110 | cu_seqlens, |
| @@ -110,7 +124,12 @@ def launch_planning_op( | |||
| 110 | rank, | 124 | rank, |
| 111 | world_size, | 125 | world_size, |
| 112 | _env_use_udma('planning'), | 126 | _env_use_udma('planning'), |
| 127 | + bool(server_dedup), | ||
| 113 | ) | 128 | ) |
| 129 | + if combine_workspace is not None: | ||
| 130 | + return _PLANNING.compute_fused(*args, combine_workspace, hidden_size) | ||
| 131 | + _PLANNING.compute(*args) | ||
| 132 | + return None | ||
| 114 | 133 | ||
| 115 | 134 | ||
| 116 | def launch_dispatch_op( | 135 | def launch_dispatch_op( |
| @@ -129,6 +148,7 @@ def launch_dispatch_op( | |||
| 129 | world_size: int, | 148 | world_size: int, |
| 130 | rank: int, | 149 | rank: int, |
| 131 | num_sms: int = 32, | 150 | num_sms: int = 32, |
| 151 | + server_dedup: bool = False, | ||
| 132 | ) -> None: | 152 | ) -> None: |
| 133 | """Launch dispatch; num_sms controls only the MTE AIV launch width.""" | 153 | """Launch dispatch; num_sms controls only the MTE AIV launch width.""" |
| 134 | global _DISPATCH | 154 | global _DISPATCH |
| @@ -152,9 +172,7 @@ def launch_dispatch_op( | |||
| 152 | rank, | 172 | rank, |
| 153 | use_udma, | 173 | use_udma, |
| 154 | ) | 174 | ) |
| 155 | - if not use_udma: | 175 | + _DISPATCH.compute(*args, num_sms, bool(server_dedup)) |
| 156 | - args += (num_sms,) | ||
| 157 | - _DISPATCH.compute(*args) | ||
| 158 | 176 | ||
| 159 | 177 | ||
| 160 | def launch_dispatch_profile_op( | 178 | def launch_dispatch_profile_op( |
| @@ -173,6 +191,7 @@ def launch_dispatch_profile_op( | |||
| 173 | num_topk: int, | 191 | num_topk: int, |
| 174 | world_size: int, | 192 | world_size: int, |
| 175 | rank: int, | 193 | rank: int, |
| 194 | + server_dedup: bool = False, | ||
| 176 | ) -> None: | 195 | ) -> None: |
| 177 | global _DISPATCH | 196 | global _DISPATCH |
| 178 | if _DISPATCH is None: | 197 | if _DISPATCH is None: |
| @@ -194,6 +213,7 @@ def launch_dispatch_profile_op( | |||
| 194 | world_size, | 213 | world_size, |
| 195 | rank, | 214 | rank, |
| 196 | _env_use_udma('dispatch'), | 215 | _env_use_udma('dispatch'), |
| 216 | + bool(server_dedup), | ||
| 197 | ) | 217 | ) |
| 198 | 218 | ||
| 199 | 219 | ||
| @@ -327,7 +347,6 @@ def launch_combine( | |||
| 327 | def launch_inter_rank_sync(ctx: dict) -> None: | 347 | def launch_inter_rank_sync(ctx: dict) -> None: |
| 328 | """Ascend replacement for the CuTe DSL rank sync kernel: a host-side | 348 | """Ascend replacement for the CuTe DSL rank sync kernel: a host-side |
| 329 | cross-rank signal barrier on the current stream.""" | 349 | cross-rank signal barrier on the current stream.""" |
| 330 | - from ._common import cross_rank_barrier | ||
| 331 | 350 | ||
| 332 | cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream) | 351 | cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream) |
| 333 | return None | 352 | 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,81 @@ 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( | ||
| 162 | torch::Tensor topk_idx, | 236 | torch::Tensor topk_idx, |
| 163 | torch::Tensor dst, | 237 | torch::Tensor dst, |
| 164 | torch::Tensor cu_seqlens, | 238 | torch::Tensor cu_seqlens, |
| @@ -207,49 +281,126 @@ void LaunchPlanningKernel( | |||
| 207 | ffts_addr); | 281 | ffts_addr); |
| 208 | } | 282 | } |
| 209 | 283 | ||
| 210 | -void LaunchMoonEPUdmaCombineKernel( | 284 | +void LaunchPlanningServerDedupKernel( |
| 211 | - torch::Tensor hidden_nvsh, | 285 | + torch::Tensor topk_idx, |
| 212 | - torch::Tensor route_weights_nvs, | ||
| 213 | - torch::Tensor sync_buffer, | ||
| 214 | torch::Tensor dst, | 286 | torch::Tensor dst, |
| 287 | + torch::Tensor cu_seqlens, | ||
| 288 | + torch::Tensor experts_to_copy, | ||
| 215 | torch::Tensor dup_groups, | 289 | torch::Tensor dup_groups, |
| 216 | torch::Tensor dup_loffs, | 290 | torch::Tensor dup_loffs, |
| 217 | torch::Tensor dup_counts, | 291 | torch::Tensor dup_counts, |
| 218 | - torch::Tensor output_sh, | 292 | + torch::Tensor tpe_all, |
| 219 | - torch::Tensor output_sk, | 293 | + torch::Tensor tpe_prefix, |
| 220 | - void* bandwidth_scratch, | 294 | + torch::Tensor balance, |
| 221 | - const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | 295 | + torch::Tensor z_tensor, |
| 222 | - void* local_workspace, | 296 | + torch::Tensor alloc_tensor, |
| 223 | - uint64_t invocation_magic) { | 297 | + torch::Tensor alloc_cumsum, |
| 298 | + torch::Tensor expert_offsets, | ||
| 299 | + torch::Tensor core_expert_counts, | ||
| 300 | + torch::Tensor dup_workspace, | ||
| 301 | + torch::Tensor dup_key_workspace, | ||
| 302 | + const ascend_moonep::PlanningTilingData& tiling, | ||
| 303 | + void* symmetric_buffer, | ||
| 304 | + uint64_t ffts_addr) { | ||
| 224 | #if defined(ASCEND_MOONEP_UDMA) | 305 | #if defined(ASCEND_MOONEP_UDMA) |
| 225 | - TORCH_CHECK(local_workspace != nullptr, "local_workspace must not be null"); | 306 | + TORCH_CHECK(symmetric_buffer != nullptr, |
| 226 | - TORCH_CHECK(bandwidth_scratch != nullptr, | 307 | + "planning symmetric_buffer must not be null"); |
| 227 | - "bandwidth_scratch must not be null"); | ||
| 228 | - | ||
| 229 | aclrtStream stream = GetCurrentAclStream(); | 308 | aclrtStream stream = GetCurrentAclStream(); |
| 230 | - moonep_udma_combine_kernel_do( | 309 | + planning_server_dedup_kernel_do( |
| 231 | stream, | 310 | stream, |
| 232 | - BytePtr(hidden_nvsh.data_ptr()), | 311 | + BytePtr(topk_idx.data_ptr()), |
| 233 | - BytePtr(route_weights_nvs.data_ptr()), | 312 | + BytePtr(symmetric_buffer), |
| 234 | - BytePtr(sync_buffer.data_ptr()), | ||
| 235 | BytePtr(dst.data_ptr()), | 313 | BytePtr(dst.data_ptr()), |
| 314 | + BytePtr(cu_seqlens.data_ptr()), | ||
| 315 | + BytePtr(experts_to_copy.data_ptr()), | ||
| 236 | BytePtr(dup_groups.data_ptr()), | 316 | BytePtr(dup_groups.data_ptr()), |
| 237 | BytePtr(dup_loffs.data_ptr()), | 317 | BytePtr(dup_loffs.data_ptr()), |
| 238 | BytePtr(dup_counts.data_ptr()), | 318 | BytePtr(dup_counts.data_ptr()), |
| 239 | - BytePtr(output_sh.data_ptr()), | 319 | + BytePtr(tpe_all.data_ptr()), |
| 240 | - BytePtr(output_sk.data_ptr()), | 320 | + BytePtr(tpe_prefix.data_ptr()), |
| 241 | - BytePtr(local_workspace), | 321 | + BytePtr(balance.data_ptr()), |
| 242 | - BytePtr(bandwidth_scratch), | 322 | + BytePtr(z_tensor.data_ptr()), |
| 323 | + BytePtr(alloc_tensor.data_ptr()), | ||
| 324 | + BytePtr(alloc_cumsum.data_ptr()), | ||
| 325 | + BytePtr(expert_offsets.data_ptr()), | ||
| 326 | + BytePtr(core_expert_counts.data_ptr()), | ||
| 327 | + BytePtr(dup_workspace.data_ptr()), | ||
| 328 | + BytePtr(dup_key_workspace.data_ptr()), | ||
| 243 | reinterpret_cast<uint8_t*>( | 329 | reinterpret_cast<uint8_t*>( |
| 244 | - const_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(&tiling)), | 330 | + const_cast<ascend_moonep::PlanningTilingData*>(&tiling)), |
| 245 | - invocation_magic); | 331 | + ffts_addr); |
| 246 | #else | 332 | #else |
| 247 | - (void)hidden_nvsh; (void)route_weights_nvs; (void)sync_buffer; (void)dst; | 333 | + (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; | 334 | + (void)dup_groups; (void)dup_loffs; (void)dup_counts; (void)tpe_all; |
| 249 | - (void)output_sk; (void)bandwidth_scratch; (void)tiling; | 335 | + (void)tpe_prefix; (void)balance; (void)z_tensor; (void)alloc_tensor; |
| 250 | - (void)local_workspace; (void)invocation_magic; | 336 | + (void)alloc_cumsum; (void)expert_offsets; (void)core_expert_counts; (void)dup_workspace; |
| 251 | - TORCH_CHECK(false, | 337 | + (void)dup_key_workspace; (void)tiling; (void)symmetric_buffer; (void)ffts_addr; |
| 252 | - "combine UDMA kernel support is not enabled in this build; " | 338 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); |
| 253 | - "A2/A3 do not provide the UDMA combine kernel"); | 339 | +#endif |
| 340 | +} | ||
| 341 | + | ||
| 342 | +void LaunchMoonEPUdmaCombineServerDedupKernel( | ||
| 343 | + torch::Tensor hidden, torch::Tensor weights, torch::Tensor dst, | ||
| 344 | + torch::Tensor groups, torch::Tensor dups, torch::Tensor counts, | ||
| 345 | + torch::Tensor out, torch::Tensor outw, torch::Tensor workspace, | ||
| 346 | + torch::Tensor plan, | ||
| 347 | + const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | ||
| 348 | + uint64_t magic) { | ||
| 349 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 350 | + moonep_udma_combine_server_dedup_kernel_do( | ||
| 351 | + GetCurrentAclStream(), BytePtr(hidden.data_ptr()), BytePtr(weights.data_ptr()), | ||
| 352 | + BytePtr(dst.data_ptr()), BytePtr(groups.data_ptr()), BytePtr(dups.data_ptr()), | ||
| 353 | + BytePtr(counts.data_ptr()), BytePtr(out.data_ptr()), BytePtr(outw.data_ptr()), | ||
| 354 | + BytePtr(workspace.data_ptr()), BytePtr(plan.data_ptr()), | ||
| 355 | + reinterpret_cast<uint8_t*>(const_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(&tiling)), | ||
| 356 | + magic); | ||
| 357 | +#else | ||
| 358 | + (void)hidden; (void)weights; (void)dst; (void)groups; | ||
| 359 | + (void)dups; (void)counts; (void)out; (void)outw; | ||
| 360 | + (void)workspace; (void)plan; (void)tiling; (void)magic; | ||
| 361 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); | ||
| 362 | +#endif | ||
| 363 | +} | ||
| 364 | + | ||
| 365 | +void LaunchMoonEPUdmaCombineLegacyKernel( | ||
| 366 | + torch::Tensor hidden, torch::Tensor weights, torch::Tensor sync_buffer, | ||
| 367 | + torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, | ||
| 368 | + torch::Tensor counts, torch::Tensor out, torch::Tensor outw, | ||
| 369 | + void* bandwidth_scratch, void* local_workspace, | ||
| 370 | + const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | ||
| 371 | + uint64_t magic) { | ||
| 372 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 373 | + TORCH_CHECK(bandwidth_scratch != nullptr, | ||
| 374 | + "bandwidth_scratch must not be null"); | ||
| 375 | + TORCH_CHECK(local_workspace != nullptr, "local_workspace must not be null"); | ||
| 376 | + moonep_udma_combine_kernel_do( | ||
| 377 | + GetCurrentAclStream(), BytePtr(hidden.data_ptr()), BytePtr(weights.data_ptr()), | ||
| 378 | + BytePtr(sync_buffer.data_ptr()), | ||
| 379 | + BytePtr(dst.data_ptr()), BytePtr(groups.data_ptr()), BytePtr(dups.data_ptr()), | ||
| 380 | + BytePtr(counts.data_ptr()), BytePtr(out.data_ptr()), BytePtr(outw.data_ptr()), | ||
| 381 | + BytePtr(local_workspace), BytePtr(bandwidth_scratch), | ||
| 382 | + reinterpret_cast<uint8_t*>(const_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(&tiling)), | ||
| 383 | + magic); | ||
| 384 | +#else | ||
| 385 | + (void)hidden; (void)weights; (void)sync_buffer; (void)dst; | ||
| 386 | + (void)groups; (void)dups; (void)counts; (void)out; | ||
| 387 | + (void)outw; (void)bandwidth_scratch; (void)local_workspace; (void)tiling; | ||
| 388 | + (void)magic; | ||
| 389 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); | ||
| 390 | +#endif | ||
| 391 | +} | ||
| 392 | + | ||
| 393 | +void LaunchPlanningMetadataOnly( | ||
| 394 | + torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, torch::Tensor counts, | ||
| 395 | + const ascend_moonep::PlanningTilingData& tiling) { | ||
| 396 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 397 | + planning_server_dedup_kernel_do(GetCurrentAclStream(), nullptr, nullptr, BytePtr(dst.data_ptr()), | ||
| 398 | + nullptr, nullptr, BytePtr(groups.data_ptr()), BytePtr(dups.data_ptr()), BytePtr(counts.data_ptr()), | ||
| 399 | + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, | ||
| 400 | + reinterpret_cast<uint8_t*>(const_cast<ascend_moonep::PlanningTilingData*>(&tiling)), 0); | ||
| 401 | +#else | ||
| 402 | + (void)dst; (void)groups; (void)dups; (void)counts; | ||
| 403 | + (void)tiling; | ||
| 404 | + TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build"); | ||
| 254 | #endif | 405 | #endif |
| 255 | } | 406 | } |
| @@ -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,35 @@ 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( | ||
| 62 | torch::Tensor topk_idx, | 90 | torch::Tensor topk_idx, |
| 63 | torch::Tensor dst, | 91 | torch::Tensor dst, |
| 64 | torch::Tensor cu_seqlens, | 92 | torch::Tensor cu_seqlens, |
| @@ -80,17 +108,47 @@ void LaunchPlanningKernel( | |||
| 80 | void* symmetric_buffer, | 108 | void* symmetric_buffer, |
| 81 | uint64_t ffts_addr); | 109 | uint64_t ffts_addr); |
| 82 | 110 | ||
| 83 | -void LaunchMoonEPUdmaCombineKernel( | 111 | +// Server-level dedup planner (routing + server dedup tables + combine plan). |
| 84 | - torch::Tensor hidden_nvsh, | 112 | +void LaunchPlanningServerDedupKernel( |
| 85 | - torch::Tensor route_weights_nvs, | 113 | + torch::Tensor topk_idx, |
| 86 | - torch::Tensor sync_buffer, | ||
| 87 | torch::Tensor dst, | 114 | torch::Tensor dst, |
| 115 | + torch::Tensor cu_seqlens, | ||
| 116 | + torch::Tensor experts_to_copy, | ||
| 88 | torch::Tensor dup_groups, | 117 | torch::Tensor dup_groups, |
| 89 | torch::Tensor dup_loffs, | 118 | torch::Tensor dup_loffs, |
| 90 | torch::Tensor dup_counts, | 119 | torch::Tensor dup_counts, |
| 91 | - torch::Tensor output_sh, | 120 | + torch::Tensor tpe_all, |
| 92 | - torch::Tensor output_sk, | 121 | + torch::Tensor tpe_prefix, |
| 93 | - void* bandwidth_scratch, | 122 | + torch::Tensor balance, |
| 123 | + torch::Tensor z_tensor, | ||
| 124 | + torch::Tensor alloc_tensor, | ||
| 125 | + torch::Tensor alloc_cumsum, | ||
| 126 | + torch::Tensor expert_offsets, | ||
| 127 | + torch::Tensor core_expert_counts, | ||
| 128 | + torch::Tensor dup_workspace, | ||
| 129 | + torch::Tensor dup_key_workspace, | ||
| 130 | + const ascend_moonep::PlanningTilingData& tiling, | ||
| 131 | + void* symmetric_buffer, | ||
| 132 | + uint64_t ffts_addr); | ||
| 133 | + | ||
| 134 | +void LaunchMoonEPUdmaCombineServerDedupKernel( | ||
| 135 | + torch::Tensor hidden, torch::Tensor weights, torch::Tensor dst, | ||
| 136 | + torch::Tensor groups, torch::Tensor dups, torch::Tensor counts, | ||
| 137 | + torch::Tensor out, torch::Tensor outw, torch::Tensor workspace, | ||
| 138 | + torch::Tensor plan, | ||
| 94 | const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | 139 | const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, |
| 95 | - void* local_workspace, | 140 | + uint64_t magic); |
| 96 | - uint64_t invocation_magic); | 141 | + |
| 142 | +// Legacy rank-level dedup combine: workspace and its bandwidth scratch tail are | ||
| 143 | +// rank-local host tensors, not the symmetric PUT workspace. | ||
| 144 | +void LaunchMoonEPUdmaCombineLegacyKernel( | ||
| 145 | + torch::Tensor hidden, torch::Tensor weights, torch::Tensor sync_buffer, | ||
| 146 | + torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, | ||
| 147 | + torch::Tensor counts, torch::Tensor out, torch::Tensor outw, | ||
| 148 | + void* bandwidth_scratch, void* local_workspace, | ||
| 149 | + const ascend_moonep::MoonEPUdmaCombineTilingData& tiling, | ||
| 150 | + uint64_t magic); | ||
| 151 | + | ||
| 152 | +void LaunchPlanningMetadataOnly( | ||
| 153 | + torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, torch::Tensor counts, | ||
| 154 | + 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,7 +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; | 473 | (void)use_udma; |
| 457 | CheckNpuInt32(topk_idx, "topk_idx"); | 474 | CheckNpuInt32(topk_idx, "topk_idx"); |
| 458 | CheckNpuInt32(dst, "dst"); | 475 | CheckNpuInt32(dst, "dst"); |
| @@ -497,8 +514,15 @@ void Planning( | |||
| 497 | CheckedMul(world_size, num_experts, "rank-expert table") <= | 514 | CheckedMul(world_size, num_experts, "rank-expert table") <= |
| 498 | std::numeric_limits<int32_t>::max(), | 515 | std::numeric_limits<int32_t>::max(), |
| 499 | "planning requires world_size * num_experts to fit int32 indexing"); | 516 | "planning requires world_size * num_experts to fit int32 indexing"); |
| 500 | - TORCH_CHECK(num_max_tokens_per_rank >= route_count, | 517 | + // 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"); | 518 | + const bool counts_server_dedup = dup_counts.dim() == 1 && dup_counts.numel() == world_size + 2; |
| 519 | + TORCH_CHECK(server_dedup == counts_server_dedup, | ||
| 520 | + "planning dedup mode must match the plan tables: plan has ", | ||
| 521 | + counts_server_dedup ? "server" : "rank", " dedup tables"); | ||
| 522 | + TORCH_CHECK(!server_dedup || world_size % kPlanningRanksPerServer == 0, | ||
| 523 | + "server planning requires world_size divisible by 8"); | ||
| 524 | + TORCH_CHECK(num_max_tokens_per_rank >= route_count && (!server_dedup || num_max_tokens_per_rank == route_count), | ||
| 525 | + "server planning requires NvS == S*K; rank planning requires NvS >= S*K"); | ||
| 502 | TORCH_CHECK(topk_idx.numel() == route_count, | 526 | TORCH_CHECK(topk_idx.numel() == route_count, |
| 503 | "topk_idx numel must equal num_tokens * num_topk"); | 527 | "topk_idx numel must equal num_tokens * num_topk"); |
| 504 | TORCH_CHECK(dst.numel() == route_count, "dst shape mismatch"); | 528 | TORCH_CHECK(dst.numel() == route_count, "dst shape mismatch"); |
| @@ -506,11 +530,15 @@ void Planning( | |||
| 506 | "cu_seqlens shape mismatch"); | 530 | "cu_seqlens shape mismatch"); |
| 507 | TORCH_CHECK(experts_to_copy.numel() == world_size * num_prefetch_slots, | 531 | TORCH_CHECK(experts_to_copy.numel() == world_size * num_prefetch_slots, |
| 508 | "experts_to_copy shape mismatch"); | 532 | "experts_to_copy shape mismatch"); |
| 509 | - TORCH_CHECK(dup_groups.numel() == num_max_tokens_per_rank * 3, | 533 | + const int64_t dup_capacity = server_dedup ? kPlanningRanksPerServer * num_max_tokens_per_rank : |
| 510 | - "dup_groups shape mismatch"); | 534 | + num_max_tokens_per_rank; |
| 511 | - TORCH_CHECK(dup_loffs.numel() == num_max_tokens_per_rank, | 535 | + const int64_t count_size = server_dedup ? world_size + 2 : 2; |
| 512 | - "dup_loffs shape mismatch"); | 536 | + 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"); | 537 | + dup_groups.size(1) == 3, "dup_groups must be int32 [NvS, 3]"); |
| 538 | + TORCH_CHECK(dup_loffs.dim() == 1 && dup_loffs.numel() == dup_capacity, | ||
| 539 | + "dup_loffs must be int32 [", dup_capacity, "] for the selected dup format"); | ||
| 540 | + TORCH_CHECK(dup_counts.dim() == 1 && dup_counts.numel() == count_size, | ||
| 541 | + "dup_counts must be int32 [2] or [R+2]"); | ||
| 514 | TORCH_CHECK(symmetric_workspace_addr != 0, | 542 | TORCH_CHECK(symmetric_workspace_addr != 0, |
| 515 | "planning symmetric workspace address must not be zero"); | 543 | "planning symmetric workspace address must not be zero"); |
| 516 | TORCH_CHECK( | 544 | TORCH_CHECK( |
| @@ -518,12 +546,12 @@ void Planning( | |||
| 518 | "planning local workspace base must be 32-byte aligned"); | 546 | "planning local workspace base must be 32-byte aligned"); |
| 519 | 547 | ||
| 520 | const auto layout = MakePlanningWorkspaceLayout( | 548 | const auto layout = MakePlanningWorkspaceLayout( |
| 521 | - num_tokens, num_topk, num_experts, world_size, core_num); | 549 | + num_tokens, num_topk, num_experts, world_size, core_num, server_dedup); |
| 522 | TORCH_CHECK(local_workspace.numel() >= layout.total_elems, | 550 | TORCH_CHECK(local_workspace.numel() >= layout.total_elems, |
| 523 | "planning local workspace is too small: need ", | 551 | "planning local workspace is too small: need ", |
| 524 | layout.total_elems, " int32 elements, got ", local_workspace.numel()); | 552 | layout.total_elems, " int32 elements, got ", local_workspace.numel()); |
| 525 | const int64_t required_symmetric_bytes = PlanningSymmetricWorkspaceBytes( | 553 | const int64_t required_symmetric_bytes = PlanningSymmetricWorkspaceBytes( |
| 526 | - num_experts, num_max_tokens_per_rank, world_size); | 554 | + num_experts, num_max_tokens_per_rank, world_size, server_dedup); |
| 527 | TORCH_CHECK(symmetric_workspace_bytes >= required_symmetric_bytes, | 555 | TORCH_CHECK(symmetric_workspace_bytes >= required_symmetric_bytes, |
| 528 | "planning symmetric workspace is too small: need ", | 556 | "planning symmetric workspace is too small: need ", |
| 529 | required_symmetric_bytes, " bytes, got ", symmetric_workspace_bytes); | 557 | required_symmetric_bytes, " bytes, got ", symmetric_workspace_bytes); |
| @@ -541,14 +569,26 @@ void Planning( | |||
| 541 | tiling.symmetric_dup_rank_counts_offset = | 569 | tiling.symmetric_dup_rank_counts_offset = |
| 542 | static_cast<uint32_t>(AlignUp(num_experts, kAlignElems)); | 570 | static_cast<uint32_t>(AlignUp(num_experts, kAlignElems)); |
| 543 | tiling.source_dup_tokens_per_tile = | 571 | tiling.source_dup_tokens_per_tile = |
| 544 | - SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes); | 572 | + SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes, server_dedup); |
| 545 | tiling.owner_reduce_tile_elems = static_cast<uint32_t>( | 573 | tiling.owner_reduce_tile_elems = static_cast<uint32_t>( |
| 546 | SelectOwnerReduceTileElems( | 574 | SelectOwnerReduceTileElems( |
| 547 | world_size, | 575 | world_size, |
| 548 | num_experts / world_size, | 576 | num_experts / world_size, |
| 549 | core_num, | 577 | core_num, |
| 550 | static_cast<int64_t>(kPlanningUbSizeBytes))); | 578 | static_cast<int64_t>(kPlanningUbSizeBytes))); |
| 551 | - tiling.reserved = 0; | 579 | + tiling.server_dedup = server_dedup ? 1U : 0U; |
| 580 | + torch::Tensor combine_plan; | ||
| 581 | + TORCH_CHECK(server_dedup || !combine_workspace.defined(), | ||
| 582 | + "the legacy rank-level planner does not produce a combine " | ||
| 583 | + "execution plan; construct the Buffer with dedup_mode='server'"); | ||
| 584 | + if (server_dedup && combine_workspace.defined()) { | ||
| 585 | + combine_plan = AllocateCombinePlan(combine_workspace, dst, dup_groups, | ||
| 586 | + dup_loffs, dup_counts, num_tokens, hidden_size, num_topk, world_size, rank); | ||
| 587 | + tiling.combine_mode = 1U; | ||
| 588 | + tiling.combine_h = hidden_size; | ||
| 589 | + tiling.combine_workspace = reinterpret_cast<uint64_t>(combine_workspace.data_ptr()); | ||
| 590 | + tiling.combine_plan = reinterpret_cast<uint64_t>(combine_plan.data_ptr()); | ||
| 591 | + } | ||
| 552 | 592 | ||
| 553 | auto tpe_all = SliceWorkspace(local_workspace, layout.tpe_all); | 593 | auto tpe_all = SliceWorkspace(local_workspace, layout.tpe_all); |
| 554 | auto tpe_prefix = SliceWorkspace(local_workspace, layout.tpe_prefix); | 594 | auto tpe_prefix = SliceWorkspace(local_workspace, layout.tpe_prefix); |
| @@ -563,28 +603,93 @@ void Planning( | |||
| 563 | 603 | ||
| 564 | // SHMEM initializes FFTS where required; A5 legitimately returns zero. | 604 | // SHMEM initializes FFTS where required; A5 legitimately returns zero. |
| 565 | const uint64_t ffts_addr = shmemx_get_ffts_config(); | 605 | const uint64_t ffts_addr = shmemx_get_ffts_config(); |
| 606 | + const auto launch_planning = [&](auto launcher) { | ||
| 607 | + launcher( | ||
| 608 | + topk_idx, | ||
| 609 | + dst, | ||
| 610 | + cu_seqlens, | ||
| 611 | + experts_to_copy, | ||
| 612 | + dup_groups, | ||
| 613 | + dup_loffs, | ||
| 614 | + dup_counts, | ||
| 615 | + tpe_all, | ||
| 616 | + tpe_prefix, | ||
| 617 | + balance, | ||
| 618 | + z, | ||
| 619 | + alloc, | ||
| 620 | + alloc_cumsum, | ||
| 621 | + expert_offsets, | ||
| 622 | + core_expert_counts, | ||
| 623 | + dup_workspace, | ||
| 624 | + dup_key_workspace, | ||
| 625 | + tiling, | ||
| 626 | + reinterpret_cast<void*>(static_cast<uintptr_t>(symmetric_workspace_addr)), | ||
| 627 | + ffts_addr); | ||
| 628 | + }; | ||
| 629 | + if (server_dedup) { | ||
| 630 | + launch_planning(LaunchPlanningServerDedupKernel); | ||
| 631 | + } else { | ||
| 632 | + launch_planning(LaunchPlanningLegacyKernel); | ||
| 633 | + } | ||
| 634 | + return combine_plan; | ||
| 635 | +} | ||
| 566 | 636 | ||
| 567 | - LaunchPlanningKernel( | 637 | +torch::Tensor AllocateCombinePlan( |
| 568 | - topk_idx, | 638 | + torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups, |
| 569 | - dst, | 639 | + torch::Tensor dups, torch::Tensor counts, |
| 570 | - cu_seqlens, | 640 | + int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) { |
| 571 | - experts_to_copy, | 641 | + TORCH_CHECK(S > 0 && H > 0 && H % 8 == 0 && H <= 4 * 1024 * 1024 && |
| 572 | - dup_groups, | 642 | + K > 0 && K <= 16 && R > 0 && R <= 1024 && rank >= 0 && rank < R && |
| 573 | - dup_loffs, | 643 | + uint64_t(S) <= ((1ULL << 30) - 1) / uint64_t(K) / uint64_t(R), |
| 574 | - dup_counts, | 644 | + "invalid combine execution-plan dimensions"); |
| 575 | - tpe_all, | 645 | + TORCH_CHECK(R == 1 || (R % 2 == 0 && |
| 576 | - tpe_prefix, | 646 | + (R < 128 ? (R <= 8 || R % 8 == 0) : R % 16 == 0)), |
| 577 | - balance, | 647 | + "unsupported combine topology"); |
| 578 | - z, | 648 | + const int64_t n = S * K; |
| 579 | - alloc, | 649 | + TORCH_CHECK(n <= std::numeric_limits<uint32_t>::max() / 8U, |
| 580 | - alloc_cumsum, | 650 | + "combine scratch index exceeds uint32"); |
| 581 | - expert_offsets, | 651 | + for (const auto& tensor : {workspace, dst, groups, dups, counts}) { |
| 582 | - core_expert_counts, | 652 | + TORCH_CHECK(tensor.device().type() == c10::DeviceType::PrivateUse1 && |
| 583 | - dup_workspace, | 653 | + tensor.device() == dst.device() && tensor.is_contiguous(), |
| 584 | - dup_key_workspace, | 654 | + "combine planning tensors must be contiguous on the same NPU"); |
| 585 | - tiling, | 655 | + } |
| 586 | - reinterpret_cast<void*>(static_cast<uintptr_t>(symmetric_workspace_addr)), | 656 | + TORCH_CHECK(dst.scalar_type() == torch::kInt32 && dst.dim() == 1 && dst.numel() == n, |
| 587 | - ffts_addr); | 657 | + "dst must be int32 [S*K]"); |
| 658 | + TORCH_CHECK(groups.scalar_type() == torch::kInt32 && groups.dim() == 2 && | ||
| 659 | + groups.size(0) == n && groups.size(1) == 3, "groups must be int32 [S*K,3]"); | ||
| 660 | + TORCH_CHECK(counts.scalar_type() == torch::kInt32 && counts.dim() == 1 && | ||
| 661 | + (counts.numel() == 2 || counts.numel() == R + 2), "invalid dup counts"); | ||
| 662 | + const bool server = counts.numel() == R + 2; | ||
| 663 | + TORCH_CHECK(!server || R % 8 == 0, "server planning requires full 8-rank servers"); | ||
| 664 | + TORCH_CHECK(!server || uint64_t(n) <= kMoonEPServerDupRouteLimit, | ||
| 665 | + "server planning route exceeds packed capacity"); | ||
| 666 | + TORCH_CHECK(dups.scalar_type() == torch::kInt32 && dups.dim() == 1 && | ||
| 667 | + dups.numel() == (server ? 8 * n : n), "invalid dup member capacity"); | ||
| 668 | + const auto p = MakeCombinePutLayout(n, H, R, K); | ||
| 669 | + TORCH_CHECK(workspace.scalar_type() == torch::kUInt8 && workspace.dim() == 1 && | ||
| 670 | + uint64_t(workspace.numel()) >= p.bytes, "combine planning workspace too small"); | ||
| 671 | + for (const auto& tensor : {dst, groups, dups, counts}) | ||
| 672 | + TORCH_CHECK(!workspace.is_alias_of(tensor), "planning input must not alias exchange workspace"); | ||
| 673 | + const auto q = MakeCombineExecutionPlanLayout(n, R); | ||
| 674 | + auto plan = torch::empty({static_cast<int64_t>(q.bytes)}, dst.options().dtype(torch::kUInt8)); | ||
| 675 | + return plan; | ||
| 676 | +} | ||
| 677 | + | ||
| 678 | +torch::Tensor PlanningPrepareCombinePlan( | ||
| 679 | + torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups, | ||
| 680 | + torch::Tensor dups, torch::Tensor counts, | ||
| 681 | + int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) { | ||
| 682 | + auto plan = AllocateCombinePlan(workspace, dst, groups, dups, counts, S, H, K, R, rank); | ||
| 683 | + PlanningTilingData tiling{}; | ||
| 684 | + tiling.num_tokens = S; tiling.num_topk = K; tiling.world_size = R; | ||
| 685 | + tiling.rank = rank; tiling.server_dedup = counts.numel() == R + 2; | ||
| 686 | + tiling.block_dim = kCombinePutCores; | ||
| 687 | + tiling.combine_mode = 2U; // Synthetic/precomputed routes: same planning entry. | ||
| 688 | + tiling.combine_h = H; | ||
| 689 | + tiling.combine_workspace = reinterpret_cast<uint64_t>(workspace.data_ptr()); | ||
| 690 | + tiling.combine_plan = reinterpret_cast<uint64_t>(plan.data_ptr()); | ||
| 691 | + LaunchPlanningMetadataOnly(dst, groups, dups, counts, tiling); | ||
| 692 | + return plan; | ||
| 588 | } | 693 | } |
| 589 | 694 | ||
| 590 | } // namespace ascend_moonep::ops | 695 | } // 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,31 @@ 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 | +// Server-level dedup planner: also materializes the combine execution plan when | ||
| 142 | +// the tiling requests the fused mode. | ||
| 143 | +ASCEND_MOONEP_EXPORT void planning_server_dedup_kernel_do( | ||
| 144 | + void* stream, | ||
| 145 | + uint8_t* topk_idx, | ||
| 146 | + uint8_t* symmetric_buffer, | ||
| 147 | + uint8_t* dst, | ||
| 148 | + uint8_t* cu_seqlens, | ||
| 149 | + uint8_t* experts_to_copy, | ||
| 150 | + uint8_t* dup_groups, | ||
| 151 | + uint8_t* dup_loffs, | ||
| 152 | + uint8_t* dup_counts, | ||
| 153 | + uint8_t* tpe_all, | ||
| 154 | + uint8_t* tpe_prefix, | ||
| 155 | + uint8_t* balance, | ||
| 156 | + uint8_t* z_tensor, | ||
| 157 | + uint8_t* alloc_tensor, | ||
| 158 | + uint8_t* alloc_cumsum, | ||
| 159 | + uint8_t* expert_offsets, | ||
| 160 | + uint8_t* core_expert_counts, | ||
| 161 | + uint8_t* dup_workspace, | ||
| 162 | + uint8_t* dup_key_workspace, | ||
| 163 | + uint8_t* tiling_host, | ||
| 164 | + uint64_t ffts_addr); | ||
| 165 | + | ||
| 112 | ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | 166 | ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( |
| 113 | void* stream, | 167 | void* stream, |
| 114 | void* expert_grads, | 168 | 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 | ||
| @@ -11,6 +11,7 @@ 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 ( |
| 15 | launch_combine_op, | 16 | launch_combine_op, |
| 16 | launch_dispatch_op, | 17 | launch_dispatch_op, |
| @@ -71,6 +72,10 @@ class PlanningOp(KernelOp): | |||
| 71 | B = int(ctx["B"]) | 72 | B = int(ctx["B"]) |
| 72 | N = S * K | 73 | N = S * K |
| 73 | NvS = int(ctx["NvS"]) | 74 | NvS = int(ctx["NvS"]) |
| 75 | + # Planning output capacity depends on the dedup domain; rank and server share the same operator entry. | ||
| 76 | + server_dedup = plan.dedup_mode == "server" | ||
| 77 | + dup_capacity = RANKS_PER_SERVER * NvS if server_dedup else NvS | ||
| 78 | + count_size = R + 2 if server_dedup else 2 | ||
| 74 | _collect_inputs( | 79 | _collect_inputs( |
| 75 | "PlanningOp", | 80 | "PlanningOp", |
| 76 | tensors=( | 81 | tensors=( |
| @@ -82,8 +87,8 @@ class PlanningOp(KernelOp): | |||
| 82 | ("plan.zero_fill_ranges", plan.zero_fill_ranges, [E + B, 2], torch.int32), | 87 | ("plan.zero_fill_ranges", plan.zero_fill_ranges, [E + B, 2], torch.int32), |
| 83 | ("plan.remote_stats", plan.remote_stats, [2], torch.int32), | 88 | ("plan.remote_stats", plan.remote_stats, [2], torch.int32), |
| 84 | ("plan.dup_groups", plan.dup_groups, [NvS, 3], torch.int32), | 89 | ("plan.dup_groups", plan.dup_groups, [NvS, 3], torch.int32), |
| 85 | - ("plan.dup_loffs", plan.dup_loffs, [NvS], torch.int32), | 90 | + ("plan.dup_loffs", plan.dup_loffs, [dup_capacity], torch.int32), |
| 86 | - ("plan.dup_counts", plan.dup_counts, [2], torch.int32), | 91 | + ("plan.dup_counts", plan.dup_counts, [count_size], torch.int32), |
| 87 | ("ctx.planning_workspace", ctx["planning_workspace"], None, torch.int32), | 92 | ("ctx.planning_workspace", ctx["planning_workspace"], None, torch.int32), |
| 88 | ), | 93 | ), |
| 89 | scalars=(("shmem_instance_id", shmem_instance_id),), | 94 | scalars=(("shmem_instance_id", shmem_instance_id),), |
| @@ -92,7 +97,22 @@ class PlanningOp(KernelOp): | |||
| 92 | workspace = self.sym_workspace() | 97 | workspace = self.sym_workspace() |
| 93 | if workspace is None: | 98 | if workspace is None: |
| 94 | raise RuntimeError("PlanningOp requires a symmetric workspace") | 99 | raise RuntimeError("PlanningOp requires a symmetric workspace") |
| 95 | - launch_planning_op( | 100 | + # Custom NPU writes do not bump Tensor._version; invalidate prepared plans |
| 101 | + # explicitly whenever the supported planner rebuilds this plan's routing. | ||
| 102 | + if server_dedup: | ||
| 103 | + ctx['_combine_plan_generation'] = ctx.get('_combine_plan_generation', 0) + 1 | ||
| 104 | + object.__setattr__(plan, '_planning_generation', ctx['_combine_plan_generation']) | ||
| 105 | + object.__setattr__(plan, 'combine_execution_plan', None) | ||
| 106 | + ctx.pop('_planning_timing_events', None) | ||
| 107 | + if ctx.get('_planning_timing_enabled', False): | ||
| 108 | + from .planning import begin_base_planning_timing | ||
| 109 | + begin_base_planning_timing(ctx, plan) | ||
| 110 | + fused = server_dedup and ctx['_combine_use_udma'] | ||
| 111 | + fused_timing = None | ||
| 112 | + if fused: | ||
| 113 | + from .planning import begin_fused_combine_plan | ||
| 114 | + fused_timing = begin_fused_combine_plan() | ||
| 115 | + storage = launch_planning_op( | ||
| 96 | topk_flat, | 116 | topk_flat, |
| 97 | plan.dst, | 117 | plan.dst, |
| 98 | cu_seqlens, | 118 | cu_seqlens, |
| @@ -111,7 +131,18 @@ class PlanningOp(KernelOp): | |||
| 111 | int(self.num_sms), | 131 | int(self.num_sms), |
| 112 | rank, | 132 | rank, |
| 113 | R, | 133 | R, |
| 134 | + server_dedup, | ||
| 135 | + combine_workspace=ctx['combine_workspace'] if fused else None, | ||
| 136 | + hidden_size=int(ctx['H']) if fused else 0, | ||
| 114 | ) | 137 | ) |
| 138 | + # One planning kernel produces routing AND combine tables. This only | ||
| 139 | + # attaches its output/event; it does not launch a second kernel. | ||
| 140 | + if ctx.get('_planning_timing_enabled', False): | ||
| 141 | + from .planning import end_base_planning_timing | ||
| 142 | + end_base_planning_timing(ctx) | ||
| 143 | + if fused: | ||
| 144 | + from .planning import prepare_combine_plan | ||
| 145 | + prepare_combine_plan(ctx, plan, storage=storage, fused_timing=fused_timing) | ||
| 115 | 146 | ||
| 116 | 147 | ||
| 117 | class DispatchOp(KernelOp): | 148 | class DispatchOp(KernelOp): |
| @@ -152,6 +183,7 @@ class DispatchOp(KernelOp): | |||
| 152 | int(ctx["R"]), | 183 | int(ctx["R"]), |
| 153 | int(ctx["rank"]), | 184 | int(ctx["rank"]), |
| 154 | num_sms=self.num_sms, | 185 | num_sms=self.num_sms, |
| 186 | + server_dedup=plan.dedup_mode == "server", | ||
| 155 | ) | 187 | ) |
| 156 | 188 | ||
| 157 | def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan, | 189 | def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan, |
| @@ -177,6 +209,7 @@ class DispatchOp(KernelOp): | |||
| 177 | int(ctx["K"]), | 209 | int(ctx["K"]), |
| 178 | int(ctx["R"]), | 210 | int(ctx["R"]), |
| 179 | int(ctx["rank"]), | 211 | int(ctx["rank"]), |
| 212 | + plan.dedup_mode == "server", | ||
| 180 | ) | 213 | ) |
| 181 | 214 | ||
| 182 | 215 | ||
| @@ -189,12 +222,22 @@ class CombineOp(KernelOp): | |||
| 189 | - reads remote rows from symmetric ``ctx['hidden_buf']`` via shmem_ptr | 222 | - reads remote rows from symmetric ``ctx['hidden_buf']`` via shmem_ptr |
| 190 | - optional weight gather from ``ctx['weights_buf']`` into user-facing | 223 | - optional weight gather from ``ctx['weights_buf']`` into user-facing |
| 191 | output_sk [S, K] fp32 | 224 | output_sk [S, K] fp32 |
| 192 | - - launcher selects native/UDMA from ASCEND_MOONEP_COMBINE_USE_UDMA | 225 | + - launcher selects native / legacy-rank UDMA / server-dedup UDMA |
| 226 | + from the environment and the plan's dedup mode | ||
| 193 | - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule | 227 | - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule |
| 194 | """ | 228 | """ |
| 195 | 229 | ||
| 196 | def compute(self, ctx, output_sh, plan, output_sk=None, | 230 | def compute(self, ctx, output_sh, plan, output_sk=None, |
| 197 | shmem_instance_id: int = 0): | 231 | shmem_instance_id: int = 0): |
| 232 | + server_dedup = plan.dedup_mode == "server" | ||
| 233 | + if server_dedup: | ||
| 234 | + if not ctx['_combine_use_udma']: | ||
| 235 | + raise ValueError('server dedup requires UDMA combine') | ||
| 236 | + from .combine import launch_combine_prepared | ||
| 237 | + if plan.combine_execution_plan is None: | ||
| 238 | + raise ValueError('UDMA combine requires PlanningOp to generate its execution plan first') | ||
| 239 | + return launch_combine_prepared(ctx, output_sh, plan, | ||
| 240 | + plan.combine_execution_plan, output_sk) | ||
| 198 | weight_buf = ( | 241 | weight_buf = ( |
| 199 | ctx["weights_buf"].view(torch.float32) | 242 | ctx["weights_buf"].view(torch.float32) |
| 200 | if output_sk is not None else None | 243 | if output_sk is not None else None |
| @@ -217,6 +260,7 @@ class CombineOp(KernelOp): | |||
| 217 | num_sms=self.num_sms, | 260 | num_sms=self.num_sms, |
| 218 | ) | 261 | ) |
| 219 | 262 | ||
| 263 | + | ||
| 220 | class PrefetchOp(KernelOp): | 264 | class PrefetchOp(KernelOp): |
| 221 | """Corresponds to ``moonep.launch_prefetch``. | 265 | """Corresponds to ``moonep.launch_prefetch``. |
| 222 | 266 | ||
| @@ -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, |
| @@ -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 ] |
| @@ -16,8 +16,10 @@ Two mutually exclusive build paths: | |||
| 16 | 16 | ||
| 17 | 2. Ascend / NPU (when an Ascend toolchain is detected): compiles the | 17 | 2. Ascend / NPU (when an Ascend toolchain is detected): compiles the |
| 18 | vendored `npu_patch._C` extension from `npu_patch/native/csrc/` and | 18 | vendored `npu_patch._C` extension from `npu_patch/native/csrc/` and |
| 19 | - links the AscendC kernel library (`npu_patch/lib/libascend_moonep_kernels.so`) | 19 | + links the AscendC kernel libraries |
| 20 | - built by `npu_patch/scripts/build_base.sh` (wrapper: `build_a5.sh`). The GPU | 20 | + (`npu_patch/lib/libascend_moonep_kernels.so` and |
| 21 | + `npu_patch/lib/libascend_moonep_kernels_server_dedup.so` on Ascend950) built by | ||
| 22 | + `npu_patch/scripts/build_base.sh` (wrapper: `build_a5.sh`). The GPU | ||
| 21 | logic is unchanged. | 23 | logic is unchanged. |
| 22 | 24 | ||
| 23 | The backend is selected at build time by `_is_ascend_build()`: it prefers an | 25 | The backend is selected at build time by `_is_ascend_build()`: it prefers an |
| @@ -85,11 +87,17 @@ def _npu_extension(): | |||
| 85 | kernel_lib_dir = Path( | 87 | kernel_lib_dir = Path( |
| 86 | os.environ.get("ASCEND_MOONEP_KERNEL_LIB_DIR", ROOT / "npu_patch" / "lib") | 88 | os.environ.get("ASCEND_MOONEP_KERNEL_LIB_DIR", ROOT / "npu_patch" / "lib") |
| 87 | ) | 89 | ) |
| 88 | - if not (kernel_lib_dir / "libascend_moonep_kernels.so").exists(): | 90 | + use_udma = os.environ.get("ASCEND_MOONEP_UDMA", "0").strip() == "1" |
| 89 | - raise RuntimeError( | 91 | + kernel_libraries = ["ascend_moonep_kernels"] |
| 90 | - f"Kernel library not found in {kernel_lib_dir}. Run " | 92 | + if use_udma: |
| 91 | - "npu_patch/scripts/build_base.sh -soc_type <SOC_TYPE> first." | 93 | + kernel_libraries.append("ascend_moonep_kernels_server_dedup") |
| 92 | - ) | 94 | + for library in kernel_libraries: |
| 95 | + kernel_lib = f"lib{library}.so" | ||
| 96 | + if not (kernel_lib_dir / kernel_lib).exists(): | ||
| 97 | + raise RuntimeError( | ||
| 98 | + f"Kernel library {kernel_lib} not found in {kernel_lib_dir}. Run " | ||
| 99 | + "npu_patch/scripts/build_base.sh -soc_type <SOC_TYPE> first." | ||
| 100 | + ) | ||
| 93 | torch_npu_root = Path(torch_npu.__file__).resolve().parent | 101 | torch_npu_root = Path(torch_npu.__file__).resolve().parent |
| 94 | native = ROOT / "npu_patch" / "native" | 102 | native = ROOT / "npu_patch" / "native" |
| 95 | 103 | ||
| @@ -152,7 +160,7 @@ def _npu_extension(): | |||
| 152 | ] | 160 | ] |
| 153 | # Pass the build script's UDMA flag to the C++ extension. | 161 | # Pass the build script's UDMA flag to the C++ extension. |
| 154 | define_macros = [] | 162 | define_macros = [] |
| 155 | - if os.environ.get("ASCEND_MOONEP_UDMA", "0").strip() == "1": | 163 | + if use_udma: |
| 156 | define_macros.append(("ASCEND_MOONEP_UDMA", "1")) | 164 | define_macros.append(("ASCEND_MOONEP_UDMA", "1")) |
| 157 | # Product architecture macro for acl_shared_buffer.cpp's VMM export path | 165 | # Product architecture macro for acl_shared_buffer.cpp's VMM export path |
| 158 | # (A2 -> SHMEM does V2 DEFAULT; A3/A5 -> pre-export Fabric V2). build_base.sh | 166 | # (A2 -> SHMEM does V2 DEFAULT; A3/A5 -> pre-export Fabric V2). build_base.sh |
| @@ -170,7 +178,7 @@ def _npu_extension(): | |||
| 170 | define_macros=define_macros, | 178 | define_macros=define_macros, |
| 171 | include_dirs=include_dirs, | 179 | include_dirs=include_dirs, |
| 172 | library_dirs=library_dirs, | 180 | library_dirs=library_dirs, |
| 173 | - libraries=["ascend_moonep_kernels", "torch_npu", "ascendcl", "runtime", "shmem", "dl"], | 181 | + libraries=kernel_libraries + ["torch_npu", "ascendcl", "runtime", "shmem", "dl"], |
| 174 | extra_compile_args=["-O2", "-std=c++20"], | 182 | extra_compile_args=["-O2", "-std=c++20"], |
| 175 | extra_link_args=["-Wl,-rpath,$ORIGIN/lib"] | 183 | extra_link_args=["-Wl,-rpath,$ORIGIN/lib"] |
| 176 | + [f"-Wl,-rpath,{path}" for path in rpath_dirs], | 184 | + [f"-Wl,-rpath,{path}" for path in rpath_dirs], |
| @@ -24,6 +24,7 @@ mixed (do not mix). | |||
| 24 | from __future__ import annotations | 24 | from __future__ import annotations |
| 25 | 25 | ||
| 26 | import os | 26 | import os |
| 27 | +import warnings | ||
| 27 | 28 | ||
| 28 | import torch | 29 | import torch |
| 29 | import torch.distributed as dist | 30 | import torch.distributed as dist |
| @@ -43,12 +44,116 @@ from ._C import acl_shmem_barrier_all, acl_shmem_get_unique_id | |||
| 43 | from .runtime_audit import audit_loaded_shmem_library | 44 | from .runtime_audit import audit_loaded_shmem_library |
| 44 | 45 | ||
| 45 | 46 | ||
| 47 | +# --------------------------------------------------------------------------- | ||
| 48 | +# Dedup domain flags. | ||
| 49 | +# | ||
| 50 | +# The Buffer's dedup domain is fixed at construction (``dedup_mode``), but the | ||
| 51 | +# shmem bootstrap runs later, after every Buffer (and every framework-side VMM | ||
| 52 | +# chunk) exists, and it holds no Buffer handle. ``_create_context`` therefore | ||
| 53 | +# publishes the choice as two process environment variables -- the mode plus its | ||
| 54 | +# boolean flag -- and the bootstrap reads it back. A manually exported pair is | ||
| 55 | +# honoured identically, which lets a launcher configure the domain outside | ||
| 56 | +# Python without passing ``dedup_mode`` through every layer. | ||
| 57 | +# --------------------------------------------------------------------------- | ||
| 58 | +DEDUP_MODE_ENV = "ASCEND_MOONEP_DEDUP_MODE" | ||
| 59 | +SERVER_DEDUP_ENV = "ASCEND_MOONEP_SERVER_DEDUP" | ||
| 60 | +DEDUP_MODES = ("rank", "server") | ||
| 61 | + | ||
| 62 | +# UDMA QP count per peer pair when the caller does not configure one. | ||
| 63 | +DEFAULT_QP_COUNT = 2 | ||
| 64 | +# The server-level dedup kernels map chunks onto two active QPs per peer pair | ||
| 65 | +# (``GetChunkQpSlot``); any other count desynchronises dispatch/combine. | ||
| 66 | +SERVER_DEDUP_QP_COUNT = 2 | ||
| 67 | + | ||
| 68 | +_TRUE_VALUES = ("1", "true", "yes", "on") | ||
| 69 | +_FALSE_VALUES = ("0", "false", "no", "off") | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def publish_dedup_env(dedup_mode: str) -> None: | ||
| 73 | + """Publish a Buffer's dedup domain for the later shmem bootstrap. | ||
| 74 | + | ||
| 75 | + Writes ``ASCEND_MOONEP_DEDUP_MODE`` (``rank`` / ``server``) and | ||
| 76 | + ``ASCEND_MOONEP_SERVER_DEDUP`` (``1`` / ``0``) so that | ||
| 77 | + ``ShmemRuntime.init_with_buffer`` / ``init_with_ip_port`` -- and any child | ||
| 78 | + process or launcher inspecting the environment -- can tell which dedup | ||
| 79 | + domain this process uses without holding the Buffer. | ||
| 80 | + """ | ||
| 81 | + mode = str(dedup_mode).strip().lower() | ||
| 82 | + if mode not in DEDUP_MODES: | ||
| 83 | + raise ValueError( | ||
| 84 | + f"dedup_mode must be 'rank' or 'server', got {dedup_mode!r}") | ||
| 85 | + os.environ[DEDUP_MODE_ENV] = mode | ||
| 86 | + os.environ[SERVER_DEDUP_ENV] = "1" if mode == "server" else "0" | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +def server_dedup_enabled() -> bool: | ||
| 90 | + """Whether this process runs the server-level dedup domain. | ||
| 91 | + | ||
| 92 | + The boolean flag wins when it is explicitly set (it is the flag a launcher | ||
| 93 | + toggles on its own); otherwise the published mode decides. Anything | ||
| 94 | + unrecognised is treated as rank-level dedup, the process default. | ||
| 95 | + """ | ||
| 96 | + raw = os.environ.get(SERVER_DEDUP_ENV, "").strip().lower() | ||
| 97 | + if raw in _TRUE_VALUES: | ||
| 98 | + return True | ||
| 99 | + if raw in _FALSE_VALUES: | ||
| 100 | + return False | ||
| 101 | + return os.environ.get(DEDUP_MODE_ENV, "").strip().lower() == "server" | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +def resolve_qp_count(enable_udma: bool, qp_count: int = 0) -> int: | ||
| 105 | + """Resolve the per-peer UDMA QP count of a bootstrap call. | ||
| 106 | + | ||
| 107 | + ``qp_count=0`` means "not configured": fall back to | ||
| 108 | + ``ASCEND_MOONEP_QP_COUNT`` and then to :data:`DEFAULT_QP_COUNT`. QP | ||
| 109 | + configuration only exists on the UDMA path, so a non-UDMA bootstrap is left | ||
| 110 | + untouched. | ||
| 111 | + | ||
| 112 | + Server-level dedup only supports two QPs per peer pair, so a caller that | ||
| 113 | + configured anything else is overridden with a warning rather than failing | ||
| 114 | + the collective: the requested count is a performance knob, while the | ||
| 115 | + server kernels are only correct at two. | ||
| 116 | + """ | ||
| 117 | + if not enable_udma: | ||
| 118 | + return qp_count | ||
| 119 | + if not qp_count: | ||
| 120 | + qp_count = _env_qp_count() or DEFAULT_QP_COUNT | ||
| 121 | + if server_dedup_enabled() and qp_count != SERVER_DEDUP_QP_COUNT: | ||
| 122 | + warnings.warn( | ||
| 123 | + "server-level dedup only supports " | ||
| 124 | + f"qp_count={SERVER_DEDUP_QP_COUNT} (got {qp_count} from " | ||
| 125 | + "qp_count/ASCEND_MOONEP_QP_COUNT); forcing " | ||
| 126 | + f"qp_count={SERVER_DEDUP_QP_COUNT}", | ||
| 127 | + stacklevel=2, | ||
| 128 | + ) | ||
| 129 | + qp_count = SERVER_DEDUP_QP_COUNT | ||
| 130 | + return qp_count | ||
| 131 | + | ||
| 132 | + | ||
| 46 | def _env_udma_enabled() -> bool: | 133 | def _env_udma_enabled() -> bool: |
| 47 | return os.environ.get("ASCEND_MOONEP_USE_UDMA", "0").strip().lower() in ( | 134 | return os.environ.get("ASCEND_MOONEP_USE_UDMA", "0").strip().lower() in ( |
| 48 | "1", "true", "yes", "on" | 135 | "1", "true", "yes", "on" |
| 49 | ) | 136 | ) |
| 50 | 137 | ||
| 51 | 138 | ||
| 139 | +def _env_qp_count() -> int: | ||
| 140 | + """UDMA QP count per peer pair (``ASCEND_MOONEP_QP_COUNT``, default 2). | ||
| 141 | + | ||
| 142 | + Each QP is one more URMA connection created during shmem_init: at 64 ranks | ||
| 143 | + that is 63 * qp_count connections per rank, so lowering it to 1 shortens | ||
| 144 | + init noticeably at the cost of some UDMA bandwidth. Under server-level dedup | ||
| 145 | + the value is ignored: :func:`resolve_qp_count` forces 2 with a warning. | ||
| 146 | + """ | ||
| 147 | + raw = os.environ.get("ASCEND_MOONEP_QP_COUNT", "").strip() | ||
| 148 | + if not raw: | ||
| 149 | + return 0 | ||
| 150 | + try: | ||
| 151 | + value = int(raw) | ||
| 152 | + except ValueError: | ||
| 153 | + return 0 | ||
| 154 | + return value if value > 0 else 0 | ||
| 155 | + | ||
| 156 | + | ||
| 52 | def default_shmem_ip_port(master_addr: str, master_port: int) -> str: | 157 | def default_shmem_ip_port(master_addr: str, master_port: int) -> str: |
| 53 | """Derive the shmem DEFAULT-bootstrap ip_port URL from the torchrun | 158 | """Derive the shmem DEFAULT-bootstrap ip_port URL from the torchrun |
| 54 | rendezvous address. | 159 | rendezvous address. |
| @@ -155,6 +260,12 @@ class ShmemRuntime: | |||
| 155 | (``buffer_c.symmetric_descriptors()``, populated by ``Buffer`` / | 260 | (``buffer_c.symmetric_descriptors()``, populated by ``Buffer`` / |
| 156 | ``create_vmm_physical`` at construction). Must run AFTER every Buffer is | 261 | ``create_vmm_physical`` at construction). Must run AFTER every Buffer is |
| 157 | constructed and BEFORE the first dispatch/combine/prefetch/reduce_grad. | 262 | constructed and BEFORE the first dispatch/combine/prefetch/reduce_grad. |
| 263 | + | ||
| 264 | + ``qp_count`` is the per-peer UDMA QP count (``0`` = unset, resolved from | ||
| 265 | + ``ASCEND_MOONEP_QP_COUNT`` else 2). When the Buffer construction | ||
| 266 | + published the server-level dedup domain | ||
| 267 | + (``ASCEND_MOONEP_SERVER_DEDUP=1``), a non-2 value is overridden with a | ||
| 268 | + warning: the server dedup kernels only support two QPs. | ||
| 158 | """ | 269 | """ |
| 159 | if cls._poisoned: | 270 | if cls._poisoned: |
| 160 | raise RuntimeError( | 271 | raise RuntimeError( |
| @@ -164,8 +275,9 @@ class ShmemRuntime: | |||
| 164 | enable_udma = _env_udma_enabled() | 275 | enable_udma = _env_udma_enabled() |
| 165 | if cls._initialized: | 276 | if cls._initialized: |
| 166 | return | 277 | return |
| 167 | - if enable_udma and not qp_count: | 278 | + # Server-level dedup only supports two QPs per peer pair; the domain is |
| 168 | - qp_count = 2 | 279 | + # read from the flags published at Buffer construction. |
| 280 | + qp_count = resolve_qp_count(enable_udma, qp_count) | ||
| 169 | if ip_port is not None: | 281 | if ip_port is not None: |
| 170 | cls.init_with_ip_port(group=group, descriptors=descriptors, | 282 | cls.init_with_ip_port(group=group, descriptors=descriptors, |
| 171 | tail_bytes=tail_bytes, ip_port=ip_port, | 283 | tail_bytes=tail_bytes, ip_port=ip_port, |
| @@ -240,6 +352,10 @@ class ShmemRuntime: | |||
| 240 | omit it. ``descriptors`` defaults to the process-wide registered VMM | 352 | omit it. ``descriptors`` defaults to the process-wide registered VMM |
| 241 | allocations (``buffer_c.symmetric_descriptors()``). Timing is the | 353 | allocations (``buffer_c.symmetric_descriptors()``). Timing is the |
| 242 | same as ``init_with_buffer``. | 354 | same as ``init_with_buffer``. |
| 355 | + | ||
| 356 | + ``qp_count`` follows the same policy as ``init_with_buffer``: the | ||
| 357 | + per-peer UDMA QP count, forced to 2 with a warning when the process | ||
| 358 | + published the server-level dedup domain. | ||
| 243 | """ | 359 | """ |
| 244 | if cls._poisoned: | 360 | if cls._poisoned: |
| 245 | raise RuntimeError( | 361 | raise RuntimeError( |
| @@ -276,8 +392,7 @@ class ShmemRuntime: | |||
| 276 | ) | 392 | ) |
| 277 | if descriptors is None: | 393 | if descriptors is None: |
| 278 | descriptors = symmetric_descriptors() | 394 | descriptors = symmetric_descriptors() |
| 279 | - if enable_udma and not qp_count: | 395 | + qp_count = resolve_qp_count(enable_udma, qp_count) |
| 280 | - qp_count = 2 | ||
| 281 | shmem_init_with_ip_port( | 396 | shmem_init_with_ip_port( |
| 282 | int(rank), int(world_size), ip_port, descriptors, | 397 | int(rank), int(world_size), ip_port, descriptors, |
| 283 | tail_bytes=int(tail_bytes), | 398 | tail_bytes=int(tail_bytes), |
| @@ -4,7 +4,7 @@ | |||
| 4 | Like test_buffer_combine.py, verify exact round trips through the Buffer API. | 4 | Like test_buffer_combine.py, verify exact round trips through the Buffer API. |
| 5 | Keep three zero-copy results live in distinct caller-owned banks, then switch | 5 | Keep three zero-copy results live in distinct caller-owned banks, then switch |
| 6 | back to the default storage and check that copying results survive later calls. | 6 | back to the default storage and check that copying results survive later calls. |
| 7 | -Dispatch and Combine use MTE; expert pointer operations are tested separately. | 7 | +Exercise the default MTE backend and opt-in URMA server dedup on A5. |
| 8 | 8 | ||
| 9 | Run in fresh workers (EP2 or EP8): | 9 | Run in fresh workers (EP2 or EP8): |
| 10 | torchrun --nproc-per-node=2 -m pytest -s -x \ | 10 | torchrun --nproc-per-node=2 -m pytest -s -x \ |
| @@ -17,6 +17,7 @@ import pytest | |||
| 17 | 17 | ||
| 18 | from kernel_test_utils import init_shmem | 18 | from kernel_test_utils import init_shmem |
| 19 | from npu_patch import Buffer, ShmemRuntime | 19 | from npu_patch import Buffer, ShmemRuntime |
| 20 | +from npu_patch.api import _is_ascend950 | ||
| 20 | from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors | 21 | from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors |
| 21 | 22 | ||
| 22 | 23 | ||
| @@ -24,26 +25,34 @@ from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors | |||
| 24 | _KEEPALIVE = [] | 25 | _KEEPALIVE = [] |
| 25 | 26 | ||
| 26 | 27 | ||
| 27 | -def test_buffer_comm_buffers(dist_env): | 28 | +@pytest.mark.parametrize("dedup_mode", ["rank", "server"]) |
| 29 | +def test_buffer_comm_buffers(dist_env, dedup_mode): | ||
| 28 | rank, world = dist_env | 30 | rank, world = dist_env |
| 29 | if world not in (2, 8): | 31 | if world not in (2, 8): |
| 30 | pytest.skip("communication-bank recipe requires EP2 or EP8") | 32 | pytest.skip("communication-bank recipe requires EP2 or EP8") |
| 31 | if ShmemRuntime.is_initialized(): | 33 | if ShmemRuntime.is_initialized(): |
| 32 | raise RuntimeError("run this test in fresh workers without an active SHMEM heap") | 34 | raise RuntimeError("run this test in fresh workers without an active SHMEM heap") |
| 33 | - s, h, k, local, b = 16, 128, 1, 2, 2 | 35 | + server = dedup_mode == "server" |
| 34 | device = torch.device("npu", torch.npu.current_device()) | 36 | device = torch.device("npu", torch.npu.current_device()) |
| 37 | + if server and (world != 8 or not _is_ascend950( | ||
| 38 | + device.index, torch.npu.get_device_properties(device.index))): | ||
| 39 | + pytest.skip("server communication banks require eight Ascend950 ranks") | ||
| 40 | + s, h, k, local, b = 16, 128, 2 if server else 1, 2, 2 | ||
| 35 | buffer = Buffer(S=s, H=h, K=k, E=world * local, B=b, num_ep_ranks=world, | 41 | buffer = Buffer(S=s, H=h, K=k, E=world * local, B=b, num_ep_ranks=world, |
| 36 | - group=dist.group.WORLD, explicitly_destroy=True, use_udma=False) | 42 | + group=dist.group.WORLD, explicitly_destroy=True, use_udma=server, |
| 43 | + dedup_mode=dedup_mode) | ||
| 37 | sources = [] | 44 | sources = [] |
| 38 | _KEEPALIVE.extend((buffer, sources)) | 45 | _KEEPALIVE.extend((buffer, sources)) |
| 39 | for _ in range(3): | 46 | for _ in range(3): |
| 40 | for shape, dtype in (((s * k, h), torch.bfloat16), ((s * k,), torch.int32)): | 47 | for shape, dtype in (((s * k, h), torch.bfloat16), ((s * k,), torch.int32)): |
| 41 | sources.append(create_vmm_physical(shape, dtype, device.index)[0]) | 48 | sources.append(create_vmm_physical(shape, dtype, device.index)[0]) |
| 42 | # Register every bank in the same order on all ranks before SHMEM init. | 49 | # Register every bank in the same order on all ranks before SHMEM init. |
| 43 | - init_shmem(group=dist.group.WORLD, enable_udma=False) | 50 | + init_shmem(group=dist.group.WORLD, enable_udma=server) |
| 44 | banks = [buffer.prepare_comm_buffers(*sources[i:i + 2]) for i in range(0, 6, 2)] | 51 | banks = [buffer.prepare_comm_buffers(*sources[i:i + 2]) for i in range(0, 6, 2)] |
| 45 | current = torch_npu.npu.current_stream() | 52 | current = torch_npu.npu.current_stream() |
| 46 | routes = torch.zeros(s, k, dtype=torch.int32, device=device) | 53 | routes = torch.zeros(s, k, dtype=torch.int32, device=device) |
| 54 | + if server: | ||
| 55 | + routes[:, 1] = local | ||
| 47 | counts = torch.bincount(routes.flatten().long(), minlength=world * local).int() | 56 | counts = torch.bincount(routes.flatten().long(), minlength=world * local).int() |
| 48 | probabilities = torch.ones(s, k, dtype=torch.float32, device=device) | 57 | probabilities = torch.ones(s, k, dtype=torch.float32, device=device) |
| 49 | saved = [] | 58 | saved = [] |
| @@ -55,6 +64,7 @@ def test_buffer_comm_buffers(dist_env): | |||
| 55 | out, probs, _, plan, done = buffer.dispatch( | 64 | out, probs, _, plan, done = buffer.dispatch( |
| 56 | hidden, probabilities, routes, counts, async_finish=True, | 65 | hidden, probabilities, routes, counts, async_finish=True, |
| 57 | zero_copy=True, router_weights_zero_copy=True) | 66 | zero_copy=True, router_weights_zero_copy=True) |
| 67 | + assert (plan.combine_execution_plan is not None) == server | ||
| 58 | assert out.data_ptr() == bank.hidden.data_ptr() | 68 | assert out.data_ptr() == bank.hidden.data_ptr() |
| 59 | assert probs.data_ptr() == bank.route.data_ptr() | 69 | assert probs.data_ptr() == bank.route.data_ptr() |
| 60 | saved.append((hidden, out, plan, done, bank)) | 70 | saved.append((hidden, out, plan, done, bank)) |
| @@ -65,7 +75,7 @@ def test_buffer_comm_buffers(dist_env): | |||
| 65 | combined, _, event = buffer.combine(plan, out, async_finish=True, zero_copy=True) | 75 | combined, _, event = buffer.combine(plan, out, async_finish=True, zero_copy=True) |
| 66 | current.wait_event(event) | 76 | current.wait_event(event) |
| 67 | torch.npu.synchronize() | 77 | torch.npu.synchronize() |
| 68 | - torch.testing.assert_close(combined, hidden, atol=0, rtol=0) | 78 | + torch.testing.assert_close(combined, hidden * k, atol=0, rtol=0) |
| 69 | 79 | ||
| 70 | # None explicitly restores the default communication storage. | 80 | # None explicitly restores the default communication storage. |
| 71 | buffer.set_comm_buffers(None) | 81 | buffer.set_comm_buffers(None) |
| @@ -79,7 +89,7 @@ def test_buffer_comm_buffers(dist_env): | |||
| 79 | result, _, event = buffer.combine(plan, out, async_finish=True) | 89 | result, _, event = buffer.combine(plan, out, async_finish=True) |
| 80 | current.wait_event(event) | 90 | current.wait_event(event) |
| 81 | torch.npu.synchronize() | 91 | torch.npu.synchronize() |
| 82 | - torch.testing.assert_close(result, hidden, atol=0, rtol=0) | 92 | + torch.testing.assert_close(result, hidden * k, atol=0, rtol=0) |
| 83 | 93 | ||
| 84 | # Only successful, globally drained execution may release symmetric backing. | 94 | # Only successful, globally drained execution may release symmetric backing. |
| 85 | torch.npu.synchronize() | 95 | torch.npu.synchronize() |
| @@ -0,0 +1,127 @@ | |||
| 1 | +"""Server-dedup environment flags and the ``qp_count=2`` clamp. | ||
| 2 | + | ||
| 3 | +The Buffer's dedup domain is fixed at construction, while the shmem bootstrap | ||
| 4 | +runs later and holds no Buffer handle: ``_create_context`` publishes | ||
| 5 | +``ASCEND_MOONEP_DEDUP_MODE`` / ``ASCEND_MOONEP_SERVER_DEDUP`` and | ||
| 6 | +``ShmemRuntime.init_with_buffer`` / ``init_with_ip_port`` read them back to | ||
| 7 | +enforce the server domain's QP requirement (the server kernels only support two | ||
| 8 | +active QPs per peer pair). | ||
| 9 | + | ||
| 10 | +Covered here, host-only (no device allocation, no collective): | ||
| 11 | + | ||
| 12 | + 1. publishing / reading the dedup flags; | ||
| 13 | + 2. the QP-count policy: unchanged for rank-level dedup and for non-UDMA | ||
| 14 | + bootstraps, forced to 2 with a warning under server-level dedup. | ||
| 15 | + | ||
| 16 | +Run: | ||
| 17 | + python -m pytest -s test_npu/buffer_test/test_dedup_env_qp.py | ||
| 18 | +""" | ||
| 19 | + | ||
| 20 | +import os | ||
| 21 | +import sys | ||
| 22 | + | ||
| 23 | +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 24 | + | ||
| 25 | +import pytest | ||
| 26 | + | ||
| 27 | +from npu_patch import shmem_runtime as sr | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +_ENV_NAMES = ( | ||
| 31 | + sr.DEDUP_MODE_ENV, | ||
| 32 | + sr.SERVER_DEDUP_ENV, | ||
| 33 | + "ASCEND_MOONEP_QP_COUNT", | ||
| 34 | +) | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +@pytest.fixture(autouse=True) | ||
| 38 | +def clean_dedup_env(monkeypatch): | ||
| 39 | + """Every case starts without published flags or a QP override. | ||
| 40 | + | ||
| 41 | + ``publish_dedup_env`` writes ``os.environ`` directly (that is its job), so | ||
| 42 | + teardown also pops the variables instead of relying on ``monkeypatch`` undo | ||
| 43 | + records alone. | ||
| 44 | + """ | ||
| 45 | + for name in _ENV_NAMES: | ||
| 46 | + monkeypatch.delenv(name, raising=False) | ||
| 47 | + yield | ||
| 48 | + for name in _ENV_NAMES: | ||
| 49 | + os.environ.pop(name, None) | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def test_publish_roundtrip(): | ||
| 53 | + sr.publish_dedup_env("server") | ||
| 54 | + assert os.environ[sr.DEDUP_MODE_ENV] == "server" | ||
| 55 | + assert os.environ[sr.SERVER_DEDUP_ENV] == "1" | ||
| 56 | + assert sr.server_dedup_enabled() is True | ||
| 57 | + | ||
| 58 | + sr.publish_dedup_env("rank") | ||
| 59 | + assert os.environ[sr.DEDUP_MODE_ENV] == "rank" | ||
| 60 | + assert os.environ[sr.SERVER_DEDUP_ENV] == "0" | ||
| 61 | + assert sr.server_dedup_enabled() is False | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def test_publish_rejects_unknown_mode(): | ||
| 65 | + with pytest.raises(ValueError): | ||
| 66 | + sr.publish_dedup_env("board") | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def test_unset_flags_mean_rank_dedup(): | ||
| 70 | + assert sr.server_dedup_enabled() is False | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +def test_flag_wins_over_mode(monkeypatch): | ||
| 74 | + # A launcher may flip only the boolean flag; it stays authoritative. | ||
| 75 | + monkeypatch.setenv(sr.DEDUP_MODE_ENV, "rank") | ||
| 76 | + monkeypatch.setenv(sr.SERVER_DEDUP_ENV, "1") | ||
| 77 | + assert sr.server_dedup_enabled() is True | ||
| 78 | + | ||
| 79 | + monkeypatch.setenv(sr.DEDUP_MODE_ENV, "server") | ||
| 80 | + monkeypatch.setenv(sr.SERVER_DEDUP_ENV, "0") | ||
| 81 | + assert sr.server_dedup_enabled() is False | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def test_mode_alone_enables_server_dedup(monkeypatch): | ||
| 85 | + monkeypatch.setenv(sr.DEDUP_MODE_ENV, "server") | ||
| 86 | + assert sr.server_dedup_enabled() is True | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +def test_qp_count_defaults_and_env(monkeypatch): | ||
| 90 | + # Unset: two QPs per peer pair (the historical default). | ||
| 91 | + assert sr.resolve_qp_count(True, 0) == 2 | ||
| 92 | + # Explicit request wins over the environment. | ||
| 93 | + monkeypatch.setenv("ASCEND_MOONEP_QP_COUNT", "4") | ||
| 94 | + assert sr.resolve_qp_count(True, 0) == 4 | ||
| 95 | + assert sr.resolve_qp_count(True, 1) == 1 | ||
| 96 | + # QP configuration only exists on the UDMA path. | ||
| 97 | + assert sr.resolve_qp_count(False, 0) == 0 | ||
| 98 | + assert sr.resolve_qp_count(False, 4) == 4 | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +def test_rank_dedup_keeps_configured_qp_count(): | ||
| 102 | + sr.publish_dedup_env("rank") | ||
| 103 | + assert sr.resolve_qp_count(True, 4) == 4 | ||
| 104 | + assert sr.resolve_qp_count(True, 1) == 1 | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +def test_server_dedup_forces_two_qps_with_warning(): | ||
| 108 | + sr.publish_dedup_env("server") | ||
| 109 | + with pytest.warns(UserWarning, match="only supports qp_count=2"): | ||
| 110 | + assert sr.resolve_qp_count(True, 4) == 2 | ||
| 111 | + with pytest.warns(UserWarning, match="only supports qp_count=2"): | ||
| 112 | + assert sr.resolve_qp_count(True, 1) == 2 | ||
| 113 | + # Two is the supported value: nothing is corrected, nothing is warned. | ||
| 114 | + assert sr.resolve_qp_count(True, 2) == 2 | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +def test_server_dedup_overrides_qp_env(monkeypatch): | ||
| 118 | + monkeypatch.setenv("ASCEND_MOONEP_QP_COUNT", "8") | ||
| 119 | + sr.publish_dedup_env("server") | ||
| 120 | + with pytest.warns(UserWarning, match="only supports qp_count=2"): | ||
| 121 | + assert sr.resolve_qp_count(True, 0) == 2 | ||
| 122 | + | ||
| 123 | + | ||
| 124 | +def test_server_dedup_leaves_non_udma_bootstrap_alone(): | ||
| 125 | + sr.publish_dedup_env("server") | ||
| 126 | + # No QPs are created without enable_udma, so there is nothing to clamp. | ||
| 127 | + assert sr.resolve_qp_count(False, 0) == 0 | ||
| @@ -145,7 +145,8 @@ def init_shmem(group=None, enable_udma=None, qp_count=0, ip_port=None, args=None | |||
| 145 | return | 145 | return |
| 146 | descriptors = symmetric_descriptors() | 146 | descriptors = symmetric_descriptors() |
| 147 | if dist.is_initialized(): | 147 | if dist.is_initialized(): |
| 148 | - group = dist.group.WORLD | 148 | + if group is None: |
| 149 | + group = dist.group.WORLD | ||
| 149 | dist.barrier(group=group) | 150 | dist.barrier(group=group) |
| 150 | if _should_use_ip_port_bootstrap(ip_port=ip_port, args=args): | 151 | if _should_use_ip_port_bootstrap(ip_port=ip_port, args=args): |
| 151 | if ip_port is None: | 152 | if ip_port is None: |
| @@ -395,15 +396,30 @@ def dedup_plan_fields_equal(plan, snapshot): | |||
| 395 | for field in DEDUP_PLAN_FIELDS) | 396 | for field in DEDUP_PLAN_FIELDS) |
| 396 | 397 | ||
| 397 | 398 | ||
| 398 | -def _dedup_group_map(plan, *, max_print=5): | 399 | +def _dedup_group_map(plan, *, max_print=5, dedup_mode=None, |
| 399 | - """Build {primary_loff: sorted duplicate loff tuple} plus internal | 400 | + ranks_per_server=8): |
| 401 | + """Build {primary_loff: sorted duplicate tuple} plus internal | ||
| 400 | consistency errors. The builder allocates the compact prefixes with | 402 | consistency errors. The builder allocates the compact prefixes with |
| 401 | per-warp atomicAdds, so ``dup_groups`` / ``dup_loffs`` ordering is not | 403 | per-warp atomicAdds, so ``dup_groups`` / ``dup_loffs`` ordering is not |
| 402 | - stable — only the group set is compared.""" | 404 | + stable — only the group set is compared. |
| 405 | + | ||
| 406 | + ``dedup_mode`` defaults to the plan's own domain. Rank-level plans store | ||
| 407 | + duplicate *loffs* (< NvS); server-level plans store full destination | ||
| 408 | + addresses (< R * NvS) and reserve R+2 count rows, so both the capacity and | ||
| 409 | + the address range follow the domain instead of assuming rank. | ||
| 410 | + """ | ||
| 411 | + if dedup_mode is None: | ||
| 412 | + dedup_mode = plan.dedup_mode | ||
| 413 | + if dedup_mode not in ("rank", "server"): | ||
| 414 | + raise ValueError(f"unsupported dedup_mode: {dedup_mode!r}") | ||
| 403 | groups = plan.dup_groups.cpu() | 415 | groups = plan.dup_groups.cpu() |
| 404 | dup_loffs = plan.dup_loffs.cpu() | 416 | dup_loffs = plan.dup_loffs.cpu() |
| 405 | counts = plan.dup_counts.cpu() | 417 | counts = plan.dup_counts.cpu() |
| 406 | - NvS = dup_loffs.numel() | 418 | + NvS = int(plan.NvS) |
| 419 | + R = int(plan.R) | ||
| 420 | + is_server = dedup_mode == "server" | ||
| 421 | + capacity = ranks_per_server * NvS if is_server else NvS | ||
| 422 | + address_limit = R * NvS if is_server else NvS | ||
| 407 | errors = [] | 423 | errors = [] |
| 408 | mapping = {} | 424 | mapping = {} |
| 409 | 425 | ||
| @@ -412,9 +428,10 @@ def _dedup_group_map(plan, *, max_print=5): | |||
| 412 | if group_count < 0 or group_count > NvS: | 428 | if group_count < 0 or group_count > NvS: |
| 413 | errors.append(f"dup group count {group_count} out of range [0, {NvS}]") | 429 | errors.append(f"dup group count {group_count} out of range [0, {NvS}]") |
| 414 | group_count = max(0, min(group_count, NvS)) | 430 | group_count = max(0, min(group_count, NvS)) |
| 415 | - if dup_count_total < 0 or dup_count_total > NvS: | 431 | + if dup_count_total < 0 or dup_count_total > capacity: |
| 416 | - errors.append(f"dup loff count {dup_count_total} out of range [0, {NvS}]") | 432 | + errors.append( |
| 417 | - dup_count_total = max(0, min(dup_count_total, NvS)) | 433 | + f"dup loff count {dup_count_total} out of range [0, {capacity}]") |
| 434 | + dup_count_total = max(0, min(dup_count_total, capacity)) | ||
| 418 | 435 | ||
| 419 | seen_dups = [] | 436 | seen_dups = [] |
| 420 | for group_idx in range(group_count): | 437 | for group_idx in range(group_count): |
| @@ -436,7 +453,7 @@ def _dedup_group_map(plan, *, max_print=5): | |||
| 436 | dups = [] | 453 | dups = [] |
| 437 | for offset_t in dup_loffs[dup_start:dup_start + dup_count].tolist(): | 454 | for offset_t in dup_loffs[dup_start:dup_start + dup_count].tolist(): |
| 438 | offset = int(offset_t) | 455 | offset = int(offset_t) |
| 439 | - if not (0 <= offset < NvS): | 456 | + if not (0 <= offset < address_limit): |
| 440 | errors.append( | 457 | errors.append( |
| 441 | f"dup group {group_idx} contains out-of-range dup loff {offset}" | 458 | f"dup group {group_idx} contains out-of-range dup loff {offset}" |
| 442 | ) | 459 | ) |
| @@ -445,7 +462,7 @@ def _dedup_group_map(plan, *, max_print=5): | |||
| 445 | seen_dups.append(offset) | 462 | seen_dups.append(offset) |
| 446 | if primary in mapping: | 463 | if primary in mapping: |
| 447 | errors.append(f"primary loff {primary} appears in multiple dup groups") | 464 | errors.append(f"primary loff {primary} appears in multiple dup groups") |
| 448 | - if primary in dups: | 465 | + if not is_server and primary in dups: |
| 449 | errors.append(f"dup group {group_idx} lists its own primary {primary}") | 466 | errors.append(f"dup group {group_idx} lists its own primary {primary}") |
| 450 | mapping[primary] = tuple(sorted(dups)) | 467 | mapping[primary] = tuple(sorted(dups)) |
| 451 | 468 | ||
| @@ -456,16 +473,18 @@ def _dedup_group_map(plan, *, max_print=5): | |||
| 456 | errors.append( | 473 | errors.append( |
| 457 | f"dup loff count mismatch: header={dup_count_total}, used={len(seen_dups)}" | 474 | f"dup loff count mismatch: header={dup_count_total}, used={len(seen_dups)}" |
| 458 | ) | 475 | ) |
| 459 | - overlap = seen_dup_set & set(mapping.keys()) | 476 | + if not is_server: |
| 460 | - if overlap: | 477 | + overlap = seen_dup_set & set(mapping.keys()) |
| 461 | - errors.append( | 478 | + if overlap: |
| 462 | - f"rows appear both as primary and duplicate: {sorted(overlap)[:max_print]}" | 479 | + errors.append( |
| 463 | - ) | 480 | + f"rows appear both as primary and duplicate: {sorted(overlap)[:max_print]}" |
| 481 | + ) | ||
| 464 | 482 | ||
| 465 | return mapping, errors | 483 | return mapping, errors |
| 466 | 484 | ||
| 467 | 485 | ||
| 468 | -def dedup_plan_semantic_errors(name, actual, expected, max_print=5): | 486 | +def dedup_plan_semantic_errors(name, actual, expected, max_print=5, |
| 487 | + ranks_per_server=8): | ||
| 469 | errors = [] | 488 | errors = [] |
| 470 | for field in DEDUP_PLAN_FIELDS: | 489 | for field in DEDUP_PLAN_FIELDS: |
| 471 | actual_t = getattr(actual, field) | 490 | actual_t = getattr(actual, field) |
| @@ -482,17 +501,33 @@ def dedup_plan_semantic_errors(name, actual, expected, max_print=5): | |||
| 482 | if errors: | 501 | if errors: |
| 483 | return errors | 502 | return errors |
| 484 | 503 | ||
| 504 | + dedup_mode = actual.dedup_mode | ||
| 505 | + if expected.dedup_mode != dedup_mode: | ||
| 506 | + errors.append( | ||
| 507 | + f"{name} dedup domain actual={dedup_mode} " | ||
| 508 | + f"expected={expected.dedup_mode}") | ||
| 509 | + return errors | ||
| 510 | + | ||
| 485 | actual_counts = actual.dup_counts.cpu() | 511 | actual_counts = actual.dup_counts.cpu() |
| 486 | expected_counts = expected.dup_counts.cpu() | 512 | expected_counts = expected.dup_counts.cpu() |
| 487 | - for idx, label in ((0, "dup group count"), (1, "dup loff count")): | 513 | + if not torch.equal(actual_counts, expected_counts): |
| 488 | - a = int(actual_counts[idx].item()) | 514 | + diff = (actual_counts != expected_counts).nonzero().reshape(-1).tolist() |
| 489 | - e = int(expected_counts[idx].item()) | 515 | + idx = int(diff[0]) if diff else 0 |
| 490 | - if a != e: | 516 | + if idx == 0: |
| 491 | - errors.append(f"{name} {label} actual={a} expected={e}") | 517 | + label = "dup group count" |
| 518 | + elif idx == 1: | ||
| 519 | + label = "dup loff count" | ||
| 520 | + else: | ||
| 521 | + label = f"source prefix [{idx - 2}]" | ||
| 522 | + errors.append( | ||
| 523 | + f"{name} {label} actual={int(actual_counts[idx])} " | ||
| 524 | + f"expected={int(expected_counts[idx])}") | ||
| 492 | 525 | ||
| 493 | - actual_map, group_errors = _dedup_group_map(actual, max_print=max_print) | 526 | + map_kwargs = dict(max_print=max_print, dedup_mode=dedup_mode, |
| 527 | + ranks_per_server=ranks_per_server) | ||
| 528 | + actual_map, group_errors = _dedup_group_map(actual, **map_kwargs) | ||
| 494 | expected_map, expected_group_errors = _dedup_group_map( | 529 | expected_map, expected_group_errors = _dedup_group_map( |
| 495 | - expected, max_print=max_print | 530 | + expected, **map_kwargs |
| 496 | ) | 531 | ) |
| 497 | errors.extend(f"{name} actual {err}" for err in group_errors[:max_print]) | 532 | errors.extend(f"{name} actual {err}" for err in group_errors[:max_print]) |
| 498 | errors.extend(f"{name} expected {err}" for err in expected_group_errors[:max_print]) | 533 | errors.extend(f"{name} expected {err}" for err in expected_group_errors[:max_print]) |
| @@ -555,10 +590,15 @@ def assert_ulp_all_ranks(name, actual, expected, rank, R, max_ulps=1): | |||
| 555 | def dedup_plan_invariant_errors(case, ctx, plan): | 590 | def dedup_plan_invariant_errors(case, ctx, plan): |
| 556 | errors = [] | 591 | errors = [] |
| 557 | NvS = int(ctx["NvS"]) | 592 | NvS = int(ctx["NvS"]) |
| 593 | + R = int(ctx["R"]) | ||
| 594 | + dedup_mode = ctx.get("dedup_mode", plan.dedup_mode) | ||
| 595 | + ranks_per_server = int(ctx.get("ranks_per_server", 8)) | ||
| 596 | + is_server = dedup_mode == "server" | ||
| 597 | + capacity = ranks_per_server * NvS if is_server else NvS | ||
| 558 | expected_shapes = { | 598 | expected_shapes = { |
| 559 | "dup_groups": (NvS, 3), | 599 | "dup_groups": (NvS, 3), |
| 560 | - "dup_loffs": (NvS,), | 600 | + "dup_loffs": (capacity,), |
| 561 | - "dup_counts": (2,), | 601 | + "dup_counts": (R + 2,) if is_server else (2,), |
| 562 | } | 602 | } |
| 563 | 603 | ||
| 564 | for field, shape in expected_shapes.items(): | 604 | for field, shape in expected_shapes.items(): |
| @@ -574,10 +614,28 @@ def dedup_plan_invariant_errors(case, ctx, plan): | |||
| 574 | 614 | ||
| 575 | counts = plan.dup_counts.cpu() | 615 | counts = plan.dup_counts.cpu() |
| 576 | for idx, label in ((0, "dup group count"), (1, "dup loff count")): | 616 | for idx, label in ((0, "dup group count"), (1, "dup loff count")): |
| 617 | + limit = NvS if idx == 0 else capacity | ||
| 577 | count = int(counts[idx].item()) | 618 | count = int(counts[idx].item()) |
| 578 | - if count < 0 or count > NvS: | 619 | + if count < 0 or count > limit: |
| 579 | - errors.append(f"{label} {count} is out of range [0, {NvS}]") | 620 | + errors.append(f"{label} {count} is out of range [0, {limit}]") |
| 580 | 621 | ||
| 581 | - _mapping, group_errors = _dedup_group_map(plan) | 622 | + if is_server: |
| 623 | + prefixes = counts[2:].to(torch.int64) | ||
| 624 | + if prefixes.numel() != R: | ||
| 625 | + errors.append( | ||
| 626 | + f"server source prefixes must have {R} entries, " | ||
| 627 | + f"got {prefixes.numel()}") | ||
| 628 | + else: | ||
| 629 | + if int(prefixes[0].item()) != 0: | ||
| 630 | + errors.append( | ||
| 631 | + f"server source prefix[0] must be 0, got {int(prefixes[0].item())}") | ||
| 632 | + if not bool(torch.all(prefixes[1:] >= prefixes[:-1]).item()): | ||
| 633 | + errors.append("server source prefixes are not non-decreasing") | ||
| 634 | + if int(prefixes[-1].item()) > int(counts[0].item()): | ||
| 635 | + errors.append( | ||
| 636 | + "server source prefix exceeds the total group count") | ||
| 637 | + | ||
| 638 | + _mapping, group_errors = _dedup_group_map( | ||
| 639 | + plan, dedup_mode=dedup_mode, ranks_per_server=ranks_per_server) | ||
| 582 | errors.extend(group_errors) | 640 | errors.extend(group_errors) |
| 583 | return errors | 641 | return errors |
| @@ -35,7 +35,7 @@ from npu_patch.launchers import ( | |||
| 35 | launch_planning_op, | 35 | launch_planning_op, |
| 36 | planning_workspace_sizes, | 36 | planning_workspace_sizes, |
| 37 | ) | 37 | ) |
| 38 | -from npu_patch.planning import allocate_planning_outputs | 38 | +from npu_patch.planning import RANKS_PER_SERVER, allocate_planning_outputs |
| 39 | from generate_topk_routing import generate_topk_routing | 39 | from generate_topk_routing import generate_topk_routing |
| 40 | 40 | ||
| 41 | 41 | ||
| @@ -294,6 +294,8 @@ def build_route_reference( | |||
| 294 | alloc_cumsum: torch.Tensor, | 294 | alloc_cumsum: torch.Tensor, |
| 295 | expert_offsets: torch.Tensor, | 295 | expert_offsets: torch.Tensor, |
| 296 | NvS: int, | 296 | NvS: int, |
| 297 | + *, | ||
| 298 | + ranks_per_domain: int = 1, | ||
| 297 | ): | 299 | ): |
| 298 | world_size, num_tokens, num_topk = (int(v) for v in topk.shape) | 300 | world_size, num_tokens, num_topk = (int(v) for v in topk.shape) |
| 299 | route_count = num_tokens * num_topk | 301 | route_count = num_tokens * num_topk |
| @@ -349,10 +351,11 @@ def build_route_reference( | |||
| 349 | 351 | ||
| 350 | raw_dst = raw_dst_flat.reshape(world_size, num_tokens, num_topk) | 352 | raw_dst = raw_dst_flat.reshape(world_size, num_tokens, num_topk) |
| 351 | dest_ranks = torch.div(raw_dst, NvS, rounding_mode="floor") | 353 | dest_ranks = torch.div(raw_dst, NvS, rounding_mode="floor") |
| 352 | - duplicate_mask = torch.zeros_like(dest_ranks, dtype=torch.bool) | 354 | + domains = dest_ranks // ranks_per_domain |
| 355 | + duplicate_mask = torch.zeros_like(domains, dtype=torch.bool) | ||
| 353 | for kidx in range(1, num_topk): | 356 | for kidx in range(1, num_topk): |
| 354 | duplicate_mask[:, :, kidx] = ( | 357 | duplicate_mask[:, :, kidx] = ( |
| 355 | - dest_ranks[:, :, :kidx] == dest_ranks[:, :, kidx:kidx + 1] | 358 | + domains[:, :, :kidx] == domains[:, :, kidx:kidx + 1] |
| 356 | ).any(dim=2) | 359 | ).any(dim=2) |
| 357 | dst = torch.where(duplicate_mask, -raw_dst - 1, raw_dst) | 360 | dst = torch.where(duplicate_mask, -raw_dst - 1, raw_dst) |
| 358 | return order, raw_dst, dst | 361 | return order, raw_dst, dst |
| @@ -362,39 +365,49 @@ def build_dup_reference_for_rank( | |||
| 362 | raw_dst_by_route: torch.Tensor, | 365 | raw_dst_by_route: torch.Tensor, |
| 363 | NvS: int, | 366 | NvS: int, |
| 364 | dup_rank: int, | 367 | dup_rank: int, |
| 368 | + *, | ||
| 369 | + ranks_per_domain: int = 1, | ||
| 365 | ): | 370 | ): |
| 366 | world_size = int(raw_dst_by_route.shape[0]) | 371 | world_size = int(raw_dst_by_route.shape[0]) |
| 367 | if dup_rank < 0 or dup_rank >= world_size: | 372 | if dup_rank < 0 or dup_rank >= world_size: |
| 368 | raise ValueError(f"dup_rank must be in [0, {world_size}), got {dup_rank}") | 373 | raise ValueError(f"dup_rank must be in [0, {world_size}), got {dup_rank}") |
| 369 | 374 | ||
| 370 | dest_ranks = torch.div(raw_dst_by_route, NvS, rounding_mode="floor") | 375 | dest_ranks = torch.div(raw_dst_by_route, NvS, rounding_mode="floor") |
| 371 | - loffs = torch.remainder(raw_dst_by_route, NvS) | 376 | + domain_mask = dest_ranks // ranks_per_domain == dup_rank // ranks_per_domain |
| 372 | - local_mask = dest_ranks == dup_rank | 377 | + primary_indices = domain_mask.to(torch.int64).argmax(dim=2, keepdim=True) |
| 373 | - local_route_ordinals = local_mask.cumsum(dim=2) | 378 | + primary_raw = raw_dst_by_route.gather(2, primary_indices).squeeze(2) |
| 374 | - routes_per_group = local_mask.sum(dim=2) | 379 | + routes_per_group = domain_mask.sum(dim=2) |
| 375 | - valid_groups = routes_per_group > 1 | 380 | + # Each group belongs to the rank hosting its first route in top-k order. |
| 381 | + valid_groups = (routes_per_group > 1) & (primary_raw // NvS == dup_rank) | ||
| 376 | duplicate_counts = routes_per_group[valid_groups] - 1 | 382 | duplicate_counts = routes_per_group[valid_groups] - 1 |
| 377 | group_count = int(duplicate_counts.numel()) | 383 | group_count = int(duplicate_counts.numel()) |
| 378 | loff_count = int(duplicate_counts.sum().item()) | 384 | loff_count = int(duplicate_counts.sum().item()) |
| 379 | - if group_count > NvS or loff_count > NvS: | 385 | + loff_capacity = NvS * ranks_per_domain |
| 386 | + if group_count > NvS or loff_count > loff_capacity: | ||
| 380 | raise ValueError( | 387 | raise ValueError( |
| 381 | - "source-dup reference exceeds NvS capacity: " | 388 | + "source-dup reference exceeds capacity: " |
| 382 | - f"groups={group_count}, loffs={loff_count}, NvS={NvS}" | 389 | + f"groups={group_count}/{NvS}, loffs={loff_count}/{loff_capacity}" |
| 383 | ) | 390 | ) |
| 384 | 391 | ||
| 385 | dup_groups = torch.zeros((NvS, 3), dtype=torch.int64) | 392 | dup_groups = torch.zeros((NvS, 3), dtype=torch.int64) |
| 386 | - dup_loffs = torch.zeros(NvS, dtype=torch.int64) | 393 | + dup_loffs = torch.zeros(loff_capacity, dtype=torch.int64) |
| 387 | dup_counts = torch.tensor((group_count, loff_count), dtype=torch.int64) | 394 | dup_counts = torch.tensor((group_count, loff_count), dtype=torch.int64) |
| 395 | + server_dedup = ranks_per_domain > 1 | ||
| 396 | + if server_dedup: | ||
| 397 | + groups_per_source = valid_groups.sum(dim=1) | ||
| 398 | + source_prefixes = groups_per_source.cumsum(dim=0) - groups_per_source | ||
| 399 | + dup_counts = torch.cat((dup_counts, source_prefixes)) | ||
| 388 | if group_count > 0: | 400 | if group_count > 0: |
| 389 | - primary_indices = local_mask.to(torch.int64).argmax(dim=2) | ||
| 390 | - primary_loffs = loffs.gather(2, primary_indices.unsqueeze(2)).squeeze(2) | ||
| 391 | loff_starts = duplicate_counts.cumsum(dim=0) - duplicate_counts | 401 | loff_starts = duplicate_counts.cumsum(dim=0) - duplicate_counts |
| 392 | 402 | ||
| 393 | - dup_groups[:group_count, 0] = primary_loffs[valid_groups] | 403 | + dup_groups[:group_count, 0] = primary_raw[valid_groups] % NvS |
| 394 | dup_groups[:group_count, 1] = loff_starts | 404 | dup_groups[:group_count, 1] = loff_starts |
| 395 | dup_groups[:group_count, 2] = duplicate_counts | 405 | dup_groups[:group_count, 2] = duplicate_counts |
| 396 | - duplicate_mask = local_mask & (local_route_ordinals > 1) | 406 | + duplicate_mask = ( |
| 397 | - dup_loffs[:loff_count] = loffs[duplicate_mask] | 407 | + valid_groups.unsqueeze(2) & domain_mask & (domain_mask.cumsum(dim=2) > 1) |
| 408 | + ) | ||
| 409 | + duplicate_raw = raw_dst_by_route[duplicate_mask] | ||
| 410 | + dup_loffs[:loff_count] = duplicate_raw if server_dedup else duplicate_raw % NvS | ||
| 398 | 411 | ||
| 399 | return ( | 412 | return ( |
| 400 | dup_groups.to(torch.int32), | 413 | dup_groups.to(torch.int32), |
| @@ -409,6 +422,8 @@ def planning_reference( | |||
| 409 | num_prefetch_slots: int, | 422 | num_prefetch_slots: int, |
| 410 | NvS: int, | 423 | NvS: int, |
| 411 | dup_rank: int, | 424 | dup_rank: int, |
| 425 | + *, | ||
| 426 | + dedup_mode: str = "rank", | ||
| 412 | ) -> PlanningReference: | 427 | ) -> PlanningReference: |
| 413 | topk = topk.detach().cpu().to(torch.int64).contiguous() | 428 | topk = topk.detach().cpu().to(torch.int64).contiguous() |
| 414 | if topk.ndim != 3: | 429 | if topk.ndim != 3: |
| @@ -425,6 +440,13 @@ def planning_reference( | |||
| 425 | raise ValueError("current Ascend planning kernel requires B == E / R") | 440 | raise ValueError("current Ascend planning kernel requires B == E / R") |
| 426 | if NvS < route_count: | 441 | if NvS < route_count: |
| 427 | raise ValueError("NvS must be at least S * K") | 442 | raise ValueError("NvS must be at least S * K") |
| 443 | + if dedup_mode not in ("rank", "server"): | ||
| 444 | + raise ValueError(f"unsupported dedup mode: {dedup_mode!r}") | ||
| 445 | + ranks_per_domain = RANKS_PER_SERVER if dedup_mode == "server" else 1 | ||
| 446 | + if world_size % ranks_per_domain != 0: | ||
| 447 | + raise ValueError("server dedup requires complete eight-rank servers") | ||
| 448 | + if dedup_mode == "server" and NvS != route_count: | ||
| 449 | + raise ValueError("server dedup requires NvS == S * K") | ||
| 428 | 450 | ||
| 429 | tpe = tokens_per_expert_from_topk(topk.to(torch.int32), num_experts).to(torch.int64) | 451 | tpe = tokens_per_expert_from_topk(topk.to(torch.int32), num_experts).to(torch.int64) |
| 430 | tpe_cumsum = tpe.cumsum(dim=0) | 452 | tpe_cumsum = tpe.cumsum(dim=0) |
| @@ -526,6 +548,7 @@ def planning_reference( | |||
| 526 | alloc_cumsum, | 548 | alloc_cumsum, |
| 527 | expert_offsets, | 549 | expert_offsets, |
| 528 | NvS, | 550 | NvS, |
| 551 | + ranks_per_domain=ranks_per_domain, | ||
| 529 | ) | 552 | ) |
| 530 | raw_dst = raw_dst_3d.reshape(world_size, route_count) | 553 | raw_dst = raw_dst_3d.reshape(world_size, route_count) |
| 531 | 554 | ||
| @@ -533,6 +556,7 @@ def planning_reference( | |||
| 533 | raw_dst_3d, | 556 | raw_dst_3d, |
| 534 | NvS, | 557 | NvS, |
| 535 | dup_rank, | 558 | dup_rank, |
| 559 | + ranks_per_domain=ranks_per_domain, | ||
| 536 | ) | 560 | ) |
| 537 | 561 | ||
| 538 | return PlanningReference( | 562 | return PlanningReference( |