AUTOMATIC1111/stable-diffusion-webui · error · Exception

bad file inside {filename}: {name}

Error message

bad file inside {filename}: {name}

What it means

check_pt treats new-format PyTorch files as zip archives and validates every member name against allowed_zip_names_re, which only permits '<dir>/version', '<dir>/byteorder', '<dir>/data.pkl', '<dir>/.data/serialization_id' and '<dir>/data/<number>'. Any other entry (extra folders, sibling files, typical zip-bomb path tricks) raises 'bad file inside'. This is a structural safety check on untrusted checkpoints.

Source

Thrown at modules/safe.py:76

            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
        with zipfile.ZipFile(filename) as z:
            check_zip_filenames(filename, z.namelist())

            # find filename of data.pkl in zip file: '<directory name>/data.pkl'
            data_pkl_filenames = [f for f in z.namelist() if data_pkl_re.match(f)]
            if len(data_pkl_filenames) == 0:
                raise Exception(f"data.pkl not found in {filename}")
            if len(data_pkl_filenames) > 1:
                raise Exception(f"Multiple data.pkl found in {filename}")
            with z.open(data_pkl_filenames[0]) as file:
                unpickler = RestrictedUnpickler(file)
                unpickler.extra_handler = extra_handler

View on GitHub (pinned to 82a973c043)

Solutions

  1. Re-save the model properly with torch.save(state_dict, path) from a trusted environment so the archive layout is canonical.
  2. Prefer the .safetensors format for distribution — it sidesteps pickle/zip checks entirely.
  3. Do not edit or add files inside .pt/.ckpt zip archives; keep them exactly as exported.

Example fix

# before: hand-zipped archive with extra files
# model.zip contains: data.pkl, data/0, README.md  -> 'bad file inside'

# after: canonical re-save
import torch
torch.save(state_dict, 'model.pt')  # produces only allowed member names
Defensive patterns

Strategy: validation

Validate before calling

import re, zipfile

allowed = re.compile(r"^([^/]+)/((data/\d+)|version|byteorder|.data/serialization_id|(data\.pkl))$")

def pt_zip_ok(path):
    with zipfile.ZipFile(path) as z:
        return all(allowed.match(n) for n in z.namelist())

assert pt_zip_ok('model.pt'), 'archive layout is not a canonical torch checkpoint'

Type guard

def is_canonical_torch_zip(path: str) -> bool:
    import re, zipfile
    allowed = re.compile(r"^([^/]+)/((data/\d+)|version|byteorder|.data/serialization_id|(data\.pkl))$")
    try:
        with zipfile.ZipFile(path) as z:
            return all(allowed.match(n) for n in z.namelist())
    except zipfile.BadZipFile:
        return False

Try / catch

try:
    weights = torch.load(path)
except Exception as e:
    if 'bad file inside' in str(e):
        raise RuntimeError(f'{path} has a non-standard archive layout; re-save with torch.save or use safetensors')
    raise

Prevention

When it happens

Trigger: Loading a .pt/.ckpt that is a zip whose archive contains unexpected member names — e.g. a repacked checkpoint with extra files added, a directory prefix change, nested folders, or a hand-zipped model that does not follow the torch archive layout.

Common situations: Users re-zipping checkpoints (adding READMEs or metadata files inside the archive); files produced by unusual saving code (custom zipfile writers); rarely, crafted archives attempting path traversal.

Related errors


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