AUTOMATIC1111/stable-diffusion-webui · error · Exception

global '{module}/{name}' is forbidden

Error message

global '{module}/{name}' is forbidden

What it means

modules/safe.py replaces torch.load with a RestrictedUnpickler whose find_class allow-lists a small set of globals (torch storage types, collections OrderedDict, specific pytorch_lightning callbacks, _codecs.encode, __builtin__.set). Any pickle referencing a module/global outside that allow-list raises 'global ... is forbidden' — this is the webui's protection against arbitrary code execution from malicious checkpoint files.

Source

Thrown at modules/safe.py:64

        if module == 'torch.nn.modules.container' and name in ['ParameterDict']:
            return getattr(torch.nn.modules.container, name)
        if module == 'numpy.core.multiarray' and name in ['scalar', '_reconstruct']:
            return getattr(numpy.core.multiarray, name)
        if module == 'numpy' and name in ['dtype', 'ndarray']:
            return getattr(numpy, name)
        if module == '_codecs' and name == 'encode':
            return encode
        if module == "pytorch_lightning.callbacks" and name == 'model_checkpoint':
            import pytorch_lightning.callbacks
            return pytorch_lightning.callbacks.model_checkpoint
        if module == "pytorch_lightning.callbacks.model_checkpoint" and name == 'ModelCheckpoint':
            import pytorch_lightning.callbacks.model_checkpoint
            return pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint
        if module == "__builtin__" and name == 'set':
            return set

        # Forbid everything else.
        raise Exception(f"global '{module}/{name}' is forbidden")


# Regular expression that accepts 'dirname/version', 'dirname/byteorder', 'dirname/data.pkl', '.data/serialization_id', and 'dirname/data/<number>'
allowed_zip_names_re = re.compile(r"^([^/]+)/((data/\d+)|version|byteorder|.data/serialization_id|(data\.pkl))$")
data_pkl_re = re.compile(r"^([^/]+)/data\.pkl$")

def check_zip_filenames(filename, names):
    for name in names:
        if allowed_zip_names_re.match(name):
            continue

        raise Exception(f"bad file inside {filename}: {name}")


def check_pt(filename, extra_handler):
    try:

        # new pytorch format is a zip file

View on GitHub (pinned to 82a973c043)

Solutions

  1. If the file is from an untrusted source, treat this error as a safety stop — do NOT bypass it; obtain the model from the original trusted release.
  2. If you know the file is safe and need it loadable, re-save the tensor data as a plain state_dict / safetensors (e.g. torch.save({'tensor': t}) or convert to .safetensors) so no custom globals are referenced.
  3. As a last resort for trusted files only, load with weights_only=True via torch directly or temporarily use --disable-safe-unpickle (understands the risk) — prefer converting instead.

Example fix

# before: checkpoint contains a custom class global -> 'global ... is forbidden'
ckpt = torch.load('model.pt')

# after: re-export pure tensors as safetensors from a trusted environment
from safetensors.torch import save_file
import torch
 tensors = {k: v for k, v in trusted_state_dict.items()}
 save_file(tensors, 'model.safetensors')
Defensive patterns

Strategy: try-catch

Validate before calling

def inspect_pt_globals(path):
    """Best-effort: list module/global names referenced by the pickle (trusted files only)."""
    import pickletools, io
    names = []
    # Not a full safety check; use only as a diagnostic on trusted files.
    return names

Try / catch

try:
    weights = torch.load(ckpt_path)  # routed through modules.safe
except Exception as e:
    if 'is forbidden' in str(e):
        # untrusted or exotic pickle: do not bypass; convert from a trusted source instead
        raise RuntimeError(f'{ckpt_path} references disallowed globals; obtain a safetensors version')
    raise

Prevention

When it happens

Trigger: Loading a .pt/.ckpt/.pth file whose pickle bytecode references a forbidden global — either a genuinely malicious pickle (e.g. os.system, subprocess) or a legitimate-but-exotic object type produced by another framework (e.g. numpy arrays, custom classes, sgm/modules from other UIs) that is not on the allow-list.

Common situations: Loading checkpoints saved by third-party tools or other UIs that embed non-allow-listed classes (common with some LoRA/embedding converters or old Lightning checkpoints); rarely, an actually malicious model file downloaded from untrusted sources.

Understand the failure class

Related errors


AI-assisted analysis of AUTOMATIC1111/stable-diffusion-webui@82a973c043 (2026-08-14). Data as JSON: /api/errors/a044311e5f5f1059. Report an issue: GitHub.