pytorch - 💡(How to fix) Fix PackageImporter.load_pickle() race can silently deserialize the wrong tensor across concurrent loads [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#180307Fetched 2026-04-15 06:18:43
View on GitHub
Comments
0
Participants
1
Timeline
2
Reactions
0
Participants
Timeline (top)
labeled ×2

A race condition in torch.package.PackageImporter.load_pickle() can silently deserialize the wrong tensor data when multiple threads reuse the same PackageImporter instance. Under concurrent reduce_package unpickling, one thread can observe another thread's deserialization storage context and restore the wrong resource without any exception.

Error Message

import importlib.util import shutil import sys import threading from pathlib import Path from textwrap import dedent

import torch from torch.package import PackageExporter, PackageImporter

def build_helper_module(outdir: Path) -> object: module_path = outdir / "race_confusion_mod.py" module_path.write_text( dedent( """ import threading import time import torch

        victim_ready = threading.Event()
        holder_ready = threading.Event()

        class VictimObj:
            def __reduce_package__(self, exporter):
                return (unpackage_victim, ())

        class HolderObj:
            def __reduce_package__(self, exporter):
                return (unpackage_holder, ())

        def unpackage_victim(importer):
            victim_ready.set()
            if not holder_ready.wait(5):
                raise RuntimeError("holder callback did not run in time")
            return torch.tensor(
                importer.storage_context.get_storage("0.storage", torch.float32)._typed_storage(),
                dtype=torch.float32,
            ).clone()

        def unpackage_holder(importer):
            holder_ready.set()
            time.sleep(0.5)
            return "holder-ok"
        """
    ),
    encoding="utf-8",
)

spec = importlib.util.spec_from_file_location("race_confusion_mod", module_path)
if spec is None or spec.loader is None:
    raise RuntimeError("failed to create import spec for helper module")
module = importlib.util.module_from_spec(spec)
sys.modules["race_confusion_mod"] = module
spec.loader.exec_module(module)
return module

def main() -> None: outdir = Path(file).resolve().parent / "artifacts" if outdir.exists(): shutil.rmtree(outdir) outdir.mkdir(parents=True, exist_ok=True)

helper_module = build_helper_module(outdir)
victim = helper_module.VictimObj()
holder = helper_module.HolderObj()

package_path = outdir / "race_confusion_package.pt"
payload = torch.tensor([9.0, 10.0, 11.0, 12.0], dtype=torch.float32)
with package_path.open("wb") as package_file:
    with PackageExporter(package_file) as exporter:
        exporter.intern("race_confusion_mod")
        exporter.save_pickle("res", "a.pkl", {"probe": victim})
        exporter.save_pickle("res", "b.pkl", {"payload": payload, "probe": holder})

importer = PackageImporter(str(package_path))
packaged_module = importer.import_module("race_confusion_mod")

results: dict[str, object] = {}
errors: dict[str, str] = {}

def load_a() -> None:
    try:
        results["a"] = importer.load_pickle("res", "a.pkl")
    except Exception as exc:
        errors["a"] = f"{type(exc).__name__}: {exc}"

def load_b() -> None:
    try:
        if not packaged_module.victim_ready.wait(5):
            raise RuntimeError("victim callback did not run in time")
        results["b"] = importer.load_pickle("res", "b.pkl")
    except Exception as exc:
        errors["b"] = f"{type(exc).__name__}: {exc}"

threads = [
    threading.Thread(target=load_a, args=()),
    threading.Thread(target=load_b, args=()),
]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join(timeout=10)

if any(thread.is_alive() for thread in threads):
    raise RuntimeError("threads did not finish in time")
if errors:
    raise RuntimeError(f"unexpected errors: {errors}")

loaded_a = results["a"]
loaded_b = results["b"]
if not isinstance(loaded_a, dict) or not isinstance(loaded_b, dict):
    raise RuntimeError("unexpected result types")

print("package_path", package_path, flush=True)
print("a_probe", loaded_a["probe"], flush=True)
print("b_payload", loaded_b["payload"], flush=True)
print(
    "a_probe_matches_b_payload",
    torch.equal(loaded_a["probe"], loaded_b["payload"]),
    flush=True,
)
print("errors", errors, flush=True)

if name == "main": main()

Root Cause

Details

The root cause is in PackageImporter in torch/package/package_importer.py (lines 150-152, 276-285, and 294-306 in the local source tree). The importer stores storage_context and last_map_location as instance-level mutable fields, then passes the importer object itself into reduce_package callbacks via return func(self, *args). During load_pickle(), set_deserialization_context() temporarily writes those fields on the shared importer object and clears them afterward.

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): 56 On-line CPU(s) list: 0-55 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Gold 6330 CPU @ 2.00GHz CPU family: 6 Model: 106 Thread(s) per core: 1 Core(s) per socket: 28 Socket(s): 2 Stepping: 6 CPU max MHz: 2000.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 pni pclmulqdq dtes64 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 invpcid_single intel_ppin 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 wbnoinvd dtherm arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 2.6 MiB (56 instances) L1i cache: 1.8 MiB (56 instances) L2 cache: 70 MiB (56 instances) L3 cache: 84 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-27 NUMA node1 CPU(s): 28-55 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT disabled 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 SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Code Example

