ComfyUI icon indicating copy to clipboard operation
ComfyUI copied to clipboard

DynamicVRAM: the largest cast weight grows a cast buffer on every offload stream, taking VRAM from resident weights

Open ootsby opened this issue 1 week ago • 0 comments

AI Usage: Claude Fable 5.2 was used to generate the issue description below.

Problem

With DynamicVRAM and async offload, each offload stream has its own cast buffer. A buffer grows to fit the largest thing sent through it and is not released until reset_cast_buffers().

cast_modules_with_vbar has a guard that is meant to keep the largest cast weight on one stream, so that only one buffer grows to its size (comfy/ops.py lines 151–165). It does not do that:

  • It compares the required size against a local cast_buffer that is always None when the guard runs. That local is only assigned later, in get_cast_buffer, and the guard only runs for single-module calls. So the current size always reads as 0, and the guard takes the next stream on every cast of the largest weight, not only when the stream's buffer is too small. The weight lands on whichever stream the rotation gives, and every stream grows a buffer for it.
  • It takes the next stream without checking that its buffer fits, which only finds the right stream when there are two.

The cost shows up when a model has one weight much larger than the rest and that weight has no VRAM behind its VBAR slot. Each stream then holds a buffer of that weight's size. That VRAM comes out of the resident weights, so more of the model is streamed on every step.

I found it generating text with Gemma 4 12B (gemma4_12b_h3_pe_int8) on a 16 GB card. The tied embedding and output head, model.embed_tokens.weight, is 1920 MiB and is cast for every token's logits. The next largest weights are 56 MiB. Both streams held a 1920 MiB buffer.

Measurements

Windows 11, 16 GB NVIDIA GPU, torch 2.14.1+cu130, comfy-aimdo 0.6.0, two offload streams, master at f99de883d. The repro script below, with 3 GiB of VRAM allocated first so that the model does not fit. Sampled mid-decode over 128 tokens, two runs:

Cast buffers Weights resident Decode speed
1920 + 1920 MiB 6.25–6.34 GiB of 12.06 4.14–4.17 tok/s

For scale, the same runs with the guard keeping the weight on one stream (#17901):

Cast buffers Weights resident Decode speed
1920 + 240 MiB 7.84–8.00 GiB of 12.06 5.66–5.72 tok/s

The exact figures move with how much VRAM other programs hold. When the whole model fits, no cast buffer is used and there is nothing to see: 12.06 GiB resident and 46–48 tok/s either way.

Repro

There is no workflow attached; the script drives the text encoder directly so that the buffers can be read mid-decode. Run it with the embedded Python, with PROBE_COMFY set to the ComfyUI checkout, PROBE_MODEL to the model file, and PROBE_HOG_GIB=3 (or whatever leaves the model about 2 to 3 GiB short on the card in use). It prints the cast buffer sizes for three generations; on master both are 1920 MiB.

Repro script
import os
import sys
import time

COMFY = os.environ["PROBE_COMFY"]  # checkout to test
MODEL = os.environ["PROBE_MODEL"]  # gemma4_12b_h3_pe_int8.safetensors
sys.path.insert(0, COMFY)
sys.argv = sys.argv[:1]
os.environ.setdefault("PYTORCH_ALLOC_CONF", "backend:cudaMallocAsync")

from comfy.cli_args import args
import comfy_aimdo.control

comfy_aimdo.control.init(simple_vram_headroom=None, nvml_pressure=not args.disable_nvml_pressure)

import torch
import comfy.model_management
import comfy.memory_management

assert comfy_aimdo.control.init_devices((d.index, 0) for d in comfy.model_management.get_all_torch_devices())
comfy.memory_management.aimdo_enabled = True

import comfy.sd
import comfy.model_patcher
import comfy.text_encoders.llama as llama

comfy.model_patcher.CoreModelPatcher = comfy.model_patcher.ModelPatcherDynamic

clip = comfy.sd.load_clip([MODEL], clip_type=comfy.sd.CLIPType.STABLE_DIFFUSION)
tokens = clip.tokenize("Write a very long story about a fennec fox.", skip_template=False, min_length=1, thinking=False)

# Stand-in for another program holding VRAM, so the model no longer fits.
hog_gib = float(os.environ.get("PROBE_HOG_GIB", "0"))
hog = torch.empty(int(hog_gib * 2**30), dtype=torch.uint8, device="cuda") if hog_gib else None

samples = []
orig_sample = llama.BaseGenerate.sample_token


def spy(self, *a, **k):
    vbar = self.model.embed_tokens._v[0]
    free, total = torch.cuda.mem_get_info()
    samples.append((vbar.loaded_size(), [b.size() >> 20 for b in comfy.model_management.STREAM_AIMDO_CAST_BUFFERS.values()], total - free, time.time()))
    return orig_sample(self, *a, **k)


llama.BaseGenerate.sample_token = spy


def run(n):
    samples.clear()
    clip.generate(tokens, do_sample=False, max_length=n)
    torch.cuda.synchronize()
    decode = samples[8:]
    dt = (decode[-1][3] - decode[0][3]) / (len(decode) - 1)
    mid = decode[len(decode) // 2]
    print("tok/s %.2f" % (1 / dt), "| cast buffers MiB", sorted(mid[1], reverse=True), "| weights resident GiB %.2f" % (mid[0] / 2**30),
          "| device VRAM used GiB %.2f" % (mid[2] / 2**30))


run(48)
run(128)
run(128)
sys.stdout.flush()
os._exit(0)

Without a GPU, the logic can be seen with fake streams and buffers: cast one weight repeatedly with other stream requests in between, and more than one stream's buffer reaches the weight's size. The test in #17901 does this and fails on master with 2, 3 and 4 streams.

Proposed fix

#17901 makes the guard read the stream's own buffer and rotate until it finds a stream whose buffer fits.

The problem does not depend on that approach. Anything that stops a single outsized weight from sizing every stream's cast buffer would address it.

ootsby avatar Nov 21 '26 14:11 ootsby