microsoft/qlib · error · ValueError
model is not fitted yet!
Error message
model is not fitted yet!
What it means
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.
Source
Thrown at qlib/contrib/model/pytorch_sandwich.py:362
stop_steps = 0
best_epoch = step
best_param = copy.deepcopy(self.sandwich_model.state_dict())
else:
stop_steps += 1
if stop_steps >= self.early_stop:
self.logger.info("early stop")
break
self.logger.info("best score: %.6lf @ %d" % (best_score, best_epoch))
self.sandwich_model.load_state_dict(best_param)
torch.save(best_param, save_path)
if self.use_gpu:
torch.cuda.empty_cache()
def predict(self, dataset: DatasetH, segment: Union[Text, slice] = "test"):
if not self.fitted:
raise ValueError("model is not fitted yet!")
x_test = dataset.prepare(segment, col_set="feature", data_key=DataHandlerLP.DK_I)
index = x_test.index
self.sandwich_model.eval()
x_values = x_test.values
sample_num = x_values.shape[0]
preds = []
for begin in range(sample_num)[:: self.batch_size]:
if sample_num - begin < self.batch_size:
end = sample_num
else:
end = begin + self.batch_size
x_batch = torch.from_numpy(x_values[begin:end]).float().to(self.device)
with torch.no_grad():
pred = self.sandwich_model(x_batch).detach().cpu().numpy()
preds.append(pred)
View on GitHub (pinned to 79633dd950)
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.
Example fix
model.fit(dataset) # must log 'best score: ...' before this flag is set preds = model.predict(dataset, segment="test")
Defensive patterns
Strategy: validation
Validate before calling
if not model.fitted:
raise RuntimeError("fit() must complete before predict(); check training logs for failures")
preds = model.predict(dataset, segment="test") Type guard
def is_fitted(model) -> bool:
return bool(getattr(model, "fitted", False)) Try / catch
try:
preds = model.predict(dataset, segment)
except ValueError as e:
if "not fitted" in str(e):
raise RuntimeError("Training did not complete; inspect earlier fit() errors") from e
raise Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- model is not fitted yet!
- model is not fitted yet!
- model is not fitted yet!
- model is not fitted yet!
- model is not fitted yet!
AI-assisted analysis of microsoft/qlib@79633dd950 (2026-08-15).
Data as JSON: /api/errors/c850e2eff110ce2a.
Report an issue: GitHub.