ComfyUI-MultiGPU icon indicating copy to clipboard operation
ComfyUI-MultiGPU copied to clipboard

Process abort (`cudaErrorIllegalAddress`) on consumer dual-GPU when P2P is unavailable and `cudaMallocAsync` is the active allocator

Open TaoGunner opened this issue 3 months ago • 3 comments

Summary

On a 2x RTX 3090 system, GeForce cards have PCIe P2P disabled at driver level, so can_access_peer correctly reports False and the CPU-staging path engages. That path then produces CUDA error: an illegal memory access was encountered.

Critically, the error surfaces from a C++ destructor, so it is not catchable as a Python exception — it calls abort() and kills the whole ComfyUI process:

terminate called after throwing an instance of 'c10::AcceleratorError'
  what(): CUDA error: an illegal memory access was encountered
Exception raised from free_impl at /__w/pytorch/pytorch/c10/cuda/CUDAMallocAsyncAllocator.cpp:206
Fatal Python error: Aborted

ComfyUI runs with the cudaMallocAsync backend (visible at startup: Device: cuda:0 NVIDIA GeForce RTX 3090 : cudaMallocAsync). That allocator uses per-device memory pools and is far stricter about foreign pointers than the native caching allocator — I suspect the CPU-staged tensor ends up freed against the wrong device's pool.

Two distinct reproductions

Both on MiniMax H3 (ComfyUI 0.30.0 native nodes), text encoder = Qwen3-VL 32B int8_convrot.

A. Quantized text encoder on cuda:1 — fails at load

CLIPLoaderMultiGPU (and CLIPLoaderDisTorch2MultiGPU, identical result), device cuda:1:

[MultiGPU P2P] can_access_peer(1, 0) = False
...
comfy_kitchen/tensor/int8.py:172 in dequantize
  torch.ops.comfy_kitchen.dequantize_int8_convrot_weight_dtype(...)
comfy_kitchen/backends/cuda/__init__.py:1531 in dequantize_int8_convrot_weight_dtype
  _wrap_for_dlpack(q_2d)
→ torch.AcceleratorError: CUDA error: an illegal memory access was encountered

B. fp16 video VAE on cuda:1 — fails during decode

VAELoaderMultiGPU, device cuda:1. Sampling completes fine (20 steps, 3.82 s/it, diffusion model on cuda:0). CPU-staging logs look healthy:

[MultiGPU P2P] can_access_peer(1, 0) = False
[MultiGPU DLPack] CPU-staging tensor from cuda:1 to cuda:0 (P2P unavailable)
[MultiGPU CUDA Guard] Switching CUDA current device 1 -> 0 (comfy_kitchen._wrap_for_dlpack(staged))
[MultiGPU CUDA Guard] Restored CUDA current device 0 -> 1 (comfy_kitchen._wrap_for_dlpack(staged))

…repeated several times, then hard abort inside the VAE's attention block:

Stack (most recent call first):
  File "/root/ComfyUI/comfy/ops.py", line 93 in scaled_dot_product_attention
  File "/root/ComfyUI/comfy/ldm/modules/attention.py", line 526 in attention_pytorch
  File "/root/ComfyUI/comfy/ldm/minimax/vae.py", line 239 in forward
  File "/root/ComfyUI/comfy/ldm/minimax/vae.py", line 499 in tiled_decode
  File "/root/ComfyUI/comfy/ldm/minimax/vae.py", line 690 in decode

Frame #8 in the C++ trace is at::native::_flash_attention_forward, so a staged tensor reaches flash-attention and dies on free.

Since B involves no quantization at all, the trigger is cross-device pointers in general, not the int8_convrot path specifically.

Working configuration

Everything on cuda:0 with stock loaders works. ComfyUI's built-in DynamicVRAM streams the 26 GB text encoder through host RAM without issue (Model MiniMaxH3TEModel_ prepared for dynamic VRAM loading. 25882MB Staged). So the second GPU is currently unusable on this hardware.

Questions / suggestions

  1. Is the CPU-staging path tested against the cudaMallocAsync allocator? A note in the README about PYTORCH_CUDA_ALLOC_CONF=backend:native would help if it is a known incompatibility.
  2. Should the staged tensor be materialized as a real copy owned by the destination device's pool, rather than wrapped via DLPack across the boundary?
  3. Consider refusing to place models on a non-default device when can_access_peer is False and the allocator is cudaMallocAsync — a clear error at load time beats a process abort mid-decode.

Happy to test patches; the setup reproduces both cases reliably in under two minutes.

Environment

  • ComfyUI 0.30.0 (rev 5693, b1693ecb)
  • PyTorch 2.13.0+cu130, Python 3.13.14
  • comfy-kitchen 0.2.26, comfy-aimdo 0.4.11
  • 2x NVIDIA RTX 3090 (no NVLink bridge), PCIe P2P disabled by driver
  • Allocator: cudaMallocAsync
  • Launch args: --listen --port 8188 --reserve-vram 1.0 --disable-smart-memory
  • Docker, image yanwk/comfyui-boot:cu130-slim
  • Note: issue #<номер первого> had to be worked around first to reach this point

TaoGunner avatar Aug 06 '26 23:08 TaoGunner

This issue is still present in the current version. I'm encountering the exact same error on a Dual 5060TI configuration.

andypotato avatar Aug 17 '26 02:08 andypotato

Qwen 3.8 proposes to basically remove most of the code in _patch_comfy_kitchen_dlpack_device_guard:

diff --git a/__init__.py b/__init__.py
index 2d00d58..df2cf6f 100644
--- a/__init__.py
+++ b/__init__.py
@@ -525,7 +525,7 @@ def _patch_comfy_sample_runtime_device():
         logger.info("[MultiGPU] Patched comfy.sample.sample_custom with runtime device guard")
 
 def _patch_comfy_kitchen_dlpack_device_guard():
-    """Guard comfy_kitchen DLPack export with P2P-aware CPU-staging fallback."""
+    """Guard comfy_kitchen DLPack export by aligning the CUDA current device with the tensor."""
     try:
         comfy_kitchen_cuda = importlib.import_module("comfy_kitchen.backends.cuda")
     except ImportError:
@@ -540,43 +540,16 @@ def _patch_comfy_kitchen_dlpack_device_guard():
     if getattr(wrap_for_dlpack, "_multigpu_cuda_device_guard", False):
         return True
 
-    from .p2p_registry import p2p_registry
-
     def wrap_for_dlpack_with_device_guard(*args, **kwargs):
         tensor = args[0] if args else kwargs.get("tensor")
         tensor_device = getattr(tensor, "device", None)
-        exec_device = get_current_device()
-        exec_device = _coerce_torch_device(exec_device)
-
-        # Determine if cross-device staging is needed
-        needs_staging = False
-        def _valid_cuda(d):
-            return d is not None and d.type == "cuda" and d.index is not None
-
-        if _valid_cuda(tensor_device) and _valid_cuda(exec_device):
-            if tensor_device.index != exec_device.index and not p2p_registry.can_access_peer(tensor_device.index, exec_device.index):
-                needs_staging = True
 
-        if needs_staging:
-            logger.info(
-                f"[MultiGPU DLPack] CPU-staging tensor from cuda:{tensor_device.index} "
-                f"to cuda:{exec_device.index} (P2P unavailable)"
-            )
-            staged_tensor = tensor.to("cpu").to(exec_device)
-            wrap_for_dlpack_with_device_guard._dlpack_staging_count += 1
-            with cuda_device_guard(exec_device, reason="comfy_kitchen._wrap_for_dlpack(staged)"):
-                if args:
-                    return wrap_for_dlpack(staged_tensor, *args[1:], **kwargs)
-                else:
-                    return wrap_for_dlpack(staged_tensor, **kwargs)
-        else:
-            with cuda_device_guard(tensor_device, reason="comfy_kitchen._wrap_for_dlpack"):
-                return wrap_for_dlpack(*args, **kwargs)
+        with cuda_device_guard(tensor_device, reason="comfy_kitchen._wrap_for_dlpack"):
+            return wrap_for_dlpack(*args, **kwargs)
 
     wrap_for_dlpack_with_device_guard._multigpu_cuda_device_guard = True
-    wrap_for_dlpack_with_device_guard._dlpack_staging_count = 0
     comfy_kitchen_cuda._wrap_for_dlpack = wrap_for_dlpack_with_device_guard
-    logger.info("[MultiGPU] Applied comfy_kitchen CUDA DLPack device guard patch (P2P-aware)")
+    logger.info("[MultiGPU] Applied comfy_kitchen CUDA DLPack device guard patch (device-aligned)")
     return True
 
 logger.info("[MultiGPU Core Patching] Patching mm.get_torch_device, mm.text_encoder_device, mm.unet_offload_device")

It seems to work fine on my system with a 5090 and a 3090. Not sure if it has negative consequences with P2P enabled, though.

ata4 avatar Aug 22 '26 17:08 ata4

Second data point for you: 2x 3080 20G, Windows, torch 2.10+cu130, H3 int8_convrot. Same device-aligned approach, no staging branch, and it's stayed up across long chained runs (300+ frame segments, hours of sampling) where the P2P-aware version was dying every few runs.

On your open question about P2P-enabled systems: can't test that here (GeForce, no NVLink, can_access_peer is always False on this box). How I read it though: the staging fallback was only there because the export has to happen on the tensor's device - the guard's job is putting the current device in the right place, and the P2P probe was an extra branch on top deciding whether to stage instead. Drop it and same-device export behaves exactly as before; cross-device export just follows whatever the runtime can actually do at copy time. With P2P present that's a direct path, whereas the old code would have staged through host memory first - slower, not safer. That's reasoning, not a measurement, so someone with a real P2P pair should confirm.

One thing worth keeping in mind either way: staging is also where a second failure lives - packed quantized weights moved across devices go through comfy_kitchen's dequant/requant dispatch, which is what #220 is about. Dropping the branch removes both failure modes, and I think that's the stronger argument than the P2P question.

If you'd rather not wait for the upstream fix to land: the other way around this is to not move weights between devices at all. I split the DiT blocks across both cards once at load time and keep them there, which takes the guard, the probe and the staging path out of the picture entirely. That ended up as a node - https://github.com/ylzbj1-stack/ComfyUI-StaticPipeline - Windows + H3 in my case, but nothing in the mechanism is model-specific.

ylzbj1-stack avatar Sep 15 '26 04:09 ylzbj1-stack