code-HFD / src /psi /models /interaction_arch /coupled_joint.py
Tinghong-Ye22's picture
Add files using upload-large-folder tool
06f9561 verified
Raw History Blame Contribute Delete
23.4 kB
"""True layer-internal, sparse dual-Qwen joint attention; isolated experiment.
At ONE penultimate-or-earlier tail layer, each query attends in a SINGLE softmax
to its full own causal KV plus sampled current-packet donor KV. Donor K/V are
stop-gradient. The exact native self-attention remains the zero-gate control:
``native + gate * (joint - native)``. Gate=1 is full joint attention; gate=0 is
the original backbone, including the original attention kernel and KV writes.
No source/past foreign bank is stored. Own history, eviction, MRoPE and ledger
remain owned by the unchanged formal encode_av. Text/answer branches NEVER
enter the joint executor. QA benefits through the NEXT layer's fused AV KV,
not by reading teacher-forced answer states or adding answers to the AV cache.
The paired executor uses a synchronous Python call stack, not threads: body
encode enters its model forward -> QA encode pauses at the selected layer ->
body model runs to that layer -> both layers are coupled -> body finishes ->
QA finishes -> body encode returns. The subsequent formal QA encode consumes
that already computed QA result, checking the original cache identity.
Register gates before optimizer construction, enable after prepare. No formal
source file is modified. Single-threaded; incompatible with other AV patches.
"""
from __future__ import annotations
from dataclasses import dataclass
from functools import wraps
from types import MethodType
import weakref
import torch
from torch import nn
from torch.nn import functional as F
from transformers.cache_utils import DynamicCache, DynamicLayer
from transformers.models.qwen2_5_omni.modeling_qwen2_5_omni import apply_multimodal_rotary_pos_emb
from psi.models import causal_av
from psi.models.full_duplex_psi0 import QwenStreamingKVCache
from psi.models.swa_qa_branch import OnlineQaBranch
class JointGate(nn.Module):
def __init__(self, device):
super().__init__()
# A signed residual interpolation gate. No hidden sigmoid epsilon and
# no second zero-initialized projection that would kill gate gradients.
self.gate = nn.Parameter(torch.zeros((), dtype=torch.float32, device=device))
def forward(self, native, joint, valid_queries):
correction = self.gate * (joint.float() - native.float())
correction = correction * valid_queries[..., None].to(correction.dtype)
return native + correction.to(native.dtype)
class JointAttentionQaBranch(OnlineQaBranch):
@property
def delta_keys(self):
return super().delta_keys | {"joint_qa." + key for key in self.joint_qa.state_dict()}
def audit_joint_optimizer(model, optimizer):
body_gate = {id(p) for p in model.joint_body.parameters()}
qa_gate = {id(p) for p in model.qa_model.joint_qa.parameters()}
qa_ids, nonqa_ids, all_ids = set(), set(), []
for group in optimizer.param_groups:
ids = {id(p) for p in group["params"]}
(qa_ids if group.get("group_name") == "swa_qa" else nonqa_ids).update(ids)
all_ids.extend(id(p) for p in group["params"])
if len(all_ids) != len(set(all_ids)):
raise RuntimeError("Duplicate optimizer parameters in joint experiment")
if not qa_gate <= qa_ids or qa_gate & nonqa_ids:
raise RuntimeError("QA joint gate must belong only to the existing swa_qa optimizer group")
if not body_gate <= nonqa_ids or body_gate & qa_ids:
raise RuntimeError("Body joint gate must belong only to the body optimizer groups")
def _clock(cache):
return (tuple(cache.source_ids), tuple(cache.logical_window_counts),
tuple(cache.av_next_positions or (0,) * len(cache.source_ids)), cache.slot_rebind_count)
def _empty(cache):
return (cache.past_key_values is None and cache.token_count == 0
and cache.attention_mask is None and not any(cache.logical_window_counts)
and not any(cache.av_next_positions))
@dataclass
class _Pair:
body_cache: object
qa_cache: object
original_qa_missing: bool
body_grad: bool
qa_grad: bool
phase: str = "start"
packets: object = None
active: object = None
prepared: object = None
body_args: object = None
qa_args: object = None
qa_layer_input: object = None
qa_layer_kwargs: object = None
body_output: object = None
qa_layer_output: object = None
qa_encoded: object = None
class CoupledJointRuntime:
def __init__(self, model, layer_index, max_cross_tokens):
self._model_ref = weakref.ref(model)
self.layer_index = layer_index
self.max_cross_tokens = max_cross_tokens
self.enabled = False
self._pair = None
self._restores = []
self._counts = dict(body_av_forwards=0, qa_av_forwards=0, paired_windows=0,
joint_softmax_calls=0, text_layer_bypasses=0,
current_cross_tokens_total=0)
@property
def stats(self):
model = self._model_ref()
return {**self._counts, "coupling_level": "internal_joint_attention",
"joint_layer_index": self.layer_index, "single_softmax_over_own_and_cross": True,
"cross_scope": "current_packet_causal_tokens", "max_cross_tokens": self.max_cross_tokens,
"donor_stop_gradient": True, "answer_writes_av": False,
"joint_backend": "torch_sdpa", "native_self_backend_unchanged": True,
"body_gate": float(model.joint_body.gate.detach()),
"qa_gate": float(model.qa_model.joint_qa.gate.detach()),
"resident_cross_history_banks": 0}
def _patch(self, owner, name, function):
self._restores.append((owner, name, name in owner.__dict__, owner.__dict__.get(name)))
setattr(owner, name, function)
def enable(self, model=None, *, optimizer=None, prepared=False):
model = self._model_ref() if model is None else model
if model is not self._model_ref() or not prepared or self.enabled:
raise RuntimeError("Enable once, after prepare, on the same unwrapped registered model")
for name in ("_coupled_joint_runtime", "_coupled_cross_runtime", "_shared_av_runtime"):
if getattr(causal_av, name, None) is not None:
raise RuntimeError("Another AV architecture dispatcher is installed")
if optimizer is not None:
audit_joint_optimizer(model, optimizer)
body, qa = model.vlm_model.model, model.qa_model.vlm_model.model
if body.embed_tokens.weight.device != qa.embed_tokens.weight.device:
raise RuntimeError("Paired joint prototype requires both Qwens on the same device")
for text, gate in ((body, model.joint_body), (qa, model.qa_model.joint_qa)):
if gate.gate.device != text.embed_tokens.weight.device or gate.gate.dtype != torch.float32:
raise RuntimeError("Joint gates must remain FP32 on their receiving model device")
if text.gradient_checkpointing or text.config.output_attentions or text.config.output_hidden_states:
raise RuntimeError("Joint prototype requires cache-enabled non-checkpointed ordinary AV forwards")
if text.config.attention_dropout or getattr(text, "has_sliding_layers", False):
raise RuntimeError("Joint prototype supports deterministic full-attention Qwen only")
self._original_encode = causal_av.encode_av
self._original_body_forward, self._original_qa_forward = body.forward, qa.forward
self._original_body_layer = body.layers[self.layer_index].forward
self._original_qa_layer = qa.layers[self.layer_index].forward
original_condition = model._encode_qwen_stream_input
@wraps(original_condition)
def condition(_model, **kwargs):
if _model.swa_packets is None:
return original_condition(**kwargs)
if self._pair is not None:
raise RuntimeError("Nested/concurrent paired AV encoding is forbidden")
cache = kwargs["cache"]
# This is EXACTLY the formal branch's cache selection. A missing
# QA history is empty only if the formal cache really has none.
private = cache.qa_cache or QwenStreamingKVCache.empty(cache.source_ids)
if _clock(cache) != _clock(private):
raise RuntimeError("Joint body/QA source incarnation or AV clock differs")
pair = self._pair = _Pair(cache, private, cache.qa_cache is None,
torch.is_grad_enabled(), torch.is_grad_enabled() and _model.training
and any(getattr(_model, "swa_answer_targets", ()) or ()))
try:
output = original_condition(**kwargs)
if pair.phase != "consumed":
raise RuntimeError("Formal body/QA pair was not completely consumed")
self._counts["paired_windows"] += 1
return output
finally:
self._pair = None
self._patch(model, "_encode_qwen_stream_input", MethodType(condition, model))
self._patch(body, "forward", self._body_forward)
self._patch(qa, "forward", self._qa_forward)
self._patch(body.layers[self.layer_index], "forward", self._body_layer)
self._patch(qa.layers[self.layer_index], "forward", self._qa_layer)
self._dispatch = self._encode_av
causal_av.encode_av = self._dispatch
causal_av._coupled_joint_runtime = self
self.enabled = True
return self
def _encode_av(self, qwen, cache, packets, active, **kwargs):
pair, model = self._pair, self._model_ref()
if pair is None:
return self._original_encode(qwen, cache, packets, active, **kwargs)
if qwen is model.vlm_model:
if pair.phase != "start" or cache is not pair.body_cache:
raise RuntimeError("Joint body encode has the wrong cache or ordering")
prepared = kwargs.get("prepared")
if prepared is None or prepared.embeds.requires_grad:
raise RuntimeError("Joint AV needs explicit frozen PreparedAVBatch")
pair.packets, pair.active, pair.prepared = packets, active, prepared
pair.phase = "body_entry"
result = self._original_encode(qwen, cache, packets, active, **kwargs)
if pair.phase != "body_return" or pair.qa_encoded is None:
raise RuntimeError("Joint executor did not finish both model forwards")
pair.phase = "await_qa"
self._counts["body_av_forwards"] += 1
return result
if qwen is model.qa_model.vlm_model:
if pair.phase != "await_qa" or packets is not pair.packets or kwargs.get("prepared") is not pair.prepared:
raise RuntimeError("Formal QA call does not match its precomputed AV pair")
same_cache = cache is pair.qa_cache
# Formal code constructs a second empty instance when qa_cache was
# None. Accept ONLY that genuinely empty, same-source initial case.
if not same_cache and not (pair.original_qa_missing and _empty(cache)
and cache.source_ids == pair.qa_cache.source_ids):
raise RuntimeError("QA cache identity differs; never fabricate or substitute AV history")
expected = (model.qa_model.memory_seconds, model.qa_model.av_context_limit, 128)
received = (kwargs.get("memory_seconds"), kwargs.get("context_limit"), kwargs.get("auxiliary", 128))
if received != expected:
raise RuntimeError("Formal QA cache budget differs from the precomputed QA budget")
pair.phase = "consumed"
return pair.qa_encoded
raise RuntimeError("Unrelated AV model interrupted the paired joint executor")
def _body_forward(self, *args, **kwargs):
pair = self._pair
if pair is None or pair.phase == "consumed":
return self._original_body_forward(*args, **kwargs)
if pair.phase != "body_entry" or args:
raise RuntimeError("Unexpected body model entry in paired AV execution")
self._validate_model_args(kwargs)
pair.body_args = kwargs
pair.phase = "qa_prefix"
model = self._model_ref()
model.qa_model.vlm_processor = model.vlm_processor
with torch.set_grad_enabled(pair.qa_grad):
pair.qa_encoded = self._original_encode(
model.qa_model.vlm_model, pair.qa_cache, pair.packets, pair.active,
memory_seconds=model.qa_model.memory_seconds,
context_limit=model.qa_model.av_context_limit, prepared=pair.prepared)
if pair.phase != "qa_suffix" or pair.body_output is None:
raise RuntimeError("QA failed to rendezvous with the body joint layer")
pair.phase = "body_return"
self._counts["qa_av_forwards"] += 1
return pair.body_output
def _qa_forward(self, *args, **kwargs):
pair = self._pair
if pair is None or pair.phase == "consumed":
return self._original_qa_forward(*args, **kwargs)
if pair.phase != "qa_prefix" or args:
raise RuntimeError("Text/extra QA forward attempted to enter the AV rendezvous")
self._validate_model_args(kwargs)
pair.qa_args = kwargs
return self._original_qa_forward(**kwargs)
@staticmethod
def _validate_model_args(kwargs):
if kwargs.get("use_cache") is not True or kwargs.get("return_dict") is not True:
raise RuntimeError("Joint AV requires the formal cached model return contract")
for key in ("inputs_embeds", "attention_mask", "position_ids", "cache_position"):
if not isinstance(kwargs.get(key), torch.Tensor):
raise RuntimeError("Joint AV requires explicit tensor input/mask/position geometry")
if kwargs["attention_mask"].ndim != 2 or kwargs["position_ids"].shape[0] != 3:
raise RuntimeError("Unsupported packed/custom AV geometry")
def _qa_layer(self, hidden, **kwargs):
pair = self._pair
if pair is None or pair.phase == "consumed":
self._counts["text_layer_bypasses"] += 1
return self._original_qa_layer(hidden, **kwargs)
if pair.phase != "qa_prefix":
raise RuntimeError("QA joint-layer rendezvous occurred twice or out of order")
pair.qa_layer_input, pair.qa_layer_kwargs = hidden, kwargs
pair.phase = "body_running"
with torch.set_grad_enabled(pair.body_grad):
pair.body_output = self._original_body_forward(**pair.body_args)
if pair.qa_layer_output is None:
raise RuntimeError("Body did not produce the paired QA layer output")
pair.phase = "qa_suffix"
return pair.qa_layer_output
def _body_layer(self, hidden, **kwargs):
pair = self._pair
if pair is None or pair.phase == "consumed":
self._counts["text_layer_bypasses"] += 1
return self._original_body_layer(hidden, **kwargs)
if pair.phase != "body_running" or pair.qa_layer_input is None:
raise RuntimeError("Body joint layer has no same-window QA input")
body_output, qa_output = self._joint_layers(hidden, kwargs, pair)
pair.qa_layer_output = qa_output
return body_output
def _native_attention(self, layer, hidden, kwargs, model_args):
captured = []
handle = layer.self_attn.q_proj.register_forward_hook(lambda _m, _a, output: captured.append(output))
try:
normalized = layer.input_layernorm(hidden)
native, _ = layer.self_attn(hidden_states=normalized, **kwargs)
finally:
handle.remove()
if len(captured) != 1:
raise RuntimeError("Expected exactly one native query projection")
attn = layer.self_attn
query = captured[0].view(hidden.shape[0], hidden.shape[1], -1, attn.head_dim).transpose(1, 2)
cos, sin = kwargs["position_embeddings"]
query = apply_multimodal_rotary_pos_emb(query, query, cos, sin, attn.rope_scaling["mrope_section"])[0]
cache = kwargs["past_key_values"]
if type(cache) is not DynamicCache or type(cache.layers[self.layer_index]) is not DynamicLayer:
raise RuntimeError("Joint requires independent full-attention DynamicCache layers")
cached = cache.layers[self.layer_index]
if model_args["attention_mask"].shape != (hidden.shape[0], cached.keys.shape[-2]):
raise RuntimeError("Own attention mask and physically updated KV disagree")
return dict(layer=layer, hidden=hidden, native=native, query=query,
keys=cached.keys, values=cached.values, full_mask=model_args["attention_mask"])
def _joint_attention(self, own, donor, gate, current_mask):
query, keys, values = own["query"], own["keys"], own["values"]
batch, _, width, _ = query.shape
count = min(width, self.max_cross_tokens)
# Fixed deterministic subsampling, independent of labels/query content.
# No pooled future-token summaries are introduced by the sparse bank.
indices = torch.arange(count, device=query.device) * width // count
donor_keys = donor["keys"][..., -width:, :].detach().index_select(-2, indices)
donor_values = donor["values"][..., -width:, :].detach().index_select(-2, indices)
all_keys = torch.cat((keys, donor_keys.to(keys.dtype)), dim=-2)
all_values = torch.cat((values, donor_values.to(values.dtype)), dim=-2)
query_order = torch.arange(width, device=query.device)
own_order = torch.arange(keys.shape[-2], device=query.device)
own_visible = (own["full_mask"].bool()[:, None, None, :]
& (own_order[None, :] <= keys.shape[-2] - width + query_order[:, None])[None, None])
cross_visible = (current_mask.bool().index_select(-1, indices)[:, None, None, :]
& (indices[None, :] <= query_order[:, None])[None, None])
visible = torch.cat((own_visible, cross_visible), dim=-1)
# ONE normalization over the concatenated banks. The original FA2/eager
# self path above remains untouched; only this new selected-layer joint
# path uses SDPA's explicit boolean causal block mask.
joint = F.scaled_dot_product_attention(
query, all_keys, all_values, attn_mask=visible, dropout_p=0.,
is_causal=False, scale=own["layer"].self_attn.scaling,
enable_gqa=query.shape[1] != all_keys.shape[1])
joint = joint.transpose(1, 2).reshape(batch, width, -1).contiguous()
joint = own["layer"].self_attn.o_proj(joint)
self._counts["joint_softmax_calls"] += 1
self._counts["current_cross_tokens_total"] += count
return gate(own["native"], joint, current_mask.bool())
@staticmethod
def _finish_layer(layer, residual, attention):
hidden = residual + attention
return (hidden + layer.mlp(layer.post_attention_layernorm(hidden)),)
def _joint_layers(self, body_hidden, body_kwargs, pair):
model = self._model_ref()
body_layer = model.vlm_model.model.layers[self.layer_index]
qa_layer = model.qa_model.vlm_model.model.layers[self.layer_index]
width = pair.prepared.mask.shape[1]
if body_hidden.shape != pair.qa_layer_input.shape or body_hidden.shape[:2] != pair.prepared.mask.shape:
raise RuntimeError("Joint current-packet hidden geometry differs across sources/branches")
if not torch.equal(pair.body_args["position_ids"], pair.qa_args["position_ids"]):
raise RuntimeError("Current-packet absolute multimodal positions differ across branches")
for arguments in (pair.body_args, pair.qa_args):
if not torch.equal(arguments["attention_mask"][:, -width:], pair.prepared.mask):
raise RuntimeError("Current-packet masks differ; source/padding isolation would be unsafe")
if body_kwargs["past_key_values"] is pair.qa_layer_kwargs["past_key_values"]:
raise RuntimeError("Mutable AV cache containers must never be shared")
with torch.set_grad_enabled(pair.body_grad):
body = self._native_attention(body_layer, body_hidden, body_kwargs, pair.body_args)
with torch.set_grad_enabled(pair.qa_grad):
qa = self._native_attention(qa_layer, pair.qa_layer_input, pair.qa_layer_kwargs, pair.qa_args)
with torch.set_grad_enabled(pair.body_grad):
body_attention = self._joint_attention(body, qa, model.joint_body, pair.prepared.mask)
body_output = self._finish_layer(body_layer, body_hidden, body_attention)
with torch.set_grad_enabled(pair.qa_grad):
qa_attention = self._joint_attention(qa, body, model.qa_model.joint_qa, pair.prepared.mask)
qa_output = self._finish_layer(qa_layer, pair.qa_layer_input, qa_attention)
return body_output, qa_output
def close(self):
if self._pair is not None:
raise RuntimeError("Cannot close an active joint pair")
if not self.enabled:
return
if causal_av.encode_av is not self._dispatch:
raise RuntimeError("Another patch replaced the joint dispatcher")
causal_av.encode_av = self._original_encode
if getattr(causal_av, "_coupled_joint_runtime", None) is self:
del causal_av._coupled_joint_runtime
for owner, name, had_value, value in reversed(self._restores):
if had_value:
setattr(owner, name, value)
else:
delattr(owner, name)
self._restores.clear()
self.enabled = False
def register_coupled_joint(model, *, layer_index=34, max_cross_tokens=32):
"""Register two FP32 scalar gates before optimizer creation; no hooks yet."""
qa = getattr(model, "qa_model", None)
if type(qa) is not OnlineQaBranch:
raise TypeError("Register joint on the unmodified formal OnlineQaBranch")
if hasattr(model, "joint_body") or hasattr(qa, "joint_qa"):
raise RuntimeError("Joint gates already registered")
body, reader = model.vlm_model.model, qa.vlm_model.model
if len(body.layers) != len(reader.layers) or not len(body.layers) - 8 <= layer_index < len(body.layers) - 1:
raise ValueError("Joint must be in the trainable tail and before the final layer so QA AV KV can change")
if max_cross_tokens < 1:
raise ValueError("Sparse current-packet cross bank must contain at least one token")
if {id(p) for p in model.vlm_model.parameters()} & {id(p) for p in qa.vlm_model.parameters()}:
raise ValueError("Joint requires genuinely independent Qwen backbones")
left, right = body.layers[layer_index].self_attn, reader.layers[layer_index].self_attn
for name in ("head_dim", "num_heads", "num_key_value_heads", "rope_scaling"):
if getattr(left, name) != getattr(right, name):
raise ValueError("Joint attention head/RoPE geometry must agree across branches")
model.joint_body = JointGate(body.embed_tokens.weight.device)
qa.joint_qa = JointGate(reader.embed_tokens.weight.device)
qa.__class__ = JointAttentionQaBranch
return CoupledJointRuntime(model, layer_index, max_cross_tokens)