import importlib.util
import shutil
import sys
import threading
from pathlib import Path
from textwrap import dedent

import torch
from torch.package import PackageExporter, PackageImporter


def build_helper_module(outdir: Path) -> object:
    module_path = outdir / "race_confusion_mod.py"
    module_path.write_text(
        dedent(
            """
            import threading
            import time
            import torch

            victim_ready = threading.Event()
            holder_ready = threading.Event()

            class VictimObj:
                def __reduce_package__(self, exporter):
                    return (unpackage_victim, ())

            class HolderObj:
                def __reduce_package__(self, exporter):
                    return (unpackage_holder, ())

            def unpackage_victim(importer):
                victim_ready.set()
                if not holder_ready.wait(5):
                    raise RuntimeError("holder callback did not run in time")
                return torch.tensor(
                    importer.storage_context.get_storage("0.storage", torch.float32)._typed_storage(),
                    dtype=torch.float32,
                ).clone()

            def unpackage_holder(importer):
                holder_ready.set()
                time.sleep(0.5)
                return "holder-ok"
            """
        ),
        encoding="utf-8",
    )

    spec = importlib.util.spec_from_file_location("race_confusion_mod", module_path)
    if spec is None or spec.loader is None:
        raise RuntimeError("failed to create import spec for helper module")
    module = importlib.util.module_from_spec(spec)
    sys.modules["race_confusion_mod"] = module
    spec.loader.exec_module(module)
    return module


def main() -> None:
    outdir = Path(__file__).resolve().parent / "artifacts"
    if outdir.exists():
        shutil.rmtree(outdir)
    outdir.mkdir(parents=True, exist_ok=True)

    helper_module = build_helper_module(outdir)
    victim = helper_module.VictimObj()
    holder = helper_module.HolderObj()

    package_path = outdir / "race_confusion_package.pt"
    payload = torch.tensor([9.0, 10.0, 11.0, 12.0], dtype=torch.float32)
    with package_path.open("wb") as package_file:
        with PackageExporter(package_file) as exporter:
            exporter.intern("race_confusion_mod")
            exporter.save_pickle("res", "a.pkl", {"probe": victim})
            exporter.save_pickle("res", "b.pkl", {"payload": payload, "probe": holder})

    importer = PackageImporter(str(package_path))
    packaged_module = importer.import_module("race_confusion_mod")

    results: dict[str, object] = {}
    errors: dict[str, str] = {}

    def load_a() -> None:
        try:
            results["a"] = importer.load_pickle("res", "a.pkl")
        except Exception as exc:
            errors["a"] = f"{type(exc).__name__}: {exc}"

    def load_b() -> None:
        try:
            if not packaged_module.victim_ready.wait(5):
                raise RuntimeError("victim callback did not run in time")
            results["b"] = importer.load_pickle("res", "b.pkl")
        except Exception as exc:
            errors["b"] = f"{type(exc).__name__}: {exc}"

    threads = [
        threading.Thread(target=load_a, args=()),
        threading.Thread(target=load_b, args=()),
    ]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join(timeout=10)

    if any(thread.is_alive() for thread in threads):
        raise RuntimeError("threads did not finish in time")
    if errors:
        raise RuntimeError(f"unexpected errors: {errors}")

    loaded_a = results["a"]
    loaded_b = results["b"]
    if not isinstance(loaded_a, dict) or not isinstance(loaded_b, dict):
        raise RuntimeError("unexpected result types")

    print("package_path", package_path, flush=True)
    print("a_probe", loaded_a["probe"], flush=True)
    print("b_payload", loaded_b["payload"], flush=True)
    print(
        "a_probe_matches_b_payload",
        torch.equal(loaded_a["probe"], loaded_b["payload"]),
        flush=True,
    )
    print("errors", errors, flush=True)


