Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions hyper_parallel/trainer/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -749,9 +749,13 @@ def postforward(
Backward loss and named globally aggregated loss values.
"""
local_loss = self.loss_fn(model_output=outputs, labels=labels)
foundation_loss = local_loss.get("foundation_loss") if isinstance(local_loss, dict) else local_loss
if foundation_loss is not None:
bind_aux_loss_scale(foundation_loss)
foundation_losses = (
(value for key, value in local_loss.items() if key.split("_loss", maxsplit=1)[0] == "foundation")
if isinstance(local_loss, dict) else (local_loss,)
)
for foundation_loss in foundation_losses:
if foundation_loss is not None:
bind_aux_loss_scale(foundation_loss)
if self.loss_normalizer is None:
loss_dict: Dict[str, torch.Tensor] = mean_global_loss(
local_loss,
Expand Down
4 changes: 2 additions & 2 deletions hyper_parallel/trainer/config/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,15 +111,15 @@ def __post_init__(self) -> None:

def _validate_loss_normalization(self) -> None:
"""Reject unsupported objectives before building the model or Trainer."""
if self.training.loss_normalization == "legacy":
if self.training.loss_normalization != "microbatch":
return
for path, options in (("model", self.model), ("model.config", getattr(self.model, "config", None))):
for name in ("mtp_num_layers", "moe_aux_loss_coeff", "router_aux_loss_coef", "router_aux_loss_coeff"):
value = options.get(name) if isinstance(options, Mapping) else getattr(options, name, None)
if value is not None and value > 0:
raise ValueError(
f"training.loss_normalization={self.training.loss_normalization!r} only supports main LM loss; "
f"{path}.{name}={value} enables MTP or auxiliary loss. Disable it or use 'legacy'."
f"{path}.{name}={value} enables MTP or auxiliary loss. Use 'legacy' or 'token'."
)

def to_dict(self) -> dict[str, Any]:
Expand Down
28 changes: 19 additions & 9 deletions hyper_parallel/trainer/runtime/loss_normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,19 @@ class StepLossNormalization:
"""Normalize local mean losses without retaining micro-batch inputs.

Counts describe CP-local targets and are replicated across TP ranks, as in
TextParallelBatch. Both modes accept only the main LM loss, as a scalar or
``foundation_loss``. Models must not fold MTP or auxiliary objectives into
that scalar; their independent normalization is not supported.
TextParallelBatch. Token mode accepts losses sharing one token-count family
and external weight, including separately averaged LM/MTP branches. Injected
auxiliary losses must follow the public auxiliary-loss scaling context.
Microbatch mode accepts only the main LM loss; it does not normalize MTP or
auxiliary objectives.
"""

def __init__(self, mode: str, micro_steps: int, mesh: MeshContext) -> None:
"""Create fresh scalar accounting for one optimizer step."""
if mode not in ("microbatch", "token"):
raise ValueError("loss_normalization must be 'microbatch' or 'token'")
if mesh.sequence_parallel:
raise ValueError("microbatch/token normalization requires TP-replicated token counts")
self.mode = mode
self.micro_steps = micro_steps
self.mesh = mesh
Expand All @@ -57,19 +61,25 @@ def reduce(
"""Return global reporting values with locally weighted backward edges.

Args:
losses: CP-local main LM mean, optionally keyed by ``foundation_loss``.
losses: Mean objectives with the same external token weight in token mode.
counts: Effective local target counts keyed by ``<family>_tokens``.
"""
if isinstance(losses, torch.Tensor):
losses = {"foundation_loss": losses}
if set(losses) != {"foundation_loss"}:
if self.mode == "microbatch" and set(losses) != {"foundation_loss"}:
raise ValueError(
"microbatch/token normalization supports only foundation_loss (main LM loss); "
"MTP and auxiliary losses are not supported. Use legacy for existing model-specific objectives."
"microbatch normalization supports only foundation_loss (main LM loss); "
"use legacy or token for MTP and auxiliary objectives."
)
if self.mode == "token":
loss_device = losses["foundation_loss"].device
count = counts["foundation_tokens"].detach().to(loss_device)
families = {key.split("_loss", maxsplit=1)[0] for key in losses}
if len(families) != 1:
raise ValueError("Token normalization requires losses sharing one token-count family")
if self.loss_names and self.loss_names != set(losses):
raise ValueError("Token normalization requires the same loss keys throughout an optimizer step")
family = next(iter(families))
loss_device = next(iter(losses.values())).device
count = counts[f"{family}_tokens"].detach().to(loss_device)
self.token_count = count if self.token_count is None else self.token_count + count
self.loss_names.update(losses)

Expand Down