Lightning-AI/pytorch-lightning · error · AttributeError

{attribute} is neither stored in the model namespace nor the

Error message

{attribute} is neither stored in the model namespace nor the `hparams` namespace/dict, nor the datamodule.

What it means

lightning_getattr looks for the attribute in three places: the model namespace, model.hparams (namespace or dict), and the datamodule. If none holds it, AttributeError is raised. Used by batch-size finders and auto-scale logic to read 'batch_size'.

Source

Thrown at src/lightning/pytorch/utilities/parsing.py:304

    Checks for attribute in model namespace, the old hparams namespace/dict, and the datamodule.

    """
    return _lightning_get_first_attr_holder(model, attribute) is not None


def lightning_getattr(model: "pl.LightningModule", attribute: str) -> Optional[Any]:
    """Special getattr for Lightning. Checks for attribute in model namespace, the old hparams namespace/dict, and the
    datamodule.

    Raises:
        AttributeError:
            If ``model`` doesn't have ``attribute`` in any of
            model namespace, the hparams namespace/dict, and the datamodule.

    """
    holder = _lightning_get_first_attr_holder(model, attribute)
    if holder is None:
        raise AttributeError(
            f"{attribute} is neither stored in the model namespace"
            " nor the `hparams` namespace/dict, nor the datamodule."
        )

    if isinstance(holder, dict):
        return holder[attribute]
    return getattr(holder, attribute)


def lightning_setattr(model: "pl.LightningModule", attribute: str, value: Any) -> None:
    """Special setattr for Lightning. Checks for attribute in model namespace and the old hparams namespace/dict. Will
    also set the attribute on datamodule, if it exists.

    Raises:
        AttributeError:
            If ``model`` doesn't have ``attribute`` in any of
            model namespace, the hparams namespace/dict, and the datamodule.

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. Set the attribute on the LightningModule: self.batch_size = 32 in __init__
  2. Or save it into hparams: self.save_hyperparameters({'batch_size': 32})
  3. Or attach it to the datamodule and pass the datamodule to the Trainer

Example fix

# before
class M(LightningModule):
    def __init__(self, bs=32):
        super().__init__()
        # batch size never stored
# after
class M(LightningModule):
    def __init__(self, batch_size=32):
        super().__init__()
        self.batch_size = batch_size
Defensive patterns

Strategy: validation

Validate before calling

from lightning.pytorch.utilities.parsing import lightning_hasattr  # if available
has = hasattr(model, 'batch_size') or 'batch_size' in getattr(model, 'hparams', {}) or hasattr(dm, 'batch_size')
assert has, 'batch_size not found anywhere'

Type guard

def has_tunable_attr(model, name='batch_size', dm=None) -> bool:
    return any(hasattr(o, name) or name in getattr(o, 'hparams', {})
               for o in (model, dm) if o is not None)

Try / catch

try:
    val = lightning_getattr(model, 'batch_size')
except AttributeError:
    val = default_bs

Prevention

When it happens

Trigger: Running trainer.tuner.scale_batch_size or lr_find on a model that stores batch size under a different name (e.g. self.bs or only in the dataloader method) and has no datamodule attribute.

Common situations: Auto batch-size scaling where the LightningModule uses self.batch_size locally but never assigns it as instance attribute, or save_hyperparameters wasn't called so hparams is empty.

Related errors


AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28). Data as JSON: /api/errors/997cb5b2e9987516. Report an issue: GitHub.