{"record":{"id":"c850e2eff110ce2a","repo":"microsoft/qlib","slug":"model-is-not-fitted-yet-c850e2","errorCode":null,"errorMessage":"model is not fitted yet!","messagePattern":"model is not fitted yet!","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"qlib/contrib/model/pytorch_sandwich.py","lineNumber":362,"sourceCode":"                stop_steps = 0\n                best_epoch = step\n                best_param = copy.deepcopy(self.sandwich_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.sandwich_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: DatasetH, segment: Union[Text, slice] = \"test\"):\n        if not self.fitted:\n            raise ValueError(\"model is not fitted yet!\")\n\n        x_test = dataset.prepare(segment, col_set=\"feature\", data_key=DataHandlerLP.DK_I)\n        index = x_test.index\n        self.sandwich_model.eval()\n        x_values = x_test.values\n        sample_num = x_values.shape[0]\n        preds = []\n\n        for begin in range(sample_num)[:: self.batch_size]:\n            if sample_num - begin < self.batch_size:\n                end = sample_num\n            else:\n                end = begin + self.batch_size\n            x_batch = torch.from_numpy(x_values[begin:end]).float().to(self.device)\n            with torch.no_grad():\n                pred = self.sandwich_model(x_batch).detach().cpu().numpy()\n            preds.append(pred)\n","sourceCodeStart":344,"sourceCodeEnd":380,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/contrib/model/pytorch_sandwich.py#L344-L380","documentation":"Raised by SANDWICH model predict() in qlib/contrib/model/pytorch_sandwich.py:362 when self.fitted is False. fitted is set True only at the end of a successful fit(); predict() refuses to run inference on an untrained model. This mirrors the guard used across all qlib contrib pytorch models.","triggerScenarios":"Calling predict() before fit(); calling predict() after fit() aborted early (e.g. the empty-data ValueError above, NaN loss, CUDA OOM) since fitted is never set on the failure path.","commonSituations":"Workflow 'record' task run with a model that failed silently in a prior step; interactive sessions where fit raised and the user retries predict; pickle round-trips of partially trained models.","solutions":["Ensure model.fit(dataset) ran to completion (check for 'best score: ... @ ...' in logs) before predict().","Fix any earlier fit()-time exception first — this error is only a symptom.","Use the model's save/load API for checkpoint reuse instead of relying on half-fit objects."],"exampleFix":"model.fit(dataset)                 # must log 'best score: ...' before this flag is set\npreds = model.predict(dataset, segment=\"test\")","handlingStrategy":"validation","validationCode":"if not model.fitted:\n    raise RuntimeError(\"fit() must complete before predict(); check training logs for failures\")\npreds = model.predict(dataset, segment=\"test\")","typeGuard":"def is_fitted(model) -> bool:\n    return bool(getattr(model, \"fitted\", False))","tryCatchPattern":"try:\n    preds = model.predict(dataset, segment)\nexcept ValueError as e:\n    if \"not fitted\" in str(e):\n        raise RuntimeError(\"Training did not complete; inspect earlier fit() errors\") from e\n    raise","preventionTips":["Check the fitted attribute before predict in automated pipelines.","Confirm the 'best score: ... @ ...' log line appeared before predicting.","Fail the whole pipeline when fit() raises, instead of continuing to inference steps."],"tags":["qlib","pytorch","lifecycle","predict-before-fit","sandwich"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}