ultralytics/yolov5 · error · ModuleNotFoundError

--model {opt.model} not found. Available models are: \n

Error message

--model {opt.model} not found. Available models are: \n

What it means

classify/train.py raises ModuleNotFoundError when the --model value is neither an existing file, nor a string ending in .pt, nor a key in torchvision.models.__dict__. The message lists the models available from the ultralytics/yolov5 GitHub hub so the user can pick a valid name. It fires in the classify training entrypoint after dataset setup, right before the model is constructed.

Source

Thrown at classify/train.py:149

        testloader = create_classification_dataloader(
            path=test_dir,
            imgsz=imgsz,
            batch_size=bs // WORLD_SIZE * 2,
            augment=False,
            cache=opt.cache,
            rank=-1,
            workers=nw,
        )

    # Model
    with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
        if Path(opt.model).is_file() or opt.model.endswith(".pt"):
            model = attempt_load(opt.model, device="cpu", fuse=False)
        elif opt.model in torchvision.models.__dict__:  # TorchVision models i.e. resnet50, efficientnet_b0
            model = torchvision.models.__dict__[opt.model](weights="IMAGENET1K_V1" if pretrained else None)
        else:
            m = hub.list("ultralytics/yolov5")  # + hub.list('pytorch/vision')  # models
            raise ModuleNotFoundError(f"--model {opt.model} not found. Available models are: \n" + "\n".join(m))
        if isinstance(model, DetectionModel):
            LOGGER.warning("pass YOLOv5 classifier model with '-cls' suffix, i.e. '--model yolov5s-cls.pt'")
            model = ClassificationModel(model=model, nc=nc, cutoff=opt.cutoff or 10)  # convert to classification model
        reshape_classifier_output(model, nc)  # update class count
    for m in model.modules():
        if not pretrained and hasattr(m, "reset_parameters"):
            m.reset_parameters()
        if isinstance(m, torch.nn.Dropout) and opt.dropout is not None:
            m.p = opt.dropout  # set dropout
    for p in model.parameters():
        p.requires_grad = True  # for training
    model = model.to(device)

    # Info
    if RANK in {-1, 0}:
        model.names = trainloader.dataset.classes  # attach class names
        model.transforms = testloader.dataset.torch_transforms  # attach inference transforms
        model_info(model)

View on GitHub (pinned to 20d1d78a08)

Solutions

  1. Use a shipped classifier checkpoint name, e.g. --model yolov5n-cls.pt (the .pt suffix routes to attempt_download).
  2. If pointing at a local checkpoint, verify the path exists: python -c "from pathlib import Path; print(Path('my.pt').is_file())" before training.
  3. For torchvision backbones, confirm the name is valid for your installed version: python -c "import torchvision; print('resnet50' in torchvision.models.__dict__)".
  4. Re-run and pick a name from the model list printed in the error message itself.

Example fix

# before
python classify/train.py --model yolov5s-clss --data imagenet ...

# after
python classify/train.py --model yolov5s-cls.pt --data imagenet ...
Defensive patterns

Strategy: validation

Validate before calling

from pathlib import Path
import torchvision

def valid_classify_model(name: str) -> bool:
    return Path(name).is_file() or name.endswith('.pt') or name in torchvision.models.__dict__

assert valid_classify_model(opt.model), f"--model {opt.model} is not a file, .pt, or torchvision model"

Type guard

def is_loadable_model_name(name: str) -> bool:
    """True if classify/train.py will accept this --model value."""
    return Path(name).is_file() or name.endswith(".pt") or name in torchvision.models.__dict__

Prevention

When it happens

Trigger: Running classify/train.py with a misspelled or nonexistent --model (e.g. --model yolov5s-clss or --model foo) where the file does not exist on disk; passing a torchvision architecture name that is invalid for the installed torchvision version; passing a bare name like 'resnet50' when torchvision was not imported correctly or the name was removed.

Common situations: Typos in shell scripts or wandb sweeps; using a custom checkpoint path that has not been downloaded yet; assuming any torchvision name works on an old torchvision pinned by YOLOv5 CI; forgetting the '-cls' suffix convention so users type arbitrary names.

Related errors


AI-assisted analysis of ultralytics/yolov5@20d1d78a08 (2026-08-15). Data as JSON: /api/errors/240aca7fdee902f2. Report an issue: GitHub.