if __name__ == "__main__":
    main()
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Summary

A race condition in torch.package.PackageImporter.load_pickle() can silently deserialize the wrong tensor data when multiple threads reuse the same PackageImporter instance. Under concurrent reduce_package unpickling, one thread can observe another thread's deserialization storage context and restore the wrong resource without any exception.

Details

The root cause is in PackageImporter in torch/package/package_importer.py (lines 150-152, 276-285, and 294-306 in the local source tree). The importer stores storage_context and last_map_location as instance-level mutable fields, then passes the importer object itself into reduce_package callbacks via return func(self, *args). During load_pickle(), set_deserialization_context() temporarily writes those fields on the shared importer object and clears them afterward.

Because these fields are shared across the importer instance rather than scoped per thread or per load, concurrent calls to load_pickle() on the same importer can overwrite each other's deserialization context. A __reduce_package__ callback running in thread A can therefore read importer.storage_context after thread B has replaced it, causing thread A to deserialize thread B's tensor storage.

The proof of concept demonstrates silent data confusion rather than a crash. A crafted package contains a.pkl with a VictimObj and b.pkl with both a real tensor payload and a HolderObj. Two threads then call load_pickle() concurrently on the same PackageImporter. The callback for VictimObj waits until the callback for HolderObj has installed the second thread's storage context, then explicitly reads importer.storage_context.get_storage("0.storage", torch.float32). As a result, a.pkl is successfully restored, but its probe tensor is silently replaced with the payload from b.pkl.

PoC

Run poc_package_load_pickle_race_silent_confusion.py. This case does not split attacker and victim behavior into separate scripts. The proof of concept builds a minimal package, reuses one PackageImporter across two threads, and shows that one resource is silently restored using another resource's tensor storage:

import importlib.util
import shutil
import sys
import threading
from pathlib import Path
from textwrap import dedent

import torch
from torch.package import PackageExporter, PackageImporter


def build_helper_module(outdir: Path) -> object:
    module_path = outdir / "race_confusion_mod.py"
    module_path.write_text(
        dedent(
            """
            import threading
            import time
            import torch

            victim_ready = threading.Event()
            holder_ready = threading.Event()

            class VictimObj:
                def __reduce_package__(self, exporter):
                    return (unpackage_victim, ())

            class HolderObj:
                def __reduce_package__(self, exporter):
                    return (unpackage_holder, ())

            def unpackage_victim(importer):
                victim_ready.set()
                if not holder_ready.wait(5):
                    raise RuntimeError("holder callback did not run in time")
                return torch.tensor(
                    importer.storage_context.get_storage("0.storage", torch.float32)._typed_storage(),
                    dtype=torch.float32,
                ).clone()

            def unpackage_holder(importer):
                holder_ready.set()
                time.sleep(0.5)
                return "holder-ok"
            """
        ),
        encoding="utf-8",
    )

    spec = importlib.util.spec_from_file_location("race_confusion_mod", module_path)
    if spec is None or spec.loader is None:
        raise RuntimeError("failed to create import spec for helper module")
    module = importlib.util.module_from_spec(spec)
    sys.modules["race_confusion_mod"] = module
    spec.loader.exec_module(module)
    return module


