tracel-ai/burn · error

Failed to write VGG19 weights to the cache file for Gram…

Error message

Failed to write VGG19 weights to the cache file for Gram Matrix Loss

What it means

`download_weights_if_not_saved` in crates/burn-vision/src/loss/gram_matrix/weights.rs:49 panics when `write_all` fails after the temporary `.pth.tmp` VGG19 file was created successfully. The downloaded bytes could not be fully written to the temp file. Because the temp file is only renamed onto the real cache path after a complete write, the cache remains in a consistent (empty) state and the next run will retry the download.

Solutions

  1. Free space on the cache filesystem (`df -h ~/.cache`) — ENOSPC is the most common cause for a mid-write failure
  2. Delete any leftover `*.pth.tmp` file and retry the download
  3. Move the cache to a larger/reliable volume via `XDG_CACHE_HOME` pointing at a bigger mount
  4. Check `dmesg`/system logs for I/O errors on the storage device if the problem recurs after freeing space

Example fix

// before: panic mid-write
let mut file = File::create(&temp_path)
    .expect("Failed to create VGG19 cache file for Gram Matrix Loss");
file.write_all(&bytes)
    .expect("Failed to write VGG19 weights to the cache file for Gram Matrix Loss");
// after: clean up the temp file on failure
let mut file = File::create(&temp_path)
    .with_context(|| format!("create {} failed", temp_path.display()))?;
if let Err(e) = file.write_all(&bytes) {
    let _ = std::fs::remove_file(&temp_path);
    return Err(anyhow!("write VGG19 weights failed: {e}"));
}
Defensive patterns

Strategy: retry

Validate before calling

// Check available space on the cache filesystem before triggering the download
let cache_dir = dirs::cache_dir().unwrap().join("burn-pretrained-models/loss/vgg19");
let stat = nix::sys::statvfs::statvfs(&cache_dir).unwrap();
let free_mb = stat.blocks_available() as u64 * stat.fragment_size() / 1024 / 1024;
assert!(free_mb > 1024, "only {free_mb} MiB free at cache location; VGG19 needs headroom");

Type guard

fn has_enough_space(path: &std::path::Path, min_bytes: u64) -> bool {
    nix::sys::statvfs::statvfs(path).map(|s| {
        s.blocks_available() as u64 * s.fragment_size() >= min_bytes
    }).unwrap_or(false)
}

Try / catch

match std::panic::catch_unwind(||
    burn_vision::loss::gram_matrix::load_vgg19_weights(device)
) {
    Ok(_) => {},
    Err(_) => {
        // temp file is left behind; remove it and retry once after freeing space
        let _ = std::fs::remove_file(
            dirs::cache_dir().unwrap().join("burn-pretrained-models/loss/vgg19/weights.pth.tmp"));
        eprintln!("VGG19 weight write failed; cleaned temp file, retry after checking disk space");
    }
}

Prevention

When it happens

Trigger: Calling `load_vgg19_weights` when the cache file is absent, `File::create` on `.pth.tmp` succeeded, but `write_all(&bytes)` fails — typically ENOSPC (disk filled mid-write) or an EIO from the underlying storage.

Common situations: Large VGG19 weights exhausting remaining disk space during the write; flaky network filesystem or USB storage dropping errors mid-write; disk quotas exceeded for the user's cache partition; container ephemeral storage limit hit.

Related errors


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

Appendix: source

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

/// 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
        // so this code block can run again which is the desired behavior.
        let temp_path = cache_path.with_extension("pth.tmp");
        let mut file = File::create(&temp_path)
            .expect("Failed to create VGG19 cache file for Gram Matrix Loss");
        file.write_all(&bytes)
            .expect("Failed to write VGG19 weights to the cache file for Gram Matrix Loss");

        rename(temp_path, cache_path)
            .expect("Failed to rename temporary file to the actual VGG19 cache file name for Gram Matrix Loss");
    }
}

/// Loads ImageNet pretrained weights into the provided VGG19 feature extractor.
///
/// This function downloads the official PyTorch VGG19 weights, remaps the keys
/// from PyTorch's `features.X` format to Burn's `convX_Y` format, and loads
/// them into the module.
///
/// # Arguments
///
/// - `vgg19` - An initialized VGG19 module with random weights.
///
/// # Returns
///

View on GitHub (pinned to d16f7ba2ed)