tracel-ai/burn · error

Failed to write weights

Error message

Failed to write weights

What it means

This panic comes from an `expect` in `download_if_needed` in crates/burn-train/src/metric/vision/lpips/weights.rs:63. The LPIPS metric downloads pretrained network weights, caches them on disk, and this expect fires when `File::write_all` fails to persist the already-downloaded bytes to the cache file. The download itself succeeded, so the failure is on the local filesystem side (disk, permissions, or I/O error during the write).

Source

Thrown at crates/burn-train/src/metric/vision/lpips/weights.rs:63

fn get_cache_dir() -> PathBuf {
    let cache_dir = dirs::cache_dir()
        .expect("Could not get cache directory")
        .join("burn-dataset")
        .join("lpips");

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

    cache_dir
}

/// Download file if not cached and return the cache path.
fn download_if_needed(url: &str, cache_path: &PathBuf, message: &str) {
    if !cache_path.exists() {
        let bytes = download_file_as_bytes(url, message);
        let mut file = File::create(cache_path).expect("Failed to create cache file");
        file.write_all(&bytes).expect("Failed to write weights");
    }
}

/// Download and load pretrained weights into an LPIPS module.
///
/// This loads both:
/// 1. ImageNet pretrained backbone weights (VGG16/AlexNet/SqueezeNet)
/// 2. LPIPS trained linear layer weights
///
/// Weights are cached in the user's cache directory to avoid re-downloading.
///
/// # Arguments
///
/// * `lpips` - The LPIPS module to load weights into.
/// * `net` - The network type (determines which weights to download).
///
/// # Returns
///

View on GitHub (pinned to d16f7ba2ed)

Solutions

  1. Free disk space in the cache partition (`df -h ~/.cache`) and delete any partial cache file, then retry
  2. Verify write permissions on the cache directory (`ls -ld ~/.cache/burn-pretrained-models`) and fix ownership/ACLs if needed
  3. Pre-download the weights manually to the expected cache path so the `download_if_needed` write path is skipped entirely
  4. Move the cache to a more reliable local filesystem (e.g. set HOME/XDG_CACHE_HOME to a local disk instead of an NFS mount)

Example fix

// before: unguarded write panics with 'Failed to write weights'
let mut file = File::create(cache_path).expect("Failed to create cache file");
file.write_all(&bytes).expect("Failed to write weights");
// after: clean error instead of panic
let mut file = File::create(cache_path)
    .map_err(|e| anyhow!("Failed to create cache file: {e}"))?;
file.write_all(&bytes)
    .with_context(|| format!("Failed to write weights to {}", cache_path.display()))?;
Defensive patterns

Strategy: try-catch

Validate before calling

// Rust: check writability and space before calling load_pretrained_weights
use std::fs::OpenOptions;
let cache_path = dirs::home_dir().unwrap().join(
    ".cache/burn-pretrained-models/metric/lpips/weights");
if let Some(parent) = cache_path.parent() {
    assert!(parent.exists() || std::fs::create_dir_all(parent).is_ok(),
        "cache dir not creatable");
}
// probe write access
OpenOptions::new().write(true).create(true)
    .open(cache_path.with_extension(".write-test"))
    .expect("cache path not writable");

Type guard

fn is_cache_writable(cache_path: &std::path::Path) -> bool {
    cache_path.parent().map(|p| p.is_dir()).unwrap_or(false)
        && OpenOptions::new().write(true).create(true)
            .open(cache_path.with_extension(".probe")).is_ok()
}

Try / catch

// catch_unwind since the library panics via expect
let result = std::panic::catch_unwind(|| {
    lpips::load_pretrained_weights(device)
});
match result {
    Ok(Ok(weights)) => {/* use weights */},
    Ok(Err(e)) => eprintln!("load failed: {e}"),
    Err(panic) => eprintln!("panicked while writing weights: {panic:?}"),
}

Prevention

When it happens

Trigger: Calling `load_pretrained_weights` for LPIPS when the cache file does not exist: `download_file_as_bytes` succeeds, `File::create` on the cache path succeeds, but `write_all(&bytes)` returns Err (e.g. disk filled up mid-write, file handle became invalid, or an I/O error such as EIO/ENOSPC).

Common situations: Disk quota or full filesystem after the download consumed the remaining space; container/CI runners with tiny tmpfs volumes; antivirus or backup software locking the newly created file; flaky network mounts where the file descriptor goes stale between create and write.

Related errors


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