qwen_tts 0.1.1

Qwen3-TTS text-to-speech model implementation for Candle
Documentation
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Voice cloning configuration and prompt structures.

use candle_core::Tensor;

/// Configuration for voice cloning generation.
#[derive(Debug, Clone)]
pub struct VoiceCloneConfig {
    /// Maximum number of tokens to generate
    pub max_new_tokens: usize,
    /// Minimum duration in seconds
    pub min_duration: Option<f32>,
    /// Maximum duration in seconds
    pub max_duration: Option<f32>,
}

impl Default for VoiceCloneConfig {
    fn default() -> Self {
        Self {
            max_new_tokens: 2048,
            min_duration: None,
            max_duration: Some(30.0),
        }
    }
}

/// Container for one sample's voice-clone prompt information.
///
/// This struct holds all the information needed to perform voice cloning
/// for a single sample in a batch.
///
/// # Modes
///
/// - **X-vector only mode** (`x_vector_only_mode = true`): Only the speaker embedding
///   is used. No in-context learning. `ref_code` and `ref_text` are ignored.
///
/// - **ICL mode** (`icl_mode = true`): In-context learning mode where the model
///   learns from the reference audio and transcript. Requires both `ref_code`
///   and `ref_text` to be present.
///
/// # Example
///
/// ```no_run
/// use qwen_tts::model::voice_clone::VoiceClonePromptItem;
/// use candle_core::{Device, Tensor, DType};
///
/// # fn main() -> candle_core::Result<()> {
/// let device = Device::Cpu;
/// let speaker_embedding = Tensor::zeros((1024,), DType::F32, &device)?;
/// let ref_codes = Tensor::zeros((100, 32), DType::I64, &device)?;
///
/// // X-vector only mode - just clone speaker characteristics
/// let prompt = VoiceClonePromptItem::x_vector_only(speaker_embedding.clone());
///
/// // ICL mode - learn from reference audio and transcript
/// let prompt = VoiceClonePromptItem::icl(
///     ref_codes,
///     speaker_embedding,
///     "Hello, this is a reference transcript.".to_string(),
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct VoiceClonePromptItem {
    /// Reference audio codes from the tokenizer.
    ///
    /// Shape depends on tokenizer type:
    /// - 12Hz (V2): `(codes_len, num_quantizers)` - 2D tensor
    /// - 25Hz (V1): `(codes_len,)` - 1D tensor
    ///
    /// Required for ICL mode, optional for x-vector only mode.
    pub ref_code: Option<Tensor>,

    /// Speaker embedding extracted from reference audio.
    ///
    /// Shape: `(speaker_dim,)` typically 1024 dimensions.
    /// Always required.
    pub ref_spk_embedding: Tensor,

    /// Whether to use x-vector (speaker embedding) only mode.
    ///
    /// When true, only the speaker embedding is used for voice cloning.
    /// The model won't use ICL (in-context learning) from reference audio.
    pub x_vector_only_mode: bool,

    /// Whether in-context learning mode is enabled.
    ///
    /// When true (and x_vector_only_mode is false), the model uses both
    /// the speaker embedding and learns from the reference audio/transcript.
    /// Requires `ref_code` and `ref_text` to be present.
    pub icl_mode: bool,

    /// Reference transcript text.
    ///
    /// The text spoken in the reference audio. Required for ICL mode
    /// so the model can learn the correspondence between text and audio.
    pub ref_text: Option<String>,
}

impl VoiceClonePromptItem {
    /// Create a new voice clone prompt for x-vector only mode.
    ///
    /// In this mode, only the speaker embedding is used for voice cloning.
    /// This is simpler but may not capture prosodic patterns as well as ICL mode.
    ///
    /// # Arguments
    ///
    /// * `ref_spk_embedding` - Speaker embedding tensor of shape `(speaker_dim,)`
    pub fn x_vector_only(ref_spk_embedding: Tensor) -> Self {
        Self {
            ref_code: None,
            ref_spk_embedding,
            x_vector_only_mode: true,
            icl_mode: false,
            ref_text: None,
        }
    }

    /// Create a new voice clone prompt for ICL (in-context learning) mode.
    ///
    /// In this mode, the model learns from both the speaker embedding and
    /// the reference audio/transcript pair. This typically produces better
    /// results for matching prosody and speaking style.
    ///
    /// # Arguments
    ///
    /// * `ref_code` - Audio codes from the tokenizer
    /// * `ref_spk_embedding` - Speaker embedding tensor
    /// * `ref_text` - Transcript of the reference audio
    pub fn icl(ref_code: Tensor, ref_spk_embedding: Tensor, ref_text: String) -> Self {
        Self {
            ref_code: Some(ref_code),
            ref_spk_embedding,
            x_vector_only_mode: false,
            icl_mode: true,
            ref_text: Some(ref_text),
        }
    }

    /// Create a new voice clone prompt with all fields specified.
    pub fn new(
        ref_code: Option<Tensor>,
        ref_spk_embedding: Tensor,
        x_vector_only_mode: bool,
        ref_text: Option<String>,
    ) -> Self {
        Self {
            ref_code,
            ref_spk_embedding,
            x_vector_only_mode,
            icl_mode: !x_vector_only_mode,
            ref_text,
        }
    }

    /// Check if this prompt is valid for its mode.
    ///
    /// Returns an error message if validation fails.
    pub fn validate(&self) -> Result<(), String> {
        if self.icl_mode && !self.x_vector_only_mode {
            // ICL mode requires ref_code and ref_text
            if self.ref_code.is_none() {
                return Err("ICL mode requires ref_code to be present".to_string());
            }
            if self.ref_text.is_none() {
                return Err("ICL mode requires ref_text to be present".to_string());
            }
        }
        Ok(())
    }

    /// Returns true if this prompt uses ICL mode.
    pub fn is_icl(&self) -> bool {
        self.icl_mode && !self.x_vector_only_mode
    }

