microsoft/qlib · error · ValueError
unknown metric `%s`
Error message
unknown metric `%s`
What it means
Thrown by TransformerTSModel.metric_fn, the per-epoch scoring function used for early stopping and best-model selection. Only '' and 'loss' (negated training loss) are implemented; any other `metric` string raises during the first validation pass.
Source
Thrown at qlib/contrib/model/pytorch_transformer_ts.py:100
def mse(self, pred, label):
loss = (pred.float() - label.float()) ** 2
return torch.mean(loss)
def loss_fn(self, pred, label):
mask = ~torch.isnan(label)
if self.loss == "mse":
return self.mse(pred[mask], label[mask])
raise ValueError("unknown loss `%s`" % self.loss)
def metric_fn(self, pred, label):
mask = torch.isfinite(label)
if self.metric in ("", "loss"):
return -self.loss_fn(pred[mask], label[mask])
raise ValueError("unknown metric `%s`" % self.metric)
def train_epoch(self, data_loader):
self.model.train()
for data in data_loader:
feature = data[:, :, 0:-1].to(self.device)
label = data[:, -1, -1].to(self.device)
pred = self.model(feature.float()) # .float()
loss = self.loss_fn(pred, label)
self.train_optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_value_(self.model.parameters(), 3.0)
self.train_optimizer.step()
def test_epoch(self, data_loader):
self.model.eval()
View on GitHub (pinned to 79633dd950)
Solutions
- Set metric='loss' or '' exactly (no extra whitespace) in the TransformerTSModel constructor.
- Use per-model config dicts so metric names valid in other models don't leak into this one.
- Subclass and override metric_fn for a custom early-stopping metric like IC.
Example fix
# before model = TransformerTSModel(..., metric="ic") # after model = TransformerTSModel(..., metric="loss")
Defensive patterns
Strategy: validation
Validate before calling
metric = model_kwargs.get("metric", "")
assert metric in ("", "loss"), f"TransformerTSModel metric must be '' or 'loss', got {metric!r}" Try / catch
try:
model.fit(ds, valid)
except ValueError as e:
if "unknown metric" in str(e):
model_kwargs["metric"] = "loss"
model = TransformerTSModel(**model_kwargs)
model.fit(ds, valid)
else:
raise Prevention
- Strip/normalize metric strings from configs to avoid whitespace/case mismatches.
- Use metric='loss' uniformly for loss-based early stopping across these models.
When it happens
Trigger: TransformerTSModel(..., metric='ic'|'loss '|any non-empty value other than 'loss') then fit(); metric_fn hits the raise.
Common situations: Configs copied from IC-based workflows; trailing whitespace in the metric string (e.g. 'loss ') which fails the equality; shared hyperparameter dicts across heterogeneous models.
Related errors
- unknown metric `%s`
- model is not fitted yet!
- model is not fitted yet!
- unknown metric `%s`
- unknown metric `%s`
AI-assisted analysis of microsoft/qlib@79633dd950 (2026-08-15).
Data as JSON: /api/errors/a124182c512145e5.
Report an issue: GitHub.