{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# FastSpeech 2 on Colab + Hugging Face\n", "\n", "Set `HF_REPO_ID` below to the model repo containing this code, the 200,000-step checkpoint, and HiFi-GAN weights. Choose `DATA_SOURCE = 'drive_preprocessed'` to reuse preprocessed features on Drive, or `DATA_SOURCE = 'download_and_preprocess'` to fetch raw LJSpeech plus the upstream MFA alignments and build features in Colab. Select a GPU runtime first. The full fetch/preprocess path needs several GB of temporary disk and can take a while.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "HF_REPO_ID = 'lushy/fastspeech2-ljspeech' # change this to your own repo to publish elsewhere\n", "START_STEP = 200000\n", "TOTAL_STEP = 900000\n", "SAVE_EVERY = 10000\n", "DATA_SOURCE = 'drive_preprocessed' # or 'download_and_preprocess'\n", "DRIVE_DATA = '/content/drive/MyDrive/FastSpeech2/preprocessed_data/LJSpeech'\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install -q 'huggingface_hub>=0.30.0'\n", "from google.colab import drive\n", "drive.mount('/content/drive')\n", "from huggingface_hub import snapshot_download, hf_hub_download, notebook_login\n", "from pathlib import Path\n", "import shutil, os\n", "notebook_login() # needed for private repos and for the upload cell\n", "WORK_DIR = Path('/content/FastSpeech2')\n", "DRIVE_RUN = Path('/content/drive/MyDrive/FastSpeech2')\n", "if WORK_DIR.exists(): shutil.rmtree(WORK_DIR)\n", "WORK_DIR.mkdir(parents=True)\n", "snapshot_download(repo_id=HF_REPO_ID, repo_type='model', local_dir=WORK_DIR, ignore_patterns=['checkpoints/**','output/**','preprocessed_data/**','raw_data/**','**/*.pth','**/*.pth.tar','**/*.bin'])\n", "hf_hub_download(repo_id=HF_REPO_ID, repo_type='model', filename='hifigan/generator_LJSpeech.bin', local_dir=WORK_DIR)\n", "shutil.copy2(WORK_DIR/'hifigan/generator_LJSpeech.bin', WORK_DIR/'hifigan/generator_LJSpeech.pth.tar')\n", "if START_STEP:\n", " checkpoint = hf_hub_download(repo_id=HF_REPO_ID, repo_type='model', filename=f'checkpoints/{START_STEP}.bin', local_dir=WORK_DIR)\n", " ckpt_dir = WORK_DIR/'output/ckpt/LJSpeech'; ckpt_dir.mkdir(parents=True, exist_ok=True)\n", " shutil.copy2(checkpoint, ckpt_dir/f'{START_STEP}.pth.tar')\n", "os.chdir(WORK_DIR)\n", "print('Project:', WORK_DIR)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install -r requirements-colab.txt\n", "import sys, torch\n", "assert sys.version_info[:2] in {(3,12),(3,13)}, f'Expected CPython 3.12/3.13, got {sys.version}'\n", "assert torch.cuda.is_available(), 'Enable a GPU runtime before training'\n", "print(sys.version, torch.__version__, torch.cuda.get_device_name(0))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fetch or prepare the dataset\n", "\n", "Use the Drive option when you already have the features. The download option fetches the official LJSpeech archive and the MFA TextGrids referenced by the original FastSpeech 2 instructions, then runs this repo's preparation scripts.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import shutil, subprocess, tarfile, zipfile, yaml, requests\n", "from tqdm.auto import tqdm\n", "\n", "if DATA_SOURCE == 'drive_preprocessed':\n", " data_src = Path(DRIVE_DATA)\n", " assert (data_src/'train.txt').is_file(), f'Missing preprocessed dataset: {data_src}'\n", " shutil.copytree(data_src, WORK_DIR/'preprocessed_data/LJSpeech')\n", "elif DATA_SOURCE == 'download_and_preprocess':\n", " raw_root = Path('/content/ljspeech-source')\n", " corpus = raw_root/'LJSpeech-1.1'\n", " archive = raw_root/'LJSpeech-1.1.tar.bz2'\n", " raw_root.mkdir(parents=True, exist_ok=True)\n", " if not (corpus/'metadata.csv').is_file():\n", " if not archive.is_file():\n", " url = 'https://data.keithito.com/data/speech/LJSpeech-1.1.tar.bz2'\n", " with requests.get(url, stream=True, timeout=120) as response:\n", " response.raise_for_status()\n", " total = int(response.headers.get('content-length', 0))\n", " with archive.open('wb') as output, tqdm(total=total, unit='B', unit_scale=True, desc='LJSpeech') as bar:\n", " for chunk in response.iter_content(chunk_size=1024*1024):\n", " if chunk:\n", " output.write(chunk)\n", " bar.update(len(chunk))\n", " with tarfile.open(archive, 'r:bz2') as bundle:\n", " bundle.extractall(raw_root, filter='data')\n", " archive.unlink(missing_ok=True)\n", "\n", " align_root = Path('/content/fastspeech2-alignments')\n", " align_root.mkdir(parents=True, exist_ok=True)\n", " import gdown\n", " gdown.download_folder(\n", " url='https://drive.google.com/drive/folders/1DBRkALpPd6FL9gjHMmMEdHODmkgNIIK4',\n", " output=str(align_root), quiet=False, use_cookies=False,\n", " )\n", " for archive_file in align_root.rglob('*.zip'):\n", " with zipfile.ZipFile(archive_file) as bundle:\n", " root = align_root.resolve()\n", " for member in bundle.infolist():\n", " destination = (align_root/member.filename).resolve()\n", " if destination != root and root not in destination.parents:\n", " raise ValueError(f'Unsafe path in alignment archive: {member.filename}')\n", " bundle.extractall(align_root)\n", " textgrids = [p for p in align_root.rglob('*') if p.is_file() and p.name.startswith('LJ') and p.suffix.lower()=='.textgrid']\n", " if len(textgrids) < 10000:\n", " raise RuntimeError(f'Expected the LJSpeech MFA alignments, found only {len(textgrids)} TextGrid files. Check the shared alignment folder.')\n", "\n", " config_path = WORK_DIR/'config/LJSpeech/preprocess_colab.yaml'\n", " config = yaml.safe_load((WORK_DIR/'config/LJSpeech/preprocess.yaml').read_text())\n", " config['path']['corpus_path'] = str(corpus)\n", " config['path']['raw_path'] = str(raw_root/'aligned')\n", " config['path']['preprocessed_path'] = str(WORK_DIR/'preprocessed_data/LJSpeech')\n", " config_path.write_text(yaml.safe_dump(config, sort_keys=False))\n", " subprocess.run(['python','prepare_align.py',str(config_path)], cwd=WORK_DIR, check=True)\n", " textgrid_dir = WORK_DIR/'preprocessed_data/LJSpeech/TextGrid/LJSpeech'\n", " textgrid_dir.mkdir(parents=True, exist_ok=True)\n", " for path in textgrids:\n", " shutil.copy2(path, textgrid_dir/path.name)\n", " subprocess.run(['python','preprocess.py',str(config_path)], cwd=WORK_DIR, check=True)\n", "else:\n", " raise ValueError(\"DATA_SOURCE must be 'drive_preprocessed' or 'download_and_preprocess'\")\n", "print('Prepared data:', WORK_DIR/'preprocessed_data/LJSpeech')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import yaml\n", "cfg = WORK_DIR/'config/LJSpeech'\n", "preprocess = yaml.safe_load((cfg/'preprocess.yaml').read_text())\n", "train = yaml.safe_load((cfg/'train.yaml').read_text())\n", "preprocess['path']['preprocessed_path'] = str(WORK_DIR/'preprocessed_data/LJSpeech')\n", "train['path']['ckpt_path'] = str(DRIVE_RUN/'output/ckpt/LJSpeech')\n", "train['path']['log_path'] = str(DRIVE_RUN/'output/log/LJSpeech')\n", "train['path']['result_path'] = str(DRIVE_RUN/'output/result/LJSpeech')\n", "train['step']['total_step'] = TOTAL_STEP\n", "train['step']['save_step'] = SAVE_EVERY\n", "train['step']['keep_checkpoint_count'] = 2\n", "(cfg/'preprocess_colab.yaml').write_text(yaml.safe_dump(preprocess, sort_keys=False))\n", "(cfg/'train_colab.yaml').write_text(yaml.safe_dump(train, sort_keys=False))\n", "print(f'Resuming from {START_STEP}; checkpoints saved every {SAVE_EVERY} steps to Drive.')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Train\n", "\n", "The run writes checkpoints and TensorBoard logs to Drive. Keep the runtime connected while this cell runs." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python train.py --restore_step $START_STEP -p config/LJSpeech/preprocess_colab.yaml -m config/LJSpeech/model.yaml -t config/LJSpeech/train_colab.yaml" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Publish the newest checkpoint\n", "\n", "This uploads code, the vocoder, and the newest checkpoint to the same Hugging Face model repo. Authenticate when prompted; the token stays in the Colab secret/login flow." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "checkpoints = sorted((DRIVE_RUN/'output/ckpt/LJSpeech').glob('*.pth.tar'), key=lambda p: int(p.name.split('.')[0]))\n", "assert checkpoints, 'No checkpoints found on Drive'\n", "import subprocess\n", "subprocess.run(['python', 'scripts/push_to_hub.py', HF_REPO_ID, '--checkpoint', str(checkpoints[-1])], cwd=WORK_DIR, check=True)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%load_ext tensorboard\n", "%tensorboard --logdir /content/drive/MyDrive/FastSpeech2/output/log/LJSpeech" ] } ], "metadata": { "colab": { "gpuType": "T4", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }