AlperKTS commited on
Commit
7e305fc
·
verified ·
1 Parent(s): 91737e9

fix: keep sage off attention shorter than one K/V block

Browse files

Mirrors GitHub cf2b44f. sageattn_qk_int8_pv_fp16_cuda (what auto picks on sm80/86/87) returns NaN below one K/V block; Krea2 txtfusion attends over 12 tokens, so a single NaN blacked out the latent at random. Guard routes sub-block attention to stock.

Files changed (2) hide show
  1. TROUBLESHOOTING.md +34 -0
  2. sage_mask_guard.py +47 -10
TROUBLESHOOTING.md CHANGED
@@ -141,6 +141,40 @@ float-mask attention calls to ComfyUI's stock attention and leaves everything el
141
  you keep the speedup on every normal block and pay full price only on the biased ones. The
142
  console logs `float attention mask -> stock attention` once per run when it fires.
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  Merging the LoRA into the checkpoint appeared to fix it only because that comparison also
145
  dropped the `ref_boost` bias; the quantized model and its LoRA branch are not involved. If
146
  you load a plain `--format w4a4` / `int8` checkpoint through the stock `UNETLoader`, the
 
141
  you keep the speedup on every normal block and pay full price only on the biased ones. The
142
  console logs `float attention mask -> stock attention` once per run when it fires.
143
 
144
+ ## Random all-black frames with sage `auto` / `..._fp16_cuda`
145
+
146
+ Also fixed, and it is a sage kernel bug, not a quantization one. `sageattn_qk_int8_pv_fp16_cuda`
147
+ returns NaN for sequences shorter than one K/V block. Standalone, no ComfyUI, same inputs on
148
+ every call, RTX 3090, head_dim 128, bf16 and fp16 alike:
149
+
150
+ ```
151
+ B=64 H=20 N=4..48 -> 7-10 of 10 calls non-finite
152
+ B=64 H=20 N=63..128 -> 0 of 10
153
+ B=592 H=20 N=12 / 32 -> 0-3 of 20, and it flips between processes
154
+ triton, every shape -> 0 of 20
155
+ ```
156
+
157
+ Krea2's `txtfusion` layerwise blocks attend over **12 tokens**, so every sampling step rolls
158
+ these dice, and a single NaN there poisons the latent: a completely black frame. `auto` picks
159
+ this kernel on sm80/86/87 (`sageattention/core.py`), which is why "auto" and "cuda fp16" were
160
+ the two settings people reported black images on.
161
+
162
+ The intermittency is what made it look like a LoRA or SVDQuant problem: the same graph is
163
+ clean on one model load and black on the next, and it survives across runs until the model is
164
+ reloaded. It is neither. Measured before the fix, 768px edit workflow, cold load each time:
165
+ roughly one black frame in three or four. After it: 10 of 10 clean, and byte-identical
166
+ outputs run to run.
167
+
168
+ The guard now routes any attention shorter than one K/V block to stock attention. Sage has
169
+ nothing to win on a 12-token attention, so this costs no measurable speed, and it applies
170
+ regardless of which sage kernel is selected. Console logs
171
+ `attention shorter than one K/V block ... -> stock attention` once per run.
172
+
173
+ One more thing worth knowing about `auto`: on sm80/86/87 its dispatch calls the kernel
174
+ *without* forwarding `attn_mask` at all, so krea2edit's `ref_boost` would be silently ignored
175
+ even when the output is not black. Prefer `sageattn_qk_int8_pv_fp16_triton` if you want the
176
+ bias honoured on the blocks the guard does not intercept.
177
+
178
  Merging the LoRA into the checkpoint appeared to fix it only because that comparison also
179
  dropped the `ref_boost` bias; the quantized model and its LoRA branch are not involved. If
180
  you load a plain `--format w4a4` / `int8` checkpoint through the stock `UNETLoader`, the
sage_mask_guard.py CHANGED
@@ -1,7 +1,7 @@
1
- """Route float-mask attention calls away from sage-attention.
2
 
3
- Sage's kernels take an ``attn_mask``, but a *float* (additive-bias) mask is the one
4
- shape they handle badly:
5
 
6
  * ``sageattn_qk_int8_pv_fp16_triton`` stages the mask tile through shared memory on
7
  top of the K/V pipeline. At head_dim 128 that is 139276 bytes against the 101376
@@ -16,6 +16,21 @@ text-to-image step. The only caller that hands Krea2 a float mask is
16
  comfyui-krea2edit's ``ref_boost`` bias, so this guard costs nothing unless that
17
  feature is on, and then it costs sage's speedup on the edit blocks alone.
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  Installed by the loader on the model it returns, and wrapped at sample time rather
20
  than at load time because ComfyUI's Patch Sage Attention node may well run after us.
21
  """
