{"record":{"id":"ca46e6b8fdc8032c","repo":"microsoft/qlib","slug":"model-is-not-fitted-yet-ca46e6","errorCode":null,"errorMessage":"model is not fitted yet!","messagePattern":"model is not fitted yet!","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"qlib/contrib/model/pytorch_gats_ts.py","lineNumber":317,"sourceCode":"                stop_steps = 0\n                best_epoch = step\n                best_param = copy.deepcopy(self.GAT_model.state_dict())\n            else:\n                stop_steps += 1\n                if stop_steps >= self.early_stop:\n                    self.logger.info(\"early stop\")\n                    break\n\n        self.logger.info(\"best score: %.6lf @ %d\" % (best_score, best_epoch))\n        self.GAT_model.load_state_dict(best_param)\n        torch.save(best_param, save_path)\n\n        if self.use_gpu:\n            torch.cuda.empty_cache()\n\n    def predict(self, dataset):\n        if not self.fitted:\n            raise ValueError(\"model is not fitted yet!\")\n\n        dl_test = dataset.prepare(\"test\", col_set=[\"feature\", \"label\"], data_key=DataHandlerLP.DK_I)\n        dl_test.config(fillna_type=\"ffill+bfill\")\n        sampler_test = DailyBatchSampler(dl_test)\n        test_loader = DataLoader(dl_test, sampler=sampler_test, num_workers=self.n_jobs)\n        self.GAT_model.eval()\n        preds = []\n\n        for data in test_loader:\n            data = data.squeeze()\n            feature = data[:, :, 0:-1].to(self.device)\n\n            with torch.no_grad():\n                pred = self.GAT_model(feature.float()).detach().cpu().numpy()\n\n            preds.append(pred)\n\n        return pd.Series(np.concatenate(preds), index=dl_test.get_index())","sourceCodeStart":299,"sourceCodeEnd":335,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_gats_ts.py#L299-L335","documentation":"GATsTSModel.predict() begins by checking self.fitted, set True only when fit() finishes its early-stopping loop and restores best weights. Predicting before a successful fit raises ValueError immediately. Note this ts variant's predict() takes the test segment unconditionally ('test'), so it cannot be pointed at other segments anyway.","triggerScenarios":"model.predict(dataset) on a GATsTSModel that never completed fit(), including models whose fit() aborted on empty data, bad loss/metric/optimizer strings, or runtime errors like CUDA OOM.","commonSituations":"Failed training cells followed by prediction cells in notebooks; fresh processes that rebuild the model without restoring fitted state; pipeline code that ignores fit() exceptions.","solutions":["Complete fit(dataset) before calling predict(dataset).","Diagnose and fix any earlier fit() failure; fitted is only set on clean completion.","When serving a saved model, reload its state dict and set model.fitted = True before predicting."],"exampleFix":"# before\nmodel = GATsTSModel()\nmodel.predict(dataset)  # ValueError\n\n# after\nmodel = GATsTSModel()\nmodel.fit(dataset)\nmodel.predict(dataset)","handlingStrategy":"validation","validationCode":"if not getattr(model, 'fitted', False):\n    raise RuntimeError('GATsTSModel is not fitted; call fit() before predict()')","typeGuard":"def is_fitted(m) -> bool:\n    return bool(getattr(m, 'fitted', False))","tryCatchPattern":"try:\n    pred = model.predict(dataset)\nexcept ValueError as e:\n    if 'not fitted' in str(e):\n        model.fit(dataset)\n        pred = model.predict(dataset)\n    else:\n        raise","preventionTips":["Gate predict() calls on model.fitted in orchestration code.","Fail the whole pipeline when fit() fails; never predict from a half-fitted model.","Remember this ts model always predicts the 'test' segment; other segments need code changes."],"tags":["pytorch","qlib","lifecycle","state-error","gats-ts"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}