#1953·CosyVoice

CosyVoice 2/3 output collapses into unintelligible speech on transformers >= 4.53: forward_one_step passes a mask frozen at prompt length

Author: xuyukuanCreated Oct 1, 2026Updated Oct 1, 2026

Summary

CosyVoice 2 / CosyVoice 3 produce fluent-sounding nonsense on transformers >= 4.53 (upstream pins 4.51.3). This has been reported repeatedly (#1446, #1735, #1636, #1886) and a community workaround was posted in a comment on #1446, but I could not find a precise mechanism anywhere — every report stops at "transformers version problem". I traced it to a single expression and quantified it.

Root cause: Qwen2Encoder.forward_one_step in cosyvoice/llm/llm.py computes its attention mask as masks[:, -1, :], whose width is frozen at the initial prompt length. transformers >= 4.53 requires the 2D mask to span number_of_seen_tokens + q_length and silently pads a shorter mask with 0 — which on a torch.bool mask means False, i.e. "do not attend". From decoding step 1 onward, every freshly sampled speech token is appended to the KV cache and then immediately excluded from attention.

Environment

OS Windows 11
GPU RTX 3060
torch / torchaudio 2.7.0+cu128
transformers 4.57.6 (upstream pins 4.51.3)
onnxruntime 1.18.0 (CPU build)
CosyVoice commit 074ca6d
Model Fun-CosyVoice3-0.5B

Symptom

inference_zero_shot with the shipped asset/zero_shot_prompt.wav:

  • output duration jumps unpredictably between 0.12 s and 15.20 s for the same input text
  • the long case is exactly max_token_text_ratio (20) × text_tokens (19) × 40 ms — the LLM runs into the hard ceiling and never emits EOS
  • ASR (faster-whisper large-v3-turbo) transcribes the output as Yeah. Nah. Bye., or surfaces training-set boilerplate such as 请不吝点赞 订阅 转发 打赏支持明镜与点点栏目 — 0 % character recall

The audio is fluent — correct prosody, correct speaker timbre — which is why this is easily mistaken for a model-quality problem rather than a masking bug.

Root cause

cosyvoice/llm/llm.py (unchanged upstream code):

python
def forward_one_step(self, xs, masks, cache=None):
    input_masks = masks[:, -1, :]                 # <-- width frozen at prompt length
    outs = self.model(
        inputs_embeds=xs,
        attention_mask=input_masks,
        ...
    )

# call site, `Qwen2LM.inference_wrapper`:
masks = torch.tril(torch.ones((1, lm_input.shape[1], lm_input.shape[1]), device=...)).to(torch.bool)

masks[:, -1, :] is the last row of a lower-triangular all-ones matrix. That row is all-True, and its width is lm_input.shape[1] — the initial prompt length (41 tokens in the case below). masks is built once, outside the decode loop, so that width never changes, while kv_length grows 41 → 42 → 43 → …

In transformers/masking_utils.py (4.57.6), _preprocess_mask_arguments / sdpa_mask_recent_torch:

python
if (padding_length := kv_length + kv_offset - attention_mask.shape[-1]) > 0:
    local_padding_mask = torch.nn.functional.pad(attention_mask, (0, padding_length))

and the docstring of create_causal_mask states the 2D mask is

"corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length)"

So the missing padding_length = kv_length − 41 trailing positions are padded with 0. The tensor is torch.bool; 0 is False, which means masked out. The model never sees the speech tokens it just generated.

This also explains the two sharpest observations:

  • step 0 is bit-identical to a correct full-sequence forward — at step 0 padding_length == 0, so nothing is masked
  • divergence begins exactly at step 1, and the frozen hidden states at the tail of a long generation (|hidden| identical to the 4th decimal for the last 8 steps)

Measurements

Teacher-forcing the prompt clip's own 87 speech tokens and scoring the model's probability of the true next token at each step:

decoding path avg log-prob perplexity distinct |hidden| values
one-shot full-sequence forward (proper causal mask) −3.593 36.35 87 / 87
current forward_one_step (KV cache) −6.892 983.91 76 / 87
variant: full-width mask −3.593 36.35 87 / 87
variant: attention_mask=None −3.593 36.35 87 / 87
variant: full-width mask + explicit position_ids −3.593 36.35 87 / 87

Perplexity 36 is a healthy figure for a 6561-entry speech-token vocabulary; 984 is indistinguishable from sampling noise. Note that the three variants converge to bit-identical values, which rules out a dtype / numerical-drift explanation.

Suggested fix

masks[:, -1, :] is the last row of tril(ones), i.e. all-True — so an all-True mask of the correct width is an exact drop-in replacement:

python
def forward_one_step(self, xs, masks, cache=None):
    if cache is None:
        past = 0
    else:
        try:
            past = cache.get_seq_length()
        except AttributeError:
            past = cache[0][0].shape[-2]
    input_masks = torch.ones(1, past + xs.shape[1], dtype=torch.bool, device=xs.device)
    outs = self.model(
        inputs_embeds=xs,
        attention_mask=input_masks,
        output_hidden_states=True,
        return_dict=True,
        use_cache=True,
        past_key_values=cache,
    )
    xs = outs.hidden_states[-1]
    new_cache = outs.past_key_values
    return xs, new_cache

This is the same shape of fix as the one posted by @EmreOzkose in #1446 (attention_mask=masks instead of masks[:, -1, :]) — two independent traces landing on the same expression. masks is kept in the signature for call-site compatibility.

Verification

Same request, same reference clip, 6 seeded runs:

before after
duration 2.28 / 9.48 / 2.88 s (unstable) 2.44–3.48 s
ASR language en 0.27–0.29 / zh 0.56 (self-contradictory) zh, language_probability 0.99–1.00
ASR transcript Yeah. Nah. Bye. / 比赞人汤我比赞不复… 今天天气不错,我们一起出去走走吧 — 6/6 identical
character recall 0 % 100 % (15/15, ignoring punctuation)
ASR avg log-prob −0.94 −0.15

Related observations (not the cause, not changed here)

  • CosyVoice3LM does not override inference / inference_wrapper, so it inherits Qwen2LM's. Worth documenting explicitly, because the v2 and v3 special-token layouts are incompatible (sos=6561 / eos=6562 vs sos=0 / eos=6561) and the dispatch is by self.__class__.__name__.
  • sampling_ids masks self.speech_token_size (which is sos, 6561) under ignore_eos, rather than eos (6562). Harmless while generation is healthy — the model emits EOS reliably once the mask above is fixed — but PR #1916 looks like it touches the same spot.

Other reports of the same symptom

#1446 (transformers 4.53.1 / 4.53.2, and 4.40.1 incidentally) · #1735 (zero-shot voice cloning "mostly gibberish") · #1636 · #1886 (torch ≥ 2.7 for RTX 50-series) · plus #1692 and #1741 as cited by #1886.

This issue is submitted as a consolidated, root-caused report rather than another symptom-only one.