@@ -29,7 +44,12 @@ import torch
29
  import comfy.patcher_extension
30
 
31
  _KEY = "krea2_sage_mask_guard"
32
- _warned = False
 
 
 
 
 
33
 
34
 
35
  def _mask_of(args, kwargs):
@@ -39,16 +59,33 @@ def _mask_of(args, kwargs):
39
  return args[4] if len(args) > 4 else None
40
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  def _guard(override):
43
  def guarded(func, *args, **kwargs):
44
  mask = _mask_of(args, kwargs)
45
  if mask is not None and torch.is_floating_point(mask):
46
- global _warned
47
- if not _warned:
48
- _warned = True
49
- logging.info("[krea2-svdquant] float attention mask -> stock attention "
50
- "(sage mishandles additive-bias masks)")
51
- return func(*args, **kwargs)
52
  return override(func, *args, **kwargs)
53
 
54
  guarded.krea2_mask_guard = True
 
1
+ """Route the two attention shapes sage-attention gets wrong back to stock attention.
2
 
3
+ **Float masks.** Sage's kernels take an ``attn_mask``, but a *float* (additive-bias) mask is
4
+ the one shape they handle badly:
5
 
6
  * ``sageattn_qk_int8_pv_fp16_triton`` stages the mask tile through shared memory on
7
  top of the K/V pipeline. At head_dim 128 that is 139276 bytes against the 101376
 
16
  comfyui-krea2edit's ``ref_boost`` bias, so this guard costs nothing unless that
17
  feature is on, and then it costs sage's speedup on the edit blocks alone.
18
 
19
+ **Short sequences.** ``sageattn_qk_int8_pv_fp16_cuda`` returns NaN for sequences shorter
20
+ than one K/V block, which is what ``auto`` resolves to on sm80/86/87 (``core.py``). Measured
21
+ on a 3090 at head_dim 128, same inputs every call, bf16 and fp16 alike::
22
+
23
+ B=64 H=20 N=4..48 -> 7-10 of 10 calls non-finite
24
+ B=64 H=20 N=63..128 -> 0 of 10
25
+ B=592 H=20 N=12/32 -> 0-3 of 20, flips with the allocator state
26
+ triton, every shape -> 0
27
+
28
+ Krea2's ``txtfusion`` layerwise blocks attend over 12 tokens, so every step hits it, and one
29
+ NaN there poisons the whole latent: an all-black frame. The intermittency is why this looked
30
+ like a LoRA or quantization bug -- the same graph is fine on one model load and black on the
31
+ next. Sage has nothing to win on a 12-token attention anyway, so those calls go to stock
32
+ attention unconditionally rather than only under the kernels known to be broken.
33
+
34
  Installed by the loader on the model it returns, and wrapped at sample time rather
35
  than at load time because ComfyUI's Patch Sage Attention node may well run after us.
36
  """
 
44
  import comfy.patcher_extension
45
 
46
  _KEY = "krea2_sage_mask_guard"
47
+
48
+ # One K/V block. The measured boundary sits between 48 (broken) and 63 (clean), and 64 is
49
+ # the kernel's block size, so this is the block edge rather than a fudged constant.
50
+ _MIN_SEQ = 64
51
+
52
+ _warned: set[str] = set()
53
 
54
 
55
  def _mask_of(args, kwargs):
 
59
  return args[4] if len(args) > 4 else None
60
 
61
 
62
+ def _seq_len(q, kwargs):
63
+ """Tokens per attention call, for both call shapes ComfyUI uses.
64
+
65
+ ``skip_reshape`` means q already arrives as [B, H, N, D]; otherwise it is
66
+ [B, N, H*D] and still has to be split by head.
67
+ """
68
+ if kwargs.get("skip_reshape"):
69
+ return q.shape[-2]
70
+ return q.shape[1] if q.ndim == 3 else q.shape[-2]
71
+
72
+
73
+ def _bail(reason, func, args, kwargs):
74
+ if reason not in _warned:
75
+ _warned.add(reason)
76
+ logging.info("[krea2-svdquant] %s -> stock attention", reason)
77
+ return func(*args, **kwargs)
78
+
79
+
80
  def _guard(override):
81
  def guarded(func, *args, **kwargs):
82
  mask = _mask_of(args, kwargs)
83
  if mask is not None and torch.is_floating_point(mask):
84
+ return _bail("float attention mask (sage mishandles additive-bias masks)",
85
+ func, args, kwargs)
86
+ if _seq_len(args[0], kwargs) < _MIN_SEQ:
87
+ return _bail("attention shorter than one K/V block (sage's CUDA kernel "
88
+ "returns NaN there)", func, args, kwargs)
 
89
  return override(func, *args, **kwargs)
90
 
91
  guarded.krea2_mask_guard = True