Fix small_input attention fallback OOMing without pytorch attention - #16228
Fix small_input attention fallback OOMing without pytorch attention#16228chelsealong wants to merge 2 commits into
Conversation
optimized_attention_for_device(small_input=True) fell back to attention_basic, which materializes the full N x N score matrix, on any device where pytorch_attention_enabled() is False (e.g. AMD RDNA2/older GPUs without aotriton SDPA kernels). Text encoders that tokenize a variable number of reference images into the same sequence (MiniMax H3) can push N high enough to OOM on this path even though ComfyUI already ships chunked, hardware-agnostic alternatives. Use attention_sub_quad instead, which has an identical signature and is already the default small-input-independent fallback used elsewhere in this file.
…orch Without CUDA, importing comfy.ldm.modules.attention pulls in comfy.model_management, which calls torch.cuda.current_device() at import time and raises. The test only passed before because it happened to run after gemma4_template_test.py alphabetically, which sets args.cpu = True as a side effect. Apply the same guard directly in this test file so it collects and passes in isolation, matching the CI unit-test job's CPU-only torch install.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📜 Recent review details⏰ Context from checks skipped due to timeout. (8)
🧰 Additional context used📓 Path-based instructions (3)Core ML/diffusion engine.⚙️ CodeRabbit configuration file Files:
IMPORTANT: Only comment on issues directly introduced by this PR's code changes.⚙️ CodeRabbit configuration file Files:
Documentation and README edits should be concise, factual, and tied to the changed behavior.📄 CodeRabbit inference engine (AGENTS.md) Files:
🔇 Additional comments (2)
📝 WalkthroughWalkthroughThe small-input branch of Severity of issue fixed: Medium Merge Risk: ⚪ Minimal · up to The change prevents full attention score materialization for the affected fallback path while preserving targeted regression coverage, so it is ready to merge after normal checks. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Comment |
Fixes #16160
Problem
optimized_attention_for_device(small_input=True)only offered a two-waychoice:
attention_pytorchwhen pytorch attention (SDPA) is enabled, orattention_basicotherwise.attention_basicmaterializes the fullN x Nscore matrix, which is fine for typical short text-encodersequences but becomes the largest allocation in the run once
Ngrows —e.g. MiniMax H3's
<Picture i>reference-image tokens are appended to thesame sequence CLIP encodes with
small_input=True(
comfy/text_encoders/llama.py:757), so encoding several reference imagespushes
Ninto the thousands.On GPUs where
pytorch_attention_enabled()isFalse— notably AMDRDNA2-and-older architectures (
gfx1030,gfx1031,gfx1035,gfx1010,gfx1011,gfx1012,gfx906,gfx900,gfx803), which ship no aotritonSDPA kernels — there was no way to avoid this path.
--use-pytorch-cross-attentionmakes it worse (falls through to PyTorch's math SDPA backend, which uses
~5x more memory than
attention_basicat the same shape per the issue'sown benchmark), and
--use-split-cross-attention/--use-quad-cross-attentiondon't help either since the
small_input=Truebranch is hardcoded andbypasses the module-level
optimized_attentionrebinding those flags use.Fix
Change the
small_input=True, no-pytorch-attention fallback fromattention_basictoattention_sub_quad, which:mask,skip_reshape,skip_output_reshape,enable_gqavia**kwargs),used elsewhere in this file (e.g. for
device == cpu),repro from 10.25 GiB (OOM) to ~1.3 GiB.
attention_splitwas considered and rejected (by the issue reporter) asthe alternative: its chunk size falls back to no chunking at all when the
sequence length isn't evenly divisible by the step count, which can still
OOM.
Test plan
Added
tests-unit/comfy_test/optimized_attention_for_device_test.py,asserting that
optimized_attention_for_device(..., small_input=True)returns
attention_sub_quad(notattention_basic) whenpytorch_attention_enabled()isFalse.This sandbox (and CI's unit-test job, which installs CPU-only torch)
has no CUDA device, and importing
comfy.ldm.modules.attentionpullsin
comfy.model_management, which callstorch.cuda.current_device()at module import time. The test file guards against this the same way
tests-unit/comfy_test/gemma4_template_test.pyalready does — settingcomfy.cli_args.args.cpu = Truebefore the import when CUDA isn'tavailable — so it collects and passes standalone, with no dependency
on import order relative to other test files.
Ran the exact command from
.github/workflows/test-unit.ymlinisolation, both before and after the source fix:
Also ran
ruff checkon both changed files: all checks passed.🤖 Generated with Claude Code