tracel-ai/burn · error

Failed to create cache directory for Gram Matrix Loss

Error message

Failed to create cache directory for Gram Matrix Loss

What it means

`get_cache_dir` in crates/burn-vision/src/loss/gram_matrix/weights.rs:25 panics when `create_dir_all` fails to create `~/.cache/burn-pretrained-models/loss/vgg19/`. The cache parent was resolvable (dirs::cache_dir() worked), but the directories could not actually be created on disk. This is a filesystem permission or state problem, not an environment problem.

Source

Thrown at crates/burn-vision/src/loss/gram_matrix/weights.rs:25

use std::fs::{File, create_dir_all, rename};
use std::io::Write;
use std::path::PathBuf;

const VGG19_URL: &str = "https://download.pytorch.org/models/vgg19-dcbb9e9d.pth";

/// Resolves and returns the local cache directory for the VGG19 weights.
///
/// Creates the directory `~/.cache/burn-pretrained-models/loss/vgg19/`
/// (or OS equivalent) if it does not already exist.
fn get_cache_dir() -> PathBuf {
    let cache_dir = dirs::cache_dir()
        .expect("Failed to get cache directory for Gram Matrix Loss")
        .join("burn-pretrained-models")
        .join("loss")
        .join("vgg19");

    if !cache_dir.exists() {
        create_dir_all(&cache_dir).expect("Failed to create cache directory for Gram Matrix Loss");
    }

    cache_dir
}

/// Downloads the pretrained weights to the `cache_path` if they don't exist already.
///
/// Requires an active internet connection on the first run. Subsequent runs will
/// use the locally cached `.pth` file.
fn download_weights_if_not_saved(cache_path: &PathBuf) {
    if !cache_path.exists() {
        let bytes = download_file_as_bytes(
            VGG19_URL,
            "Downloading VGG19 ImageNet weights for Gram Matrix Loss...",
        );

        // Write to a temporary file. If writing gets completed, then rename to the actual/correct name.
        // If writing is not completed, the file with the correct name (i.e. `cache_path`) will not exist

View on GitHub (pinned to d16f7ba2ed)

Solutions

  1. Check permissions on the cache path and fix ownership: `ls -la ~/.cache` then `chown -R $(id -u) ~/.cache`
  2. Remove a conflicting regular file if a path component like ~/.cache/burn-pretrained-models is a file, not a directory: `rm ~/.cache/burn-pretrained-models`
  3. Point the cache somewhere writable by setting XDG_CACHE_HOME to a writable directory
  4. Mount or remount the target filesystem read-write if it is read-only (containers: add an emptyDir volume for the cache path)

Example fix

// before: panic on mkdir failure
create_dir_all(&cache_dir).expect("Failed to create cache directory for Gram Matrix Loss");
// after: actionable error
create_dir_all(&cache_dir)
    .with_context(|| format!("Failed to create cache dir {} — check permissions", cache_dir.display()))?;
Defensive patterns

Strategy: validation

Validate before calling

// Ensure the target cache dir tree is creatable before calling the library
let base = dirs::cache_dir().expect("cache dir env");
let vgg19_dir = base.join("burn-pretrained-models/loss/vgg19");
std::fs::create_dir_all(&vgg19_dir)
    .unwrap_or_else(|e| panic!("cannot create {}: {e}; fix permissions", vgg19_dir.display()));
// also confirm no file occupies a path component
for anc in [base.join("burn-pretrained-models"), base.join("burn-pretrained-models/loss")] {
    assert!(!anc.is_file(), "{} is a file, not a directory — remove it", anc.display());
}

Type guard

fn cache_dir_creatable(base: &std::path::Path) -> bool {
    let probe = base.join("burn-pretrained-models/loss/vgg19");
    std::fs::create_dir_all(&probe).is_ok()
        && OpenOptions::new().write(true).create(true)
            .open(probe.join(".probe")).is_ok()
}

Try / catch

let result = std::panic::catch_unwind(||
    burn_vision::loss::gram_matrix::load_vgg19_weights(device)
);
if result.is_err() {
    eprintln!("failed to create vgg19 cache dir — check ~/.cache permissions and read-only mounts");
}

Prevention

When it happens

Trigger: Calling `load_vgg19_weights` when `~/.cache/burn-pretrained-models/loss/vgg19` does not exist and `create_dir_all` returns Err: parent directory not writable by the current user, a file already exists at one of the path components, or a read-only filesystem.

Common situations: Read-only container root filesystems (Kubernetes securityContext with readOnlyRootFilesystem); ~/.cache owned by root after an earlier sudo run; path collision where ~/.cache/burn-pretrained-models exists as a regular file; immutable/locked directories.

Understand the failure class

Background: Permission denied / not authorized / 403 Forbidden: access-control rejections when the caller lacks the required role, grant, or ownership — this error's family across 18 libraries.

Related errors


AI-assisted analysis of tracel-ai/burn@d16f7ba2ed (2026-09-05). Data as JSON: /api/errors/d7f12b1a65a78ba1. Report an issue: GitHub.