microsoft/qlib · error · ValueError

model is not fitted yet!

Error message

model is not fitted yet!

What it means

Raised by TabNet model predict() in qlib/contrib/model/pytorch_tabnet.py:219 when self.fitted is False. fitted is set only at the end of a successful fit() (after restoring best params and torch.save of the checkpoint); predict refuses inference otherwise.

Source

Thrown at qlib/contrib/model/pytorch_tabnet.py:219

                stop_steps = 0
                best_epoch = epoch_idx
                best_param = copy.deepcopy(self.tabnet_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.tabnet_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.tabnet_model.eval()
        x_values = torch.from_numpy(x_test.values)
        x_values[torch.isnan(x_values)] = 0
        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 = x_values[begin:end].float().to(self.device)
            priors = torch.ones(end - begin, self.d_feat).to(self.device)

View on GitHub (pinned to 79633dd950)

Solutions

  1. Complete model.fit(dataset) (with or without pretrain) before predict().
  2. If fit fails, fix the earlier error; this ValueError is downstream noise.
  3. Reuse trained checkpoints through the documented save/load path.

Example fix

model.fit(dataset)                     # pretrain + finetune completes here
preds = model.predict(dataset, segment="test")
Defensive patterns

Strategy: validation

Validate before calling

if not model.fitted:
    raise RuntimeError("TabNet requires a completed fit() (pretrain alone is not enough)")
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("TabNet finetune fit() did not complete") from e
    raise

Prevention

When it happens

Trigger: predict() before fit(); predict() after fit() failed mid-training (empty data, loss/metric ValueError, NaN loss, OOM); predict() on a fresh model object with a pretrain checkpoint but no finetune fit.

Common situations: Assuming pretrain_fn alone makes the model predict-ready (it does not — fit() must still run); scripted backtests that ignore fit failures.

Related errors


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