{"record":{"id":"05764db516c33cb3","repo":"tracel-ai/burn","slug":"failed-to-write-vgg19-weights-to-the-cache-file-fo","errorCode":null,"errorMessage":"Failed to write VGG19 weights to the cache file for Gram Matrix Loss","messagePattern":"Failed to write VGG19 weights to the cache file for Gram Matrix Loss","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-vision/src/loss/gram_matrix/weights.rs","lineNumber":49,"sourceCode":"/// Downloads the pretrained weights to the `cache_path` if they don't exist already.\n///\n/// Requires an active internet connection on the first run. Subsequent runs will\n/// use the locally cached `.pth` file.\nfn download_weights_if_not_saved(cache_path: &PathBuf) {\n    if !cache_path.exists() {\n        let bytes = download_file_as_bytes(\n            VGG19_URL,\n            \"Downloading VGG19 ImageNet weights for Gram Matrix Loss...\",\n        );\n\n        // Write to a temporary file. If writing gets completed, then rename to the actual/correct name.\n        // If writing is not completed, the file with the correct name (i.e. `cache_path`) will not exist\n        // so this code block can run again which is the desired behavior.\n        let temp_path = cache_path.with_extension(\"pth.tmp\");\n        let mut file = File::create(&temp_path)\n            .expect(\"Failed to create VGG19 cache file for Gram Matrix Loss\");\n        file.write_all(&bytes)\n            .expect(\"Failed to write VGG19 weights to the cache file for Gram Matrix Loss\");\n\n        rename(temp_path, cache_path)\n            .expect(\"Failed to rename temporary file to the actual VGG19 cache file name for Gram Matrix Loss\");\n    }\n}\n\n/// Loads ImageNet pretrained weights into the provided VGG19 feature extractor.\n///\n/// This function downloads the official PyTorch VGG19 weights, remaps the keys\n/// from PyTorch's `features.X` format to Burn's `convX_Y` format, and loads\n/// them into the module.\n///\n/// # Arguments\n///\n/// - `vgg19` - An initialized VGG19 module with random weights.\n///\n/// # Returns\n///","sourceCodeStart":31,"sourceCodeEnd":67,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-vision/src/loss/gram_matrix/weights.rs#L31-L67","documentation":"`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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Free space on the cache filesystem (`df -h ~/.cache`) — ENOSPC is the most common cause for a mid-write failure","Delete any leftover `*.pth.tmp` file and retry the download","Move the cache to a larger/reliable volume via `XDG_CACHE_HOME` pointing at a bigger mount","Check `dmesg`/system logs for I/O errors on the storage device if the problem recurs after freeing space"],"exampleFix":"// before: panic mid-write\nlet mut file = File::create(&temp_path)\n    .expect(\"Failed to create VGG19 cache file for Gram Matrix Loss\");\nfile.write_all(&bytes)\n    .expect(\"Failed to write VGG19 weights to the cache file for Gram Matrix Loss\");\n// after: clean up the temp file on failure\nlet mut file = File::create(&temp_path)\n    .with_context(|| format!(\"create {} failed\", temp_path.display()))?;\nif let Err(e) = file.write_all(&bytes) {\n    let _ = std::fs::remove_file(&temp_path);\n    return Err(anyhow!(\"write VGG19 weights failed: {e}\"));\n}","handlingStrategy":"retry","validationCode":"// Check available space on the cache filesystem before triggering the download\nlet cache_dir = dirs::cache_dir().unwrap().join(\"burn-pretrained-models/loss/vgg19\");\nlet stat = nix::sys::statvfs::statvfs(&cache_dir).unwrap();\nlet free_mb = stat.blocks_available() as u64 * stat.fragment_size() / 1024 / 1024;\nassert!(free_mb > 1024, \"only {free_mb} MiB free at cache location; VGG19 needs headroom\");","typeGuard":"fn has_enough_space(path: &std::path::Path, min_bytes: u64) -> bool {\n    nix::sys::statvfs::statvfs(path).map(|s| {\n        s.blocks_available() as u64 * s.fragment_size() >= min_bytes\n    }).unwrap_or(false)\n}","tryCatchPattern":"match std::panic::catch_unwind(||\n    burn_vision::loss::gram_matrix::load_vgg19_weights(device)\n) {\n    Ok(_) => {},\n    Err(_) => {\n        // temp file is left behind; remove it and retry once after freeing space\n        let _ = std::fs::remove_file(\n            dirs::cache_dir().unwrap().join(\"burn-pretrained-models/loss/vgg19/weights.pth.tmp\"));\n        eprintln!(\"VGG19 weight write failed; cleaned temp file, retry after checking disk space\");\n    }\n}","preventionTips":["Check disk space before large model downloads (df or statvfs)","Avoid network/USB mounts for the model cache; prefer local SSD","Set container ephemeral-storage limits high enough for cached weights","Treat any *.pth.tmp leftover as a signal of a failed write and clean it before retrying"],"tags":["filesystem","io","disk-space","cache","panics","burn"],"backgroundTag":"cache-file-write-failed","analyzedSha":"d16f7ba2ed0d41408189384044cc886fb4c8f957","analyzedAt":"2026-09-05T13:19:14.260Z","contentChangedAt":"2026-09-05T13:19:14.260Z","schemaVersion":2},"datasetVersion":"2026-09-12T17:17:11.597Z"}