microsoft/qlib · error · ValueError

model is not fitted yet!

Error message

model is not fitted yet!

What it means

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.

Source

Thrown at qlib/contrib/model/pytorch_gats_ts.py:317

                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):
        if not self.fitted:
            raise ValueError("model is not fitted yet!")

        dl_test = dataset.prepare("test", col_set=["feature", "label"], data_key=DataHandlerLP.DK_I)
        dl_test.config(fillna_type="ffill+bfill")
        sampler_test = DailyBatchSampler(dl_test)
        test_loader = DataLoader(dl_test, sampler=sampler_test, num_workers=self.n_jobs)
        self.GAT_model.eval()
        preds = []

        for data in test_loader:
            data = data.squeeze()
            feature = data[:, :, 0:-1].to(self.device)

            with torch.no_grad():
                pred = self.GAT_model(feature.float()).detach().cpu().numpy()

            preds.append(pred)

        return pd.Series(np.concatenate(preds), index=dl_test.get_index())

View on GitHub (pinned to 79633dd950)

Solutions

  1. Complete fit(dataset) before calling predict(dataset).
  2. Diagnose and fix any earlier fit() failure; fitted is only set on clean completion.
  3. When serving a saved model, reload its state dict and set model.fitted = True before predicting.

Example fix

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

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

Strategy: validation

Validate before calling

if not getattr(model, 'fitted', False):
    raise RuntimeError('GATsTSModel 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 GATsTSModel that never completed fit(), including models whose fit() aborted on empty data, bad loss/metric/optimizer strings, or runtime errors like CUDA OOM.

Common situations: 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.

Related errors


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