File size: 14,549 Bytes
7934b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# FastPitch Speaker Interpolation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this tutorial we will explore the following:\n",
    "- What is speaker interpolation in a multi-speaker Text-to-Speech model\n",
    "- Why we need speaker interpolation\n",
    "- Step-by-step demo of performing speaker interpolation using pretrained multi-speaker FastPitch model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## License\n",
    "\n",
    "> Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES.  All rights reserved.\n",
    ">\n",
    "> Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "> you may not use this file except in compliance with the License.\n",
    "> You may obtain a copy of the License at\n",
    ">\n",
    ">     http://www.apache.org/licenses/LICENSE-2.0\n",
    ">\n",
    "> Unless required by applicable law or agreed to in writing, software\n",
    "> distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "> See the License for the specific language governing permissions and\n",
    "> limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### What is Speaker Interpolation in a Multi-speaker Text-to-speech Model\n",
    "\n",
    "Given a Multi-speaker Text-to-Speech (TTS) model that can generate speech in more than one speaker's voice, Speaker Interpolation is the process of synthesizing new synthetic **voices by combining two or more existing speaker voices** without the need for any further finetuning. Before we go in depths of the process let's understand why we need speaker interpolation?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Why we need speaker interpolation\n",
    "\n",
    "To release any TTS model, trained on datasets where the speakers do not want speech to be generated in their voice, speaker interpolation is important. This technique can be used to replace the original speaker's in the pretrained model with the interpolated synthetic speakers. This work would solve this problem.\n",
    "\n",
    "\n",
    "This technique can be used to generate large multi-speaker dataset for training Automatic Speech Recognition (ASR) models or voice conversion models. It enables users to create an infinite number of speaker voices. \n",
    "\n",
    "We can also use speaker interpolation for achieving varying multi-dialect or multi-emotional voices in text-to-speech (TTS) synthesis. They may\n",
    "be used for personalizing speech and generating speech with specific voice characteristics in speech synthesis systems.\n",
    "\n",
    "In case of self-supervised learning (SSL), speaker interpolation can be used for negative sampling. In addition to the above use cases, speaker interpolation can be used for data augmentation as well."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step-by-step demo of Speaker Interpolation using Pretrained multi-speaker FastPitch model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Method\n",
    "\n",
    "1. Train a multi-speaker spectrogram generator model (like FastPitch) using embedding lookup table. This means that during training an embedding (speaker embedding) will be learnt for each speaker.\n",
    "\n",
    "2. Extract speaker embeddings for any two speakers, you want to combine, from the model trained in step 1.\n",
    "\n",
    "3. Perform a weighted sum of the two speaker embeddings extracted in step 2. This will give the speaker embedding for the interpolated speaker.\n",
    "\n",
    "4. Use the speaker embedding obtained from step 3, to condition the multi-speaker model in step 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install NeMo library. If you are running locally (rather than on Google Colab), comment out the below lines\n",
    "# and instead follow the instructions at https://github.com/NVIDIA/NeMo#Installation\n",
    "BRANCH = 'r1.17.0'\n",
    "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If seaborn is not installed already run this cell\n",
    "!pip install seaborn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "You can either run this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
    "Instructions for setting up Colab are as follows:\n",
    "1. Open a new Python 3 notebook.\n",
    "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
    "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
    "4. Run this cell to set up dependencies# .\n",
    "\"\"\"\n",
    "\n",
    "import json\n",
    "\n",
    "import torch\n",
    "import numpy as np\n",
    "import IPython.display as ipd\n",
    "from matplotlib.pyplot import imshow\n",
    "from matplotlib import pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "from nemo.collections.tts.models import FastPitchModel, HifiGanModel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Load Pretrained multi-speaker FastPitch model**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's view the available model checkpoints for FastPitch \n",
    "FastPitchModel.list_available_models()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We will choose the English multi-speaker model: tts_en_fastpitch_multispeaker\n",
    "spec_gen_model = FastPitchModel.from_pretrained(\"tts_en_fastpitch_multispeaker\")\n",
    "spec_gen_model.cuda()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Visualization**\n",
    "\n",
    "To understand the process better, let's try to visualize how the embeddings get combined to create a new speaker embedding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Original Speaker IDs\n",
    "speaker_1 = 2\n",
    "speaker_2 = 10\n",
    "\n",
    "# Extracting speaker embeddings for speaker_1 and speaker_2\n",
    "speaker_emb_1 = spec_gen_model.fastpitch.speaker_emb(torch.tensor(speaker_1, dtype=torch.int32).cuda()).clone().detach()\n",
    "speaker_emb_2 = spec_gen_model.fastpitch.speaker_emb(torch.tensor(speaker_2, dtype=torch.int32).cuda()).clone().detach()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will now visualize the two speaker embeddings. The embedding dimensions are 384, so to keep the visualization clear we will only visualize the first 30 elements of each embedding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "plt.rcParams['figure.figsize'] = [20, 1]\n",
    "tmp_emb = np.vstack([speaker_emb_1.cpu()[:30], speaker_emb_2.cpu()[:30]])\n",
    "sns.heatmap(data=tmp_emb, cmap=\"coolwarm\", xticklabels=False, yticklabels=[\"speaker1\", \"speaker2\"])\n",
    "plt.title(\"Visualizing Speaker Embeddings\", fontsize =20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's combine the two speaker embeddings and generate the synthetic speaker embedding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Weights assigned to each speaker, in the process of generating the new speaker\n",
    "# You can play around with these weights\n",
    "weight_speaker_1 = 0.5\n",
    "weight_speaker_2 = 0.5\n",
    "\n",
    "interpolated_speaker_emb = weight_speaker_1 * speaker_emb_1 + weight_speaker_2 * speaker_emb_2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will now visualize the interpolated speaker along with the two speaker original embeddings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "plt.rcParams['figure.figsize'] = [20, 2]\n",
    "tmp_emb = np.vstack([speaker_emb_1.cpu()[:30], speaker_emb_2.cpu()[:30], interpolated_speaker_emb.cpu()[:30]])\n",
    "sns.heatmap(data=tmp_emb, cmap=\"coolwarm\", xticklabels=False, yticklabels=[\"speaker1\", \"speaker2\", \"interpolated_speaker\"])\n",
    "plt.title(\"Visualizing Original and Interpolated Speaker Embeddings\", fontsize =20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Extraction and Combining of speaker embeddings**\n",
    "\n",
    "This entire process of doing speaker interpolation is performed by the method `interpolate_speaker` in the FastPitch class."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Generate Speech using speaker interpolation**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we will use this process of speaker interpolation to generate speech using original speaker voices and interpolated speaker voice. For this we will need a vocoder to convert generated spectrogram to waveform speech. So let's load HiFiGAN vocoder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vocoder = HifiGanModel.from_pretrained(\"tts_en_hifitts_hifigan_ft_fastpitch\")\n",
    "vocoder.cuda().eval()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we will define a function which will take as input the spectrogram generator model, vocoder model, text to be converted to speech and speaker id. This function will return spectrogram and audio of the generated speech."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def infer(spec_gen_model, vocoder_model, str_input, speaker=None):\n",
    "    \"\"\"\n",
    "    Synthesizes spectrogram and audio from a text string given a spectrogram synthesis and vocoder model.\n",
    "    \n",
    "    Args:\n",
    "        spec_gen_model: Spectrogram generator model (FastPitch in our case)\n",
    "        vocoder_model: Vocoder model (HiFiGAN in our case)\n",
    "        str_input: Text input for the synthesis\n",
    "        speaker: Speaker ID\n",
    "    \n",
    "    Returns:\n",
    "        spectrogram and waveform of the synthesized audio.\n",
    "    \"\"\"\n",
    "    spec_gen_model.eval()\n",
    "    with torch.no_grad():\n",
    "        parsed = spec_gen_model.parse(str_input)\n",
    "        if speaker is not None:\n",
    "            speaker = torch.tensor([speaker]).long().to(device=spec_gen_model.device)\n",
    "        spectrogram = spec_gen_model.generate_spectrogram(tokens=parsed, speaker=speaker)\n",
    "        audio = vocoder_model.convert_spectrogram_to_audio(spec=spectrogram)\n",
    "        \n",
    "    if spectrogram is not None:\n",
    "        if isinstance(spectrogram, torch.Tensor):\n",
    "            spectrogram = spectrogram.to('cpu').numpy()\n",
    "        if len(spectrogram.shape) == 3:\n",
    "            spectrogram = spectrogram[0]\n",
    "    else:\n",
    "        raise Exception(\"None value was generated for spectrogram\")\n",
    "    if isinstance(audio, torch.Tensor):\n",
    "        audio = audio.to('cpu').numpy()\n",
    "    return spectrogram, audio"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's generate some speech."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Choose any original speakers (speaker1 and speaker2)\n",
    "# Choose new_speaker ID such that it is not already assigned to an existing speaker\n",
    "speaker1, speaker2, new_speaker = 6097, 92, 1000\n",
    "\n",
    "# Choose weight1 corresponding to speaker1 and weight2 corresponding to speaker2\n",
    "# You can change this and play around with the weights\n",
    "weight1, weight2 = 0.4, 0.6\n",
    "\n",
    "# Perform Speaker Interpolation\n",
    "spec_gen_model.interpolate_speaker(speaker1, speaker2, weight1, weight2, new_speaker)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# This is the text you want to convert to speech\n",
    "text = \"Hello World, Speaker Interpolation is cool\"\n",
    "\n",
    "_, audio = infer(spec_gen_model, vocoder, text, speaker=speaker1)\n",
    "print(f\"audio generated for speaker {speaker1}\")\n",
    "ipd.display(ipd.Audio(audio, rate=44100))\n",
    "\n",
    "_, audio = infer(spec_gen_model, vocoder, text, speaker=speaker2)\n",
    "print(f\"audio generated for speaker {speaker2}\")\n",
    "ipd.display(ipd.Audio(audio, rate=44100))\n",
    "\n",
    "_, audio = infer(spec_gen_model, vocoder, text, speaker=new_speaker)\n",
    "print(f\"audio generated for Interpolated Speaker\")\n",
    "ipd.display(ipd.Audio(audio, rate=44100))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It was observed that for speaker interpolation to work well and stable, the pretrained multi-speaker FastPitch model needs to be robust. So, training multi-speaker FastPitch model on larger data with larger number of speakers help in getting better interpolated speakers."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}