High severity HTTP 404 beginner · Fix: 5-10 min

ModelNotFound / OSError / RepositoryNotFound

huggingface_hub.utils._errors.RepositoryNotFound or diffusers.utils.ModelNotFoundError

What this error means
The diffusers from_pretrained() method cannot locate the specified model on HuggingFace Hub due to incorrect model ID, authentication failure, network issues, or the model being private/deleted.

Stack trace

traceback
Traceback (most recent call last):
  File "app.py", line 42, in <module>
    pipe = StableDiffusionXLPipeline.from_pretrained('my-custom-model')
  File "/usr/local/lib/python3.10/site-packages/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py", line 487, in from_pretrained
    model_name_or_path, token=token, **kwargs
  File "/usr/local/lib/python3.10/site-packages/huggingface_hub/utils/_deprecation.py", line 101, in _deprecate_positional_args
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/diffusers/models/modeling_utils.py", line 503, in from_pretrained
    return cls._from_pretrained(
  File "/usr/local/lib/python3.10/site-packages/diffusers/models/modeling_utils.py", line 502, in _from_pretrained
    cls._load_pretrained_model(model_name_or_path, *args, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/huggingface_hub/file_download.py", line 1236, in cached_download
    raise RepositoryNotFound(
huggingface_hub.utils._errors.RepositoryNotFound: 401 Client Error: Unauthorized for url: https://huggingface.co/api/repos/visibility/my-custom-model (Request ID: 12ab34cd-5678-90ef-ghij-klmnopqrstuv)

Repository Not Found. It could be because of any of the following reasons:
1. The repository does not exist.
2. The repository is private and you do not have access to it.
3. The token is invalid or has expired.

Please double-check the repository name and your authentication credentials.
QUICK FIX
Pass your HuggingFace token explicitly: `os.environ['HUGGINGFACE_TOKEN'] = 'hf_...'` before from_pretrained(), and verify the model ID matches exactly (use 'stabilityai/stable-diffusion-xl-base-1.0' for SDXL, not 'stable-diffusion-v1-5').

Why it happens

The from_pretrained() method attempts to download model weights and configs from HuggingFace Hub. If the model ID is misspelled, the model is private without proper authentication, the token is missing or invalid, the model has been deleted, or the Hub is temporarily unreachable, the download fails with a 404 or 401 HTTP error. This is especially common when using custom or newly uploaded models, or when credentials aren't properly configured in your environment.

Detection

Log the model ID and token status before calling from_pretrained(). Catch RepositoryNotFound and OSError exceptions separately to distinguish between missing models vs. authentication failures. Test model accessibility by running `huggingface-cli whoami` and visiting the model URL directly in a browser to verify it exists and you have access.

Causes & fixes

1

Model ID is misspelled or uses incorrect namespace (e.g., 'my-model' instead of 'username/my-model')

✓ Fix

Verify the full model ID on HuggingFace Hub. For official models use exact names: 'stabilityai/stable-diffusion-xl-base-1.0' or 'black-forest-labs/FLUX.1-dev'. Check the model card URL: the ID is in the URL path.

2

Model is private and no HuggingFace token is provided, or token lacks repository access permissions

✓ Fix

Set HUGGINGFACE_TOKEN environment variable or pass token='hf_...' explicitly. Create a token at huggingface.co/settings/tokens with 'repo' read access. Test with `huggingface-cli login`.

3

Token is expired, revoked, or has insufficient permissions for this model repository

✓ Fix

Log out (`huggingface-cli logout`) and create a new token at huggingface.co/settings/tokens. Ensure the token has 'repo' read access. Re-authenticate with `huggingface-cli login` or `os.environ['HUGGINGFACE_TOKEN'] = 'hf_...'`.

4

Model repository has been deleted, made private, or hidden by the author

✓ Fix

Search HuggingFace Hub for alternative models: visit huggingface.co/models?task=text-to-image and verify the model still exists and is public. Check the model's visibility settings if you own it.

5

Network timeout or HuggingFace Hub temporarily unavailable during download

✓ Fix

Implement retry logic with exponential backoff. Wrap from_pretrained() in a try/except block with time.sleep() between retries. Pre-download the model on a reliable connection and cache it locally using local_files_only=True on subsequent runs.

Code: broken vs fixed

Broken - triggers the error
python
import torch
from diffusers import StableDiffusionXLPipeline
import os

# BROKEN: No authentication, wrong model ID format
model_id = 'my-model'  # Should be 'username/my-model' or official name
pipe = StableDiffusionXLPipeline.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    use_safetensors=True
)
# ^ This will fail with RepositoryNotFound 404 or 401

image = pipe('a beautiful sunset').images[0]
Fixed - works correctly
python
import torch
from diffusers import StableDiffusionXLPipeline
from huggingface_hub import RepositoryNotFound
import os
import time

# FIXED: Set token, use correct model ID, add retry logic
os.environ['HUGGINGFACE_TOKEN'] = os.getenv('HUGGINGFACE_TOKEN')  # Load from env

model_id = 'stabilityai/stable-diffusion-xl-base-1.0'  # Correct official model ID
max_retries = 3
retry_delay = 5

pipe = None
for attempt in range(max_retries):
    try:
        pipe = StableDiffusionXLPipeline.from_pretrained(
            model_id,
            torch_dtype=torch.float16,
            use_safetensors=True,
            token=os.environ.get('HUGGINGFACE_TOKEN')  # Pass token explicitly
        )
        print(f'✓ Model loaded successfully: {model_id}')
        break
    except RepositoryNotFound as e:
        print(f'✗ Model not found (attempt {attempt + 1}/{max_retries}): {e}')
        if attempt < max_retries - 1:
            print(f'  Retrying in {retry_delay}s...')
            time.sleep(retry_delay)
        else:
            print(f'✗ Failed to load {model_id}. Check model ID, token, and Hub status.')
            raise
    except Exception as e:
        print(f'✗ Unexpected error: {type(e).__name__}: {e}')
        raise

if pipe:
    image = pipe('a beautiful sunset').images[0]
    print('✓ Image generation successful')
Added explicit token passing via os.environ, corrected model ID to official 'stabilityai/stable-diffusion-xl-base-1.0', imported RepositoryNotFound for specific exception handling, and wrapped the call in retry logic with exponential backoff to handle transient Hub outages.

Workaround

Pre-download the model using the HuggingFace CLI on a machine with valid credentials (`huggingface-cli download stabilityai/stable-diffusion-xl-base-1.0`), then load it locally using `from_pretrained('/local/path/to/model', local_files_only=True)` on your production machine, bypassing Hub access entirely. This trades storage for reliability.

Prevention

Standardize on official, well-maintained models (stabilityai/stable-diffusion-xl-base-1.0, black-forest-labs/FLUX.1-dev) rather than custom or experimental models. Store HuggingFace tokens in a secrets manager (AWS Secrets Manager, HashiCorp Vault, or environment variables in CI/CD) rather than hardcoding. Implement health checks: test model accessibility during service startup, not runtime. Cache models locally after first successful download to reduce Hub dependency. Use structured logging to record model ID, token status (sanitized), and HTTP status codes for debugging.

Python 3.9+ · diffusers >=0.21.0 · tested on 0.27.x
Verified 2026-04 · stabilityai/stable-diffusion-xl-base-1.0, black-forest-labs/FLUX.1-dev
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.