microsoft/qlib · error · ValueError

unknown loss `%s`

Error message

unknown loss `%s`

What it means

The TS LSTM loss_fn() supports only weighted MSE ('mse'): NaN labels are masked, missing weights default to ones, then weighted mean squared error is returned. Any other self.loss value raises ValueError("unknown loss `%s`") during the first training batch. The loss string is unchecked at construction, so the failure is deferred into fit().

Source

Thrown at qlib/contrib/model/pytorch_lstm_ts.py:150

    @property
    def use_gpu(self):
        return self.device != torch.device("cpu")

    def mse(self, pred, label, weight):
        loss = weight * (pred - label) ** 2
        return torch.mean(loss)

    def loss_fn(self, pred, label, weight):
        mask = ~torch.isnan(label)

        if weight is None:
            weight = torch.ones_like(label)

        if self.loss == "mse":
            return self.mse(pred[mask], label[mask], weight[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], weight=None)

        raise ValueError("unknown metric `%s`" % self.metric)

    def train_epoch(self, data_loader):
        self.LSTM_model.train()

        for data, weight in data_loader:
            feature = data[:, :, 0:-1].to(self.device)
            label = data[:, -1, -1].to(self.device)

            pred = self.LSTM_model(feature.float())
            loss = self.loss_fn(pred, label, weight.to(self.device))

View on GitHub (pinned to 79633dd950)

Solutions

  1. Set loss='mse' — the sole supported loss for this model.
  2. Custom loss: subclass and override loss_fn(self, pred, label, weight); handle weight=None by defaulting to torch.ones_like(label) and keep the NaN mask.
  3. Fail fast: assert self.loss == 'mse' in your subclass __init__.

Example fix

# before
model = LSTMModel(..., loss="huber")
model.fit(dataset, reweighter=rw)  # ValueError: unknown loss `huber`

# after
model = LSTMModel(..., loss="mse")
model.fit(dataset, reweighter=rw)
Defensive patterns

Strategy: validation

Validate before calling

assert loss == "mse", "TS LSTM supports only loss='mse' (weighted MSE)"
model = LSTMModel(..., loss=loss)

Type guard

def is_supported_loss(name: str) -> bool:
    return name == "mse"

Try / catch

try:
    model.fit(dataset, reweighter=rw)
except ValueError as e:
    if "unknown loss" in str(e):
        raise ValueError("loss must be 'mse'; reweighter only reweights MSE") from e
    raise

Prevention

When it happens

Trigger: model.fit(dataset) (optionally with reweighter) where loss != 'mse', e.g. 'mae' or 'huber'. The DataLoaders are built first; the raise happens on the first batch of train_epoch.

Common situations: Experimenting with losses for imbalanced financial data; copying configs between model families; pairing a reweighter and assuming it changes the supported loss set (it only reweights MSE).

Related errors


AI-assisted analysis of microsoft/qlib@79633dd950 (2026-08-15). Data as JSON: /api/errors/1fd1e47f670fb7df. Report an issue: GitHub.