def main() -> None:
    outdir = Path(__file__).resolve().parent / "artifacts"
    if outdir.exists():
        shutil.rmtree(outdir)
    outdir.mkdir(parents=True, exist_ok=True)

    helper_module = build_helper_module(outdir)
    victim = helper_module.VictimObj()
    holder = helper_module.HolderObj()

    package_path = outdir / "race_confusion_package.pt"
    payload = torch.tensor([9.0, 10.0, 11.0, 12.0], dtype=torch.float32)
    with package_path.open("wb") as package_file:
        with PackageExporter(package_file) as exporter:
            exporter.intern("race_confusion_mod")
            exporter.save_pickle("res", "a.pkl", {"probe": victim})
            exporter.save_pickle("res", "b.pkl", {"payload": payload, "probe": holder})

    importer = PackageImporter(str(package_path))
    packaged_module = importer.import_module("race_confusion_mod")

    results: dict[str, object] = {}
    errors: dict[str, str] = {}

    def load_a() -> None:
        try:
            results["a"] = importer.load_pickle("res", "a.pkl")
        except Exception as exc:
            errors["a"] = f"{type(exc).__name__}: {exc}"

    def load_b() -> None:
        try:
            if not packaged_module.victim_ready.wait(5):
                raise RuntimeError("victim callback did not run in time")
            results["b"] = importer.load_pickle("res", "b.pkl")
        except Exception as exc:
            errors["b"] = f"{type(exc).__name__}: {exc}"

    threads = [
        threading.Thread(target=load_a, args=()),
        threading.Thread(target=load_b, args=()),
    ]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join(timeout=10)

    if any(thread.is_alive() for thread in threads):
        raise RuntimeError("threads did not finish in time")
    if errors:
        raise RuntimeError(f"unexpected errors: {errors}")

    loaded_a = results["a"]
    loaded_b = results["b"]
    if not isinstance(loaded_a, dict) or not isinstance(loaded_b, dict):
        raise RuntimeError("unexpected result types")

    print("package_path", package_path, flush=True)
    print("a_probe", loaded_a["probe"], flush=True)
    print("b_payload", loaded_b["payload"], flush=True)
    print(
        "a_probe_matches_b_payload",
        torch.equal(loaded_a["probe"], loaded_b["payload"]),
        flush=True,
    )
    print("errors", errors, flush=True)


if __name__ == "__main__":
    main()

When the issue is reproduced successfully, the script reports that a_probe_matches_b_payload is True and errors is empty, showing that one resource was restored with another resource's tensor data without an exception.

Versions

PyTorch version: 2.11.0+cu126 Is debug build: False CUDA used to build PyTorch: 12.6 ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64) GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0 Clang version: Could not collect CMake version: version 3.22.1 Libc version: glibc-2.35

Python version: 3.13.12 | packaged by Anaconda, Inc. | (main, Feb 24 2026, 16:13:31) [GCC 14.3.0] (64-bit runtime) Python platform: Linux-5.15.0-139-generic-x86_64-with-glibc2.35 Is CUDA available: True CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: GPU models and configuration: []

