File size: 6,435 Bytes
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""Qwen3-TTS-12Hz sequence layouts shared by TTS-V4 training and streaming inference.

stream_icl / stream_xvec reproduce Qwen3-TTS native dual-track streaming
(generate(..., non_streaming_mode=False)) token for token, but take the target
text incrementally so generation can start before the full text exists.
Conditioning layout follows QwenLM/Qwen3-TTS (Apache-2.0).
"""
import torch

PAD, EOS = -1, -2  # sentinels in the text track


def special_embeds(tts):
    talker, cfg = tts.model.talker, tts.model.config
    ids = torch.tensor([[cfg.tts_bos_token_id, cfg.tts_eos_token_id, cfg.tts_pad_token_id]], device=talker.device)
    bos, eos, pad = talker.text_projection(talker.get_text_embeddings()(ids)).chunk(3, dim=1)
    return bos[0, 0], eos[0, 0], pad[0, 0]


def text_embeds(tts, ids):
    """ids: list[int] with PAD/EOS sentinels -> [len, D]."""
    talker = tts.model.talker
    _, eos, pad = special_embeds(tts)
    if not ids:
        return pad[None, :0]
    real = [i for i in ids if i >= 0]
    out = torch.empty(len(ids), pad.shape[0], device=pad.device, dtype=pad.dtype)
    if real:
        emb = talker.text_projection(talker.get_text_embeddings()(torch.tensor([real], device=talker.device)))[0]
    k = 0
    for j, i in enumerate(ids):
        if i == PAD:
            out[j] = pad
        elif i == EOS:
            out[j] = eos
        else:
            out[j] = emb[k]
            k += 1
    return out


def role_control(tts, speaker, role_ids):
    """role (3) + control (6) positions, identical to native generate()."""
    model, talker, cfg = tts.model, tts.model.talker, tts.model.config
    device = talker.device
    bos, _, pad = special_embeds(tts)
    tags = torch.tensor([[cfg.talker_config.codec_think_id, cfg.talker_config.codec_think_bos_id,
                          cfg.talker_config.codec_language_id['chinese'], cfg.talker_config.codec_think_eos_id]], device=device)
    tail = torch.tensor([[cfg.talker_config.codec_pad_id, cfg.talker_config.codec_bos_id]], device=device)
    codec = torch.cat([talker.get_input_embeddings()(tags), speaker.to(device, pad.dtype).view(1, 1, -1),
                       talker.get_input_embeddings()(tail)], dim=1)
    role = talker.text_projection(talker.get_text_embeddings()(role_ids.to(device).view(1, -1)))
    control = torch.cat([pad.view(1, 1, -1).expand(-1, codec.shape[1] - 2, -1), bos.view(1, 1, -1)], dim=1) + codec[:, :-1]
    return torch.cat([role, control], dim=1)[0]


def frame_embeds(tts, codes):
    """[T,16] codes -> [T,D] summed codec embeddings (talker book 0 + predictor books 1..15)."""
    talker = tts.model.talker
    codes = codes.to(talker.device)
    parts = [talker.get_input_embeddings()(codes[:, :1])]
    parts += [talker.code_predictor.get_input_embeddings()[i - 1](codes[:, i:i + 1]) for i in range(1, 16)]
    return torch.cat(parts, dim=1).sum(1)  # same summation order as native generate()


def ref_codec_embeds(tts, ref_codes):
    talker, cfg = tts.model.talker, tts.model.config
    bos = talker.get_input_embeddings()(torch.tensor([cfg.talker_config.codec_bos_id], device=talker.device))
    return torch.cat([bos, frame_embeds(tts, ref_codes)], dim=0)


def stream_track(mode, ref_ids, target_ids, ended, gap=0):
    """Native Qwen3-TTS dual-track text stream.

    icl : reference transcript then target text then EOS, laid over [codec BOS +
          reference frames] and continuing one token per generated frame
          (generate(..., non_streaming_mode=False) with an ICL prompt).
          gap > 0: EXPERIMENTAL, not used for inference. PAD tokens between the
          reference transcript and the target text (tried for an earlier start;
          free-running generation collapsed even after training).
    xvec: target text then EOS; first token on the codec-BOS position, then one
          token per generated frame (x-vector/speaker-embedding prompt).
    iclx: EXPERIMENTAL, not used for inference (see stream_prefix; did not train well).
    """
    track = (list(ref_ids) + [PAD] * gap if mode == 'icl' else []) + list(target_ids)
    if ended:
        track.append(EOS)
    return track


def prefix_positions(mode, ref_codes):
    """Prefix positions that carry text-track elements (the rest of the track goes one per generated frame)."""
    return 1 + ref_codes.shape[0] if mode == 'icl' else 1


def required_target_tokens(mode, ref_ids, ref_codes):
    """Target tokens needed before generation can start (if text has not ended)."""
    if mode == 'icl':
        return max(0, prefix_positions(mode, ref_codes) - len(ref_ids))
    return 1  # xvec, iclx


def low_latency_gap(mode, ref_ids, ref_codes, available, ended):
    """PAD gap that lets icl generation start with only `available` target tokens."""
    if mode != 'icl' or ended:
        return 0
    return max(0, required_target_tokens(mode, ref_ids, ref_codes) - available)


def stream_prefix(tts, mode, speaker, role_ids, ref_ids, ref_codes, target_ids, ended, gap=0):
    """Prefill embeddings and the text-track remainder for generated frames."""
    talker, cfg = tts.model.talker, tts.model.config
    if mode == 'iclx':
        # V4 low-latency ICL: reference transcript (+codec pad) then [codec BOS + reference frames]
        # (+text pad), as in native non-streaming ICL but without the target text; the target text
        # then streams dual-track from the last reference frame on, one token per frame (as xvec).
        pad_code = talker.get_input_embeddings()(torch.tensor([cfg.talker_config.codec_pad_id], device=talker.device))
        ref_text = text_embeds(tts, list(ref_ids)) + pad_code
        codec = ref_codec_embeds(tts, ref_codes)
        track = list(target_ids) + ([EOS] if ended else [])
        head = [PAD] * (codec.shape[0] - 1) + track[:1] + [PAD] * (1 - len(track[:1]))
        prefix = torch.cat([role_control(tts, speaker, role_ids), ref_text, text_embeds(tts, head) + codec], dim=0)
        return prefix, track[1:]
    if mode == 'icl':
        codec = ref_codec_embeds(tts, ref_codes)
    else:
        codec = talker.get_input_embeddings()(torch.tensor([cfg.talker_config.codec_bos_id], device=talker.device))
    n = codec.shape[0]
    track = stream_track(mode, ref_ids, target_ids, ended, gap)
    head = track[:n] + [PAD] * max(0, n - len(track))
    prefix = torch.cat([role_control(tts, speaker, role_ids), text_embeds(tts, head) + codec], dim=0)
    return prefix, track[n:]