[Perf][Qwen3-TTS] Fuse QKV and gate_up projections in code predictor (#5791)

Signed-off-by: sheenlin <sheenlin@tencent.com>
Signed-off-by: Gao Han <hgaoaf@connect.ust.hk>
Co-authored-by: sheenlin <sheenlin@tencent.com>
Co-authored-by: yurain <yurain26@users.noreply.github.com>
Co-authored-by: Gao Han <hgaoaf@connect.ust.hk>
This commit is contained in:
authored and GitHub committed 2026-08-20 19:22:40 +00:00
1 parent 13c2de684c
commit 37c11e6e4f
9 files changed
+972 -41

No files matched your search

+102
View File
@@ -414,6 +414,108 @@ def test_qwen3_tts_code_predictor_forward_uses_projected_embedding_and_sampling(
assert sample_calls == [{0: generator}]
def test_310p_attention_forward_runs_fused_qkv_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
"""Exercise the mocked 310P fused-QKV path at runtime on CPU.
The reviewer explicitly asked for more than source inspection: this test now
instantiates the patched attention, runs ``prepare_qkv_weights()``, verifies
the packed weight/bias cache, and drives the mocked 310P flash-attention op.
"""
module, _ = _load_qwen3_tts_patch(monkeypatch)
trans_calls = []
rotary_calls = []
flash_calls = []
def maybe_trans_nz(weight: torch.Tensor) -> torch.Tensor:
trans_calls.append(weight.detach().clone())
return weight + 1.0
def npu_rotary_mul(hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
rotary_calls.append((hidden_states.detach().clone(), cos.detach().clone(), sin.detach().clone()))
return hidden_states + cos - sin
def npu_flash_attention(**kwargs) -> None:
flash_calls.append(
{key: value.detach().clone() if torch.is_tensor(value) else value for key, value in kwargs.items()}
)
kwargs["out"].copy_((kwargs["query"] + kwargs["key"] + kwargs["value"]).to(kwargs["out"].dtype))
monkeypatch.setattr(module, "maybe_trans_nz", maybe_trans_nz)
monkeypatch.setattr(module, "aligned_16", lambda tensor: tensor)
monkeypatch.setattr(module.torch_npu, "npu_rotary_mul", npu_rotary_mul, raising=False)
monkeypatch.setattr(module.torch_npu, "_npu_flash_attention", npu_flash_attention, raising=False)
config = SimpleNamespace(
num_attention_heads=2,
num_key_value_heads=2,
head_dim=2,
hidden_size=4,
num_code_groups=2,
attention_bias=True,
rms_norm_eps=1e-6,
)
attention = module._Qwen3CodePredictorAttention310P(config)
attention.num_heads = 2
attention.num_kv_heads = 2
attention.head_dim = 2
attention.scaling = 0.5
attention._q_size = attention.num_heads * attention.head_dim
attention._kv_size = attention.num_kv_heads * attention.head_dim
attention.q_norm = torch.nn.Identity()
attention.k_norm = torch.nn.Identity()
attention.o_proj = torch.nn.Identity()
attention.qkv_proj = torch.nn.Linear(4, attention._q_size + 2 * attention._kv_size, bias=True)
with torch.no_grad():
attention.qkv_proj.weight.copy_(torch.arange(48, dtype=torch.float32).reshape(12, 4) / 10)
attention.qkv_proj.bias.copy_(torch.arange(12, dtype=torch.float32) / 10)
attention._split_qkv = lambda qkv: qkv.split([attention._q_size, attention._kv_size, attention._kv_size], dim=-1)
attention.prepare_qkv_weights()
assert len(trans_calls) == 1
assert trans_calls[0].is_contiguous()
expected_fused_weight = attention.qkv_proj.weight.detach().clone().contiguous() + 1.0
torch.testing.assert_close(attention._fused_qkv_weight, expected_fused_weight)
assert attention._fused_qkv_bias is attention.qkv_proj.bias
hidden_states = (torch.arange(12, dtype=torch.float32).reshape(1, 3, 4) - 3) / 10
cos = torch.full((1, 3, 2), 0.25, dtype=torch.float32)
sin = torch.full((1, 3, 2), -0.5, dtype=torch.float32)
attention_mask = torch.arange(9, dtype=torch.float32).reshape(3, 3)
output = attention(hidden_states, (cos, sin), attention_mask=attention_mask)
expected_qkv = torch.nn.functional.linear(hidden_states, expected_fused_weight, attention.qkv_proj.bias)
expected_q_raw, expected_k_raw, expected_v_raw = expected_qkv.split(
[attention._q_size, attention._kv_size, attention._kv_size],
dim=-1,
)
expected_q = expected_q_raw.view(1, 3, attention.num_heads, attention.head_dim).transpose(1, 2)
expected_k = expected_k_raw.view(1, 3, attention.num_kv_heads, attention.head_dim).transpose(1, 2)
expected_v = expected_v_raw.view(1, 3, attention.num_kv_heads, attention.head_dim).transpose(1, 2)
expected_cos = cos.unsqueeze(1)
expected_sin = sin.unsqueeze(1)
expected_q = expected_q + expected_cos - expected_sin
expected_k = expected_k + expected_cos - expected_sin
expected_q_f = expected_q.transpose(1, 2).reshape(3, attention.num_heads, attention.head_dim)
expected_k_f = expected_k.transpose(1, 2).reshape(3, attention.num_kv_heads, attention.head_dim)
expected_v_f = expected_v.transpose(1, 2).reshape(3, attention.num_kv_heads, attention.head_dim)
expected_flash = (expected_q_f + expected_k_f + expected_v_f).to(torch.float16).to(torch.float32)
assert len(rotary_calls) == 2
assert len(flash_calls) == 1
torch.testing.assert_close(flash_calls[0]["query"], expected_q_f)
torch.testing.assert_close(flash_calls[0]["key"], expected_k_f)
torch.testing.assert_close(flash_calls[0]["value"], expected_v_f)
torch.testing.assert_close(flash_calls[0]["mask"], attention_mask)
torch.testing.assert_close(flash_calls[0]["seq_len"], torch.tensor([3], dtype=torch.int32))
assert flash_calls[0]["scale_value"] == pytest.approx(0.5)
assert flash_calls[0]["num_heads"] == 2
assert flash_calls[0]["num_kv_heads"] == 2
torch.testing.assert_close(output, expected_flash.reshape(1, 3, 4))
def test_qwen3_tts_talker_patch_uses_fp16_runtime_dtype(monkeypatch: pytest.MonkeyPatch) -> None:
module, _ = _load_qwen3_tts_patch(monkeypatch)
talker = module._Qwen3TTSTalker310P(vllm_config=object())