Nvidia driver version: 550.144.03 cuDNN version: Could not collect 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): 56 On-line CPU(s) list: 0-55 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Gold 6330 CPU @ 2.00GHz CPU family: 6 Model: 106 Thread(s) per core: 1 Core(s) per socket: 28 Socket(s): 2 Stepping: 6 CPU max MHz: 2000.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 pni pclmulqdq dtes64 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 invpcid_single intel_ppin 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 wbnoinvd dtherm arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 2.6 MiB (56 instances) L1i cache: 1.8 MiB (56 instances) L2 cache: 70 MiB (56 instances) L3 cache: 84 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-27 NUMA node1 CPU(s): 28-55 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT disabled 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 SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] numpy==2.4.3 [pip3] nvidia-cublas==13.1.0.3 [pip3] nvidia-cublas-cu12==12.6.4.1 [pip3] nvidia-cuda-cupti==13.0.85 [pip3] nvidia-cuda-cupti-cu12==12.6.80 [pip3] nvidia-cuda-nvrtc==13.0.88 [pip3] nvidia-cuda-nvrtc-cu12==12.6.85 [pip3] nvidia-cuda-runtime==13.0.96 [pip3] nvidia-cuda-runtime-cu12==12.6.77 [pip3] nvidia-cudnn-cu12==9.10.2.21 [pip3] nvidia-cudnn-cu13==9.19.0.56 [pip3] nvidia-cufft==12.0.0.61 [pip3] nvidia-cufft-cu12==11.3.0.4 [pip3] nvidia-curand==10.4.0.35 [pip3] nvidia-curand-cu12==10.3.7.77 [pip3] nvidia-cusolver==12.0.4.66 [pip3] nvidia-cusolver-cu12==11.7.1.2 [pip3] nvidia-cusparse==12.6.3.3 [pip3] nvidia-cusparse-cu12==12.5.4.2 [pip3] nvidia-cusparselt-cu12==0.7.1 [pip3] nvidia-cusparselt-cu13==0.8.0 [pip3] nvidia-nccl-cu12==2.28.9 [pip3] nvidia-nccl-cu13==2.28.9 [pip3] nvidia-nvjitlink==13.0.88 [pip3] nvidia-nvjitlink-cu12==12.6.85 [pip3] nvidia-nvtx==13.0.85 [pip3] nvidia-nvtx-cu12==12.6.77 [pip3] torch==2.11.0+cu126 [pip3] torchvision==0.26.0+cu126 [pip3] triton==3.6.0 [conda] numpy 2.4.3 pypi_0 pypi [conda] nvidia-cublas 13.1.0.3 pypi_0 pypi [conda] nvidia-cublas-cu12 12.6.4.1 pypi_0 pypi [conda] nvidia-cuda-cupti 13.0.85 pypi_0 pypi [conda] nvidia-cuda-cupti-cu12 12.6.80 pypi_0 pypi [conda] nvidia-cuda-nvrtc 13.0.88 pypi_0 pypi [conda] nvidia-cuda-nvrtc-cu12 12.6.85 pypi_0 pypi [conda] nvidia-cuda-runtime 13.0.96 pypi_0 pypi [conda] nvidia-cuda-runtime-cu12 12.6.77 pypi_0 pypi [conda] nvidia-cudnn-cu12 9.10.2.21 pypi_0 pypi [conda] nvidia-cudnn-cu13 9.19.0.56 pypi_0 pypi [conda] nvidia-cufft 12.0.0.61 pypi_0 pypi [conda] nvidia-cufft-cu12 11.3.0.4 pypi_0 pypi [conda] nvidia-curand 10.4.0.35 pypi_0 pypi [conda] nvidia-curand-cu12 10.3.7.77 pypi_0 pypi [conda] nvidia-cusolver 12.0.4.66 pypi_0 pypi [conda] nvidia-cusolver-cu12 11.7.1.2 pypi_0 pypi [conda] nvidia-cusparse 12.6.3.3 pypi_0 pypi [conda] nvidia-cusparse-cu12 12.5.4.2 pypi_0 pypi [conda] nvidia-cusparselt-cu12 0.7.1 pypi_0 pypi [conda] nvidia-cusparselt-cu13 0.8.0 pypi_0 pypi [conda] nvidia-nccl-cu12 2.28.9 pypi_0 pypi [conda] nvidia-nccl-cu13 2.28.9 pypi_0 pypi [conda] nvidia-nvjitlink 13.0.88 pypi_0 pypi [conda] nvidia-nvjitlink-cu12 12.6.85 pypi_0 pypi [conda] nvidia-nvtx 13.0.85 pypi_0 pypi [conda] nvidia-nvtx-cu12 12.6.77 pypi_0 pypi [conda] torch 2.11.0+cu126 pypi_0 pypi [conda] torchvision 0.26.0+cu126 pypi_0 pypi [conda] triton 3.6.0 pypi_0 pypi

extent analysis

TL;DR

The most likely fix for the silent data corruption issue in torch.package.PackageImporter.load_pickle() is to ensure that each thread uses its own instance of PackageImporter to avoid overwriting each other's deserialization context.

Guidance

  • Identify the source of the concurrent access to PackageImporter instances and refactor the code to create a new instance for each thread.
  • Verify that the deserialization context is not shared across threads by checking the storage_context and last_map_location fields of the PackageImporter instance.
  • Consider using thread-local storage or other synchronization mechanisms to ensure that each thread has its own isolated deserialization context.
  • Review the __reduce_package__ callbacks to ensure that they do not rely on shared state or modify the PackageImporter instance in a way that could affect other threads.

Example

import threading
from torch.package import PackageImporter

def load_pickle(thread_id):
    # Create a new PackageImporter instance for each thread
    importer = PackageImporter("path/to/package.pt")
    # Load the pickle using the thread-local PackageImporter instance
    data = importer.load_pickle("res", "a.pkl")
    # Process the data
    print(f"Thread {thread_id} loaded data: {data}")

threads = []
for i in range(2):
    thread = threading.Thread(target=load_pickle, args=(i,))
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

Notes

The provided code snippet demonstrates a proof of concept for the silent data corruption issue, but it does not provide a clear solution. The fix will depend on the specific use case and requirements of the application. Additionally, the issue may be specific to the PyTorch version (2.11.0+cu126) and may not be present in other versions.

Recommendation

Apply a workaround by creating a new PackageImporter instance for each thread to avoid sharing the deserialization context. This will ensure that each thread has its own isolated context and prevent silent data corruption.

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