From e7c809f759b83c58310ed72ea19fe08570850d49 Mon Sep 17 00:00:00 2001 From: Jin Li <59594262+liji-nv@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:08:24 +0800 Subject: [PATCH 1/6] [None][perf] MoE: add online drift-aware dynamic expert placement without offline calibration Static warmup placement lags behind shifting online expert hotspots when counter history accumulates across windows. Add zero-env, typed online drift-aware load tracking and hot-path optimizations to WarmupPlacementController: - Introduce frozen OnlineDriftConfig (default step_ema=0.5, drift_alpha=0.4) and rank-0 _OnlineLoadTracker for exponential increment smoothing and first-order distribution drift extrapolation without offline calibration. - Synchronize post-decay global counter snapshots via MPI.Reduce to rank 0 so per-rank floor rounding never drops small route counts, while keeping inter-round EMA forgetting decoupled from int32 overflow halving. - Add optional typed post-freeze concurrency-shift re-adaptation (max_readapts, default 0 to preserve zero post-freeze overhead) with rank-0 decision broadcast to eliminate cross-rank floating-point divergence. - Enforce fail-closed bijection and replicated-cover validation in apply_plan and register_layer. - Optimize Triton _count_kernel with CUDA-graph-safe flag/bound early exit, mask short-circuiting before router logit loads, and adaptive rows-per-CTA; vectorize plan_layer_copy_moves and plan_layer_swaps while preserving exact determinism and max_moved_fraction budgets. - Extend test_moe_warmup_placement.py with bijection assertions, CPU online drift/determinism/decay-sync/fail-closed regression coverage, and CUDA Graph count_routing regression coverage. Signed-off-by: Jin Li <59594262+liji-nv@users.noreply.github.com> --- .../moe/fused_moe/moe_warmup_placement.py | 433 +++++++++++++++--- .../_torch/moe/test_moe_warmup_placement.py | 152 ++++++ 2 files changed, 529 insertions(+), 56 deletions(-) diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py index 9dd06631c330..bccb7f0a7cad 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py @@ -35,6 +35,11 @@ With ``min_round_gain`` a round whose plan lowers the planner's estimate (slowest rank over the mean, averaged over layers) by fewer percentage points moves nothing. With ``decay < 1`` the counters are scaled by it after every round, moved or not, so later rounds follow recent traffic. +By default the planner also runs online drift-aware load tracking on rank 0 +(``OnlineDriftConfig``): per-check-interval counter increments are exponentially smoothed +(``step_ema``) and extrapolated along their round-to-round distribution delta (``drift_alpha``), +requiring zero offline calibration files. Optional post-freeze re-adaptation (``max_readapts > 0``) +watches EP-wide live-row shifts after freeze and re-opens bounded placement rounds when load shifts. With a large ``max_migrations``, no ``deadline_step`` and ``min_pos >= 2`` (a request's first decode step never counts) the placement follows the served decode traffic for the whole run; ``count_every_steps`` then counts one forward in that many, to keep the per-step host work of the @@ -137,6 +142,152 @@ class RouteCounters(NamedTuple): row_offset: int # the launch's first row in the forward +@dataclasses.dataclass(frozen=True) +class OnlineDriftConfig: + """Typed parameters for online drift-aware load tracking and optional post-freeze re-adaptation. + + ``step_ema`` exponentially averages per-check-interval counter increments on rank 0 (``0.0`` + disables EMA and uses the raw counters directly). ``drift_alpha`` extrapolates each layer's + normalized routing distribution one step along its round-to-round delta (``0.0`` disables + extrapolation). ``max_readapts > 0`` monitors post-freeze EP-wide live-row shifts and re-opens + bounded placement rounds when load moves outside ``(readapt_ratio_low, readapt_ratio_high)``. + """ + + step_ema: float = 0.5 + drift_alpha: float = 0.4 + max_readapts: int = 0 + readapt_cooldown_steps: int = 48 + readapt_check_interval: int = 32 + readapt_ratio_high: float = 1.4 + readapt_ratio_low: float = 0.7 + readapt_min_window_steps: int = 96 + + def __post_init__(self) -> None: + if not (math.isfinite(self.step_ema) and 0.0 <= self.step_ema < 1.0): + raise ValueError(f"{_LOG} step_ema must be in [0, 1), got {self.step_ema}") + if not (math.isfinite(self.drift_alpha) and self.drift_alpha >= 0.0): + raise ValueError(f"{_LOG} drift_alpha must be >= 0, got {self.drift_alpha}") + if self.max_readapts < 0: + raise ValueError(f"{_LOG} max_readapts must be >= 0, got {self.max_readapts}") + if self.readapt_cooldown_steps < 1: + raise ValueError( + f"{_LOG} readapt_cooldown_steps must be >= 1, got {self.readapt_cooldown_steps}" + ) + if self.readapt_check_interval < 1: + raise ValueError( + f"{_LOG} readapt_check_interval must be >= 1, got {self.readapt_check_interval}" + ) + if not (math.isfinite(self.readapt_ratio_high) and self.readapt_ratio_high > 1.0): + raise ValueError( + f"{_LOG} readapt_ratio_high must be > 1, got {self.readapt_ratio_high}" + ) + if not (math.isfinite(self.readapt_ratio_low) and 0.0 < self.readapt_ratio_low < 1.0): + raise ValueError( + f"{_LOG} readapt_ratio_low must be in (0, 1), got {self.readapt_ratio_low}" + ) + if self.readapt_min_window_steps < 1: + raise ValueError( + f"{_LOG} readapt_min_window_steps must be >= 1, got {self.readapt_min_window_steps}" + ) + + @property + def uses_ema(self) -> bool: + return self.step_ema > 0.0 + + @property + def uses_drift(self) -> bool: + return self.drift_alpha > 0.0 + + +def predict_drifted_load( + load: np.ndarray, + prev_prob: Optional[np.ndarray], + drift_alpha: float, +) -> Tuple[np.ndarray, Optional[np.ndarray]]: + """Extrapolate ``load`` one step along its normalized distribution drift. + + Returns ``(predicted_load, cur_prob)`` where ``predicted_load`` is non-negative and preserves + the total mass of ``load``. Deterministic in float64. + """ + arr = np.asarray(load, dtype=np.float64) + total = float(arr.sum()) + if not (math.isfinite(total) and total > 0.0): + return arr, None + cur_prob = arr / total + if drift_alpha <= 0.0 or prev_prob is None or prev_prob.shape != cur_prob.shape: + return arr, cur_prob + pred = np.maximum(cur_prob + drift_alpha * (cur_prob - prev_prob), 0.0) + pred_sum = float(pred.sum()) + if not (math.isfinite(pred_sum) and pred_sum > 0.0): + return arr, cur_prob + return (pred / pred_sum) * total, cur_prob + + +class _OnlineLoadTracker: + """Rank-0 online EMA and drift-extrapolation tracker over global routing histograms.""" + + def __init__(self, config: OnlineDriftConfig) -> None: + self.config = config + self._ema: Optional[np.ndarray] = None + self._prev_glob: Optional[np.ndarray] = None + self._prev_prob: Dict[int, np.ndarray] = {} + + @property + def uses_ema(self) -> bool: + return self.config.uses_ema + + @property + def uses_drift(self) -> bool: + return self.config.uses_drift + + def reset(self) -> None: + self._ema = None + self._prev_glob = None + self._prev_prob.clear() + + def observe(self, glob: np.ndarray) -> None: + """Fold the newly counted routes since the previous check into the per-layer EMA.""" + if not self.uses_ema: + return + if self._prev_glob is None: + delta = glob.astype(np.float64) + else: + delta = np.maximum(glob - self._prev_glob, 0).astype(np.float64) + self._prev_glob = glob.copy() + if delta.any(): + if self._ema is None: + self._ema = delta + else: + self._ema = self.config.step_ema * self._ema + delta + + def layer_load( + self, layer_index: int, num_experts: int, glob: np.ndarray + ) -> Tuple[np.ndarray, Optional[np.ndarray]]: + """Return ``(effective_load, cur_prob)`` for planning ``layer_index``.""" + if self.uses_ema and self._ema is not None: + ema_row = self._ema[layer_index, :num_experts] + raw = ema_row if ema_row.any() else glob[layer_index, :num_experts].astype(np.float64) + else: + raw = glob[layer_index, :num_experts].astype(np.float64) + if not raw.any(): + return raw, None + return predict_drifted_load(raw, self._prev_prob.get(layer_index), self.config.drift_alpha) + + def on_counters_decayed(self, decayed_glob: Optional[np.ndarray], decay: float = 1.0) -> None: + """Synchronize the baseline snapshot and EMA weight with the post-decay counters.""" + if not self.uses_ema: + return + if decayed_glob is not None: + self._prev_glob = decayed_glob + if decay < 1.0 and self._ema is not None: + self._ema = self._ema * decay + + def commit_probs(self, next_prob: Dict[int, np.ndarray]) -> None: + """Record the normalized distributions observed in a completed planning round.""" + if self.uses_drift and next_prob: + self._prev_prob.update(next_prob) + + # ----------------------------------------------------------------------------------- schedule NONE, CHECK, LAST = 0, 1, 2 @@ -237,6 +388,12 @@ def transfer_groups( return groups +def is_bijective_placement(slot_expert: Sequence[int], num_experts: int) -> bool: + """A one-copy placement that maps every expert 0..num_experts-1 to a unique slot.""" + se = list(slot_expert) + return len(se) == num_experts and set(se) == set(range(num_experts)) + + def is_replicated_cover( slot_expert: Sequence[int], num_experts: int, slots_per_rank: int, ep_size: int ) -> bool: @@ -252,6 +409,16 @@ def is_replicated_cover( ) +def is_valid_placement( + slot_expert: Sequence[int], num_experts: int, slots_per_rank: int, ep_size: int +) -> bool: + """Whether ``slot_expert`` is a valid one-copy bijection or replicated cover.""" + total_slots = slots_per_rank * ep_size + if total_slots == num_experts: + return is_bijective_placement(slot_expert, num_experts) + return is_replicated_cover(slot_expert, num_experts, slots_per_rank, ep_size) + + def copy_transfers( old: Sequence[int], new: Sequence[int], slots_per_rank: int ) -> List[Tuple[int, int]]: @@ -351,7 +518,6 @@ def plan_layer_copy_moves( holds[rank_of, se] = True per_copy = np.asarray(weight(lam / np.maximum(copies, 1)), dtype=np.float64) loads = np.bincount(rank_of, weights=per_copy[se], minlength=ranks) - rank_ids = np.arange(ranks) moves = 0 while moves < max_moves: donors = np.flatnonzero(copies[se] > target[se]) @@ -363,21 +529,23 @@ def plan_layer_copy_moves( don_new = np.asarray(weight(lam[dex] / (copies[dex] - 1)), dtype=np.float64) # Rank load changes [receiver, donor slot, rank]: the receiver's copies get lighter, the # donor expert's other copies heavier, and the donor slot's rank swaps one copy for another. - own = rank_ids[None, :] == drank[:, None] rec_holds = holds[:, rec].T - don_holds = holds[:, dex].T & ~own - delta = (rec_holds * (rec_new - per_copy[rec])[:, None])[:, None, :] + ( - don_holds * (don_new - per_copy[dex])[:, None] - )[None, :, :] - delta += own[None, :, :] * (rec_new[:, None] - per_copy[dex][None, :])[:, :, None] - new_loads = loads + delta + don_holds = holds[:, dex].T.copy() + d_idx = np.arange(donors.size) + don_holds[d_idx, drank] = False + base_rec = loads + rec_holds * (rec_new - per_copy[rec])[:, None] + don_delta = don_holds * (don_new - per_copy[dex])[:, None] + new_loads = base_rec[:, None, :] + don_delta[None, :, :] + new_loads[:, d_idx, drank] += rec_new[:, None] - per_copy[dex][None, :] peak = new_loads.max(axis=2) ok = ~holds[drank[None, :], rec[:, None]] & (peak <= loads.max()) if not ok.any(): break - sq = (new_loads**2).sum(axis=2) - flat = np.lexsort((sq[ok], peak[ok]))[0] - i, j = (int(x[flat]) for x in np.nonzero(ok)) + best_peak = peak[ok].min() + tied = ok & (peak == best_peak) + tied_loads = new_loads[tied] + best = int(np.argmin(np.einsum("ij,ij->i", tied_loads, tied_loads))) + i, j = (int(x[best]) for x in np.nonzero(tied)) s, e, d, r = int(donors[j]), int(rec[i]), int(dex[j]), int(drank[j]) se[s] = e copies[d] -= 1 @@ -405,9 +573,15 @@ def plan_layer_swaps( experts = np.asarray(slot_expert, dtype=np.int64).reshape(-1, slots_per_rank).copy() weight = np.asarray(slot_weight, dtype=np.float64).reshape(-1, slots_per_rank).copy() ranks = experts.shape[0] - copies = np.bincount(experts.reshape(-1)).max(initial=1) > 1 + counts = np.bincount(experts.reshape(-1)) + copies = counts.max(initial=1) > 1 + holds: Optional[np.ndarray] = None + if copies: + holds = np.zeros((ranks, counts.size), dtype=bool) + holds[np.arange(ranks)[:, None], experts] = True loads = weight.sum(axis=1) mean = float(loads.mean()) + thr = min_gain * mean swaps = 0 while swaps < max_swaps and mean > 0: order = np.argsort(-loads, kind="stable") @@ -416,7 +590,7 @@ def plan_layer_swaps( # A swap relieves the heavier rank by at most half their load gap: closer pairs (less a # rounding margin) cannot pass min_gain. gap = loads[heavy][:, None] - loads[light][None, :] - need = 2.0 * min_gain * mean - 1e-9 * loads[heavy][:, None] + need = 2.0 * thr - 1e-9 * loads[heavy][:, None] pair_hi, pair_lo = np.nonzero((gap > 0) & (gap >= need)) if pair_hi.size == 0: break @@ -424,21 +598,23 @@ def plan_layer_swaps( # shift[p, i, j]: load moving from rank his[p] to rank los[p] by swapping slots i and j; the # first best pair in (heavy, light, i, j) order wins. shift = weight[his][:, :, None] - weight[los][:, None, :] - load_hi = loads[his][:, None, None] - load_lo = loads[los][:, None, None] - drop = 2.0 * shift * ((load_hi - load_lo) - shift) - relief = load_hi - np.maximum(load_hi - shift, load_lo + shift) - ok = relief > min_gain * mean - if copies: + rem = gap[pair_hi, pair_lo][:, None, None] - shift + ok = (shift > thr) & (rem > thr) + if holds is not None: # A copy may not join a rank that already holds its expert. - same = experts[his][:, :, None] == experts[los][:, None, :] - ok &= ~same.any(axis=2)[:, :, None] & ~same.any(axis=1)[:, None, :] - drop = np.where(ok, drop, -np.inf) + ok &= (~holds[los[:, None], experts[his]])[:, :, None] & ( + ~holds[his[:, None], experts[los]] + )[:, None, :] + drop = np.where(ok, shift * rem, -np.inf) p, i, j = np.unravel_index(int(np.argmax(drop)), drop.shape) if not np.isfinite(drop[p, i, j]): break hi, lo, i, j = int(his[p]), int(los[p]), int(i), int(j) - experts[hi, i], experts[lo, j] = experts[lo, j], experts[hi, i] + e_hi, e_lo = int(experts[hi, i]), int(experts[lo, j]) + experts[hi, i], experts[lo, j] = e_lo, e_hi + if holds is not None: + holds[hi, e_hi], holds[hi, e_lo] = False, True + holds[lo, e_lo], holds[lo, e_hi] = False, True weight[hi, i], weight[lo, j] = weight[lo, j], weight[hi, i] loads[hi] = weight[hi].sum() loads[lo] = weight[lo].sum() @@ -470,10 +646,13 @@ def _count_kernel( ROWS: tl.constexpr, ROW_MASK: tl.constexpr, ): + if tl.load(flag_ptr) == 0: + return bound = tl.load(bound_ptr) limit = tl.where(bound >= 0, tl.minimum(bound - row_offset, num_rows), num_rows) - limit = tl.where(tl.load(flag_ptr) != 0, limit, 0) row0 = tl.program_id(0) * ROWS + if row0 >= limit: + return offs_e = tl.arange(0, BLOCK_E) for i in tl.static_range(ROWS): row = row0 + i @@ -482,17 +661,17 @@ def _count_kernel( if ROW_MASK: g = row + row_offset live = (g < mask_len) & (tl.load(mask_ptr + g, mask=g < mask_len, other=0) != 0) - lg = tl.load( - logits_ptr + row * logit_stride + offs_e, - mask=offs_e < NUM_EXPERTS, - other=0.0, - ) - live = live & (tl.max(tl.abs(lg.to(tl.float32)), axis=0) > 0.0) if live: - for k in tl.static_range(TOP_K): - e = tl.load(ids_ptr + row * TOP_K + k) - if (e >= 0) & (e < NUM_EXPERTS): - tl.atomic_add(hist_ptr + e, 1) + lg = tl.load( + logits_ptr + row * logit_stride + offs_e, + mask=offs_e < NUM_EXPERTS, + other=0.0, + ) + if tl.max(tl.abs(lg.to(tl.float32)), axis=0) > 0.0: + for k in tl.static_range(TOP_K): + e = tl.load(ids_ptr + row * TOP_K + k) + if (e >= 0) & (e < NUM_EXPERTS): + tl.atomic_add(hist_ptr + e, 1) except ImportError: # pragma: no cover - CPU-only environments triton = None @@ -507,14 +686,14 @@ def count_routing( is below the live-row bound, its mask byte is set (with a mask) and its logits are not all zero. One launch; inside a CUDA graph it exits after one load once the flag is cleared.""" rows, top_k = expert_ids.shape - if rows == 0: - return num_experts = counters.hist.numel() + if rows == 0 or num_experts == 0: + return ids = expert_ids if ids.dtype != torch.int32 or not ids.is_contiguous(): ids = ids.to(torch.int32).contiguous() mask = counters.mask - rows_per_prog = 16 + rows_per_prog = 1 if rows <= 2048 else 4 _count_kernel[(triton.cdiv(rows, rows_per_prog),)]( ids, router_logits, @@ -574,8 +753,10 @@ def __init__( ep_rank: int, ep_size: int, num_target_layers: Optional[int] = None, + drift_config: Optional[OnlineDriftConfig] = None, ) -> None: self.settings = settings + self.drift_config = drift_config if drift_config is not None else OnlineDriftConfig() self.ep_rank = ep_rank self.ep_size = ep_size self.num_target_layers = num_target_layers @@ -604,7 +785,13 @@ def __init__( self._live_rows: Dict[int, collections.deque] = {0: collections.deque(maxlen=32)} self._rows_at_last_round = 0 self._next_check = settings.start_step + settings.interval_steps - logger.info(f"{_LOG} enabled: {settings}") + self._tracker = _OnlineLoadTracker(self.drift_config) + self._readapt_deadline: Optional[int] = None + self._next_readapt_check: Optional[int] = None + self._frozen_ep_rows: float = 0.0 + self._post_freeze_rows: collections.deque[int] = collections.deque(maxlen=16) + self._readapt_count = 0 + logger.info(f"{_LOG} enabled: {settings}, drift={self.drift_config}") # ------------------------------------------------------------------ registration def register_layer( @@ -638,9 +825,9 @@ def register_layer( f"route other rows than the main pass" ) return None - one_copy = slots_per_rank * self.ep_size == num_experts and sorted( - initial_assignments - ) == list(range(num_experts)) + one_copy = slots_per_rank * self.ep_size == num_experts and is_bijective_placement( + initial_assignments, num_experts + ) replicated = not one_copy and is_replicated_cover( initial_assignments, num_experts, slots_per_rank, self.ep_size ) @@ -771,6 +958,12 @@ def _make_exchange_group(self) -> ProcessGroup: def _counting(self) -> bool: return self._hist is not None and not self.frozen + def _can_readapt(self) -> bool: + return ( + self.drift_config.max_readapts > 0 + and self._readapt_count < self.drift_config.max_readapts + ) + def route_counters(self, index: int, row_offset: int) -> Optional[RouteCounters]: """Layer ``index``'s counters for a routing kernel that counts its own picks, for the whole run once finalized (the flag stops it at the freeze, so it keeps one compiled variant).""" @@ -793,7 +986,7 @@ def counters(self, index: int, row_offset: int) -> Optional[RouteCounters]: @property def active(self) -> bool: """Whether the per-step live-row inputs are still needed.""" - return self._finalized and self._counting() + return self._finalized and (self._counting() or (self.frozen and self._can_readapt())) def set_live_rows(self, requests: ScheduledRequests, draft_len: int) -> None: """Every pass's live-row bound and, with ``min_pos``, row mask for the next forward. Main @@ -803,6 +996,8 @@ def set_live_rows(self, requests: ScheduledRequests, draft_len: int) -> None: rows and the rows of generation requests with fewer than ``min_pos`` generated tokens are masked out. The masks go up through a pinned ring on the current stream.""" if not self._counting(): + if self.frozen and self._can_readapt(): + self._post_freeze_rows.append(real_rows_of(requests, draft_len)) return if self._step % self.settings.count_every_steps: for bound in self._bounds: @@ -849,15 +1044,85 @@ def set_live_rows(self, requests: ScheduledRequests, draft_len: int) -> None: self._mask_slot = (self._mask_slot + 1) % len(self._mask_ring) # ------------------------------------------------------------------ schedule + def _next_action(self, step: int) -> int: + if self._readapt_deadline is not None: + if step >= self._readapt_deadline: + return LAST + if step >= self._next_check: + anchor = self._counting_since if self._counting_since is not None else step + k = (step - anchor) // self.settings.interval_steps + 1 + self._next_check = anchor + k * self.settings.interval_steps + return CHECK + return NONE + action, self._next_check = schedule_action(self.settings, step, self._next_check) + return action + + def _maybe_readapt(self, step: int) -> None: + """Re-open placement rounds when EP-wide live rows shift past the configured bounds.""" + if ( + not self._can_readapt() + or self._next_readapt_check is None + or step < self._next_readapt_check + ): + return + from mpi4py import MPI + + interval = self.drift_config.readapt_check_interval + k = (step - self._next_readapt_check) // interval + 1 + self._next_readapt_check += k * interval + cur_local = float(np.mean(self._post_freeze_rows)) if self._post_freeze_rows else 0.0 + cur_tot = self._comm.reduce(cur_local, op=MPI.SUM, root=0) + trigger = False + ratio = 0.0 + if ( + self.ep_rank == 0 + and self._frozen_ep_rows > 0.0 + and cur_tot is not None + and cur_tot > 0.0 + ): + ratio = float(cur_tot) / self._frozen_ep_rows + trigger = ( + ratio >= self.drift_config.readapt_ratio_high + or ratio <= self.drift_config.readapt_ratio_low + ) + if not self._comm.bcast(trigger, root=0): + return + self._readapt_count += 1 + self.frozen = False + self.migrations_done = 0 + self._hist.zero_() + self._flag.fill_(1) + self._counting_since = step + self._rows_at_last_round = 0 + self._tracker.reset() + for rows in self._live_rows.values(): + rows.clear() + self._post_freeze_rows.clear() + self._next_check = step + self.settings.interval_steps + self._readapt_deadline = step + max( + self.drift_config.readapt_min_window_steps, 3 * self.settings.interval_steps + ) + self._next_readapt_check = None + if self.ep_rank == 0: + logger.info( + f"{_LOG} concurrency shift detected at step {step} " + f"(EP rows {self._frozen_ep_rows:.0f} -> {float(cur_tot):.0f}, ratio={ratio:.2f}x): " + f"re-adapting placement (readapt #{self._readapt_count}, " + f"deadline={self._readapt_deadline})" + ) + def on_step(self, step: int) -> None: self._step = step - if not self._finalized or self.frozen: + if not self._finalized: + return + if self.frozen: + self._maybe_readapt(step) return if self._counting_since is None and step >= self.settings.start_step: self._flag.fill_(1) self._counting_since = step logger.info(f"{_LOG} counters on at step {step}") - action, self._next_check = schedule_action(self.settings, step, self._next_check) + action = self._next_action(step) if action != NONE: # Weights made in inference mode can only be updated in place inside it. with torch.inference_mode(): @@ -868,7 +1133,13 @@ def on_step(self, step: int) -> None: def reset_schedule(self) -> None: """Restart the schedule and the counters at executor step 0 (the executor rebound its resources); the placement and the rounds done stay.""" - if not self._finalized or self.frozen: + if not self._finalized: + return + self._step = -1 + if self.frozen: + if self._can_readapt() and self._next_readapt_check is not None: + self._next_readapt_check = self.drift_config.readapt_cooldown_steps + self._post_freeze_rows.clear() return self._flag.fill_(0) self._hist.zero_() @@ -876,10 +1147,11 @@ def reset_schedule(self) -> None: bound.fill_(-1) self._counting_since = None self._next_check = self.settings.start_step + self.settings.interval_steps + self._readapt_deadline = None self._rows_at_last_round = 0 + self._tracker.reset() for rows in self._live_rows.values(): rows.clear() - self._step = -1 # ------------------------------------------------------------------ one round def _round(self, step: int, last: bool = False) -> None: @@ -891,6 +1163,8 @@ def _round(self, step: int, last: bool = False) -> None: local = self._hist.cpu().numpy().astype(np.int64) glob = np.empty_like(local) self._comm.Allreduce(local, glob, op=MPI.SUM) + if self.ep_rank == 0: + self._tracker.observe(glob) first = self.layers[0] rows = int(glob[0, : first.num_experts].sum()) // max(1, first.top_k) fresh = rows - self._rows_at_last_round @@ -912,14 +1186,19 @@ def _round(self, step: int, last: bool = False) -> None: self._check_movable(step) cost = self._cost_inputs(step, glob) if self.settings.planner == "cost" else None plan, note = None, "" + next_prob: Dict[int, np.ndarray] = {} if self.ep_rank == 0: plan, before, after = [], 0.0, 0.0 for layer in self.layers: - load = glob[layer.index, : layer.num_experts].astype(np.float64) - if not layer.movable or not load.any(): + if not layer.movable: + plan.append(None) + continue + load, cur_prob = self._tracker.layer_load(layer.index, layer.num_experts, glob) + if cur_prob is None: # Without counts every expert ties, and the copies would go to the lowest ids. plan.append(None) continue + next_prob[layer.index] = cur_prob spr = layer.slots_per_rank if layer.replicated: lam, weight = _replica_inputs(load, layer.top_k, cost, layer.row_space) @@ -962,7 +1241,10 @@ def _round(self, step: int, last: bool = False) -> None: plan = None plan = self._comm.bcast(plan, root=0) if plan is None: - self._decay_counters(rows, glob, local) + decayed_glob = self._decay_counters(rows, glob, local) + if self.ep_rank == 0: + self._tracker.on_counters_decayed(decayed_glob, decay=self.settings.decay) + self._tracker.commit_probs(next_prob) logger.info( f"{_LOG} step {step}: the plan gains less than {self.settings.min_round_gain} " f"points; the placement stays, {(time.perf_counter() - t0) * 1e3:.0f} ms{note}" @@ -976,7 +1258,10 @@ def _round(self, step: int, last: bool = False) -> None: if applied is None: return # skipped on every rank: the next boundary or the deadline tries again moved, nbytes = applied - self._decay_counters(rows, glob, local) + decayed_glob = self._decay_counters(rows, glob, local) + if self.ep_rank == 0: + self._tracker.on_counters_decayed(decayed_glob, decay=self.settings.decay) + self._tracker.commit_probs(next_prob) self.migrations_done += 1 logger.info( f"{_LOG} round {self.migrations_done}/{self.settings.max_migrations} at step {step}" @@ -988,10 +1273,15 @@ def _round(self, step: int, last: bool = False) -> None: if self.migrations_done >= self.settings.max_migrations: self._freeze(step) - def _decay_counters(self, rows: int, glob: np.ndarray, local: np.ndarray) -> None: + def _decay_counters( + self, rows: int, glob: np.ndarray, local: np.ndarray + ) -> Optional[np.ndarray]: """Every counter keeps ``decay`` of its value, so later rounds follow recent traffic; the next round's fresh rows count from here. A counter near the int32 limit on any rank halves - them all (the planners use only their ratios). Collective on the EP group.""" + them all (the planners use only their ratios). Collective on the EP group. + + When EMA tracking is active and ``decay < 1``, returns the exact post-decay global counter + matrix on rank 0 (None on other ranks) so per-rank floor rounding never drops counts.""" from mpi4py import MPI first = self.layers[0] @@ -1000,10 +1290,17 @@ def _decay_counters(self, rows: int, glob: np.ndarray, local: np.ndarray) -> Non if peak * decay >= _COUNTER_HALVING_AT: decay = min(decay, 0.5) self._rows_at_last_round = rows - if decay < 1.0: - self._hist.copy_(torch.floor(self._hist.double() * decay).to(torch.int32)) - kept = np.floor(glob[0, : first.num_experts] * decay).sum() - self._rows_at_last_round = int(kept) // max(1, first.top_k) + if decay >= 1.0: + return None + self._hist.copy_(torch.floor(self._hist.double() * decay).to(torch.int32)) + kept = np.floor(glob[0, : first.num_experts] * decay).sum() + self._rows_at_last_round = int(kept) // max(1, first.top_k) + if not self._tracker.uses_ema: + return None + decayed_local = np.floor(local.astype(np.float64) * decay).astype(np.int64) + decayed_glob = np.empty_like(decayed_local) if self.ep_rank == 0 else None + self._comm.Reduce(decayed_local, decayed_glob, op=MPI.SUM, root=0) + return decayed_glob def _max_swaps(self, layer: _Layer) -> int: return int(self.settings.max_moved_fraction * len(layer.assign)) // 2 @@ -1073,8 +1370,20 @@ def apply_plan( bytes received), or None when a rank fails to prepare and the plan is skipped everywhere.""" from mpi4py import MPI + if len(plan) != len(self.layers): + raise ValueError( + f"{_LOG} plan length {len(plan)} does not match layer count {len(self.layers)}" + ) if any(new is not None and not layer.movable for layer, new in zip(self.layers, plan)): raise ValueError(f"{_LOG} the plan moves a layer that cannot move") + for layer, new in zip(self.layers, plan): + if new is not None and not is_valid_placement( + new, layer.num_experts, layer.slots_per_rank, self.ep_size + ): + raise ValueError( + f"{_LOG} layer {layer.index}: invalid placement for {layer.num_experts} " + f"experts across {self.ep_size} x {layer.slots_per_rank} slots" + ) ok = 1 try: self._prepare_local(plan) @@ -1106,6 +1415,18 @@ def _freeze(self, step: int) -> None: bound.fill_(-1) torch.cuda.synchronize() self.frozen = True + self._readapt_deadline = None + if self._can_readapt() and self._comm is not None: + from mpi4py import MPI + + local_r = float(np.mean(self._live_rows[0])) if self._live_rows[0] else 0.0 + tot_r = self._comm.reduce(local_r, op=MPI.SUM, root=0) + if self.ep_rank == 0: + self._frozen_ep_rows = float(tot_r) + self._next_readapt_check = step + self.drift_config.readapt_cooldown_steps + self._post_freeze_rows.clear() + else: + self._next_readapt_check = None logger.info(f"{_LOG} frozen at step {step} after {self.migrations_done} round(s)") # ------------------------------------------------------------------ migration diff --git a/tests/unittest/_torch/moe/test_moe_warmup_placement.py b/tests/unittest/_torch/moe/test_moe_warmup_placement.py index c7904d6204ef..e5895d2071a6 100644 --- a/tests/unittest/_torch/moe/test_moe_warmup_placement.py +++ b/tests/unittest/_torch/moe/test_moe_warmup_placement.py @@ -20,6 +20,7 @@ from typing import Optional import cloudpickle +import numpy as np import pytest import torch from _torch.moe.quantize_utils import NVFP4QuantizeUtil @@ -214,6 +215,9 @@ def _check_live_round(controller, layers, balancer, inputs, reference, graphs, b if len(new) > _NUM_EXPERTS: cover = mwp.is_replicated_cover(new, _NUM_EXPERTS, spr, world) _assert_on_all_ranks(None if cover else f"layer {i}: two copies on one rank") + else: + bijective = mwp.is_bijective_placement(new, _NUM_EXPERTS) + _assert_on_all_ranks(None if bijective else f"layer {i}: placement is not a bijection") moved = sum(a != b for a, b in zip(old, new)) budget = 2 * (int(0.1 * len(new)) // 2) _assert_on_all_ranks( @@ -392,3 +396,151 @@ def test_megamoe_placement(gens: int, draft_len: int) -> None: ) as executor: results = [executor.submit(run) for _ in range(_WORLD_SIZE)] assert all(result.result() is None for result in results) + + +@pytest.mark.cpu_only +def test_online_drift_rebalance_bijection_and_determinism() -> None: + """Online EMA + drift extrapolation rebalances faster under hot-expert drift, preserves + bijection/replicated-cover invariants, stays deterministic across ranks, tracks post-decay + increments accurately, and rejects invalid placements.""" + ep_size, spr, num_experts = 8, 8, 64 + spr_rep = spr + 1 + max_swaps = 4 + + def make_phase_counts(hot_weights: dict[int, int], cold: int = 1) -> np.ndarray: + local = np.full((ep_size, 1, num_experts), cold, dtype=np.int64) + for rank_idx, val in hot_weights.items(): + local[:, 0, rank_idx * spr : (rank_idx + 1) * spr] = val + return local + + # Phase 0 concentrates load on rank 0; phase 1 drifts toward rank 3 while rank 0 cools; + # phase 2 completes the shift to rank 3 (evaluated out-of-sample on the placement after phase 1). + phases = [ + make_phase_counts({0: 120}), + make_phase_counts({0: 25, 3: 65}), + ] + next_target = make_phase_counts({3: 120}).sum(axis=0)[0].astype(np.float64) + + def run_sequence(cfg: mwp.OnlineDriftConfig) -> tuple[list[int], list[int], list[np.ndarray]]: + tracker = mwp._OnlineLoadTracker(cfg) + assign = list(range(num_experts)) + rep_assign = list(range(num_experts)) + list(range(ep_size)) + hist_local = np.zeros((ep_size, 1, num_experts), dtype=np.int64) + loads_seen: list[np.ndarray] = [] + for delta_local in phases: + hist_local += delta_local + glob = hist_local.sum(axis=0) + tracker.observe(glob) + load, cur_prob = tracker.layer_load(0, num_experts, glob) + assert cur_prob is not None + loads_seen.append(load.copy()) + + assign, _ = mwp.plan_layer_swaps(load[assign], assign, spr, max_swaps, min_gain=0.0) + assert mwp.is_bijective_placement(assign, num_experts) + + lam, weight = mwp._replica_inputs(load, top_k=6, cost=None, row_space=0) + chosen, moves = mwp.plan_layer_copy_moves( + lam, rep_assign, spr_rep, weight, 2 * max_swaps + ) + copies = np.bincount(chosen, minlength=num_experts) + slot_w = weight(lam[chosen] / copies[chosen]) + rep_assign, _ = mwp.plan_layer_swaps( + slot_w, chosen, spr_rep, (2 * max_swaps - moves) // 2, min_gain=0.0 + ) + assert mwp.is_replicated_cover(rep_assign, num_experts, spr_rep, ep_size) + tracker.commit_probs({0: cur_prob}) + return assign, rep_assign, loads_seen + + drift_cfg = mwp.OnlineDriftConfig(step_ema=0.5, drift_alpha=0.4) + static_cfg = mwp.OnlineDriftConfig(step_ema=0.0, drift_alpha=0.0) + + drift_a, rep_a, loads_a = run_sequence(drift_cfg) + drift_b, rep_b, loads_b = run_sequence(drift_cfg) + static_a, _, _ = run_sequence(static_cfg) + + # Strict cross-rank determinism for both effective loads and discrete placements. + assert drift_a == drift_b + assert rep_a == rep_b + assert all(np.array_equal(a, b) for a, b in zip(loads_a, loads_b)) + + # On the upcoming drifted traffic, drift-aware placement yields lower tail imbalance. + assert mwp._excess(next_target, drift_a, spr) < mwp._excess(next_target, static_a, spr) + + # Exact post-decay snapshot sync prevents losing routes when per-rank floor rounds to zero. + t = mwp._OnlineLoadTracker(drift_cfg) + local_r = np.ones((ep_size, 1, num_experts), dtype=np.int64) + t.observe(local_r.sum(axis=0)) + decayed_local = np.floor(local_r.astype(np.float64) * 0.5).astype(np.int64) + t.on_counters_decayed(decayed_local.sum(axis=0), decay=0.5) + next_local = decayed_local + np.ones((ep_size, 1, num_experts), dtype=np.int64) + t.observe(next_local.sum(axis=0)) + eff, _ = t.layer_load(0, num_experts, next_local.sum(axis=0)) + np.testing.assert_allclose(eff, np.full(num_experts, 0.5 * (0.5 * ep_size) + ep_size)) + + # Fail-closed validation rejects duplicate/missing experts and invalid drift bounds. + bad_bijection = list(range(num_experts)) + bad_bijection[0] = bad_bijection[1] + assert not mwp.is_valid_placement(bad_bijection, num_experts, spr, ep_size) + bad_rep = list(range(num_experts)) + [0] * ep_size + assert not mwp.is_valid_placement(bad_rep, num_experts, spr_rep, ep_size) + with pytest.raises(ValueError, match="step_ema"): + mwp.OnlineDriftConfig(step_ema=1.0) + with pytest.raises(ValueError, match="drift_alpha"): + mwp.OnlineDriftConfig(drift_alpha=-0.1) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA") +def test_count_routing_early_exit_mask_and_cuda_graph() -> None: + """The Triton route-counting kernel honors flag early-exit, live-row bounds, row_offset, + row masks, and zero-logit filtering under CUDA graph replay.""" + rows, top_k, num_experts = 96, 6, 384 + row_offset = 16 + device = torch.device("cuda", 0) + gen = torch.Generator(device="cpu").manual_seed(2026) + ids = torch.randint(0, num_experts, (rows, top_k), generator=gen, dtype=torch.int32).to(device) + logits = torch.randn((rows, num_experts), generator=gen, dtype=torch.bfloat16).to(device) + logits[10:20].zero_() + + hist = torch.zeros(num_experts, dtype=torch.int32, device=device) + flag = torch.ones(1, dtype=torch.int32, device=device) + bound = torch.tensor([row_offset + 64], dtype=torch.int32, device=device) + mask = torch.zeros(row_offset + rows, dtype=torch.int8, device=device) + mask[row_offset : row_offset + rows : 2] = 1 + counters = mwp.RouteCounters( + hist=hist, flag=flag, bound=bound, mask=mask, row_offset=row_offset + ) + + # Warmup JIT before graph capture. + mwp.count_routing(ids, counters, logits) + torch.cuda.synchronize() + hist.zero_() + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + mwp.count_routing(ids, counters, logits) + + # Replay 1: active counting with partial bound, mask, row_offset, and zero-logit rows. + graph.replay() + torch.cuda.synchronize() + valid_rows = ( + (torch.arange(rows, device=device) < 64) + & (mask[row_offset : row_offset + rows] != 0) + & (logits.abs().amax(dim=1) > 0) + ) + expected = torch.bincount(ids[valid_rows].reshape(-1).long(), minlength=num_experts).to( + torch.int32 + ) + assert torch.equal(hist, expected) + + # Replay 2: flag cleared -> early exit leaves counters untouched. + flag.zero_() + graph.replay() + torch.cuda.synchronize() + assert torch.equal(hist, expected) + + # Replay 3: flag restored but bound <= row_offset -> zero rows counted. + flag.fill_(1) + bound.fill_(row_offset) + graph.replay() + torch.cuda.synchronize() + assert torch.equal(hist, expected) From deda40996c16d4490eec3f9e1caf279b0266eb56 Mon Sep 17 00:00:00 2001 From: Jin Li <59594262+liji-nv@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:17:36 +0800 Subject: [PATCH 2/6] [None][fix] MoE: address review feedback on online placement decay baseline and readaptation Address valid CodeRabbit and Pyrefly findings on PR #23186: - Compute _rows_at_last_round in _decay_counters from the MPI sum of locally floored first-layer counts (both with and without EMA), preventing small post-decay counts from over-estimating the fresh-row baseline and deferring real incoming rows. - Gate post-freeze _post_freeze_rows sampling by count_every_steps so the post-freeze average samples the same step cadence as the frozen baseline. - Rebase an active _readapt_deadline relative to start_step on reset_schedule() instead of clearing it, preserving bounded readaptation windows across executor restarts. - Add Optional type-narrowing guards in _maybe_readapt, on_step, reset_schedule, and _decay_counters so Pyrefly reports zero diagnostics. - Extend test_moe_warmup_placement.py to cover the 4-row Triton tile-split boundary (2049 rows, live_bound=2046) and real 4-rank MPI lifecycle checks (post-decay fresh-row & EMA sync, alternating-load cadence alignment, collective readapt reopen/rebase/refreeze, and max_readapts cap). Signed-off-by: Jin Li <59594262+liji-nv@users.noreply.github.com> --- .../moe/fused_moe/moe_warmup_placement.py | 34 +++- .../_torch/moe/test_moe_warmup_placement.py | 177 +++++++++++++++++- 2 files changed, 194 insertions(+), 17 deletions(-) diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py index bccb7f0a7cad..e8659cd457a2 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py @@ -996,7 +996,11 @@ def set_live_rows(self, requests: ScheduledRequests, draft_len: int) -> None: rows and the rows of generation requests with fewer than ``min_pos`` generated tokens are masked out. The masks go up through a pinned ring on the current stream.""" if not self._counting(): - if self.frozen and self._can_readapt(): + if ( + self.frozen + and self._can_readapt() + and self._step % self.settings.count_every_steps == 0 + ): self._post_freeze_rows.append(real_rows_of(requests, draft_len)) return if self._step % self.settings.count_every_steps: @@ -1063,6 +1067,9 @@ def _maybe_readapt(self, step: int) -> None: not self._can_readapt() or self._next_readapt_check is None or step < self._next_readapt_check + or self._comm is None + or self._hist is None + or self._flag is None ): return from mpi4py import MPI @@ -1119,6 +1126,7 @@ def on_step(self, step: int) -> None: self._maybe_readapt(step) return if self._counting_since is None and step >= self.settings.start_step: + assert self._flag is not None self._flag.fill_(1) self._counting_since = step logger.info(f"{_LOG} counters on at step {step}") @@ -1135,19 +1143,23 @@ def reset_schedule(self) -> None: resources); the placement and the rounds done stay.""" if not self._finalized: return + prev_step = self._step self._step = -1 if self.frozen: if self._can_readapt() and self._next_readapt_check is not None: self._next_readapt_check = self.drift_config.readapt_cooldown_steps self._post_freeze_rows.clear() return + assert self._flag is not None and self._hist is not None self._flag.fill_(0) self._hist.zero_() for bound in self._bounds: bound.fill_(-1) self._counting_since = None self._next_check = self.settings.start_step + self.settings.interval_steps - self._readapt_deadline = None + if self._readapt_deadline is not None: + remaining = max(1, self._readapt_deadline - max(0, prev_step)) + self._readapt_deadline = self.settings.start_step + remaining self._rows_at_last_round = 0 self._tracker.reset() for rows in self._live_rows.values(): @@ -1241,8 +1253,10 @@ def _round(self, step: int, last: bool = False) -> None: plan = None plan = self._comm.bcast(plan, root=0) if plan is None: - decayed_glob = self._decay_counters(rows, glob, local) + decayed_glob = self._decay_counters(rows, local) if self.ep_rank == 0: + # Use configured settings.decay for float64 EMA forgetting (decoupled from int32 + # overflow halving); decayed_glob already matches the exact post-decay counter base. self._tracker.on_counters_decayed(decayed_glob, decay=self.settings.decay) self._tracker.commit_probs(next_prob) logger.info( @@ -1258,7 +1272,7 @@ def _round(self, step: int, last: bool = False) -> None: if applied is None: return # skipped on every rank: the next boundary or the deadline tries again moved, nbytes = applied - decayed_glob = self._decay_counters(rows, glob, local) + decayed_glob = self._decay_counters(rows, local) if self.ep_rank == 0: self._tracker.on_counters_decayed(decayed_glob, decay=self.settings.decay) self._tracker.commit_probs(next_prob) @@ -1273,9 +1287,7 @@ def _round(self, step: int, last: bool = False) -> None: if self.migrations_done >= self.settings.max_migrations: self._freeze(step) - def _decay_counters( - self, rows: int, glob: np.ndarray, local: np.ndarray - ) -> Optional[np.ndarray]: + def _decay_counters(self, rows: int, local: np.ndarray) -> Optional[np.ndarray]: """Every counter keeps ``decay`` of its value, so later rounds follow recent traffic; the next round's fresh rows count from here. A counter near the int32 limit on any rank halves them all (the planners use only their ratios). Collective on the EP group. @@ -1284,6 +1296,7 @@ def _decay_counters( matrix on rank 0 (None on other ranks) so per-rank floor rounding never drops counts.""" from mpi4py import MPI + assert self._comm is not None and self._hist is not None first = self.layers[0] decay = self.settings.decay peak = self._comm.allreduce(int(local.max(initial=0)), op=MPI.MAX) @@ -1293,11 +1306,12 @@ def _decay_counters( if decay >= 1.0: return None self._hist.copy_(torch.floor(self._hist.double() * decay).to(torch.int32)) - kept = np.floor(glob[0, : first.num_experts] * decay).sum() - self._rows_at_last_round = int(kept) // max(1, first.top_k) + decayed_local = np.floor(local.astype(np.float64) * decay).astype(np.int64) + kept_local = int(decayed_local[0, : first.num_experts].sum()) + kept = int(self._comm.allreduce(kept_local, op=MPI.SUM)) + self._rows_at_last_round = kept // max(1, first.top_k) if not self._tracker.uses_ema: return None - decayed_local = np.floor(local.astype(np.float64) * decay).astype(np.int64) decayed_glob = np.empty_like(decayed_local) if self.ep_rank == 0 else None self._comm.Reduce(decayed_local, decayed_glob, op=MPI.SUM, root=0) return decayed_glob diff --git a/tests/unittest/_torch/moe/test_moe_warmup_placement.py b/tests/unittest/_torch/moe/test_moe_warmup_placement.py index e5895d2071a6..d693a02a7c79 100644 --- a/tests/unittest/_torch/moe/test_moe_warmup_placement.py +++ b/tests/unittest/_torch/moe/test_moe_warmup_placement.py @@ -16,6 +16,7 @@ import functools import pickle import sys +import weakref from types import SimpleNamespace from typing import Optional @@ -375,6 +376,162 @@ def _run_placement(gens: int, draft_len: int) -> None: _assert_on_all_ranks( f"separate count launches: {len(separate_counts)}" if separate_counts else None ) + if gens == 25: + _check_controller_lifecycle_contracts(layers[0]) + + +def _check_controller_lifecycle_contracts(moe) -> None: + """Exercise production MPI post-decay reduction, fresh-row baseline, alternating-load + cadence alignment, collective readaptation reopen/refreeze, and deadline rebase on restart.""" + rank, world = mpi_rank(), mpi_world_size() + num_experts, spr = 8, 8 // world + device = torch.device("cuda", rank) + + def make_ctrl( + settings: MoeWarmupPlacementConfig, drift_cfg: mwp.OnlineDriftConfig + ) -> mwp.WarmupPlacementController: + ctrl = mwp.WarmupPlacementController( + settings, ep_rank=rank, ep_size=world, drift_config=drift_cfg + ) + ctrl._finalized = True + ctrl._comm = MPI.COMM_WORLD + with torch.inference_mode(False): + ctrl._hist = torch.zeros((1, num_experts), dtype=torch.int32, device=device) + ctrl._flag = torch.zeros(1, dtype=torch.int32, device=device) + ctrl._bounds = [torch.full((1,), -1, dtype=torch.int32, device=device)] + ctrl.layers = [ + mwp._Layer( + index=0, + num_experts=num_experts, + top_k=1, + slots_per_rank=spr, + moe=weakref.ref(moe), + balancer=moe.layer_load_balancer, + assign=list(range(num_experts)), + movable=False, + ) + ] + return ctrl + + # 1. Production _decay_counters keeps exact retained fresh-row baseline and EMA increment sync + # even when every rank's local counter floors to 0 (both EMA enabled and disabled). + for step_ema in (0.0, 0.5): + s_dec = MoeWarmupPlacementConfig( + start_step=0, + interval_steps=1, + max_migrations=4, + min_rows=1, + decay=0.5, + min_round_gain=1e9, + ) + ctrl = make_ctrl(s_dec, mwp.OnlineDriftConfig(step_ema=step_ema, drift_alpha=0.0)) + ctrl.on_step(0) + ctrl._hist[0, 0] = 1 # 1 pick per rank -> 4 global; each rank floors to 0 at decay=0.5 + ctrl.on_step(1) # skipped by min_round_gain=1e9, runs _decay_counters + _assert_on_all_ranks( + None + if ctrl._rows_at_last_round == 0 + else f"ema={step_ema}: rows_at_last_round={ctrl._rows_at_last_round} != 0" + ) + # One fresh row on rank 0 must register as fresh=1 and deliver the full +1 delta to EMA. + if rank == 0: + ctrl._hist[0, 0] = 1 + ctrl.settings = s_dec.model_copy(update={"min_round_gain": 0.0}) + ctrl.on_step(2) + _assert_on_all_ranks( + None + if ctrl.migrations_done == 1 + else f"ema={step_ema}: 1 fresh row was deferred after floor decay" + ) + if step_ema > 0.0 and rank == 0: + # Round 1 observed 4 -> decayed by 0.5 to 2; round 2 observes +1 -> 0.5 * 2 + 1 = 2.0, + # then decayed by 0.5 to 1.0 after round 2 completes. + expected_ema = 0.5 * (0.5 * (0.5 * world) + 1.0) + assert ctrl._tracker._ema is not None + got_ema = float(ctrl._tracker._ema[0, 0]) + ok = abs(got_ema - expected_ema) < 1e-9 + _assert_on_all_ranks(None if ok else f"ema={got_ema} != {expected_ema}") + else: + _assert_on_all_ranks(None) + + # 2. Alternating workload under count_every_steps=2 must not trigger false readaptation; + # a true load shift must reopen every rank, reset_schedule must preserve a bounded + # rebased deadline, and the controller must refreeze at deadline without a second reopen. + def reqs_with_gens(n: int) -> SimpleNamespace: + live = [ + SimpleNamespace(is_dummy=False, max_beam_num_tokens=1100, orig_prompt_len=100) + for _ in range(n) + ] + return SimpleNamespace(context_requests=[], generation_requests=live) + + s_ra = MoeWarmupPlacementConfig( + start_step=0, + interval_steps=2, + max_migrations=1, + min_rows=1, + count_every_steps=2, + deadline_step=4, + ) + d_ra = mwp.OnlineDriftConfig( + step_ema=0.5, + drift_alpha=0.4, + max_readapts=1, + readapt_cooldown_steps=4, + readapt_check_interval=2, + readapt_min_window_steps=6, + ) + ra = make_ctrl(s_ra, d_ra) + for step in range(5): + ra.on_step(step) + if step < 4: + ra.set_live_rows(reqs_with_gens(10 if step % 2 == 0 else 100), draft_len=0) + _assert_on_all_ranks(None if ra.frozen and ra.active else "expected frozen with readapt active") + + # Unchanged alternating workload past cooldown + checks must stay frozen. + for step in range(5, 13): + ra.on_step(step) + ra.set_live_rows(reqs_with_gens(10 if step % 2 == 0 else 100), draft_len=0) + _assert_on_all_ranks( + None if ra.frozen and ra._readapt_count == 0 else "spurious readapt on alternating load" + ) + + # Real 4x load shift on counted steps reopens all ranks together. + for step in range(13, 19): + ra.on_step(step) + if ra.frozen: + ra.set_live_rows(reqs_with_gens(40 if step % 2 == 0 else 100), draft_len=0) + else: + break + _assert_on_all_ranks( + None + if (not ra.frozen and ra._readapt_count == 1 and ra._readapt_deadline is not None) + else "failed to reopen all ranks on real load shift" + ) + + # Executor restart during open readapt window preserves a bounded rebased deadline. + ra.reset_schedule() + _assert_on_all_ranks( + None + if (not ra.frozen and ra._readapt_deadline is not None) + else "reset_schedule dropped active readapt deadline" + ) + deadline = ra._readapt_deadline + assert deadline is not None + for step in range(deadline + 1): + ra.on_step(step) + _assert_on_all_ranks( + None + if (ra.frozen and not ra.active) + else "controller did not refreeze at rebased deadline or stayed active past max_readapts" + ) + + # Further shifts after reaching max_readapts=1 must never reopen again. + for step in range(deadline + 1, deadline + 12): + ra.on_step(step) + ra.set_live_rows(reqs_with_gens(80), draft_len=0) + _assert_on_all_ranks( + None if (ra.frozen and ra._readapt_count == 1) else "reopened past max_readapts" + ) @pytest.mark.threadleak(enabled=False) @@ -490,20 +647,26 @@ def run_sequence(cfg: mwp.OnlineDriftConfig) -> tuple[list[int], list[int], list @pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA") -def test_count_routing_early_exit_mask_and_cuda_graph() -> None: - """The Triton route-counting kernel honors flag early-exit, live-row bounds, row_offset, - row masks, and zero-logit filtering under CUDA graph replay.""" - rows, top_k, num_experts = 96, 6, 384 +@pytest.mark.parametrize( + ("rows", "live_bound"), + [(96, 64), (2049, 2046)], + ids=["rows1", "rows4_tile_split"], +) +def test_count_routing_early_exit_mask_and_cuda_graph(rows: int, live_bound: int) -> None: + """The Triton route-counting kernel honors flag early-exit, live-row bounds (including + 4-row tile splits above 2048 rows), row_offset, row masks, and zero-logit filtering under + CUDA graph replay.""" + top_k, num_experts = 6, 384 row_offset = 16 device = torch.device("cuda", 0) - gen = torch.Generator(device="cpu").manual_seed(2026) + gen = torch.Generator(device="cpu").manual_seed(2026 + rows) ids = torch.randint(0, num_experts, (rows, top_k), generator=gen, dtype=torch.int32).to(device) logits = torch.randn((rows, num_experts), generator=gen, dtype=torch.bfloat16).to(device) logits[10:20].zero_() hist = torch.zeros(num_experts, dtype=torch.int32, device=device) flag = torch.ones(1, dtype=torch.int32, device=device) - bound = torch.tensor([row_offset + 64], dtype=torch.int32, device=device) + bound = torch.tensor([row_offset + live_bound], dtype=torch.int32, device=device) mask = torch.zeros(row_offset + rows, dtype=torch.int8, device=device) mask[row_offset : row_offset + rows : 2] = 1 counters = mwp.RouteCounters( @@ -523,7 +686,7 @@ def test_count_routing_early_exit_mask_and_cuda_graph() -> None: graph.replay() torch.cuda.synchronize() valid_rows = ( - (torch.arange(rows, device=device) < 64) + (torch.arange(rows, device=device) < live_bound) & (mask[row_offset : row_offset + rows] != 0) & (logits.abs().amax(dim=1) > 0) ) From f1476c87c92abaddfbdf17bd73ee99196c98df89 Mon Sep 17 00:00:00 2001 From: Jin Li <59594262+liji-nv@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:06:10 +0800 Subject: [PATCH 3/6] [None][fix] MoE: make reset_schedule idempotent for readapt deadline and expand regression checks Address latest CodeRabbit review findings on PR #23186: - Make reset_schedule() idempotent for an active _readapt_deadline when called repeatedly before the next step (prev_step < 0) or before start_step, avoiding repeatedly adding start_step to the remaining readaptation window. - Replace the rank-0-only EMA None assert in _check_controller_lifecycle_contracts with a collective _assert_on_all_ranks check so an EMA failure cannot hang peer ranks in mpi_allgather. - Add direct regression coverage for low-ratio readaptation reopen, frozen-state reset_schedule(), repeated reset_schedule() idempotency with start_step > 0, readapt_ratio_low bounds, and apply_plan() fail-closed ValueError guards before any collective. Signed-off-by: Jin Li <59594262+liji-nv@users.noreply.github.com> --- .../moe/fused_moe/moe_warmup_placement.py | 4 +- .../_torch/moe/test_moe_warmup_placement.py | 107 +++++++++++++++--- 2 files changed, 92 insertions(+), 19 deletions(-) diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py index e8659cd457a2..179cdc6196a0 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py @@ -1157,8 +1157,8 @@ def reset_schedule(self) -> None: bound.fill_(-1) self._counting_since = None self._next_check = self.settings.start_step + self.settings.interval_steps - if self._readapt_deadline is not None: - remaining = max(1, self._readapt_deadline - max(0, prev_step)) + if self._readapt_deadline is not None and prev_step >= 0: + remaining = max(1, self._readapt_deadline - max(self.settings.start_step, prev_step)) self._readapt_deadline = self.settings.start_step + remaining self._rows_at_last_round = 0 self._tracker.reset() diff --git a/tests/unittest/_torch/moe/test_moe_warmup_placement.py b/tests/unittest/_torch/moe/test_moe_warmup_placement.py index d693a02a7c79..fa9fad173117 100644 --- a/tests/unittest/_torch/moe/test_moe_warmup_placement.py +++ b/tests/unittest/_torch/moe/test_moe_warmup_placement.py @@ -443,16 +443,17 @@ def make_ctrl( if ctrl.migrations_done == 1 else f"ema={step_ema}: 1 fresh row was deferred after floor decay" ) + ema_problem = None if step_ema > 0.0 and rank == 0: # Round 1 observed 4 -> decayed by 0.5 to 2; round 2 observes +1 -> 0.5 * 2 + 1 = 2.0, # then decayed by 0.5 to 1.0 after round 2 completes. expected_ema = 0.5 * (0.5 * (0.5 * world) + 1.0) - assert ctrl._tracker._ema is not None - got_ema = float(ctrl._tracker._ema[0, 0]) - ok = abs(got_ema - expected_ema) < 1e-9 - _assert_on_all_ranks(None if ok else f"ema={got_ema} != {expected_ema}") - else: - _assert_on_all_ranks(None) + ema = ctrl._tracker._ema + if ema is None: + ema_problem = "tracker has no EMA after two rounds" + elif abs(float(ema[0, 0]) - expected_ema) >= 1e-9: + ema_problem = f"ema={float(ema[0, 0])} != {expected_ema}" + _assert_on_all_ranks(ema_problem) # 2. Alternating workload under count_every_steps=2 must not trigger false readaptation; # a true load shift must reopen every rank, reset_schedule must preserve a bounded @@ -465,12 +466,12 @@ def reqs_with_gens(n: int) -> SimpleNamespace: return SimpleNamespace(context_requests=[], generation_requests=live) s_ra = MoeWarmupPlacementConfig( - start_step=0, + start_step=2, interval_steps=2, max_migrations=1, min_rows=1, count_every_steps=2, - deadline_step=4, + deadline_step=6, ) d_ra = mwp.OnlineDriftConfig( step_ema=0.5, @@ -481,14 +482,14 @@ def reqs_with_gens(n: int) -> SimpleNamespace: readapt_min_window_steps=6, ) ra = make_ctrl(s_ra, d_ra) - for step in range(5): + for step in range(7): ra.on_step(step) - if step < 4: + if step < 6: ra.set_live_rows(reqs_with_gens(10 if step % 2 == 0 else 100), draft_len=0) _assert_on_all_ranks(None if ra.frozen and ra.active else "expected frozen with readapt active") # Unchanged alternating workload past cooldown + checks must stay frozen. - for step in range(5, 13): + for step in range(7, 15): ra.on_step(step) ra.set_live_rows(reqs_with_gens(10 if step % 2 == 0 else 100), draft_len=0) _assert_on_all_ranks( @@ -496,7 +497,7 @@ def reqs_with_gens(n: int) -> SimpleNamespace: ) # Real 4x load shift on counted steps reopens all ranks together. - for step in range(13, 19): + for step in range(15, 21): ra.on_step(step) if ra.frozen: ra.set_live_rows(reqs_with_gens(40 if step % 2 == 0 else 100), draft_len=0) @@ -508,14 +509,16 @@ def reqs_with_gens(n: int) -> SimpleNamespace: else "failed to reopen all ranks on real load shift" ) - # Executor restart during open readapt window preserves a bounded rebased deadline. + # Executor restart during open readapt window preserves a bounded rebased deadline, + # and a repeated reset before the next step is idempotent even with start_step > 0. + ra.reset_schedule() + deadline = ra._readapt_deadline ra.reset_schedule() _assert_on_all_ranks( None - if (not ra.frozen and ra._readapt_deadline is not None) - else "reset_schedule dropped active readapt deadline" + if (not ra.frozen and deadline is not None and ra._readapt_deadline == deadline) + else "reset_schedule dropped or extended active readapt deadline" ) - deadline = ra._readapt_deadline assert deadline is not None for step in range(deadline + 1): ra.on_step(step) @@ -533,6 +536,36 @@ def reqs_with_gens(n: int) -> SimpleNamespace: None if (ra.frozen and ra._readapt_count == 1) else "reopened past max_readapts" ) + # 3. Frozen reset_schedule resets cooldown/buffer, and a low-ratio load drop reopens all ranks. + ra_low = make_ctrl(s_ra, d_ra) + for step in range(7): + ra_low.on_step(step) + if step < 6: + ra_low.set_live_rows(reqs_with_gens(100), draft_len=0) + ra_low.on_step(8) + ra_low.set_live_rows(reqs_with_gens(100), draft_len=0) + ra_low.reset_schedule() + _assert_on_all_ranks( + None + if ( + ra_low.frozen + and ra_low._next_readapt_check == d_ra.readapt_cooldown_steps + and not ra_low._post_freeze_rows + ) + else "frozen reset_schedule failed to reset readapt cooldown or buffer" + ) + for step in range(0, 7): + ra_low.on_step(step) + if ra_low.frozen: + ra_low.set_live_rows(reqs_with_gens(40), draft_len=0) + else: + break + _assert_on_all_ranks( + None + if (not ra_low.frozen and ra_low._readapt_count == 1) + else "low-ratio load drop failed to reopen all ranks" + ) + @pytest.mark.threadleak(enabled=False) @pytest.mark.skipif( @@ -634,16 +667,56 @@ def run_sequence(cfg: mwp.OnlineDriftConfig) -> tuple[list[int], list[int], list eff, _ = t.layer_load(0, num_experts, next_local.sum(axis=0)) np.testing.assert_allclose(eff, np.full(num_experts, 0.5 * (0.5 * ep_size) + ep_size)) - # Fail-closed validation rejects duplicate/missing experts and invalid drift bounds. + # Fail-closed validation rejects duplicate/missing experts, bad apply_plan inputs before any + # collective, and invalid drift bounds. bad_bijection = list(range(num_experts)) bad_bijection[0] = bad_bijection[1] assert not mwp.is_valid_placement(bad_bijection, num_experts, spr, ep_size) bad_rep = list(range(num_experts)) + [0] * ep_size assert not mwp.is_valid_placement(bad_rep, num_experts, spr_rep, ep_size) + + guard_ctrl = mwp.WarmupPlacementController( + MoeWarmupPlacementConfig(start_step=0, interval_steps=1), ep_rank=0, ep_size=ep_size + ) + dummy_ref = weakref.ref(guard_ctrl) + guard_ctrl.layers = [ + mwp._Layer( + index=0, + num_experts=num_experts, + top_k=6, + slots_per_rank=spr, + moe=dummy_ref, + balancer=None, + assign=list(range(num_experts)), + movable=True, + ), + mwp._Layer( + index=1, + num_experts=num_experts, + top_k=6, + slots_per_rank=spr_rep, + moe=dummy_ref, + balancer=None, + assign=list(range(num_experts)) + list(range(ep_size)), + replicated=True, + movable=True, + ), + ] + with pytest.raises(ValueError, match="plan length"): + guard_ctrl.apply_plan([None], step=0) + with pytest.raises(ValueError, match="invalid placement"): + guard_ctrl.apply_plan([bad_bijection, None], step=0) + with pytest.raises(ValueError, match="invalid placement"): + guard_ctrl.apply_plan([None, bad_rep], step=0) + with pytest.raises(ValueError, match="step_ema"): mwp.OnlineDriftConfig(step_ema=1.0) with pytest.raises(ValueError, match="drift_alpha"): mwp.OnlineDriftConfig(drift_alpha=-0.1) + with pytest.raises(ValueError, match="readapt_ratio_low"): + mwp.OnlineDriftConfig(readapt_ratio_low=1.0) + with pytest.raises(ValueError, match="readapt_ratio_low"): + mwp.OnlineDriftConfig(readapt_ratio_low=0.0) @pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA") From 63807be37bbcf74be523ca793cb0bb7061a4b2f6 Mon Sep 17 00:00:00 2001 From: Jin Li <59594262+liji-nv@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:28:55 +0800 Subject: [PATCH 4/6] [None][fix] MoE: rebase readapt deadline from first unrun step and tighten boundary assertions Address the 4 Minor CodeRabbit findings on PR #23186: - Count remaining readaptation steps in reset_schedule() from first_unrun = max(settings.start_step, prev_step + 1) so resets after a completed forward do not grant an extra step. - Use math.isclose(..., rel_tol=0.0, abs_tol=1e-9) in the distributed EMA check so NaN fails the collective assertion. - Derive expected_rebased_deadline independently in _check_controller_lifecycle_contracts and assert the controller stays open at expected_rebased_deadline - 1 and freezes at expected_rebased_deadline. - Unmask both live_bound - 1 and live_bound in test_count_routing_early_exit_mask_and_cuda_graph so the bound alone distinguishes the last live row from the first out-of-bound row in the split 4-row tile. Signed-off-by: Jin Li <59594262+liji-nv@users.noreply.github.com> --- .../moe/fused_moe/moe_warmup_placement.py | 3 +- .../_torch/moe/test_moe_warmup_placement.py | 47 +++++++++++++++---- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py index 179cdc6196a0..6f183751e1c2 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py @@ -1158,7 +1158,8 @@ def reset_schedule(self) -> None: self._counting_since = None self._next_check = self.settings.start_step + self.settings.interval_steps if self._readapt_deadline is not None and prev_step >= 0: - remaining = max(1, self._readapt_deadline - max(self.settings.start_step, prev_step)) + first_unrun = max(self.settings.start_step, prev_step + 1) + remaining = max(1, self._readapt_deadline - first_unrun) self._readapt_deadline = self.settings.start_step + remaining self._rows_at_last_round = 0 self._tracker.reset() diff --git a/tests/unittest/_torch/moe/test_moe_warmup_placement.py b/tests/unittest/_torch/moe/test_moe_warmup_placement.py index fa9fad173117..d77d8f7563f5 100644 --- a/tests/unittest/_torch/moe/test_moe_warmup_placement.py +++ b/tests/unittest/_torch/moe/test_moe_warmup_placement.py @@ -14,6 +14,7 @@ """ import functools +import math import pickle import sys import weakref @@ -451,7 +452,7 @@ def make_ctrl( ema = ctrl._tracker._ema if ema is None: ema_problem = "tracker has no EMA after two rounds" - elif abs(float(ema[0, 0]) - expected_ema) >= 1e-9: + elif not math.isclose(float(ema[0, 0]), expected_ema, rel_tol=0.0, abs_tol=1e-9): ema_problem = f"ema={float(ema[0, 0])} != {expected_ema}" _assert_on_all_ranks(ema_problem) @@ -497,31 +498,54 @@ def reqs_with_gens(n: int) -> SimpleNamespace: ) # Real 4x load shift on counted steps reopens all ranks together. + reopen_step = -1 for step in range(15, 21): ra.on_step(step) if ra.frozen: ra.set_live_rows(reqs_with_gens(40 if step % 2 == 0 else 100), draft_len=0) else: + reopen_step = step break + orig_window = max(d_ra.readapt_min_window_steps, 3 * s_ra.interval_steps) + expected_orig_deadline = reopen_step + orig_window _assert_on_all_ranks( None - if (not ra.frozen and ra._readapt_count == 1 and ra._readapt_deadline is not None) + if ( + not ra.frozen + and ra._readapt_count == 1 + and ra._readapt_deadline == expected_orig_deadline + ) else "failed to reopen all ranks on real load shift" ) - # Executor restart during open readapt window preserves a bounded rebased deadline, - # and a repeated reset before the next step is idempotent even with start_step > 0. + # Executor restart during open readapt window rebases the remaining unrun steps from + # start_step, and a repeated reset before the next step is idempotent even with start_step > 0. + expected_rebased_deadline = s_ra.start_step + max( + 1, expected_orig_deadline - max(s_ra.start_step, reopen_step + 1) + ) ra.reset_schedule() - deadline = ra._readapt_deadline + first_deadline = ra._readapt_deadline ra.reset_schedule() _assert_on_all_ranks( None - if (not ra.frozen and deadline is not None and ra._readapt_deadline == deadline) - else "reset_schedule dropped or extended active readapt deadline" + if ( + not ra.frozen + and first_deadline == expected_rebased_deadline + and ra._readapt_deadline == expected_rebased_deadline + ) + else ( + f"reset_schedule deadline mismatch: first={first_deadline}, " + f"second={ra._readapt_deadline}, expected={expected_rebased_deadline}" + ) ) - assert deadline is not None - for step in range(deadline + 1): + for step in range(expected_rebased_deadline): ra.on_step(step) + _assert_on_all_ranks( + None + if not ra.frozen + else f"controller froze early before rebased deadline {expected_rebased_deadline}" + ) + ra.on_step(expected_rebased_deadline) _assert_on_all_ranks( None if (ra.frozen and not ra.active) @@ -529,7 +553,7 @@ def reqs_with_gens(n: int) -> SimpleNamespace: ) # Further shifts after reaching max_readapts=1 must never reopen again. - for step in range(deadline + 1, deadline + 12): + for step in range(expected_rebased_deadline + 1, expected_rebased_deadline + 12): ra.on_step(step) ra.set_live_rows(reqs_with_gens(80), draft_len=0) _assert_on_all_ranks( @@ -742,6 +766,9 @@ def test_count_routing_early_exit_mask_and_cuda_graph(rows: int, live_bound: int bound = torch.tensor([row_offset + live_bound], dtype=torch.int32, device=device) mask = torch.zeros(row_offset + rows, dtype=torch.int8, device=device) mask[row_offset : row_offset + rows : 2] = 1 + # Keep both live_bound - 1 and live_bound unmasked so the bound alone separates them. + mask[row_offset + live_bound - 1] = 1 + mask[row_offset + live_bound] = 1 counters = mwp.RouteCounters( hist=hist, flag=flag, bound=bound, mask=mask, row_offset=row_offset ) From 179b4253b8b25cedf3f18bf33f5c9131f92494f8 Mon Sep 17 00:00:00 2001 From: Jin Li <59594262+liji-nv@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:40:06 +0800 Subject: [PATCH 5/6] [None][fix] MoE: fix EMA view aliasing, swap tie parity, and default decay/min_rows semantics Address trtllm-agent-review (B1, P1, B5, N3, N5, N6, N7, R2, R3, R6) and CodeRabbit feedback on PR #23186: - Fix B1 (Blocker): copy the float64 EMA slice in _OnlineLoadTracker.layer_load and copy per_copy in target_copies so lpt replicated planning never mutates self._ema in place. - Fix P1: restore the exact relief = load_hi - np.maximum(load_hi - shift, load_lo + shift) > thr acceptance test in plan_layer_swaps so min_gain=0 rejects zero-gain rank-load exchanges bit-for-bit identically to main. - Fix B5: default OnlineDriftConfig.step_ema to 0.0 (keeping drift_alpha=0.4 as the single default-on drift estimator), compute opt-in EMA only on non-deferred planned rounds via preview_ema/commit_round without compounding step_ema with settings.decay, preserving exact decay and min_rows semantics and eliminating steady/deferred regressions. - Fix CodeRabbit & N7: preserve zero remaining steps in reset_schedule() so a reset after the last permitted forward refreezes at start_step; enforce strict int checks on OnlineDriftConfig integer fields; allow zero-baseline freezes to reopen when live traffic arrives; guard post-freeze sampling with _step >= 0 and floor frozen reset cooldown by start_step. - Fix N5, N6, R2, R3, R6: deduplicate schedule catch-up and EP live-row mean helpers; update docstrings, collective ordering docs, and MOE_DEVELOPER_GUIDE; register test_count_routing_early_exit_mask_and_cuda_graph in l0_b200.yml; add B1, P1, B5, zero-remaining, zero-baseline, unmasked/unbounded kernel, and OOB expert-id regression tests. Signed-off-by: Jin Li <59594262+liji-nv@users.noreply.github.com> --- .../moe/fused_moe/MOE_DEVELOPER_GUIDE.md | 2 +- .../moe/fused_moe/moe_warmup_placement.py | 239 +++++++++-------- .../test_lists/test-db/l0_b200.yml | 1 + .../_torch/moe/test_moe_warmup_placement.py | 244 +++++++++++++----- 4 files changed, 311 insertions(+), 175 deletions(-) diff --git a/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md b/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md index c68076960f88..bb0e0ae5ded8 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md +++ b/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md @@ -1463,7 +1463,7 @@ set wrong has a test that catches it: the previous expert's values after a migration, with no error; extend `tests/unittest/_torch/moe/test_w4a16_nvfp4_eplb.py` for a new one. - `FUSED_COMM` backends use `ignore_allreduce=False` for EPLB statistic update because the fused kernel AllReduces routing stats internally. -- Warmup expert placement (`MoeLoadBalancerConfig.warmup_placement`, standard mode only; `moe_warmup_placement.py`) learns the placement of the static balancer layers from the live rows of real requests: each round swaps at most `max_moved_fraction` of a layer's slots between heavy and light ranks and moves their per-slot tensors GPU to GPU in place (captured CUDA graphs stay valid); the placement freezes after `max_migrations` rounds. With extra slots (`num_slots > num_experts`) a layer keeps copies of experts, which hold the same bytes, so outputs are unchanged; each round also moves the copies towards hot experts (cold experts take the extra slots a layer does not need). A backend that `counts_routes` adds the picks in its routing launch; otherwise the schedulers issue a separate count launch. Only a backend that implements `on_expert_placement_changed` is re-placed: `TrtllmCutedslMegaMoeNvfp4Impl` applies a static placement itself (`maps_expert_slots`), so `FusedCommMoEScheduler` hands it expert ids and its route + quantize launch writes slots into the launch bucket. Layers on other backends keep their configured placement, and a model whose MoE layers all run other backends is rejected at load. +- Warmup expert placement (`MoeLoadBalancerConfig.warmup_placement`, standard mode only; `moe_warmup_placement.py`) learns the placement of the static balancer layers from the live rows of real requests: each round swaps at most `max_moved_fraction` of a layer's slots between heavy and light ranks and moves their per-slot tensors GPU to GPU in place (captured CUDA graphs stay valid); multi-round planning also applies rank-0 first-order routing-distribution drift extrapolation (`OnlineDriftConfig`, with opt-in per-round EMA and post-freeze readaptation) before freezing after `max_migrations` rounds. With extra slots (`num_slots > num_experts`) a layer keeps copies of experts, which hold the same bytes, so outputs are unchanged; each round also moves the copies towards hot experts (cold experts take the extra slots a layer does not need). A backend that `counts_routes` adds the picks in its routing launch; otherwise the schedulers issue a separate count launch. Only a backend that implements `on_expert_placement_changed` is re-placed: `TrtllmCutedslMegaMoeNvfp4Impl` applies a static placement itself (`maps_expert_slots`), so `FusedCommMoEScheduler` hands it expert ids and its route + quantize launch writes slots into the launch bucket. Layers on other backends keep their configured placement, and a model whose MoE layers all run other backends is rejected at load. - Per-layer dynamic EPLB uses `MoeConfig.load_balancer.mode=per_layer_dynamic` with `num_slots` greater than the model expert count. Backend resolution selects `MEGAMOE_CUTEDSL` when no concrete backend is requested and rejects an diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py index 6f183751e1c2..f260fdf4e11c 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py @@ -35,11 +35,11 @@ With ``min_round_gain`` a round whose plan lowers the planner's estimate (slowest rank over the mean, averaged over layers) by fewer percentage points moves nothing. With ``decay < 1`` the counters are scaled by it after every round, moved or not, so later rounds follow recent traffic. -By default the planner also runs online drift-aware load tracking on rank 0 -(``OnlineDriftConfig``): per-check-interval counter increments are exponentially smoothed -(``step_ema``) and extrapolated along their round-to-round distribution delta (``drift_alpha``), -requiring zero offline calibration files. Optional post-freeze re-adaptation (``max_readapts > 0``) -watches EP-wide live-row shifts after freeze and re-opens bounded placement rounds when load shifts. +By default the planner also applies first-order distribution drift extrapolation on rank 0 +(``OnlineDriftConfig.drift_alpha``) across multi-round updates while preserving the configured +``decay`` and ``min_rows`` counter semantics; opt-in per-round increment EMA (``step_ema``) and +post-freeze re-adaptation (``max_readapts > 0``, watching the EP sum of per-rank mean live rows per +counted forward) are configured through ``OnlineDriftConfig``. With a large ``max_migrations``, no ``deadline_step`` and ``min_pos >= 2`` (a request's first decode step never counts) the placement follows the served decode traffic for the whole run; ``count_every_steps`` then counts one forward in that many, to keep the per-step host work of the @@ -142,18 +142,34 @@ class RouteCounters(NamedTuple): row_offset: int # the launch's first row in the forward +def _require_int(name: str, value: object, minimum: int) -> None: + if not isinstance(value, int) or isinstance(value, bool) or value < minimum: + raise ValueError(f"{_LOG} {name} must be an int >= {minimum}, got {value!r}") + + @dataclasses.dataclass(frozen=True) class OnlineDriftConfig: """Typed parameters for online drift-aware load tracking and optional post-freeze re-adaptation. - ``step_ema`` exponentially averages per-check-interval counter increments on rank 0 (``0.0`` - disables EMA and uses the raw counters directly). ``drift_alpha`` extrapolates each layer's - normalized routing distribution one step along its round-to-round delta (``0.0`` disables - extrapolation). ``max_readapts > 0`` monitors post-freeze EP-wide live-row shifts and re-opens - bounded placement rounds when load moves outside ``(readapt_ratio_low, readapt_ratio_high)``. + Attributes: + step_ema: Opt-in per-planned-round exponential smoothing factor over counter increments on + rank 0 (``0.0`` disables EMA and plans directly on the decayed counters). + drift_alpha: First-order extrapolation gain applied to each layer's round-to-round + normalized routing distribution delta (``0.0`` disables extrapolation). + max_readapts: Maximum number of post-freeze re-adaptation windows (``0`` disables + post-freeze monitoring). + readapt_cooldown_steps: Steps after freeze (or frozen restart) before the first post-freeze + live-row ratio check. + readapt_check_interval: Steps between subsequent post-freeze live-row ratio checks. + readapt_ratio_high: Upper ratio of post-freeze EP mean live rows per counted forward to the + frozen baseline that triggers re-adaptation (must be > 1). + readapt_ratio_low: Lower ratio of post-freeze EP mean live rows per counted forward to the + frozen baseline that triggers re-adaptation (must be in (0, 1)). + readapt_min_window_steps: Minimum step span of a re-opened re-adaptation window before its + deadline refreezes placement. """ - step_ema: float = 0.5 + step_ema: float = 0.0 drift_alpha: float = 0.4 max_readapts: int = 0 readapt_cooldown_steps: int = 48 @@ -167,16 +183,9 @@ def __post_init__(self) -> None: raise ValueError(f"{_LOG} step_ema must be in [0, 1), got {self.step_ema}") if not (math.isfinite(self.drift_alpha) and self.drift_alpha >= 0.0): raise ValueError(f"{_LOG} drift_alpha must be >= 0, got {self.drift_alpha}") - if self.max_readapts < 0: - raise ValueError(f"{_LOG} max_readapts must be >= 0, got {self.max_readapts}") - if self.readapt_cooldown_steps < 1: - raise ValueError( - f"{_LOG} readapt_cooldown_steps must be >= 1, got {self.readapt_cooldown_steps}" - ) - if self.readapt_check_interval < 1: - raise ValueError( - f"{_LOG} readapt_check_interval must be >= 1, got {self.readapt_check_interval}" - ) + _require_int("max_readapts", self.max_readapts, 0) + _require_int("readapt_cooldown_steps", self.readapt_cooldown_steps, 1) + _require_int("readapt_check_interval", self.readapt_check_interval, 1) if not (math.isfinite(self.readapt_ratio_high) and self.readapt_ratio_high > 1.0): raise ValueError( f"{_LOG} readapt_ratio_high must be > 1, got {self.readapt_ratio_high}" @@ -185,10 +194,7 @@ def __post_init__(self) -> None: raise ValueError( f"{_LOG} readapt_ratio_low must be in (0, 1), got {self.readapt_ratio_low}" ) - if self.readapt_min_window_steps < 1: - raise ValueError( - f"{_LOG} readapt_min_window_steps must be >= 1, got {self.readapt_min_window_steps}" - ) + _require_int("readapt_min_window_steps", self.readapt_min_window_steps, 1) @property def uses_ema(self) -> bool: @@ -245,45 +251,54 @@ def reset(self) -> None: self._prev_glob = None self._prev_prob.clear() - def observe(self, glob: np.ndarray) -> None: - """Fold the newly counted routes since the previous check into the per-layer EMA.""" + def preview_ema(self, glob: np.ndarray) -> Optional[np.ndarray]: + """Compute the updated per-layer EMA for a candidate round without mutating tracker state.""" if not self.uses_ema: - return + return None if self._prev_glob is None: delta = glob.astype(np.float64) else: delta = np.maximum(glob - self._prev_glob, 0).astype(np.float64) - self._prev_glob = glob.copy() - if delta.any(): - if self._ema is None: - self._ema = delta - else: - self._ema = self.config.step_ema * self._ema + delta + if not delta.any(): + return self._ema + if self._ema is None: + return delta + return self.config.step_ema * self._ema + delta def layer_load( - self, layer_index: int, num_experts: int, glob: np.ndarray + self, + layer_index: int, + num_experts: int, + glob: np.ndarray, + ema: Optional[np.ndarray] = None, ) -> Tuple[np.ndarray, Optional[np.ndarray]]: - """Return ``(effective_load, cur_prob)`` for planning ``layer_index``.""" - if self.uses_ema and self._ema is not None: - ema_row = self._ema[layer_index, :num_experts] - raw = ema_row if ema_row.any() else glob[layer_index, :num_experts].astype(np.float64) + """Return ``(effective_load, cur_prob)`` for planning ``layer_index``. + + Always returns a freshly owned float64 array so planners cannot mutate ``self._ema``.""" + src_ema = self._ema if ema is None else ema + if self.uses_ema and src_ema is not None: + ema_row = src_ema[layer_index, :num_experts] + if ema_row.any(): + raw = ema_row.copy() + else: + raw = glob[layer_index, :num_experts].astype(np.float64) else: raw = glob[layer_index, :num_experts].astype(np.float64) if not raw.any(): return raw, None return predict_drifted_load(raw, self._prev_prob.get(layer_index), self.config.drift_alpha) - def on_counters_decayed(self, decayed_glob: Optional[np.ndarray], decay: float = 1.0) -> None: - """Synchronize the baseline snapshot and EMA weight with the post-decay counters.""" - if not self.uses_ema: - return - if decayed_glob is not None: - self._prev_glob = decayed_glob - if decay < 1.0 and self._ema is not None: - self._ema = self._ema * decay - - def commit_probs(self, next_prob: Dict[int, np.ndarray]) -> None: - """Record the normalized distributions observed in a completed planning round.""" + def commit_round( + self, + ema_next: Optional[np.ndarray], + post_round_glob: np.ndarray, + next_prob: Dict[int, np.ndarray], + ) -> None: + """Commit EMA, post-decay counter baseline, and layer distributions after a round.""" + if self.uses_ema: + if ema_next is not None: + self._ema = ema_next + self._prev_glob = post_round_glob.copy() if self.uses_drift and next_prob: self._prev_prob.update(next_prob) @@ -293,6 +308,12 @@ def commit_probs(self, next_prob: Dict[int, np.ndarray]) -> None: NONE, CHECK, LAST = 0, 1, 2 +def _advance_boundary(step: int, anchor: int, interval: int) -> int: + """First grid point ``anchor + k * interval`` strictly past ``step``.""" + k = (step - anchor) // interval + 1 + return anchor + k * interval + + def schedule_action( settings: MoeWarmupPlacementConfig, step: int, next_check: int ) -> Tuple[int, int]: @@ -302,8 +323,7 @@ def schedule_action( if settings.deadline_step is not None and step >= settings.deadline_step: return LAST, next_check if step >= next_check: - k = (step - settings.start_step) // settings.interval_steps + 1 - return CHECK, settings.start_step + k * settings.interval_steps + return CHECK, _advance_boundary(step, settings.start_step, settings.interval_steps) return NONE, next_check @@ -471,7 +491,7 @@ def target_copies(lam: np.ndarray, weight: _Weight, ep_size: int, total_slots: i the coldest experts, which are rarely active. Deterministic.""" lam = np.asarray(lam, dtype=np.float64) copies = np.ones(lam.size, dtype=np.int64) - per_copy = np.asarray(weight(lam), dtype=np.float64) + per_copy = np.array(weight(lam), dtype=np.float64, copy=True) total = float(per_copy.sum()) bound = max(total / ep_size, float(per_copy.max())) for _ in range(total_slots - lam.size): @@ -598,8 +618,11 @@ def plan_layer_swaps( # shift[p, i, j]: load moving from rank his[p] to rank los[p] by swapping slots i and j; the # first best pair in (heavy, light, i, j) order wins. shift = weight[his][:, :, None] - weight[los][:, None, :] + load_hi = loads[his][:, None, None] + load_lo = loads[los][:, None, None] + relief = load_hi - np.maximum(load_hi - shift, load_lo + shift) rem = gap[pair_hi, pair_lo][:, None, None] - shift - ok = (shift > thr) & (rem > thr) + ok = relief > thr if holds is not None: # A copy may not join a rank that already holds its expert. ok &= (~holds[los[:, None], experts[his]])[:, :, None] & ( @@ -740,12 +763,17 @@ class WarmupPlacementController: Collectives of a round run in the same order on every rank: counter allreduce, live-row allreduce (``planner="cost"``), plan broadcast, prepare vote, checksum allreduce (first round), - slot transfers, failure count, counter peak. The round's device buffers are reserved before the - vote, and a rank-local error before it skips the round everywhere; after the vote errors are - fatal. + slot transfers, failure count, counter peak, retained-rows allreduce (``decay < 1``), and + post-decay histogram reduce to rank 0 (``decay < 1`` with EMA enabled). On freeze with + readaptation armed, ``_freeze`` reduces the baseline live-row mean to rank 0, and each + post-freeze readaptation check reduces the current live-row mean to rank 0 and broadcasts the + reopen decision. The round's device buffers are reserved before the vote, and a rank-local error + before it skips the round everywhere; after the vote errors are fatal. ``num_target_layers``: the target model's decoder layers, or None when unknown; a ``"main"`` - layer at or past it is a draft (MTP) layer.""" + layer at or past it is a draft (MTP) layer. + ``drift_config``: optional ``OnlineDriftConfig`` for drift extrapolation, opt-in per-round EMA, + and post-freeze readaptation (defaults to ``OnlineDriftConfig()``).""" def __init__( self, @@ -999,6 +1027,7 @@ def set_live_rows(self, requests: ScheduledRequests, draft_len: int) -> None: if ( self.frozen and self._can_readapt() + and self._step >= 0 and self._step % self.settings.count_every_steps == 0 ): self._post_freeze_rows.append(real_rows_of(requests, draft_len)) @@ -1048,50 +1077,53 @@ def set_live_rows(self, requests: ScheduledRequests, draft_len: int) -> None: self._mask_slot = (self._mask_slot + 1) % len(self._mask_ring) # ------------------------------------------------------------------ schedule + def _mean_live_rows_ep(self, samples: Sequence[int]) -> Optional[float]: + """Sum of per-rank mean live rows per counted forward on rank 0 (None on other ranks).""" + from mpi4py import MPI + + assert self._comm is not None + local = float(np.mean(samples)) if samples else 0.0 + tot = self._comm.reduce(local, op=MPI.SUM, root=0) + return None if tot is None else float(tot) + def _next_action(self, step: int) -> int: if self._readapt_deadline is not None: if step >= self._readapt_deadline: return LAST if step >= self._next_check: anchor = self._counting_since if self._counting_since is not None else step - k = (step - anchor) // self.settings.interval_steps + 1 - self._next_check = anchor + k * self.settings.interval_steps + self._next_check = _advance_boundary(step, anchor, self.settings.interval_steps) return CHECK return NONE action, self._next_check = schedule_action(self.settings, step, self._next_check) return action def _maybe_readapt(self, step: int) -> None: - """Re-open placement rounds when EP-wide live rows shift past the configured bounds.""" + """Re-open placement rounds when EP mean live rows per counted forward shift past bounds.""" if ( not self._can_readapt() or self._next_readapt_check is None or step < self._next_readapt_check - or self._comm is None - or self._hist is None - or self._flag is None ): return - from mpi4py import MPI + assert self._comm is not None and self._hist is not None and self._flag is not None - interval = self.drift_config.readapt_check_interval - k = (step - self._next_readapt_check) // interval + 1 - self._next_readapt_check += k * interval - cur_local = float(np.mean(self._post_freeze_rows)) if self._post_freeze_rows else 0.0 - cur_tot = self._comm.reduce(cur_local, op=MPI.SUM, root=0) + self._next_readapt_check = _advance_boundary( + step, self._next_readapt_check, self.drift_config.readapt_check_interval + ) + cur_tot = self._mean_live_rows_ep(self._post_freeze_rows) trigger = False ratio = 0.0 - if ( - self.ep_rank == 0 - and self._frozen_ep_rows > 0.0 - and cur_tot is not None - and cur_tot > 0.0 - ): - ratio = float(cur_tot) / self._frozen_ep_rows - trigger = ( - ratio >= self.drift_config.readapt_ratio_high - or ratio <= self.drift_config.readapt_ratio_low - ) + if self.ep_rank == 0 and cur_tot is not None and cur_tot > 0.0: + if self._frozen_ep_rows <= 0.0: + ratio = math.inf + trigger = True + else: + ratio = cur_tot / self._frozen_ep_rows + trigger = ( + ratio >= self.drift_config.readapt_ratio_high + or ratio <= self.drift_config.readapt_ratio_low + ) if not self._comm.bcast(trigger, root=0): return self._readapt_count += 1 @@ -1110,11 +1142,11 @@ def _maybe_readapt(self, step: int) -> None: self.drift_config.readapt_min_window_steps, 3 * self.settings.interval_steps ) self._next_readapt_check = None - if self.ep_rank == 0: + if self.ep_rank == 0 and cur_tot is not None: logger.info( - f"{_LOG} concurrency shift detected at step {step} " - f"(EP rows {self._frozen_ep_rows:.0f} -> {float(cur_tot):.0f}, ratio={ratio:.2f}x): " - f"re-adapting placement (readapt #{self._readapt_count}, " + f"{_LOG} live-row shift detected at step {step} " + f"(EP mean rows/forward {self._frozen_ep_rows:.0f} -> {cur_tot:.0f}, " + f"ratio={ratio:.2f}x): re-adapting placement (readapt #{self._readapt_count}, " f"deadline={self._readapt_deadline})" ) @@ -1147,7 +1179,9 @@ def reset_schedule(self) -> None: self._step = -1 if self.frozen: if self._can_readapt() and self._next_readapt_check is not None: - self._next_readapt_check = self.drift_config.readapt_cooldown_steps + self._next_readapt_check = max( + self.settings.start_step, self.drift_config.readapt_cooldown_steps + ) self._post_freeze_rows.clear() return assert self._flag is not None and self._hist is not None @@ -1159,7 +1193,7 @@ def reset_schedule(self) -> None: self._next_check = self.settings.start_step + self.settings.interval_steps if self._readapt_deadline is not None and prev_step >= 0: first_unrun = max(self.settings.start_step, prev_step + 1) - remaining = max(1, self._readapt_deadline - first_unrun) + remaining = max(0, self._readapt_deadline - first_unrun) self._readapt_deadline = self.settings.start_step + remaining self._rows_at_last_round = 0 self._tracker.reset() @@ -1176,8 +1210,6 @@ def _round(self, step: int, last: bool = False) -> None: local = self._hist.cpu().numpy().astype(np.int64) glob = np.empty_like(local) self._comm.Allreduce(local, glob, op=MPI.SUM) - if self.ep_rank == 0: - self._tracker.observe(glob) first = self.layers[0] rows = int(glob[0, : first.num_experts].sum()) // max(1, first.top_k) fresh = rows - self._rows_at_last_round @@ -1199,14 +1231,18 @@ def _round(self, step: int, last: bool = False) -> None: self._check_movable(step) cost = self._cost_inputs(step, glob) if self.settings.planner == "cost" else None plan, note = None, "" + ema_next: Optional[np.ndarray] = None next_prob: Dict[int, np.ndarray] = {} if self.ep_rank == 0: + ema_next = self._tracker.preview_ema(glob) plan, before, after = [], 0.0, 0.0 for layer in self.layers: if not layer.movable: plan.append(None) continue - load, cur_prob = self._tracker.layer_load(layer.index, layer.num_experts, glob) + load, cur_prob = self._tracker.layer_load( + layer.index, layer.num_experts, glob, ema=ema_next + ) if cur_prob is None: # Without counts every expert ties, and the copies would go to the lowest ids. plan.append(None) @@ -1256,10 +1292,9 @@ def _round(self, step: int, last: bool = False) -> None: if plan is None: decayed_glob = self._decay_counters(rows, local) if self.ep_rank == 0: - # Use configured settings.decay for float64 EMA forgetting (decoupled from int32 - # overflow halving); decayed_glob already matches the exact post-decay counter base. - self._tracker.on_counters_decayed(decayed_glob, decay=self.settings.decay) - self._tracker.commit_probs(next_prob) + self._tracker.commit_round( + ema_next, glob if decayed_glob is None else decayed_glob, next_prob + ) logger.info( f"{_LOG} step {step}: the plan gains less than {self.settings.min_round_gain} " f"points; the placement stays, {(time.perf_counter() - t0) * 1e3:.0f} ms{note}" @@ -1275,8 +1310,9 @@ def _round(self, step: int, last: bool = False) -> None: moved, nbytes = applied decayed_glob = self._decay_counters(rows, local) if self.ep_rank == 0: - self._tracker.on_counters_decayed(decayed_glob, decay=self.settings.decay) - self._tracker.commit_probs(next_prob) + self._tracker.commit_round( + ema_next, glob if decayed_glob is None else decayed_glob, next_prob + ) self.migrations_done += 1 logger.info( f"{_LOG} round {self.migrations_done}/{self.settings.max_migrations} at step {step}" @@ -1432,12 +1468,9 @@ def _freeze(self, step: int) -> None: self.frozen = True self._readapt_deadline = None if self._can_readapt() and self._comm is not None: - from mpi4py import MPI - - local_r = float(np.mean(self._live_rows[0])) if self._live_rows[0] else 0.0 - tot_r = self._comm.reduce(local_r, op=MPI.SUM, root=0) - if self.ep_rank == 0: - self._frozen_ep_rows = float(tot_r) + tot_r = self._mean_live_rows_ep(self._live_rows[0]) + if self.ep_rank == 0 and tot_r is not None: + self._frozen_ep_rows = tot_r self._next_readapt_check = step + self.drift_config.readapt_cooldown_steps self._post_freeze_rows.clear() else: @@ -1745,7 +1778,7 @@ def on_executor_restart() -> None: def active() -> bool: - """Whether a controller still counts (cheap; for per-step hooks).""" + """Whether any controller still needs per-step live-row inputs (counting or readapt-armed).""" return any(c.active for c in list(_controllers)) diff --git a/tests/integration/test_lists/test-db/l0_b200.yml b/tests/integration/test_lists/test-db/l0_b200.yml index ee00cdb2860a..c18841055613 100644 --- a/tests/integration/test_lists/test-db/l0_b200.yml +++ b/tests/integration/test_lists/test-db/l0_b200.yml @@ -175,6 +175,7 @@ l0_b200: # Fused DS-V4 routing and activation quantization for the TRTLLM and MegaMoE backends. - unittest/_torch/moe/test_dsv4_route_quant.py - unittest/_torch/moe/test_megamoe_stage_inputs.py + - unittest/_torch/moe/test_moe_warmup_placement.py::test_count_routing_early_exit_mask_and_cuda_graph - unittest/_torch/moe/test_moe_module.py::test_dsv4_fused_route_quant_matches_separate_launches - unittest/_torch/moe/test_moe_module.py::test_dspark_draft_fused_route_quant_matches_separate_launches - unittest/_torch/modules/test_gated_mlp.py::test_fp8_block_scale_mlp_small_m_matches_deep_gemm diff --git a/tests/unittest/_torch/moe/test_moe_warmup_placement.py b/tests/unittest/_torch/moe/test_moe_warmup_placement.py index d77d8f7563f5..ac2a7bbc14f8 100644 --- a/tests/unittest/_torch/moe/test_moe_warmup_placement.py +++ b/tests/unittest/_torch/moe/test_moe_warmup_placement.py @@ -33,6 +33,7 @@ from tensorrt_llm._torch.model_config import ModelConfig from tensorrt_llm._torch.moe.fused_moe import SwigluActivation, create_moe from tensorrt_llm._torch.moe.fused_moe import moe_warmup_placement as mwp +from tensorrt_llm._torch.moe.fused_moe.interface import MoE from tensorrt_llm._torch.moe.fused_moe.mega_moe import mega_moe_cute_dsl from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import ( MoeLoadBalancer, @@ -78,7 +79,7 @@ def _routing(bias: torch.Tensor) -> DeepSeekV4MoeRoutingMethod: ) -def _build(weights, bias, settings, tokens: int, passes): +def _build(weights, bias, settings, tokens: int, passes, drift_config=None): """One layer per (row pass, rows per request, extra slots per rank) of ``passes`` on a static balancer, with a warmup placement controller for ``settings``.""" rank, world_size = mpi_rank(), mpi_world_size() @@ -113,7 +114,9 @@ def lb_config(extra_slots): max_num_tokens=tokens, moe_max_num_tokens=tokens, ) - controller = mwp.WarmupPlacementController(settings, ep_rank=rank, ep_size=world_size) + controller = mwp.WarmupPlacementController( + settings, ep_rank=rank, ep_size=world_size, drift_config=drift_config + ) balancer = MoeLoadBalancer( ep_rank=rank, ep_size=world_size, layer_updates_per_iter=0, warmup_placement=controller ) @@ -275,12 +278,14 @@ def _run_placement(gens: int, draft_len: int) -> None: max_moved_fraction=0.1, min_gain=0.0, ) + drift_cfg = None if gens == 25 else mwp.OnlineDriftConfig(step_ema=0.5, drift_alpha=0.4) layers, balancer, controller = _build( weights, bias, settings, tokens, passes=(("main", None, 0), ("draft", draft_len, 0), ("main", None, 1)), + drift_config=drift_cfg, ) del weights default = list(layers[2].initial_global_assignments) @@ -381,9 +386,10 @@ def _run_placement(gens: int, draft_len: int) -> None: _check_controller_lifecycle_contracts(layers[0]) -def _check_controller_lifecycle_contracts(moe) -> None: +def _check_controller_lifecycle_contracts(moe: MoE) -> None: """Exercise production MPI post-decay reduction, fresh-row baseline, alternating-load - cadence alignment, collective readaptation reopen/refreeze, and deadline rebase on restart.""" + cadence alignment, collective readaptation reopen/refreeze, zero-baseline reopen, and + deadline rebase (including zero remaining steps) on restart.""" rank, world = mpi_rank(), mpi_world_size() num_experts, spr = 8, 8 // world device = torch.device("cuda", rank) @@ -415,7 +421,8 @@ def make_ctrl( return ctrl # 1. Production _decay_counters keeps exact retained fresh-row baseline and EMA increment sync - # even when every rank's local counter floors to 0 (both EMA enabled and disabled). + # even when every rank's local counter floors to 0 (both EMA enabled and disabled), without + # compounding step_ema with decay. for step_ema in (0.0, 0.5): s_dec = MoeWarmupPlacementConfig( start_step=0, @@ -446,9 +453,9 @@ def make_ctrl( ) ema_problem = None if step_ema > 0.0 and rank == 0: - # Round 1 observed 4 -> decayed by 0.5 to 2; round 2 observes +1 -> 0.5 * 2 + 1 = 2.0, - # then decayed by 0.5 to 1.0 after round 2 completes. - expected_ema = 0.5 * (0.5 * (0.5 * world) + 1.0) + # Round 1 observed 4 -> committed EMA=4.0, post-decay baseline=0; + # round 2 observes +1 -> 0.5 * 4.0 + 1.0 = 3.0 (no decay compounding). + expected_ema = 0.5 * float(world) + 1.0 ema = ctrl._tracker._ema if ema is None: ema_problem = "tracker has no EMA after two rounds" @@ -458,7 +465,8 @@ def make_ctrl( # 2. Alternating workload under count_every_steps=2 must not trigger false readaptation; # a true load shift must reopen every rank, reset_schedule must preserve a bounded - # rebased deadline, and the controller must refreeze at deadline without a second reopen. + # rebased deadline (distinguishing readapt_min_window_steps=8 from 3*interval_steps=6), + # and the controller must refreeze at deadline without a second reopen. def reqs_with_gens(n: int) -> SimpleNamespace: live = [ SimpleNamespace(is_dummy=False, max_beam_num_tokens=1100, orig_prompt_len=100) @@ -475,12 +483,12 @@ def reqs_with_gens(n: int) -> SimpleNamespace: deadline_step=6, ) d_ra = mwp.OnlineDriftConfig( - step_ema=0.5, + step_ema=0.0, drift_alpha=0.4, max_readapts=1, readapt_cooldown_steps=4, readapt_check_interval=2, - readapt_min_window_steps=6, + readapt_min_window_steps=8, ) ra = make_ctrl(s_ra, d_ra) for step in range(7): @@ -521,7 +529,7 @@ def reqs_with_gens(n: int) -> SimpleNamespace: # Executor restart during open readapt window rebases the remaining unrun steps from # start_step, and a repeated reset before the next step is idempotent even with start_step > 0. expected_rebased_deadline = s_ra.start_step + max( - 1, expected_orig_deadline - max(s_ra.start_step, reopen_step + 1) + 0, expected_orig_deadline - max(s_ra.start_step, reopen_step + 1) ) ra.reset_schedule() first_deadline = ra._readapt_deadline @@ -545,22 +553,33 @@ def reqs_with_gens(n: int) -> SimpleNamespace: if not ra.frozen else f"controller froze early before rebased deadline {expected_rebased_deadline}" ) - ra.on_step(expected_rebased_deadline) + # Reset after the last permitted forward preserves zero remaining steps -> freezes at start_step. + ra.reset_schedule() + _assert_on_all_ranks( + None + if (not ra.frozen and ra._readapt_deadline == s_ra.start_step) + else f"zero-remaining reset deadline={ra._readapt_deadline} != {s_ra.start_step}" + ) + for step in range(s_ra.start_step): + ra.on_step(step) + _assert_on_all_ranks(None if not ra.frozen else "froze before restarted start_step") + ra.on_step(s_ra.start_step) _assert_on_all_ranks( None if (ra.frozen and not ra.active) - else "controller did not refreeze at rebased deadline or stayed active past max_readapts" + else "controller did not refreeze at start_step or stayed active past max_readapts" ) # Further shifts after reaching max_readapts=1 must never reopen again. - for step in range(expected_rebased_deadline + 1, expected_rebased_deadline + 12): + for step in range(s_ra.start_step + 1, s_ra.start_step + 12): ra.on_step(step) ra.set_live_rows(reqs_with_gens(80), draft_len=0) _assert_on_all_ranks( None if (ra.frozen and ra._readapt_count == 1) else "reopened past max_readapts" ) - # 3. Frozen reset_schedule resets cooldown/buffer, and a low-ratio load drop reopens all ranks. + # 3. Frozen reset_schedule resets cooldown/buffer, low-ratio drop reopens all ranks, and a + # zero-baseline freeze reopens once live traffic arrives. ra_low = make_ctrl(s_ra, d_ra) for step in range(7): ra_low.on_step(step) @@ -569,16 +588,17 @@ def reqs_with_gens(n: int) -> SimpleNamespace: ra_low.on_step(8) ra_low.set_live_rows(reqs_with_gens(100), draft_len=0) ra_low.reset_schedule() + expected_check = max(s_ra.start_step, d_ra.readapt_cooldown_steps) _assert_on_all_ranks( None if ( ra_low.frozen - and ra_low._next_readapt_check == d_ra.readapt_cooldown_steps + and ra_low._next_readapt_check == expected_check and not ra_low._post_freeze_rows ) else "frozen reset_schedule failed to reset readapt cooldown or buffer" ) - for step in range(0, 7): + for step in range(0, expected_check + 3): ra_low.on_step(step) if ra_low.frozen: ra_low.set_live_rows(reqs_with_gens(40), draft_len=0) @@ -590,6 +610,20 @@ def reqs_with_gens(n: int) -> SimpleNamespace: else "low-ratio load drop failed to reopen all ranks" ) + ra_zero = make_ctrl(s_ra, d_ra) + ra_zero.on_step(6) # freezes before any live_rows sample -> baseline 0 + for step in range(7, 13): + ra_zero.on_step(step) + if ra_zero.frozen: + ra_zero.set_live_rows(reqs_with_gens(20), draft_len=0) + else: + break + _assert_on_all_ranks( + None + if (not ra_zero.frozen and ra_zero._readapt_count == 1) + else "zero-baseline freeze failed to reopen when traffic arrived" + ) + @pytest.mark.threadleak(enabled=False) @pytest.mark.skipif( @@ -614,9 +648,9 @@ def test_megamoe_placement(gens: int, draft_len: int) -> None: @pytest.mark.cpu_only def test_online_drift_rebalance_bijection_and_determinism() -> None: - """Online EMA + drift extrapolation rebalances faster under hot-expert drift, preserves - bijection/replicated-cover invariants, stays deterministic across ranks, tracks post-decay - increments accurately, and rejects invalid placements.""" + """Verify drift extrapolation improvement, EMA immutability under lpt replicated planning, + exact swap parity on min_gain=0 floating-point ties, bijection/cover invariants, and + fail-closed guards.""" ep_size, spr, num_experts = 8, 8, 64 spr_rep = spr + 1 max_swaps = 4 @@ -628,14 +662,16 @@ def make_phase_counts(hot_weights: dict[int, int], cold: int = 1) -> np.ndarray: return local # Phase 0 concentrates load on rank 0; phase 1 drifts toward rank 3 while rank 0 cools; - # phase 2 completes the shift to rank 3 (evaluated out-of-sample on the placement after phase 1). + # evaluated out-of-sample on the completed shift to rank 3. phases = [ make_phase_counts({0: 120}), make_phase_counts({0: 25, 3: 65}), ] next_target = make_phase_counts({3: 120}).sum(axis=0)[0].astype(np.float64) - def run_sequence(cfg: mwp.OnlineDriftConfig) -> tuple[list[int], list[int], list[np.ndarray]]: + def run_sequence( + cfg: mwp.OnlineDriftConfig, decay: float = 0.5 + ) -> tuple[list[int], list[int], list[np.ndarray]]: tracker = mwp._OnlineLoadTracker(cfg) assign = list(range(num_experts)) rep_assign = list(range(num_experts)) + list(range(ep_size)) @@ -644,8 +680,8 @@ def run_sequence(cfg: mwp.OnlineDriftConfig) -> tuple[list[int], list[int], list for delta_local in phases: hist_local += delta_local glob = hist_local.sum(axis=0) - tracker.observe(glob) - load, cur_prob = tracker.layer_load(0, num_experts, glob) + ema_next = tracker.preview_ema(glob) + load, cur_prob = tracker.layer_load(0, num_experts, glob, ema=ema_next) assert cur_prob is not None loads_seen.append(load.copy()) @@ -662,37 +698,91 @@ def run_sequence(cfg: mwp.OnlineDriftConfig) -> tuple[list[int], list[int], list slot_w, chosen, spr_rep, (2 * max_swaps - moves) // 2, min_gain=0.0 ) assert mwp.is_replicated_cover(rep_assign, num_experts, spr_rep, ep_size) - tracker.commit_probs({0: cur_prob}) + hist_local = np.floor(hist_local.astype(np.float64) * decay).astype(np.int64) + tracker.commit_round(ema_next, hist_local.sum(axis=0), {0: cur_prob}) return assign, rep_assign, loads_seen - drift_cfg = mwp.OnlineDriftConfig(step_ema=0.5, drift_alpha=0.4) - static_cfg = mwp.OnlineDriftConfig(step_ema=0.0, drift_alpha=0.0) + default_cfg = mwp.OnlineDriftConfig() + assert not default_cfg.uses_ema and default_cfg.uses_drift - drift_a, rep_a, loads_a = run_sequence(drift_cfg) - drift_b, rep_b, loads_b = run_sequence(drift_cfg) - static_a, _, _ = run_sequence(static_cfg) + # Exact formula check for predict_drifted_load. + p_prev = np.array([0.8, 0.2], dtype=np.float64) + pred, p_cur = mwp.predict_drifted_load(np.array([40.0, 60.0]), p_prev, drift_alpha=0.5) + np.testing.assert_allclose(p_cur, np.array([0.4, 0.6])) + np.testing.assert_allclose(pred, np.array([20.0, 80.0])) - # Strict cross-rank determinism for both effective loads and discrete placements. - assert drift_a == drift_b - assert rep_a == rep_b - assert all(np.array_equal(a, b) for a, b in zip(loads_a, loads_b)) - - # On the upcoming drifted traffic, drift-aware placement yields lower tail imbalance. + # Drift extrapolation alone (step_ema=0) improves out-of-sample tail excess over static counts. + drift_a, rep_a, loads_a = run_sequence(default_cfg, decay=0.5) + static_a, _, _ = run_sequence(mwp.OnlineDriftConfig(step_ema=0.0, drift_alpha=0.0), decay=0.5) assert mwp._excess(next_target, drift_a, spr) < mwp._excess(next_target, static_a, spr) - - # Exact post-decay snapshot sync prevents losing routes when per-rank floor rounds to zero. - t = mwp._OnlineLoadTracker(drift_cfg) - local_r = np.ones((ep_size, 1, num_experts), dtype=np.int64) - t.observe(local_r.sum(axis=0)) - decayed_local = np.floor(local_r.astype(np.float64) * 0.5).astype(np.int64) - t.on_counters_decayed(decayed_local.sum(axis=0), decay=0.5) - next_local = decayed_local + np.ones((ep_size, 1, num_experts), dtype=np.int64) - t.observe(next_local.sum(axis=0)) - eff, _ = t.layer_load(0, num_experts, next_local.sum(axis=0)) - np.testing.assert_allclose(eff, np.full(num_experts, 0.5 * (0.5 * ep_size) + ep_size)) + assert mwp.is_replicated_cover(rep_a, num_experts, spr_rep, ep_size) + assert len(loads_a) == len(phases) + + # Regression (B1): lpt replicated planning must not mutate tracker._ema through a view. + ema_tracker = mwp._OnlineLoadTracker(mwp.OnlineDriftConfig(step_ema=0.5, drift_alpha=0.4)) + skew = np.array([[100] + [10] * 7], dtype=np.int64) + ema_next = ema_tracker.preview_ema(skew) + assert ema_next is not None + ema_tracker.commit_round(ema_next, skew, {}) + assert ema_tracker._ema is not None + before_ema = ema_tracker._ema.copy() + load_lpt, _ = ema_tracker.layer_load(0, 8, skew) + assert not np.shares_memory(load_lpt, ema_tracker._ema) + lam_lpt, w_lpt = mwp._replica_inputs(load_lpt, top_k=2, cost=None, row_space=0) + mwp.plan_layer_copy_moves(lam_lpt, list(range(8)) + list(range(4)), 3, w_lpt, max_moves=4) + np.testing.assert_array_equal(ema_tracker._ema, before_ema) + + # Regression (P1): plan_layer_swaps at min_gain=0 must reject exact rank-load exchanges and + # match the reference acceptance/ranking rules across floating-point tie-heavy cases. + def ref_plan_swaps( + slot_w: np.ndarray, slot_e: list[int], rank_slots: int, limit: int + ) -> tuple[list[int], int]: + ex = np.asarray(slot_e, dtype=np.int64).reshape(-1, rank_slots).copy() + wt = np.asarray(slot_w, dtype=np.float64).reshape(-1, rank_slots).copy() + r = ex.shape[0] + has_copies = np.bincount(ex.reshape(-1)).max(initial=1) > 1 + lds = wt.sum(axis=1) + mn = float(lds.mean()) + n_swaps = 0 + while n_swaps < limit and mn > 0: + order = np.argsort(-lds, kind="stable") + heavy = order[: max(1, r // 4)] + light = order[r - max(1, r // 2) :] + gap = lds[heavy][:, None] - lds[light][None, :] + p_hi, p_lo = np.nonzero((gap > 0) & (gap >= -1e-9 * lds[heavy][:, None])) + if p_hi.size == 0: + break + his, los = heavy[p_hi], light[p_lo] + shift = wt[his][:, :, None] - wt[los][:, None, :] + l_hi, l_lo = lds[his][:, None, None], lds[los][:, None, None] + drop = 2.0 * shift * ((l_hi - l_lo) - shift) + ok = (l_hi - np.maximum(l_hi - shift, l_lo + shift)) > 0.0 + if has_copies: + same = ex[his][:, :, None] == ex[los][:, None, :] + ok &= ~same.any(axis=2)[:, :, None] & ~same.any(axis=1)[:, None, :] + drop = np.where(ok, drop, -np.inf) + p, i, j = np.unravel_index(int(np.argmax(drop)), drop.shape) + if not np.isfinite(drop[p, i, j]): + break + hi, lo, i, j = int(his[p]), int(los[p]), int(i), int(j) + ex[hi, i], ex[lo, j] = ex[lo, j], ex[hi, i] + wt[hi, i], wt[lo, j] = wt[lo, j], wt[hi, i] + lds[hi], lds[lo] = wt[hi].sum(), wt[lo].sum() + n_swaps += 1 + return ex.reshape(-1).tolist(), n_swaps + + rng = np.random.default_rng(12345) + for case_idx in range(50): + r = (4, 8, 16)[case_idx % 3] + rs = (2, 4, 8)[(case_idx // 3) % 3] + u = float(rng.uniform(0.9, 1.1)) + counts = rng.integers(0, 6, size=r * rs) + sw = counts.astype(np.float64) * u / 3.0 + se = list(range(r * rs)) if case_idx % 2 == 0 else [i % (r * rs - r) for i in range(r * rs)] + assert mwp.plan_layer_swaps(sw, se, rs, 6, 0.0) == ref_plan_swaps(sw, se, rs, 6) # Fail-closed validation rejects duplicate/missing experts, bad apply_plan inputs before any - # collective, and invalid drift bounds. + # collective, and invalid drift bounds / non-integer limits. bad_bijection = list(range(num_experts)) bad_bijection[0] = bad_bijection[1] assert not mwp.is_valid_placement(bad_bijection, num_experts, spr, ep_size) @@ -741,34 +831,47 @@ def run_sequence(cfg: mwp.OnlineDriftConfig) -> tuple[list[int], list[int], list mwp.OnlineDriftConfig(readapt_ratio_low=1.0) with pytest.raises(ValueError, match="readapt_ratio_low"): mwp.OnlineDriftConfig(readapt_ratio_low=0.0) + with pytest.raises(ValueError, match="max_readapts"): + mwp.OnlineDriftConfig(**{"max_readapts": 1.5}) + with pytest.raises(ValueError, match="max_readapts"): + mwp.OnlineDriftConfig(max_readapts=True) @pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA") @pytest.mark.parametrize( - ("rows", "live_bound"), - [(96, 64), (2049, 2046)], - ids=["rows1", "rows4_tile_split"], + ("rows", "live_bound", "use_mask"), + [(96, 64, True), (2049, 2046, True), (2049, -1, False)], + ids=["rows1_masked", "rows4_tile_split_masked", "rows4_unmasked_unbounded"], ) -def test_count_routing_early_exit_mask_and_cuda_graph(rows: int, live_bound: int) -> None: +def test_count_routing_early_exit_mask_and_cuda_graph( + rows: int, live_bound: int, use_mask: bool +) -> None: """The Triton route-counting kernel honors flag early-exit, live-row bounds (including - 4-row tile splits above 2048 rows), row_offset, row masks, and zero-logit filtering under - CUDA graph replay.""" + 4-row tile splits above 2048 rows and unbounded bound=-1), row_offset, masked/unmasked modes, + out-of-range expert ids, and zero-logit filtering under CUDA graph replay.""" top_k, num_experts = 6, 384 row_offset = 16 device = torch.device("cuda", 0) - gen = torch.Generator(device="cpu").manual_seed(2026 + rows) + gen = torch.Generator(device="cpu").manual_seed(2026 + rows + int(use_mask)) ids = torch.randint(0, num_experts, (rows, top_k), generator=gen, dtype=torch.int32).to(device) + # Include out-of-range ids to verify they are ignored without corrupting memory. + ids[0, 0] = -1 + ids[1, 1] = num_experts logits = torch.randn((rows, num_experts), generator=gen, dtype=torch.bfloat16).to(device) logits[10:20].zero_() hist = torch.zeros(num_experts, dtype=torch.int32, device=device) flag = torch.ones(1, dtype=torch.int32, device=device) - bound = torch.tensor([row_offset + live_bound], dtype=torch.int32, device=device) - mask = torch.zeros(row_offset + rows, dtype=torch.int8, device=device) - mask[row_offset : row_offset + rows : 2] = 1 - # Keep both live_bound - 1 and live_bound unmasked so the bound alone separates them. - mask[row_offset + live_bound - 1] = 1 - mask[row_offset + live_bound] = 1 + bound_val = -1 if live_bound < 0 else row_offset + live_bound + bound = torch.tensor([bound_val], dtype=torch.int32, device=device) + mask: Optional[torch.Tensor] = None + if use_mask: + mask = torch.zeros(row_offset + rows, dtype=torch.int8, device=device) + # Stride 3 exercises both even and odd lanes of 4-row programs. + mask[row_offset : row_offset + rows : 3] = 1 + # Keep both live_bound - 1 and live_bound unmasked so the bound alone separates them. + mask[row_offset + live_bound - 1] = 1 + mask[row_offset + live_bound] = 1 counters = mwp.RouteCounters( hist=hist, flag=flag, bound=bound, mask=mask, row_offset=row_offset ) @@ -782,17 +885,16 @@ def test_count_routing_early_exit_mask_and_cuda_graph(rows: int, live_bound: int with torch.cuda.graph(graph): mwp.count_routing(ids, counters, logits) - # Replay 1: active counting with partial bound, mask, row_offset, and zero-logit rows. + # Replay 1: active counting with bound, optional mask, row_offset, zero-logit and OOB ids. graph.replay() torch.cuda.synchronize() - valid_rows = ( - (torch.arange(rows, device=device) < live_bound) - & (mask[row_offset : row_offset + rows] != 0) - & (logits.abs().amax(dim=1) > 0) - ) - expected = torch.bincount(ids[valid_rows].reshape(-1).long(), minlength=num_experts).to( - torch.int32 - ) + limit = rows if live_bound < 0 else live_bound + valid_rows = (torch.arange(rows, device=device) < limit) & (logits.abs().amax(dim=1) > 0) + if mask is not None: + valid_rows &= mask[row_offset : row_offset + rows] != 0 + kept_ids = ids[valid_rows].reshape(-1).long() + kept_ids = kept_ids[(kept_ids >= 0) & (kept_ids < num_experts)] + expected = torch.bincount(kept_ids, minlength=num_experts).to(torch.int32) assert torch.equal(hist, expected) # Replay 2: flag cleared -> early exit leaves counters untouched. From 8a507ea4b271e95bb97973dabe17621eb792d2d0 Mon Sep 17 00:00:00 2001 From: Jin Li <59594262+liji-nv@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:33:04 +0800 Subject: [PATCH 6/6] [None][perf] MoE: expose opt-in warmup_placement step_ema and drift_alpha in llm_args Signed-off-by: Jin Li <59594262+liji-nv@users.noreply.github.com> --- .../moe/fused_moe/MOE_DEVELOPER_GUIDE.md | 2 +- .../_torch/moe/fused_moe/moe_load_balancer.py | 8 +- .../moe/fused_moe/moe_warmup_placement.py | 17 ++-- tensorrt_llm/llmapi/llm_args.py | 17 ++++ .../schemas/trtllm-serve-config.schema.json | 17 ++++ .../trtllm-serve-disagg-config.schema.json | 17 ++++ .../usage/llm_args_golden_manifest.json | 10 +++ .../_torch/moe/test_moe_warmup_placement.py | 86 +++++++++++++++---- .../test_trtllm_serve_config_schemas.py | 5 ++ 9 files changed, 151 insertions(+), 28 deletions(-) diff --git a/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md b/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md index bb0e0ae5ded8..6e68e2490afb 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md +++ b/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md @@ -1463,7 +1463,7 @@ set wrong has a test that catches it: the previous expert's values after a migration, with no error; extend `tests/unittest/_torch/moe/test_w4a16_nvfp4_eplb.py` for a new one. - `FUSED_COMM` backends use `ignore_allreduce=False` for EPLB statistic update because the fused kernel AllReduces routing stats internally. -- Warmup expert placement (`MoeLoadBalancerConfig.warmup_placement`, standard mode only; `moe_warmup_placement.py`) learns the placement of the static balancer layers from the live rows of real requests: each round swaps at most `max_moved_fraction` of a layer's slots between heavy and light ranks and moves their per-slot tensors GPU to GPU in place (captured CUDA graphs stay valid); multi-round planning also applies rank-0 first-order routing-distribution drift extrapolation (`OnlineDriftConfig`, with opt-in per-round EMA and post-freeze readaptation) before freezing after `max_migrations` rounds. With extra slots (`num_slots > num_experts`) a layer keeps copies of experts, which hold the same bytes, so outputs are unchanged; each round also moves the copies towards hot experts (cold experts take the extra slots a layer does not need). A backend that `counts_routes` adds the picks in its routing launch; otherwise the schedulers issue a separate count launch. Only a backend that implements `on_expert_placement_changed` is re-placed: `TrtllmCutedslMegaMoeNvfp4Impl` applies a static placement itself (`maps_expert_slots`), so `FusedCommMoEScheduler` hands it expert ids and its route + quantize launch writes slots into the launch bucket. Layers on other backends keep their configured placement, and a model whose MoE layers all run other backends is rejected at load. +- Warmup expert placement (`MoeLoadBalancerConfig.warmup_placement`, standard mode only; `moe_warmup_placement.py`) learns the placement of the static balancer layers from the live rows of real requests: each round swaps at most `max_moved_fraction` of a layer's slots between heavy and light ranks and moves their per-slot tensors GPU to GPU in place (captured CUDA graphs stay valid); opt-in `step_ema` and `drift_alpha` on `MoeWarmupPlacementConfig` (both `0.0` by default, forwarded via `OnlineDriftConfig`) enable rank-0 per-round increment EMA and round-to-round routing-distribution drift extrapolation before freezing after `max_migrations` rounds. With extra slots (`num_slots > num_experts`) a layer keeps copies of experts, which hold the same bytes, so outputs are unchanged; each round also moves the copies towards hot experts (cold experts take the extra slots a layer does not need). A backend that `counts_routes` adds the picks in its routing launch; otherwise the schedulers issue a separate count launch. Only a backend that implements `on_expert_placement_changed` is re-placed: `TrtllmCutedslMegaMoeNvfp4Impl` applies a static placement itself (`maps_expert_slots`), so `FusedCommMoEScheduler` hands it expert ids and its route + quantize launch writes slots into the launch bucket. Layers on other backends keep their configured placement, and a model whose MoE layers all run other backends is rejected at load. - Per-layer dynamic EPLB uses `MoeConfig.load_balancer.mode=per_layer_dynamic` with `num_slots` greater than the model expert count. Backend resolution selects `MEGAMOE_CUTEDSL` when no concrete backend is requested and rejects an diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py b/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py index 1e0b88ea1c73..95cc8390a6dd 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_load_balancer.py @@ -1268,7 +1268,8 @@ def _create_warmup_placement( model_config: "ModelConfig", ep_rank: int, ep_size: int) -> Optional["WarmupPlacementController"]: """The controller of ``moe_load_balancer.warmup_placement``, or None when unset.""" - from .moe_warmup_placement import (WarmupPlacementController, + from .moe_warmup_placement import (OnlineDriftConfig, + WarmupPlacementController, register_controller) settings = model_config.moe_load_balancer.warmup_placement if settings is None: @@ -1278,10 +1279,13 @@ def _create_warmup_placement( if text_config is None: text_config = model_config.pretrained_config num_layers = getattr(text_config, "num_hidden_layers", None) + drift_config = OnlineDriftConfig(step_ema=settings.step_ema, + drift_alpha=settings.drift_alpha) controller = WarmupPlacementController(settings, ep_rank=ep_rank, ep_size=ep_size, - num_target_layers=num_layers) + num_target_layers=num_layers, + drift_config=drift_config) register_controller(controller) return controller diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py index f260fdf4e11c..b6668bc4aafc 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_warmup_placement.py @@ -35,11 +35,12 @@ With ``min_round_gain`` a round whose plan lowers the planner's estimate (slowest rank over the mean, averaged over layers) by fewer percentage points moves nothing. With ``decay < 1`` the counters are scaled by it after every round, moved or not, so later rounds follow recent traffic. -By default the planner also applies first-order distribution drift extrapolation on rank 0 -(``OnlineDriftConfig.drift_alpha``) across multi-round updates while preserving the configured -``decay`` and ``min_rows`` counter semantics; opt-in per-round increment EMA (``step_ema``) and -post-freeze re-adaptation (``max_readapts > 0``, watching the EP sum of per-rank mean live rows per -counted forward) are configured through ``OnlineDriftConfig``. +Opt-in online drift tracking on rank 0 is configured via ``OnlineDriftConfig`` (and exposed on +``MoeWarmupPlacementConfig`` via ``step_ema`` and ``drift_alpha``, both defaulting to ``0.0``): +``step_ema`` smooths per-planned-round counter increments, ``drift_alpha`` extrapolates each +layer's normalized distribution along its round-to-round delta on rounds 2+, and +``max_readapts > 0`` watches the EP sum of per-rank mean live rows per counted forward after freeze +to re-open bounded placement rounds. With a large ``max_migrations``, no ``deadline_step`` and ``min_pos >= 2`` (a request's first decode step never counts) the placement follows the served decode traffic for the whole run; ``count_every_steps`` then counts one forward in that many, to keep the per-step host work of the @@ -170,7 +171,7 @@ class OnlineDriftConfig: """ step_ema: float = 0.0 - drift_alpha: float = 0.4 + drift_alpha: float = 0.0 max_readapts: int = 0 readapt_cooldown_steps: int = 48 readapt_check_interval: int = 32 @@ -772,8 +773,8 @@ class WarmupPlacementController: ``num_target_layers``: the target model's decoder layers, or None when unknown; a ``"main"`` layer at or past it is a draft (MTP) layer. - ``drift_config``: optional ``OnlineDriftConfig`` for drift extrapolation, opt-in per-round EMA, - and post-freeze readaptation (defaults to ``OnlineDriftConfig()``).""" + ``drift_config``: optional ``OnlineDriftConfig`` for opt-in drift extrapolation, per-round EMA, + and post-freeze readaptation (defaults to ``OnlineDriftConfig()``, all disabled).""" def __init__( self, diff --git a/tensorrt_llm/llmapi/llm_args.py b/tensorrt_llm/llmapi/llm_args.py index 28076aa42472..af995441acdd 100644 --- a/tensorrt_llm/llmapi/llm_args.py +++ b/tensorrt_llm/llmapi/llm_args.py @@ -2281,6 +2281,23 @@ class MoeWarmupPlacementConfig(StrictBaseModel): "the layers, by fewer than this many percentage points (not a fraction, unlike min_gain) " "moves nothing; 0 turns the check off.", status="prototype") + step_ema: float = Field( + default=0.0, + ge=0.0, + lt=1.0, + allow_inf_nan=False, + description= + "Per-planned-round exponential smoothing factor over counter increments on rank 0; " + "0 disables EMA and plans directly on the decayed counters.", + status="prototype") + drift_alpha: float = Field( + default=0.0, + ge=0.0, + allow_inf_nan=False, + description= + "First-order extrapolation gain applied on rounds 2+ to each layer's round-to-round " + "normalized routing distribution delta; 0 disables extrapolation.", + status="prototype") class _MoeLoadBalancerConfigBase(StrictBaseModel): diff --git a/tensorrt_llm/schemas/trtllm-serve-config.schema.json b/tensorrt_llm/schemas/trtllm-serve-config.schema.json index 23999d2e8237..193c0a3d9b9b 100644 --- a/tensorrt_llm/schemas/trtllm-serve-config.schema.json +++ b/tensorrt_llm/schemas/trtllm-serve-config.schema.json @@ -5699,6 +5699,14 @@ "title": "Decay", "type": "number" }, + "drift_alpha": { + "default": 0.0, + "description": "First-order extrapolation gain applied on rounds 2+ to each layer's round-to-round normalized routing distribution delta; 0 disables extrapolation.", + "minimum": 0.0, + "status": "prototype", + "title": "Drift Alpha", + "type": "number" + }, "interval_steps": { "description": "A placement round every this many steps after start_step.", "minimum": 1, @@ -5772,6 +5780,15 @@ "status": "prototype", "title": "Start Step", "type": "integer" + }, + "step_ema": { + "default": 0.0, + "description": "Per-planned-round exponential smoothing factor over counter increments on rank 0; 0 disables EMA and plans directly on the decayed counters.", + "exclusiveMaximum": 1.0, + "minimum": 0.0, + "status": "prototype", + "title": "Step Ema", + "type": "number" } }, "required": [ diff --git a/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json b/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json index a1f5e8b21a92..428f774faf32 100644 --- a/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json +++ b/tensorrt_llm/schemas/trtllm-serve-disagg-config.schema.json @@ -7864,6 +7864,14 @@ "title": "Decay", "type": "number" }, + "drift_alpha": { + "default": 0.0, + "description": "First-order extrapolation gain applied on rounds 2+ to each layer's round-to-round normalized routing distribution delta; 0 disables extrapolation.", + "minimum": 0.0, + "status": "prototype", + "title": "Drift Alpha", + "type": "number" + }, "interval_steps": { "description": "A placement round every this many steps after start_step.", "minimum": 1, @@ -7937,6 +7945,15 @@ "status": "prototype", "title": "Start Step", "type": "integer" + }, + "step_ema": { + "default": 0.0, + "description": "Per-planned-round exponential smoothing factor over counter increments on rank 0; 0 disables EMA and plans directly on the decayed counters.", + "exclusiveMaximum": 1.0, + "minimum": 0.0, + "status": "prototype", + "title": "Step Ema", + "type": "number" } }, "required": [ diff --git a/tensorrt_llm/usage/llm_args_golden_manifest.json b/tensorrt_llm/usage/llm_args_golden_manifest.json index 4e6b673e5196..e77bc29e920e 100644 --- a/tensorrt_llm/usage/llm_args_golden_manifest.json +++ b/tensorrt_llm/usage/llm_args_golden_manifest.json @@ -1344,6 +1344,11 @@ "kind": "value", "path": "moe_config.load_balancer.warmup_placement.decay" }, + { + "capture_policy": "float", + "kind": "value", + "path": "moe_config.load_balancer.warmup_placement.drift_alpha" + }, { "capture_policy": "int", "kind": "value", @@ -1393,6 +1398,11 @@ "kind": "value", "path": "moe_config.load_balancer.warmup_placement.start_step" }, + { + "capture_policy": "float", + "kind": "value", + "path": "moe_config.load_balancer.warmup_placement.step_ema" + }, { "capture_policy": "int|none", "kind": "value", diff --git a/tests/unittest/_torch/moe/test_moe_warmup_placement.py b/tests/unittest/_torch/moe/test_moe_warmup_placement.py index ac2a7bbc14f8..f19ab8e6f232 100644 --- a/tests/unittest/_torch/moe/test_moe_warmup_placement.py +++ b/tests/unittest/_torch/moe/test_moe_warmup_placement.py @@ -277,8 +277,12 @@ def _run_placement(gens: int, draft_len: int) -> None: decay=0.5, max_moved_fraction=0.1, min_gain=0.0, + step_ema=0.0 if gens == 25 else 0.5, + drift_alpha=0.0 if gens == 25 else 0.4, + ) + drift_cfg = mwp.OnlineDriftConfig( + step_ema=settings.step_ema, drift_alpha=settings.drift_alpha ) - drift_cfg = None if gens == 25 else mwp.OnlineDriftConfig(step_ema=0.5, drift_alpha=0.4) layers, balancer, controller = _build( weights, bias, @@ -395,7 +399,10 @@ def _check_controller_lifecycle_contracts(moe: MoE) -> None: device = torch.device("cuda", rank) def make_ctrl( - settings: MoeWarmupPlacementConfig, drift_cfg: mwp.OnlineDriftConfig + settings: MoeWarmupPlacementConfig, + drift_cfg: mwp.OnlineDriftConfig, + *, + movable: bool = False, ) -> mwp.WarmupPlacementController: ctrl = mwp.WarmupPlacementController( settings, ep_rank=rank, ep_size=world, drift_config=drift_cfg @@ -415,24 +422,32 @@ def make_ctrl( moe=weakref.ref(moe), balancer=moe.layer_load_balancer, assign=list(range(num_experts)), - movable=False, + movable=movable, ) ] return ctrl # 1. Production _decay_counters keeps exact retained fresh-row baseline and EMA increment sync - # even when every rank's local counter floors to 0 (both EMA enabled and disabled), without - # compounding step_ema with decay. - for step_ema in (0.0, 0.5): + # even when every rank's local counter floors to 0 (both EMA/drift disabled and enabled), + # without compounding step_ema with decay; movable=True with min_gain=1e9 exercises _round's + # rank-0 layer_load + predict_drifted_load path without mutating weights. + for step_ema, drift_alpha in ((0.0, 0.0), (0.5, 0.4)): s_dec = MoeWarmupPlacementConfig( start_step=0, interval_steps=1, max_migrations=4, min_rows=1, decay=0.5, + min_gain=1e9, min_round_gain=1e9, + step_ema=step_ema, + drift_alpha=drift_alpha, + ) + ctrl = make_ctrl( + s_dec, + mwp.OnlineDriftConfig(step_ema=step_ema, drift_alpha=drift_alpha), + movable=True, ) - ctrl = make_ctrl(s_dec, mwp.OnlineDriftConfig(step_ema=step_ema, drift_alpha=0.0)) ctrl.on_step(0) ctrl._hist[0, 0] = 1 # 1 pick per rank -> 4 global; each rank floors to 0 at decay=0.5 ctrl.on_step(1) # skipped by min_round_gain=1e9, runs _decay_counters @@ -441,9 +456,10 @@ def make_ctrl( if ctrl._rows_at_last_round == 0 else f"ema={step_ema}: rows_at_last_round={ctrl._rows_at_last_round} != 0" ) - # One fresh row on rank 0 must register as fresh=1 and deliver the full +1 delta to EMA. + # One fresh row on rank 0 (expert 1) must register as fresh=1, deliver the full +1 delta + # to EMA, and produce a non-trivial prev_prob update for drift extrapolation. if rank == 0: - ctrl._hist[0, 0] = 1 + ctrl._hist[0, 1] = 1 ctrl.settings = s_dec.model_copy(update={"min_round_gain": 0.0}) ctrl.on_step(2) _assert_on_all_ranks( @@ -453,14 +469,27 @@ def make_ctrl( ) ema_problem = None if step_ema > 0.0 and rank == 0: - # Round 1 observed 4 -> committed EMA=4.0, post-decay baseline=0; - # round 2 observes +1 -> 0.5 * 4.0 + 1.0 = 3.0 (no decay compounding). - expected_ema = 0.5 * float(world) + 1.0 + # Round 1 observed [4, 0, ...] -> committed EMA=[4.0, 0.0, ...], post-decay baseline=0; + # round 2 observes [0, 1, ...] -> EMA=[2.0, 1.0, ...] (no decay compounding) and + # prev_prob=[2/3, 1/3, ...]. + expected_e0 = 0.5 * float(world) + expected_e1 = 1.0 + expected_p1 = expected_e1 / (expected_e0 + expected_e1) ema = ctrl._tracker._ema + prev_p = ctrl._tracker._prev_prob.get(0) if ema is None: ema_problem = "tracker has no EMA after two rounds" - elif not math.isclose(float(ema[0, 0]), expected_ema, rel_tol=0.0, abs_tol=1e-9): - ema_problem = f"ema={float(ema[0, 0])} != {expected_ema}" + elif not math.isclose( + float(ema[0, 0]), expected_e0, rel_tol=0.0, abs_tol=1e-9 + ) or not math.isclose(float(ema[0, 1]), expected_e1, rel_tol=0.0, abs_tol=1e-9): + ema_problem = f"ema=({float(ema[0, 0])}, {float(ema[0, 1])}) != ({expected_e0}, {expected_e1})" + elif drift_alpha > 0.0 and ( + prev_p is None + or not math.isclose(float(prev_p[1]), expected_p1, rel_tol=0.0, abs_tol=1e-9) + ): + ema_problem = ( + f"prev_prob[1]={None if prev_p is None else float(prev_p[1])} != {expected_p1}" + ) _assert_on_all_ranks(ema_problem) # 2. Alternating workload under count_every_steps=2 must not trigger false readaptation; @@ -703,7 +732,7 @@ def run_sequence( return assign, rep_assign, loads_seen default_cfg = mwp.OnlineDriftConfig() - assert not default_cfg.uses_ema and default_cfg.uses_drift + assert not default_cfg.uses_ema and not default_cfg.uses_drift # Exact formula check for predict_drifted_load. p_prev = np.array([0.8, 0.2], dtype=np.float64) @@ -712,12 +741,35 @@ def run_sequence( np.testing.assert_allclose(pred, np.array([20.0, 80.0])) # Drift extrapolation alone (step_ema=0) improves out-of-sample tail excess over static counts. - drift_a, rep_a, loads_a = run_sequence(default_cfg, decay=0.5) - static_a, _, _ = run_sequence(mwp.OnlineDriftConfig(step_ema=0.0, drift_alpha=0.0), decay=0.5) + drift_a, rep_a, loads_a = run_sequence( + mwp.OnlineDriftConfig(step_ema=0.0, drift_alpha=0.4), decay=0.5 + ) + static_a, _, _ = run_sequence(default_cfg, decay=0.5) assert mwp._excess(next_target, drift_a, spr) < mwp._excess(next_target, static_a, spr) assert mwp.is_replicated_cover(rep_a, num_experts, spr_rep, ep_size) assert len(loads_a) == len(phases) + # _create_warmup_placement forwards step_ema and drift_alpha from MoeWarmupPlacementConfig. + from tensorrt_llm._torch.moe.fused_moe.moe_load_balancer import _create_warmup_placement + + wp_cfg = MoeWarmupPlacementConfig(start_step=0, interval_steps=1, step_ema=0.5, drift_alpha=0.4) + lb_cfg = MoeLoadBalancerConfig(num_slots=num_experts, warmup_placement=wp_cfg) + mock_mc = SimpleNamespace( + moe_load_balancer=lb_cfg, + pretrained_config=SimpleNamespace(num_hidden_layers=4), + ) + wired = _create_warmup_placement(mock_mc, ep_rank=0, ep_size=ep_size) + assert wired is not None + assert wired.drift_config.step_ema == 0.5 + assert wired.drift_config.drift_alpha == 0.4 + for bad_wp in ( + {"step_ema": float("nan")}, + {"drift_alpha": float("inf")}, + {"drift_alpha": float("nan")}, + ): + with pytest.raises(ValueError): + MoeWarmupPlacementConfig(start_step=0, interval_steps=1, **bad_wp) + # Regression (B1): lpt replicated planning must not mutate tracker._ema through a view. ema_tracker = mwp._OnlineLoadTracker(mwp.OnlineDriftConfig(step_ema=0.5, drift_alpha=0.4)) skew = np.array([[100] + [10] * 7], dtype=np.int64) diff --git a/tests/unittest/llmapi/test_trtllm_serve_config_schemas.py b/tests/unittest/llmapi/test_trtllm_serve_config_schemas.py index 03ce8525e7bc..904272f767f8 100644 --- a/tests/unittest/llmapi/test_trtllm_serve_config_schemas.py +++ b/tests/unittest/llmapi/test_trtllm_serve_config_schemas.py @@ -1044,6 +1044,8 @@ def test_dspark_device_reranking_field( "decay": 0.5, "min_round_gain": 0.5, "count_every_steps": 4, + "step_ema": 0.5, + "drift_alpha": 0.4, }, }, True, @@ -1051,6 +1053,9 @@ def test_dspark_device_reranking_field( ({"num_slots": 288, "warmup_placement": {"interval_steps": 4000}}, False), ({"num_slots": 288, "warmup_placement": {**_WARMUP_PLACEMENT, "interval_steps": 0}}, False), ({"num_slots": 288, "warmup_placement": {**_WARMUP_PLACEMENT, "decay": 0}}, False), + ({"num_slots": 288, "warmup_placement": {**_WARMUP_PLACEMENT, "step_ema": 1.0}}, False), + ({"num_slots": 288, "warmup_placement": {**_WARMUP_PLACEMENT, "step_ema": -0.1}}, False), + ({"num_slots": 288, "warmup_placement": {**_WARMUP_PLACEMENT, "drift_alpha": -0.1}}, False), ( { "num_slots": 288,