espnet2.torch_utils.safe_torch_load.safe_torch_load
espnet2.torch_utils.safe_torch_load.safe_torch_load
espnet2.torch_utils.safe_torch_load.safe_torch_load(path: str | Path, map_location=None, **kwargs)
Load a PyTorch checkpoint safely, defaulting to weights_only=True.
In PyTorch >= 2.6 the safe default is weights_only=True, which prevents arbitrary code execution via pickle gadgets (CWE-502). This wrapper always tries weights_only=True first.
If that attempt fails (e.g. the checkpoint contains non-tensor objects), no automatic fallback is performed. Instead, a UnsafeLoadRefusedError (a sub-class of RuntimeError) is raised with instructions for explicit opt-in.
Unsafe fallback (weights_only=False) is only performed when at least one of the following explicit opt-in mechanisms is active:
- the environment variable
ESPNET_ALLOW_UNSAFE_TORCH_LOAD=1is set, or - the process is running on an interactive TTY and the user types the confirmation phrase
I_UNDERSTAND_THE_RISKwhen prompted.
Never pass weights_only via **kwargs; callers should rely on this wrapper’s policy.
- Parameters:
- path – Path to the checkpoint file.
- map_location – Passed directly to
torch.load. - **kwargs – Additional keyword arguments forwarded to
torch.load(excludingweights_only).
- Returns: The deserialized checkpoint object.
- Raises:
- UnsafeLoadRefusedError – If
weights_only=Truefails and no explicit opt-in is provided, with an actionable message describing the opt-in options. - OSError – If the file cannot be opened (propagated without fallback).
- UnsafeLoadRefusedError – If
