pytorch - 💡(How to fix) Fix `_streaming_load` crashes on zero-element tensor storages (`torch.frombuffer` rejects empty buffer) [1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#180481Fetched 2026-04-17 08:22:14
View on GitHub
Comments
0
Participants
1
Timeline
29
Reactions
0
Participants
Timeline (top)
mentioned ×13subscribed ×13labeled ×2closed ×1

torch.distributed._serialization._streaming_load raises ValueError: both buffer length (0) and count (-1) must not be 0 when deserializing a state dict that contains zero-element tensors. _streaming_save handles them correctly, but _streaming_load fails on the read path.

This breaks TorchFT peer recovery when FSDP2 is used, because fully_shard can produce zero-element shards when small parameters (e.g. bias vectors) are split across ranks.

Error Message

ValueError: both buffer length (0) and count (-1) must not be 0

Root Cause

In _PseudoZipFile.read_from (torch/distributed/_serialization.py#L54-L70):

def read_from(self, f):
    entries = _weights_only_unpickler.load(f)
    for entry in entries:
        data = f.read(entry.length)
        if entry.is_storage:
            storage = torch.frombuffer(   # <- fails when entry.length == 0
                data,                      #    because data is b'' (empty bytes)
                dtype=torch.uint8,
            ).untyped_storage()

torch.frombuffer does not accept a zero-length buffer. When entry.length == 0 (zero-element tensor storage), f.read(0) returns b"", and torch.frombuffer(b"", dtype=torch.uint8) raises the error.

The write path (write_to) handles this correctly — UntypedStorage._write_file writes 0 bytes for an empty storage, and the entry is recorded with length=0.

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 224 On-line CPU(s) list: 0-223 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Platinum 8480+ CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 56 Socket(s): 2 Stepping: 8 CPU(s) scaling MHz: 41% CPU max MHz: 3800.0000 CPU min MHz: 800.0000 BogoMIPS: 4000.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 5.3 MiB (112 instances) L1i cache: 3.5 MiB (112 instances) L2 cache: 224 MiB (112 instances) L3 cache: 210 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-55,112-167 NUMA node1 CPU(s): 56-111,168-223 Vulnerability Gather data sampling: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Code Example

import torch
import io
from torch.distributed._serialization import _streaming_save, _streaming_load

buf = io.BytesIO()
_streaming_save({"weight": torch.randn(10), "bias": torch.empty(0)}, buf)

buf.seek(0)
loaded = _streaming_load(buf, weights_only=False)  # ValueError

---

ValueError: both buffer length (0) and count (-1) must not be 0

---

def read_from(self, f):
    entries = _weights_only_unpickler.load(f)
    for entry in entries:
        data = f.read(entry.length)
        if entry.is_storage:
            storage = torch.frombuffer(   # <- fails when entry.length == 0
                data,                      #    because data is b'' (empty bytes)
                dtype=torch.uint8,
            ).untyped_storage()

---

[ft::0:.../2 - step 1000] got exception in recovery: both buffer length (0) and count (-1) must not be 0
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Description

torch.distributed._serialization._streaming_load raises ValueError: both buffer length (0) and count (-1) must not be 0 when deserializing a state dict that contains zero-element tensors. _streaming_save handles them correctly, but _streaming_load fails on the read path.

This breaks TorchFT peer recovery when FSDP2 is used, because fully_shard can produce zero-element shards when small parameters (e.g. bias vectors) are split across ranks.

Reproduction

import torch
import io
from torch.distributed._serialization import _streaming_save, _streaming_load

buf = io.BytesIO()
_streaming_save({"weight": torch.randn(10), "bias": torch.empty(0)}, buf)

buf.seek(0)
loaded = _streaming_load(buf, weights_only=False)  # ValueError
ValueError: both buffer length (0) and count (-1) must not be 0

Root Cause

In _PseudoZipFile.read_from (torch/distributed/_serialization.py#L54-L70):

def read_from(self, f):
    entries = _weights_only_unpickler.load(f)
    for entry in entries:
        data = f.read(entry.length)
        if entry.is_storage:
            storage = torch.frombuffer(   # <- fails when entry.length == 0
                data,                      #    because data is b'' (empty bytes)
                dtype=torch.uint8,
            ).untyped_storage()

torch.frombuffer does not accept a zero-length buffer. When entry.length == 0 (zero-element tensor storage), f.read(0) returns b"", and torch.frombuffer(b"", dtype=torch.uint8) raises the error.

The write path (write_to) handles this correctly — UntypedStorage._write_file writes 0 bytes for an empty storage, and the entry is recorded with length=0.

Context

This was found while testing TorchFT fault-tolerant training with FSDP2. TorchFT's HTTPTransport uses _streaming_save / _streaming_load for in-memory checkpoint transfer between replicas during peer recovery. When FSDP2 shards a small parameter (e.g. a 64-dim bias) across 4 ranks, some ranks end up with zero-element shards. The healthy replica serializes its state dict (including empty shards) successfully, but the recovering replica fails to deserialize it.

Symptoms: recovery fails on ranks 1-3 (which hold the empty shards) but succeeds on rank 0. The error message does not mention tensors or serialization, making it hard to diagnose:

[ft::0:.../2 - step 1000] got exception in recovery: both buffer length (0) and count (-1) must not be 0

Versions

PyTorch version: 2.8.0+cu128 Is debug build: False CUDA used to build PyTorch: 12.8 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64) GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0 Clang version: Could not collect CMake version: Could not collect Libc version: glibc-2.39

Python version: 3.12.12 | packaged by conda-forge | (main, Oct 22 2025, 23:25:55) [GCC 14.3.0] (64-bit runtime) Python platform: Linux-5.15.0-122-generic-x86_64-with-glibc2.39 Is CUDA available: False CUDA runtime version: No CUDA CUDA_MODULE_LOADING set to: N/A GPU models and configuration: No CUDA Nvidia driver version: No CUDA cuDNN version: No CUDA Is XPU available: False HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True Caching allocator config: N/A

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 224 On-line CPU(s) list: 0-223 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Platinum 8480+ CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 56 Socket(s): 2 Stepping: 8 CPU(s) scaling MHz: 41% CPU max MHz: 3800.0000 CPU min MHz: 800.0000 BogoMIPS: 4000.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 5.3 MiB (112 instances) L1i cache: 3.5 MiB (112 instances) L2 cache: 224 MiB (112 instances) L3 cache: 210 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-55,112-167 NUMA node1 CPU(s): 56-111,168-223 Vulnerability Gather data sampling: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] Could not collect [conda] Could not collect

cc @awgu @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @pragupta @msaroufim @dcci @aditvenk @xmfan @weifengpy

extent analysis

TL;DR

The most likely fix is to modify the _PseudoZipFile.read_from method to handle zero-length buffers correctly when deserializing state dictionaries containing zero-element tensors.

Guidance

  • Identify the line of code in _PseudoZipFile.read_from where torch.frombuffer is called with a potentially zero-length buffer and add a conditional check to handle this case.
  • Consider adding a special case to handle zero-element tensors when deserializing state dictionaries to prevent the ValueError from being raised.
  • Review the write_to method in _PseudoZipFile to ensure it correctly handles zero-length buffers when serializing state dictionaries.
  • Test the modified code with the provided reproduction example to verify the fix.

Example

def read_from(self, f):
    entries = _weights_only_unpickler.load(f)
    for entry in entries:
        data = f.read(entry.length)
        if entry.is_storage:
            if entry.length == 0:  # Handle zero-length buffer
                storage = torch.Storage([])  # Create an empty storage
            else:
                storage = torch.frombuffer(data, dtype=torch.uint8).untyped_storage()

Notes

The provided fix assumes that the issue is solely due to the handling of zero-length buffers in the _PseudoZipFile.read_from method. However, the root cause may be more complex, and additional modifications may be necessary to fully resolve the issue.

Recommendation

Apply the workaround by modifying the _PseudoZipFile.read_from method to handle zero-length buffers correctly, as this is the most direct way to address the issue without waiting for a potential fix in a future version of PyTorch.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

pytorch - 💡(How to fix) Fix `_streaming_load` crashes on zero-element tensor storages (`torch.frombuffer` rejects empty buffer) [1 participants]