{"record":{"id":"4026c31fafa8f453","repo":"Lightning-AI/pytorch-lightning","slug":"device-is-expected-to-be-a-torch-device-or-a-str","errorCode":null,"errorMessage":"device is expected to be a torch.device or a str. Found {device}","messagePattern":"device is expected to be a torch\\.device or a str\\. Found (.+?)","errorType":"exception","errorClass":"MisconfigurationException","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/callbacks/stochastic_weight_avg.py","lineNumber":116,"sourceCode":"        \"\"\"\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\n        self.momenta: dict[nn.modules.batchnorm._BatchNorm, Optional[float]] = {}\n        self._max_epochs: int\n","sourceCodeStart":98,"sourceCodeEnd":134,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/callbacks/stochastic_weight_avg.py#L98-L134","documentation":"The optional `device` argument of StochasticWeightAveraging (where the SWA-averaged model copy is kept) must be a torch.device or a str. Any other type (int, None is allowed) raises this MisconfigurationException at construction.","triggerScenarios":"SWA(device=0) intending GPU index 0, or passing a torch.cuda device object of another library type.","commonSituations":"Migrating from an API that accepted a device index integer; passing device=0 copied from Trainer(accelerator='gpu', devices=[0]) style configs.","solutions":["Use SWA(device='cuda') or SWA(device=torch.device('cuda'))","For a specific GPU: SWA(device='cuda:0')","Or omit device to keep the averaged model on CPU by default"],"exampleFix":"# before\nswa = SWA(device=0)\n# after\nswa = SWA(device=\"cuda:0\")  # or torch.device(\"cuda:0\")","handlingStrategy":"validation","validationCode":"import torch\ndevice = None if cfg.device is None else str(cfg.device)  # coerce to str/torch.device\nassert device is None or isinstance(device, (str, torch.device))\nswa = SWA(device=device)","typeGuard":"def is_valid_device(d) -> bool:\n    return d is None or isinstance(d, (str, torch.device))","tryCatchPattern":null,"preventionTips":["Normalize devices with torch.device(...) or a string early in config loading","Never pass int indices to device= kwargs"],"tags":["swa","device","validation","callback"],"backgroundTag":"invalid-hyperparameter-value","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}