trl icon indicating copy to clipboard operation
trl copied to clipboard

SFTTrainer: Logging Experts Statistics

Open shon-otmazgin opened this issue 1 year ago • 9 comments

Feature request

Hello,

When fine-tuning MoE models and setting output_router_logits=True, I’ve found it useful to report per-expert token throughput statistics. This information is extremely valuable for identifying which expert layers are most active and therefore the best candidates for adding LoRA adapters later on. I implemented this functionality myself, and although it isn’t fully optimized, it has worked well for my use case.

class SFTTrainerWithExpertsLogging(SFTTrainer):
    def compute_loss(
            self,
            model: nn.Module,
            inputs: dict[str, torch.Tensor | Any],
            return_outputs: bool = False,
            num_items_in_batch: torch.Tensor | None = None,
    ):
        (loss, outputs) = super().compute_loss(
            model, inputs, return_outputs=True, num_items_in_batch=num_items_in_batch
        )

        mode = "train" if self.model.training else "eval"

        # Compute expert usage statistics
        if hasattr(outputs, "router_logits") and outputs.router_logits is not None:
            labels = inputs.get("labels")
            mask = labels != -100 if labels is not None else None

            with torch.no_grad():
                for layer_idx, router_logit in enumerate(outputs.router_logits):
                    expert_indices = router_logit.argmax(dim=-1)
                    expert_indices = expert_indices.flatten()[mask.flatten()]
                    num_experts = router_logit.shape[-1]

                    # Count tokens per expert locally
                    expert_counts = torch.bincount(expert_indices, minlength=num_experts)[:num_experts]

                    # Sum across all processes
                    if self.accelerator.use_distributed:
                        torch.distributed.all_reduce(expert_counts, op=torch.distributed.ReduceOp.SUM)

                    # Normalize
                    expert_percentages = expert_counts / num_items_in_batch
                    for expert_idx in range(num_experts):
                        metric_key = f"expert_usage_layer_{layer_idx}_expert_{expert_idx}"
                        self._metrics[mode][metric_key].append(expert_percentages[expert_idx].item())

                if hasattr(outputs, "aux_loss") and outputs.aux_loss is not None:
                    aux_loss = self.accelerator.gather_for_metrics(outputs.aux_loss).mean().item()
                    self._metrics[mode]["aux_loss"].append(aux_loss)

        return (loss, outputs) if return_outputs else loss

Motivation

When fine-tuning MoE models, it’s often inefficient to attach LoRA adapters to every expert layer. By collecting statistics on which experts are actually being activated, we can make much better use of PEFT methods and selectively target only the most impactful experts.

Your contribution

see code above.

shon-otmazgin avatar Dec 02 '25 20:12 shon-otmazgin

Thanks for the feature request. This looks good to me. Feel free to open a PR 👍

qgallouedec avatar Dec 03 '25 01:12 qgallouedec

Cool. I am thinking also adding not only stats but also which topk tokens routed, but I wonder how to do it and visualize it.

shon-otmazgin avatar Dec 03 '25 12:12 shon-otmazgin

Good question @shon-otmazgin , I’ve been thinking about this a bit. For top-k token routing, it probably makes more sense to treat it as diagnostic information rather than a first-class metric. Since the router already exposes router_logits, we can derive top-k expert usage without additional forward passes. Logging raw token IDs or strings per expert can get noisy and expensive though, especially in distributed setups, so a reasonable middle ground would be to aggregate things like top-k expert frequencies per layer and optionally token counts behind a flag. From an implementation standpoint, I’d keep this opt-in (e.g. log_expert_usage=True), compute it only during eval, use accelerator.gather_for_metrics for aggregation, and log summary statistics rather than full token lists. If that sounds reasonable, I’m happy to put together a lightweight PR that adds this without impacting training performance.

Saad-Mallebhari avatar Jan 25 '26 12:01 Saad-Mallebhari

Thanks for the discussion, this makes sense.

I’ve started working on a PR that adds opt-in expert usage logging in SFTTrainer, scoped to eval-only and using aggregated statistics derived from router_logits, in line with the points raised above. I’ll keep it lightweight and avoid impacting the training path.

I’ll share a PR shortly for review.

CodersAcademy006 avatar Jan 25 '26 13:01 CodersAcademy006

Hey @shon-otmazgin, thanks for the detailed writeup, and sorry this has been sitting a while.

