microsoft/qlib · error · ValueError

model is not fitted yet!

Error message

model is not fitted yet!

What it means

GATsModel.predict() checks self.fitted, which is set True only after fit() completes its early-stopping loop and restores the best parameters. Calling predict() beforehand raises ValueError with no data access attempted. The guard prevents scoring with an untrained attention network.

Source

Thrown at qlib/contrib/model/pytorch_gats.py:303

                stop_steps = 0
                best_epoch = step
                best_param = copy.deepcopy(self.GAT_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.GAT_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")
        index = x_test.index
        self.GAT_model.eval()
        x_values = x_test.values
        preds = []

        # organize the data into daily batches
        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.GAT_model(x_batch).detach().cpu().numpy()

            preds.append(pred)

View on GitHub (pinned to 79633dd950)

Solutions

  1. Run fit(dataset) to completion before predict(dataset).
  2. If fit() failed, resolve that failure first; fitted flips True only on a clean finish.
  3. When restoring a saved model in a fresh process, load its state dict and set model.fitted = True before predict().

Example fix

# before
model = GATsModel()
model.predict(dataset)  # ValueError

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

Strategy: validation

Validate before calling

if not getattr(model, 'fitted', False):
    raise RuntimeError('GATsModel is not fitted; call fit() before predict()')

Type guard

def is_fitted(m) -> bool:
    return bool(getattr(m, 'fitted', False))

Try / catch

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

Prevention

When it happens

Trigger: model.predict(dataset) on a GATsModel that never ran fit(), or whose fit() aborted mid-way (empty data, bad loss/metric/optimizer, OOM) leaving fitted=False.

Common situations: Notebook runs where the training cell failed and downstream prediction cells still execute; checkpoint scripts that construct the model but forget to load weights; swallowing fit() exceptions with bare except and proceeding.

Related errors


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