{"record":{"id":"28e199e54e8e9175","repo":"Stability-AI/generative-models","slug":"expected-key-target-to-instantiate","errorCode":null,"errorMessage":"Expected key `target` to instantiate.","messagePattern":"Expected key `target` to instantiate\\.","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"critical","filePath":"sgm/util.py","lineNumber":174,"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, invalidate_cache=True):\n    module, cls = string.rsplit(\".\", 1)\n    if invalidate_cache:\n        importlib.invalidate_caches()\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\ndef append_zero(x):\n    return torch.cat([x, x.new_zeros([1])])\n\n\ndef append_dims(x, target_dims):","sourceCodeStart":156,"sourceCodeEnd":192,"githubUrl":"https://github.com/Stability-AI/generative-models/blob/e8cd657656fa5d61688191730d0e03242bf4ed44/sgm/util.py#L156-L192","documentation":"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.').","triggerScenarios":"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.","commonSituations":"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.","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"],"exampleFix":"// before\nfirst_stage_config:\n  params:\n    ckpt_path: model.ckpt\n// after\nfirst_stage_config:\n  target: sgm.models.autoencoder.AutoencoderKL\n  params:\n    ckpt_path: model.ckpt","handlingStrategy":"validation","validationCode":"def safe_instantiate(config):\n    if isinstance(config, str) and config in ('__is_first_stage__', '__is_unconditional__'):\n        return None\n    if not isinstance(config, dict) or 'target' not in config:\n        raise KeyError(f\"config missing 'target': {config!r}\")\n    return instantiate_from_config(config)","typeGuard":"def is_instantiable_config(c) -> bool:\n    return isinstance(c, dict) and 'target' in c","tryCatchPattern":"try:\n    stage = instantiate_from_config(first_stage_cfg)\nexcept KeyError as e:\n    if 'target' in str(e):\n        logging.error('config lacks target: %s', json.dumps(first_stage_cfg, default=str))\n    return None  # or treat as __is_first_stage__ sentinel","preventionTips":["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'"],"tags":["python","keyerror","config","instantiate"],"backgroundTag":"missing-config-key","analyzedSha":"e8cd657656fa5d61688191730d0e03242bf4ed44","analyzedAt":"2026-08-29T11:23:43.234Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}