We're keen on this: MoE support is an area we're actively building out, and per-expert usage stats are a genuinely useful diagnostic for LoRA targeting. SFT already requests output_router_logits and logs the load-balancing aux_loss for MoE models, see https://github.com/huggingface/trl/blob/1925183c91852c30088ed8ad53181e7b7147489e/trl/trainer/sft_trainer.py#L1719-L1722 and https://github.com/huggingface/trl/blob/1925183c91852c30088ed8ad53181e7b7147489e/trl/trainer/sft_trainer.py#L1834-L1837 so expert-usage logging slots right next to that. The one thing to nail before a PR is metric cardinality: one expert_usage_layer_{i}_expert_{j} key per (layer, expert) explodes fast, a 48-layer / 128-expert model like Qwen3-30B-A3B would emit ~6k series every step.

cc @AmineDiro if you want to take a look at this one (low priority)

qgallouedec avatar Jul 13 '26 16:07 qgallouedec

Hi @shon-otmazgin, thanks for opening this issue and sharing the concrete implementation.

I ran into the same need while using SFTTrainer with MoE models. Evaluation loss alone did not show whether routing traffic was becoming concentrated on a small subset of experts, so I checked whether TRL already exposed this information and found this issue.

Your example makes the targeted-LoRA use case clear. I explored a related implementation with additional handling for Top-K routing, padding, distributed evaluation, and bounded-cardinality logging. I also built and tested a prototype against TRL commit 9d706a14.

Before going further, are you currently preparing an upstream PR for this, @shon-otmazgin? If so, I would be happy to coordinate and contribute the Top-K, distributed, and regression-test parts to your implementation.

Proposed behavior

The prototype adds an opt-in SFTConfig.log_expert_usage flag, disabled by default, and collects expert-usage statistics during evaluation.

The changes are limited to:

  • trl/trainer/sft_config.py: configuration and compatibility checks.
  • trl/trainer/sft_trainer.py: router-logit collection, local counting, distributed reduction, and logging.
  • tests/test_sft_expert_usage.py: focused tests for counting semantics and compatibility.

The main implementation choices are:

  • Request output_router_logits=True for this feature only during evaluation and only when enabled.
  • Count every Top-K expert assignment. Using argmax records only one expert when a token is dispatched to multiple experts.
  • Apply attention_mask before counting so padding positions are excluded.
  • Accumulate a compact int64 [num_layers, num_experts] count matrix locally.
  • Reduce that matrix with accelerator.reduce(..., reduction="sum"); full router logits are never gathered across ranks.
  • Normalize each layer using its total number of assignments, so the expert shares within that layer sum to one.
  • Support both the regular nll path and chunked_nll.

The core counting path is approximately:

layer_counts = []
for layer_router_logits in router_logits:
    num_experts = layer_router_logits.shape[-1]
    flat_logits = layer_router_logits.reshape(-1, num_experts)

    if attention_mask is not None:
        valid = attention_mask.reshape(-1).bool().to(flat_logits.device)
        flat_logits = flat_logits[valid]

    selected = flat_logits.topk(num_experts_per_tok, dim=-1).indices
    layer_counts.append(torch.bincount(selected.reshape(-1), minlength=num_experts))

counts = torch.stack(layer_counts)
counts = self.accelerator.reduce(counts, reduction="sum")

The prototype currently logs five bounded-cardinality summaries:

  • expert_usage/normalized_entropy_mean
  • expert_usage/normalized_entropy_min
  • expert_usage/max_share_mean
  • expert_usage/max_share_max
  • expert_usage/active_fraction_mean

The full layer-by-expert matrix is still useful for the targeted-LoRA use case. I left its public representation open because emitting a scalar key for every layer and expert can create a very large logging namespace. Possible interfaces include per-expert scalar metrics, Top-N experts, or a JSON/NumPy artifact alongside the summary metrics.

Validation

I tested the prototype with Python 3.12.11, PyTorch 2.8.0+cu128, Transformers 5.13.1, Accelerate 1.14.0, BF16, and two GPUs.

Check Result
Focused expert-usage tests 5 passed
Existing targeted GPU regression tests 2 passed
Ruff Passed
Qwen3-MoE, single GPU nll = chunked_nll = 11.932475090026855
GptOss, single GPU nll = chunked_nll = 12.207236289978027
Feature disabled No expert-usage metrics; eval-loss delta 0
Qwen3-MoE, two-process NCCL nll = chunked_nll = 11.932504653930664
Single/distributed summaries All five metric deltas were 0
Single/distributed eval loss Absolute delta 2.9564e-05, within rtol=1e-5, atol=1e-5

