Stability-AI/generative-models · critical · KeyError
Expected key `target` to instantiate.
Error message
Expected key `target` to instantiate.
What it means
instantiate_from_config expects a dict with a 'target' key holding the dotted python path of the class to build. Sentinel configs '__is_first_stage__' and '__is_unconditional__' short-circuit to None; anything else without 'target' raises KeyError('Expected key `target` to instantiate.').
Source
Thrown at sgm/util.py:174
Take the mean over all non-batch dimensions.
"""
return tensor.mean(dim=list(range(1, len(tensor.shape))))
def count_params(model, verbose=False):
total_params = sum(p.numel() for p in model.parameters())
if verbose:
print(f"{model.__class__.__name__} has {total_params * 1.e-6:.2f} M params.")
return total_params
def instantiate_from_config(config):
if not "target" in config:
if config == "__is_first_stage__":
return None
elif config == "__is_unconditional__":
return None
raise KeyError("Expected key `target` to instantiate.")
return get_obj_from_str(config["target"])(**config.get("params", dict()))
def get_obj_from_str(string, reload=False, invalidate_cache=True):
module, cls = string.rsplit(".", 1)
if invalidate_cache:
importlib.invalidate_caches()
if reload:
module_imp = importlib.import_module(module)
importlib.reload(module_imp)
return getattr(importlib.import_module(module, package=None), cls)
def append_zero(x):
return torch.cat([x, x.new_zeros([1])])
def append_dims(x, target_dims):View on GitHub (pinned to e8cd657656)
Solutions
- Ensure every model/submodule config dict has a 'target' key with the full dotted class path
- Check YAML indentation so 'target' sits inside the intended node, not a sibling
- If the sentinel semantics apply, pass the exact strings '__is_first_stage__' or '__is_unconditional__'
- Print the offending config dict at the call site to see what was actually received
Example fix
// before
first_stage_config:
params:
ckpt_path: model.ckpt
// after
first_stage_config:
target: sgm.models.autoencoder.AutoencoderKL
params:
ckpt_path: model.ckpt Defensive patterns
Strategy: validation
Validate before calling
def safe_instantiate(config):
if isinstance(config, str) and config in ('__is_first_stage__', '__is_unconditional__'):
return None
if not isinstance(config, dict) or 'target' not in config:
raise KeyError(f"config missing 'target': {config!r}")
return instantiate_from_config(config) Type guard
def is_instantiable_config(c) -> bool:
return isinstance(c, dict) and 'target' in c Try / catch
try:
stage = instantiate_from_config(first_stage_cfg)
except KeyError as e:
if 'target' in str(e):
logging.error('config lacks target: %s', json.dumps(first_stage_cfg, default=str))
return None # or treat as __is_first_stage__ sentinel Prevention
- Verify YAML indentation: target/params must be siblings inside the intended node
- Keep full first-stage/cond-stage configs in checkpoint metadata instead of trimmed dicts
- Never pass an empty dict or params-only dict to instantiate_from_config
- Write a CI check that walks all model YAMLs and asserts every node has 'target'
When it happens
Trigger: Passing a config dict to instantiate_from_config (from sgm/util.py:174) that lacks 'target' — e.g. an empty dict, a dict with only 'params', or a mis-nested dict where target ended up in a sub-dict.
Common situations: YAML indentation mistakes in model configs (params merged at the wrong level); passing None-handling sentinels incorrectly; checkpoint-loading code (load_model_from_config, apply_ckpt) hitting a first-stage/cond-stage config that was trimmed; calling configure_optimizers-style paths with partial config objects.
Related errors
- need either 'input_key' or 'input_keys' for embedder {embedd
- unknown merge strategy {self.merge_strategy}
- Unknown loss type {self.loss_type}
- provide num_res_blocks either as an int (globally constant)
- NotImplementedError
AI-assisted analysis of Stability-AI/generative-models@e8cd657656 (2026-08-29).
Data as JSON: /api/errors/28e199e54e8e9175.
Report an issue: GitHub.