Added reference token attention isolation (kv_cache) for Krea2 edit training. Same training cost with significant inference speed up. 2x inference speedup.

This commit is contained in:
Jaret Burkett committed 2026-07-09 12:00:55 -06:00
1 parent 6233efe1bb
commit a4bbe167ce
7 files changed
+177 -13

No files matched your search

@@ -210,7 +210,13 @@ class Attention(torch.nn.Module):
self.wo = torch.nn.Linear(dim, dim, bias=bias)
def forward(
self, qkv: Tensor, freqs: Tensor | None = None, mask: Tensor | None = None
self,
qkv: Tensor,
freqs: Tensor | None = None,
mask: Tensor | None = None,
ref_span: tuple[int, int] | None = None,
kv_capture: list | None = None,
kv_cache: tuple[Tensor, Tensor] | None = None,
) -> Tensor:
q, k, v, gate = self.wq(qkv), self.wk(qkv), self.wv(qkv), self.gate(qkv)
@@ -223,6 +229,20 @@ class Attention(torch.nn.Module):
q, k, v = self.qknorm(q, k, v)
if freqs is not None:
q, k = ropeapply(q, k, freqs)
if kv_capture is not None and ref_span is not None:
# Stash this block's post-RoPE ref K/V so later denoising steps can
# run without the ref tokens in the sequence (clone: drop the view
# into the full-sequence K/V so only the ref span stays alive).
kv_capture.append(
(
k[:, :, ref_span[0] : ref_span[1]].clone(),
v[:, :, ref_span[0] : ref_span[1]].clone(),
)
)
if kv_cache is not None:
# Cached ref K/V are already RoPE'd at their original positions.
k = torch.cat((k, kv_cache[0]), dim=2)
v = torch.cat((v, kv_cache[1]), dim=2)
out = self.wo(attention(q, k, v, mask=mask, gqa=self.gqa) * F.sigmoid(gate))
return out
@@ -326,8 +346,16 @@ class SingleStreamBlock(nn.Module):
self.mlp = SwiGLU(features, multiplier, bias)
def forward(
self, x: Tensor, vec: Tensor, freqs: Tensor, mask: Tensor | None = None
self,
x: Tensor,
vec: Tensor,
freqs: Tensor,
mask: Tensor | None = None,
ref_span: tuple[int, int] | None = None,
kv_capture: list | None = None,
kv_cache: tuple[Tensor, Tensor] | None = None,
) -> Tensor:
attn_kwargs = dict(ref_span=ref_span, kv_capture=kv_capture, kv_cache=kv_cache)
# ``vec`` is the (B, 1, 6*features) modulation input, or a tuple
# ``(vec, refvec, split)`` for reference-image conditioning: tokens
# ``[:split]`` (text + noisy image) are modulated with ``vec`` while
@@ -351,13 +379,15 @@ class SingleStreamBlock(nn.Module):
def gate(h, g):
return torch.cat((m[g] * h[:, :split], r[g] * h[:, split:]), dim=1)
x = x + gate(self.attn(mod(self.prenorm(x), 0, 1), freqs, mask), 2)
x = x + gate(
self.attn(mod(self.prenorm(x), 0, 1), freqs, mask, **attn_kwargs), 2
)
x = x + gate(self.mlp(mod(self.postnorm(x), 3, 4)), 5)
return x
prescale, preshift, pregate, postscale, postshift, postgate = self.mod(vec)
x = x + pregate * self.attn(
(1 + prescale) * self.prenorm(x) + preshift, freqs, mask
(1 + prescale) * self.prenorm(x) + preshift, freqs, mask, **attn_kwargs
)
x = x + postgate * self.mlp((1 + postscale) * self.postnorm(x) + postshift)
@@ -445,6 +475,9 @@ class SingleStreamDiT(nn.Module):
pos: Tensor,
mask: Tensor | None = None,
reflen: int = 0,
isolate_refs: bool = False,
ref_kv_capture: list | None = None,
ref_kv_cache: tuple[list, Tensor] | None = None,
) -> Tensor:
img = self.first(img)
t = self.tmlp(temb(t, self.config.tdim, device=img.device, dtype=img.dtype))
@@ -483,11 +516,46 @@ class SingleStreamDiT(nn.Module):
)
blockvec = (tvec, self.tproj(t0), txtlen + imglen - reflen)
padmask = mask # (B, L) key-padding mask, incl. the 256-alignment pad
mask = _mask(mask)
if reflen > 0 and isolate_refs:
# Asymmetric attention (OminiControl2-style "feature reuse"): ref
# queries attend only to ref keys, while text + noisy queries still
# see everything. Combined with the t=0 modulation above, ref hidden
# states become independent of t and of the noisy tokens, so their
# per-layer K/V can be computed once and cached across denoising
# steps at inference. Changes attention flow vs the base model, so
# it needs to be trained in.
split = txtlen + imglen - reflen
is_ref = torch.zeros(
combined.shape[1], dtype=torch.bool, device=combined.device
)
is_ref[split : split + reflen] = True
mask = mask & (~is_ref[:, None] | is_ref[None, :])
# Ref K/V caching (inference-only; requires isolate_refs so the cached
# features are step-invariant). Capture mode: this pass has the refs in
# the sequence and records each block's post-RoPE ref K/V. Reuse mode:
# the refs are dropped from the sequence (reflen == 0) and the cached
# K/V are appended as extra attention keys instead.
ref_span = None
if ref_kv_capture is not None and reflen > 0:
assert isolate_refs, "ref K/V capture requires isolate_refs"
split = txtlen + imglen - reflen
ref_span = (split, split + reflen)
blockcaches = [None] * len(self.blocks)
if ref_kv_cache is not None:
blockcaches, refmask = ref_kv_cache
# live queries may attend a cached ref key wherever that ref token
# is real (refmask right-pads samples with fewer ref tokens)
extra = padmask.unsqueeze(1).unsqueeze(3) & refmask.unsqueeze(1).unsqueeze(2)
mask = torch.cat((mask, extra), dim=3)
freqs = self.posemb(pos)
for block in self.blocks:
for block, blockkv in zip(self.blocks, blockcaches):
if self.gradient_checkpointing and torch.is_grad_enabled():
combined = checkpoint(
block,
@@ -498,7 +566,15 @@ class SingleStreamDiT(nn.Module):
use_reentrant=False,
)
else:
combined = block(combined, blockvec, freqs, mask)
combined = block(
combined,
blockvec,
freqs,
mask,
ref_span=ref_span,
kv_capture=ref_kv_capture,
kv_cache=blockkv,
)
final = self.last(combined, t)
output = final[:, txtlen : txtlen + imglen - reflen, :]