Lightning-AI/pytorch-lightning · error · TypeError

Expected `fabric.save(filter=...)` for key {k!r} to be a cal

Error message

Expected `fabric.save(filter=...)` for key {k!r} to be a callable, given {v!r}

What it means

Each value in the fabric.save(filter={...}) dict must be callable — it is applied as a predicate to the tensors/objects under that state key. Passing a non-callable (bool, string, list of names) fails the `callable(v)` check with TypeError naming the offending key and value.

Source

Thrown at src/lightning/fabric/fabric.py:865

            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]:
        """Load a checkpoint from a file and restore the state of objects (modules, optimizers, etc.).

        How and which processes load gets determined by the `strategy`.
        This method must be called on all processes!

        Args:
            path: A path to where the file is located.

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. Provide a function: filter={'model': lambda k, v: k in ('weight', 'bias')}
  2. For simple key selection, build the state dict to only contain what you want to save and omit filter entirely

Example fix

# before
fabric.save('ckpt.pth', state, filter={'model': True})
# after
fabric.save('ckpt.pth', state, filter={'model': lambda k, v: True})
Defensive patterns

Strategy: type-guard

Validate before calling

assert all(callable(v) for v in filter.values()), 'filter values must be callables'

Type guard

def valid_filter_values(f):
    return all(callable(v) for v in f.values())

Prevention

When it happens

Trigger: filter={'model': True}, filter={'model': ['weight']}, or filter={'model': 'lambda ...'} (stringified lambda).

Common situations: Trying to use filter as an include-list of parameter names; JSON-round-tripped configs turning functions into strings.

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


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