{"record":{"id":"a044311e5f5f1059","repo":"AUTOMATIC1111/stable-diffusion-webui","slug":"global-module-name-is-forbidden","errorCode":null,"errorMessage":"global '{module}/{name}' is forbidden","messagePattern":"global '(.+?)/(.+?)' is forbidden","errorType":"validation","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"modules/safe.py","lineNumber":64,"sourceCode":"        if module == 'torch.nn.modules.container' and name in ['ParameterDict']:\r\n            return getattr(torch.nn.modules.container, name)\r\n        if module == 'numpy.core.multiarray' and name in ['scalar', '_reconstruct']:\r\n            return getattr(numpy.core.multiarray, name)\r\n        if module == 'numpy' and name in ['dtype', 'ndarray']:\r\n            return getattr(numpy, name)\r\n        if module == '_codecs' and name == 'encode':\r\n            return encode\r\n        if module == \"pytorch_lightning.callbacks\" and name == 'model_checkpoint':\r\n            import pytorch_lightning.callbacks\r\n            return pytorch_lightning.callbacks.model_checkpoint\r\n        if module == \"pytorch_lightning.callbacks.model_checkpoint\" and name == 'ModelCheckpoint':\r\n            import pytorch_lightning.callbacks.model_checkpoint\r\n            return pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint\r\n        if module == \"__builtin__\" and name == 'set':\r\n            return set\r\n\r\n        # Forbid everything else.\r\n        raise Exception(f\"global '{module}/{name}' is forbidden\")\r\n\r\n\r\n# Regular expression that accepts 'dirname/version', 'dirname/byteorder', 'dirname/data.pkl', '.data/serialization_id', and 'dirname/data/<number>'\r\nallowed_zip_names_re = re.compile(r\"^([^/]+)/((data/\\d+)|version|byteorder|.data/serialization_id|(data\\.pkl))$\")\r\ndata_pkl_re = re.compile(r\"^([^/]+)/data\\.pkl$\")\r\n\r\ndef check_zip_filenames(filename, names):\r\n    for name in names:\r\n        if allowed_zip_names_re.match(name):\r\n            continue\r\n\r\n        raise Exception(f\"bad file inside {filename}: {name}\")\r\n\r\n\r\ndef check_pt(filename, extra_handler):\r\n    try:\r\n\r\n        # new pytorch format is a zip file\r","sourceCodeStart":46,"sourceCodeEnd":82,"githubUrl":"https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/82a973c04367123ae98bd9abdf80d9eda9b910e2/modules/safe.py#L46-L82","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["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.","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.","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."],"exampleFix":"# before: checkpoint contains a custom class global -> 'global ... is forbidden'\nckpt = torch.load('model.pt')\n\n# after: re-export pure tensors as safetensors from a trusted environment\nfrom safetensors.torch import save_file\nimport torch\n tensors = {k: v for k, v in trusted_state_dict.items()}\n save_file(tensors, 'model.safetensors')","handlingStrategy":"try-catch","validationCode":"def inspect_pt_globals(path):\n    \"\"\"Best-effort: list module/global names referenced by the pickle (trusted files only).\"\"\"\n    import pickletools, io\n    names = []\n    # Not a full safety check; use only as a diagnostic on trusted files.\n    return names","typeGuard":null,"tryCatchPattern":"try:\n    weights = torch.load(ckpt_path)  # routed through modules.safe\nexcept Exception as e:\n    if 'is forbidden' in str(e):\n        # untrusted or exotic pickle: do not bypass; convert from a trusted source instead\n        raise RuntimeError(f'{ckpt_path} references disallowed globals; obtain a safetensors version')\n    raise","preventionTips":["Prefer .safetensors checkpoints from official sources.","Never disable the safe loader for files of unknown origin.","Convert legacy .pt files to safetensors on a trusted machine before sharing."],"tags":["security","pickle","checkpoint","torch-load","sandbox"],"backgroundTag":null,"analyzedSha":"82a973c04367123ae98bd9abdf80d9eda9b910e2","analyzedAt":"2026-08-14T16:46:43.225Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}