Compatibility boundaries

The feature remains disabled by default because returning router logits may increase evaluation memory and runtime.

The current prototype:

  • Requires the model to expose router_logits and num_experts_per_tok.
  • Explicitly rejects Liger because that path does not expose the required standard model outputs.
  • Has been exercised with Qwen3-MoE and GptOss output structures.
  • Still needs coverage for padding-free evaluation and distributed-sampler tail duplication when the dataset size is not divisible by world_size.

I used attention_mask because it measures actual non-padding router traffic, including prompt and context tokens. A labels != -100 mask would measure expert usage over loss-bearing tokens only. Both semantics are potentially useful, so this may need an explicit API decision.

Prototype patch

Prototype patch:

0001-sfttrainer-log-moe-expert-usage.patch

Patch scope: 3 files changed, 214 insertions(+), 3 deletions(-)

SHA256: 84a9d0bb61a8dd801bd9740eef10d2be6fc884ccbffac90bb564c88b216740a0

@qgallouedec @albertvillanova, could you advise whether this opt-in evaluation path fits the intended SFTTrainer API, particularly:

  1. Should expert usage cover all non-padding tokens or only loss-bearing tokens?
  2. Should the full layer-by-expert matrix use scalar metrics, a Top-N representation, or a separate artifact?

If this direction looks reasonable and @shon-otmazgin is not already preparing a PR, I can clean up the prototype, add the remaining boundary tests, and open a PR. If work is already underway, I would be glad to contribute these parts to it.

kaining-never-stop avatar Jul 16 '26 04:07 kaining-never-stop

Hi @qgallouedec and @AmineDiro, I have opened #6514 and marked it ready for review after completing the final validation on commit 82aa1441.

The PR keeps the output bounded to five summary metrics. For distributed evaluation, it retains counts per sample until Accelerator.gather_for_metrics() removes duplicated sampler-tail entries, then sums them into the layer-by-expert count matrix.

The final validation covered:

  • 10 passed focused and validator tests, plus Ruff;
  • tiny Qwen3-MoE and GptOss on BF16 GPU for both nll and chunked_nll;
  • a two-process NCCL Qwen3-MoE run;
  • a non-divisible tail case with five samples and a global batch size of four, where the observed IDs were exactly [0, 1, 2, 3, 4];
  • zero single-process versus distributed deltas for all five expert-usage summaries on both loss paths.

The full validation details and the remaining API choices are documented in the PR description. Thank you for taking a look when time permits.

kaining-never-stop avatar Jul 27 '26 07:07 kaining-never-stop

Hey @kaining-never-stop, thanks for the thorough prototype and for getting it to #6514; answering your two API questions so you're unblocked.

  1. Use attention_mask, not labels != -100. SFT already computes the load-balancing aux loss over all non-padding tokens https://github.com/huggingface/trl/blob/c061050d3c4eb62dda345adf6f1a4e892619adec/trl/trainer/sft_trainer.py#L357-L358 so counting the same token set keeps expert usage and the aux_loss we already log directly comparable. One semantics is enough here -> no extra flag.

  2. Keep the five bounded summaries only. A scalar key per (layer, expert) is ~6k series per step on something like Qwen3-30B-A3B, which is more than the logging backends should carry by default. If the full matrix turns out to be necessary for the targeted-LoRA workflow @shon-otmazgin described, let's do it as a separate artifact-based follow-up rather than widening log_expert_usage.

One thing worth calling out in the config docstring: scoping to eval-only answers "which experts are hot on my eval set", which is a narrower claim than the training-time stats in the original request. That's fine for LoRA targeting, but it should be explicit. I'll do a proper pass on the PR.

qgallouedec avatar Aug 03 '26 16:08 qgallouedec

Thanks @qgallouedec, that settles both API questions.

I kept the attention_mask semantics and the five bounded summaries unchanged, and updated the SFTConfig documentation in a369c417 to state explicitly that these statistics describe routing traffic on the evaluation dataset, not expert usage during training. The focused suite remains at 16 passed, and Ruff is clean.

I will leave the full layer-by-expert matrix for a separate artifact-based follow-up if the targeted-LoRA workflow needs it. Thanks for taking a proper pass on the PR.

kaining-never-stop avatar Aug 03 '26 16:08 kaining-never-stop