{"record":{"id":"df5e1d2f94ac2afe","repo":"microsoft/qlib","slug":"unknown-loss-s-df5e1d","errorCode":null,"errorMessage":"unknown loss `%s`","messagePattern":"unknown loss `(.+?)`","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"qlib/contrib/model/pytorch_lstm.py","lineNumber":142,"sourceCode":"\n        self.fitted = False\n        self.lstm_model.to(self.device)\n\n    @property\n    def use_gpu(self):\n        return self.device != torch.device(\"cpu\")\n\n    def mse(self, pred, label):\n        loss = (pred - label) ** 2\n        return torch.mean(loss)\n\n    def loss_fn(self, pred, label):\n        mask = ~torch.isnan(label)\n\n        if self.loss == \"mse\":\n            return self.mse(pred[mask], label[mask])\n\n        raise ValueError(\"unknown loss `%s`\" % self.loss)\n\n    def metric_fn(self, pred, label):\n        mask = torch.isfinite(label)\n\n        if self.metric in (\"\", \"loss\"):\n            return -self.loss_fn(pred[mask], label[mask])\n\n        raise ValueError(\"unknown metric `%s`\" % self.metric)\n\n    def train_epoch(self, x_train, y_train):\n        x_train_values = x_train.values\n        y_train_values = np.squeeze(y_train.values)\n\n        self.lstm_model.train()\n\n        indices = np.arange(len(x_train_values))\n        np.random.shuffle(indices)\n","sourceCodeStart":124,"sourceCodeEnd":160,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_lstm.py#L124-L160","documentation":"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.","triggerScenarios":"model.fit(...) with loss='mae', 'huber', 'smooth_l1', or any string other than 'mse'. Constructor accepts it; first training batch raises.","commonSituations":"Switching loss for robust regression experiments; configs imported from models with richer loss menus; assuming sklearn/lightgbm objective names carry over.","solutions":["Set loss='mse' — the only implemented loss for this LSTM model.","Subclass and override loss_fn(pred, label) for custom losses, preserving the NaN mask (~torch.isnan(label)) since qlib labels frequently contain NaNs.","Add an early check of self.loss in your subclass __init__ to fail before expensive data prep."],"exampleFix":"# before\nmodel = LSTMModel(..., loss=\"mae\")\nmodel.fit(dataset)  # ValueError: unknown loss `mae`\n\n# after\nmodel = LSTMModel(..., loss=\"mse\")\nmodel.fit(dataset)","handlingStrategy":"validation","validationCode":"assert loss == \"mse\", \"pytorch_lstm supports only loss='mse'\"\nmodel = LSTMModel(..., loss=loss)","typeGuard":"def is_supported_loss(name: str) -> bool:\n    return name == \"mse\"","tryCatchPattern":"try:\n    model.fit(dataset)\nexcept ValueError as e:\n    if \"unknown loss\" in str(e):\n        raise ValueError(\"loss must be 'mse' for this LSTM model\") from e\n    raise","preventionTips":["loss is unvalidated at __init__ — assert it yourself before fit to avoid wasted data prep.","Subclass with an __init__ check when managing many experiment configs.","Keep NaN-masked MSE semantics in mind if you override loss_fn (labels often contain NaNs)."],"tags":["pytorch","qlib","loss-function","lstm","config"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}