Lightning-AI/pytorch-lightning · error · TypeError
Filter should be a dictionary, given {filter!r}
Error message
Filter should be a dictionary, given {filter!r} What it means
fabric.save(path, state, filter=...) expects `filter` to be a dictionary mapping state keys to callables (predicate functions applied per entry). Any other type (a bare lambda, a list, a string) fails the isinstance(filter, dict) check with TypeError.
Source
Thrown at src/lightning/fabric/fabric.py:858
Raises:
TypeError: If filter is not a dictionary or contains non-callable values.
ValueError: If filter keys don't match state keys.
Example::
state = {"model": model, "optimizer": optimizer, "epoch": epoch}
fabric.save("checkpoint.pth", state)
# With filter
def param_filter(name, param):
return "bias" not in name # Save only non-bias parameters
fabric.save("checkpoint.pth", state, filter={"model": param_filter})
"""
if filter is not None:
if not isinstance(filter, dict):
raise TypeError(f"Filter should be a dictionary, given {filter!r}")
if not set(filter).issubset(state):
raise ValueError(
f"The filter keys {filter.keys() - state} are not present in the state keys {set(state)}."
)
for k, v in filter.items():
if not callable(v):
raise TypeError(f"Expected `fabric.save(filter=...)` for key {k!r} to be a callable, given {v!r}")
self._strategy.save_checkpoint(path=path, state=_unwrap_objects(state), filter=filter)
self.barrier()
def load(
self,
path: Union[str, Path],
state: Optional[dict[str, Union[nn.Module, Optimizer, Any]]] = None,
strict: bool = True,
*,
weights_only: Optional[bool] = None,
) -> dict[str, Any]:View on GitHub (pinned to 9fed5c27d2)
Solutions
- Wrap the callable(s) in a dict keyed by state keys: filter={'model': lambda k, v: 'optimizer' not in k}
- Ensure every filter key exists in `state` (the next check enforces subset)
Example fix
# before
fabric.save('ckpt.pth', state, filter=lambda k, v: 'optimizer' not in k)
# after
fabric.save('ckpt.pth', state, filter={'model': lambda k, v: 'optimizer' not in k}) Defensive patterns
Strategy: type-guard
Validate before calling
assert filter is None or isinstance(filter, dict), 'filter must be a dict of {state_key: callable}' Type guard
def is_valid_filter(f):
return f is None or isinstance(f, dict) Prevention
- Remember filter is a dict of {state_key: predicate}, not a bare callable or list
When it happens
Trigger: Calling fabric.save('ckpt.pth', state, filter=lambda k, v: ...) — passing a bare callable instead of {'key': callable}; or passing a list of key names thinking it selects keys.
Common situations: Selective checkpointing of model weights but not optimizer state; misunderstanding the filter API shape from the docstring example.
Understand the failure class
Background: Invalid argument type errors: "must be of type string", "expected X, got Y", and ERR_INVALID_ARG_TYPE explained — this error's family across 15 libraries.
Related errors
- Expected `fabric.save(filter=...)` for key {k!r} to be a cal
- The filter keys {filter.keys() - state} are not present in t
- Received multiple values for {', '.join(duplicated_plugin_ke
- Received both `precision={precision_input}` and `plugins={se
- accelerator set through both strategy class and accelerator
AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28).
Data as JSON: /api/errors/a6ad2d4102dac681.
Report an issue: GitHub.