{"record":{"id":"1fd1e47f670fb7df","repo":"microsoft/qlib","slug":"unknown-loss-s-1fd1e4","errorCode":null,"errorMessage":"unknown loss `%s`","messagePattern":"unknown loss `(.+?)`","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"qlib/contrib/model/pytorch_lstm_ts.py","lineNumber":150,"sourceCode":"\n    @property\n    def use_gpu(self):\n        return self.device != torch.device(\"cpu\")\n\n    def mse(self, pred, label, weight):\n        loss = weight * (pred - label) ** 2\n        return torch.mean(loss)\n\n    def loss_fn(self, pred, label, weight):\n        mask = ~torch.isnan(label)\n\n        if weight is None:\n            weight = torch.ones_like(label)\n\n        if self.loss == \"mse\":\n            return self.mse(pred[mask], label[mask], weight[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], weight=None)\n\n        raise ValueError(\"unknown metric `%s`\" % self.metric)\n\n    def train_epoch(self, data_loader):\n        self.LSTM_model.train()\n\n        for data, weight in data_loader:\n            feature = data[:, :, 0:-1].to(self.device)\n            label = data[:, -1, -1].to(self.device)\n\n            pred = self.LSTM_model(feature.float())\n            loss = self.loss_fn(pred, label, weight.to(self.device))","sourceCodeStart":132,"sourceCodeEnd":168,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_lstm_ts.py#L132-L168","documentation":"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().","triggerScenarios":"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.","commonSituations":"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).","solutions":["Set loss='mse' — the sole supported loss for this model.","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.","Fail fast: assert self.loss == 'mse' in your subclass __init__."],"exampleFix":"# before\nmodel = LSTMModel(..., loss=\"huber\")\nmodel.fit(dataset, reweighter=rw)  # ValueError: unknown loss `huber`\n\n# after\nmodel = LSTMModel(..., loss=\"mse\")\nmodel.fit(dataset, reweighter=rw)","handlingStrategy":"validation","validationCode":"assert loss == \"mse\", \"TS LSTM supports only loss='mse' (weighted MSE)\"\nmodel = LSTMModel(..., loss=loss)","typeGuard":"def is_supported_loss(name: str) -> bool:\n    return name == \"mse\"","tryCatchPattern":"try:\n    model.fit(dataset, reweighter=rw)\nexcept ValueError as e:\n    if \"unknown loss\" in str(e):\n        raise ValueError(\"loss must be 'mse'; reweighter only reweights MSE\") from e\n    raise","preventionTips":["Remember the reweighter changes sample weights, not the loss family.","Assert the loss string before fit — __init__ doesn't check it.","Custom loss overrides must accept and apply the weight argument."],"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"}