-
Notifications
You must be signed in to change notification settings - Fork 29
[feat] Track entropy and MI of routing distribution for topk MoE #188
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
oleksost
wants to merge
18
commits into
main
Choose a base branch
from
routing_stats
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.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
2a7cf1b
added mutual information and entropy for routing probs
oleksost dd85e84
format
oleksost aef18e7
pre-commits
oleksost bef39d8
improved
oleksost 620ec76
using metrics dict instead of losses
oleksost 7a93aee
reduce metrics
oleksost eb617e8
check return_metrics before reducing metrics
oleksost 440738a
check return metrics before reducing
oleksost e5f3c4b
corrwect averaging with number of layers
oleksost 27e2a5c
device
oleksost b016d95
Merge branch 'main' into routing_stats
oleksost 7b9ac8c
polishing
oleksost 0577b2c
simplified: all metrics from forward are reduced
oleksost 9e2ec37
Merge branch 'routing_stats' of https://github.com/ServiceNow/Fast-LLβ¦
oleksost efd16bf
nvm
oleksost 1202f5f
moved runner test to a new file
oleksost 9855b82
parameter for MoE metrics calculation
oleksost 9c47764
Merge branch 'main' into routing_stats
oleksost 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
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
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 |
---|---|---|
|
@@ -17,6 +17,7 @@ | |
TransformerDimNames, | ||
TransformerKwargs, | ||
TransformerLossNames, | ||
TransformerRoutingMetrics, | ||
) | ||
from fast_llm.layers.transformer.mlp import MLPBase | ||
from fast_llm.logging import log_distributed_grad, log_distributed_tensor, log_memory_usage | ||
|
@@ -26,6 +27,41 @@ | |
logger = logging.getLogger(__name__) | ||
|
||
|
||
@torch.compile | ||
def calculate_normalized_average_entropy(probs: torch.Tensor) -> torch.Tensor: | ||
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. Could try |
||
""" | ||
Calculates routing entropy for each token, then averages over all tokens. | ||
If low, means a lot of mass is put on a single expert in all tokens, which can indicate collapse or specialization. | ||
""" | ||
n_experts = probs.size(-1) | ||
entropy_values = calculate_entropy(probs) | ||
average_entropy = entropy_values.mean() # Average over batch and tokens | ||
return average_entropy / torch.log(torch.tensor(n_experts, dtype=probs.dtype, device=probs.device)) | ||
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.
|
||
|
||
|
||
@torch.compile | ||
def calculate_entropy(probs: torch.Tensor) -> torch.Tensor: | ||
probs = torch.clamp(probs, min=1e-9) # Avoid log(0) | ||
return -torch.sum(probs * torch.log(probs), dim=-1) | ||
|
||
|
||
@torch.compile | ||
def calculate_mutual_information(probs: torch.Tensor) -> torch.Tensor: | ||
""" | ||
Calculates the difference between the entropy of the average routing and | ||
the average routing entropy, we average across all tokens of all examples in the batch. | ||
If low, means that routing is not informative. | ||
""" | ||
n_experts = probs.size(-1) | ||
average_routing = torch.mean(probs.view(-1, n_experts), dim=0) # Average over tokens | ||
entropy_avg_routing = calculate_entropy(average_routing) / torch.log( | ||
torch.tensor(n_experts, dtype=probs.dtype) | ||
) # H[E[X]] | ||
entropy_routing = calculate_normalized_average_entropy(probs) # E[H[X]] | ||
|
||
return entropy_avg_routing - entropy_routing | ||
|
||
|
||
class MixtureOfExpertMLP(MLPBase): | ||
""" | ||
MoeLayer following implementation from | ||
|
@@ -48,6 +84,7 @@ def __init__(self, config: TransformerConfig, tensor_space: TensorSpace, name: s | |
self._config = config | ||
self._tensor_space = tensor_space | ||
self._debug_mode = self._config.debug_transformer or self._config.debug_transformer_memory | ||
self._calculate_moe_metrics = config.calculate_moe_metrics | ||
|
||
self._num_experts = config.num_experts | ||
self._experts_per_token = config.num_experts_per_token | ||
|
@@ -103,7 +140,9 @@ def forward( | |
|
||
# Routing | ||
if self._routing_type == RoutingType.topk: | ||
scores, top_experts = self._topk_routing(logits, kwargs.get(TransformerKwargs.grad_output), losses) | ||
scores, top_experts = self._topk_routing( | ||
logits, kwargs.get(TransformerKwargs.grad_output), losses, metrics | ||
) | ||
if self._num_shared_experts > 0: | ||
scores, top_experts = self._add_shared_experts(top_experts, scores) | ||
elif self._routing_type == RoutingType.sinkhorn: | ||
|
@@ -169,11 +208,26 @@ def _topk_routing( | |
logits: torch.Tensor, | ||
grad_scale: float | None = None, | ||
losses: dict | None = None, | ||
metrics: dict | None = None, | ||
) -> tuple[torch.Tensor, torch.Tensor]: | ||
top_logits, top_experts = torch.topk(logits, k=self._experts_per_token, dim=-1) | ||
scores = torch.softmax(top_logits, dim=-1, dtype=torch.float32) | ||
if losses is not None or (self.training and grad_scale is not None): | ||
probs = torch.softmax(logits, dim=-1, dtype=torch.float32) | ||
|
||
# Store these metrics | ||
if metrics is not None and self._calculate_moe_metrics: | ||
# Calculate and log entropy and mutual information | ||
entropy = calculate_normalized_average_entropy(probs) | ||
mutual_info = calculate_mutual_information(probs) | ||
if TransformerRoutingMetrics.normalized_average_entropy not in metrics: | ||
metrics[TransformerRoutingMetrics.normalized_average_entropy] = [] | ||
if TransformerRoutingMetrics.mutual_info not in metrics: | ||
metrics[TransformerRoutingMetrics.mutual_info] = [] | ||
|
||
metrics[TransformerRoutingMetrics.normalized_average_entropy].append(entropy.detach()) | ||
metrics[TransformerRoutingMetrics.mutual_info].append(mutual_info.detach()) | ||
|
||
mask = torch.nn.functional.one_hot(top_experts, num_classes=self._num_unshared_experts).sum(dim=1) | ||
# Auxiliary loss, corresponding to the sum of probabilities for the top experts. | ||
# In the optimal case (uniform distribution), loss = experts_per_token / num_experts. | ||
|
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This loss/metric split is way more complicated than needed. How about having a single entry, and using a
is_metric
flag inLossDef
(or a derived class) to distinguish? Then no change is needed other than extracting metrics from the context before returning fromrun_step
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This would be nice!
Maybe better to leave it for a separate pr? It would make this one larger as it would require also changing the interfaces of the models' forward functions (that expect losses and metrics) as well as making sure that metrics are only calculated when
return_metrics
is True.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There isn't much change needed actually, just need to add
kwargs["return_metrics"]
. I would prefer doing this here so we don't growScheduleRunner
too much.