{"record":{"id":"1d5a92f7240eb98f","repo":"Lightning-AI/pytorch-lightning","slug":"the-avg-fn-should-be-callable","errorCode":null,"errorMessage":"The `avg_fn` should be callable.","messagePattern":"The `avg_fn` should be callable\\.","errorType":"exception","errorClass":"MisconfigurationException","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/callbacks/stochastic_weight_avg.py","lineNumber":113,"sourceCode":"                When None is provided, it will infer the `device` from ``pl_module``.\n                (default: ``\"cpu\"``)\n\n        \"\"\"\n\n        err_msg = \"swa_epoch_start should be a >0 integer or a float between 0 and 1.\"\n        if isinstance(swa_epoch_start, int) and swa_epoch_start < 1:\n            raise MisconfigurationException(err_msg)\n        if isinstance(swa_epoch_start, float) and not (0 <= swa_epoch_start <= 1):\n            raise MisconfigurationException(err_msg)\n\n        wrong_type = not isinstance(swa_lrs, (float, list))\n        wrong_float = isinstance(swa_lrs, float) and swa_lrs <= 0\n        wrong_list = isinstance(swa_lrs, list) and not all(lr > 0 and isinstance(lr, float) for lr in swa_lrs)\n        if wrong_type or wrong_float or wrong_list:\n            raise MisconfigurationException(\"The `swa_lrs` should a positive float, or a list of positive floats\")\n\n        if avg_fn is not None and not callable(avg_fn):\n            raise MisconfigurationException(\"The `avg_fn` should be callable.\")\n\n        if device is not None and not isinstance(device, (torch.device, str)):\n            raise MisconfigurationException(f\"device is expected to be a torch.device or a str. Found {device}\")\n\n        self.n_averaged: Optional[Tensor] = None\n        self._swa_epoch_start = swa_epoch_start\n        self._swa_lrs = swa_lrs\n        self._annealing_epochs = annealing_epochs\n        self._annealing_strategy = annealing_strategy\n        self._avg_fn = avg_fn or self.avg_fn\n        self._device = device\n        self._model_contains_batch_norm: Optional[bool] = None\n        self._average_model: Optional[pl.LightningModule] = None\n        self._initialized = False\n        self._swa_scheduler: Optional[LRScheduler] = None\n        self._scheduler_state: Optional[dict] = None\n        self._init_n_averaged = 0\n        self._latest_update_epoch = -1","sourceCodeStart":95,"sourceCodeEnd":131,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/callbacks/stochastic_weight_avg.py#L95-L131","documentation":"StochasticWeightAveraging accepts an optional custom averaging function avg_fn (passed to torch's SWA utils), which must be callable. Passing anything non-callable (a lambda result, a string, None-check passes) raises this MisconfigurationException in __init__.","triggerScenarios":"SWA(avg_fn=0.5) or avg_fn=some_object that isn't a function/callable class instance.","commonSituations":"Confusing avg_fn parameters with a float weight; passing an unpickled/serialized function reference that lost callability.","solutions":["Pass a callable with signature avg_fn(averaged_model_parameter, model_parameter, num_averaged) -> tensor, e.g. torch.optim.swa_utils.get_ema_multi_avg_fn(0.9)","Or omit avg_fn to use the default equal averaging"],"exampleFix":"# before\nswa = SWA(avg_fn=0.9)\n# after\nfrom torch.optim.swa_utils import get_ema_multi_avg_fn\nswa = SWA(avg_fn=get_ema_multi_avg_fn(0.9))","handlingStrategy":"type-guard","validationCode":"import torch\navg_fn = None if cfg.ema is None else __import__('torch.optim.swa_utils', fromlist=['x']).get_ema_multi_avg_fn(cfg.ema)\nassert avg_fn is None or callable(avg_fn)\nswa = SWA(avg_fn=avg_fn)","typeGuard":"def is_valid_avg_fn(fn) -> bool:\n    return fn is None or callable(fn)","tryCatchPattern":null,"preventionTips":["Use factory helpers (get_ema_multi_avg_fn) to build avg_fn","Keep avg_fn as a top-level or lambda callable, never a scalar"],"tags":["swa","avg-fn","validation","callback"],"backgroundTag":"invalid-hyperparameter-value","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}