{"record":{"id":"48bdae63d6a74e60","repo":"lllyasviel/ControlNet","slug":"expected-key-target-to-instantiate","errorCode":null,"errorMessage":"Expected key `target` to instantiate.","messagePattern":"Expected key `target` to instantiate\\.","errorType":"validation","errorClass":"KeyError","httpStatus":null,"severity":"critical","filePath":"ldm/util.py","lineNumber":78,"sourceCode":"    Take the mean over all non-batch dimensions.\n    \"\"\"\n    return tensor.mean(dim=list(range(1, len(tensor.shape))))\n\n\ndef count_params(model, verbose=False):\n    total_params = sum(p.numel() for p in model.parameters())\n    if verbose:\n        print(f\"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.\")\n    return total_params\n\n\ndef instantiate_from_config(config):\n    if not \"target\" in config:\n        if config == '__is_first_stage__':\n            return None\n        elif config == \"__is_unconditional__\":\n            return None\n        raise KeyError(\"Expected key `target` to instantiate.\")\n    return get_obj_from_str(config[\"target\"])(**config.get(\"params\", dict()))\n\n\ndef get_obj_from_str(string, reload=False):\n    module, cls = string.rsplit(\".\", 1)\n    if reload:\n        module_imp = importlib.import_module(module)\n        importlib.reload(module_imp)\n    return getattr(importlib.import_module(module, package=None), cls)\n\n\nclass AdamWwithEMAandWings(optim.Optimizer):\n    # credit to https://gist.github.com/crowsonkb/65f7265353f403714fce3b2595e0b298\n    def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8,  # TODO: check hyperparameters before using\n                 weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999,   # ema decay to match previous code\n                 ema_power=1., param_names=()):\n        \"\"\"AdamW that saves EMA versions of the parameters.\"\"\"\n        if not 0.0 <= lr:","sourceCodeStart":60,"sourceCodeEnd":96,"githubUrl":"https://github.com/lllyasviel/ControlNet/blob/ed85cd1e25a5ed592f7d8178495b4483de0331bf/ldm/util.py#L60-L96","documentation":"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.","triggerScenarios":"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__'.","commonSituations":"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.","solutions":["Print/inspect the dict you pass and add the missing 'target': a fully-qualified dotted path like 'ldm.models.diffusion.ddpm.LatentDiffusion'","Make sure you pass the nested section (e.g. config['model']) not the top-level config when that's what the API expects","If the component should be skipped, use the sentinel string '__is_first_stage__' or '__is_unconditional__' instead of an empty dict","Verify the dotted path resolves: importlib.import_module on the module part before instantiating"],"exampleFix":"# before\nmodel = instantiate_from_config({\"params\": {\"image_size\": 256}})\n# after\nmodel = instantiate_from_config({\n    \"target\": \"ldm.models.diffusion.ddpm.LatentDiffusion\",\n    \"params\": {\"image_size\": 256}\n})","handlingStrategy":"validation","validationCode":"def valid_instantiation_config(cfg) -> bool:\n    if cfg in ('__is_first_stage__', '__is_unconditional__'):\n        return True\n    return isinstance(cfg, dict) and isinstance(cfg.get('target'), str) and '.' in cfg['target']","typeGuard":"from typing import TypeGuard, Any\n\ndef has_target(cfg: Any) -> TypeGuard[dict]:\n    return isinstance(cfg, dict) and 'target' in cfg","tryCatchPattern":"try:\n    obj = instantiate_from_config(cfg)\nexcept KeyError as e:\n    if 'target' in str(e):\n        raise ValueError(f'Invalid component config: {cfg!r} missing \"target\"')\n    raise","preventionTips":["Keep configs in version control next to the code version that parses them","Validate config JSON with a schema check (target + params keys) before training","Pass nested sections like config['model'], not the whole document"],"tags":["latent-diffusion","stable-diffusion","config","reflection","instantiation"],"backgroundTag":"invalid-dynamic-config-instantiation","analyzedSha":"ed85cd1e25a5ed592f7d8178495b4483de0331bf","analyzedAt":"2026-08-27T12:58:54.167Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}