microsoft/qlib · error · ValueError

unknown loss `%s`

Error message

unknown loss `%s`

What it means

pytorch_lstm.py's loss_fn() implements only masked MSE: predictions/labels with NaN labels are masked out, then mean squared error is computed. If self.loss != 'mse' it raises ValueError("unknown loss `%s`"). Because __init__ does not validate the loss string, the error appears during the first train_epoch call, after dataset preparation.

Source

Thrown at qlib/contrib/model/pytorch_lstm.py:142

        self.fitted = False
        self.lstm_model.to(self.device)

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

    def mse(self, pred, label):
        loss = (pred - label) ** 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, x_train, y_train):
        x_train_values = x_train.values
        y_train_values = np.squeeze(y_train.values)

        self.lstm_model.train()

        indices = np.arange(len(x_train_values))
        np.random.shuffle(indices)

View on GitHub (pinned to 79633dd950)

Solutions

  1. Set loss='mse' — the only implemented loss for this LSTM model.
  2. Subclass and override loss_fn(pred, label) for custom losses, preserving the NaN mask (~torch.isnan(label)) since qlib labels frequently contain NaNs.
  3. Add an early check of self.loss in your subclass __init__ to fail before expensive data prep.

Example fix

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

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

Strategy: validation

Validate before calling

assert loss == "mse", "pytorch_lstm supports only loss='mse'"
model = LSTMModel(..., loss=loss)

Type guard

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

Try / catch

try:
    model.fit(dataset)
except ValueError as e:
    if "unknown loss" in str(e):
        raise ValueError("loss must be 'mse' for this LSTM model") from e
    raise

Prevention

When it happens

Trigger: model.fit(...) with loss='mae', 'huber', 'smooth_l1', or any string other than 'mse'. Constructor accepts it; first training batch raises.

Common situations: Switching loss for robust regression experiments; configs imported from models with richer loss menus; assuming sklearn/lightgbm objective names carry over.

Related errors


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