Comfy-Org/ComfyUI · error · KeyError
Expected key `target` to instantiate.
Error message
Expected key `target` to instantiate.
What it means
instantiate_from_config() builds an object from a config dict by importing the class named under the "target" key. The only exempt values are the sentinel strings '__is_first_stage__' and '__is_unconditional__' (which return None); any other dict without "target" raises KeyError. This is a config-schema error: the dict cannot describe what to instantiate.
Source
Thrown at comfy/ldm/util.py:79
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:
logging.info(f"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.")
return total_params
def instantiate_from_config(config):
if "target" not 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):
module, cls = string.rsplit(".", 1)
if reload:
module_imp = importlib.import_module(module)
importlib.reload(module_imp)
return getattr(importlib.import_module(module, package=None), cls)
class AdamWwithEMAandWings(optim.Optimizer):
# credit to https://gist.github.com/crowsonkb/65f7265353f403714fce3b2595e0b298
def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8, # TODO: check hyperparameters before using
weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999, # ema decay to match previous code
ema_power=1., param_names=()):
"""AdamW that saves EMA versions of the parameters."""
if not 0.0 <= lr:View on GitHub (pinned to 1c6d8d45b3)
Solutions
- Ensure the dict has a "target" key with a fully qualified class path, e.g. {"target": "comfy.ldm.seedvr.vae.AutoencoderKLSeedVR", "params": {...}}.
- If None is intended for an optional stage, use the sentinels '__is_first_stage__' or '__is_unconditional__' or skip the call.
- Inspect the checkpoint's config file for a truncated/malformed stage entry.
Example fix
# before
model = instantiate_from_config({"params": {"embed_dim": 4}})
# after
model = instantiate_from_config({"target": "comfy.ldm....Decoder", "params": {"embed_dim": 4}}) Defensive patterns
Strategy: validation
Validate before calling
SENTINELS = {"__is_first_stage__", "__is_unconditional__"}
if isinstance(config, dict) and "target" not in config and config not in SENTINELS:
raise KeyError("config lacks 'target'; wrap as {'target': ..., 'params': ...}")
obj = instantiate_from_config(config) Type guard
def is_instantiable_config(config) -> bool:
return config in ("__is_first_stage__", "__is_unconditional__") or (isinstance(config, dict) and "target" in config) Try / catch
try:
obj = instantiate_from_config(stage_cfg)
except KeyError as e:
if "target" in str(e):
logging.warning("skipping stage without target: %r", stage_cfg)
obj = None
else:
raise Prevention
- Schema-check config files for a 'target' key per stage before loading.
- Don't pass params dicts directly; wrap them with their target class path.
When it happens
Trigger: instantiate_from_config(config) where config is a dict lacking "target" — e.g. a checkpoint's JSON/YAML config missing the first-stage/unet entry, or passing params directly instead of wrapping them in {"target": ..., "params": ...}.
Common situations: Editing or truncating a model config JSON; a checkpoint config that uses a different schema version; passing the wrong sub-dict (config["params"] instead of config).
Related errors
- `only_cross_attention` can only be set to True if `added_kv_
- Unknown normalization type: {norm_type}
- Unknown activation type: {activation_type}
- Block with {block_type=} is not supported.
- Block type {block_type} not supported
AI-assisted analysis of Comfy-Org/ComfyUI@1c6d8d45b3 (2026-08-14).
Data as JSON: /api/errors/bdcebd9a2ee60773.
Report an issue: GitHub.