-
-
Notifications
You must be signed in to change notification settings - Fork 19.3k
[EPLB] Fix balancedness metric computation and add verbose reporting #39178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
arpera
wants to merge
14
commits into
vllm-project:main
Choose a base branch
from
arpera:artem/fix-eplb-balancedness
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+142
−33
Open
Changes from 3 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
72832b4
[EPLB] Fix balancedness computation: use per-layer mean/max across ranks
arpera 3bd5159
[EPLB] Use float64 for balancedness summation to avoid precision loss
arpera 29c8d66
[EPLB] Fix balancedness metric computation and add verbose reporting
arpera 44a1887
Address review comments on balancedness reporting
arpera 8b54a8d
Merge branch 'main' into artem/fix-eplb-balancedness
arpera 9b1ee18
[EPLB] Add imbalance, global_step, async-overdue, and JSONL dump
arpera 7e83952
[Doc] Document log_balancedness_interval
arpera 030f7f8
Merge branch 'main' into artem/fix-eplb-balancedness
arpera 3468ef0
Merge branch 'main' into artem/fix-eplb-balancedness
arpera fe20aaa
Replace print by logger.info
arpera 25ce08b
Simplify patch; remove verbose logging to stderr with heat-map
arpera c7a9ae3
Merge remote-tracking branch 'origin/main' into artem/fix-eplb-balanc…
arpera af8c63c
Fix mypy issue
arpera 94f56ff
Enable moe_report.py
arpera File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,6 +26,7 @@ | |
| physical experts. | ||
| """ | ||
|
|
||
| import sys | ||
| import threading | ||
| from collections.abc import Sequence | ||
| from dataclasses import dataclass | ||
|
|
@@ -48,6 +49,7 @@ | |
|
|
||
| from .async_worker import start_async_worker | ||
| from .eplb_communicator import EplbCommunicator, create_eplb_communicator | ||
| from .eplb_utils import heat_cell | ||
| from .policy import EPLB_POLICIES, AbstractEplbPolicy, DefaultEplbPolicy | ||
| from .rebalance_execute import ( | ||
| RecvMetadata, | ||
|
|
@@ -516,6 +518,106 @@ def add_model( | |
| self.model_states[model_config.compute_hash()] = model_state | ||
| self.num_valid_physical_experts = model.num_physical_experts | ||
|
|
||
| def _dump( | ||
| self, | ||
| num_tokens_per_rank: torch.Tensor, | ||
| verbose: bool = False, | ||
| ) -> None: | ||
| """Print EPLB balancedness stats to stderr.""" | ||
| layer_means = num_tokens_per_rank.mean(dim=1, dtype=torch.float64) | ||
| layer_maxes = num_tokens_per_rank.max(dim=1).values.to(torch.float64) | ||
| valid_layers = layer_means > 0 | ||
|
|
||
| # Compute balancedness ratio: | ||
| # for each layer: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think the code does ratio of sums not sum of ratios. |
||
| # (max load across ranks) / (mean load across ranks) | ||
|
arpera marked this conversation as resolved.
Outdated
|
||
| # then average over active layers. | ||
| if valid_layers.any(): | ||
| layer_ratios = layer_maxes[valid_layers] / layer_means[valid_layers] | ||
| balancedness = layer_ratios.mean().item() | ||
| else: | ||
| balancedness = 1.0 | ||
| steps_left = ( | ||
| self.expert_rearrangement_step_interval - self.expert_rearrangement_step | ||
| ) | ||
| step = self.expert_rearrangement_step | ||
|
|
||
| if not verbose: | ||
| print( | ||
|
arpera marked this conversation as resolved.
Outdated
|
||
| f"EPLB: step={step}, balancedness={balancedness:.2f}x, " | ||
| f"\nNext rearrangement in {steps_left} steps", | ||
| file=sys.stderr, | ||
| flush=True, | ||
| ) | ||
| return | ||
|
|
||
| # ---- verbose dump ---- | ||
| lines: list[str] = [ | ||
| "=== EPLB dump ===", | ||
| f"step={step}, balancedness={balancedness:.2f}x", | ||
| f"Next rearrangement in {steps_left} steps", | ||
|
arpera marked this conversation as resolved.
Outdated
|
||
| ] | ||
|
|
||
| num_ranks = num_tokens_per_rank.shape[1] | ||
| if num_ranks == 0: | ||
| lines += ["No EP ranks.", "=== end EPLB dump ==="] | ||
| print("\n".join(lines), file=sys.stderr, flush=True) | ||
| return | ||
|
|
||
| # Per-layer / per-rank token table | ||
| table = num_tokens_per_rank.long().cpu() # [n_layers, num_ranks] | ||
| n_layers = table.shape[0] | ||
| total = int(table.sum().item()) | ||
| if total > 0: | ||
| row_sums = table.sum(dim=1) | ||
| col_sums = table.sum(dim=0) | ||
|
|
||
| # Auto-size columns to fit the widest value | ||
| biggest_value = max(int(table.max().item()), int(col_sums.max().item())) | ||
| val_w = max(6, len(str(biggest_value))) | ||
| sum_w = max(6, len(str(total))) | ||
| label_w = len(f"Layer{n_layers - 1}") | ||
|
|
||
| # Header | ||
| lines.append("Tokens per MoE layer and EP rank:") | ||
|
arpera marked this conversation as resolved.
Outdated
|
||
| rank_hdr = " ".join(f"{'rank' + str(r):>{val_w}}" for r in range(num_ranks)) | ||
| lines.append(f"{'':{label_w}} {rank_hdr} {'sum':>{sum_w}} max/mean") | ||
|
|
||
| # One row per MoE layer | ||
| for i in range(n_layers): | ||
| row = table[i] | ||
| row_min = int(row.min().item()) | ||
| row_max = int(row.max().item()) | ||
| row_total = int(row_sums[i].item()) | ||
| row_mean = row_total / num_ranks | ||
| ratio = row_max / row_mean if row_mean > 0 else float("inf") | ||
| vals = [int(row[r].item()) for r in range(num_ranks)] | ||
| cells = " ".join( | ||
| heat_cell(f"{v:>{val_w}}", v, row_min, row_max) for v in vals | ||
| ) | ||
| lines.append( | ||
| f"{'Layer' + str(i):{label_w}} {cells}" | ||
| f" {row_total:>{sum_w}} {ratio:.2f}x" | ||
| ) | ||
|
|
||
| # Totals row | ||
| mean_per_rank = total / num_ranks | ||
| totals_max = int(col_sums.max().item()) | ||
| totals_ratio = ( | ||
| totals_max / mean_per_rank if mean_per_rank > 0 else float("inf") | ||
| ) | ||
| totals_cells = " ".join( | ||
| f"{int(col_sums[r].item()):>{val_w}}" for r in range(num_ranks) | ||
| ) | ||
| sigma = "\u03a3" | ||
| lines.append( | ||
| f"{sigma:{label_w}} {totals_cells}" | ||
| f" {total:>{sum_w}} {totals_ratio:.2f}x" | ||
| ) | ||
|
|
||
| lines.append("=== end EPLB dump ===") | ||
| print("\n".join(lines), file=sys.stderr, flush=True) | ||
|
arpera marked this conversation as resolved.
Outdated
|
||
|
|
||
| def step( | ||
| self, | ||
| is_dummy: bool = False, | ||
|
|
@@ -534,12 +636,6 @@ def step( | |
| `profile_run` to reserve enough memory | ||
| for the communication buffer. | ||
| log_stats (bool): If `True`, log the expert load metrics. | ||
|
|
||
| # Stats | ||
|
arpera marked this conversation as resolved.
|
||
| The metrics are all summed up across layers. | ||
| - `avg_tokens`: The average load across ranks. | ||
| - `max_tokens`: The maximum load across ranks. | ||
| - `balancedness`: The ratio of average load to maximum load. | ||
| """ | ||
| ep_group = get_ep_group().device_group | ||
| if is_profile: | ||
|
|
@@ -573,31 +669,10 @@ def step( | |
| .float() | ||
| ) | ||
|
|
||
| # Compute balancedness ratio: | ||
| # for each layer: | ||
| # (mean load across ranks) / (max load across ranks) | ||
| avg_tokens_tensor = num_tokens_per_rank.mean(dim=0).sum(dim=0) | ||
| max_tokens_tensor = num_tokens_per_rank.max(dim=0).values.sum(dim=0) | ||
|
|
||
| # Just to make type checker happy | ||
| tokens_tensors: list[float] = torch.stack( | ||
| [avg_tokens_tensor, max_tokens_tensor] | ||
| ).tolist() | ||
| avg_tokens, max_tokens = tokens_tensors | ||
| balancedness = avg_tokens / max_tokens if max_tokens > 0 else 0.0 | ||
|
|
||
| if ep_group.rank() == 0: | ||
| logger.info( | ||
| "EPLB step: %d for model %s: avg_tokens=%.2f, " | ||
| "max_tokens=%d, balancedness=%.4f, " | ||
| "steps until the next rearrangement: %d", | ||
| self.expert_rearrangement_step, | ||
| eplb_model_state.model_name, | ||
| avg_tokens, | ||
| max_tokens, | ||
| balancedness, | ||
| self.expert_rearrangement_step_interval | ||
| - self.expert_rearrangement_step, | ||
| self._dump( | ||
| num_tokens_per_rank, | ||
| verbose=self.parallel_config.eplb_config.log_balancedness_verbose, | ||
| ) | ||
|
|
||
| # Update the expert load sliding window | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.