microsoft/qlib · error · ValueError

model is not fitted yet!

Error message

model is not fitted yet!

What it means

IGMTFModel.predict requires self.fitted == True. The flag is set only after fit() finishes (including its early-stop loop and state restore), so predicting from an unfitted instance — or one whose fit crashed — raises this ValueError.

Source

Thrown at qlib/contrib/model/pytorch_igmtf.py:329

                stop_steps = 0
                best_epoch = step
                best_param = copy.deepcopy(self.igmtf_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.igmtf_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_train = dataset.prepare("train", col_set="feature", data_key=DataHandlerLP.DK_L)
        train_hidden, train_hidden_day = self.get_train_hidden(x_train)
        x_test = dataset.prepare(segment, col_set="feature", data_key=DataHandlerLP.DK_I)
        index = x_test.index
        self.igmtf_model.eval()
        x_values = x_test.values
        preds = []

        daily_index, daily_count = self.get_daily_inter(x_test, shuffle=False)

        for idx, count in zip(daily_index, daily_count):
            batch = slice(idx, idx + count)
            x_batch = torch.from_numpy(x_values[batch]).float().to(self.device)

            with torch.no_grad():
                pred = (
                    self.igmtf_model(x_batch, train_hidden=train_hidden, train_hidden_day=train_hidden_day)
                    .detach()

View on GitHub (pinned to 79633dd950)

Solutions

  1. Fit the model to completion before calling predict
  2. Load saved weights and set model.fitted = True if you intentionally skip refitting
  3. Ensure fit() exceptions abort the pipeline instead of falling through to predict

Example fix

# before
model = IGMTFModel()
model.predict(dataset)  # not fitted

# after
model.fit(dataset)
model.predict(dataset)
Defensive patterns

Strategy: validation

Validate before calling

if not model.fitted:
    raise RuntimeError("IGMTFModel must complete fit() before predict()")

Type guard

def is_fitted(model) -> bool:
    return bool(getattr(model, "fitted", False))

Try / catch

try:
    preds = model.predict(dataset)
except ValueError as e:
    if "not fitted" in str(e):
        model.fit(dataset)
        preds = model.predict(dataset)
    else:
        raise

Prevention

When it happens

Trigger: Calling predict() on a model that never completed fit(); or after a fit() exception (empty data, bad metric, NaN loss) left fitted False while the caller continued.

Common situations: Train/infer split across processes or notebooks where the infer side builds a fresh IGMTFModel; swallowing fit exceptions; pickling a model before fit finished.

Related errors


AI-assisted analysis of microsoft/qlib@79633dd950 (2026-08-15). Data as JSON: /api/errors/368a614bb5c1d43a. Report an issue: GitHub.