lllyasviel/ControlNet · critical · KeyError

Expected key `target` to instantiate.

Error message

Expected key `target` to instantiate.

What it means

Raised by ldm.util.instantiate_from_config when the config dict passed to it has no 'target' key (and is not one of the sentinel strings '__is_first_stage__' or '__is_unconditional__'). In latent-diffusion/Stable-Diffusion codebases, every component (first stage, cond stage, model, optimizer) is built reflectively from a config dict via config['target'] (a dotted import path) plus optional config['params']; a missing 'target' means the config is structurally invalid.

Source

Thrown at ldm/util.py:78

    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):
    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 ed85cd1e25)

Solutions

  1. Print/inspect the dict you pass and add the missing 'target': a fully-qualified dotted path like 'ldm.models.diffusion.ddpm.LatentDiffusion'
  2. Make sure you pass the nested section (e.g. config['model']) not the top-level config when that's what the API expects
  3. If the component should be skipped, use the sentinel string '__is_first_stage__' or '__is_unconditional__' instead of an empty dict
  4. Verify the dotted path resolves: importlib.import_module on the module part before instantiating

Example fix

# before
model = instantiate_from_config({"params": {"image_size": 256}})
# after
model = instantiate_from_config({
    "target": "ldm.models.diffusion.ddpm.LatentDiffusion",
    "params": {"image_size": 256}
})
Defensive patterns

Strategy: validation

Validate before calling

def valid_instantiation_config(cfg) -> bool:
    if cfg in ('__is_first_stage__', '__is_unconditional__'):
        return True
    return isinstance(cfg, dict) and isinstance(cfg.get('target'), str) and '.' in cfg['target']

Type guard

from typing import TypeGuard, Any

def has_target(cfg: Any) -> TypeGuard[dict]:
    return isinstance(cfg, dict) and 'target' in cfg

Try / catch

try:
    obj = instantiate_from_config(cfg)
except KeyError as e:
    if 'target' in str(e):
        raise ValueError(f'Invalid component config: {cfg!r} missing "target"')
    raise

Prevention

When it happens

Trigger: Calling instantiate_from_config(cfg) where cfg lacks the 'target' key — e.g. passing a params-only dict, passing the whole JSON config instead of the sub-dict under 'model', loading a YAML/JSON whose keys were renamed, or a config conditioned to be unconditional but represented as a dict rather than the string '__is_unconditional__'.

Common situations: Using Stable-Diffusion config JSONs from a different repo version (schema drift), building custom models with LatentDiffusion(config_path, ...) where the config's 'model' section is malformed, or programmatically editing configs and dropping the target key.

Related errors


AI-assisted analysis of lllyasviel/ControlNet@ed85cd1e25 (2026-08-27). Data as JSON: /api/errors/48bdae63d6a74e60. Report an issue: GitHub.