{"record":{"id":"f2578e01eff96a2c","repo":"microsoft/qlib","slug":"unknown-loss-s-f2578e","errorCode":null,"errorMessage":"unknown loss `%s`","messagePattern":"unknown loss `(.+?)`","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"qlib/contrib/model/pytorch_localformer_ts.py","lineNumber":95,"sourceCode":"\r\n        self.fitted = False\r\n        self.model.to(self.device)\r\n\r\n    @property\r\n    def use_gpu(self):\r\n        return self.device != torch.device(\"cpu\")\r\n\r\n    def mse(self, pred, label):\r\n        loss = (pred.float() - label.float()) ** 2\r\n        return torch.mean(loss)\r\n\r\n    def loss_fn(self, pred, label):\r\n        mask = ~torch.isnan(label)\r\n\r\n        if self.loss == \"mse\":\r\n            return self.mse(pred[mask], label[mask])\r\n\r\n        raise ValueError(\"unknown loss `%s`\" % self.loss)\r\n\r\n    def metric_fn(self, pred, label):\r\n        mask = torch.isfinite(label)\r\n\r\n        if self.metric in (\"\", \"loss\"):\r\n            return -self.loss_fn(pred[mask], label[mask])\r\n\r\n        raise ValueError(\"unknown metric `%s`\" % self.metric)\r\n\r\n    def train_epoch(self, data_loader):\r\n        self.model.train()\r\n\r\n        for data in data_loader:\r\n            feature = data[:, :, 0:-1].to(self.device)\r\n            label = data[:, -1, -1].to(self.device)\r\n\r\n            pred = self.model(feature.float())  # .float()\r\n            loss = self.loss_fn(pred, label)\r","sourceCodeStart":77,"sourceCodeEnd":113,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_localformer_ts.py#L77-L113","documentation":"LOCALTransformerModel.loss_fn() supports exactly one training loss: 'mse' (masked mean squared error that ignores NaN labels). If self.loss is any other value it raises ValueError(\"unknown loss `%s`\"). The loss value is not validated in __init__, so this error surfaces mid-fit, inside train_epoch/validation, after data loading has already run.","triggerScenarios":"Calling model.fit(...) with loss set to anything other than 'mse' (e.g. 'mae', 'huber', 'binary'). The constructor accepts the string silently; the ValueError fires on the first batch of the first training epoch.","commonSituations":"Porting a config from a model with more losses (e.g. XGBoost/LightGBM params like 'reg:absoluteerror'); attempting MAE or Huber for robust regression; assuming the library auto-detects the loss from the label type.","solutions":["Set loss='mse' in the model kwargs — it is the only supported option.","For a custom loss, subclass and override loss_fn(self, pred, label); keep NaN masking via mask = ~torch.isnan(label).","Validate loss in __init__ of your subclass so misconfiguration fails fast instead of after data loading."],"exampleFix":"# before\nmodel = LOCALTransformerModel(..., loss=\"mae\")\nmodel.fit(dataset)  # ValueError: unknown loss `mae` on first batch\n\n# after\nmodel = LOCALTransformerModel(..., loss=\"mse\")\nmodel.fit(dataset)","handlingStrategy":"validation","validationCode":"loss = \"mse\"\nassert loss == \"mse\", \"LOCALTransformerModel supports only loss='mse'\"\nmodel = LOCALTransformerModel(..., loss=loss)","typeGuard":"def is_supported_loss(name: str) -> bool:\n    return isinstance(name, str) and name == \"mse\"","tryCatchPattern":"try:\n    model.fit(dataset)\nexcept ValueError as e:\n    if \"unknown loss\" in str(e):\n        raise ValueError(\"Only loss='mse' is supported; fix model kwargs and re-fit\") from e\n    raise","preventionTips":["The loss kwarg is not validated at __init__ — check it yourself before fit() to avoid wasted data prep.","Subclass and add an __init__ assertion if you manage many configs.","Keep model-family-specific option sets documented next to your config files."],"tags":["pytorch","qlib","loss-function","transformer","config"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}