orig-inference.ipynb 12.6 KB
Newer Older
Nikhilesh Bhatnagar's avatar
Nikhilesh Bhatnagar committed
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n",
      "Loading G2P model... Done!\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import json\n",
    "import yaml\n",
    "import numpy\n",
    "import torch\n",
    "!mkdir -p ../wavs\n",
    "import onnxruntime\n",
    "from sys import path\n",
    "from tqdm import tqdm\n",
    "SAMPLING_RATE = 22050\n",
    "os.chdir('../Fastspeech2_HS')\n",
    "path.append(\"hifigan\")\n",
    "from env import AttrDict\n",
    "from models import Generator\n",
    "from IPython.display import Audio\n",
    "from scipy.io.wavfile import write\n",
    "from meldataset import MAX_WAV_VALUE\n",
    "from espnet_onnx.export import TTSModelExport\n",
    "from espnet2.bin.tts_inference import Text2Speech\n",
    "from espnet_onnx import Text2Speech as Text2SpeechInference\n",
    "from text_preprocess_for_inference import TTSDurAlignPreprocessor, CharTextPreprocessor, TTSPreprocessor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Original Inference\n",
    "* uses the environment defined in Fastspeech2_HS repo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_hifigan_vocoder(language, gender, family, device):\n",
    "    vocoder_config = f\"vocoder/{gender}/{family}/hifigan/config.json\"\n",
    "    vocoder_generator = f\"vocoder/{gender}/{family}/hifigan/generator\"\n",
    "    with open(vocoder_config, 'r') as f: json_config = json.load(f)\n",
    "    h = AttrDict(json_config)\n",
    "    torch.manual_seed(h.seed)\n",
    "    device = torch.device(device)\n",
    "    generator = Generator(h).to(device)\n",
    "    state_dict_g = torch.load(vocoder_generator, device)\n",
    "    generator.load_state_dict(state_dict_g['generator'])\n",
    "    generator.eval()\n",
    "    generator.remove_weight_norm()\n",
    "    return generator\n",
    "def load_fastspeech2_model(language, gender, device):\n",
    "    with open(f\"{language}/{gender}/model/config.yaml\", \"r\") as file: config = yaml.safe_load(file)\n",
    "    current_working_directory = os.getcwd()\n",
    "    feat = \"model/feats_stats.npz\"\n",
    "    pitch = \"model/pitch_stats.npz\"\n",
    "    energy = \"model/energy_stats.npz\"\n",
    "    feat_path = os.path.join(current_working_directory, language, gender, feat)\n",
    "    pitch_path = os.path.join(current_working_directory, language, gender, pitch)\n",
    "    energy_path = os.path.join(current_working_directory, language, gender, energy)\n",
    "    config[\"normalize_conf\"][\"stats_file\"] = feat_path\n",
    "    config[\"pitch_normalize_conf\"][\"stats_file\"] = pitch_path\n",
    "    config[\"energy_normalize_conf\"][\"stats_file\"] = energy_path\n",
    "    with open(f\"{language}/{gender}/model/config.yaml\", \"w\") as file: yaml.dump(config, file)\n",
    "    tts_model = f\"{language}/{gender}/model/model.pth\"\n",
    "    tts_config = f\"{language}/{gender}/model/config.yaml\"\n",
    "    return Text2Speech(train_config=tts_config, model_file=tts_model, device=device)\n",
    "def text_synthesis(language, gender, sample_text, vocoder, MAX_WAV_VALUE, device):\n",
    "    with torch.no_grad():\n",
    "        model = load_fastspeech2_model(language, gender, device)\n",
    "        out = model(sample_text, decode_conf={\"alpha\": 1})\n",
    "        x = out[\"feat_gen_denorm\"].T.unsqueeze(0) * 2.3262\n",
    "        x = x.to(device)\n",
    "        y_g_hat = vocoder(x)\n",
    "        audio = y_g_hat.squeeze()\n",
    "        audio = audio * MAX_WAV_VALUE\n",
    "        audio = audio.cpu().numpy().astype('int16')\n",
    "        return audio\n",
    "def text2speech(language, gender, family, sample_text, device):\n",
    "    vocoder = load_hifigan_vocoder(language, gender, family, device)\n",
    "    if language == \"urdu\" or language == \"punjabi\": preprocessor = CharTextPreprocessor()\n",
    "    elif language == \"english\": preprocessor = TTSPreprocessor()\n",
    "    else: preprocessor = TTSDurAlignPreprocessor()\n",
    "    preprocessed_text, phrases = preprocessor.preprocess(sample_text, language, gender)\n",
    "    preprocessed_text = \" \".join(preprocessed_text)\n",
    "    audio = text_synthesis(language, gender, preprocessed_text, vocoder, MAX_WAV_VALUE, device)\n",
    "    output_file = f\"../wavs/{language}_{gender}-{family}_orig_output.wav\"\n",
    "    write(output_file, SAMPLING_RATE, audio)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Original Inference Results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Removing weight norm...\n",
      "length: 26624 array: [945 894 605 ...  10  12  30]\n",
      "abssum: 42271788 min: -16131 max: 10878\n"
     ]
    }
   ],
   "source": [
    "audio_orig = text_synthesis('english', 'male', 'this is a sentence', load_hifigan_vocoder('english', 'male', 'aryan', 'cpu'), MAX_WAV_VALUE, 'cpu')\n",
    "print('length:', len(audio_orig), 'array:', audio_orig)\n",
    "print('abssum:', numpy.abs(audio_orig).sum(), 'min:', audio_orig.min(), 'max:', audio_orig.max())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Removing weight norm...\n",
      "length: 26624 array: [945 894 605 ...  10  12  30]\n",
      "abssum: 42271796 min: -16131 max: 10878\n"
     ]
    }
   ],
   "source": [
    "audio_orig = text_synthesis('english', 'male', 'this is a sentence', load_hifigan_vocoder('english', 'male', 'aryan', 'cuda'), MAX_WAV_VALUE, 'cuda')\n",
    "print('length:', len(audio_orig), 'array:', audio_orig)\n",
    "print('abssum:', numpy.abs(audio_orig).sum(), 'min:', audio_orig.min(), 'max:', audio_orig.max())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Latest Pytorch Inference Results\n",
    "* similar environment as defined in scripts/perform_onnx_conversion"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/nikhilesh/miniforge3/envs/iitm-tts-latest-pytorch/lib/python3.10/site-packages/torch/nn/utils/weight_norm.py:30: UserWarning: torch.nn.utils.weight_norm is deprecated in favor of torch.nn.utils.parametrizations.weight_norm.\n",
      "  warnings.warn(\"torch.nn.utils.weight_norm is deprecated in favor of torch.nn.utils.parametrizations.weight_norm.\")\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Removing weight norm...\n",
      "length: 26624 array: [945 894 605 ...  10  12  30]\n",
      "abssum: 42271783 min: -16131 max: 10878\n"
     ]
    }
   ],
   "source": [
    "audio_orig = text_synthesis('english', 'male', 'this is a sentence', load_hifigan_vocoder('english', 'male', 'aryan', 'cpu'), MAX_WAV_VALUE, 'cpu')\n",
    "print('length:', len(audio_orig), 'array:', audio_orig)\n",
    "print('abssum:', numpy.abs(audio_orig).sum(), 'min:', audio_orig.min(), 'max:', audio_orig.max())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "audio_orig = text_synthesis('english', 'male', 'this is a sentence', load_hifigan_vocoder('english', 'male', 'aryan', 'cuda'), MAX_WAV_VALUE, 'cuda')\n",
    "print('length:', len(audio_orig), 'array:', audio_orig)\n",
    "print('abssum:', numpy.abs(audio_orig).sum(), 'min:', audio_orig.min(), 'max:', audio_orig.max())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "ORT Conversion"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "!mkdir -p ../ort_models\n",
    "def convert_to_ort(language, gender, family):\n",
    "    vocoder = load_hifigan_vocoder(language, gender, family, 'cpu')\n",
    "    model = load_fastspeech2_model(language, gender, 'cpu')\n",
    "    if language == \"urdu\" or language == \"punjabi\": preprocessor = CharTextPreprocessor()\n",
    "    elif language == \"english\": preprocessor = TTSPreprocessor()\n",
    "    else: preprocessor = TTSDurAlignPreprocessor()\n",
    "    preprocessed_text, phrases = preprocessor.preprocess('this is a sentence', language, gender)\n",
    "    preprocessed_text = \" \".join(preprocessed_text)\n",
    "    exporter = TTSModelExport()\n",
    "    exporter.export(model, f'{language}-{gender}-ort', quantize=False)\n",
    "    out = model(preprocessed_text, decode_conf={\"alpha\": 1})\n",
    "    x = out[\"feat_gen_denorm\"].T.unsqueeze(0) * 2.3262\n",
    "    torch.onnx.export(vocoder, x, f'../ort_models/vocoders/{gender}-{family}-vocoder.onnx', input_names=['input'], output_names=['output'], dynamic_axes={'input': [0, 2], 'output': [0]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "convert_to_ort('english', 'male', 'aryan')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "ORT Inference\n",
    "* environment as defined in triton_models/tts/envbuilder.sh\n",
    "* you can delete the ort_models folder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_hifigan_vocoder(language, gender, family, device): return onnxruntime.InferenceSession(f\"../ort_models/vocoders/{gender}-{family}-vocoder.onnx\", providers=['CPUExecutionProvider' if device == 'cpu' else 'CUDAExecutionProvider'])\n",
    "def load_fastspeech2_model(language, gender, device): return Text2SpeechInference(f'{language}-{gender}-ort', providers=['CPUExecutionProvider' if device == 'cpu' else 'CUDAExecutionProvider'])\n",
    "def text_synthesis(language, gender, sample_text, vocoder, MAX_WAV_VALUE, device):\n",
    "    model = load_fastspeech2_model(language, gender, device)\n",
    "    x = numpy.expand_dims(model.postprocess(model.tts_model(model.preprocess.token_id_converter.tokens2ids(model.preprocess.tokenizer.text2tokens(sample_text)))['feat_gen']).T, axis=0) * 2.3262\n",
    "    y_g_hat = vocoder.run(None, {'input': x})[0]\n",
    "    audio = y_g_hat.squeeze()\n",
    "    audio = audio * MAX_WAV_VALUE\n",
    "    audio = audio.astype('int16')\n",
    "    return audio\n",
    "def text2speech(language, gender, family, sample_text, device):\n",
    "    vocoder = load_hifigan_vocoder(language, gender, family, device)\n",
    "    if language == \"urdu\" or language == \"punjabi\": preprocessor = CharTextPreprocessor()\n",
    "    elif language == \"english\": preprocessor = TTSPreprocessor()\n",
    "    else: preprocessor = TTSDurAlignPreprocessor()\n",
    "    preprocessed_text, phrases = preprocessor.preprocess(sample_text, language, gender)\n",
    "    preprocessed_text = \" \".join(preprocessed_text)\n",
    "    audio = text_synthesis(language, gender, preprocessed_text, vocoder, MAX_WAV_VALUE, device)\n",
    "    output_file = f\"../wavs/{language}_{gender}-{family}_ort_output.wav\"\n",
    "    write(output_file, SAMPLING_RATE, audio)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "ORT Inference Results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "audio_orig = text_synthesis('english', 'male', 'this', load_hifigan_vocoder('english', 'male', 'aryan', 'cpu'), MAX_WAV_VALUE, 'cpu')\n",
    "print('length:', len(audio_orig), 'array:', audio_orig)\n",
    "print('abssum:', numpy.abs(audio_orig).sum(), 'min:', audio_orig.min(), 'max:', audio_orig.max())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "iitm-tts",
   "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.11.6"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}