Skip to content
Open
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
9 changes: 7 additions & 2 deletions modelopt/torch/distill/loss_balancers.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,13 @@ def __init__(self, kd_loss_weight: float | list[float] = 0.5):
ValueError if kd_loss_weight is out of bounds.
"""
super().__init__()
if isinstance(kd_loss_weight, float):
kd_loss_weight = [kd_loss_weight]
if isinstance(kd_loss_weight, (int, float)):
kd_loss_weight = [float(kd_loss_weight)]

if any(w < 0.0 for w in kd_loss_weight):
raise ValueError(
f"Individual kd_loss_weight values must be non-negative, got {kd_loss_weight}"
)

sum_kd_loss_weight = sum(kd_loss_weight)
if sum_kd_loss_weight < 0.0 or sum_kd_loss_weight > 1.0:
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/torch/distill/test_loss_balancers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""Test distillation loss balancers."""
# pyrefly: ignore [missing-import]
import pytest
from modelopt.torch.distill.loss_balancers import StaticLossBalancer

@pytest.mark.parametrize(
("weight", "expected"),
[(1, [1.0]), (0.5, [0.5])],
)
def test_static_loss_balancer_weight_validation(weight, expected):
"""Test that StaticLossBalancer correctly validates scalar and negative weights."""
# 1. Verify scalar weights are accepted (and cast to list of float)
balancer = StaticLossBalancer(weight)
assert balancer._kd_loss_weight == expected

# 2. Verify negative individual weights are rejected even if sum is valid
with pytest.raises(ValueError, match="non-negative"):
StaticLossBalancer([0.5, -0.3])