    /// Returns true if this prompt uses x-vector only mode.
    pub fn is_x_vector_only(&self) -> bool {
        self.x_vector_only_mode
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use candle_core::{DType, Device};

    fn create_test_embedding() -> Tensor {
        Tensor::zeros((1024,), DType::F32, &Device::Cpu).unwrap()
    }

    fn create_test_codes() -> Tensor {
        Tensor::zeros((100, 32), DType::I64, &Device::Cpu).unwrap()
    }

    // =========================================================================
    // X-Vector Only Mode Tests
    // =========================================================================

    #[test]
    fn test_x_vector_only_creation() {
        let embedding = create_test_embedding();
        let prompt = VoiceClonePromptItem::x_vector_only(embedding);

        assert!(
            prompt.ref_code.is_none(),
            "x_vector_only should have no ref_code"
        );
        assert!(
            prompt.x_vector_only_mode,
            "x_vector_only_mode should be true"
        );
        assert!(!prompt.icl_mode, "icl_mode should be false");
        assert!(
            prompt.ref_text.is_none(),
            "x_vector_only should have no ref_text"
        );
    }

    #[test]
    fn test_x_vector_only_validates() {
        let embedding = create_test_embedding();
        let prompt = VoiceClonePromptItem::x_vector_only(embedding);

        let result = prompt.validate();
        assert!(
            result.is_ok(),
            "x_vector_only prompt should validate successfully"
        );
    }

    #[test]
    fn test_is_x_vector_only_predicate() {
        let embedding = create_test_embedding();
        let prompt = VoiceClonePromptItem::x_vector_only(embedding);

        assert!(
            prompt.is_x_vector_only(),
            "is_x_vector_only() should return true"
        );
        assert!(
            !prompt.is_icl(),
            "is_icl() should return false for x_vector_only"
        );
    }

    // =========================================================================
    // ICL Mode Tests
    // =========================================================================

    #[test]
    fn test_icl_creation() {
        let codes = create_test_codes();
        let embedding = create_test_embedding();
        let ref_text = "Hello, this is a test.".to_string();

        let prompt = VoiceClonePromptItem::icl(codes, embedding, ref_text.clone());

        assert!(prompt.ref_code.is_some(), "icl should have ref_code");
        assert!(
            !prompt.x_vector_only_mode,
            "x_vector_only_mode should be false for icl"
        );
        assert!(prompt.icl_mode, "icl_mode should be true");
        assert_eq!(prompt.ref_text, Some(ref_text), "ref_text should match");
    }

    #[test]
    fn test_icl_validates_with_all_fields() {
        let codes = create_test_codes();
        let embedding = create_test_embedding();
        let ref_text = "Hello, this is a test.".to_string();

        let prompt = VoiceClonePromptItem::icl(codes, embedding, ref_text);

        let result = prompt.validate();
        assert!(
            result.is_ok(),
            "icl prompt with all fields should validate successfully"
        );
    }

    #[test]
    fn test_is_icl_predicate() {
        let codes = create_test_codes();
        let embedding = create_test_embedding();
        let ref_text = "Hello, this is a test.".to_string();

        let prompt = VoiceClonePromptItem::icl(codes, embedding, ref_text);

        assert!(
            prompt.is_icl(),
            "is_icl() should return true for icl prompt"
        );
        assert!(
            !prompt.is_x_vector_only(),
            "is_x_vector_only() should return false for icl"
        );
    }

    // =========================================================================
    // ICL Validation Failure Tests
    // =========================================================================

    #[test]
    fn test_icl_missing_ref_code_fails_validation() {
        let embedding = create_test_embedding();

        // Create an ICL prompt manually without ref_code
        let prompt = VoiceClonePromptItem {
            ref_code: None,
            ref_spk_embedding: embedding,
            x_vector_only_mode: false,
            icl_mode: true,
            ref_text: Some("Some text".to_string()),
        };

        let result = prompt.validate();
        assert!(
            result.is_err(),
            "ICL prompt without ref_code should fail validation"
        );
        let err_msg = result.unwrap_err();
        assert!(
            err_msg.contains("ref_code"),
            "Error should mention ref_code: {}",
            err_msg
        );
    }

    #[test]
    fn test_icl_missing_ref_text_fails_validation() {
        let codes = create_test_codes();
        let embedding = create_test_embedding();

        // Create an ICL prompt manually without ref_text
        let prompt = VoiceClonePromptItem {
            ref_code: Some(codes),
            ref_spk_embedding: embedding,
            x_vector_only_mode: false,
            icl_mode: true,
            ref_text: None,
        };

        let result = prompt.validate();
        assert!(
            result.is_err(),
            "ICL prompt without ref_text should fail validation"
        );
        let err_msg = result.unwrap_err();
        assert!(
            err_msg.contains("ref_text"),
            "Error should mention ref_text: {}",
            err_msg
        );
    }

    // =========================================================================
    // Constructor new() Tests
    // =========================================================================

    #[test]
    fn test_new_constructor_x_vector_mode() {
        let embedding = create_test_embedding();

        let prompt = VoiceClonePromptItem::new(
            None, embedding, true, // x_vector_only_mode
            None,
        );

        assert!(prompt.x_vector_only_mode);
        assert!(
            !prompt.icl_mode,
            "icl_mode should be opposite of x_vector_only_mode"
        );
    }

    #[test]
    fn test_new_constructor_icl_mode() {
        let codes = create_test_codes();
        let embedding = create_test_embedding();
        let ref_text = "Test text".to_string();

        let prompt = VoiceClonePromptItem::new(
            Some(codes),
            embedding,
            false, // x_vector_only_mode
            Some(ref_text),
        );

        assert!(!prompt.x_vector_only_mode);
        assert!(
            prompt.icl_mode,
            "icl_mode should be opposite of x_vector_only_mode"
        );
    }

    // =========================================================================
    // VoiceCloneConfig Tests
    // =========================================================================

    #[test]
    fn test_voice_clone_config_default() {
        let config = VoiceCloneConfig::default();

        assert_eq!(config.max_new_tokens, 2048);
        assert!(config.min_duration.is_none());
        assert_eq!(config.max_duration, Some(30.0));
    }
}