mirror of
https://github.com/RVC-Boss/GPT-SoVITS.git
synced 2026-11-24 15:13:36 +08:00
refactor: reduce repository to inference service and organize project
This commit is contained in:
parent
b4570b876f
commit
8fbc8c2ed8
208
.dockerignore
208
.dockerignore
@ -1,198 +1,16 @@
|
||||
GPT_SoVITS/pretrained_models/*
|
||||
tools/asr/models/*
|
||||
tools/uvr5/uvr5_weights/*
|
||||
|
||||
# Build context excludes model caches and local runtime bundles.
|
||||
.git
|
||||
.DS_Store
|
||||
.vscode
|
||||
*.pyc
|
||||
env
|
||||
.codex
|
||||
runtime
|
||||
.idea
|
||||
output
|
||||
logs
|
||||
SoVITS_weights*/
|
||||
GPT_weights*/
|
||||
TEMP
|
||||
weight.json
|
||||
ffmpeg*
|
||||
ffprobe*
|
||||
cfg.json
|
||||
speakers.json
|
||||
ref_audios
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
**/__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
.idea/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
models
|
||||
GPT_SoVITS/pretrained_models/*
|
||||
GPT_SoVITS/text/G2PWModel/*
|
||||
__pycache__
|
||||
*.pyc
|
||||
tools/AP_BWE_main/24kto48k/*.zip
|
||||
references
|
||||
.env
|
||||
.env.*
|
||||
GPT_SoVITS/configs/tts_local*.yaml
|
||||
output.wav
|
||||
|
||||
194
.github/build_windows_packages.ps1
vendored
194
.github/build_windows_packages.ps1
vendored
@ -1,194 +0,0 @@
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
Write-Host "Current location: $(Get-Location)"
|
||||
|
||||
$cuda = $env:TORCH_CUDA
|
||||
if (-not $cuda) {
|
||||
Write-Error "Missing TORCH_CUDA env (cu124 or cu128)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$date = $env:DATE_SUFFIX
|
||||
if ([string]::IsNullOrWhiteSpace($date)) {
|
||||
$date = Get-Date -Format "MMdd"
|
||||
}
|
||||
|
||||
$pkgName = "GPT-SoVITS-$date"
|
||||
$tmpDir = "tmp"
|
||||
$srcDir = $PWD
|
||||
|
||||
$suffix = $env:PKG_SUFFIX
|
||||
if (-not [string]::IsNullOrWhiteSpace($suffix)) {
|
||||
$pkgName = "$pkgName$suffix"
|
||||
}
|
||||
|
||||
$pkgName = "$pkgName-$cuda"
|
||||
|
||||
$baseHF = "https://huggingface.co/XXXXRT/GPT-SoVITS-Pretrained/resolve/main"
|
||||
$PRETRAINED_URL = "$baseHF/pretrained_models.zip"
|
||||
$G2PW_URL = "$baseHF/G2PWModel.zip"
|
||||
$UVR5_URL = "$baseHF/uvr5_weights.zip"
|
||||
$NLTK_URL = "$baseHF/nltk_data.zip"
|
||||
$JTALK_URL = "$baseHF/open_jtalk_dic_utf_8-1.11.tar.gz"
|
||||
|
||||
$PYTHON_VERSION = "3.11.12"
|
||||
$PY_RELEASE_VERSION = "20250409"
|
||||
|
||||
Write-Host "[INFO] Cleaning .git..."
|
||||
Remove-Item "$srcDir\.git" -Recurse -Force -ErrorAction SilentlyContinue
|
||||
|
||||
Write-Host "[INFO] Creating tmp dir..."
|
||||
New-Item -ItemType Directory -Force -Path $tmpDir
|
||||
|
||||
Write-Host "[INFO] System Python version:"
|
||||
python --version
|
||||
python -m site
|
||||
|
||||
Write-Host "[INFO] Downloading Python $PYTHON_VERSION..."
|
||||
$zst = "$tmpDir\python.tar.zst"
|
||||
Invoke-WebRequest "https://github.com/astral-sh/python-build-standalone/releases/download/$PY_RELEASE_VERSION/cpython-$PYTHON_VERSION+$PY_RELEASE_VERSION-x86_64-pc-windows-msvc-pgo-full.tar.zst" -OutFile $zst
|
||||
& "C:\Program Files\7-Zip\7z.exe" e $zst -o"$tmpDir" -aoa
|
||||
$tar = Get-ChildItem "$tmpDir" -Filter "*.tar" | Select-Object -First 1
|
||||
& "C:\Program Files\7-Zip\7z.exe" x $tar.FullName -o"$tmpDir\extracted" -aoa
|
||||
Move-Item "$tmpDir\extracted\python\install" "$srcDir\runtime"
|
||||
|
||||
Write-Host "[INFO] Copying Redistributing Visual C++ Runtime..."
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
$vsPath = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
|
||||
$redistRoot = Join-Path $vsPath "VC\Redist\MSVC"
|
||||
$targetVer = Get-ChildItem -Path $redistRoot -Directory |
|
||||
Where-Object { $_.Name -match "^14\." } |
|
||||
Sort-Object Name -Descending |
|
||||
Select-Object -First 1
|
||||
$x64Path = Join-Path $targetVer.FullName "x64"
|
||||
Get-ChildItem -Path $x64Path -Directory | Where-Object {
|
||||
$_.Name -match '^Microsoft\..*\.(CRT|OpenMP)$'
|
||||
} | ForEach-Object {
|
||||
Get-ChildItem -Path $_.FullName -Filter "*.dll" | ForEach-Object {
|
||||
Copy-Item -Path $_.FullName -Destination "$srcDir\runtime" -Force
|
||||
}
|
||||
}
|
||||
|
||||
function DownloadAndUnzip($url, $targetRelPath) {
|
||||
$filename = Split-Path $url -Leaf
|
||||
$tmpZip = "$tmpDir\$filename"
|
||||
Invoke-WebRequest $url -OutFile $tmpZip
|
||||
Expand-Archive -Path $tmpZip -DestinationPath $tmpDir -Force
|
||||
$subdirName = $filename -replace '\.zip$', ''
|
||||
$sourcePath = Join-Path $tmpDir $subdirName
|
||||
$destRoot = Join-Path $srcDir $targetRelPath
|
||||
$destPath = Join-Path $destRoot $subdirName
|
||||
if (Test-Path $destPath) {
|
||||
Remove-Item $destPath -Recurse -Force
|
||||
}
|
||||
Move-Item $sourcePath $destRoot
|
||||
Remove-Item $tmpZip
|
||||
}
|
||||
|
||||
Write-Host "[INFO] Download pretrained_models..."
|
||||
DownloadAndUnzip $PRETRAINED_URL "GPT_SoVITS"
|
||||
|
||||
Write-Host "[INFO] Download G2PWModel..."
|
||||
DownloadAndUnzip $G2PW_URL "GPT_SoVITS\text"
|
||||
|
||||
Write-Host "[INFO] Download UVR5 model..."
|
||||
DownloadAndUnzip $UVR5_URL "tools\uvr5"
|
||||
|
||||
Write-Host "[INFO] Downloading funasr..."
|
||||
$funasrUrl = "https://huggingface.co/XXXXRT/GPT-SoVITS-Pretrained/resolve/main/funasr.zip"
|
||||
$funasrZip = "$tmpDir\funasr.zip"
|
||||
Invoke-WebRequest -Uri $funasrUrl -OutFile $funasrZip
|
||||
Expand-Archive -Path $funasrZip -DestinationPath "$srcDir\tools\asr\models" -Force
|
||||
Remove-Item $funasrZip
|
||||
|
||||
Write-Host "[INFO] Download ffmpeg..."
|
||||
$ffUrl = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip"
|
||||
$ffZip = "$tmpDir\ffmpeg.zip"
|
||||
Invoke-WebRequest -Uri $ffUrl -OutFile $ffZip
|
||||
Expand-Archive $ffZip -DestinationPath $tmpDir -Force
|
||||
$ffDir = Get-ChildItem -Directory "$tmpDir" | Where-Object { $_.Name -like "ffmpeg*" } | Select-Object -First 1
|
||||
Move-Item "$($ffDir.FullName)\bin\ffmpeg.exe" "$srcDir\runtime"
|
||||
Move-Item "$($ffDir.FullName)\bin\ffprobe.exe" "$srcDir\runtime"
|
||||
Remove-Item $ffZip
|
||||
Remove-Item $ffDir.FullName -Recurse -Force
|
||||
|
||||
Write-Host "[INFO] Installing PyTorch..."
|
||||
& ".\runtime\python.exe" -m ensurepip
|
||||
& ".\runtime\python.exe" -m pip install --upgrade pip --no-warn-script-location
|
||||
switch ($cuda) {
|
||||
"cu124" {
|
||||
& ".\runtime\python.exe" -m pip install torch==2.6 torchaudio --index-url https://download.pytorch.org/whl/cu124 --no-warn-script-location
|
||||
}
|
||||
"cu128" {
|
||||
& ".\runtime\python.exe" -m pip install torch torchaudio --index-url https://download.pytorch.org/whl/cu128 --no-warn-script-location
|
||||
}
|
||||
default {
|
||||
Write-Error "Unsupported CUDA version: $cuda"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "[INFO] Installing dependencies..."
|
||||
& ".\runtime\python.exe" -m pip install -r extra-req.txt --no-deps --no-warn-script-location
|
||||
& ".\runtime\python.exe" -m pip install -r requirements.txt --no-warn-script-location
|
||||
|
||||
Write-Host "[INFO] Downloading NLTK and pyopenjtalk dictionary..."
|
||||
$PYTHON = ".\runtime\python.exe"
|
||||
$prefix = & $PYTHON -c "import sys; print(sys.prefix)"
|
||||
$jtalkPath = & $PYTHON -c "import os, pyopenjtalk; print(os.path.dirname(pyopenjtalk.__file__))"
|
||||
$nltkZip = "$tmpDir\nltk_data.zip"
|
||||
$jtalkTar = "$tmpDir\open_jtalk_dic_utf_8-1.11.tar.gz"
|
||||
|
||||
Invoke-WebRequest -Uri $NLTK_URL -OutFile $nltkZip
|
||||
Expand-Archive -Path $nltkZip -DestinationPath $prefix -Force
|
||||
Remove-Item $nltkZip
|
||||
|
||||
Invoke-WebRequest -Uri $JTALK_URL -OutFile $jtalkTar
|
||||
& "C:\Program Files\7-Zip\7z.exe" e $jtalkTar -o"$tmpDir" -aoa
|
||||
$innerTar = Get-ChildItem "$tmpDir" -Filter "*.tar" | Select-Object -First 1
|
||||
& "C:\Program Files\7-Zip\7z.exe" x $innerTar.FullName -o"$jtalkPath" -aoa
|
||||
Remove-Item $jtalkTar
|
||||
Remove-Item $innerTar.FullName
|
||||
|
||||
Write-Host "[INFO] Preparing final directory $pkgName ..."
|
||||
$items = @(Get-ChildItem -Filter "*.sh") +
|
||||
@(Get-ChildItem -Filter "*.ipynb") +
|
||||
@("$tmpDir", ".github", "Docker", "docs", ".gitignore", ".dockerignore", "README.md")
|
||||
Remove-Item $items -Force -Recurse -ErrorAction SilentlyContinue
|
||||
$curr = Get-Location
|
||||
Set-Location ../
|
||||
Get-ChildItem .
|
||||
Copy-Item -Path $curr -Destination $pkgName -Recurse
|
||||
$7zPath = "$pkgName.7z"
|
||||
$start = Get-Date
|
||||
Write-Host "Compress Starting at $start"
|
||||
& "C:\Program Files\7-Zip\7z.exe" a -t7z "$7zPath" "$pkgName" -m0=lzma2 -mx=9 -md=1g -ms=1g -mmc=500 -mfb=273 -mlc=0 -mlp=4 -mpb=4 -mc=8g -mmt=on -bsp1
|
||||
$end = Get-Date
|
||||
Write-Host "Elapsed time: $($end - $start)"
|
||||
Get-ChildItem .
|
||||
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install "modelscope" "huggingface_hub[hf_transfer]" --no-warn-script-location
|
||||
|
||||
Write-Host "[INFO] Uploading to ModelScope..."
|
||||
$msUser = $env:MODELSCOPE_USERNAME
|
||||
$msToken = $env:MODELSCOPE_TOKEN
|
||||
if (-not $msUser -or -not $msToken) {
|
||||
Write-Error "Missing MODELSCOPE_USERNAME or MODELSCOPE_TOKEN"
|
||||
exit 1
|
||||
}
|
||||
modelscope upload "$msUser/GPT-SoVITS-Packages" "$7zPath" "$7zPath" --repo-type model --token $msToken
|
||||
|
||||
Write-Host "[SUCCESS] Uploaded: $7zPath to ModelScope"
|
||||
|
||||
Write-Host "[INFO] Uploading to HuggingFace..."
|
||||
$hfUser = $env:HUGGINGFACE_USERNAME
|
||||
$hfToken = $env:HUGGINGFACE_TOKEN
|
||||
if (-not $hfUser -or -not $hfToken) {
|
||||
Write-Error "Missing HUGGINGFACE_USERNAME or HUGGINGFACE_TOKEN"
|
||||
exit 1
|
||||
}
|
||||
$env:HF_HUB_ENABLE_HF_TRANSFER = "1"
|
||||
huggingface-cli upload "$hfUser/GPT-SoVITS-Packages" "$7zPath" "$7zPath" --repo-type model --token $hfToken
|
||||
|
||||
Write-Host "[SUCCESS] Uploaded: $7zPath to HuggingFace"
|
||||
38
.github/workflows/build_windows_packages.yaml
vendored
38
.github/workflows/build_windows_packages.yaml
vendored
@ -1,38 +0,0 @@
|
||||
name: Build and Upload Windows Package
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
date:
|
||||
description: "Date suffix (optional)"
|
||||
required: false
|
||||
default: ""
|
||||
suffix:
|
||||
description: "Package name suffix (optional)"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
matrix:
|
||||
torch_cuda: [cu124, cu128]
|
||||
env:
|
||||
TORCH_CUDA: ${{ matrix.torch_cuda }}
|
||||
MODELSCOPE_USERNAME: ${{ secrets.MODELSCOPE_USERNAME }}
|
||||
MODELSCOPE_TOKEN: ${{ secrets.MODELSCOPE_TOKEN }}
|
||||
HUGGINGFACE_USERNAME: ${{ secrets.HUGGINGFACE_USERNAME }}
|
||||
HUGGINGFACE_TOKEN: ${{ secrets.HUGGINGFACE_TOKEN }}
|
||||
DATE_SUFFIX: ${{ github.event.inputs.date }}
|
||||
PKG_SUFFIX: ${{ github.event.inputs.suffix }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run Build and Upload Script
|
||||
shell: pwsh
|
||||
run: |
|
||||
Move-Item .github/build_windows_packages.ps1 ../build_windows_packages.ps1
|
||||
../build_windows_packages.ps1
|
||||
280
.github/workflows/docker-publish.yaml
vendored
280
.github/workflows/docker-publish.yaml
vendored
@ -1,280 +0,0 @@
|
||||
name: Build and Publish Docker Image
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
generate-meta:
|
||||
runs-on: ubuntu-22.04
|
||||
outputs:
|
||||
tag: ${{ steps.meta.outputs.tag }}
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Generate Tag
|
||||
id: meta
|
||||
run: |
|
||||
DATE=$(date +'%Y%m%d')
|
||||
COMMIT=$(git rev-parse --short=6 HEAD)
|
||||
echo "tag=${DATE}-${COMMIT}" >> $GITHUB_OUTPUT
|
||||
build-amd64:
|
||||
needs: generate-meta
|
||||
runs-on: ubuntu-22.04
|
||||
environment: Docker
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- cuda_version: 12.6
|
||||
lite: true
|
||||
torch_base: lite
|
||||
tag_prefix: cu126-lite
|
||||
- cuda_version: 12.6
|
||||
lite: false
|
||||
torch_base: full
|
||||
tag_prefix: cu126
|
||||
- cuda_version: 12.8
|
||||
lite: true
|
||||
torch_base: lite
|
||||
tag_prefix: cu128-lite
|
||||
- cuda_version: 12.8
|
||||
lite: false
|
||||
torch_base: full
|
||||
tag_prefix: cu128
|
||||
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Free up disk space
|
||||
run: |
|
||||
echo "Before cleanup:"
|
||||
df -h
|
||||
|
||||
sudo rm -rf /opt/ghc
|
||||
sudo rm -rf /opt/hostedtoolcache/CodeQL
|
||||
sudo rm -rf /opt/hostedtoolcache/PyPy
|
||||
sudo rm -rf /opt/hostedtoolcache/go
|
||||
sudo rm -rf /opt/hostedtoolcache/node
|
||||
sudo rm -rf /opt/hostedtoolcache/Ruby
|
||||
sudo rm -rf /opt/microsoft
|
||||
sudo rm -rf /opt/pipx
|
||||
sudo rm -rf /opt/az
|
||||
sudo rm -rf /opt/google
|
||||
|
||||
|
||||
sudo rm -rf /usr/lib/jvm
|
||||
sudo rm -rf /usr/lib/google-cloud-sdk
|
||||
sudo rm -rf /usr/lib/dotnet
|
||||
|
||||
sudo rm -rf /usr/local/lib/android
|
||||
sudo rm -rf /usr/local/.ghcup
|
||||
sudo rm -rf /usr/local/julia1.11.5
|
||||
sudo rm -rf /usr/local/share/powershell
|
||||
sudo rm -rf /usr/local/share/chromium
|
||||
|
||||
sudo rm -rf /usr/share/swift
|
||||
sudo rm -rf /usr/share/miniconda
|
||||
sudo rm -rf /usr/share/az_12.1.0
|
||||
sudo rm -rf /usr/share/dotnet
|
||||
|
||||
echo "After cleanup:"
|
||||
df -h
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ vars.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_PASSWORD }}
|
||||
|
||||
- name: Build and Push Docker Image (amd64)
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: true
|
||||
platforms: linux/amd64
|
||||
build-args: |
|
||||
LITE=${{ matrix.lite }}
|
||||
TORCH_BASE=${{ matrix.torch_base }}
|
||||
CUDA_VERSION=${{ matrix.cuda_version }}
|
||||
WORKFLOW=true
|
||||
tags: |
|
||||
xxxxrt666/gpt-sovits:${{ matrix.tag_prefix }}-${{ needs.generate-meta.outputs.tag }}-amd64
|
||||
xxxxrt666/gpt-sovits:latest-${{ matrix.tag_prefix }}-amd64
|
||||
|
||||
build-arm64:
|
||||
needs: generate-meta
|
||||
runs-on: ubuntu-22.04-arm
|
||||
environment: Docker
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- cuda_version: 12.6
|
||||
lite: true
|
||||
torch_base: lite
|
||||
tag_prefix: cu126-lite
|
||||
- cuda_version: 12.6
|
||||
lite: false
|
||||
torch_base: full
|
||||
tag_prefix: cu126
|
||||
- cuda_version: 12.8
|
||||
lite: true
|
||||
torch_base: lite
|
||||
tag_prefix: cu128-lite
|
||||
- cuda_version: 12.8
|
||||
lite: false
|
||||
torch_base: full
|
||||
tag_prefix: cu128
|
||||
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Free up disk space
|
||||
run: |
|
||||
echo "Before cleanup:"
|
||||
df -h
|
||||
|
||||
sudo rm -rf /opt/ghc
|
||||
sudo rm -rf /opt/hostedtoolcache/CodeQL
|
||||
sudo rm -rf /opt/hostedtoolcache/PyPy
|
||||
sudo rm -rf /opt/hostedtoolcache/go
|
||||
sudo rm -rf /opt/hostedtoolcache/node
|
||||
sudo rm -rf /opt/hostedtoolcache/Ruby
|
||||
sudo rm -rf /opt/microsoft
|
||||
sudo rm -rf /opt/pipx
|
||||
sudo rm -rf /opt/az
|
||||
sudo rm -rf /opt/google
|
||||
|
||||
|
||||
sudo rm -rf /usr/lib/jvm
|
||||
sudo rm -rf /usr/lib/google-cloud-sdk
|
||||
sudo rm -rf /usr/lib/dotnet
|
||||
|
||||
sudo rm -rf /usr/local/lib/android
|
||||
sudo rm -rf /usr/local/.ghcup
|
||||
sudo rm -rf /usr/local/julia1.11.5
|
||||
sudo rm -rf /usr/local/share/powershell
|
||||
sudo rm -rf /usr/local/share/chromium
|
||||
|
||||
sudo rm -rf /usr/share/swift
|
||||
sudo rm -rf /usr/share/miniconda
|
||||
sudo rm -rf /usr/share/az_12.1.0
|
||||
sudo rm -rf /usr/share/dotnet
|
||||
|
||||
echo "After cleanup:"
|
||||
df -h
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ vars.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_PASSWORD }}
|
||||
|
||||
- name: Build and Push Docker Image (arm64)
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: true
|
||||
platforms: linux/arm64
|
||||
build-args: |
|
||||
LITE=${{ matrix.lite }}
|
||||
TORCH_BASE=${{ matrix.torch_base }}
|
||||
CUDA_VERSION=${{ matrix.cuda_version }}
|
||||
WORKFLOW=true
|
||||
tags: |
|
||||
xxxxrt666/gpt-sovits:${{ matrix.tag_prefix }}-${{ needs.generate-meta.outputs.tag }}-arm64
|
||||
xxxxrt666/gpt-sovits:latest-${{ matrix.tag_prefix }}-arm64
|
||||
|
||||
|
||||
merge-and-clean:
|
||||
needs:
|
||||
- build-amd64
|
||||
- build-arm64
|
||||
- generate-meta
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- tag_prefix: cu126-lite
|
||||
- tag_prefix: cu126
|
||||
- tag_prefix: cu128-lite
|
||||
- tag_prefix: cu128
|
||||
environment: Docker
|
||||
|
||||
steps:
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ vars.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_PASSWORD }}
|
||||
|
||||
- name: Merge amd64 and arm64 into multi-arch image
|
||||
run: |
|
||||
DATE_TAG=${{ needs.generate-meta.outputs.tag }}
|
||||
TAG_PREFIX=${{ matrix.tag_prefix }}
|
||||
|
||||
docker buildx imagetools create \
|
||||
--tag ${{ vars.DOCKER_HUB_USERNAME }}/gpt-sovits:${TAG_PREFIX}-${DATE_TAG} \
|
||||
${{ vars.DOCKER_HUB_USERNAME }}/gpt-sovits:${TAG_PREFIX}-${DATE_TAG}-amd64 \
|
||||
${{ vars.DOCKER_HUB_USERNAME }}/gpt-sovits:${TAG_PREFIX}-${DATE_TAG}-arm64
|
||||
|
||||
docker buildx imagetools create \
|
||||
--tag ${{ vars.DOCKER_HUB_USERNAME }}/gpt-sovits:latest-${TAG_PREFIX} \
|
||||
${{ vars.DOCKER_HUB_USERNAME }}/gpt-sovits:latest-${TAG_PREFIX}-amd64 \
|
||||
${{ vars.DOCKER_HUB_USERNAME }}/gpt-sovits:latest-${TAG_PREFIX}-arm64
|
||||
- name: Delete old platform-specific tags via Docker Hub API
|
||||
env:
|
||||
DOCKER_HUB_USERNAME: ${{ vars.DOCKER_HUB_USERNAME }}
|
||||
DOCKER_HUB_TOKEN: ${{ secrets.DOCKER_HUB_PASSWORD }}
|
||||
TAG_PREFIX: ${{ matrix.tag_prefix }}
|
||||
DATE_TAG: ${{ needs.generate-meta.outputs.tag }}
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y jq
|
||||
|
||||
TOKEN=$(curl -s -u $DOCKER_HUB_USERNAME:$DOCKER_HUB_TOKEN \
|
||||
"https://auth.docker.io/token?service=registry.docker.io&scope=repository:$DOCKER_HUB_USERNAME/gpt-sovits:pull,push,delete" \
|
||||
| jq -r .token)
|
||||
|
||||
for PLATFORM in amd64 arm64; do
|
||||
SAFE_PLATFORM=$(echo $PLATFORM | sed 's/\//-/g')
|
||||
TAG="${TAG_PREFIX}-${DATE_TAG}-${SAFE_PLATFORM}"
|
||||
LATEST_TAG="latest-${TAG_PREFIX}-${SAFE_PLATFORM}"
|
||||
|
||||
for DEL_TAG in "$TAG" "$LATEST_TAG"; do
|
||||
echo "Deleting tag: $DEL_TAG"
|
||||
curl -X DELETE -H "Authorization: Bearer $TOKEN" https://registry-1.docker.io/v2/$DOCKER_HUB_USERNAME/gpt-sovits/manifests/$DEL_TAG
|
||||
done
|
||||
done
|
||||
create-default:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- merge-and-clean
|
||||
environment: Docker
|
||||
steps:
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ vars.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_PASSWORD }}
|
||||
|
||||
- name: Create Default Tag
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
--tag ${{ vars.DOCKER_HUB_USERNAME }}/gpt-sovits:latest \
|
||||
${{ vars.DOCKER_HUB_USERNAME }}/gpt-sovits:latest-cu126-lite
|
||||
|
||||
68
.github/workflows/inference.yaml
vendored
Normal file
68
.github/workflows/inference.yaml
vendored
Normal file
@ -0,0 +1,68 @@
|
||||
name: Inference Tests and Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Install inference runtime
|
||||
run: |
|
||||
python -m pip install torch==2.7.1 torchaudio==2.7.1 --index-url https://download.pytorch.org/whl/cpu
|
||||
python -m pip install -r requirements.txt
|
||||
- name: Prepare language resources
|
||||
run: python -c "import nltk; [nltk.download(n, quiet=True, raise_on_error=True) for n in ('cmudict','punkt','punkt_tab','averaged_perceptron_tagger','averaged_perceptron_tagger_eng')]; import pyopenjtalk; pyopenjtalk.g2p('test')"
|
||||
- name: Import service without model weights
|
||||
run: python -c "import api_v2; assert api_v2.tts_pipeline is None"
|
||||
- name: Test API, streaming, and checkpoint compatibility
|
||||
run: python -m unittest discover -s tests -t . -p "test_*.py"
|
||||
|
||||
docker:
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Set image name
|
||||
shell: bash
|
||||
run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/gpt-sovits-inference" >> "$GITHUB_ENV"
|
||||
- name: Build inference image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
load: true
|
||||
tags: ${{ env.IMAGE }}:latest
|
||||
- name: Verify container imports and HTTP contract
|
||||
run: |
|
||||
docker run --rm --entrypoint python "$IMAGE:latest" -c "import api_v2; assert api_v2.tts_pipeline is None"
|
||||
docker run --rm --entrypoint python "$IMAGE:latest" -m unittest tests.test_api_v2_streaming
|
||||
- name: Log in to GitHub Container Registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Publish inference image
|
||||
if: github.event_name != 'pull_request'
|
||||
run: docker push "$IMAGE:latest"
|
||||
232
.gitignore
vendored
232
.gitignore
vendored
@ -1,195 +1,51 @@
|
||||
.DS_Store
|
||||
.vscode
|
||||
__pycache__
|
||||
*.pyc
|
||||
env
|
||||
runtime
|
||||
.idea
|
||||
output
|
||||
logs
|
||||
SoVITS_weights*/
|
||||
GPT_weights*/
|
||||
TEMP
|
||||
weight.json
|
||||
ffmpeg*
|
||||
ffprobe*
|
||||
cfg.json
|
||||
speakers.json
|
||||
ref_audios
|
||||
tools/AP_BWE_main/24kto48k/*
|
||||
!tools/AP_BWE_main/24kto48k/readme.txt
|
||||
# Local environments and runtime bundles
|
||||
/.codex/
|
||||
/.venv/
|
||||
/venv/
|
||||
/env/
|
||||
/ENV/
|
||||
/runtime/
|
||||
.env
|
||||
.env.*
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
# Models, references and local inference settings
|
||||
/models/
|
||||
/references/
|
||||
/ref_audios/
|
||||
/GPT_weights*/
|
||||
/SoVITS_weights*/
|
||||
/GPT_SoVITS/text/G2PWModel/
|
||||
/GPT_SoVITS/configs/tts_local*.yaml
|
||||
/tools/AP_BWE_main/24kto48k/*
|
||||
!/tools/AP_BWE_main/24kto48k/config.json
|
||||
/weight.json
|
||||
/cfg.json
|
||||
/speakers.json
|
||||
/ffmpeg*
|
||||
/ffprobe*
|
||||
|
||||
# Generated output, caches and package artifacts
|
||||
/output/
|
||||
/output.wav
|
||||
/logs/
|
||||
/TEMP/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
*.log
|
||||
.cache/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
.mypy_cache/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
htmlcov/
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
build/
|
||||
dist/
|
||||
*.egg-info/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
# Local editor and OS state
|
||||
.vscode/
|
||||
.idea/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
@ -1,191 +0,0 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"<a href=\"https://colab.research.google.com/github/RVC-Boss/GPT-SoVITS/blob/main/Colab-Inference.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# GPT-SoVITS Infer"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Env Setup (Run Once Only)\n",
|
||||
"## 环境配置, 只需运行一次"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### 1."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "e9b7iFV3dm1f"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%%writefile /content/setup.sh\n",
|
||||
"set -e\n",
|
||||
"\n",
|
||||
"cd /content\n",
|
||||
"\n",
|
||||
"git clone https://github.com/RVC-Boss/GPT-SoVITS.git\n",
|
||||
"\n",
|
||||
"cd GPT-SoVITS\n",
|
||||
"\n",
|
||||
"mkdir -p GPT_weights\n",
|
||||
"\n",
|
||||
"mkdir -p SoVITS_weights\n",
|
||||
"\n",
|
||||
"if conda env list | awk '{print $1}' | grep -Fxq \"GPTSoVITS\"; then\n",
|
||||
" :\n",
|
||||
"else\n",
|
||||
" conda create -n GPTSoVITS python=3.10 -y\n",
|
||||
"fi\n",
|
||||
"\n",
|
||||
"source activate GPTSoVITS\n",
|
||||
"\n",
|
||||
"pip install ipykernel\n",
|
||||
"\n",
|
||||
"bash install.sh --device CU126 --source HF"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### 2."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"cellView": "form",
|
||||
"id": "0NgxXg5sjv7z"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install -q condacolab\n",
|
||||
"import condacolab\n",
|
||||
"condacolab.install_from_url(\"https://repo.anaconda.com/archive/Anaconda3-2024.10-1-Linux-x86_64.sh\")\n",
|
||||
"!cd /content && bash setup.sh"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Download Model"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Download From HuggingFace"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"cellView": "form",
|
||||
"id": "vbZY-LnM0tzq"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Modify These\n",
|
||||
"USER_ID = \"AkitoP\"\n",
|
||||
"REPO_NAME = \"GPT-SoVITS-v2-aegi\"\n",
|
||||
"BRANCH = \"main\"\n",
|
||||
"GPT_PATH = \"new_aegigoe-e100.ckpt\"\n",
|
||||
"SOVITS_PATH = \"new_aegigoe_e60_s32220.pth\"\n",
|
||||
"\n",
|
||||
"# Do Not Modify\n",
|
||||
"HF_BASE = \"https://huggingface.co\"\n",
|
||||
"REPO_ID = f\"{USER_ID}/{REPO_NAME}\"\n",
|
||||
"GPT_URL = f\"{HF_BASE}/{REPO_ID}/blob/{BRANCH}/{GPT_PATH}\"\n",
|
||||
"SOVITS_URL = f\"{HF_BASE}/{REPO_ID}/blob/{BRANCH}/{SOVITS_PATH}\"\n",
|
||||
"\n",
|
||||
"!cd \"/content/GPT-SoVITS/GPT_weights\" && wget \"{GPT_URL}\"\n",
|
||||
"!cd \"/content/GPT-SoVITS/SoVITS_weights\" && wget \"{SOVITS_URL}\"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Download From ModelScope"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Modify These\n",
|
||||
"USER_ID = \"aihobbyist\"\n",
|
||||
"REPO_NAME = \"GPT-SoVits-V2-models\"\n",
|
||||
"BRANCH = \"master\"\n",
|
||||
"GPT_PATH = \"Genshin_Impact/EN/GPT_GenshinImpact_EN_5.1.ckpt\"\n",
|
||||
"SOVITS_PATH = \"Wuthering_Waves/CN/SV_WutheringWaves_CN_1.3.pth\"\n",
|
||||
"\n",
|
||||
"# Do Not Modify\n",
|
||||
"HF_BASE = \"https://www.modelscope.cn/models\"\n",
|
||||
"REPO_ID = f\"{USER_ID}/{REPO_NAME}\"\n",
|
||||
"GPT_URL = f\"{HF_BASE}/{REPO_ID}/resolve/{BRANCH}/{GPT_PATH}\"\n",
|
||||
"SOVITS_URL = f\"{HF_BASE}/{REPO_ID}/resolve/{BRANCH}/{SOVITS_PATH}\"\n",
|
||||
"\n",
|
||||
"!cd \"/content/GPT-SoVITS/GPT_weights\" && wget \"{GPT_URL}\"\n",
|
||||
"!cd \"/content/GPT-SoVITS/SoVITS_weights\" && wget \"{SOVITS_URL}\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Launch WebUI\n",
|
||||
"# 启动 WebUI"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"cellView": "form",
|
||||
"id": "4oRGUzkrk8C7"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!cd /content/GPT-SoVITS && source activate GPTSoVITS && export is_share=True && python webui.py"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"accelerator": "GPU",
|
||||
"colab": {
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@ -1,117 +0,0 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"colab_type": "text",
|
||||
"id": "view-in-github"
|
||||
},
|
||||
"source": [
|
||||
"<a href=\"https://colab.research.google.com/github/RVC-Boss/GPT-SoVITS/blob/main/Colab-WebUI.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# GPT-SoVITS WebUI"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "_o6a8GS2lWQM"
|
||||
},
|
||||
"source": [
|
||||
"## Env Setup (Run Once Only)\n",
|
||||
"## 环境配置, 只需运行一次"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### 1."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%%writefile /content/setup.sh\n",
|
||||
"set -e\n",
|
||||
"\n",
|
||||
"cd /content\n",
|
||||
"\n",
|
||||
"git clone https://github.com/RVC-Boss/GPT-SoVITS.git\n",
|
||||
"\n",
|
||||
"cd GPT-SoVITS\n",
|
||||
"\n",
|
||||
"if conda env list | awk '{print $1}' | grep -Fxq \"GPTSoVITS\"; then\n",
|
||||
" :\n",
|
||||
"else\n",
|
||||
" conda create -n GPTSoVITS python=3.10 -y\n",
|
||||
"fi\n",
|
||||
"\n",
|
||||
"source activate GPTSoVITS\n",
|
||||
"\n",
|
||||
"pip install ipykernel\n",
|
||||
"\n",
|
||||
"bash install.sh --device CU126 --source HF --download-uvr5"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### 2."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install -q condacolab\n",
|
||||
"import condacolab\n",
|
||||
"condacolab.install_from_url(\"https://repo.anaconda.com/archive/Anaconda3-2024.10-1-Linux-x86_64.sh\")\n",
|
||||
"!cd /content && bash setup.sh"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Launch WebUI\n",
|
||||
"## 启动 WebUI"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4oRGUzkrk8C7"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!cd /content/GPT-SoVITS && source activate GPTSoVITS && export is_share=True && python webui.py"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"accelerator": "GPU",
|
||||
"colab": {
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
|
||||
|
||||
cd "$SCRIPT_DIR" || exit 1
|
||||
|
||||
cd .. || exit 1
|
||||
|
||||
set -e
|
||||
|
||||
source "$HOME/conda/etc/profile.d/conda.sh"
|
||||
|
||||
mkdir -p GPT_SoVITS
|
||||
|
||||
mkdir -p GPT_SoVITS/text
|
||||
|
||||
ln -s /workspace/models/pretrained_models /workspace/GPT-SoVITS/GPT_SoVITS/pretrained_models
|
||||
|
||||
ln -s /workspace/models/G2PWModel /workspace/GPT-SoVITS/GPT_SoVITS/text/G2PWModel
|
||||
|
||||
TERM=dumb bash install.sh --device "CU${CUDA_VERSION//./}" --source HF
|
||||
|
||||
pip cache purge
|
||||
|
||||
pip show torch
|
||||
|
||||
rm -rf /tmp/* /var/tmp/*
|
||||
|
||||
rm -rf "$HOME/conda/pkgs"
|
||||
|
||||
mkdir -p "$HOME/conda/pkgs"
|
||||
|
||||
rm -rf /root/.conda /root/.cache
|
||||
@ -1,82 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
|
||||
|
||||
cd "$SCRIPT_DIR" || exit 1
|
||||
|
||||
cd .. || exit 1
|
||||
|
||||
if [ -d "$HOME/conda" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
WORKFLOW=${WORKFLOW:-"false"}
|
||||
TARGETPLATFORM=${TARGETPLATFORM:-"linux/amd64"}
|
||||
|
||||
if [ "$WORKFLOW" = "true" ]; then
|
||||
WGET_CMD=(wget -nv --tries=25 --wait=5 --read-timeout=40 --retry-on-http-error=404)
|
||||
else
|
||||
WGET_CMD=(wget --tries=25 --wait=5 --read-timeout=40 --retry-on-http-error=404)
|
||||
fi
|
||||
|
||||
if [ "$TARGETPLATFORM" = "linux/amd64" ]; then
|
||||
"${WGET_CMD[@]}" -O Miniforge.sh "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
|
||||
SYSROOT_PKG="sysroot_linux-64>=2.28"
|
||||
elif [ "$TARGETPLATFORM" = "linux/arm64" ]; then
|
||||
"${WGET_CMD[@]}" -O Miniforge.sh "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
|
||||
SYSROOT_PKG="sysroot_linux-aarch64>=2.28"
|
||||
else
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LOG_PATH="/tmp/miniforge-install.log"
|
||||
|
||||
bash Miniforge.sh -b -p "$HOME/conda" >"$LOG_PATH" 2>&1
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "== Miniforge Installed =="
|
||||
else
|
||||
echo "Failed to Install miniforge"
|
||||
tail -n 50 "$LOG_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
rm Miniforge.sh
|
||||
|
||||
source "$HOME/conda/etc/profile.d/conda.sh"
|
||||
|
||||
"$HOME/conda/bin/conda" init bash
|
||||
|
||||
source "$HOME/.bashrc"
|
||||
|
||||
"$HOME/conda/bin/conda" info
|
||||
|
||||
"$HOME/conda/bin/conda" update --all -y
|
||||
|
||||
"$HOME/conda/bin/conda" install python=3.12 -y
|
||||
|
||||
"$HOME/conda/bin/conda" install gcc=11 gxx ffmpeg cmake make unzip $SYSROOT_PKG "libstdcxx-ng>=11" -y
|
||||
|
||||
if [ "$CUDA_VERSION" = "12.8" ]; then
|
||||
"$HOME/conda/bin/pip" install torch torchcodec --no-cache-dir --index-url https://download.pytorch.org/whl/cu128
|
||||
"$HOME/conda/bin/conda" install cuda-nvcc=12.8 -y
|
||||
elif [ "$CUDA_VERSION" = "12.6" ]; then
|
||||
"$HOME/conda/bin/pip" install torch torchcodec --no-cache-dir --index-url https://download.pytorch.org/whl/cu126
|
||||
"$HOME/conda/bin/conda" install cuda-nvcc=12.6 -y
|
||||
fi
|
||||
|
||||
export PATH="$HOME/conda/bin:$PATH"
|
||||
|
||||
"$HOME/conda/bin/pip" install psutil ninja packaging wheel "setuptools>=42" einops
|
||||
"$HOME/conda/bin/pip" install flash-attn -i https://xxxxrt666.github.io/PIP-Index/ --no-build-isolation
|
||||
"$HOME/conda/bin/pip" cache purge
|
||||
|
||||
rm $LOG_PATH
|
||||
|
||||
rm -rf "$HOME/conda/pkgs"
|
||||
|
||||
mkdir -p "$HOME/conda/pkgs"
|
||||
|
||||
rm -rf "$HOME/.conda" "$HOME/.cache"
|
||||
76
Dockerfile
76
Dockerfile
@ -1,60 +1,26 @@
|
||||
ARG CUDA_VERSION=12.6
|
||||
ARG TORCH_BASE=full
|
||||
ARG BASE_IMAGE=pytorch/pytorch:2.7.1-cuda12.8-cudnn9-runtime
|
||||
FROM ${BASE_IMAGE}
|
||||
ARG TORCH_INDEX_URL=https://download.pytorch.org/whl/cu128
|
||||
|
||||
FROM xxxxrt666/torch-base:cu${CUDA_VERSION}-${TORCH_BASE}
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONPATH=/app \
|
||||
NLTK_DATA=/opt/nltk_data
|
||||
|
||||
LABEL maintainer="XXXXRT"
|
||||
LABEL version="V2 Pro"
|
||||
LABEL description="Docker image for GPT-SoVITS"
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ffmpeg libsndfile1 build-essential \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ARG CUDA_VERSION=12.6
|
||||
COPY requirements.txt ./requirements.txt
|
||||
RUN python -m pip install --no-cache-dir --upgrade pip \
|
||||
&& python -m pip install --no-cache-dir torchaudio==2.7.1 --index-url ${TORCH_INDEX_URL} \
|
||||
&& python -m pip install --no-cache-dir -r requirements.txt \
|
||||
&& python -c "import nltk; [nltk.download(name, download_dir='/opt/nltk_data', quiet=True, raise_on_error=True) for name in ('cmudict', 'punkt', 'punkt_tab', 'averaged_perceptron_tagger', 'averaged_perceptron_tagger_eng')]" \
|
||||
&& python -c "import pyopenjtalk; pyopenjtalk.g2p('test')"
|
||||
|
||||
ENV CUDA_VERSION=${CUDA_VERSION}
|
||||
COPY . .
|
||||
EXPOSE 9880
|
||||
|
||||
SHELL ["/bin/bash", "-c"]
|
||||
|
||||
WORKDIR /workspace/GPT-SoVITS
|
||||
|
||||
COPY Docker /workspace/GPT-SoVITS/Docker/
|
||||
|
||||
ARG LITE=false
|
||||
ENV LITE=${LITE}
|
||||
|
||||
ARG WORKFLOW=false
|
||||
ENV WORKFLOW=${WORKFLOW}
|
||||
|
||||
ARG TARGETPLATFORM
|
||||
ENV TARGETPLATFORM=${TARGETPLATFORM}
|
||||
|
||||
COPY extra-req.txt /workspace/GPT-SoVITS/
|
||||
|
||||
COPY requirements.txt /workspace/GPT-SoVITS/
|
||||
|
||||
COPY install.sh /workspace/GPT-SoVITS/
|
||||
|
||||
RUN bash Docker/install_wrapper.sh
|
||||
|
||||
EXPOSE 9871 9872 9873 9874 9880
|
||||
|
||||
ENV PYTHONPATH="/workspace/GPT-SoVITS"
|
||||
|
||||
RUN conda init bash && echo "conda activate base" >> ~/.bashrc
|
||||
|
||||
WORKDIR /workspace
|
||||
|
||||
RUN rm -rf /workspace/GPT-SoVITS
|
||||
|
||||
WORKDIR /workspace/GPT-SoVITS
|
||||
|
||||
COPY . /workspace/GPT-SoVITS
|
||||
|
||||
CMD ["/bin/bash", "-c", "\
|
||||
rm -rf /workspace/GPT-SoVITS/GPT_SoVITS/pretrained_models && \
|
||||
rm -rf /workspace/GPT-SoVITS/GPT_SoVITS/text/G2PWModel && \
|
||||
rm -rf /workspace/GPT-SoVITS/tools/asr/models && \
|
||||
rm -rf /workspace/GPT-SoVITS/tools/uvr5/uvr5_weights && \
|
||||
ln -s /workspace/models/pretrained_models /workspace/GPT-SoVITS/GPT_SoVITS/pretrained_models && \
|
||||
ln -s /workspace/models/G2PWModel /workspace/GPT-SoVITS/GPT_SoVITS/text/G2PWModel && \
|
||||
ln -s /workspace/models/asr_models /workspace/GPT-SoVITS/tools/asr/models && \
|
||||
ln -s /workspace/models/uvr5_weights /workspace/GPT-SoVITS/tools/uvr5/uvr5_weights && \
|
||||
exec bash"]
|
||||
ENTRYPOINT ["python", "api_v2.py"]
|
||||
CMD ["-a", "0.0.0.0", "-p", "9880", "-c", "GPT_SoVITS/configs/tts_infer.yaml"]
|
||||
|
||||
@ -1,149 +0,0 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/data/bucket_sampler.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
import itertools
|
||||
import math
|
||||
import random
|
||||
from random import shuffle
|
||||
from typing import Iterator, Optional, TypeVar
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.utils.data import Dataset, Sampler
|
||||
|
||||
__all__ = [
|
||||
"DistributedBucketSampler",
|
||||
]
|
||||
|
||||
T_co = TypeVar("T_co", covariant=True)
|
||||
|
||||
|
||||
class DistributedBucketSampler(Sampler[T_co]):
|
||||
r"""
|
||||
sort the dataset wrt. input length
|
||||
divide samples into buckets
|
||||
sort within buckets
|
||||
divide buckets into batches
|
||||
sort batches
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dataset: Dataset,
|
||||
num_replicas: Optional[int] = None,
|
||||
rank: Optional[int] = None,
|
||||
shuffle: bool = True,
|
||||
seed: int = 0,
|
||||
drop_last: bool = False,
|
||||
batch_size: int = 32,
|
||||
) -> None:
|
||||
if num_replicas is None:
|
||||
if not dist.is_available():
|
||||
raise RuntimeError("Requires distributed package to be available")
|
||||
num_replicas = dist.get_world_size() if torch.cuda.is_available() else 1
|
||||
if rank is None:
|
||||
if not dist.is_available():
|
||||
raise RuntimeError("Requires distributed package to be available")
|
||||
rank = dist.get_rank() if torch.cuda.is_available() else 0
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.set_device(rank)
|
||||
if rank >= num_replicas or rank < 0:
|
||||
raise ValueError("Invalid rank {}, rank should be in the interval [0, {}]".format(rank, num_replicas - 1))
|
||||
self.dataset = dataset
|
||||
self.num_replicas = num_replicas
|
||||
self.rank = rank
|
||||
self.epoch = 0
|
||||
self.drop_last = drop_last
|
||||
# If the dataset length is evenly divisible by # of replicas, then there
|
||||
# is no need to drop any data, since the dataset will be split equally.
|
||||
if self.drop_last and len(self.dataset) % self.num_replicas != 0: # type: ignore[arg-type]
|
||||
# Split to nearest available length that is evenly divisible.
|
||||
# This is to ensure each rank receives the same amount of data when
|
||||
# using this Sampler.
|
||||
self.num_samples = math.ceil(
|
||||
(len(self.dataset) - self.num_replicas) / self.num_replicas, # type: ignore[arg-type]
|
||||
)
|
||||
else:
|
||||
self.num_samples = math.ceil(
|
||||
len(self.dataset) / self.num_replicas,
|
||||
) # type: ignore[arg-type]
|
||||
self.total_size = self.num_samples * self.num_replicas
|
||||
self.shuffle = shuffle
|
||||
self.seed = seed
|
||||
self.batch_size = batch_size
|
||||
self.id_with_length = self._get_sample_lengths()
|
||||
self.id_buckets = self.make_buckets(bucket_width=2.0)
|
||||
|
||||
def _get_sample_lengths(self):
|
||||
id_with_lengths = []
|
||||
for i in range(len(self.dataset)):
|
||||
id_with_lengths.append((i, self.dataset.get_sample_length(i)))
|
||||
id_with_lengths.sort(key=lambda x: x[1])
|
||||
return id_with_lengths
|
||||
|
||||
def make_buckets(self, bucket_width: float = 2.0):
|
||||
buckets = []
|
||||
cur = []
|
||||
max_sec = bucket_width
|
||||
for id, sec in self.id_with_length:
|
||||
if sec < max_sec:
|
||||
cur.append(id)
|
||||
else:
|
||||
buckets.append(cur)
|
||||
cur = [id]
|
||||
max_sec += bucket_width
|
||||
if len(cur) > 0:
|
||||
buckets.append(cur)
|
||||
return buckets
|
||||
|
||||
def __iter__(self) -> Iterator[T_co]:
|
||||
if self.shuffle:
|
||||
# deterministically shuffle based on epoch and seed
|
||||
g = torch.Generator()
|
||||
g.manual_seed(self.seed + self.epoch)
|
||||
random.seed(self.epoch + self.seed)
|
||||
shuffled_bucket = []
|
||||
for buc in self.id_buckets:
|
||||
buc_copy = buc.copy()
|
||||
shuffle(buc_copy)
|
||||
shuffled_bucket.append(buc_copy)
|
||||
grouped_batch_size = self.batch_size * self.num_replicas
|
||||
shuffled_bucket = list(itertools.chain(*shuffled_bucket))
|
||||
n_batch = int(math.ceil(len(shuffled_bucket) / grouped_batch_size))
|
||||
batches = [shuffled_bucket[b * grouped_batch_size : (b + 1) * grouped_batch_size] for b in range(n_batch)]
|
||||
shuffle(batches)
|
||||
indices = list(itertools.chain(*batches))
|
||||
else:
|
||||
# type: ignore[arg-type]
|
||||
indices = list(range(len(self.dataset)))
|
||||
|
||||
if not self.drop_last:
|
||||
# add extra samples to make it evenly divisible
|
||||
padding_size = self.total_size - len(indices)
|
||||
if padding_size <= len(indices):
|
||||
indices += indices[:padding_size]
|
||||
else:
|
||||
indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size]
|
||||
else:
|
||||
# remove tail of data to make it evenly divisible.
|
||||
indices = indices[: self.total_size]
|
||||
assert len(indices) == self.total_size
|
||||
|
||||
# subsample
|
||||
indices = indices[self.rank : self.total_size : self.num_replicas]
|
||||
assert len(indices) == self.num_samples
|
||||
|
||||
return iter(indices)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return self.num_samples
|
||||
|
||||
def set_epoch(self, epoch: int) -> None:
|
||||
r"""
|
||||
Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas
|
||||
use a different random ordering for each epoch. Otherwise, the next iteration of this
|
||||
sampler will yield the same ordering.
|
||||
|
||||
Args:
|
||||
epoch (int): Epoch number.
|
||||
"""
|
||||
self.epoch = epoch
|
||||
@ -1,81 +0,0 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/data/data_module.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
from pytorch_lightning import LightningDataModule
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
from AR.data.bucket_sampler import DistributedBucketSampler
|
||||
from AR.data.dataset import Text2SemanticDataset
|
||||
|
||||
|
||||
class Text2SemanticDataModule(LightningDataModule):
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
train_semantic_path,
|
||||
train_phoneme_path,
|
||||
dev_semantic_path=None,
|
||||
dev_phoneme_path=None,
|
||||
):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.train_semantic_path = train_semantic_path
|
||||
self.train_phoneme_path = train_phoneme_path
|
||||
self.dev_semantic_path = dev_semantic_path
|
||||
self.dev_phoneme_path = dev_phoneme_path
|
||||
self.num_workers = self.config["data"]["num_workers"]
|
||||
|
||||
def prepare_data(self):
|
||||
pass
|
||||
|
||||
def setup(self, stage=None, output_logs=False):
|
||||
self._train_dataset = Text2SemanticDataset(
|
||||
phoneme_path=self.train_phoneme_path,
|
||||
semantic_path=self.train_semantic_path,
|
||||
max_sec=self.config["data"]["max_sec"],
|
||||
pad_val=self.config["data"]["pad_val"],
|
||||
)
|
||||
self._dev_dataset = self._train_dataset
|
||||
# self._dev_dataset = Text2SemanticDataset(
|
||||
# phoneme_path=self.dev_phoneme_path,
|
||||
# semantic_path=self.dev_semantic_path,
|
||||
# max_sample=self.config['data']['max_eval_sample'],
|
||||
# max_sec=self.config['data']['max_sec'],
|
||||
# pad_val=self.config['data']['pad_val'])
|
||||
|
||||
def train_dataloader(self):
|
||||
batch_size = (
|
||||
self.config["train"]["batch_size"] // 2
|
||||
if self.config["train"].get("if_dpo", False) is True
|
||||
else self.config["train"]["batch_size"]
|
||||
)
|
||||
batch_size = max(min(batch_size, len(self._train_dataset) // 4), 1) # 防止不保存
|
||||
sampler = DistributedBucketSampler(self._train_dataset, batch_size=batch_size)
|
||||
return DataLoader(
|
||||
self._train_dataset,
|
||||
batch_size=batch_size,
|
||||
sampler=sampler,
|
||||
collate_fn=self._train_dataset.collate,
|
||||
num_workers=self.num_workers,
|
||||
persistent_workers=True,
|
||||
prefetch_factor=16,
|
||||
)
|
||||
|
||||
def val_dataloader(self):
|
||||
return DataLoader(
|
||||
self._dev_dataset,
|
||||
batch_size=1,
|
||||
shuffle=False,
|
||||
collate_fn=self._train_dataset.collate,
|
||||
num_workers=max(self.num_workers, 12),
|
||||
persistent_workers=True,
|
||||
prefetch_factor=16,
|
||||
)
|
||||
|
||||
# 这个会使用到嘛?
|
||||
def test_dataloader(self):
|
||||
return DataLoader(
|
||||
self._dev_dataset,
|
||||
batch_size=1,
|
||||
shuffle=False,
|
||||
collate_fn=self._train_dataset.collate,
|
||||
)
|
||||
@ -1,326 +0,0 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/data/dataset.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
|
||||
# sys.path.append("/data/docker/liujing04/gpt-vits/mq-vits-s1bert_no_bert")
|
||||
import os
|
||||
import traceback
|
||||
from typing import Dict, List
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import torch
|
||||
from torch.utils.data import DataLoader, Dataset
|
||||
|
||||
version = os.environ.get("version", None)
|
||||
|
||||
from text import cleaned_text_to_sequence
|
||||
|
||||
# from config import exp_dir
|
||||
|
||||
|
||||
def batch_sequences(sequences: List[np.array], axis: int = 0, pad_value: int = 0):
|
||||
seq = sequences[0]
|
||||
ndim = seq.ndim
|
||||
if axis < 0:
|
||||
axis += ndim
|
||||
dtype = seq.dtype
|
||||
pad_value = dtype.type(pad_value)
|
||||
seq_lengths = [seq.shape[axis] for seq in sequences]
|
||||
max_length = np.max(seq_lengths)
|
||||
|
||||
padded_sequences = []
|
||||
for seq, length in zip(sequences, seq_lengths):
|
||||
padding = [(0, 0)] * axis + [(0, max_length - length)] + [(0, 0)] * (ndim - axis - 1)
|
||||
padded_seq = np.pad(seq, padding, mode="constant", constant_values=pad_value)
|
||||
padded_sequences.append(padded_seq)
|
||||
batch = np.stack(padded_sequences)
|
||||
return batch
|
||||
|
||||
|
||||
class Text2SemanticDataset(Dataset):
|
||||
"""dataset class for text tokens to semantic model training."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
phoneme_path: str,
|
||||
semantic_path: str,
|
||||
max_sample: int = None,
|
||||
max_sec: int = 100,
|
||||
pad_val: int = 1024,
|
||||
# min value of phoneme/sec
|
||||
min_ps_ratio: int = 3,
|
||||
# max value of phoneme/sec
|
||||
max_ps_ratio: int = 25,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
self.semantic_data = pd.read_csv(
|
||||
semantic_path,
|
||||
delimiter="\t",
|
||||
encoding="utf-8",
|
||||
)
|
||||
# get dict
|
||||
self.path2 = phoneme_path # "%s/2-name2text.txt"%exp_dir#phoneme_path
|
||||
self.path3 = "%s/3-bert" % (
|
||||
os.path.dirname(
|
||||
phoneme_path,
|
||||
)
|
||||
) # "%s/3-bert"%exp_dir#bert_dir
|
||||
self.path6 = semantic_path # "%s/6-name2semantic.tsv"%exp_dir#semantic_path
|
||||
if not os.path.exists(self.path2):
|
||||
raise FileNotFoundError(f"Phoneme data file not found: {self.path2}")
|
||||
if not os.path.exists(self.path6):
|
||||
raise FileNotFoundError(f"Semantic data file not found: {self.path6}")
|
||||
self.phoneme_data = {}
|
||||
with open(self.path2, "r", encoding="utf8") as f:
|
||||
lines = f.read().strip("\n").split("\n")
|
||||
|
||||
for line in lines:
|
||||
tmp = line.split("\t")
|
||||
if len(tmp) != 4:
|
||||
continue
|
||||
self.phoneme_data[tmp[0]] = [tmp[1], tmp[2], tmp[3]]
|
||||
|
||||
# self.phoneme_data = np.load(phoneme_path, allow_pickle=True).item()
|
||||
# pad for semantic tokens
|
||||
self.PAD: int = pad_val
|
||||
# self.hz = 25
|
||||
# with open("/data/docker/liujing04/gpt-vits/mq-vits-s1bert_no_bert/configs/s2.json", "r") as f:data = f.read()
|
||||
# data=json.loads(data)["model"]["semantic_frame_rate"]#50hz
|
||||
# self.hz=int(data[:-2])#
|
||||
self.hz = int(os.environ.get("hz", "25hz")[:-2])
|
||||
|
||||
# max seconds of semantic token
|
||||
self.max_sec = max_sec
|
||||
self.min_ps_ratio = min_ps_ratio
|
||||
self.max_ps_ratio = max_ps_ratio
|
||||
|
||||
if max_sample is not None:
|
||||
self.semantic_data = self.semantic_data[:max_sample]
|
||||
|
||||
# {idx: (semantic, phoneme)}
|
||||
# semantic list, phoneme list
|
||||
self.semantic_phoneme = []
|
||||
self.item_names = []
|
||||
|
||||
self.inited = False
|
||||
|
||||
if not self.inited:
|
||||
# 调用初始化函数
|
||||
self.init_batch()
|
||||
self.inited = True
|
||||
del self.semantic_data
|
||||
del self.phoneme_data
|
||||
# self.tokenizer = AutoTokenizer.from_pretrained("hfl/chinese-roberta-wwm-ext-large")
|
||||
# self.tokenizer = AutoTokenizer.from_pretrained("/data/docker/liujing04/bert-vits2/Bert-VITS2-master20231106/bert/chinese-roberta-wwm-ext-large")
|
||||
|
||||
def init_batch(self):
|
||||
semantic_data_len = len(self.semantic_data)
|
||||
phoneme_data_len = len(self.phoneme_data.keys())
|
||||
print("semantic_data_len:", semantic_data_len)
|
||||
print("phoneme_data_len:", phoneme_data_len)
|
||||
print(self.semantic_data)
|
||||
idx = 0
|
||||
num_not_in = 0
|
||||
num_deleted_bigger = 0
|
||||
num_deleted_ps = 0
|
||||
for i in range(semantic_data_len):
|
||||
# 先依次遍历
|
||||
# get str
|
||||
item_name = self.semantic_data.iloc[i, 0]
|
||||
# print(self.phoneme_data)
|
||||
try:
|
||||
phoneme, word2ph, text = self.phoneme_data[item_name]
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
print(f"Warning: File \"{item_name}\" not in self.phoneme_data! Skipped. ")
|
||||
num_not_in += 1
|
||||
continue
|
||||
|
||||
semantic_str = self.semantic_data.iloc[i, 1]
|
||||
# get token list
|
||||
semantic_ids = [int(idx) for idx in semantic_str.split(" ")]
|
||||
# (T), 是否需要变成 (1, T) -> 不需要,因为需要求 len
|
||||
# 过滤掉太长的样本
|
||||
if (
|
||||
len(semantic_ids) > self.max_sec * self.hz
|
||||
): #########1###根据token个数推测总时长过滤时长60s(config里)#40*25=1k
|
||||
num_deleted_bigger += 1
|
||||
continue
|
||||
# (T, ), 这个速度不会很慢,所以可以在一开始就处理,无需在 __getitem__ 里面单个处理####
|
||||
phoneme = phoneme.split(" ")
|
||||
|
||||
try:
|
||||
phoneme_ids = cleaned_text_to_sequence(phoneme, version)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
print(f"Warning: Failed to convert phonemes to sequence for file \"{item_name}\"! Skipped. ")
|
||||
num_not_in += 1
|
||||
continue
|
||||
# if len(phoneme_ids) >400:###########2:改为恒定限制为semantic/2.5就行
|
||||
if len(phoneme_ids) > self.max_sec * self.hz / 2.5: ###########2:改为恒定限制为semantic/2.5就行
|
||||
num_deleted_ps += 1
|
||||
continue
|
||||
# if len(semantic_ids) > 1000:###########3
|
||||
# num_deleted_bigger += 1
|
||||
# continue
|
||||
|
||||
ps_ratio = len(phoneme_ids) / (len(semantic_ids) / self.hz)
|
||||
|
||||
if ps_ratio > self.max_ps_ratio or ps_ratio < self.min_ps_ratio: ##########4#3~25#每秒多少个phone
|
||||
num_deleted_ps += 1
|
||||
# print(item_name)
|
||||
continue
|
||||
|
||||
self.semantic_phoneme.append((semantic_ids, phoneme_ids))
|
||||
idx += 1
|
||||
self.item_names.append(item_name)
|
||||
|
||||
min_num = 100 # 20直接不补#30补了也不存ckpt
|
||||
leng = len(self.semantic_phoneme)
|
||||
if leng < min_num:
|
||||
tmp1 = self.semantic_phoneme
|
||||
tmp2 = self.item_names
|
||||
self.semantic_phoneme = []
|
||||
self.item_names = []
|
||||
for _ in range(max(2, int(min_num / leng))):
|
||||
self.semantic_phoneme += tmp1
|
||||
self.item_names += tmp2
|
||||
if num_not_in > 0:
|
||||
print(f"there are {num_not_in} semantic datas not in phoneme datas")
|
||||
if num_deleted_bigger > 0:
|
||||
print(
|
||||
f"deleted {num_deleted_bigger} audios who's duration are bigger than {self.max_sec} seconds",
|
||||
)
|
||||
if num_deleted_ps > 0:
|
||||
# 4702 for LibriTTS, LirbriTTS 是标注数据, 是否需要筛?=> 需要,有值为 100 的极端值
|
||||
print(
|
||||
f"deleted {num_deleted_ps} audios who's phoneme/sec are bigger than {self.max_ps_ratio} or smaller than {self.min_ps_ratio}",
|
||||
)
|
||||
"""
|
||||
there are 31 semantic datas not in phoneme datas
|
||||
deleted 34 audios who's duration are bigger than 54 seconds
|
||||
deleted 3190 audios who's phoneme/sec are bigger than 25 or smaller than 3
|
||||
dataset.__len__(): 366463
|
||||
|
||||
"""
|
||||
# 345410 for LibriTTS
|
||||
print("dataset.__len__():", self.__len__())
|
||||
|
||||
def __get_item_names__(self) -> List[str]:
|
||||
return self.item_names
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.semantic_phoneme)
|
||||
|
||||
def __getitem__(self, idx: int) -> Dict:
|
||||
semantic_ids, phoneme_ids = self.semantic_phoneme[idx]
|
||||
item_name = self.item_names[idx]
|
||||
phoneme_ids_len = len(phoneme_ids)
|
||||
# semantic tokens target
|
||||
semantic_ids_len = len(semantic_ids)
|
||||
|
||||
flag = 0
|
||||
path_bert = "%s/%s.pt" % (self.path3, item_name)
|
||||
if os.path.exists(path_bert) == True:
|
||||
bert_feature = torch.load(path_bert, map_location="cpu")
|
||||
else:
|
||||
flag = 1
|
||||
if flag == 1:
|
||||
# bert_feature=torch.zeros_like(phoneme_ids,dtype=torch.float32)
|
||||
bert_feature = None
|
||||
else:
|
||||
try:
|
||||
assert bert_feature.shape[-1] == len(phoneme_ids)
|
||||
except AssertionError:
|
||||
print(f"AssertionError: The BERT feature dimension ({bert_feature.shape[-1]}) of the file '{item_name}' does not match the length of the phoneme sequence ({len(phoneme_ids)}).")
|
||||
raise
|
||||
return {
|
||||
"idx": idx,
|
||||
"phoneme_ids": phoneme_ids,
|
||||
"phoneme_ids_len": phoneme_ids_len,
|
||||
"semantic_ids": semantic_ids,
|
||||
"semantic_ids_len": semantic_ids_len,
|
||||
"bert_feature": bert_feature,
|
||||
}
|
||||
|
||||
def get_sample_length(self, idx: int):
|
||||
semantic_ids = self.semantic_phoneme[idx][0]
|
||||
sec = 1.0 * len(semantic_ids) / self.hz
|
||||
return sec
|
||||
|
||||
def collate(self, examples: List[Dict]) -> Dict:
|
||||
sample_index: List[int] = []
|
||||
phoneme_ids: List[torch.Tensor] = []
|
||||
phoneme_ids_lens: List[int] = []
|
||||
semantic_ids: List[torch.Tensor] = []
|
||||
semantic_ids_lens: List[int] = []
|
||||
# return
|
||||
|
||||
for item in examples:
|
||||
sample_index.append(item["idx"])
|
||||
phoneme_ids.append(np.array(item["phoneme_ids"], dtype=np.int64))
|
||||
semantic_ids.append(np.array(item["semantic_ids"], dtype=np.int64))
|
||||
phoneme_ids_lens.append(item["phoneme_ids_len"])
|
||||
semantic_ids_lens.append(item["semantic_ids_len"])
|
||||
|
||||
# pad 0
|
||||
phoneme_ids = batch_sequences(phoneme_ids)
|
||||
semantic_ids = batch_sequences(semantic_ids, pad_value=self.PAD)
|
||||
|
||||
# # convert each batch to torch.tensor
|
||||
phoneme_ids = torch.tensor(phoneme_ids)
|
||||
semantic_ids = torch.tensor(semantic_ids)
|
||||
phoneme_ids_lens = torch.tensor(phoneme_ids_lens)
|
||||
semantic_ids_lens = torch.tensor(semantic_ids_lens)
|
||||
bert_padded = torch.FloatTensor(len(examples), 1024, max(phoneme_ids_lens))
|
||||
bert_padded.zero_()
|
||||
|
||||
for idx, item in enumerate(examples):
|
||||
bert = item["bert_feature"]
|
||||
if bert != None:
|
||||
bert_padded[idx, :, : bert.shape[-1]] = bert
|
||||
|
||||
return {
|
||||
# List[int]
|
||||
"ids": sample_index,
|
||||
# torch.Tensor (B, max_phoneme_length)
|
||||
"phoneme_ids": phoneme_ids,
|
||||
# torch.Tensor (B)
|
||||
"phoneme_ids_len": phoneme_ids_lens,
|
||||
# torch.Tensor (B, max_semantic_ids_length)
|
||||
"semantic_ids": semantic_ids,
|
||||
# torch.Tensor (B)
|
||||
"semantic_ids_len": semantic_ids_lens,
|
||||
# torch.Tensor (B, 1024, max_phoneme_length)
|
||||
"bert_feature": bert_padded,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
root_dir = "/data/docker/liujing04/gpt-vits/prepare/dump_mix/"
|
||||
dataset = Text2SemanticDataset(
|
||||
phoneme_path=root_dir + "phoneme_train.npy",
|
||||
semantic_path=root_dir + "semantic_train.tsv",
|
||||
)
|
||||
|
||||
batch_size = 12
|
||||
dataloader = DataLoader(
|
||||
dataset,
|
||||
batch_size=batch_size,
|
||||
collate_fn=dataset.collate,
|
||||
shuffle=False,
|
||||
)
|
||||
for i, batch in enumerate(dataloader):
|
||||
if i % 1000 == 0:
|
||||
print(i)
|
||||
# if i == 0:
|
||||
# print('batch["ids"]:', batch["ids"])
|
||||
# print('batch["phoneme_ids"]:', batch["phoneme_ids"],
|
||||
# batch["phoneme_ids"].shape)
|
||||
# print('batch["phoneme_ids_len"]:', batch["phoneme_ids_len"],
|
||||
# batch["phoneme_ids_len"].shape)
|
||||
# print('batch["semantic_ids"]:', batch["semantic_ids"],
|
||||
# batch["semantic_ids"].shape)
|
||||
# print('batch["semantic_ids_len"]:', batch["semantic_ids_len"],
|
||||
# batch["semantic_ids_len"].shape)
|
||||
@ -1,6 +0,0 @@
|
||||
from GPT_SoVITS.Accel.PyTorch.AR.t2s_model_abc import (
|
||||
TokenEmbedding,
|
||||
SinePositionalEmbedding,
|
||||
)
|
||||
|
||||
SinePositionalEmbeddingNested = SinePositionalEmbedding
|
||||
@ -1 +0,0 @@
|
||||
from GPT_SoVITS.Accel.PyTorch.AR.structs import T2SRequest, T2SResult, T2SSession
|
||||
13
GPT_SoVITS/AR/models/t2s_inference.py
Normal file
13
GPT_SoVITS/AR/models/t2s_inference.py
Normal file
@ -0,0 +1,13 @@
|
||||
"""Text-to-semantic inference wrapper preserving the checkpoint's ``model`` prefix."""
|
||||
|
||||
from torch import nn
|
||||
|
||||
from AR.models.t2s_model import Text2SemanticDecoder
|
||||
|
||||
|
||||
class Text2SemanticInference(nn.Module):
|
||||
"""Checkpoint-compatible text-to-semantic model used by the TTS service."""
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.model = Text2SemanticDecoder(config=config)
|
||||
@ -1,146 +0,0 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/t2s_lightning_module.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
import os
|
||||
import sys
|
||||
|
||||
now_dir = os.getcwd()
|
||||
sys.path.append(now_dir)
|
||||
from typing import Dict
|
||||
|
||||
import torch
|
||||
from pytorch_lightning import LightningModule
|
||||
|
||||
from AR.models.t2s_model import Text2SemanticDecoder
|
||||
from AR.modules.lr_schedulers import WarmupCosineLRSchedule
|
||||
from AR.modules.optim import ScaledAdam
|
||||
|
||||
|
||||
class Text2SemanticLightningModule(LightningModule):
|
||||
def __init__(self, config, output_dir, is_train=True):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.top_k = 3
|
||||
self.model = Text2SemanticDecoder(config=config, top_k=self.top_k)
|
||||
pretrained_s1 = config.get("pretrained_s1")
|
||||
if pretrained_s1 and is_train:
|
||||
# print(self.load_state_dict(torch.load(pretrained_s1,map_location="cpu")["state_dict"]))
|
||||
print(
|
||||
self.load_state_dict(
|
||||
torch.load(
|
||||
pretrained_s1,
|
||||
map_location="cpu",
|
||||
weights_only=False,
|
||||
)["weight"],
|
||||
)
|
||||
)
|
||||
if is_train:
|
||||
self.automatic_optimization = False
|
||||
self.save_hyperparameters()
|
||||
self.eval_dir = output_dir / "eval"
|
||||
self.eval_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def training_step(self, batch: Dict, batch_idx: int):
|
||||
opt = self.optimizers()
|
||||
scheduler = self.lr_schedulers()
|
||||
forward = self.model.forward if self.config["train"].get("if_dpo", False) == True else self.model.forward_old
|
||||
loss, acc = forward(
|
||||
batch["phoneme_ids"],
|
||||
batch["phoneme_ids_len"],
|
||||
batch["semantic_ids"],
|
||||
batch["semantic_ids_len"],
|
||||
batch["bert_feature"],
|
||||
)
|
||||
self.manual_backward(loss)
|
||||
if batch_idx > 0 and batch_idx % 4 == 0:
|
||||
opt.step()
|
||||
opt.zero_grad()
|
||||
scheduler.step()
|
||||
|
||||
self.log(
|
||||
"total_loss",
|
||||
loss,
|
||||
on_step=True,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
sync_dist=True,
|
||||
)
|
||||
self.log(
|
||||
"lr",
|
||||
scheduler.get_last_lr()[0],
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
sync_dist=True,
|
||||
)
|
||||
self.log(
|
||||
f"top_{self.top_k}_acc",
|
||||
acc,
|
||||
on_step=True,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
sync_dist=True,
|
||||
)
|
||||
|
||||
def validation_step(self, batch: Dict, batch_idx: int):
|
||||
return
|
||||
|
||||
# # get loss
|
||||
# loss, acc = self.model.forward(
|
||||
# batch['phoneme_ids'], batch['phoneme_ids_len'],
|
||||
# batch['semantic_ids'], batch['semantic_ids_len'],
|
||||
# batch['bert_feature']
|
||||
# )
|
||||
#
|
||||
# self.log(
|
||||
# "val_total_loss",
|
||||
# loss,
|
||||
# on_step=True,
|
||||
# on_epoch=True,
|
||||
# prog_bar=True,
|
||||
# sync_dist=True)
|
||||
# self.log(
|
||||
# f"val_top_{self.top_k}_acc",
|
||||
# acc,
|
||||
# on_step=True,
|
||||
# on_epoch=True,
|
||||
# prog_bar=True,
|
||||
# sync_dist=True)
|
||||
#
|
||||
# # get infer output
|
||||
# semantic_len = batch['semantic_ids'].size(1)
|
||||
# prompt_len = min(int(semantic_len * 0.5), 150)
|
||||
# prompt = batch['semantic_ids'][:, :prompt_len]
|
||||
# pred_semantic = self.model.infer(batch['phoneme_ids'],
|
||||
# batch['phoneme_ids_len'], prompt,
|
||||
# batch['bert_feature']
|
||||
# )
|
||||
# save_name = f'semantic_toks_{batch_idx}.pt'
|
||||
# save_path = os.path.join(self.eval_dir, save_name)
|
||||
# torch.save(pred_semantic.detach().cpu(), save_path)
|
||||
|
||||
def configure_optimizers(self):
|
||||
model_parameters = self.model.parameters()
|
||||
parameters_names = []
|
||||
parameters_names.append([name_param_pair[0] for name_param_pair in self.model.named_parameters()])
|
||||
lm_opt = ScaledAdam(
|
||||
model_parameters,
|
||||
lr=0.01,
|
||||
betas=(0.9, 0.95),
|
||||
clipping_scale=2.0,
|
||||
parameters_names=parameters_names,
|
||||
show_dominant_parameters=False,
|
||||
clipping_update_period=1000,
|
||||
)
|
||||
|
||||
return {
|
||||
"optimizer": lm_opt,
|
||||
"lr_scheduler": {
|
||||
"scheduler": WarmupCosineLRSchedule(
|
||||
lm_opt,
|
||||
init_lr=self.config["optimizer"]["lr_init"],
|
||||
peak_lr=self.config["optimizer"]["lr"],
|
||||
end_lr=self.config["optimizer"]["lr_end"],
|
||||
warmup_steps=self.config["optimizer"]["warmup_steps"],
|
||||
total_steps=self.config["optimizer"]["decay_steps"],
|
||||
)
|
||||
},
|
||||
}
|
||||
@ -1,110 +0,0 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/t2s_lightning_module.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
import os
|
||||
import sys
|
||||
|
||||
now_dir = os.getcwd()
|
||||
sys.path.append(now_dir)
|
||||
from typing import Dict
|
||||
|
||||
import torch
|
||||
from pytorch_lightning import LightningModule
|
||||
|
||||
from AR.models.t2s_model_onnx import Text2SemanticDecoder
|
||||
from AR.modules.lr_schedulers import WarmupCosineLRSchedule
|
||||
from AR.modules.optim import ScaledAdam
|
||||
|
||||
|
||||
class Text2SemanticLightningModule(LightningModule):
|
||||
def __init__(self, config, output_dir, is_train=True):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.top_k = 3
|
||||
self.model = Text2SemanticDecoder(config=config, top_k=self.top_k)
|
||||
pretrained_s1 = config.get("pretrained_s1")
|
||||
if pretrained_s1 and is_train:
|
||||
# print(self.load_state_dict(torch.load(pretrained_s1,map_location="cpu")["state_dict"]))
|
||||
print(
|
||||
self.load_state_dict(
|
||||
torch.load(
|
||||
pretrained_s1,
|
||||
map_location="cpu",
|
||||
)["weight"],
|
||||
),
|
||||
)
|
||||
if is_train:
|
||||
self.automatic_optimization = False
|
||||
self.save_hyperparameters()
|
||||
self.eval_dir = output_dir / "eval"
|
||||
self.eval_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def training_step(self, batch: Dict, batch_idx: int):
|
||||
opt = self.optimizers()
|
||||
scheduler = self.lr_schedulers()
|
||||
loss, acc = self.model.forward(
|
||||
batch["phoneme_ids"],
|
||||
batch["phoneme_ids_len"],
|
||||
batch["semantic_ids"],
|
||||
batch["semantic_ids_len"],
|
||||
batch["bert_feature"],
|
||||
)
|
||||
self.manual_backward(loss)
|
||||
if batch_idx > 0 and batch_idx % 4 == 0:
|
||||
opt.step()
|
||||
opt.zero_grad()
|
||||
scheduler.step()
|
||||
|
||||
self.log(
|
||||
"total_loss",
|
||||
loss,
|
||||
on_step=True,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
sync_dist=True,
|
||||
)
|
||||
self.log(
|
||||
"lr",
|
||||
scheduler.get_last_lr()[0],
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
sync_dist=True,
|
||||
)
|
||||
self.log(
|
||||
f"top_{self.top_k}_acc",
|
||||
acc,
|
||||
on_step=True,
|
||||
on_epoch=True,
|
||||
prog_bar=True,
|
||||
sync_dist=True,
|
||||
)
|
||||
|
||||
def validation_step(self, batch: Dict, batch_idx: int):
|
||||
return
|
||||
|
||||
def configure_optimizers(self):
|
||||
model_parameters = self.model.parameters()
|
||||
parameters_names = []
|
||||
parameters_names.append([name_param_pair[0] for name_param_pair in self.model.named_parameters()])
|
||||
lm_opt = ScaledAdam(
|
||||
model_parameters,
|
||||
lr=0.01,
|
||||
betas=(0.9, 0.95),
|
||||
clipping_scale=2.0,
|
||||
parameters_names=parameters_names,
|
||||
show_dominant_parameters=False,
|
||||
clipping_update_period=1000,
|
||||
)
|
||||
|
||||
return {
|
||||
"optimizer": lm_opt,
|
||||
"lr_scheduler": {
|
||||
"scheduler": WarmupCosineLRSchedule(
|
||||
lm_opt,
|
||||
init_lr=self.config["optimizer"]["lr_init"],
|
||||
peak_lr=self.config["optimizer"]["lr"],
|
||||
end_lr=self.config["optimizer"]["lr_end"],
|
||||
warmup_steps=self.config["optimizer"]["warmup_steps"],
|
||||
total_steps=self.config["optimizer"]["decay_steps"],
|
||||
)
|
||||
},
|
||||
}
|
||||
@ -6,34 +6,16 @@ from typing import List, Optional
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.nn import functional as F
|
||||
from torchmetrics.classification import MulticlassAccuracy
|
||||
from tqdm import tqdm
|
||||
|
||||
from AR.models.utils import (
|
||||
dpo_loss,
|
||||
get_batch_logps,
|
||||
make_pad_mask,
|
||||
make_pad_mask_left,
|
||||
make_reject_y,
|
||||
sample,
|
||||
topk_sampling,
|
||||
)
|
||||
from AR.modules.embedding import SinePositionalEmbedding, TokenEmbedding
|
||||
from AR.modules.transformer import LayerNorm, TransformerEncoder, TransformerEncoderLayer
|
||||
|
||||
default_config = {
|
||||
"embedding_dim": 512,
|
||||
"hidden_dim": 512,
|
||||
"num_head": 8,
|
||||
"num_layers": 12,
|
||||
"num_codebook": 8,
|
||||
"p_dropout": 0.0,
|
||||
"vocab_size": 1024 + 1,
|
||||
"phoneme_vocab_size": 512,
|
||||
"EOS": 1024,
|
||||
}
|
||||
|
||||
|
||||
# @torch.jit.script ## 使用的话首次推理会非常慢,而且推理速度不稳定
|
||||
# Efficient implementation equivalent to the following:
|
||||
def scaled_dot_product_attention(
|
||||
@ -258,7 +240,7 @@ class T2STransformer:
|
||||
|
||||
|
||||
class Text2SemanticDecoder(nn.Module):
|
||||
def __init__(self, config, norm_first=False, top_k=3):
|
||||
def __init__(self, config, norm_first=False):
|
||||
super(Text2SemanticDecoder, self).__init__()
|
||||
self.model_dim = config["model"]["hidden_dim"]
|
||||
self.embedding_dim = config["model"]["embedding_dim"]
|
||||
@ -267,7 +249,6 @@ class Text2SemanticDecoder(nn.Module):
|
||||
self.norm_first = norm_first
|
||||
self.vocab_size = config["model"]["vocab_size"]
|
||||
self.phoneme_vocab_size = config["model"]["phoneme_vocab_size"]
|
||||
self.p_dropout = config["model"]["dropout"]
|
||||
self.EOS = config["model"]["EOS"]
|
||||
self.norm_first = norm_first
|
||||
assert self.EOS == self.vocab_size - 1
|
||||
@ -277,22 +258,18 @@ class Text2SemanticDecoder(nn.Module):
|
||||
self.ar_text_embedding = TokenEmbedding(
|
||||
self.embedding_dim,
|
||||
self.phoneme_vocab_size,
|
||||
self.p_dropout,
|
||||
)
|
||||
self.ar_text_position = SinePositionalEmbedding(
|
||||
self.embedding_dim,
|
||||
dropout=0.1,
|
||||
scale=False,
|
||||
alpha=True,
|
||||
)
|
||||
self.ar_audio_embedding = TokenEmbedding(
|
||||
self.embedding_dim,
|
||||
self.vocab_size,
|
||||
self.p_dropout,
|
||||
)
|
||||
self.ar_audio_position = SinePositionalEmbedding(
|
||||
self.embedding_dim,
|
||||
dropout=0.1,
|
||||
scale=False,
|
||||
alpha=True,
|
||||
)
|
||||
@ -302,7 +279,6 @@ class Text2SemanticDecoder(nn.Module):
|
||||
d_model=self.model_dim,
|
||||
nhead=self.num_head,
|
||||
dim_feedforward=self.model_dim * 4,
|
||||
dropout=0.1,
|
||||
batch_first=True,
|
||||
norm_first=norm_first,
|
||||
),
|
||||
@ -311,16 +287,6 @@ class Text2SemanticDecoder(nn.Module):
|
||||
)
|
||||
|
||||
self.ar_predict_layer = nn.Linear(self.model_dim, self.vocab_size, bias=False)
|
||||
self.loss_fct = nn.CrossEntropyLoss(reduction="sum")
|
||||
|
||||
self.ar_accuracy_metric = MulticlassAccuracy(
|
||||
self.vocab_size,
|
||||
top_k=top_k,
|
||||
average="micro",
|
||||
multidim_average="global",
|
||||
ignore_index=self.EOS,
|
||||
)
|
||||
|
||||
blocks = []
|
||||
|
||||
for i in range(self.num_layers):
|
||||
@ -352,163 +318,6 @@ class Text2SemanticDecoder(nn.Module):
|
||||
|
||||
self.t2s_transformer = T2STransformer(self.num_layers, blocks)
|
||||
|
||||
def make_input_data(self, x, x_lens, y, y_lens, bert_feature):
|
||||
x = self.ar_text_embedding(x)
|
||||
x = x + self.bert_proj(bert_feature.transpose(1, 2))
|
||||
x = self.ar_text_position(x)
|
||||
x_mask = make_pad_mask_left(x_lens)
|
||||
|
||||
y_mask = make_pad_mask(y_lens)
|
||||
y_mask_int = y_mask.type(torch.int64)
|
||||
codes = y.type(torch.int64) * (1 - y_mask_int)
|
||||
|
||||
# Training
|
||||
# AR Decoder
|
||||
y, targets = self.pad_y_eos(codes, y_mask_int, eos_id=self.EOS)
|
||||
x_len = x_lens.max()
|
||||
y_len = y_lens.max()
|
||||
y_emb = self.ar_audio_embedding(y)
|
||||
y_pos = self.ar_audio_position(y_emb)
|
||||
|
||||
xy_padding_mask = torch.concat([x_mask, y_mask], dim=1)
|
||||
|
||||
ar_xy_padding_mask = xy_padding_mask
|
||||
|
||||
x_attn_mask = F.pad(
|
||||
torch.zeros((x_len, x_len), dtype=torch.bool, device=x.device),
|
||||
(0, y_len),
|
||||
value=True,
|
||||
)
|
||||
# x_attn_mask[:, x_len]=False
|
||||
y_attn_mask = F.pad(
|
||||
torch.triu(
|
||||
torch.ones(y_len, y_len, dtype=torch.bool, device=x.device),
|
||||
diagonal=1,
|
||||
),
|
||||
(x_len, 0),
|
||||
value=False,
|
||||
)
|
||||
|
||||
xy_attn_mask = torch.concat([x_attn_mask, y_attn_mask], dim=0)
|
||||
bsz, src_len = x.shape[0], x_len + y_len
|
||||
_xy_padding_mask = (
|
||||
ar_xy_padding_mask.view(bsz, 1, 1, src_len)
|
||||
.expand(-1, self.num_head, -1, -1)
|
||||
.reshape(bsz * self.num_head, 1, src_len)
|
||||
)
|
||||
xy_attn_mask = xy_attn_mask.logical_or(_xy_padding_mask)
|
||||
new_attn_mask = torch.zeros_like(xy_attn_mask, dtype=x.dtype)
|
||||
new_attn_mask.masked_fill_(xy_attn_mask, float("-inf"))
|
||||
xy_attn_mask = new_attn_mask
|
||||
# x 和完整的 y 一次性输入模型
|
||||
xy_pos = torch.concat([x, y_pos], dim=1)
|
||||
|
||||
return xy_pos, xy_attn_mask, targets
|
||||
|
||||
def forward(self, x, x_lens, y, y_lens, bert_feature):
|
||||
"""
|
||||
x: phoneme_ids
|
||||
y: semantic_ids
|
||||
"""
|
||||
|
||||
reject_y, reject_y_lens = make_reject_y(y, y_lens)
|
||||
|
||||
xy_pos, xy_attn_mask, targets = self.make_input_data(x, x_lens, y, y_lens, bert_feature)
|
||||
|
||||
xy_dec, _ = self.h(
|
||||
(xy_pos, None),
|
||||
mask=xy_attn_mask,
|
||||
)
|
||||
x_len = x_lens.max()
|
||||
logits = self.ar_predict_layer(xy_dec[:, x_len-1:])
|
||||
|
||||
###### DPO #############
|
||||
reject_xy_pos, reject_xy_attn_mask, reject_targets = self.make_input_data(
|
||||
x, x_lens, reject_y, reject_y_lens, bert_feature
|
||||
)
|
||||
|
||||
reject_xy_dec, _ = self.h(
|
||||
(reject_xy_pos, None),
|
||||
mask=reject_xy_attn_mask,
|
||||
)
|
||||
x_len = x_lens.max()
|
||||
reject_logits = self.ar_predict_layer(reject_xy_dec[:, x_len-1:])
|
||||
|
||||
# loss
|
||||
# from feiteng: 每次 duration 越多, 梯度更新也应该更多, 所以用 sum
|
||||
|
||||
loss_1 = F.cross_entropy(logits.permute(0, 2, 1), targets, reduction="sum")
|
||||
acc = self.ar_accuracy_metric(logits.permute(0, 2, 1).detach(), targets).item()
|
||||
|
||||
A_logits, R_logits = get_batch_logps(logits, reject_logits, targets, reject_targets)
|
||||
loss_2, _, _ = dpo_loss(A_logits, R_logits, 0, 0, 0.2, reference_free=True)
|
||||
|
||||
loss = loss_1 + loss_2
|
||||
|
||||
return loss, acc
|
||||
|
||||
def forward_old(self, x, x_lens, y, y_lens, bert_feature):
|
||||
"""
|
||||
x: phoneme_ids
|
||||
y: semantic_ids
|
||||
"""
|
||||
x = self.ar_text_embedding(x)
|
||||
x = x + self.bert_proj(bert_feature.transpose(1, 2))
|
||||
x = self.ar_text_position(x)
|
||||
x_mask = make_pad_mask_left(x_lens)
|
||||
|
||||
y_mask = make_pad_mask(y_lens)
|
||||
y_mask_int = y_mask.type(torch.int64)
|
||||
codes = y.type(torch.int64) * (1 - y_mask_int)
|
||||
|
||||
# Training
|
||||
# AR Decoder
|
||||
y, targets = self.pad_y_eos(codes, y_mask_int, eos_id=self.EOS)
|
||||
x_len = x_lens.max()
|
||||
y_len = y_lens.max()
|
||||
y_emb = self.ar_audio_embedding(y)
|
||||
y_pos = self.ar_audio_position(y_emb)
|
||||
|
||||
xy_padding_mask = torch.concat([x_mask, y_mask], dim=1)
|
||||
ar_xy_padding_mask = xy_padding_mask
|
||||
|
||||
x_attn_mask = F.pad(
|
||||
torch.zeros((x_len, x_len), dtype=torch.bool, device=x.device),
|
||||
(0, y_len),
|
||||
value=True,
|
||||
)
|
||||
y_attn_mask = F.pad(
|
||||
torch.triu(
|
||||
torch.ones(y_len, y_len, dtype=torch.bool, device=x.device),
|
||||
diagonal=1,
|
||||
),
|
||||
(x_len, 0),
|
||||
value=False,
|
||||
)
|
||||
xy_attn_mask = torch.concat([x_attn_mask, y_attn_mask], dim=0)
|
||||
bsz, src_len = x.shape[0], x_len + y_len
|
||||
_xy_padding_mask = (
|
||||
ar_xy_padding_mask.view(bsz, 1, 1, src_len)
|
||||
.expand(-1, self.num_head, -1, -1)
|
||||
.reshape(bsz * self.num_head, 1, src_len)
|
||||
)
|
||||
xy_attn_mask = xy_attn_mask.logical_or(_xy_padding_mask)
|
||||
new_attn_mask = torch.zeros_like(xy_attn_mask, dtype=x.dtype)
|
||||
new_attn_mask.masked_fill_(xy_attn_mask, float("-inf"))
|
||||
xy_attn_mask = new_attn_mask
|
||||
# x 和完整的 y 一次性输入模型
|
||||
xy_pos = torch.concat([x, y_pos], dim=1)
|
||||
xy_dec, _ = self.h(
|
||||
(xy_pos, None),
|
||||
mask=xy_attn_mask,
|
||||
)
|
||||
logits = self.ar_predict_layer(xy_dec[:, x_len-1:]).permute(0, 2, 1)
|
||||
# loss
|
||||
# from feiteng: 每次 duration 越多, 梯度更新也应该更多, 所以用 sum
|
||||
loss = F.cross_entropy(logits, targets, reduction="sum")
|
||||
acc = self.ar_accuracy_metric(logits.detach(), targets).item()
|
||||
return loss, acc
|
||||
|
||||
# 需要看下这个函数和 forward 的区别以及没有 semantic 的时候 prompts 输入什么
|
||||
def infer(
|
||||
self,
|
||||
@ -575,11 +384,6 @@ class Text2SemanticDecoder(nn.Module):
|
||||
y = torch.concat([y, samples], dim=1)
|
||||
return y
|
||||
|
||||
def pad_y_eos(self, y, y_mask_int, eos_id):
|
||||
targets = F.pad(y, (0, 1), value=0) + eos_id * F.pad(y_mask_int, (0, 1), value=1)
|
||||
# 错位
|
||||
return targets[:, :-1], targets
|
||||
|
||||
def infer_panel_batch_infer(
|
||||
self,
|
||||
x: List[torch.LongTensor], #####全部文本token
|
||||
|
||||
@ -1,8 +0,0 @@
|
||||
from GPT_SoVITS.Accel import T2SRequest, T2SResult
|
||||
from GPT_SoVITS.Accel.PyTorch.AR.t2s_engine import T2SEngine as CUDAGraphRunner
|
||||
from GPT_SoVITS.Accel.PyTorch.AR.backends.flash_attn_varlen_cuda_graph import (
|
||||
Attention,
|
||||
T2SDecoder,
|
||||
TransformerBlock,
|
||||
TransformerDecoder,
|
||||
)
|
||||
@ -1,394 +0,0 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/t2s_model.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.nn import functional as F
|
||||
from torchmetrics.classification import MulticlassAccuracy
|
||||
|
||||
from AR.modules.embedding_onnx import SinePositionalEmbedding, TokenEmbedding
|
||||
from AR.modules.transformer_onnx import LayerNorm, TransformerEncoder, TransformerEncoderLayer
|
||||
|
||||
default_config = {
|
||||
"embedding_dim": 512,
|
||||
"hidden_dim": 512,
|
||||
"num_head": 8,
|
||||
"num_layers": 12,
|
||||
"num_codebook": 8,
|
||||
"p_dropout": 0.0,
|
||||
"vocab_size": 1024 + 1,
|
||||
"phoneme_vocab_size": 512,
|
||||
"EOS": 1024,
|
||||
}
|
||||
|
||||
inf_tensor_value = torch.FloatTensor([-float("Inf")]).float()
|
||||
|
||||
|
||||
def logits_to_probs(
|
||||
logits,
|
||||
previous_tokens=None,
|
||||
temperature: float = 1.0,
|
||||
top_k=None,
|
||||
top_p=None,
|
||||
repetition_penalty: float = 1.0,
|
||||
):
|
||||
previous_tokens = previous_tokens.squeeze()
|
||||
if previous_tokens is not None and repetition_penalty != 1.0:
|
||||
previous_tokens = previous_tokens.long()
|
||||
score = torch.gather(logits, dim=0, index=previous_tokens)
|
||||
score = torch.where(
|
||||
score < 0,
|
||||
score * repetition_penalty,
|
||||
score / repetition_penalty,
|
||||
)
|
||||
logits.scatter_(dim=0, index=previous_tokens, src=score)
|
||||
|
||||
if top_p is not None and top_p < 1.0:
|
||||
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
||||
cum_probs = torch.cumsum(
|
||||
torch.nn.functional.softmax(
|
||||
sorted_logits,
|
||||
dim=-1,
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
sorted_indices_to_remove = cum_probs > top_p
|
||||
sorted_indices_to_remove[0] = False # keep at least one option
|
||||
indices_to_remove = sorted_indices_to_remove.scatter(
|
||||
dim=0,
|
||||
index=sorted_indices,
|
||||
src=sorted_indices_to_remove,
|
||||
)
|
||||
logits = logits.masked_fill(indices_to_remove, -float("Inf"))
|
||||
|
||||
logits = logits / max(temperature, 1e-5)
|
||||
|
||||
if top_k is not None:
|
||||
v, _ = torch.topk(logits, top_k)
|
||||
pivot = v.select(-1, -1).unsqueeze(-1)
|
||||
logits = torch.where(logits < pivot, inf_tensor_value, logits)
|
||||
|
||||
probs = torch.nn.functional.softmax(logits, dim=-1)
|
||||
return probs
|
||||
|
||||
|
||||
def multinomial_sample_one_no_sync(
|
||||
probs_sort,
|
||||
): # Does multinomial sampling without a cuda synchronization
|
||||
q = torch.randn_like(probs_sort)
|
||||
return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int)
|
||||
|
||||
|
||||
def sample(
|
||||
logits,
|
||||
previous_tokens,
|
||||
**sampling_kwargs,
|
||||
):
|
||||
probs = logits_to_probs(
|
||||
logits=logits,
|
||||
previous_tokens=previous_tokens,
|
||||
**sampling_kwargs,
|
||||
)
|
||||
idx_next = multinomial_sample_one_no_sync(probs)
|
||||
return idx_next, probs
|
||||
|
||||
|
||||
class OnnxEncoder(nn.Module):
|
||||
def __init__(self, ar_text_embedding, bert_proj, ar_text_position):
|
||||
super().__init__()
|
||||
self.ar_text_embedding = ar_text_embedding
|
||||
self.bert_proj = bert_proj
|
||||
self.ar_text_position = ar_text_position
|
||||
|
||||
def forward(self, x, bert_feature):
|
||||
x = self.ar_text_embedding(x)
|
||||
x = x + self.bert_proj(bert_feature.transpose(1, 2))
|
||||
return self.ar_text_position(x)
|
||||
|
||||
|
||||
class T2SFirstStageDecoder(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
ar_audio_embedding,
|
||||
ar_audio_position,
|
||||
h,
|
||||
ar_predict_layer,
|
||||
loss_fct,
|
||||
ar_accuracy_metric,
|
||||
top_k,
|
||||
early_stop_num,
|
||||
num_layers,
|
||||
):
|
||||
super().__init__()
|
||||
self.ar_audio_embedding = ar_audio_embedding
|
||||
self.ar_audio_position = ar_audio_position
|
||||
self.h = h
|
||||
self.ar_predict_layer = ar_predict_layer
|
||||
self.loss_fct = loss_fct
|
||||
self.ar_accuracy_metric = ar_accuracy_metric
|
||||
self.top_k = top_k
|
||||
self.early_stop_num = early_stop_num
|
||||
self.num_layers = num_layers
|
||||
|
||||
def forward(self, x, prompt):
|
||||
y = prompt
|
||||
x_example = x[:, :, 0] * 0.0
|
||||
# N, 1, 512
|
||||
cache = {
|
||||
"all_stage": self.num_layers,
|
||||
"k": None,
|
||||
"v": None,
|
||||
"y_emb": None,
|
||||
"first_infer": 1,
|
||||
"stage": 0,
|
||||
}
|
||||
|
||||
y_emb = self.ar_audio_embedding(y)
|
||||
|
||||
cache["y_emb"] = y_emb
|
||||
y_pos = self.ar_audio_position(y_emb)
|
||||
|
||||
xy_pos = torch.concat([x, y_pos], dim=1)
|
||||
|
||||
y_example = y_pos[:, :, 0] * 0.0
|
||||
x_attn_mask = torch.matmul(x_example.transpose(0, 1), x_example).bool()
|
||||
y_attn_mask = torch.ones_like(torch.matmul(y_example.transpose(0, 1), y_example), dtype=torch.int64)
|
||||
y_attn_mask = torch.cumsum(y_attn_mask, dim=1) - torch.cumsum(
|
||||
torch.ones_like(
|
||||
y_example.transpose(0, 1),
|
||||
dtype=torch.int64,
|
||||
),
|
||||
dim=0,
|
||||
)
|
||||
y_attn_mask = y_attn_mask > 0
|
||||
|
||||
x_y_pad = torch.matmul(x_example.transpose(0, 1), y_example).bool()
|
||||
y_x_pad = torch.matmul(y_example.transpose(0, 1), x_example).bool()
|
||||
x_attn_mask_pad = torch.cat([x_attn_mask, torch.ones_like(x_y_pad)], dim=1)
|
||||
y_attn_mask = torch.cat([y_x_pad, y_attn_mask], dim=1)
|
||||
xy_attn_mask = torch.concat([x_attn_mask_pad, y_attn_mask], dim=0)
|
||||
cache["k"] = (
|
||||
torch.matmul(x_attn_mask_pad[0].float().unsqueeze(-1), torch.zeros((1, 512)))
|
||||
.unsqueeze(1)
|
||||
.repeat(self.num_layers, 1, 1, 1)
|
||||
)
|
||||
cache["v"] = (
|
||||
torch.matmul(x_attn_mask_pad[0].float().unsqueeze(-1), torch.zeros((1, 512)))
|
||||
.unsqueeze(1)
|
||||
.repeat(self.num_layers, 1, 1, 1)
|
||||
)
|
||||
|
||||
xy_dec = self.h(xy_pos, mask=xy_attn_mask, cache=cache)
|
||||
logits = self.ar_predict_layer(xy_dec[:, -1])
|
||||
samples = sample(logits[0], y, top_k=self.top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
|
||||
|
||||
y = torch.concat([y, samples], dim=1)
|
||||
|
||||
return y, cache["k"], cache["v"], cache["y_emb"], x_example
|
||||
|
||||
|
||||
class T2SStageDecoder(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
ar_audio_embedding,
|
||||
ar_audio_position,
|
||||
h,
|
||||
ar_predict_layer,
|
||||
loss_fct,
|
||||
ar_accuracy_metric,
|
||||
top_k,
|
||||
early_stop_num,
|
||||
num_layers,
|
||||
):
|
||||
super().__init__()
|
||||
self.ar_audio_embedding = ar_audio_embedding
|
||||
self.ar_audio_position = ar_audio_position
|
||||
self.h = h
|
||||
self.ar_predict_layer = ar_predict_layer
|
||||
self.loss_fct = loss_fct
|
||||
self.ar_accuracy_metric = ar_accuracy_metric
|
||||
self.top_k = top_k
|
||||
self.early_stop_num = early_stop_num
|
||||
self.num_layers = num_layers
|
||||
|
||||
def forward(self, y, k, v, y_emb, x_example):
|
||||
cache = {
|
||||
"all_stage": self.num_layers,
|
||||
"k": torch.nn.functional.pad(k, (0, 0, 0, 0, 0, 1)),
|
||||
"v": torch.nn.functional.pad(v, (0, 0, 0, 0, 0, 1)),
|
||||
"y_emb": y_emb,
|
||||
"first_infer": 0,
|
||||
"stage": 0,
|
||||
}
|
||||
|
||||
y_emb = torch.cat(
|
||||
[
|
||||
cache["y_emb"],
|
||||
self.ar_audio_embedding(y[:, -1:]),
|
||||
],
|
||||
1,
|
||||
)
|
||||
cache["y_emb"] = y_emb
|
||||
y_pos = self.ar_audio_position(y_emb)
|
||||
|
||||
xy_pos = y_pos[:, -1:]
|
||||
|
||||
y_example = y_pos[:, :, 0] * 0.0
|
||||
|
||||
xy_attn_mask = torch.cat([x_example, y_example], dim=1)
|
||||
xy_attn_mask = torch.zeros_like(xy_attn_mask, dtype=torch.bool)
|
||||
|
||||
xy_dec = self.h(xy_pos, mask=xy_attn_mask, cache=cache)
|
||||
logits = self.ar_predict_layer(xy_dec[:, -1])
|
||||
samples = sample(logits[0], y, top_k=self.top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
|
||||
|
||||
y = torch.concat([y, samples], dim=1)
|
||||
|
||||
return y, cache["k"], cache["v"], cache["y_emb"], logits, samples
|
||||
|
||||
|
||||
class Text2SemanticDecoder(nn.Module):
|
||||
def __init__(self, config, norm_first=False, top_k=3):
|
||||
super(Text2SemanticDecoder, self).__init__()
|
||||
self.model_dim = config["model"]["hidden_dim"]
|
||||
self.embedding_dim = config["model"]["embedding_dim"]
|
||||
self.num_head = config["model"]["head"]
|
||||
self.num_layers = config["model"]["n_layer"]
|
||||
self.norm_first = norm_first
|
||||
self.vocab_size = config["model"]["vocab_size"]
|
||||
self.phoneme_vocab_size = config["model"]["phoneme_vocab_size"]
|
||||
self.p_dropout = float(config["model"]["dropout"])
|
||||
self.EOS = config["model"]["EOS"]
|
||||
self.norm_first = norm_first
|
||||
assert self.EOS == self.vocab_size - 1
|
||||
self.bert_proj = nn.Linear(1024, self.embedding_dim)
|
||||
self.ar_text_embedding = TokenEmbedding(self.embedding_dim, self.phoneme_vocab_size, self.p_dropout)
|
||||
self.ar_text_position = SinePositionalEmbedding(self.embedding_dim, dropout=0.1, scale=False, alpha=True)
|
||||
self.ar_audio_embedding = TokenEmbedding(self.embedding_dim, self.vocab_size, self.p_dropout)
|
||||
self.ar_audio_position = SinePositionalEmbedding(self.embedding_dim, dropout=0.1, scale=False, alpha=True)
|
||||
self.h = TransformerEncoder(
|
||||
TransformerEncoderLayer(
|
||||
d_model=self.model_dim,
|
||||
nhead=self.num_head,
|
||||
dim_feedforward=self.model_dim * 4,
|
||||
dropout=0.1,
|
||||
batch_first=True,
|
||||
norm_first=norm_first,
|
||||
),
|
||||
num_layers=self.num_layers,
|
||||
norm=LayerNorm(self.model_dim) if norm_first else None,
|
||||
)
|
||||
self.ar_predict_layer = nn.Linear(self.model_dim, self.vocab_size, bias=False)
|
||||
self.loss_fct = nn.CrossEntropyLoss(reduction="sum")
|
||||
self.ar_accuracy_metric = MulticlassAccuracy(
|
||||
self.vocab_size,
|
||||
top_k=top_k,
|
||||
average="micro",
|
||||
multidim_average="global",
|
||||
ignore_index=self.EOS,
|
||||
)
|
||||
self.top_k = torch.LongTensor([1])
|
||||
self.early_stop_num = torch.LongTensor([-1])
|
||||
|
||||
def init_onnx(self):
|
||||
self.onnx_encoder = OnnxEncoder(self.ar_text_embedding, self.bert_proj, self.ar_text_position)
|
||||
self.first_stage_decoder = T2SFirstStageDecoder(
|
||||
self.ar_audio_embedding,
|
||||
self.ar_audio_position,
|
||||
self.h,
|
||||
self.ar_predict_layer,
|
||||
self.loss_fct,
|
||||
self.ar_accuracy_metric,
|
||||
self.top_k,
|
||||
self.early_stop_num,
|
||||
self.num_layers,
|
||||
)
|
||||
self.stage_decoder = T2SStageDecoder(
|
||||
self.ar_audio_embedding,
|
||||
self.ar_audio_position,
|
||||
self.h,
|
||||
self.ar_predict_layer,
|
||||
self.loss_fct,
|
||||
self.ar_accuracy_metric,
|
||||
self.top_k,
|
||||
self.early_stop_num,
|
||||
self.num_layers,
|
||||
)
|
||||
|
||||
def forward(self, x, prompts, bert_feature):
|
||||
early_stop_num = self.early_stop_num
|
||||
prefix_len = prompts.shape[1]
|
||||
|
||||
x = self.onnx_encoder(x, bert_feature)
|
||||
y, k, v, y_emb, stage, x_example = self.first_stage_decoder(x, prompts)
|
||||
|
||||
stop = False
|
||||
for idx in range(1, 1500):
|
||||
enco = self.stage_decoder(y, k, v, y_emb, stage, x_example)
|
||||
y, k, v, y_emb, stage, logits, samples = enco
|
||||
if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
|
||||
stop = True
|
||||
if torch.argmax(logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
|
||||
stop = True
|
||||
if stop:
|
||||
break
|
||||
y[0, -1] = 0
|
||||
return y, idx
|
||||
|
||||
def infer(self, x, prompts, bert_feature):
|
||||
top_k = self.top_k
|
||||
early_stop_num = self.early_stop_num
|
||||
|
||||
x = self.onnx_encoder(x, bert_feature)
|
||||
|
||||
y = prompts
|
||||
prefix_len = y.shape[1]
|
||||
x_len = x.shape[1]
|
||||
x_example = x[:, :, 0] * 0.0
|
||||
x_attn_mask = torch.matmul(x_example.transpose(0, 1), x_example)
|
||||
x_attn_mask = torch.zeros_like(x_attn_mask, dtype=torch.bool)
|
||||
|
||||
stop = False
|
||||
cache = {
|
||||
"all_stage": self.num_layers,
|
||||
"k": [None] * self.num_layers,
|
||||
"v": [None] * self.num_layers,
|
||||
"y_emb": None,
|
||||
"first_infer": 1,
|
||||
"stage": 0,
|
||||
}
|
||||
for idx in range(1500):
|
||||
if cache["first_infer"] == 1:
|
||||
y_emb = self.ar_audio_embedding(y)
|
||||
else:
|
||||
y_emb = torch.cat([cache["y_emb"], self.ar_audio_embedding(y[:, -1:])], 1)
|
||||
cache["y_emb"] = y_emb
|
||||
y_pos = self.ar_audio_position(y_emb)
|
||||
if cache["first_infer"] == 1:
|
||||
xy_pos = torch.concat([x, y_pos], dim=1)
|
||||
else:
|
||||
xy_pos = y_pos[:, -1:]
|
||||
y_len = y_pos.shape[1]
|
||||
if cache["first_infer"] == 1:
|
||||
x_attn_mask_pad = F.pad(x_attn_mask, (0, y_len), value=True)
|
||||
y_attn_mask = F.pad(
|
||||
torch.triu(torch.ones(y_len, y_len, dtype=torch.bool), diagonal=1),
|
||||
(x_len, 0),
|
||||
value=False,
|
||||
)
|
||||
xy_attn_mask = torch.concat([x_attn_mask_pad, y_attn_mask], dim=0)
|
||||
else:
|
||||
xy_attn_mask = torch.zeros((1, x_len + y_len), dtype=torch.bool)
|
||||
xy_dec = self.h(xy_pos, mask=xy_attn_mask, cache=cache)
|
||||
logits = self.ar_predict_layer(xy_dec[:, -1])
|
||||
samples = sample(logits[0], y, top_k=top_k, top_p=1.0, repetition_penalty=1.35)[0].unsqueeze(0)
|
||||
if early_stop_num != -1 and (y.shape[1] - prefix_len) > early_stop_num:
|
||||
stop = True
|
||||
if torch.argmax(logits, dim=-1)[0] == self.EOS or samples[0, 0] == self.EOS:
|
||||
stop = True
|
||||
if stop:
|
||||
if prompts.shape[1] == y.shape[1]:
|
||||
y = torch.concat([y, torch.zeros_like(samples)], dim=1)
|
||||
break
|
||||
y = torch.concat([y, samples], dim=1)
|
||||
cache["first_infer"] = 0
|
||||
return y, idx
|
||||
@ -1,46 +1,11 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/utils.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
from typing import Tuple
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
def sequence_mask(length, max_length=None):
|
||||
if max_length is None:
|
||||
max_length = length.max()
|
||||
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
|
||||
return x.unsqueeze(0) < length.unsqueeze(1)
|
||||
|
||||
|
||||
def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
|
||||
"""
|
||||
Args:
|
||||
lengths:
|
||||
A 1-D tensor containing sentence lengths.
|
||||
max_len:
|
||||
The length of masks.
|
||||
Returns:
|
||||
Return a 2-D bool tensor, where masked positions
|
||||
are filled with `True` and non-masked positions are
|
||||
filled with `False`.
|
||||
|
||||
#>>> lengths = torch.tensor([1, 3, 2, 5])
|
||||
#>>> make_pad_mask(lengths)
|
||||
tensor([[False, True, True, True, True],
|
||||
[False, False, False, True, True],
|
||||
[False, False, True, True, True],
|
||||
[False, False, False, False, False]])
|
||||
"""
|
||||
assert lengths.ndim == 1, lengths.ndim
|
||||
max_len = max(max_len, lengths.max())
|
||||
n = lengths.size(0)
|
||||
seq_range = torch.arange(0, max_len, device=lengths.device)
|
||||
expaned_lengths = seq_range.unsqueeze(0).expand(n, max_len)
|
||||
|
||||
return expaned_lengths >= lengths.unsqueeze(-1)
|
||||
|
||||
|
||||
def make_pad_mask_left(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
|
||||
"""
|
||||
Args:
|
||||
@ -134,8 +99,6 @@ def topk_sampling(logits, top_k=10, top_p=1.0, temperature=1.0):
|
||||
return token
|
||||
|
||||
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def multinomial_sample_one_no_sync(
|
||||
probs_sort,
|
||||
@ -197,86 +160,3 @@ def sample(
|
||||
probs = logits_to_probs(logits=logits, previous_tokens=previous_tokens, **sampling_kwargs)
|
||||
idx_next = multinomial_sample_one_no_sync(probs)
|
||||
return idx_next, probs
|
||||
|
||||
|
||||
def dpo_loss(
|
||||
policy_chosen_logps: torch.FloatTensor,
|
||||
policy_rejected_logps: torch.FloatTensor,
|
||||
reference_chosen_logps: torch.FloatTensor,
|
||||
reference_rejected_logps: torch.FloatTensor,
|
||||
beta: float,
|
||||
reference_free: bool = False,
|
||||
) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
|
||||
pi_logratios = policy_chosen_logps - policy_rejected_logps
|
||||
ref_logratios = reference_chosen_logps - reference_rejected_logps
|
||||
|
||||
if reference_free:
|
||||
ref_logratios = 0
|
||||
|
||||
logits = pi_logratios - ref_logratios
|
||||
|
||||
losses = -F.logsigmoid(beta * logits)
|
||||
chosen_rewards = beta * (policy_chosen_logps - reference_chosen_logps).detach()
|
||||
rejected_rewards = beta * (policy_rejected_logps - reference_rejected_logps).detach()
|
||||
|
||||
return losses.mean(), chosen_rewards, rejected_rewards
|
||||
|
||||
|
||||
def get_batch_logps(
|
||||
logits_target: torch.FloatTensor,
|
||||
logits_reject: torch.FloatTensor,
|
||||
labels_target: torch.LongTensor,
|
||||
labels_reject: torch.LongTensor,
|
||||
average_log_prob: bool = False,
|
||||
) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
|
||||
# dummy token; we'll ignore the losses on these tokens later
|
||||
|
||||
per_token_logps_target = torch.gather(
|
||||
logits_target.log_softmax(-1), dim=2, index=labels_target.unsqueeze(2)
|
||||
).squeeze(2)
|
||||
per_token_logps_reject = torch.gather(
|
||||
logits_reject.log_softmax(-1), dim=2, index=labels_reject.unsqueeze(2)
|
||||
).squeeze(2)
|
||||
|
||||
return per_token_logps_target.sum(-1), per_token_logps_reject.sum(-1)
|
||||
|
||||
|
||||
def make_reject_y(y_o, y_lens):
|
||||
def repeat_P(y):
|
||||
range_idx, _ = torch.randint(0, len(y), size=(2,)).sort()
|
||||
pre = y[: range_idx[0]]
|
||||
shf = y[range_idx[1] :]
|
||||
range_text = y[range_idx[0] : range_idx[1]]
|
||||
new_y = torch.cat([pre, range_text, range_text, shf])
|
||||
return new_y
|
||||
|
||||
def lost_P(y):
|
||||
range_idx, _ = torch.randint(0, len(y), size=(2,)).sort()
|
||||
pre = y[: range_idx[0]]
|
||||
shf = y[range_idx[1] :]
|
||||
range_text = y[range_idx[0] : range_idx[1]]
|
||||
new_y = torch.cat([pre, shf])
|
||||
return new_y
|
||||
|
||||
bs = len(y_lens)
|
||||
reject_y = []
|
||||
reject_y_lens = []
|
||||
for b in range(bs):
|
||||
process_item_idx = torch.randint(0, 2, size=(1,))[0]
|
||||
if process_item_idx == 0:
|
||||
new_y = repeat_P(y_o[b])
|
||||
reject_y.append(new_y)
|
||||
reject_y_lens.append(len(new_y))
|
||||
elif process_item_idx == 1:
|
||||
new_y = lost_P(y_o[b])
|
||||
reject_y.append(new_y)
|
||||
reject_y_lens.append(len(new_y))
|
||||
max_length = max(reject_y_lens)
|
||||
for b in range(bs):
|
||||
pad_length = max_length - reject_y_lens[b]
|
||||
reject_y[b] = torch.cat([reject_y[b], torch.zeros(pad_length, dtype=y_o.dtype, device=y_o.device)], dim=0)
|
||||
|
||||
reject_y = torch.stack(reject_y, dim=0)
|
||||
reject_y_lens = torch.tensor(reject_y_lens, device=y_lens.device)
|
||||
|
||||
return reject_y, reject_y_lens
|
||||
|
||||
@ -3,203 +3,33 @@ from typing import Optional, Tuple
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
from torch.nn import Linear, Module
|
||||
from torch.nn import functional as F
|
||||
from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
|
||||
from torch.nn import Module
|
||||
from torch.nn.init import constant_, xavier_uniform_
|
||||
from torch.nn.modules.linear import NonDynamicallyQuantizableLinear
|
||||
from torch.nn.parameter import Parameter
|
||||
|
||||
from AR.modules.patched_mha_with_cache import multi_head_attention_forward_patched
|
||||
|
||||
F.multi_head_attention_forward = multi_head_attention_forward_patched
|
||||
|
||||
|
||||
class MultiheadAttention(Module):
|
||||
r"""Allows the model to jointly attend to information
|
||||
from different representation subspaces as described in the paper:
|
||||
`Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_.
|
||||
|
||||
Multi-Head Attention is defined as:
|
||||
|
||||
.. math::
|
||||
\text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
|
||||
|
||||
where :math:`head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`.
|
||||
|
||||
``forward()`` will use a special optimized implementation if all of the following
|
||||
conditions are met:
|
||||
|
||||
- self attention is being computed (i.e., ``query``, ``key``, and ``value`` are the same tensor. This
|
||||
restriction will be loosened in the future.)
|
||||
- Either autograd is disabled (using ``torch.inference_mode`` or ``torch.no_grad``) or no tensor argument ``requires_grad``
|
||||
- training is disabled (using ``.eval()``)
|
||||
- dropout is 0
|
||||
- ``add_bias_kv`` is ``False``
|
||||
- ``add_zero_attn`` is ``False``
|
||||
- ``batch_first`` is ``True`` and the input is batched
|
||||
- ``kdim`` and ``vdim`` are equal to ``embed_dim``
|
||||
- at most one of ``key_padding_mask`` or ``attn_mask`` is passed
|
||||
- if a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ is passed, neither ``key_padding_mask``
|
||||
nor ``attn_mask`` is passed
|
||||
|
||||
If the optimized implementation is in use, a
|
||||
`NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ can be passed for
|
||||
``query``/``key``/``value`` to represent padding more efficiently than using a
|
||||
padding mask. In this case, a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_
|
||||
will be returned, and an additional speedup proportional to the fraction of the input
|
||||
that is padding can be expected.
|
||||
|
||||
Args:
|
||||
embed_dim: Total dimension of the model.
|
||||
num_heads: Number of parallel attention heads. Note that ``embed_dim`` will be split
|
||||
across ``num_heads`` (i.e. each head will have dimension ``embed_dim // num_heads``).
|
||||
dropout: Dropout probability on ``attn_output_weights``. Default: ``0.0`` (no dropout).
|
||||
bias: If specified, adds bias to input / output projection layers. Default: ``True``.
|
||||
add_bias_kv: If specified, adds bias to the key and value sequences at dim=0. Default: ``False``.
|
||||
add_zero_attn: If specified, adds a new batch of zeros to the key and value sequences at dim=1.
|
||||
Default: ``False``.
|
||||
kdim: Total number of features for keys. Default: ``None`` (uses ``kdim=embed_dim``).
|
||||
vdim: Total number of features for values. Default: ``None`` (uses ``vdim=embed_dim``).
|
||||
batch_first: If ``True``, then the input and output tensors are provided
|
||||
as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
|
||||
|
||||
Examples::
|
||||
|
||||
>>> # xdoctest: +SKIP
|
||||
>>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
|
||||
>>> attn_output, attn_output_weights = multihead_attn(query, key, value)
|
||||
|
||||
"""
|
||||
"""Inference attention with the original packed-projection checkpoint keys."""
|
||||
|
||||
__constants__ = ["batch_first"]
|
||||
bias_k: Optional[torch.Tensor]
|
||||
bias_v: Optional[torch.Tensor]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
embed_dim,
|
||||
num_heads,
|
||||
dropout=0.0,
|
||||
bias=True,
|
||||
add_bias_kv=False,
|
||||
add_zero_attn=False,
|
||||
kdim=None,
|
||||
vdim=None,
|
||||
batch_first=False,
|
||||
linear1_cls=Linear,
|
||||
linear2_cls=Linear,
|
||||
device=None,
|
||||
dtype=None,
|
||||
) -> None:
|
||||
def __init__(self, embed_dim, num_heads, batch_first=False, device=None, dtype=None):
|
||||
super().__init__()
|
||||
factory_kwargs = {"device": device, "dtype": dtype}
|
||||
super(MultiheadAttention, self).__init__()
|
||||
self.embed_dim = embed_dim
|
||||
self.kdim = kdim if kdim is not None else embed_dim
|
||||
self.vdim = vdim if vdim is not None else embed_dim
|
||||
self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
|
||||
|
||||
self.num_heads = num_heads
|
||||
self.dropout = dropout
|
||||
self.batch_first = batch_first
|
||||
self.head_dim = embed_dim // num_heads
|
||||
assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
|
||||
|
||||
if add_bias_kv:
|
||||
self.bias_k = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
||||
self.bias_v = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
||||
else:
|
||||
self.bias_k = self.bias_v = None
|
||||
|
||||
if linear1_cls == Linear:
|
||||
if not self._qkv_same_embed_dim:
|
||||
self.q_proj_weight = Parameter(
|
||||
torch.empty((embed_dim, embed_dim), **factory_kwargs),
|
||||
)
|
||||
self.k_proj_weight = Parameter(
|
||||
torch.empty((embed_dim, self.kdim), **factory_kwargs),
|
||||
)
|
||||
self.v_proj_weight = Parameter(
|
||||
torch.empty((embed_dim, self.vdim), **factory_kwargs),
|
||||
)
|
||||
self.register_parameter("in_proj_weight", None)
|
||||
else:
|
||||
self.in_proj_weight = Parameter(
|
||||
torch.empty((3 * embed_dim, embed_dim), **factory_kwargs),
|
||||
)
|
||||
self.register_parameter("q_proj_weight", None)
|
||||
self.register_parameter("k_proj_weight", None)
|
||||
self.register_parameter("v_proj_weight", None)
|
||||
|
||||
if bias:
|
||||
self.in_proj_bias = Parameter(torch.empty(3 * embed_dim, **factory_kwargs))
|
||||
else:
|
||||
self.register_parameter("in_proj_bias", None)
|
||||
self.out_proj = NonDynamicallyQuantizableLinear(
|
||||
embed_dim,
|
||||
embed_dim,
|
||||
bias=bias,
|
||||
**factory_kwargs,
|
||||
)
|
||||
|
||||
self._reset_parameters()
|
||||
else:
|
||||
if not self._qkv_same_embed_dim:
|
||||
raise NotImplementedError
|
||||
else:
|
||||
self.in_proj_linear = linear1_cls(
|
||||
embed_dim,
|
||||
3 * embed_dim,
|
||||
bias=bias,
|
||||
**factory_kwargs,
|
||||
)
|
||||
self.in_proj_weight = self.in_proj_linear.weight
|
||||
|
||||
self.register_parameter("q_proj_weight", None)
|
||||
self.register_parameter("k_proj_weight", None)
|
||||
self.register_parameter("v_proj_weight", None)
|
||||
|
||||
if bias:
|
||||
self.in_proj_bias = self.in_proj_linear.bias
|
||||
else:
|
||||
self.register_parameter("in_proj_bias", None)
|
||||
|
||||
self.out_proj = linear2_cls(
|
||||
embed_dim,
|
||||
embed_dim,
|
||||
bias=bias,
|
||||
**factory_kwargs,
|
||||
)
|
||||
|
||||
if self.bias_k is not None:
|
||||
xavier_normal_(self.bias_k)
|
||||
if self.bias_v is not None:
|
||||
xavier_normal_(self.bias_v)
|
||||
|
||||
self.add_zero_attn = add_zero_attn
|
||||
|
||||
def _reset_parameters(self):
|
||||
if self._qkv_same_embed_dim:
|
||||
xavier_uniform_(self.in_proj_weight)
|
||||
else:
|
||||
xavier_uniform_(self.q_proj_weight)
|
||||
xavier_uniform_(self.k_proj_weight)
|
||||
xavier_uniform_(self.v_proj_weight)
|
||||
|
||||
if self.in_proj_bias is not None:
|
||||
constant_(self.in_proj_bias, 0.0)
|
||||
constant_(self.out_proj.bias, 0.0)
|
||||
|
||||
if self.bias_k is not None:
|
||||
xavier_normal_(self.bias_k)
|
||||
if self.bias_v is not None:
|
||||
xavier_normal_(self.bias_v)
|
||||
|
||||
def __setstate__(self, state):
|
||||
# Support loading old MultiheadAttention checkpoints generated by v1.1.0
|
||||
if "_qkv_same_embed_dim" not in state:
|
||||
state["_qkv_same_embed_dim"] = True
|
||||
|
||||
super(MultiheadAttention, self).__setstate__(state)
|
||||
assert self.head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"
|
||||
self.in_proj_weight = Parameter(torch.empty((3 * embed_dim, embed_dim), **factory_kwargs))
|
||||
self.in_proj_bias = Parameter(torch.empty(3 * embed_dim, **factory_kwargs))
|
||||
self.out_proj = NonDynamicallyQuantizableLinear(embed_dim, embed_dim, **factory_kwargs)
|
||||
xavier_uniform_(self.in_proj_weight)
|
||||
constant_(self.in_proj_bias, 0.0)
|
||||
constant_(self.out_proj.bias, 0.0)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@ -212,202 +42,48 @@ class MultiheadAttention(Module):
|
||||
average_attn_weights: bool = True,
|
||||
cache=None,
|
||||
) -> Tuple[Tensor, Optional[Tensor]]:
|
||||
r"""
|
||||
Args:
|
||||
query: Query embeddings of shape :math:`(L, E_q)` for unbatched input, :math:`(L, N, E_q)` when ``batch_first=False``
|
||||
or :math:`(N, L, E_q)` when ``batch_first=True``, where :math:`L` is the target sequence length,
|
||||
:math:`N` is the batch size, and :math:`E_q` is the query embedding dimension ``embed_dim``.
|
||||
Queries are compared against key-value pairs to produce the output.
|
||||
See "Attention Is All You Need" for more details.
|
||||
key: Key embeddings of shape :math:`(S, E_k)` for unbatched input, :math:`(S, N, E_k)` when ``batch_first=False``
|
||||
or :math:`(N, S, E_k)` when ``batch_first=True``, where :math:`S` is the source sequence length,
|
||||
:math:`N` is the batch size, and :math:`E_k` is the key embedding dimension ``kdim``.
|
||||
See "Attention Is All You Need" for more details.
|
||||
value: Value embeddings of shape :math:`(S, E_v)` for unbatched input, :math:`(S, N, E_v)` when
|
||||
``batch_first=False`` or :math:`(N, S, E_v)` when ``batch_first=True``, where :math:`S` is the source
|
||||
sequence length, :math:`N` is the batch size, and :math:`E_v` is the value embedding dimension ``vdim``.
|
||||
See "Attention Is All You Need" for more details.
|
||||
key_padding_mask: If specified, a mask of shape :math:`(N, S)` indicating which elements within ``key``
|
||||
to ignore for the purpose of attention (i.e. treat as "padding"). For unbatched `query`, shape should be :math:`(S)`.
|
||||
Binary and byte masks are supported.
|
||||
For a binary mask, a ``True`` value indicates that the corresponding ``key`` value will be ignored for
|
||||
the purpose of attention. For a float mask, it will be directly added to the corresponding ``key`` value.
|
||||
need_weights: If specified, returns ``attn_output_weights`` in addition to ``attn_outputs``.
|
||||
Default: ``True``.
|
||||
attn_mask: If specified, a 2D or 3D mask preventing attention to certain positions. Must be of shape
|
||||
:math:`(L, S)` or :math:`(N\cdot\text{num\_heads}, L, S)`, where :math:`N` is the batch size,
|
||||
:math:`L` is the target sequence length, and :math:`S` is the source sequence length. A 2D mask will be
|
||||
broadcasted across the batch while a 3D mask allows for a different mask for each entry in the batch.
|
||||
Binary, byte, and float masks are supported. For a binary mask, a ``True`` value indicates that the
|
||||
corresponding position is not allowed to attend. For a byte mask, a non-zero value indicates that the
|
||||
corresponding position is not allowed to attend. For a float mask, the mask values will be added to
|
||||
the attention weight.
|
||||
average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
|
||||
heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
|
||||
effect when ``need_weights=True``. Default: ``True`` (i.e. average weights across heads)
|
||||
|
||||
Outputs:
|
||||
- **attn_output** - Attention outputs of shape :math:`(L, E)` when input is unbatched,
|
||||
:math:`(L, N, E)` when ``batch_first=False`` or :math:`(N, L, E)` when ``batch_first=True``,
|
||||
where :math:`L` is the target sequence length, :math:`N` is the batch size, and :math:`E` is the
|
||||
embedding dimension ``embed_dim``.
|
||||
- **attn_output_weights** - Only returned when ``need_weights=True``. If ``average_attn_weights=True``,
|
||||
returns attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
|
||||
:math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
|
||||
:math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
|
||||
head of shape :math:`(\text{num\_heads}, L, S)` when input is unbatched or :math:`(N, \text{num\_heads}, L, S)`.
|
||||
|
||||
.. note::
|
||||
`batch_first` argument is ignored for unbatched inputs.
|
||||
"""
|
||||
is_batched = query.dim() == 3
|
||||
if key_padding_mask is not None:
|
||||
_kpm_dtype = key_padding_mask.dtype
|
||||
if _kpm_dtype != torch.bool and not torch.is_floating_point(
|
||||
key_padding_mask,
|
||||
):
|
||||
if key_padding_mask.dtype != torch.bool and not torch.is_floating_point(key_padding_mask):
|
||||
raise AssertionError("only bool and floating types of key_padding_mask are supported")
|
||||
why_not_fast_path = ""
|
||||
if not is_batched:
|
||||
why_not_fast_path = f"input not batched; expected query.dim() of 3 but got {query.dim()}"
|
||||
elif query is not key or key is not value:
|
||||
# When lifting this restriction, don't forget to either
|
||||
# enforce that the dtypes all match or test cases where
|
||||
# they don't!
|
||||
why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
|
||||
elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
|
||||
why_not_fast_path = (
|
||||
f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
|
||||
)
|
||||
elif self.in_proj_weight is not None and query.dtype != self.in_proj_weight.dtype:
|
||||
# this case will fail anyway, but at least they'll get a useful error message.
|
||||
why_not_fast_path = (
|
||||
f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
|
||||
)
|
||||
elif self.training:
|
||||
why_not_fast_path = "training is enabled"
|
||||
elif not self.batch_first:
|
||||
why_not_fast_path = "batch_first was not True"
|
||||
elif self.bias_k is not None:
|
||||
why_not_fast_path = "self.bias_k was not None"
|
||||
elif self.bias_v is not None:
|
||||
why_not_fast_path = "self.bias_v was not None"
|
||||
elif self.dropout:
|
||||
why_not_fast_path = f"dropout was {self.dropout}, required zero"
|
||||
elif self.add_zero_attn:
|
||||
why_not_fast_path = "add_zero_attn was enabled"
|
||||
elif not self._qkv_same_embed_dim:
|
||||
why_not_fast_path = "_qkv_same_embed_dim was not True"
|
||||
elif attn_mask is not None:
|
||||
why_not_fast_path = "attn_mask was not None"
|
||||
elif query.is_nested and key_padding_mask is not None:
|
||||
why_not_fast_path = "key_padding_mask is not supported with NestedTensor input"
|
||||
elif self.num_heads % 2 == 1:
|
||||
why_not_fast_path = "num_heads is odd"
|
||||
elif torch.is_autocast_enabled():
|
||||
why_not_fast_path = "autocast is enabled"
|
||||
|
||||
if not why_not_fast_path:
|
||||
tensor_args = (
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.in_proj_weight,
|
||||
self.in_proj_bias,
|
||||
self.out_proj.weight,
|
||||
self.out_proj.bias,
|
||||
)
|
||||
# We have to use list comprehensions below because TorchScript does not support
|
||||
# generator expressions.
|
||||
if torch.overrides.has_torch_function(tensor_args):
|
||||
why_not_fast_path = "some Tensor argument has_torch_function"
|
||||
elif not all([(x is None or x.is_cuda or "cpu" in str(x.device)) for x in tensor_args]):
|
||||
why_not_fast_path = "some Tensor argument is neither CUDA nor CPU"
|
||||
elif torch.is_grad_enabled() and any([x is not None and x.requires_grad for x in tensor_args]):
|
||||
why_not_fast_path = "grad is enabled and at least one of query or the input/output projection weights or biases requires_grad"
|
||||
if not why_not_fast_path:
|
||||
return torch._native_multi_head_attention(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.embed_dim,
|
||||
self.num_heads,
|
||||
self.in_proj_weight,
|
||||
self.in_proj_bias,
|
||||
self.out_proj.weight,
|
||||
self.out_proj.bias,
|
||||
key_padding_mask if key_padding_mask is not None else attn_mask,
|
||||
need_weights,
|
||||
average_attn_weights,
|
||||
1 if key_padding_mask is not None else 0 if attn_mask is not None else None,
|
||||
)
|
||||
|
||||
any_nested = query.is_nested or key.is_nested or value.is_nested
|
||||
assert not any_nested, (
|
||||
"MultiheadAttention does not support NestedTensor outside of its fast path. "
|
||||
+ f"The fast path was not hit because {why_not_fast_path}"
|
||||
tensor_args = (query, key, value, self.in_proj_weight, self.in_proj_bias,
|
||||
self.out_proj.weight, self.out_proj.bias)
|
||||
native_attention = (
|
||||
is_batched and self.batch_first and query is key and key is value
|
||||
and cache is None and attn_mask is None
|
||||
and query.dtype == self.in_proj_bias.dtype == self.in_proj_weight.dtype
|
||||
and not (query.is_nested and key_padding_mask is not None)
|
||||
and self.num_heads % 2 == 0 and not torch.is_autocast_enabled()
|
||||
and not torch.overrides.has_torch_function(tensor_args)
|
||||
and all(t.device.type in {"cpu", "cuda"} for t in tensor_args)
|
||||
and not (torch.is_grad_enabled() and any(t.requires_grad for t in tensor_args))
|
||||
)
|
||||
if native_attention:
|
||||
return torch._native_multi_head_attention(
|
||||
query, key, value, self.embed_dim, self.num_heads,
|
||||
self.in_proj_weight, self.in_proj_bias, self.out_proj.weight, self.out_proj.bias,
|
||||
key_padding_mask, need_weights, average_attn_weights,
|
||||
1 if key_padding_mask is not None else None,
|
||||
)
|
||||
|
||||
assert not (query.is_nested or key.is_nested or value.is_nested), (
|
||||
"NestedTensor requires native attention without an explicit attention mask or KV cache"
|
||||
)
|
||||
if self.batch_first and is_batched:
|
||||
# make sure that the transpose op does not affect the "is" property
|
||||
if key is value:
|
||||
if query is key:
|
||||
query = key = value = query.transpose(1, 0)
|
||||
else:
|
||||
query, key = [x.transpose(1, 0) for x in (query, key)]
|
||||
query, key = query.transpose(1, 0), key.transpose(1, 0)
|
||||
value = key
|
||||
else:
|
||||
query, key, value = [x.transpose(1, 0) for x in (query, key, value)]
|
||||
|
||||
if not self._qkv_same_embed_dim:
|
||||
attn_output, attn_output_weights = F.multi_head_attention_forward(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.embed_dim,
|
||||
self.num_heads,
|
||||
self.in_proj_weight,
|
||||
self.in_proj_bias,
|
||||
self.bias_k,
|
||||
self.bias_v,
|
||||
self.add_zero_attn,
|
||||
self.dropout,
|
||||
self.out_proj.weight,
|
||||
self.out_proj.bias,
|
||||
training=self.training,
|
||||
key_padding_mask=key_padding_mask,
|
||||
need_weights=need_weights,
|
||||
attn_mask=attn_mask,
|
||||
use_separate_proj_weight=True,
|
||||
q_proj_weight=self.q_proj_weight,
|
||||
k_proj_weight=self.k_proj_weight,
|
||||
v_proj_weight=self.v_proj_weight,
|
||||
average_attn_weights=average_attn_weights,
|
||||
cache=cache,
|
||||
)
|
||||
else:
|
||||
attn_output, attn_output_weights = F.multi_head_attention_forward(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.embed_dim,
|
||||
self.num_heads,
|
||||
self.in_proj_weight,
|
||||
self.in_proj_bias,
|
||||
self.bias_k,
|
||||
self.bias_v,
|
||||
self.add_zero_attn,
|
||||
self.dropout,
|
||||
self.out_proj.weight,
|
||||
self.out_proj.bias,
|
||||
training=self.training,
|
||||
key_padding_mask=key_padding_mask,
|
||||
need_weights=need_weights,
|
||||
attn_mask=attn_mask,
|
||||
average_attn_weights=average_attn_weights,
|
||||
cache=cache,
|
||||
)
|
||||
if self.batch_first and is_batched:
|
||||
return attn_output.transpose(1, 0), attn_output_weights
|
||||
else:
|
||||
return attn_output, attn_output_weights
|
||||
output, weights = multi_head_attention_forward_patched(
|
||||
query, key, value, self.embed_dim, self.num_heads,
|
||||
self.in_proj_weight, self.in_proj_bias, self.out_proj.weight, self.out_proj.bias,
|
||||
key_padding_mask=key_padding_mask, need_weights=need_weights,
|
||||
attn_mask=attn_mask, average_attn_weights=average_attn_weights, cache=cache,
|
||||
)
|
||||
return (output.transpose(1, 0) if self.batch_first and is_batched else output), weights
|
||||
|
||||
@ -1,188 +0,0 @@
|
||||
# modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/activation.py
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
from torch.nn import Linear, Module
|
||||
from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
|
||||
from torch.nn.modules.linear import NonDynamicallyQuantizableLinear
|
||||
from torch.nn.parameter import Parameter
|
||||
|
||||
from AR.modules.patched_mha_with_cache_onnx import multi_head_attention_forward_patched
|
||||
|
||||
|
||||
class MultiheadAttention(Module):
|
||||
__constants__ = ["batch_first"]
|
||||
bias_k: Optional[torch.Tensor]
|
||||
bias_v: Optional[torch.Tensor]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
embed_dim,
|
||||
num_heads,
|
||||
dropout=0.0,
|
||||
bias=True,
|
||||
add_bias_kv=False,
|
||||
add_zero_attn=False,
|
||||
kdim=None,
|
||||
vdim=None,
|
||||
batch_first=False,
|
||||
linear1_cls=Linear,
|
||||
linear2_cls=Linear,
|
||||
device=None,
|
||||
dtype=None,
|
||||
) -> None:
|
||||
factory_kwargs = {"device": device, "dtype": dtype}
|
||||
super(MultiheadAttention, self).__init__()
|
||||
self.embed_dim = embed_dim
|
||||
self.kdim = kdim if kdim is not None else embed_dim
|
||||
self.vdim = vdim if vdim is not None else embed_dim
|
||||
self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
|
||||
|
||||
self.num_heads = num_heads
|
||||
self.dropout = dropout
|
||||
self.batch_first = batch_first
|
||||
self.head_dim = embed_dim // num_heads
|
||||
assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
|
||||
|
||||
if add_bias_kv:
|
||||
self.bias_k = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
||||
self.bias_v = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
||||
else:
|
||||
self.bias_k = self.bias_v = None
|
||||
|
||||
if linear1_cls == Linear:
|
||||
if not self._qkv_same_embed_dim:
|
||||
self.q_proj_weight = Parameter(
|
||||
torch.empty(
|
||||
(embed_dim, embed_dim),
|
||||
**factory_kwargs,
|
||||
)
|
||||
)
|
||||
self.k_proj_weight = Parameter(
|
||||
torch.empty(
|
||||
(embed_dim, self.kdim),
|
||||
**factory_kwargs,
|
||||
)
|
||||
)
|
||||
self.v_proj_weight = Parameter(
|
||||
torch.empty(
|
||||
(embed_dim, self.vdim),
|
||||
**factory_kwargs,
|
||||
)
|
||||
)
|
||||
self.register_parameter("in_proj_weight", None)
|
||||
else:
|
||||
self.in_proj_weight = Parameter(
|
||||
torch.empty(
|
||||
(3 * embed_dim, embed_dim),
|
||||
**factory_kwargs,
|
||||
)
|
||||
)
|
||||
self.register_parameter("q_proj_weight", None)
|
||||
self.register_parameter("k_proj_weight", None)
|
||||
self.register_parameter("v_proj_weight", None)
|
||||
|
||||
if bias:
|
||||
self.in_proj_bias = Parameter(
|
||||
torch.empty(3 * embed_dim, **factory_kwargs),
|
||||
)
|
||||
else:
|
||||
self.register_parameter("in_proj_bias", None)
|
||||
self.out_proj = NonDynamicallyQuantizableLinear(embed_dim, embed_dim, bias=bias, **factory_kwargs)
|
||||
|
||||
self._reset_parameters()
|
||||
else:
|
||||
if not self._qkv_same_embed_dim:
|
||||
raise NotImplementedError
|
||||
else:
|
||||
self.in_proj_linear = linear1_cls(
|
||||
embed_dim,
|
||||
3 * embed_dim,
|
||||
bias=bias,
|
||||
**factory_kwargs,
|
||||
)
|
||||
self.in_proj_weight = self.in_proj_linear.weight
|
||||
|
||||
self.register_parameter("q_proj_weight", None)
|
||||
self.register_parameter("k_proj_weight", None)
|
||||
self.register_parameter("v_proj_weight", None)
|
||||
|
||||
if bias:
|
||||
self.in_proj_bias = self.in_proj_linear.bias
|
||||
else:
|
||||
self.register_parameter("in_proj_bias", None)
|
||||
|
||||
self.out_proj = linear2_cls(
|
||||
embed_dim,
|
||||
embed_dim,
|
||||
bias=bias,
|
||||
**factory_kwargs,
|
||||
)
|
||||
|
||||
if self.bias_k is not None:
|
||||
xavier_normal_(self.bias_k)
|
||||
if self.bias_v is not None:
|
||||
xavier_normal_(self.bias_v)
|
||||
|
||||
self.add_zero_attn = add_zero_attn
|
||||
|
||||
def _reset_parameters(self):
|
||||
if self._qkv_same_embed_dim:
|
||||
xavier_uniform_(self.in_proj_weight)
|
||||
else:
|
||||
xavier_uniform_(self.q_proj_weight)
|
||||
xavier_uniform_(self.k_proj_weight)
|
||||
xavier_uniform_(self.v_proj_weight)
|
||||
|
||||
if self.in_proj_bias is not None:
|
||||
constant_(self.in_proj_bias, 0.0)
|
||||
constant_(self.out_proj.bias, 0.0)
|
||||
|
||||
if self.bias_k is not None:
|
||||
xavier_normal_(self.bias_k)
|
||||
if self.bias_v is not None:
|
||||
xavier_normal_(self.bias_v)
|
||||
|
||||
def __setstate__(self, state):
|
||||
# Support loading old MultiheadAttention checkpoints generated by v1.1.0
|
||||
if "_qkv_same_embed_dim" not in state:
|
||||
state["_qkv_same_embed_dim"] = True
|
||||
|
||||
super(MultiheadAttention, self).__setstate__(state)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
query: Tensor,
|
||||
key: Tensor,
|
||||
value: Tensor,
|
||||
key_padding_mask: Optional[Tensor] = None,
|
||||
need_weights: bool = True,
|
||||
attn_mask: Optional[Tensor] = None,
|
||||
average_attn_weights: bool = True,
|
||||
cache=None,
|
||||
) -> Tuple[Tensor, Optional[Tensor]]:
|
||||
any_nested = query.is_nested or key.is_nested or value.is_nested
|
||||
query = key = value = query.transpose(1, 0)
|
||||
attn_output = multi_head_attention_forward_patched(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.embed_dim,
|
||||
self.num_heads,
|
||||
self.in_proj_weight,
|
||||
self.in_proj_bias,
|
||||
self.bias_k,
|
||||
self.bias_v,
|
||||
self.add_zero_attn,
|
||||
self.dropout,
|
||||
self.out_proj.weight,
|
||||
self.out_proj.bias,
|
||||
training=self.training,
|
||||
key_padding_mask=key_padding_mask,
|
||||
need_weights=need_weights,
|
||||
attn_mask=attn_mask,
|
||||
average_attn_weights=average_attn_weights,
|
||||
cache=cache,
|
||||
)
|
||||
return attn_output.transpose(1, 0)
|
||||
@ -10,34 +10,26 @@ class TokenEmbedding(nn.Module):
|
||||
self,
|
||||
embedding_dim: int,
|
||||
vocab_size: int,
|
||||
dropout: float = 0.0,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.vocab_size = vocab_size
|
||||
self.embedding_dim = embedding_dim
|
||||
|
||||
self.dropout = torch.nn.Dropout(p=dropout)
|
||||
self.word_embeddings = nn.Embedding(self.vocab_size, self.embedding_dim)
|
||||
|
||||
@property
|
||||
def weight(self) -> torch.Tensor:
|
||||
return self.word_embeddings.weight
|
||||
|
||||
def embedding(self, index: int) -> torch.Tensor:
|
||||
return self.word_embeddings.weight[index : index + 1]
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
x = self.word_embeddings(x)
|
||||
x = self.dropout(x)
|
||||
return x
|
||||
return self.word_embeddings(x)
|
||||
|
||||
|
||||
class SinePositionalEmbedding(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
embedding_dim: int,
|
||||
dropout: float = 0.0,
|
||||
scale: bool = False,
|
||||
alpha: bool = False,
|
||||
):
|
||||
@ -45,9 +37,6 @@ class SinePositionalEmbedding(nn.Module):
|
||||
self.embedding_dim = embedding_dim
|
||||
self.x_scale = math.sqrt(embedding_dim) if scale else 1.0
|
||||
self.alpha = nn.Parameter(torch.ones(1), requires_grad=alpha)
|
||||
self.dropout = torch.nn.Dropout(p=dropout)
|
||||
|
||||
self.reverse = False
|
||||
self.pe = None
|
||||
self.extend_pe(torch.tensor(0.0).expand(1, 4000))
|
||||
|
||||
@ -59,10 +48,7 @@ class SinePositionalEmbedding(nn.Module):
|
||||
self.pe = self.pe.to(dtype=x.dtype, device=x.device)
|
||||
return
|
||||
pe = torch.zeros(x.size(1), self.embedding_dim)
|
||||
if self.reverse:
|
||||
position = torch.arange(x.size(1) - 1, -1, -1.0, dtype=torch.float32).unsqueeze(1)
|
||||
else:
|
||||
position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
|
||||
position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
|
||||
div_term = torch.exp(
|
||||
torch.arange(0, self.embedding_dim, 2, dtype=torch.float32) * -(math.log(10000.0) / self.embedding_dim)
|
||||
)
|
||||
@ -75,4 +61,4 @@ class SinePositionalEmbedding(nn.Module):
|
||||
self.extend_pe(x)
|
||||
output = x.unsqueeze(-1) if x.ndim == 2 else x
|
||||
output = output * self.x_scale + self.alpha * self.pe[:, : x.size(1)]
|
||||
return self.dropout(output)
|
||||
return output
|
||||
|
||||
@ -1,63 +0,0 @@
|
||||
# modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/embedding.py
|
||||
import math
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
class TokenEmbedding(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
embedding_dim: int,
|
||||
vocab_size: int,
|
||||
dropout: float = 0.0,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.vocab_size = vocab_size
|
||||
self.embedding_dim = embedding_dim
|
||||
|
||||
self.dropout = torch.nn.Dropout(p=dropout)
|
||||
self.word_embeddings = nn.Embedding(self.vocab_size, self.embedding_dim)
|
||||
|
||||
@property
|
||||
def weight(self) -> torch.Tensor:
|
||||
return self.word_embeddings.weight
|
||||
|
||||
def embedding(self, index: int) -> torch.Tensor:
|
||||
return self.word_embeddings.weight[index : index + 1]
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
x = self.word_embeddings(x)
|
||||
x = self.dropout(x)
|
||||
return x
|
||||
|
||||
|
||||
class SinePositionalEmbedding(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
embedding_dim: int,
|
||||
dropout: float = 0.0,
|
||||
scale: bool = False,
|
||||
alpha: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
self.embedding_dim = embedding_dim
|
||||
self.x_scale = math.sqrt(embedding_dim) if scale else 1.0
|
||||
self.alpha = nn.Parameter(torch.ones(1), requires_grad=alpha)
|
||||
self.dropout = torch.nn.Dropout(p=dropout)
|
||||
self.reverse = False
|
||||
self.div_term = torch.exp(torch.arange(0, self.embedding_dim, 2) * -(math.log(10000.0) / self.embedding_dim))
|
||||
|
||||
def extend_pe(self, x):
|
||||
position = torch.cumsum(torch.ones_like(x[:, :, 0]), dim=1).transpose(0, 1)
|
||||
scpe = (position * self.div_term).unsqueeze(0)
|
||||
pe = torch.cat([torch.sin(scpe), torch.cos(scpe)]).permute(1, 2, 0)
|
||||
pe = pe.contiguous().view(1, -1, self.embedding_dim)
|
||||
return pe
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
pe = self.extend_pe(x)
|
||||
output = x.unsqueeze(-1) if x.ndim == 2 else x
|
||||
output = output * self.x_scale + self.alpha * pe
|
||||
return self.dropout(output)
|
||||
@ -1,85 +0,0 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/modules/lr_schedulers.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
import math
|
||||
|
||||
import torch
|
||||
from matplotlib import pyplot as plt
|
||||
from torch import nn
|
||||
from torch.optim import Adam
|
||||
|
||||
|
||||
class WarmupCosineLRSchedule(torch.optim.lr_scheduler._LRScheduler):
|
||||
"""
|
||||
Implements Warmup learning rate schedule until 'warmup_steps', going from 'init_lr' to 'peak_lr' for multiple optimizers.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
optimizer,
|
||||
init_lr,
|
||||
peak_lr,
|
||||
end_lr,
|
||||
warmup_steps=10000,
|
||||
total_steps=400000,
|
||||
current_step=0,
|
||||
):
|
||||
self.init_lr = init_lr
|
||||
self.peak_lr = peak_lr
|
||||
self.end_lr = end_lr
|
||||
self.optimizer = optimizer
|
||||
self._warmup_rate = (peak_lr - init_lr) / warmup_steps
|
||||
self._decay_rate = (end_lr - peak_lr) / (total_steps - warmup_steps)
|
||||
self._current_step = current_step
|
||||
self.lr = init_lr
|
||||
self.warmup_steps = warmup_steps
|
||||
self.total_steps = total_steps
|
||||
self._last_lr = [self.lr]
|
||||
|
||||
def set_lr(self, lr):
|
||||
self._last_lr = [g["lr"] for g in self.optimizer.param_groups]
|
||||
for g in self.optimizer.param_groups:
|
||||
# g['lr'] = lr
|
||||
g["lr"] = self.end_lr ###锁定用线性
|
||||
|
||||
def step(self):
|
||||
if self._current_step < self.warmup_steps:
|
||||
lr = self.init_lr + self._warmup_rate * self._current_step
|
||||
|
||||
elif self._current_step > self.total_steps:
|
||||
lr = self.end_lr
|
||||
|
||||
else:
|
||||
decay_ratio = (self._current_step - self.warmup_steps) / (self.total_steps - self.warmup_steps)
|
||||
if decay_ratio < 0.0 or decay_ratio > 1.0:
|
||||
raise RuntimeError("Decay ratio must be in [0.0, 1.0]. Fix LR scheduler settings.")
|
||||
coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
|
||||
lr = self.end_lr + coeff * (self.peak_lr - self.end_lr)
|
||||
|
||||
self.lr = lr = self.end_lr = 0.002 ###锁定用线性###不听话,直接锁定!
|
||||
self.set_lr(lr)
|
||||
self.lr = lr
|
||||
self._current_step += 1
|
||||
return self.lr
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
m = nn.Linear(10, 10)
|
||||
opt = Adam(m.parameters(), lr=1e-4)
|
||||
s = WarmupCosineLRSchedule(
|
||||
opt,
|
||||
1e-6,
|
||||
2e-4,
|
||||
1e-6,
|
||||
warmup_steps=2000,
|
||||
total_steps=20000,
|
||||
current_step=0,
|
||||
)
|
||||
lrs = []
|
||||
for i in range(25000):
|
||||
s.step()
|
||||
lrs.append(s.lr)
|
||||
print(s.lr)
|
||||
|
||||
plt.plot(lrs)
|
||||
plt.plot(range(0, 25000), lrs)
|
||||
plt.show()
|
||||
@ -1,593 +0,0 @@
|
||||
# Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
|
||||
#
|
||||
# See ../LICENSE for clarification regarding multiple authors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import contextlib
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from typing import List, Tuple
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
from torch.optim import Optimizer
|
||||
|
||||
|
||||
class BatchedOptimizer(Optimizer):
|
||||
"""
|
||||
This class adds to class Optimizer the capability to optimize parameters in batches:
|
||||
it will stack the parameters and their grads for you so the optimizer can work
|
||||
on tensors with an extra leading dimension. This is intended for speed with GPUs,
|
||||
as it reduces the number of kernels launched in the optimizer.
|
||||
|
||||
Args:
|
||||
params:
|
||||
"""
|
||||
|
||||
def __init__(self, params, defaults):
|
||||
super(BatchedOptimizer, self).__init__(params, defaults)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def batched_params(self, param_group, group_params_names):
|
||||
"""
|
||||
This function returns (technically, yields) a list of
|
||||
of tuples (p, state), where
|
||||
p is a `fake` parameter that is stacked (over axis 0) from real parameters
|
||||
that share the same shape, and its gradient is also stacked;
|
||||
`state` is the state corresponding to this batch of parameters
|
||||
(it will be physically located in the "state" for one of the real
|
||||
parameters, the last one that has any particular shape and dtype).
|
||||
|
||||
This function is decorated as a context manager so that it can
|
||||
write parameters back to their "real" locations.
|
||||
|
||||
The idea is, instead of doing:
|
||||
<code>
|
||||
for p in group["params"]:
|
||||
state = self.state[p]
|
||||
...
|
||||
</code>
|
||||
you can do:
|
||||
<code>
|
||||
with self.batched_params(group["params"]) as batches:
|
||||
for p, state, p_names in batches:
|
||||
...
|
||||
</code>
|
||||
|
||||
Args:
|
||||
group: a parameter group, which is a list of parameters; should be
|
||||
one of self.param_groups.
|
||||
group_params_names: name for each parameter in group,
|
||||
which is List[str].
|
||||
"""
|
||||
batches = defaultdict(list) # `batches` maps from tuple (dtype_as_str,*shape) to list of nn.Parameter
|
||||
batches_names = defaultdict(list) # `batches` maps from tuple (dtype_as_str,*shape) to list of str
|
||||
|
||||
assert len(param_group) == len(group_params_names)
|
||||
for p, named_p in zip(param_group, group_params_names):
|
||||
key = (str(p.dtype), *p.shape)
|
||||
batches[key].append(p)
|
||||
batches_names[key].append(named_p)
|
||||
|
||||
batches_names_keys = list(batches_names.keys())
|
||||
sorted_idx = sorted(range(len(batches_names)), key=lambda i: batches_names_keys[i])
|
||||
batches_names = [batches_names[batches_names_keys[idx]] for idx in sorted_idx]
|
||||
batches = [batches[batches_names_keys[idx]] for idx in sorted_idx]
|
||||
|
||||
stacked_params_dict = dict()
|
||||
|
||||
# turn batches into a list, in deterministic order.
|
||||
# tuples will contain tuples of (stacked_param, state, stacked_params_names),
|
||||
# one for each batch in `batches`.
|
||||
tuples = []
|
||||
|
||||
for batch, batch_names in zip(batches, batches_names):
|
||||
p = batch[0]
|
||||
# we arbitrarily store the state in the
|
||||
# state corresponding to the 1st parameter in the
|
||||
# group. class Optimizer will take care of saving/loading state.
|
||||
state = self.state[p]
|
||||
p_stacked = torch.stack(batch)
|
||||
grad = torch.stack([torch.zeros_like(p) if p.grad is None else p.grad for p in batch])
|
||||
p_stacked.grad = grad
|
||||
stacked_params_dict[key] = p_stacked
|
||||
tuples.append((p_stacked, state, batch_names))
|
||||
|
||||
yield tuples # <-- calling code will do the actual optimization here!
|
||||
|
||||
for (stacked_params, _state, _names), batch in zip(tuples, batches):
|
||||
for i, p in enumerate(batch): # batch is list of Parameter
|
||||
p.copy_(stacked_params[i])
|
||||
|
||||
|
||||
class ScaledAdam(BatchedOptimizer):
|
||||
"""
|
||||
Implements 'Scaled Adam', a variant of Adam where we scale each parameter's update
|
||||
proportional to the norm of that parameter; and also learn the scale of the parameter,
|
||||
in log space, subject to upper and lower limits (as if we had factored each parameter as
|
||||
param = underlying_param * log_scale.exp())
|
||||
|
||||
|
||||
Args:
|
||||
params: The parameters or param_groups to optimize (like other Optimizer subclasses)
|
||||
lr: The learning rate. We will typically use a learning rate schedule that starts
|
||||
at 0.03 and decreases over time, i.e. much higher than other common
|
||||
optimizers.
|
||||
clipping_scale: (e.g. 2.0)
|
||||
A scale for gradient-clipping: if specified, the normalized gradients
|
||||
over the whole model will be clipped to have 2-norm equal to
|
||||
`clipping_scale` times the median 2-norm over the most recent period
|
||||
of `clipping_update_period` minibatches. By "normalized gradients",
|
||||
we mean after multiplying by the rms parameter value for this tensor
|
||||
[for non-scalars]; this is appropriate because our update is scaled
|
||||
by this quantity.
|
||||
betas: beta1,beta2 are momentum constants for regular momentum, and moving sum-sq grad.
|
||||
Must satisfy 0 < beta <= beta2 < 1.
|
||||
scalar_lr_scale: A scaling factor on the learning rate, that we use to update the
|
||||
scale of each parameter tensor and scalar parameters of the mode..
|
||||
If each parameter were decomposed
|
||||
as p * p_scale.exp(), where (p**2).mean().sqrt() == 1.0, scalar_lr_scale
|
||||
would be a the scaling factor on the learning rate of p_scale.
|
||||
eps: A general-purpose epsilon to prevent division by zero
|
||||
param_min_rms: Minimum root-mean-square value of parameter tensor, for purposes of
|
||||
learning the scale on the parameters (we'll constrain the rms of each non-scalar
|
||||
parameter tensor to be >= this value)
|
||||
param_max_rms: Maximum root-mean-square value of parameter tensor, for purposes of
|
||||
learning the scale on the parameters (we'll constrain the rms of each non-scalar
|
||||
parameter tensor to be <= this value)
|
||||
scalar_max: Maximum absolute value for scalar parameters (applicable if your
|
||||
model has any parameters with numel() == 1).
|
||||
size_update_period: The periodicity, in steps, with which we update the size (scale)
|
||||
of the parameter tensor. This is provided to save a little time
|
||||
in the update.
|
||||
clipping_update_period: if clipping_scale is specified, this is the period
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
params,
|
||||
lr=3e-02,
|
||||
clipping_scale=None,
|
||||
betas=(0.9, 0.98),
|
||||
scalar_lr_scale=0.1,
|
||||
eps=1.0e-08,
|
||||
param_min_rms=1.0e-05,
|
||||
param_max_rms=3.0,
|
||||
scalar_max=10.0,
|
||||
size_update_period=4,
|
||||
clipping_update_period=100,
|
||||
parameters_names=None,
|
||||
show_dominant_parameters=True,
|
||||
):
|
||||
assert parameters_names is not None, (
|
||||
"Please prepare parameters_names,which is a List[List[str]]. Each List[str] is for a groupand each str is for a parameter"
|
||||
)
|
||||
defaults = dict(
|
||||
lr=lr,
|
||||
clipping_scale=clipping_scale,
|
||||
betas=betas,
|
||||
scalar_lr_scale=scalar_lr_scale,
|
||||
eps=eps,
|
||||
param_min_rms=param_min_rms,
|
||||
param_max_rms=param_max_rms,
|
||||
scalar_max=scalar_max,
|
||||
size_update_period=size_update_period,
|
||||
clipping_update_period=clipping_update_period,
|
||||
)
|
||||
|
||||
super(ScaledAdam, self).__init__(params, defaults)
|
||||
assert len(self.param_groups) == len(parameters_names)
|
||||
self.parameters_names = parameters_names
|
||||
self.show_dominant_parameters = show_dominant_parameters
|
||||
|
||||
def __setstate__(self, state):
|
||||
super(ScaledAdam, self).__setstate__(state)
|
||||
|
||||
@torch.no_grad()
|
||||
def step(self, closure=None):
|
||||
"""Performs a single optimization step.
|
||||
|
||||
Arguments:
|
||||
closure (callable, optional): A closure that reevaluates the model
|
||||
and returns the loss.
|
||||
"""
|
||||
loss = None
|
||||
if closure is not None:
|
||||
with torch.enable_grad():
|
||||
loss = closure()
|
||||
|
||||
batch = True
|
||||
|
||||
for group, group_params_names in zip(self.param_groups, self.parameters_names):
|
||||
with self.batched_params(group["params"], group_params_names) as batches:
|
||||
# batches is list of pairs (stacked_param, state). stacked_param is like
|
||||
# a regular parameter, and will have a .grad, but the 1st dim corresponds to
|
||||
# a stacking dim, it is not a real dim.
|
||||
|
||||
if len(batches[0][1]) == 0: # if len(first state) == 0: not yet initialized
|
||||
clipping_scale = 1
|
||||
else:
|
||||
clipping_scale = self._get_clipping_scale(group, batches)
|
||||
|
||||
for p, state, _ in batches:
|
||||
# Perform optimization step.
|
||||
# grad is not going to be None, we handled that when creating the batches.
|
||||
grad = p.grad
|
||||
if grad.is_sparse:
|
||||
raise RuntimeError("ScaledAdam optimizer does not support sparse gradients")
|
||||
# State initialization
|
||||
if len(state) == 0:
|
||||
self._init_state(group, p, state)
|
||||
|
||||
self._step_one_batch(group, p, state, clipping_scale)
|
||||
|
||||
return loss
|
||||
|
||||
def _init_state(self, group: dict, p: Tensor, state: dict):
|
||||
"""
|
||||
Initializes state dict for parameter 'p'. Assumes that dim 0 of tensor p
|
||||
is actually the batch dimension, corresponding to batched-together
|
||||
parameters of a given shape.
|
||||
|
||||
|
||||
Args:
|
||||
group: Dict to look up configuration values.
|
||||
p: The parameter that we are initializing the state for
|
||||
state: Dict from string to whatever state we are initializing
|
||||
"""
|
||||
size_update_period = group["size_update_period"]
|
||||
|
||||
state["step"] = 0
|
||||
|
||||
kwargs = {"device": p.device, "dtype": p.dtype}
|
||||
|
||||
# 'delta' implements conventional momentum. There are
|
||||
# several different kinds of update going on, so rather than
|
||||
# compute "exp_avg" like in Adam, we store and decay a
|
||||
# parameter-change "delta", which combines all forms of
|
||||
# update. this is equivalent to how it's done in Adam,
|
||||
# except for the first few steps.
|
||||
state["delta"] = torch.zeros_like(p, memory_format=torch.preserve_format)
|
||||
|
||||
batch_size = p.shape[0]
|
||||
numel = p.numel() // batch_size
|
||||
numel = p.numel()
|
||||
|
||||
if numel > 1:
|
||||
# "param_rms" just periodically records the scalar root-mean-square value of
|
||||
# the parameter tensor.
|
||||
# it has a shape like (batch_size, 1, 1, 1, 1)
|
||||
param_rms = (p**2).mean(dim=list(range(1, p.ndim)), keepdim=True).sqrt()
|
||||
state["param_rms"] = param_rms
|
||||
|
||||
state["scale_exp_avg_sq"] = torch.zeros_like(param_rms)
|
||||
state["scale_grads"] = torch.zeros(size_update_period, *param_rms.shape, **kwargs)
|
||||
|
||||
# exp_avg_sq is the weighted sum of scaled gradients. as in Adam.
|
||||
state["exp_avg_sq"] = torch.zeros_like(p, memory_format=torch.preserve_format)
|
||||
|
||||
def _get_clipping_scale(self, group: dict, tuples: List[Tuple[Tensor, dict, List[str]]]) -> float:
|
||||
"""
|
||||
Returns a scalar factor <= 1.0 that dictates gradient clipping, i.e. we will scale the gradients
|
||||
by this amount before applying the rest of the update.
|
||||
|
||||
Args:
|
||||
group: the parameter group, an item in self.param_groups
|
||||
tuples: a list of tuples of (param, state, param_names)
|
||||
where param is a batched set of parameters,
|
||||
with a .grad (1st dim is batch dim)
|
||||
and state is the state-dict where optimization parameters are kept.
|
||||
param_names is a List[str] while each str is name for a parameter
|
||||
in batched set of parameters "param".
|
||||
"""
|
||||
assert len(tuples) >= 1
|
||||
clipping_scale = group["clipping_scale"]
|
||||
(first_p, first_state, _) = tuples[0]
|
||||
step = first_state["step"]
|
||||
if clipping_scale is None or step == 0:
|
||||
# no clipping. return early on step == 0 because the other
|
||||
# parameters' state won't have been initialized yet.
|
||||
return 1.0
|
||||
clipping_update_period = group["clipping_update_period"]
|
||||
|
||||
tot_sumsq = torch.tensor(0.0, device=first_p.device)
|
||||
for p, state, param_names in tuples:
|
||||
grad = p.grad
|
||||
if grad.is_sparse:
|
||||
raise RuntimeError("ScaledAdam optimizer does not support sparse gradients")
|
||||
if p.numel() == p.shape[0]: # a batch of scalars
|
||||
tot_sumsq += (grad**2).sum() # sum() to change shape [1] to []
|
||||
else:
|
||||
tot_sumsq += ((grad * state["param_rms"]) ** 2).sum()
|
||||
|
||||
tot_norm = tot_sumsq.sqrt()
|
||||
if "model_norms" not in first_state:
|
||||
first_state["model_norms"] = torch.zeros(clipping_update_period, device=p.device)
|
||||
first_state["model_norms"][step % clipping_update_period] = tot_norm
|
||||
|
||||
if step % clipping_update_period == 0:
|
||||
# Print some stats.
|
||||
# We don't reach here if step == 0 because we would have returned
|
||||
# above.
|
||||
sorted_norms = first_state["model_norms"].sort()[0].to("cpu")
|
||||
quartiles = []
|
||||
for n in range(0, 5):
|
||||
index = min(
|
||||
clipping_update_period - 1,
|
||||
(clipping_update_period // 4) * n,
|
||||
)
|
||||
quartiles.append(sorted_norms[index].item())
|
||||
|
||||
median = quartiles[2]
|
||||
threshold = clipping_scale * median
|
||||
first_state["model_norm_threshold"] = threshold
|
||||
percent_clipped = (
|
||||
first_state["num_clipped"] * 100.0 / clipping_update_period if "num_clipped" in first_state else 0.0
|
||||
)
|
||||
first_state["num_clipped"] = 0
|
||||
quartiles = " ".join(["%.3e" % x for x in quartiles])
|
||||
logging.info(
|
||||
f"Clipping_scale={clipping_scale}, grad-norm quartiles {quartiles}, threshold={threshold:.3e}, percent-clipped={percent_clipped:.1f}"
|
||||
)
|
||||
|
||||
if step < clipping_update_period:
|
||||
return 1.0 # We have not yet estimated a norm to clip to.
|
||||
else:
|
||||
try:
|
||||
model_norm_threshold = first_state["model_norm_threshold"]
|
||||
except KeyError:
|
||||
logging.info(
|
||||
"Warning: model_norm_threshold not in state: possibly you changed config when restarting, adding clipping_scale option?"
|
||||
)
|
||||
return 1.0
|
||||
ans = min(1.0, (model_norm_threshold / (tot_norm + 1.0e-20)).item())
|
||||
if ans < 1.0:
|
||||
first_state["num_clipped"] += 1
|
||||
if ans < 0.1:
|
||||
logging.warning(f"Scaling gradients by {ans}, model_norm_threshold={model_norm_threshold}")
|
||||
if self.show_dominant_parameters:
|
||||
assert p.shape[0] == len(param_names)
|
||||
self._show_gradient_dominating_parameter(tuples, tot_sumsq)
|
||||
return ans
|
||||
|
||||
def _show_gradient_dominating_parameter(self, tuples: List[Tuple[Tensor, dict, List[str]]], tot_sumsq: Tensor):
|
||||
"""
|
||||
Show information of parameter which dominating tot_sumsq.
|
||||
|
||||
Args:
|
||||
tuples: a list of tuples of (param, state, param_names)
|
||||
where param is a batched set of parameters,
|
||||
with a .grad (1st dim is batch dim)
|
||||
and state is the state-dict where optimization parameters are kept.
|
||||
param_names is a List[str] while each str is name for a parameter
|
||||
in batched set of parameters "param".
|
||||
tot_sumsq: sumsq of all parameters. Though it's could be calculated
|
||||
from tuples, we still pass it to save some time.
|
||||
"""
|
||||
all_sumsq_orig = {}
|
||||
for p, state, batch_param_names in tuples:
|
||||
# p is a stacked batch parameters.
|
||||
batch_grad = p.grad
|
||||
if p.numel() == p.shape[0]: # a batch of scalars
|
||||
batch_sumsq_orig = batch_grad**2
|
||||
# Dummpy values used by following `zip` statement.
|
||||
batch_rms_orig = torch.ones(p.shape[0])
|
||||
else:
|
||||
batch_rms_orig = state["param_rms"]
|
||||
batch_sumsq_orig = ((batch_grad * batch_rms_orig) ** 2).sum(dim=list(range(1, batch_grad.ndim)))
|
||||
|
||||
for name, sumsq_orig, rms, grad in zip(
|
||||
batch_param_names,
|
||||
batch_sumsq_orig,
|
||||
batch_rms_orig,
|
||||
batch_grad,
|
||||
):
|
||||
proportion_orig = sumsq_orig / tot_sumsq
|
||||
all_sumsq_orig[name] = (proportion_orig, sumsq_orig, rms, grad)
|
||||
|
||||
assert torch.isclose(
|
||||
sum([value[0] for value in all_sumsq_orig.values()]).cpu(),
|
||||
torch.tensor(1.0),
|
||||
)
|
||||
sorted_by_proportion = {
|
||||
k: v
|
||||
for k, v in sorted(
|
||||
all_sumsq_orig.items(),
|
||||
key=lambda item: item[1][0],
|
||||
reverse=True,
|
||||
)
|
||||
}
|
||||
dominant_param_name = next(iter(sorted_by_proportion))
|
||||
(
|
||||
dominant_proportion,
|
||||
dominant_sumsq,
|
||||
dominant_rms,
|
||||
dominant_grad,
|
||||
) = sorted_by_proportion[dominant_param_name]
|
||||
logging.info(
|
||||
f"Parameter Dominating tot_sumsq {dominant_param_name}"
|
||||
f" with proportion {dominant_proportion:.2f},"
|
||||
f" where dominant_sumsq=(grad_sumsq*orig_rms_sq)"
|
||||
f"={dominant_sumsq:.3e},"
|
||||
f" grad_sumsq = {(dominant_grad**2).sum():.3e},"
|
||||
f" orig_rms_sq={(dominant_rms**2).item():.3e}"
|
||||
)
|
||||
|
||||
def _step_one_batch(self, group: dict, p: Tensor, state: dict, clipping_scale: float):
|
||||
"""
|
||||
Do the step for one parameter, which is actually going to be a batch of
|
||||
`real` parameters, with dim 0 as the batch dim.
|
||||
Args:
|
||||
group: dict to look up configuration values
|
||||
p: parameter to update (actually multiple parameters stacked together
|
||||
as a batch)
|
||||
state: state-dict for p, to look up the optimizer state
|
||||
"""
|
||||
lr = group["lr"]
|
||||
size_update_period = group["size_update_period"]
|
||||
beta1 = group["betas"][0]
|
||||
|
||||
grad = p.grad
|
||||
if clipping_scale != 1.0:
|
||||
grad = grad * clipping_scale
|
||||
step = state["step"]
|
||||
delta = state["delta"]
|
||||
|
||||
delta.mul_(beta1)
|
||||
batch_size = p.shape[0]
|
||||
numel = p.numel() // batch_size
|
||||
if numel > 1:
|
||||
# Update the size/scale of p, and set param_rms
|
||||
scale_grads = state["scale_grads"]
|
||||
scale_grads[step % size_update_period] = (p * grad).sum(dim=list(range(1, p.ndim)), keepdim=True)
|
||||
if step % size_update_period == size_update_period - 1:
|
||||
param_rms = state["param_rms"] # shape: (batch_size, 1, 1, ..)
|
||||
param_rms.copy_((p**2).mean(dim=list(range(1, p.ndim)), keepdim=True).sqrt())
|
||||
if step > 0:
|
||||
# self._size_update() learns the overall scale on the
|
||||
# parameter, by shrinking or expanding it.
|
||||
self._size_update(group, scale_grads, p, state)
|
||||
|
||||
if numel == 1:
|
||||
# For parameters with 1 element we just use regular Adam.
|
||||
# Updates delta.
|
||||
self._step_scalar(group, p, state)
|
||||
else:
|
||||
self._step(group, p, state)
|
||||
|
||||
state["step"] = step + 1
|
||||
|
||||
def _size_update(
|
||||
self,
|
||||
group: dict,
|
||||
scale_grads: Tensor,
|
||||
p: Tensor,
|
||||
state: dict,
|
||||
) -> None:
|
||||
"""
|
||||
Called only where p.numel() > 1, this updates the scale of the parameter.
|
||||
If we imagine: p = underlying_param * scale.exp(), and we are doing
|
||||
gradient descent on underlying param and on scale, this function does the update
|
||||
on `scale`.
|
||||
|
||||
Args:
|
||||
group: dict to look up configuration values
|
||||
scale_grads: a tensor of shape (size_update_period, batch_size, 1, 1,...) containing
|
||||
grads w.r.t. the scales.
|
||||
p: The parameter to update
|
||||
state: The state-dict of p
|
||||
"""
|
||||
|
||||
param_rms = state["param_rms"]
|
||||
beta1, beta2 = group["betas"]
|
||||
size_lr = group["lr"] * group["scalar_lr_scale"]
|
||||
param_min_rms = group["param_min_rms"]
|
||||
param_max_rms = group["param_max_rms"]
|
||||
eps = group["eps"]
|
||||
step = state["step"]
|
||||
batch_size = p.shape[0]
|
||||
|
||||
size_update_period = scale_grads.shape[0]
|
||||
# correct beta2 for the size update period: we will have
|
||||
# faster decay at this level.
|
||||
beta2_corr = beta2**size_update_period
|
||||
|
||||
scale_exp_avg_sq = state["scale_exp_avg_sq"] # shape: (batch_size, 1, 1, ..)
|
||||
scale_exp_avg_sq.mul_(beta2_corr).add_(
|
||||
(scale_grads**2).mean(dim=0), # mean over dim `size_update_period`
|
||||
alpha=1 - beta2_corr,
|
||||
) # shape is (batch_size, 1, 1, ...)
|
||||
|
||||
# The 1st time we reach here is when size_step == 1.
|
||||
size_step = (step + 1) // size_update_period
|
||||
bias_correction2 = 1 - beta2_corr**size_step
|
||||
# we don't bother with bias_correction1; this will help prevent divergence
|
||||
# at the start of training.
|
||||
|
||||
denom = scale_exp_avg_sq.sqrt() + eps
|
||||
|
||||
scale_step = -size_lr * (bias_correction2**0.5) * scale_grads.sum(dim=0) / denom
|
||||
|
||||
is_too_small = param_rms < param_min_rms
|
||||
is_too_large = param_rms > param_max_rms
|
||||
|
||||
# when the param gets too small, just don't shrink it any further.
|
||||
scale_step.masked_fill_(is_too_small, 0.0)
|
||||
# when it gets too large, stop it from getting any larger.
|
||||
scale_step.masked_fill_(is_too_large, -size_lr * size_update_period)
|
||||
delta = state["delta"]
|
||||
# the factor of (1-beta1) relates to momentum.
|
||||
delta.add_(p * scale_step, alpha=(1 - beta1))
|
||||
|
||||
def _step(self, group: dict, p: Tensor, state: dict):
|
||||
"""
|
||||
This function does the core update of self.step(), in the case where the members of
|
||||
the batch have more than 1 element.
|
||||
|
||||
Args:
|
||||
group: A dict which will be used to look up configuration values
|
||||
p: The parameter to be updated
|
||||
grad: The grad of p
|
||||
state: The state-dict corresponding to parameter p
|
||||
|
||||
This function modifies p.
|
||||
"""
|
||||
grad = p.grad
|
||||
lr = group["lr"]
|
||||
beta1, beta2 = group["betas"]
|
||||
eps = group["eps"]
|
||||
param_min_rms = group["param_min_rms"]
|
||||
step = state["step"]
|
||||
|
||||
exp_avg_sq = state["exp_avg_sq"]
|
||||
exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=(1 - beta2))
|
||||
|
||||
this_step = state["step"] - (state["zero_step"] if "zero_step" in state else 0)
|
||||
bias_correction2 = 1 - beta2 ** (this_step + 1)
|
||||
if bias_correction2 < 0.99:
|
||||
# note: not in-place.
|
||||
exp_avg_sq = exp_avg_sq * (1.0 / bias_correction2)
|
||||
|
||||
denom = exp_avg_sq.sqrt()
|
||||
denom += eps
|
||||
grad = grad / denom
|
||||
|
||||
alpha = -lr * (1 - beta1) * state["param_rms"].clamp(min=param_min_rms)
|
||||
|
||||
delta = state["delta"]
|
||||
delta.add_(grad * alpha)
|
||||
p.add_(delta)
|
||||
|
||||
def _step_scalar(self, group: dict, p: Tensor, state: dict):
|
||||
"""
|
||||
A simplified form of the core update for scalar tensors, where we cannot get a good
|
||||
estimate of the parameter rms.
|
||||
"""
|
||||
beta1, beta2 = group["betas"]
|
||||
scalar_max = group["scalar_max"]
|
||||
eps = group["eps"]
|
||||
lr = group["lr"] * group["scalar_lr_scale"]
|
||||
grad = p.grad
|
||||
|
||||
exp_avg_sq = state["exp_avg_sq"] # shape: (batch_size,)
|
||||
exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
|
||||
|
||||
# bias_correction2 is like in Adam. Don't bother with bias_correction1;
|
||||
# slower update at the start will help stability anyway.
|
||||
bias_correction2 = 1 - beta2 ** (state["step"] + 1)
|
||||
denom = (exp_avg_sq / bias_correction2).sqrt() + eps
|
||||
|
||||
delta = state["delta"]
|
||||
delta.add_(grad / denom, alpha=-lr * (1 - beta1))
|
||||
p.clamp_(min=-scalar_max, max=scalar_max)
|
||||
p.add_(delta)
|
||||
@ -1,428 +1,112 @@
|
||||
from torch.nn.functional import *
|
||||
from torch.nn.functional import (
|
||||
_mha_shape_check,
|
||||
_canonical_mask,
|
||||
_none_or_dtype,
|
||||
_in_projection_packed,
|
||||
)
|
||||
import torch
|
||||
# Tensor = torch.Tensor
|
||||
# from typing import Callable, List, Optional, Tuple, Union
|
||||
|
||||
|
||||
def multi_head_attention_forward_patched(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
embed_dim_to_check,
|
||||
num_heads,
|
||||
in_proj_weight,
|
||||
in_proj_bias,
|
||||
bias_k,
|
||||
bias_v,
|
||||
add_zero_attn,
|
||||
dropout_p: float,
|
||||
out_proj_weight,
|
||||
out_proj_bias,
|
||||
training=True,
|
||||
key_padding_mask=None,
|
||||
need_weights=True,
|
||||
attn_mask=None,
|
||||
use_separate_proj_weight=False,
|
||||
q_proj_weight=None,
|
||||
k_proj_weight=None,
|
||||
v_proj_weight=None,
|
||||
static_k=None,
|
||||
static_v=None,
|
||||
average_attn_weights=True,
|
||||
is_causal=False,
|
||||
cache=None,
|
||||
):
|
||||
r"""
|
||||
Args:
|
||||
query, key, value: map a query and a set of key-value pairs to an output.
|
||||
See "Attention Is All You Need" for more details.
|
||||
embed_dim_to_check: total dimension of the model.
|
||||
num_heads: parallel attention heads.
|
||||
in_proj_weight, in_proj_bias: input projection weight and bias.
|
||||
bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
|
||||
add_zero_attn: add a new batch of zeros to the key and
|
||||
value sequences at dim=1.
|
||||
dropout_p: probability of an element to be zeroed.
|
||||
out_proj_weight, out_proj_bias: the output projection weight and bias.
|
||||
training: apply dropout if is ``True``.
|
||||
key_padding_mask: if provided, specified padding elements in the key will
|
||||
be ignored by the attention. This is an binary mask. When the value is True,
|
||||
the corresponding value on the attention layer will be filled with -inf.
|
||||
need_weights: output attn_output_weights.
|
||||
Default: `True`
|
||||
Note: `needs_weight` defaults to `True`, but should be set to `False`
|
||||
For best performance when attention weights are not nedeeded.
|
||||
*Setting needs_weights to `True`
|
||||
leads to a significant performance degradation.*
|
||||
attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
|
||||
the batches while a 3D mask allows to specify a different mask for the entries of each batch.
|
||||
is_causal: If specified, applies a causal mask as attention mask, and ignores
|
||||
attn_mask for computing scaled dot product attention.
|
||||
Default: ``False``.
|
||||
.. warning::
|
||||
is_causal is provides a hint that the attn_mask is the
|
||||
causal mask.Providing incorrect hints can result in
|
||||
incorrect execution, including forward and backward
|
||||
compatibility.
|
||||
use_separate_proj_weight: the function accept the proj. weights for query, key,
|
||||
and value in different forms. If false, in_proj_weight will be used, which is
|
||||
a combination of q_proj_weight, k_proj_weight, v_proj_weight.
|
||||
q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias.
|
||||
static_k, static_v: static key and value used for attention operators.
|
||||
average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across heads.
|
||||
Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an effect
|
||||
when ``need_weights=True.``. Default: True
|
||||
|
||||
|
||||
Shape:
|
||||
Inputs:
|
||||
- query: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
|
||||
the embedding dimension.
|
||||
- key: :math:`(S, E)` or :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
|
||||
the embedding dimension.
|
||||
- value: :math:`(S, E)` or :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
|
||||
the embedding dimension.
|
||||
- key_padding_mask: :math:`(S)` or :math:`(N, S)` where N is the batch size, S is the source sequence length.
|
||||
If a FloatTensor is provided, it will be directly added to the value.
|
||||
If a BoolTensor is provided, the positions with the
|
||||
value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
|
||||
- attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
|
||||
3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
|
||||
S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
|
||||
positions. If a BoolTensor is provided, positions with ``True``
|
||||
are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
|
||||
is provided, it will be added to the attention weight.
|
||||
- static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
|
||||
N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
|
||||
- static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
|
||||
N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
|
||||
|
||||
Outputs:
|
||||
- attn_output: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
|
||||
E is the embedding dimension.
|
||||
- attn_output_weights: Only returned when ``need_weights=True``. If ``average_attn_weights=True``, returns
|
||||
attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
|
||||
:math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
|
||||
:math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
|
||||
head of shape :math:`(num_heads, L, S)` when input is unbatched or :math:`(N, num_heads, L, S)`.
|
||||
"""
|
||||
tens_ops = (
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
in_proj_weight,
|
||||
in_proj_bias,
|
||||
bias_k,
|
||||
bias_v,
|
||||
out_proj_weight,
|
||||
out_proj_bias,
|
||||
)
|
||||
if has_torch_function(tens_ops):
|
||||
return handle_torch_function(
|
||||
multi_head_attention_forward,
|
||||
tens_ops,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
embed_dim_to_check,
|
||||
num_heads,
|
||||
in_proj_weight,
|
||||
in_proj_bias,
|
||||
bias_k,
|
||||
bias_v,
|
||||
add_zero_attn,
|
||||
dropout_p,
|
||||
out_proj_weight,
|
||||
out_proj_bias,
|
||||
training=training,
|
||||
key_padding_mask=key_padding_mask,
|
||||
need_weights=need_weights,
|
||||
attn_mask=attn_mask,
|
||||
is_causal=is_causal,
|
||||
use_separate_proj_weight=use_separate_proj_weight,
|
||||
q_proj_weight=q_proj_weight,
|
||||
k_proj_weight=k_proj_weight,
|
||||
v_proj_weight=v_proj_weight,
|
||||
static_k=static_k,
|
||||
static_v=static_v,
|
||||
average_attn_weights=average_attn_weights,
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
|
||||
|
||||
# For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
|
||||
# is batched, run the computation and before returning squeeze the
|
||||
# batch dimension so that the output doesn't carry this temporary batch dimension.
|
||||
if not is_batched:
|
||||
# unsqueeze if the input is unbatched
|
||||
query = query.unsqueeze(1)
|
||||
key = key.unsqueeze(1)
|
||||
value = value.unsqueeze(1)
|
||||
if key_padding_mask is not None:
|
||||
key_padding_mask = key_padding_mask.unsqueeze(0)
|
||||
|
||||
# set up shape vars
|
||||
tgt_len, bsz, embed_dim = query.shape
|
||||
src_len, _, _ = key.shape
|
||||
|
||||
key_padding_mask = _canonical_mask(
|
||||
mask=key_padding_mask,
|
||||
mask_name="key_padding_mask",
|
||||
other_type=_none_or_dtype(attn_mask),
|
||||
other_name="attn_mask",
|
||||
target_type=query.dtype,
|
||||
)
|
||||
|
||||
if is_causal and attn_mask is None:
|
||||
raise RuntimeError(
|
||||
"Need attn_mask if specifying the is_causal hint. "
|
||||
"You may use the Transformer module method "
|
||||
"`generate_square_subsequent_mask` to create this mask."
|
||||
)
|
||||
|
||||
if is_causal and key_padding_mask is None and not need_weights:
|
||||
# when we have a kpm or need weights, we need attn_mask
|
||||
# Otherwise, we use the is_causal hint go as is_causal
|
||||
# indicator to SDPA.
|
||||
attn_mask = None
|
||||
else:
|
||||
attn_mask = _canonical_mask(
|
||||
mask=attn_mask,
|
||||
mask_name="attn_mask",
|
||||
other_type=None,
|
||||
other_name="",
|
||||
target_type=query.dtype,
|
||||
check_other=False,
|
||||
)
|
||||
|
||||
if key_padding_mask is not None:
|
||||
# We have the attn_mask, and use that to merge kpm into it.
|
||||
# Turn off use of is_causal hint, as the merged mask is no
|
||||
# longer causal.
|
||||
is_causal = False
|
||||
|
||||
assert embed_dim == embed_dim_to_check, (
|
||||
f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
|
||||
)
|
||||
if isinstance(embed_dim, torch.Tensor):
|
||||
# embed_dim can be a tensor when JIT tracing
|
||||
head_dim = embed_dim.div(num_heads, rounding_mode="trunc")
|
||||
else:
|
||||
head_dim = embed_dim // num_heads
|
||||
assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
|
||||
if use_separate_proj_weight:
|
||||
# allow MHA to have different embedding dimensions when separate projection weights are used
|
||||
assert key.shape[:2] == value.shape[:2], (
|
||||
f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
|
||||
)
|
||||
else:
|
||||
assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
|
||||
|
||||
#
|
||||
# compute in-projection
|
||||
#
|
||||
if not use_separate_proj_weight:
|
||||
assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
|
||||
q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
|
||||
else:
|
||||
assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
|
||||
assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
|
||||
assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
|
||||
if in_proj_bias is None:
|
||||
b_q = b_k = b_v = None
|
||||
else:
|
||||
b_q, b_k, b_v = in_proj_bias.chunk(3)
|
||||
q, k, v = _in_projection(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
q_proj_weight,
|
||||
k_proj_weight,
|
||||
v_proj_weight,
|
||||
b_q,
|
||||
b_k,
|
||||
b_v,
|
||||
)
|
||||
if cache != None:
|
||||
if cache["first_infer"] == 1:
|
||||
cache["k"][cache["stage"]] = k
|
||||
# print(0,cache["k"].shape)
|
||||
cache["v"][cache["stage"]] = v
|
||||
else: ###12个layer每个都要留自己的cache_kv
|
||||
# print(1,cache["k"].shape)
|
||||
cache["k"][cache["stage"]] = torch.cat(
|
||||
[cache["k"][cache["stage"]], k], 0
|
||||
) ##本来时序是1,但是proj的时候可能transpose了所以时序到0维了
|
||||
cache["v"][cache["stage"]] = torch.cat([cache["v"][cache["stage"]], v], 0)
|
||||
# print(2, cache["k"].shape)
|
||||
src_len = cache["k"][cache["stage"]].shape[0]
|
||||
k = cache["k"][cache["stage"]]
|
||||
v = cache["v"][cache["stage"]]
|
||||
# if attn_mask is not None:
|
||||
# attn_mask=attn_mask[-1:,]
|
||||
# print(attn_mask.shape,attn_mask)
|
||||
cache["stage"] = (cache["stage"] + 1) % cache["all_stage"]
|
||||
# print(2333,cache)
|
||||
# prep attention mask
|
||||
|
||||
attn_mask = _canonical_mask(
|
||||
mask=attn_mask,
|
||||
mask_name="attn_mask",
|
||||
other_type=None,
|
||||
other_name="",
|
||||
target_type=q.dtype,
|
||||
check_other=False,
|
||||
)
|
||||
|
||||
if attn_mask is not None:
|
||||
# ensure attn_mask's dim is 3
|
||||
if attn_mask.dim() == 2:
|
||||
correct_2d_size = (tgt_len, src_len)
|
||||
if attn_mask.shape != correct_2d_size:
|
||||
raise RuntimeError(
|
||||
f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}."
|
||||
)
|
||||
attn_mask = attn_mask.unsqueeze(0)
|
||||
elif attn_mask.dim() == 3:
|
||||
correct_3d_size = (bsz * num_heads, tgt_len, src_len)
|
||||
if attn_mask.shape != correct_3d_size:
|
||||
raise RuntimeError(
|
||||
f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}."
|
||||
)
|
||||
else:
|
||||
raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
|
||||
|
||||
# add bias along batch dimension (currently second)
|
||||
if bias_k is not None and bias_v is not None:
|
||||
assert static_k is None, "bias cannot be added to static key."
|
||||
assert static_v is None, "bias cannot be added to static value."
|
||||
k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
|
||||
v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
|
||||
if attn_mask is not None:
|
||||
attn_mask = pad(attn_mask, (0, 1))
|
||||
if key_padding_mask is not None:
|
||||
key_padding_mask = pad(key_padding_mask, (0, 1))
|
||||
else:
|
||||
assert bias_k is None
|
||||
assert bias_v is None
|
||||
|
||||
#
|
||||
# reshape q, k, v for multihead attention and make em batch first
|
||||
#
|
||||
q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
|
||||
if static_k is None:
|
||||
k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
||||
else:
|
||||
# TODO finish disentangling control flow so we don't do in-projections when statics are passed
|
||||
assert static_k.size(0) == bsz * num_heads, (
|
||||
f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
|
||||
)
|
||||
assert static_k.size(2) == head_dim, f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
|
||||
k = static_k
|
||||
if static_v is None:
|
||||
v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
||||
else:
|
||||
# TODO finish disentangling control flow so we don't do in-projections when statics are passed
|
||||
assert static_v.size(0) == bsz * num_heads, (
|
||||
f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
|
||||
)
|
||||
assert static_v.size(2) == head_dim, f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
|
||||
v = static_v
|
||||
|
||||
# add zero attention along batch dimension (now first)
|
||||
if add_zero_attn:
|
||||
zero_attn_shape = (bsz * num_heads, 1, head_dim)
|
||||
k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
|
||||
v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
|
||||
if attn_mask is not None:
|
||||
attn_mask = pad(attn_mask, (0, 1))
|
||||
if key_padding_mask is not None:
|
||||
key_padding_mask = pad(key_padding_mask, (0, 1))
|
||||
|
||||
# update source sequence length after adjustments
|
||||
src_len = k.size(1)
|
||||
|
||||
# merge key padding and attention masks
|
||||
if key_padding_mask is not None:
|
||||
assert key_padding_mask.shape == (
|
||||
bsz,
|
||||
src_len,
|
||||
), f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
|
||||
key_padding_mask = (
|
||||
key_padding_mask.view(bsz, 1, 1, src_len).expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
|
||||
)
|
||||
if attn_mask is None:
|
||||
attn_mask = key_padding_mask
|
||||
else:
|
||||
attn_mask = attn_mask + key_padding_mask
|
||||
|
||||
# adjust dropout probability
|
||||
if not training:
|
||||
dropout_p = 0.0
|
||||
|
||||
#
|
||||
# (deep breath) calculate attention and out projection
|
||||
#
|
||||
|
||||
if need_weights:
|
||||
B, Nt, E = q.shape
|
||||
q_scaled = q / math.sqrt(E)
|
||||
|
||||
assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
|
||||
|
||||
if attn_mask is not None:
|
||||
attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
|
||||
else:
|
||||
attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
|
||||
attn_output_weights = softmax(attn_output_weights, dim=-1)
|
||||
if dropout_p > 0.0:
|
||||
attn_output_weights = dropout(attn_output_weights, p=dropout_p)
|
||||
|
||||
attn_output = torch.bmm(attn_output_weights, v)
|
||||
|
||||
attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
|
||||
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
|
||||
attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
|
||||
|
||||
# optionally average attention weights over heads
|
||||
attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
|
||||
if average_attn_weights:
|
||||
attn_output_weights = attn_output_weights.mean(dim=1)
|
||||
|
||||
if not is_batched:
|
||||
# squeeze the output if input was unbatched
|
||||
attn_output = attn_output.squeeze(1)
|
||||
attn_output_weights = attn_output_weights.squeeze(0)
|
||||
return attn_output, attn_output_weights
|
||||
else:
|
||||
# attn_mask can be either (L,S) or (N*num_heads, L, S)
|
||||
# if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
|
||||
# in order to match the input for SDPA of (N, num_heads, L, S)
|
||||
if attn_mask is not None:
|
||||
if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
|
||||
attn_mask = attn_mask.unsqueeze(0)
|
||||
else:
|
||||
attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
|
||||
|
||||
q = q.view(bsz, num_heads, tgt_len, head_dim)
|
||||
k = k.view(bsz, num_heads, src_len, head_dim)
|
||||
v = v.view(bsz, num_heads, src_len, head_dim)
|
||||
|
||||
# with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
|
||||
attn_output = scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
|
||||
|
||||
attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
|
||||
|
||||
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
|
||||
attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
|
||||
if not is_batched:
|
||||
# squeeze the output if input was unbatched
|
||||
attn_output = attn_output.squeeze(1)
|
||||
return attn_output, None
|
||||
"""Packed-projection inference attention with per-layer KV caching."""
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
from torch.nn import functional as F
|
||||
|
||||
|
||||
def multi_head_attention_forward_patched(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
embed_dim_to_check,
|
||||
num_heads,
|
||||
in_proj_weight,
|
||||
in_proj_bias,
|
||||
out_proj_weight,
|
||||
out_proj_bias,
|
||||
key_padding_mask=None,
|
||||
need_weights=True,
|
||||
attn_mask=None,
|
||||
average_attn_weights=True,
|
||||
cache=None,
|
||||
):
|
||||
is_batched = F._mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
|
||||
if not is_batched:
|
||||
query, key, value = query.unsqueeze(1), key.unsqueeze(1), value.unsqueeze(1)
|
||||
if key_padding_mask is not None:
|
||||
key_padding_mask = key_padding_mask.unsqueeze(0)
|
||||
|
||||
tgt_len, bsz, embed_dim = query.shape
|
||||
src_len = key.shape[0]
|
||||
key_padding_mask = F._canonical_mask(
|
||||
mask=key_padding_mask, mask_name="key_padding_mask",
|
||||
other_type=F._none_or_dtype(attn_mask), other_name="attn_mask", target_type=query.dtype,
|
||||
)
|
||||
attn_mask = F._canonical_mask(
|
||||
mask=attn_mask, mask_name="attn_mask", other_type=None,
|
||||
other_name="", target_type=query.dtype, check_other=False,
|
||||
)
|
||||
assert embed_dim == embed_dim_to_check, "unexpected attention embedding dimension"
|
||||
head_dim = embed_dim // num_heads
|
||||
assert head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"
|
||||
assert key.shape == value.shape, "key and value shapes must match"
|
||||
q, k, v = F._in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
|
||||
if cache is not None:
|
||||
stage = cache["stage"]
|
||||
if cache["first_infer"] == 1:
|
||||
cache["k"][stage] = k
|
||||
cache["v"][stage] = v
|
||||
else:
|
||||
k = cache["k"][stage] = torch.cat([cache["k"][stage], k], dim=0)
|
||||
v = cache["v"][stage] = torch.cat([cache["v"][stage], v], dim=0)
|
||||
src_len = k.shape[0]
|
||||
cache["stage"] = (stage + 1) % cache["all_stage"]
|
||||
|
||||
attn_mask = F._canonical_mask(
|
||||
mask=attn_mask, mask_name="attn_mask", other_type=None,
|
||||
other_name="", target_type=q.dtype, check_other=False,
|
||||
)
|
||||
if attn_mask is not None:
|
||||
if attn_mask.dim() == 2:
|
||||
expected = (tgt_len, src_len)
|
||||
if attn_mask.shape != expected:
|
||||
raise RuntimeError(f"The 2D attn_mask shape is {attn_mask.shape}, expected {expected}")
|
||||
attn_mask = attn_mask.unsqueeze(0)
|
||||
elif attn_mask.dim() == 3:
|
||||
expected = (bsz * num_heads, tgt_len, src_len)
|
||||
if attn_mask.shape != expected:
|
||||
raise RuntimeError(f"The 3D attn_mask shape is {attn_mask.shape}, expected {expected}")
|
||||
else:
|
||||
raise RuntimeError(f"attn_mask dimension {attn_mask.dim()} is not supported")
|
||||
|
||||
q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
|
||||
k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
||||
v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
||||
src_len = k.size(1)
|
||||
if key_padding_mask is not None:
|
||||
assert key_padding_mask.shape == (bsz, src_len), "unexpected key padding mask shape"
|
||||
key_padding_mask = (
|
||||
key_padding_mask.view(bsz, 1, 1, src_len)
|
||||
.expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
|
||||
)
|
||||
attn_mask = key_padding_mask if attn_mask is None else attn_mask + key_padding_mask
|
||||
|
||||
if need_weights:
|
||||
q_scaled = q / math.sqrt(q.size(-1))
|
||||
weights = (torch.bmm(q_scaled, k.transpose(-2, -1)) if attn_mask is None
|
||||
else torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1)))
|
||||
weights = F.softmax(weights, dim=-1)
|
||||
output = torch.bmm(weights, v)
|
||||
output = output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
|
||||
output = F.linear(output, out_proj_weight, out_proj_bias).view(tgt_len, bsz, embed_dim)
|
||||
weights = weights.view(bsz, num_heads, tgt_len, src_len)
|
||||
if average_attn_weights:
|
||||
weights = weights.mean(dim=1)
|
||||
if not is_batched:
|
||||
output, weights = output.squeeze(1), weights.squeeze(0)
|
||||
return output, weights
|
||||
|
||||
if attn_mask is not None:
|
||||
if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
|
||||
attn_mask = attn_mask.unsqueeze(0)
|
||||
else:
|
||||
attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
|
||||
q = q.view(bsz, num_heads, tgt_len, head_dim)
|
||||
k = k.view(bsz, num_heads, src_len, head_dim)
|
||||
v = v.view(bsz, num_heads, src_len, head_dim)
|
||||
output = F.scaled_dot_product_attention(q, k, v, attn_mask, 0.0, False)
|
||||
output = output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
|
||||
output = F.linear(output, out_proj_weight, out_proj_bias).view(tgt_len, bsz, embed_dim)
|
||||
return (output.squeeze(1) if not is_batched else output), None
|
||||
|
||||
@ -1,85 +0,0 @@
|
||||
from torch.nn.functional import *
|
||||
from torch.nn.functional import (
|
||||
_canonical_mask,
|
||||
)
|
||||
|
||||
|
||||
def multi_head_attention_forward_patched(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
embed_dim_to_check,
|
||||
num_heads,
|
||||
in_proj_weight,
|
||||
in_proj_bias,
|
||||
bias_k,
|
||||
bias_v,
|
||||
add_zero_attn,
|
||||
dropout_p,
|
||||
out_proj_weight,
|
||||
out_proj_bias,
|
||||
training=True,
|
||||
key_padding_mask=None,
|
||||
need_weights=True,
|
||||
attn_mask=None,
|
||||
use_separate_proj_weight=False,
|
||||
q_proj_weight=None,
|
||||
k_proj_weight=None,
|
||||
v_proj_weight=None,
|
||||
static_k=None,
|
||||
static_v=None,
|
||||
average_attn_weights=True,
|
||||
is_causal=False,
|
||||
cache=None,
|
||||
):
|
||||
# set up shape vars
|
||||
_, _, embed_dim = query.shape
|
||||
attn_mask = _canonical_mask(
|
||||
mask=attn_mask,
|
||||
mask_name="attn_mask",
|
||||
other_type=None,
|
||||
other_name="",
|
||||
target_type=query.dtype,
|
||||
check_other=False,
|
||||
)
|
||||
head_dim = embed_dim // num_heads
|
||||
|
||||
proj_qkv = linear(query, in_proj_weight, in_proj_bias)
|
||||
proj_qkv = proj_qkv.unflatten(-1, (3, query.size(-1))).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
|
||||
q, k, v = proj_qkv[0], proj_qkv[1], proj_qkv[2]
|
||||
|
||||
if cache["first_infer"] == 1:
|
||||
cache["k"][cache["stage"]] = k
|
||||
cache["v"][cache["stage"]] = v
|
||||
else:
|
||||
cache["k"][cache["stage"]] = torch.cat([cache["k"][cache["stage"]][:-1], k], 0)
|
||||
cache["v"][cache["stage"]] = torch.cat([cache["v"][cache["stage"]][:-1], v], 0)
|
||||
k = cache["k"][cache["stage"]]
|
||||
v = cache["v"][cache["stage"]]
|
||||
cache["stage"] = (cache["stage"] + 1) % cache["all_stage"]
|
||||
|
||||
attn_mask = _canonical_mask(
|
||||
mask=attn_mask,
|
||||
mask_name="attn_mask",
|
||||
other_type=None,
|
||||
other_name="",
|
||||
target_type=q.dtype,
|
||||
check_other=False,
|
||||
)
|
||||
attn_mask = attn_mask.unsqueeze(0)
|
||||
|
||||
q = q.view(-1, num_heads, head_dim).transpose(0, 1)
|
||||
k = k.view(-1, num_heads, head_dim).transpose(0, 1)
|
||||
v = v.view(-1, num_heads, head_dim).transpose(0, 1)
|
||||
|
||||
dropout_p = 0.0
|
||||
attn_mask = attn_mask.unsqueeze(0)
|
||||
q = q.view(num_heads, -1, head_dim).unsqueeze(0)
|
||||
k = k.view(num_heads, -1, head_dim).unsqueeze(0)
|
||||
v = v.view(num_heads, -1, head_dim).unsqueeze(0)
|
||||
attn_output = scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
|
||||
attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(-1, embed_dim)
|
||||
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
|
||||
attn_output = attn_output.view(-1, 1, attn_output.size(1))
|
||||
|
||||
return attn_output
|
||||
@ -1,320 +0,0 @@
|
||||
# Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
|
||||
#
|
||||
# See ../../../../LICENSE for clarification regarding multiple authors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import random
|
||||
from typing import Optional
|
||||
from typing import Tuple
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
class DoubleSwishFunction(torch.autograd.Function):
|
||||
"""
|
||||
double_swish(x) = x * torch.sigmoid(x-1)
|
||||
This is a definition, originally motivated by its close numerical
|
||||
similarity to swish(swish(x)), where swish(x) = x * sigmoid(x).
|
||||
|
||||
Memory-efficient derivative computation:
|
||||
double_swish(x) = x * s, where s(x) = torch.sigmoid(x-1)
|
||||
double_swish'(x) = d/dx double_swish(x) = x * s'(x) + x' * s(x) = x * s'(x) + s(x).
|
||||
Now, s'(x) = s(x) * (1-s(x)).
|
||||
double_swish'(x) = x * s'(x) + s(x).
|
||||
= x * s(x) * (1-s(x)) + s(x).
|
||||
= double_swish(x) * (1-s(x)) + s(x)
|
||||
... so we just need to remember s(x) but not x itself.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, x: Tensor) -> Tensor:
|
||||
requires_grad = x.requires_grad
|
||||
x_dtype = x.dtype
|
||||
if x.dtype == torch.float16:
|
||||
x = x.to(torch.float32)
|
||||
|
||||
s = torch.sigmoid(x - 1.0)
|
||||
y = x * s
|
||||
|
||||
if requires_grad:
|
||||
deriv = y * (1 - s) + s
|
||||
# notes on derivative of x * sigmoid(x - 1):
|
||||
# https://www.wolframalpha.com/input?i=d%2Fdx+%28x+*+sigmoid%28x-1%29%29
|
||||
# min \simeq -0.043638. Take floor as -0.043637 so it's a lower bund
|
||||
# max \simeq 1.1990. Take ceil to be 1.2 so it's an upper bound.
|
||||
# the combination of "+ torch.rand_like(deriv)" and casting to torch.uint8 (which
|
||||
# floors), should be expectation-preserving.
|
||||
floor = -0.043637
|
||||
ceil = 1.2
|
||||
d_scaled = (deriv - floor) * (255.0 / (ceil - floor)) + torch.rand_like(deriv)
|
||||
if __name__ == "__main__":
|
||||
# for self-testing only.
|
||||
assert d_scaled.min() >= 0.0
|
||||
assert d_scaled.max() < 256.0
|
||||
d_int = d_scaled.to(torch.uint8)
|
||||
ctx.save_for_backward(d_int)
|
||||
if x.dtype == torch.float16 or torch.is_autocast_enabled():
|
||||
y = y.to(torch.float16)
|
||||
return y
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, y_grad: Tensor) -> Tensor:
|
||||
(d,) = ctx.saved_tensors
|
||||
# the same constants as used in forward pass.
|
||||
floor = -0.043637
|
||||
ceil = 1.2
|
||||
d = d * ((ceil - floor) / 255.0) + floor
|
||||
return y_grad * d
|
||||
|
||||
|
||||
class DoubleSwish(torch.nn.Module):
|
||||
def forward(self, x: Tensor) -> Tensor:
|
||||
"""Return double-swish activation function which is an approximation to Swish(Swish(x)),
|
||||
that we approximate closely with x * sigmoid(x-1).
|
||||
"""
|
||||
if torch.jit.is_scripting() or torch.jit.is_tracing():
|
||||
return x * torch.sigmoid(x - 1.0)
|
||||
return DoubleSwishFunction.apply(x)
|
||||
|
||||
|
||||
class ActivationBalancerFunction(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(
|
||||
ctx,
|
||||
x: Tensor,
|
||||
scale_factor: Tensor,
|
||||
sign_factor: Optional[Tensor],
|
||||
channel_dim: int,
|
||||
) -> Tensor:
|
||||
if channel_dim < 0:
|
||||
channel_dim += x.ndim
|
||||
ctx.channel_dim = channel_dim
|
||||
xgt0 = x > 0
|
||||
if sign_factor is None:
|
||||
ctx.save_for_backward(xgt0, scale_factor)
|
||||
else:
|
||||
ctx.save_for_backward(xgt0, scale_factor, sign_factor)
|
||||
return x
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, x_grad: Tensor) -> Tuple[Tensor, None, None, None]:
|
||||
if len(ctx.saved_tensors) == 3:
|
||||
xgt0, scale_factor, sign_factor = ctx.saved_tensors
|
||||
for _ in range(ctx.channel_dim, x_grad.ndim - 1):
|
||||
scale_factor = scale_factor.unsqueeze(-1)
|
||||
sign_factor = sign_factor.unsqueeze(-1)
|
||||
factor = sign_factor + scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
|
||||
else:
|
||||
xgt0, scale_factor = ctx.saved_tensors
|
||||
for _ in range(ctx.channel_dim, x_grad.ndim - 1):
|
||||
scale_factor = scale_factor.unsqueeze(-1)
|
||||
factor = scale_factor * (xgt0.to(x_grad.dtype) - 0.5)
|
||||
neg_delta_grad = x_grad.abs() * factor
|
||||
return (
|
||||
x_grad - neg_delta_grad,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _compute_scale_factor(
|
||||
x: Tensor,
|
||||
channel_dim: int,
|
||||
min_abs: float,
|
||||
max_abs: float,
|
||||
gain_factor: float,
|
||||
max_factor: float,
|
||||
) -> Tensor:
|
||||
if channel_dim < 0:
|
||||
channel_dim += x.ndim
|
||||
sum_dims = [d for d in range(x.ndim) if d != channel_dim]
|
||||
x_abs_mean = torch.mean(x.abs(), dim=sum_dims).to(torch.float32)
|
||||
|
||||
if min_abs == 0.0:
|
||||
below_threshold = 0.0
|
||||
else:
|
||||
# below_threshold is 0 if x_abs_mean > min_abs, can be at most max_factor if
|
||||
# x_abs)_mean , min_abs.
|
||||
below_threshold = ((min_abs - x_abs_mean) * (gain_factor / min_abs)).clamp(min=0, max=max_factor)
|
||||
|
||||
above_threshold = ((x_abs_mean - max_abs) * (gain_factor / max_abs)).clamp(min=0, max=max_factor)
|
||||
|
||||
return below_threshold - above_threshold
|
||||
|
||||
|
||||
def _compute_sign_factor(
|
||||
x: Tensor,
|
||||
channel_dim: int,
|
||||
min_positive: float,
|
||||
max_positive: float,
|
||||
gain_factor: float,
|
||||
max_factor: float,
|
||||
) -> Tensor:
|
||||
if channel_dim < 0:
|
||||
channel_dim += x.ndim
|
||||
sum_dims = [d for d in range(x.ndim) if d != channel_dim]
|
||||
proportion_positive = torch.mean((x > 0).to(torch.float32), dim=sum_dims)
|
||||
if min_positive == 0.0:
|
||||
factor1 = 0.0
|
||||
else:
|
||||
# 0 if proportion_positive >= min_positive, else can be
|
||||
# as large as max_factor.
|
||||
factor1 = ((min_positive - proportion_positive) * (gain_factor / min_positive)).clamp_(min=0, max=max_factor)
|
||||
|
||||
if max_positive == 1.0:
|
||||
factor2 = 0.0
|
||||
else:
|
||||
# 0 if self.proportion_positive <= max_positive, else can be
|
||||
# as large as -max_factor.
|
||||
factor2 = ((proportion_positive - max_positive) * (gain_factor / (1.0 - max_positive))).clamp_(
|
||||
min=0, max=max_factor
|
||||
)
|
||||
sign_factor = factor1 - factor2
|
||||
# require min_positive != 0 or max_positive != 1:
|
||||
assert not isinstance(sign_factor, float)
|
||||
return sign_factor
|
||||
|
||||
|
||||
class ActivationBalancer(torch.nn.Module):
|
||||
"""
|
||||
Modifies the backpropped derivatives of a function to try to encourage, for
|
||||
each channel, that it is positive at least a proportion `threshold` of the
|
||||
time. It does this by multiplying negative derivative values by up to
|
||||
(1+max_factor), and positive derivative values by up to (1-max_factor),
|
||||
interpolated from 1 at the threshold to those extremal values when none
|
||||
of the inputs are positive.
|
||||
|
||||
Args:
|
||||
num_channels: the number of channels
|
||||
channel_dim: the dimension/axis corresponding to the channel, e.g.
|
||||
-1, 0, 1, 2; will be interpreted as an offset from x.ndim if negative.
|
||||
min_positive: the minimum, per channel, of the proportion of the time
|
||||
that (x > 0), below which we start to modify the derivatives.
|
||||
max_positive: the maximum, per channel, of the proportion of the time
|
||||
that (x > 0), above which we start to modify the derivatives.
|
||||
max_factor: the maximum factor by which we modify the derivatives for
|
||||
either the sign constraint or the magnitude constraint;
|
||||
e.g. with max_factor=0.02, the the derivatives would be multiplied by
|
||||
values in the range [0.98..1.02].
|
||||
sign_gain_factor: determines the 'gain' with which we increase the
|
||||
change in gradient once the constraints on min_positive and max_positive
|
||||
are violated.
|
||||
scale_gain_factor: determines the 'gain' with which we increase the
|
||||
change in gradient once the constraints on min_abs and max_abs
|
||||
are violated.
|
||||
min_abs: the minimum average-absolute-value difference from the mean
|
||||
value per channel, which we allow, before we start to modify
|
||||
the derivatives to prevent this.
|
||||
max_abs: the maximum average-absolute-value difference from the mean
|
||||
value per channel, which we allow, before we start to modify
|
||||
the derivatives to prevent this.
|
||||
min_prob: determines the minimum probability with which we modify the
|
||||
gradients for the {min,max}_positive and {min,max}_abs constraints,
|
||||
on each forward(). This is done randomly to prevent all layers
|
||||
from doing it at the same time. Early in training we may use
|
||||
higher probabilities than this; it will decay to this value.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_channels: int,
|
||||
channel_dim: int,
|
||||
min_positive: float = 0.05,
|
||||
max_positive: float = 0.95,
|
||||
max_factor: float = 0.04,
|
||||
sign_gain_factor: float = 0.01,
|
||||
scale_gain_factor: float = 0.02,
|
||||
min_abs: float = 0.2,
|
||||
max_abs: float = 100.0,
|
||||
min_prob: float = 0.1,
|
||||
):
|
||||
super(ActivationBalancer, self).__init__()
|
||||
self.num_channels = num_channels
|
||||
self.channel_dim = channel_dim
|
||||
self.min_positive = min_positive
|
||||
self.max_positive = max_positive
|
||||
self.max_factor = max_factor
|
||||
self.min_abs = min_abs
|
||||
self.max_abs = max_abs
|
||||
self.min_prob = min_prob
|
||||
self.sign_gain_factor = sign_gain_factor
|
||||
self.scale_gain_factor = scale_gain_factor
|
||||
|
||||
# count measures how many times the forward() function has been called.
|
||||
# We occasionally sync this to a tensor called `count`, that exists to
|
||||
# make sure it is synced to disk when we load and save the model.
|
||||
self.cpu_count = 0
|
||||
self.register_buffer("count", torch.tensor(0, dtype=torch.int64))
|
||||
|
||||
def forward(self, x: Tensor) -> Tensor:
|
||||
if torch.jit.is_scripting() or not x.requires_grad or torch.jit.is_tracing():
|
||||
return _no_op(x)
|
||||
|
||||
count = self.cpu_count
|
||||
self.cpu_count += 1
|
||||
|
||||
if random.random() < 0.01:
|
||||
# Occasionally sync self.cpu_count with self.count.
|
||||
# count affects the decay of 'prob'. don't do this on every iter,
|
||||
# because syncing with the GPU is slow.
|
||||
self.cpu_count = max(self.cpu_count, self.count.item())
|
||||
self.count.fill_(self.cpu_count)
|
||||
|
||||
# the prob of doing some work exponentially decreases from 0.5 till it hits
|
||||
# a floor at min_prob (==0.1, by default)
|
||||
prob = max(self.min_prob, 0.5 ** (1 + (count / 4000.0)))
|
||||
|
||||
if random.random() < prob:
|
||||
sign_gain_factor = 0.5
|
||||
if self.min_positive != 0.0 or self.max_positive != 1.0:
|
||||
sign_factor = _compute_sign_factor(
|
||||
x,
|
||||
self.channel_dim,
|
||||
self.min_positive,
|
||||
self.max_positive,
|
||||
gain_factor=self.sign_gain_factor / prob,
|
||||
max_factor=self.max_factor,
|
||||
)
|
||||
else:
|
||||
sign_factor = None
|
||||
|
||||
scale_factor = _compute_scale_factor(
|
||||
x.detach(),
|
||||
self.channel_dim,
|
||||
min_abs=self.min_abs,
|
||||
max_abs=self.max_abs,
|
||||
gain_factor=self.scale_gain_factor / prob,
|
||||
max_factor=self.max_factor,
|
||||
)
|
||||
return ActivationBalancerFunction.apply(
|
||||
x,
|
||||
scale_factor,
|
||||
sign_factor,
|
||||
self.channel_dim,
|
||||
)
|
||||
else:
|
||||
return _no_op(x)
|
||||
|
||||
|
||||
def BalancedDoubleSwish(d_model, channel_dim=-1, max_abs=10.0, min_prob=0.25) -> nn.Sequential:
|
||||
"""
|
||||
ActivationBalancer -> DoubleSwish
|
||||
"""
|
||||
balancer = ActivationBalancer(d_model, channel_dim=channel_dim, max_abs=max_abs, min_prob=min_prob)
|
||||
return nn.Sequential(
|
||||
balancer,
|
||||
DoubleSwish(),
|
||||
)
|
||||
@ -1,9 +1,7 @@
|
||||
# modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/transformer.py
|
||||
import copy
|
||||
import numbers
|
||||
from functools import partial
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
from typing import List
|
||||
from typing import Optional
|
||||
from typing import Tuple
|
||||
@ -11,7 +9,6 @@ from typing import Union
|
||||
|
||||
import torch
|
||||
from AR.modules.activation import MultiheadAttention
|
||||
from AR.modules.scaling import BalancedDoubleSwish
|
||||
from torch import nn
|
||||
from torch import Tensor
|
||||
from torch.nn import functional as F
|
||||
@ -76,48 +73,14 @@ class LayerNorm(nn.Module):
|
||||
return "{normalized_shape}, eps={eps}, elementwise_affine={elementwise_affine}".format(**self.__dict__)
|
||||
|
||||
|
||||
class IdentityNorm(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
d_model: int,
|
||||
eps: float = 1e-5,
|
||||
device=None,
|
||||
dtype=None,
|
||||
) -> None:
|
||||
super(IdentityNorm, self).__init__()
|
||||
|
||||
def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
|
||||
if isinstance(input, tuple):
|
||||
return input
|
||||
|
||||
assert embedding is None
|
||||
return input
|
||||
|
||||
|
||||
class TransformerEncoder(nn.Module):
|
||||
r"""TransformerEncoder is a stack of N encoder layers. Users can build the
|
||||
BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
|
||||
|
||||
Args:
|
||||
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
|
||||
num_layers: the number of sub-encoder-layers in the encoder (required).
|
||||
norm: the layer normalization component (optional).
|
||||
enable_nested_tensor: if True, input will automatically convert to nested tensor
|
||||
(and convert back on output). This will improve the overall performance of
|
||||
TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
|
||||
|
||||
Examples::
|
||||
>>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
|
||||
>>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
|
||||
>>> src = torch.rand(10, 32, 512)
|
||||
>>> out = transformer_encoder(src)
|
||||
"""
|
||||
"""Text-to-semantic encoder stack with an optional inference KV cache."""
|
||||
|
||||
__constants__ = ["norm"]
|
||||
|
||||
def __init__(self, encoder_layer, num_layers, norm=None):
|
||||
super(TransformerEncoder, self).__init__()
|
||||
self.layers = _get_clones(encoder_layer, num_layers)
|
||||
self.layers = nn.ModuleList([copy.deepcopy(encoder_layer) for _ in range(num_layers)])
|
||||
self.num_layers = num_layers
|
||||
self.norm = norm
|
||||
|
||||
@ -126,7 +89,6 @@ class TransformerEncoder(nn.Module):
|
||||
src: Tensor,
|
||||
mask: Optional[Tensor] = None,
|
||||
src_key_padding_mask: Optional[Tensor] = None,
|
||||
return_layer_states: bool = False,
|
||||
cache=None,
|
||||
) -> Tensor:
|
||||
r"""Pass the input through the encoder layers in turn.
|
||||
@ -135,28 +97,10 @@ class TransformerEncoder(nn.Module):
|
||||
src: the sequence to the encoder (required).
|
||||
mask: the mask for the src sequence (optional).
|
||||
src_key_padding_mask: the mask for the src keys per batch (optional).
|
||||
return_layer_states: return layers' state (optional).
|
||||
|
||||
Shape:
|
||||
see the docs in Transformer class.
|
||||
"""
|
||||
if return_layer_states:
|
||||
layer_states = [] # layers' output
|
||||
output = src
|
||||
for mod in self.layers:
|
||||
output = mod(
|
||||
output,
|
||||
src_mask=mask,
|
||||
src_key_padding_mask=src_key_padding_mask,
|
||||
cache=cache,
|
||||
)
|
||||
layer_states.append(output[0])
|
||||
|
||||
if self.norm is not None:
|
||||
output = self.norm(output)
|
||||
|
||||
return layer_states, output
|
||||
|
||||
output = src
|
||||
for mod in self.layers:
|
||||
output = mod(
|
||||
@ -180,79 +124,25 @@ class TransformerEncoderLayer(nn.Module):
|
||||
d_model: int,
|
||||
nhead: int,
|
||||
dim_feedforward: int = 2048,
|
||||
dropout: float = 0.1,
|
||||
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
|
||||
batch_first: bool = False,
|
||||
norm_first: bool = False,
|
||||
device=None,
|
||||
dtype=None,
|
||||
linear1_self_attention_cls: nn.Module = nn.Linear,
|
||||
linear2_self_attention_cls: nn.Module = nn.Linear,
|
||||
linear1_feedforward_cls: nn.Module = nn.Linear,
|
||||
linear2_feedforward_cls: nn.Module = nn.Linear,
|
||||
layer_norm_cls: nn.Module = LayerNorm,
|
||||
layer_norm_eps: float = 1e-5,
|
||||
adaptive_layer_norm=False,
|
||||
) -> None:
|
||||
factory_kwargs = {"device": device, "dtype": dtype}
|
||||
super(TransformerEncoderLayer, self).__init__()
|
||||
# print(233333333333,d_model,nhead)
|
||||
# import os
|
||||
# os._exit(2333333)
|
||||
self.self_attn = MultiheadAttention(
|
||||
d_model, # 512 16
|
||||
d_model,
|
||||
nhead,
|
||||
dropout=dropout,
|
||||
batch_first=batch_first,
|
||||
linear1_cls=linear1_self_attention_cls,
|
||||
linear2_cls=linear2_self_attention_cls,
|
||||
**factory_kwargs,
|
||||
)
|
||||
|
||||
# Implementation of Feedforward model
|
||||
self.linear1 = linear1_feedforward_cls(d_model, dim_feedforward, **factory_kwargs)
|
||||
self.dropout = nn.Dropout(dropout)
|
||||
self.linear2 = linear2_feedforward_cls(dim_feedforward, d_model, **factory_kwargs)
|
||||
|
||||
self.linear1 = nn.Linear(d_model, dim_feedforward, **factory_kwargs)
|
||||
self.linear2 = nn.Linear(dim_feedforward, d_model, **factory_kwargs)
|
||||
self.norm_first = norm_first
|
||||
self.dropout1 = nn.Dropout(dropout)
|
||||
self.dropout2 = nn.Dropout(dropout)
|
||||
|
||||
# Legacy string support for activation function.
|
||||
if isinstance(activation, str):
|
||||
activation = _get_activation_fn(activation)
|
||||
elif isinstance(activation, partial):
|
||||
activation = activation(d_model)
|
||||
elif activation == BalancedDoubleSwish:
|
||||
activation = BalancedDoubleSwish(d_model)
|
||||
|
||||
# # We can't test self.activation in forward() in TorchScript,
|
||||
# # so stash some information about it instead.
|
||||
# if activation is F.relu or isinstance(activation, torch.nn.ReLU):
|
||||
# self.activation_relu_or_gelu = 1
|
||||
# elif activation is F.gelu or isinstance(activation, torch.nn.GELU):
|
||||
# self.activation_relu_or_gelu = 2
|
||||
# else:
|
||||
# self.activation_relu_or_gelu = 0
|
||||
self.activation = activation
|
||||
|
||||
norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
|
||||
if layer_norm_cls == IdentityNorm:
|
||||
norm2 = BalancedBasicNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
|
||||
else:
|
||||
norm2 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
|
||||
|
||||
if adaptive_layer_norm:
|
||||
self.norm1 = AdaptiveLayerNorm(d_model, norm1)
|
||||
self.norm2 = AdaptiveLayerNorm(d_model, norm2)
|
||||
else:
|
||||
self.norm1 = norm1
|
||||
self.norm2 = norm2
|
||||
|
||||
def __setstate__(self, state):
|
||||
super(TransformerEncoderLayer, self).__setstate__(state)
|
||||
if not hasattr(self, "activation"):
|
||||
self.activation = F.relu
|
||||
self.norm1 = LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
|
||||
self.norm2 = LayerNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@ -309,10 +199,6 @@ class TransformerEncoderLayer(nn.Module):
|
||||
key_padding_mask: Optional[Tensor],
|
||||
cache=None,
|
||||
) -> Tensor:
|
||||
# print(x.shape,attn_mask.shape,key_padding_mask)
|
||||
# torch.Size([1, 188, 512]) torch.Size([188, 188]) None
|
||||
# import os
|
||||
# os._exit(23333)
|
||||
x = self.self_attn(
|
||||
x,
|
||||
x,
|
||||
@ -322,41 +208,8 @@ class TransformerEncoderLayer(nn.Module):
|
||||
need_weights=False,
|
||||
cache=cache,
|
||||
)[0]
|
||||
return self.dropout1(x)
|
||||
return x
|
||||
|
||||
# feed forward block
|
||||
def _ff_block(self, x: Tensor) -> Tensor:
|
||||
x = self.linear2(self.dropout(self.activation(self.linear1(x))))
|
||||
return self.dropout2(x)
|
||||
|
||||
|
||||
class AdaptiveLayerNorm(nn.Module):
|
||||
r"""Adaptive Layer Normalization"""
|
||||
|
||||
def __init__(self, d_model, norm) -> None:
|
||||
super(AdaptiveLayerNorm, self).__init__()
|
||||
self.project_layer = nn.Linear(d_model, 2 * d_model)
|
||||
self.norm = norm
|
||||
self.d_model = d_model
|
||||
self.eps = self.norm.eps
|
||||
|
||||
def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
|
||||
if isinstance(input, tuple):
|
||||
input, embedding = input
|
||||
weight, bias = torch.split(
|
||||
self.project_layer(embedding),
|
||||
split_size_or_sections=self.d_model,
|
||||
dim=-1,
|
||||
)
|
||||
return (weight * self.norm(input) + bias, embedding)
|
||||
|
||||
weight, bias = torch.split(
|
||||
self.project_layer(embedding),
|
||||
split_size_or_sections=self.d_model,
|
||||
dim=-1,
|
||||
)
|
||||
return weight * self.norm(input) + bias
|
||||
|
||||
|
||||
def _get_clones(module, N):
|
||||
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
|
||||
return self.linear2(F.relu(self.linear1(x)))
|
||||
|
||||
@ -1,281 +0,0 @@
|
||||
# modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/transformer.py
|
||||
import copy
|
||||
import numbers
|
||||
from functools import partial
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
from typing import List
|
||||
from typing import Optional
|
||||
from typing import Tuple
|
||||
from typing import Union
|
||||
|
||||
import torch
|
||||
from AR.modules.activation_onnx import MultiheadAttention
|
||||
from AR.modules.scaling import BalancedDoubleSwish
|
||||
from torch import nn
|
||||
from torch import Tensor
|
||||
from torch.nn import functional as F
|
||||
|
||||
_shape_t = Union[int, List[int], torch.Size]
|
||||
|
||||
|
||||
class LayerNorm(nn.Module):
|
||||
__constants__ = ["normalized_shape", "eps", "elementwise_affine"]
|
||||
normalized_shape: Tuple[int, ...]
|
||||
eps: float
|
||||
elementwise_affine: bool
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
normalized_shape: _shape_t,
|
||||
eps: float = 1e-5,
|
||||
elementwise_affine: bool = True,
|
||||
device=None,
|
||||
dtype=None,
|
||||
) -> None:
|
||||
factory_kwargs = {"device": device, "dtype": dtype}
|
||||
super(LayerNorm, self).__init__()
|
||||
if isinstance(normalized_shape, numbers.Integral):
|
||||
# mypy error: incompatible types in assignment
|
||||
normalized_shape = (normalized_shape,) # type: ignore[assignment]
|
||||
self.normalized_shape = tuple(normalized_shape) # type: ignore[arg-type]
|
||||
self.eps = eps
|
||||
self.elementwise_affine = elementwise_affine
|
||||
if self.elementwise_affine:
|
||||
self.weight = nn.Parameter(torch.empty(self.normalized_shape, **factory_kwargs))
|
||||
self.bias = nn.Parameter(torch.empty(self.normalized_shape, **factory_kwargs))
|
||||
else:
|
||||
self.register_parameter("weight", None)
|
||||
self.register_parameter("bias", None)
|
||||
|
||||
self.reset_parameters()
|
||||
|
||||
def reset_parameters(self) -> None:
|
||||
if self.elementwise_affine:
|
||||
nn.init.ones_(self.weight)
|
||||
nn.init.zeros_(self.bias)
|
||||
|
||||
def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
|
||||
if isinstance(input, tuple):
|
||||
input, embedding = input
|
||||
return (
|
||||
F.layer_norm(
|
||||
input,
|
||||
self.normalized_shape,
|
||||
self.weight,
|
||||
self.bias,
|
||||
self.eps,
|
||||
),
|
||||
embedding,
|
||||
)
|
||||
|
||||
assert embedding is None
|
||||
return F.layer_norm(input, self.normalized_shape, self.weight, self.bias, self.eps)
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return "{normalized_shape}, eps={eps}, elementwise_affine={elementwise_affine}".format(**self.__dict__)
|
||||
|
||||
|
||||
class IdentityNorm(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
d_model: int,
|
||||
eps: float = 1e-5,
|
||||
device=None,
|
||||
dtype=None,
|
||||
) -> None:
|
||||
super(IdentityNorm, self).__init__()
|
||||
|
||||
def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
|
||||
if isinstance(input, tuple):
|
||||
return input
|
||||
|
||||
assert embedding is None
|
||||
return input
|
||||
|
||||
|
||||
class TransformerEncoder(nn.Module):
|
||||
r"""TransformerEncoder is a stack of N encoder layers. Users can build the
|
||||
BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
|
||||
|
||||
Args:
|
||||
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
|
||||
num_layers: the number of sub-encoder-layers in the encoder (required).
|
||||
norm: the layer normalization component (optional).
|
||||
enable_nested_tensor: if True, input will automatically convert to nested tensor
|
||||
(and convert back on output). This will improve the overall performance of
|
||||
TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
|
||||
|
||||
Examples::
|
||||
>>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
|
||||
>>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
|
||||
>>> src = torch.rand(10, 32, 512)
|
||||
>>> out = transformer_encoder(src)
|
||||
"""
|
||||
|
||||
__constants__ = ["norm"]
|
||||
|
||||
def __init__(self, encoder_layer, num_layers, norm=None):
|
||||
super(TransformerEncoder, self).__init__()
|
||||
self.layers = _get_clones(encoder_layer, num_layers)
|
||||
self.num_layers = num_layers
|
||||
self.norm = norm
|
||||
|
||||
def forward(
|
||||
self,
|
||||
src: Tensor,
|
||||
mask: Optional[Tensor] = None,
|
||||
src_key_padding_mask: Optional[Tensor] = None,
|
||||
return_layer_states: bool = False,
|
||||
cache=None,
|
||||
) -> Tensor:
|
||||
output = src
|
||||
for mod in self.layers:
|
||||
output = mod(
|
||||
output,
|
||||
src_mask=mask,
|
||||
src_key_padding_mask=src_key_padding_mask,
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
if self.norm is not None:
|
||||
output = self.norm(output)
|
||||
|
||||
return output
|
||||
|
||||
|
||||
class TransformerEncoderLayer(nn.Module):
|
||||
__constants__ = ["batch_first", "norm_first"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
d_model: int,
|
||||
nhead: int,
|
||||
dim_feedforward: int = 2048,
|
||||
dropout: float = 0.1,
|
||||
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
|
||||
batch_first: bool = False,
|
||||
norm_first: bool = False,
|
||||
device=None,
|
||||
dtype=None,
|
||||
linear1_self_attention_cls: nn.Module = nn.Linear,
|
||||
linear2_self_attention_cls: nn.Module = nn.Linear,
|
||||
linear1_feedforward_cls: nn.Module = nn.Linear,
|
||||
linear2_feedforward_cls: nn.Module = nn.Linear,
|
||||
layer_norm_cls: nn.Module = LayerNorm,
|
||||
layer_norm_eps: float = 1e-5,
|
||||
adaptive_layer_norm=False,
|
||||
) -> None:
|
||||
factory_kwargs = {"device": device, "dtype": dtype}
|
||||
super(TransformerEncoderLayer, self).__init__()
|
||||
self.self_attn = MultiheadAttention(
|
||||
d_model, # 512 16
|
||||
nhead,
|
||||
dropout=dropout,
|
||||
batch_first=batch_first,
|
||||
linear1_cls=linear1_self_attention_cls,
|
||||
linear2_cls=linear2_self_attention_cls,
|
||||
**factory_kwargs,
|
||||
)
|
||||
self.linear1 = linear1_feedforward_cls(d_model, dim_feedforward, **factory_kwargs)
|
||||
self.dropout = nn.Dropout(dropout)
|
||||
self.linear2 = linear2_feedforward_cls(dim_feedforward, d_model, **factory_kwargs)
|
||||
self.norm_first = norm_first
|
||||
self.dropout1 = nn.Dropout(dropout)
|
||||
self.dropout2 = nn.Dropout(dropout)
|
||||
if isinstance(activation, str):
|
||||
activation = _get_activation_fn(activation)
|
||||
elif isinstance(activation, partial):
|
||||
activation = activation(d_model)
|
||||
elif activation == BalancedDoubleSwish:
|
||||
activation = BalancedDoubleSwish(d_model)
|
||||
self.activation = activation
|
||||
|
||||
norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
|
||||
if layer_norm_cls == IdentityNorm:
|
||||
norm2 = BalancedBasicNorm(d_model, eps=layer_norm_eps, **factory_kwargs)
|
||||
else:
|
||||
norm2 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
|
||||
|
||||
if adaptive_layer_norm:
|
||||
self.norm1 = AdaptiveLayerNorm(d_model, norm1)
|
||||
self.norm2 = AdaptiveLayerNorm(d_model, norm2)
|
||||
else:
|
||||
self.norm1 = norm1
|
||||
self.norm2 = norm2
|
||||
|
||||
def __setstate__(self, state):
|
||||
super(TransformerEncoderLayer, self).__setstate__(state)
|
||||
if not hasattr(self, "activation"):
|
||||
self.activation = F.relu
|
||||
|
||||
def forward(
|
||||
self,
|
||||
src: Tensor,
|
||||
src_mask: Optional[Tensor] = None,
|
||||
src_key_padding_mask: Optional[Tensor] = None,
|
||||
cache=None,
|
||||
) -> Tensor:
|
||||
x = src
|
||||
stage_embedding = None
|
||||
x = self.norm1(
|
||||
x + self._sa_block(x, src_mask, src_key_padding_mask, cache=cache),
|
||||
stage_embedding,
|
||||
)
|
||||
x = self.norm2(x + self._ff_block(x), stage_embedding)
|
||||
|
||||
return x
|
||||
|
||||
def _sa_block(
|
||||
self,
|
||||
x: Tensor,
|
||||
attn_mask: Optional[Tensor],
|
||||
key_padding_mask: Optional[Tensor],
|
||||
cache=None,
|
||||
) -> Tensor:
|
||||
x = self.self_attn(
|
||||
x,
|
||||
x,
|
||||
x,
|
||||
attn_mask=attn_mask,
|
||||
key_padding_mask=key_padding_mask,
|
||||
need_weights=False,
|
||||
cache=cache,
|
||||
)
|
||||
return self.dropout1(x)
|
||||
|
||||
def _ff_block(self, x: Tensor) -> Tensor:
|
||||
x = self.linear2(self.dropout(self.activation(self.linear1(x))))
|
||||
return self.dropout2(x)
|
||||
|
||||
|
||||
class AdaptiveLayerNorm(nn.Module):
|
||||
r"""Adaptive Layer Normalization"""
|
||||
|
||||
def __init__(self, d_model, norm) -> None:
|
||||
super(AdaptiveLayerNorm, self).__init__()
|
||||
self.project_layer = nn.Linear(d_model, 2 * d_model)
|
||||
self.norm = norm
|
||||
self.d_model = d_model
|
||||
self.eps = self.norm.eps
|
||||
|
||||
def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
|
||||
if isinstance(input, tuple):
|
||||
input, embedding = input
|
||||
weight, bias = torch.split(
|
||||
self.project_layer(embedding),
|
||||
split_size_or_sections=self.d_model,
|
||||
dim=-1,
|
||||
)
|
||||
return (weight * self.norm(input) + bias, embedding)
|
||||
|
||||
weight, bias = torch.split(
|
||||
self.project_layer(embedding),
|
||||
split_size_or_sections=self.d_model,
|
||||
dim=-1,
|
||||
)
|
||||
return weight * self.norm(input) + bias
|
||||
|
||||
|
||||
def _get_clones(module, N):
|
||||
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
|
||||
@ -1,72 +0,0 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/text_processing/phonemizer.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
import itertools
|
||||
import re
|
||||
from typing import Dict
|
||||
from typing import List
|
||||
|
||||
import regex
|
||||
from gruut import sentences
|
||||
from gruut.const import Sentence
|
||||
from gruut.const import Word
|
||||
from AR.text_processing.symbols import SYMBOL_TO_ID
|
||||
|
||||
|
||||
class GruutPhonemizer:
|
||||
def __init__(self, language: str):
|
||||
self._phonemizer = sentences
|
||||
self.lang = language
|
||||
self.symbol_to_id = SYMBOL_TO_ID
|
||||
self._special_cases_dict: Dict[str] = {
|
||||
r"\.\.\.": "... ",
|
||||
";": "; ",
|
||||
":": ": ",
|
||||
",": ", ",
|
||||
r"\.": ". ",
|
||||
"!": "! ",
|
||||
r"\?": "? ",
|
||||
"—": "—",
|
||||
"…": "… ",
|
||||
"«": "«",
|
||||
"»": "»",
|
||||
}
|
||||
self._punctuation_regexp: str = rf"([{''.join(self._special_cases_dict.keys())}])"
|
||||
|
||||
def _normalize_punctuation(self, text: str) -> str:
|
||||
text = regex.sub(rf"\pZ+{self._punctuation_regexp}", r"\1", text)
|
||||
text = regex.sub(rf"{self._punctuation_regexp}(\pL)", r"\1 \2", text)
|
||||
text = regex.sub(r"\pZ+", r" ", text)
|
||||
return text.strip()
|
||||
|
||||
def _convert_punctuation(self, word: Word) -> str:
|
||||
if not word.phonemes:
|
||||
return ""
|
||||
if word.phonemes[0] in ["‖", "|"]:
|
||||
return word.text.strip()
|
||||
|
||||
phonemes = "".join(word.phonemes)
|
||||
# remove modifier characters ˈˌː with regex
|
||||
phonemes = re.sub(r"[ˈˌː͡]", "", phonemes)
|
||||
return phonemes.strip()
|
||||
|
||||
def phonemize(self, text: str, espeak: bool = False) -> str:
|
||||
text_to_phonemize: str = self._normalize_punctuation(text)
|
||||
sents: List[Sentence] = [sent for sent in self._phonemizer(text_to_phonemize, lang="en-us", espeak=espeak)]
|
||||
words: List[str] = [self._convert_punctuation(word) for word in itertools.chain(*sents)]
|
||||
return " ".join(words)
|
||||
|
||||
def transform(self, phonemes):
|
||||
# convert phonemes to ids
|
||||
# dictionary is in symbols.py
|
||||
return [self.symbol_to_id[p] for p in phonemes if p in self.symbol_to_id.keys()]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
phonemizer = GruutPhonemizer("en-us")
|
||||
# text -> IPA
|
||||
phonemes = phonemizer.phonemize("Hello, wor-ld ?")
|
||||
print("phonemes:", phonemes)
|
||||
print("len(phonemes):", len(phonemes))
|
||||
phoneme_ids = phonemizer.transform(phonemes)
|
||||
print("phoneme_ids:", phoneme_ids)
|
||||
print("len(phoneme_ids):", len(phoneme_ids))
|
||||
@ -1,12 +0,0 @@
|
||||
# modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/text_processing/symbols.py
|
||||
# reference: https://github.com/lifeiteng/vall-e
|
||||
PAD = "_"
|
||||
PUNCTUATION = ';:,.!?¡¿—…"«»“” '
|
||||
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
IPA_LETTERS = (
|
||||
"ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
|
||||
)
|
||||
SYMBOLS = [PAD] + list(PUNCTUATION) + list(LETTERS) + list(IPA_LETTERS)
|
||||
SPACE_ID = SYMBOLS.index(" ")
|
||||
SYMBOL_TO_ID = {s: i for i, s in enumerate(SYMBOLS)}
|
||||
ID_TO_SYMBOL = {i: s for i, s in enumerate(SYMBOLS)}
|
||||
@ -1,36 +0,0 @@
|
||||
import re
|
||||
|
||||
|
||||
def str2bool(str):
|
||||
return True if str.lower() == "true" else False
|
||||
|
||||
|
||||
def get_newest_ckpt(string_list):
|
||||
# 定义一个正则表达式模式,用于匹配字符串中的数字
|
||||
pattern = r"epoch=(\d+)-step=(\d+)\.ckpt"
|
||||
|
||||
# 使用正则表达式提取每个字符串中的数字信息,并创建一个包含元组的列表
|
||||
extracted_info = []
|
||||
for string in string_list:
|
||||
match = re.match(pattern, string)
|
||||
if match:
|
||||
epoch = int(match.group(1))
|
||||
step = int(match.group(2))
|
||||
extracted_info.append((epoch, step, string))
|
||||
# 按照 epoch 后面的数字和 step 后面的数字进行排序
|
||||
sorted_info = sorted(extracted_info, key=lambda x: (x[0], x[1]), reverse=True)
|
||||
# 获取最新的 ckpt 文件名
|
||||
newest_ckpt = sorted_info[0][2]
|
||||
return newest_ckpt
|
||||
|
||||
|
||||
# 文本存在且不为空时 return True
|
||||
def check_txt_file(file_path):
|
||||
try:
|
||||
with open(file_path, "r") as file:
|
||||
text = file.readline().strip()
|
||||
assert text.strip() != ""
|
||||
return text
|
||||
except Exception:
|
||||
return False
|
||||
return False
|
||||
@ -1,39 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Initialize modules for espnet2 neural networks."""
|
||||
|
||||
import torch
|
||||
from typeguard import check_argument_types
|
||||
|
||||
|
||||
def initialize(model: torch.nn.Module, init: str):
|
||||
"""Initialize weights of a neural network module.
|
||||
|
||||
Parameters are initialized using the given method or distribution.
|
||||
|
||||
Custom initialization routines can be implemented into submodules
|
||||
as function `espnet_initialization_fn` within the custom module.
|
||||
|
||||
Args:
|
||||
model: Target.
|
||||
init: Method of initialization.
|
||||
"""
|
||||
assert check_argument_types()
|
||||
print("init with", init)
|
||||
|
||||
# weight init
|
||||
for p in model.parameters():
|
||||
if p.dim() > 1:
|
||||
if init == "xavier_uniform":
|
||||
torch.nn.init.xavier_uniform_(p.data)
|
||||
elif init == "xavier_normal":
|
||||
torch.nn.init.xavier_normal_(p.data)
|
||||
elif init == "kaiming_uniform":
|
||||
torch.nn.init.kaiming_uniform_(p.data, nonlinearity="relu")
|
||||
elif init == "kaiming_normal":
|
||||
torch.nn.init.kaiming_normal_(p.data, nonlinearity="relu")
|
||||
else:
|
||||
raise ValueError("Unknown initialization: " + init)
|
||||
# bias init
|
||||
for name, p in model.named_parameters():
|
||||
if ".bias" in name and p.dim() == 1:
|
||||
p.data.zero_()
|
||||
@ -1,30 +0,0 @@
|
||||
import sys
|
||||
|
||||
import torch
|
||||
import yaml
|
||||
|
||||
|
||||
def load_yaml_config(path):
|
||||
with open(path) as f:
|
||||
config = yaml.full_load(f)
|
||||
return config
|
||||
|
||||
|
||||
def save_config_to_yaml(config, path):
|
||||
assert path.endswith(".yaml")
|
||||
with open(path, "w") as f:
|
||||
f.write(yaml.dump(config))
|
||||
f.close()
|
||||
|
||||
|
||||
def write_args(args, path):
|
||||
args_dict = dict((name, getattr(args, name)) for name in dir(args) if not name.startswith("_"))
|
||||
with open(path, "a") as args_file:
|
||||
args_file.write("==> torch version: {}\n".format(torch.__version__))
|
||||
args_file.write("==> cudnn version: {}\n".format(torch.backends.cudnn.version()))
|
||||
args_file.write("==> Cmd:\n")
|
||||
args_file.write(str(sys.argv))
|
||||
args_file.write("\n==> args:\n")
|
||||
for k, v in sorted(args_dict.items()):
|
||||
args_file.write(" %s: %s\n" % (str(k), str(v)))
|
||||
args_file.close()
|
||||
@ -1,130 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import mlx.core as mx
|
||||
|
||||
from ..structs_mlx import KVCache
|
||||
from ..t2s_model_abc_mlx import (
|
||||
AttentionABC,
|
||||
KVCacheHND,
|
||||
T2SDecoderABC,
|
||||
TransformerBlockABC,
|
||||
TransformerDecoderABC,
|
||||
)
|
||||
|
||||
|
||||
Array = mx.array
|
||||
|
||||
|
||||
class Attention(AttentionABC):
|
||||
def __init__(self, n_head: int, hidden_dim: int, max_seq_length: int):
|
||||
super().__init__(n_head, hidden_dim, max_seq_length)
|
||||
self.kv_class = KVCacheHND
|
||||
|
||||
def __call__(self, x: Array, input_pos: Array, max_idx: int, kv_cache: KVCache, attn_mask: Array):
|
||||
bsz, seqlen, _ = x.shape
|
||||
|
||||
qkv = self.in_proj(x)
|
||||
|
||||
q, k, v = mx.split(qkv, 3, -1)
|
||||
|
||||
q = q.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
|
||||
k = k.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
|
||||
v = v.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
|
||||
|
||||
kv_cache = self.kv_class.update_cache(input_pos, k, v, kv_cache)
|
||||
|
||||
k, v = kv_cache
|
||||
|
||||
attn = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.scale, mask=attn_mask)
|
||||
|
||||
attn = attn.transpose(0, 2, 1, 3).reshape(bsz, seqlen, -1)
|
||||
|
||||
attn = self.out_proj(attn)
|
||||
|
||||
return attn
|
||||
|
||||
|
||||
class TransformerBlock(TransformerBlockABC):
|
||||
def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int) -> None:
|
||||
super().__init__(n_head, ffn_dim, hidden_dim, max_seq_length)
|
||||
|
||||
self.attention = Attention(n_head, hidden_dim, max_seq_length)
|
||||
|
||||
|
||||
class TransformerDecoder(TransformerDecoderABC):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_dim: int,
|
||||
n_layer: int,
|
||||
n_head: int,
|
||||
ffn_dim: int,
|
||||
vocab_size: int,
|
||||
max_seq_length: int,
|
||||
max_batch_size: int,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
hidden_dim,
|
||||
n_layer,
|
||||
n_head,
|
||||
ffn_dim,
|
||||
vocab_size,
|
||||
max_seq_length,
|
||||
max_batch_size,
|
||||
)
|
||||
|
||||
self.layers = [
|
||||
TransformerBlock(
|
||||
n_head,
|
||||
ffn_dim,
|
||||
hidden_dim,
|
||||
max_seq_length,
|
||||
)
|
||||
for _ in range(n_layer)
|
||||
]
|
||||
|
||||
|
||||
class T2SDecoder(T2SDecoderABC):
|
||||
def __init__(
|
||||
self,
|
||||
config: dict,
|
||||
max_seq_length: int = 1024,
|
||||
max_batch_size: int = 10,
|
||||
) -> None:
|
||||
super().__init__(config, max_seq_length, max_batch_size)
|
||||
|
||||
self.h = TransformerDecoder(
|
||||
self.hidden_dim, self.n_layer, self.n_head, self.ffn_dim, self.vocab_size, max_seq_length, max_batch_size
|
||||
)
|
||||
|
||||
self.kv_class = KVCacheHND
|
||||
|
||||
self.extra_buffer_factory = lambda max_bs, dec: {
|
||||
"attn_mask": mx.zeros((max_bs, dec.n_head, 1, dec.max_seq_length), dtype=mx.bool_)
|
||||
}
|
||||
|
||||
def pre_forward_slots_hook(self, slots, runner):
|
||||
attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
|
||||
max_idx = runner.input_pos_buf[slots].long().max().item()
|
||||
return {"attn_mask": attn_mask_buf[slots], "max_idx": max_idx}
|
||||
|
||||
def post_forward_slots_hook(self, slots, runner) -> None:
|
||||
attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
|
||||
pos = runner.input_pos_buf[slots].long()
|
||||
attn_mask_buf[slots, :, :, pos] = True
|
||||
|
||||
def bind_session_hook(self, session, runner) -> None:
|
||||
slots = session.slot_indices
|
||||
|
||||
prefill_len = session.prefill_len
|
||||
bsz = session.bsz
|
||||
|
||||
range_tensor = mx.arange(self.max_seq_length).reshape(1, 1, 1, self.max_seq_length)
|
||||
prefill_len_expanded = prefill_len.reshape(bsz, 1, 1, 1)
|
||||
attn_mask = range_tensor < prefill_len_expanded
|
||||
|
||||
runner.extra_buffers["attn_mask_buf"][slots] = attn_mask
|
||||
|
||||
def unbind_session_hook(self, session, runner) -> None:
|
||||
slots = session.slot_indices
|
||||
attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
|
||||
attn_mask_buf[slots] = 0
|
||||
@ -1,99 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import mlx.core as mx
|
||||
|
||||
from ..structs_mlx import KVCache
|
||||
from ..t2s_model_abc_mlx import (
|
||||
AttentionABC,
|
||||
KVCacheHND,
|
||||
T2SDecoderABC,
|
||||
TransformerBlockABC,
|
||||
TransformerDecoderABC,
|
||||
)
|
||||
|
||||
|
||||
Array = mx.array
|
||||
|
||||
|
||||
class Attention(AttentionABC):
|
||||
def __init__(self, n_head: int, hidden_dim: int, max_seq_length: int):
|
||||
super().__init__(n_head, hidden_dim, max_seq_length)
|
||||
self.kv_class = KVCacheHND
|
||||
|
||||
def __call__(self, x: Array, input_pos: Array, max_idx: int, kv_cache: KVCache, attn_mask: Array):
|
||||
bsz, seqlen, _ = x.shape
|
||||
|
||||
q, k, v = self.in_proj(x).split(3, axis=-1)
|
||||
|
||||
q, k, v = map(lambda x: x.reshape(bsz, seqlen, self.n_head, self.head_dim), (q, k, v))
|
||||
|
||||
q, k, v = map(lambda x: x.swapaxes(1, 2), (q, k, v))
|
||||
|
||||
kv_cache = self.kv_class.update_cache(input_pos, k, v, kv_cache)
|
||||
|
||||
q, k, v = map(lambda x: x[..., :max_idx, :], (q, *kv_cache))
|
||||
|
||||
mask = attn_mask[..., :max_idx]
|
||||
|
||||
attn = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.scale, mask=mask)
|
||||
|
||||
attn = attn.swapaxes(1, 2).reshape(bsz, seqlen, -1)
|
||||
|
||||
attn = self.out_proj(attn)
|
||||
|
||||
return attn
|
||||
|
||||
|
||||
class TransformerBlock(TransformerBlockABC):
|
||||
def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int) -> None:
|
||||
super().__init__(n_head, ffn_dim, hidden_dim, max_seq_length)
|
||||
|
||||
self.attention = Attention(n_head, hidden_dim, max_seq_length)
|
||||
|
||||
|
||||
class TransformerDecoder(TransformerDecoderABC):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_dim: int,
|
||||
n_layer: int,
|
||||
n_head: int,
|
||||
ffn_dim: int,
|
||||
vocab_size: int,
|
||||
max_seq_length: int,
|
||||
max_batch_size: int,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
hidden_dim,
|
||||
n_layer,
|
||||
n_head,
|
||||
ffn_dim,
|
||||
vocab_size,
|
||||
max_seq_length,
|
||||
max_batch_size,
|
||||
)
|
||||
|
||||
self.layers = [
|
||||
TransformerBlock(
|
||||
n_head,
|
||||
ffn_dim,
|
||||
hidden_dim,
|
||||
max_seq_length,
|
||||
)
|
||||
for _ in range(n_layer)
|
||||
]
|
||||
|
||||
|
||||
class T2SDecoder(T2SDecoderABC):
|
||||
def __init__(
|
||||
self,
|
||||
config: dict,
|
||||
max_seq_length: int = 1024,
|
||||
max_batch_size: int = 10,
|
||||
) -> None:
|
||||
super().__init__(config, max_seq_length, max_batch_size)
|
||||
|
||||
self.h = TransformerDecoder(
|
||||
self.hidden_dim, self.n_layer, self.n_head, self.ffn_dim, self.vocab_size, max_seq_length, max_batch_size
|
||||
)
|
||||
|
||||
self.kv_class = KVCacheHND
|
||||
@ -1,324 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from collections import deque
|
||||
from collections.abc import MutableSequence
|
||||
from typing import Optional, TypeVar
|
||||
|
||||
import mlx.core as mx
|
||||
import torch
|
||||
|
||||
from ...logger import timer
|
||||
|
||||
from .sample_funcs_mlx import sample_naive_mlx as sample_naive
|
||||
from .structs_mlx import KVCache, T2SRequest, T2SSessionMLX as T2SSession
|
||||
from .t2s_model_abc_mlx import T2SDecoderABC
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
Array = mx.array
|
||||
|
||||
|
||||
def _slice_arrays(obj: T, bsz: int) -> T:
|
||||
if isinstance(obj, Array):
|
||||
if obj.ndim > 0 and obj.shape[0] >= bsz:
|
||||
return obj[:bsz] # type: ignore
|
||||
return obj # type: ignore
|
||||
if isinstance(obj, list):
|
||||
return [_slice_arrays(o, bsz) for o in obj] # type: ignore
|
||||
if isinstance(obj, tuple):
|
||||
return tuple(_slice_arrays(o, bsz) for o in obj) # type: ignore
|
||||
if isinstance(obj, dict):
|
||||
return {k: _slice_arrays(v, bsz) for k, v in obj.items()} # type: ignore
|
||||
return obj
|
||||
|
||||
|
||||
def _synchronize_device(device: torch.device) -> None:
|
||||
device_type = device.type
|
||||
if device_type == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
elif device_type == "mps":
|
||||
torch.mps.synchronize()
|
||||
elif device_type == "xpu":
|
||||
torch.xpu.synchronize()
|
||||
elif device_type == "mtia":
|
||||
torch.mtia.synchronize()
|
||||
elif device_type == "cpu":
|
||||
pass
|
||||
|
||||
|
||||
class ModelRunner:
|
||||
"""Model-side executor handling prefill, decode"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
decoder: T2SDecoderABC,
|
||||
device: mx.Device,
|
||||
dtype: mx.Dtype,
|
||||
waiting_bind: deque[T2SSession],
|
||||
):
|
||||
self.max_batch_size = decoder.max_batch_size
|
||||
|
||||
self.decoder = decoder
|
||||
self.device = device
|
||||
self.dtype = dtype
|
||||
|
||||
self.waiting_bind: deque[T2SSession] = waiting_bind
|
||||
self.slot_sessions: list[Optional[T2SSession]] = [None] * decoder.max_batch_size
|
||||
self.session_slots: dict[int, list[int]] = {}
|
||||
self.bound_sessions: list[T2SSession] = []
|
||||
self.sampler = sample_naive()
|
||||
|
||||
extra_buffer_factory = decoder.extra_buffer_factory
|
||||
is_applicable = decoder.graph_applicable
|
||||
|
||||
cuda_ok = (
|
||||
torch.cuda.is_available() and torch.version.cuda is not None and os.environ.get("CUDAGraph", "1") != "0"
|
||||
)
|
||||
self.graph_applicable = bool(cuda_ok and is_applicable)
|
||||
|
||||
dtype_bias = decoder.bert_proj.bias.dtype
|
||||
|
||||
# Shared runtime buffers for both eager and graph replay
|
||||
self.xy_pos_buf = mx.zeros((self.max_batch_size, 1, decoder.embedding_dim), dtype=dtype_bias)
|
||||
self.xy_dec_buf = mx.zeros_like(self.xy_pos_buf)
|
||||
self.input_pos_buf = mx.zeros((self.max_batch_size,), dtype=mx.int32)
|
||||
self.kv_cache_buf: MutableSequence[KVCache] = decoder.init_cache(self.max_batch_size)
|
||||
|
||||
self.step_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
|
||||
self.prefill_len_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
|
||||
self.x_len_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
|
||||
self.prompt_len_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
|
||||
self.max_step_buf = mx.zeros((self.max_batch_size), dtype=mx.int32)
|
||||
self.completed_buf = mx.zeros((self.max_batch_size), dtype=mx.bool_)
|
||||
self.y_buf = mx.full((self.max_batch_size, decoder.max_seq_length), decoder.EOS, dtype=mx.int32)
|
||||
|
||||
self.top_k_buf = mx.zeros(self.max_batch_size, dtype=mx.int32)
|
||||
self.top_p_buf = mx.zeros(self.max_batch_size, dtype=mx.float32)
|
||||
self.temperature_buf = mx.zeros(self.max_batch_size, dtype=mx.float32)
|
||||
self.repetition_penalty_buf = mx.zeros(self.max_batch_size, dtype=mx.float32)
|
||||
|
||||
self.extra_buffers = extra_buffer_factory(self.max_batch_size, decoder)
|
||||
|
||||
def prefill(self, request: T2SRequest) -> T2SSession:
|
||||
if len(request.x) > self.decoder.max_batch_size:
|
||||
raise ValueError(
|
||||
f"Request batch size {len(request.x)} exceeds decoder max batch size {self.decoder.max_batch_size}"
|
||||
)
|
||||
|
||||
session = T2SSession(
|
||||
self.decoder,
|
||||
request,
|
||||
device=self.device,
|
||||
dtype=self.dtype,
|
||||
)
|
||||
|
||||
kv_cache = self.decoder.init_cache(session.bsz)
|
||||
|
||||
with timer("MLX.Prefill", debug=request.debug):
|
||||
xy_pos = self.decoder.embed(session.x, session.request.prompts, session.bert_feature)
|
||||
xy_dec = self.decoder.h.prefill(xy_pos, kv_cache, session.attn_mask)
|
||||
session.prefill_hidden = mx.take_along_axis(xy_dec, session.input_pos - 1, axis=1)
|
||||
|
||||
session.kv_cache = kv_cache
|
||||
|
||||
session.start_time = time.perf_counter()
|
||||
session.total_tokens = 0
|
||||
return session
|
||||
|
||||
def free_slots(self) -> int:
|
||||
return sum(1 for s in self.slot_sessions if s is None)
|
||||
|
||||
def _bind_waiting_sessions(self) -> None:
|
||||
while self.waiting_bind and self.free_slots() >= self.waiting_bind[0].bsz:
|
||||
session = self.waiting_bind[0]
|
||||
if self.bind_session(session):
|
||||
self.waiting_bind.popleft()
|
||||
else:
|
||||
break
|
||||
|
||||
def _assign_slots(self, bsz: int) -> Optional[list[int]]:
|
||||
indices = [i for i, s in enumerate(self.slot_sessions) if s is None]
|
||||
if len(indices) < bsz:
|
||||
return None
|
||||
return indices[:bsz]
|
||||
|
||||
def bind_session(self, session: T2SSession) -> bool:
|
||||
slots = self._assign_slots(session.bsz)
|
||||
if slots is None:
|
||||
return False
|
||||
|
||||
for slot_idx in slots:
|
||||
self.slot_sessions[slot_idx] = session
|
||||
|
||||
idx_array = mx.array(slots, dtype=mx.int64)
|
||||
take = slice(0, len(slots))
|
||||
|
||||
# Input pos and step
|
||||
mx.put_along_axis(self.input_pos_buf, idx_array, session.input_pos[take], axis=0)
|
||||
self.step_buf[idx_array] = 0
|
||||
|
||||
# Prefill hidden goes straight into xy_dec buffer
|
||||
mx.put_along_axis(self.xy_dec_buf, idx_array, session.prefill_hidden[take], axis=0)
|
||||
|
||||
# KV Cache
|
||||
for (k_buf, v_buf), (k_src, v_src) in zip(self.kv_cache_buf, session.kv_cache):
|
||||
mx.put_along_axis(k_buf, idx_array, k_src[take], axis=0)
|
||||
mx.put_along_axis(v_buf, idx_array, v_src[take], axis=0)
|
||||
|
||||
# Sampling params
|
||||
self.top_k_buf[idx_array] = session.request.top_k
|
||||
self.top_p_buf[idx_array] = session.request.top_p
|
||||
self.temperature_buf[idx_array] = session.request.temperature
|
||||
self.repetition_penalty_buf[idx_array] = session.request.repetition_penalty
|
||||
mx.put_along_axis(self.prefill_len_buf, idx_array, session.prefill_len[take], axis=0)
|
||||
mx.put_along_axis(self.x_len_buf, idx_array, session.x_lens[take], axis=0)
|
||||
self.prompt_len_buf[idx_array] = session.prompt_len
|
||||
max_steps = (
|
||||
session.max_decode_steps
|
||||
if session.request.early_stop_num == -1
|
||||
else min(session.max_decode_steps, session.request.early_stop_num)
|
||||
)
|
||||
self.max_step_buf[idx_array] = max_steps
|
||||
self.completed_buf[idx_array] = False
|
||||
|
||||
# Token buffer
|
||||
self.y_buf[idx_array] = self.decoder.EOS
|
||||
self.y_buf[idx_array, : session.prompt_len] = session.y
|
||||
|
||||
self.session_slots[session.id] = slots
|
||||
session.slot_indices = slots
|
||||
self.decoder.bind_session_hook(session, self)
|
||||
self.bound_sessions.append(session)
|
||||
|
||||
return True
|
||||
|
||||
def unbind_session(self, session: T2SSession) -> None:
|
||||
slots = self.session_slots.pop(session.id, [])
|
||||
for slot_idx in slots:
|
||||
self.slot_sessions[slot_idx] = None
|
||||
self.input_pos_buf[slots] = 0
|
||||
self.step_buf[slots] = 0
|
||||
self.completed_buf[slots] = False
|
||||
self.decoder.unbind_session_hook(session, self)
|
||||
if session in self.bound_sessions:
|
||||
self.bound_sessions.remove(session)
|
||||
|
||||
def decode_step(self) -> list[T2SSession]:
|
||||
if not self.bound_sessions and not self.waiting_bind:
|
||||
return []
|
||||
|
||||
decoder = self.decoder
|
||||
finished_sessions: list[T2SSession] = []
|
||||
|
||||
forward_slots: list[int] = []
|
||||
prefill_slots: list[int] = []
|
||||
for slot_idx, session in enumerate(self.slot_sessions):
|
||||
if session is None:
|
||||
continue
|
||||
if self.step_buf[slot_idx].item() != 0:
|
||||
forward_slots.append(slot_idx)
|
||||
|
||||
debug = any(session.request.debug for session in self.bound_sessions)
|
||||
|
||||
try:
|
||||
if forward_slots:
|
||||
kwds = decoder.pre_forward_slots_hook(forward_slots, self)
|
||||
forward_len = max(forward_slots) + 1
|
||||
self.xy_dec_buf[:forward_len] = decoder.h(
|
||||
self.xy_pos_buf[:forward_len],
|
||||
self.input_pos_buf[:forward_len],
|
||||
_slice_arrays(self.kv_cache_buf, forward_len),
|
||||
**kwds,
|
||||
)
|
||||
|
||||
# Bind any newly ready sessions after decode and before sampling
|
||||
if self.waiting_bind and self.free_slots() > 0:
|
||||
self._bind_waiting_sessions()
|
||||
if not debug:
|
||||
debug = any(session.request.debug for session in self.bound_sessions)
|
||||
|
||||
for slot_idx, session in enumerate(self.slot_sessions):
|
||||
if session is None:
|
||||
continue
|
||||
if session.step_count == 0:
|
||||
prefill_slots.append(slot_idx)
|
||||
|
||||
active_slots = forward_slots + prefill_slots
|
||||
idx_array = mx.array(active_slots, dtype=mx.int32)
|
||||
if not active_slots:
|
||||
return []
|
||||
|
||||
logits_all = decoder.ar_predict_layer(self.xy_dec_buf[idx_array].squeeze(1))
|
||||
|
||||
first_step_mask = mx.equal(self.step_buf[idx_array], 0).astype(mx.bool_)
|
||||
|
||||
if mx.any(first_step_mask):
|
||||
logits_all[first_step_mask, -1] = float("-inf")
|
||||
|
||||
samples: Array = self.sampler(
|
||||
logits=logits_all,
|
||||
valid_lens=self.input_pos_buf[idx_array] + self.prefill_len_buf[idx_array],
|
||||
previous_tokens=self.y_buf[idx_array],
|
||||
repetition_penalty=self.repetition_penalty_buf[idx_array],
|
||||
temperature=self.temperature_buf[idx_array],
|
||||
top_k=self.top_k_buf[idx_array],
|
||||
top_p=self.top_p_buf[idx_array],
|
||||
)
|
||||
|
||||
argmax_token = mx.argmax(logits_all, axis=-1)
|
||||
eos_mask_all = mx.logical_or(mx.equal(argmax_token, decoder.EOS), mx.equal(samples.squeeze(1), decoder.EOS))
|
||||
|
||||
samples_clamp = samples[:]
|
||||
samples_clamp[samples_clamp >= decoder.vocab_size - 1] = decoder.vocab_size - 2
|
||||
|
||||
y_emb_all = decoder.ar_audio_embedding(samples_clamp)
|
||||
pos_offset = self.step_buf[idx_array] + self.prefill_len_buf[idx_array]
|
||||
next_xy_all = decoder.ar_audio_position(pos_offset, y_emb_all)
|
||||
|
||||
sample_vals = samples.squeeze(1)
|
||||
write_pos = self.prompt_len_buf[idx_array] + self.step_buf[idx_array]
|
||||
|
||||
# Only write for slots that are not already done and not EOS
|
||||
write_mask = (~self.completed_buf[idx_array]) & (~eos_mask_all)
|
||||
if mx.any(write_mask):
|
||||
write_slots = idx_array[write_mask]
|
||||
self.y_buf[write_slots, write_pos[write_mask]] = sample_vals[write_mask]
|
||||
self.input_pos_buf[write_slots] += 1
|
||||
|
||||
new_step = self.step_buf[idx_array]
|
||||
new_step[write_mask] += 1
|
||||
forced_stop = new_step >= self.max_step_buf[idx_array]
|
||||
self.step_buf[idx_array] = new_step
|
||||
|
||||
self.completed_buf[idx_array] |= eos_mask_all | forced_stop
|
||||
|
||||
# Update next xy for continuing slots
|
||||
continue_mask = ~(self.completed_buf[idx_array])
|
||||
if mx.any(continue_mask):
|
||||
cont_slots = idx_array[continue_mask]
|
||||
cont_xy = next_xy_all[continue_mask]
|
||||
self.xy_pos_buf[cont_slots] = cont_xy
|
||||
|
||||
# Sync back
|
||||
for slots in list(self.session_slots.values()):
|
||||
if not slots:
|
||||
continue
|
||||
session = self.slot_sessions[slots[0]]
|
||||
if session is None:
|
||||
continue
|
||||
session_step = int(self.step_buf[slots[0]].item())
|
||||
session.step_count = session_step
|
||||
session.total_tokens = int(session_step * session.bsz)
|
||||
session.completed = self.completed_buf[slots]
|
||||
if bool(mx.all(session.completed)):
|
||||
finished_sessions.append(session)
|
||||
self.unbind_session(session)
|
||||
|
||||
decoder.post_forward_slots_hook(forward_slots, self)
|
||||
|
||||
finally:
|
||||
pass
|
||||
|
||||
return finished_sessions
|
||||
@ -1,132 +0,0 @@
|
||||
from functools import partial
|
||||
from typing import Protocol
|
||||
|
||||
import mlx.core as mx
|
||||
|
||||
|
||||
Array = mx.array
|
||||
|
||||
|
||||
class SampleProtocolMLX(Protocol):
|
||||
@staticmethod
|
||||
def __call__(
|
||||
logits: Array,
|
||||
valid_lens: Array,
|
||||
previous_tokens: Array,
|
||||
repetition_penalty: Array,
|
||||
temperature: Array,
|
||||
top_k: Array,
|
||||
top_p: Array,
|
||||
) -> Array: ...
|
||||
|
||||
|
||||
def apply_repetition_penalty(logits: Array, previous_tokens: Array, valid_lens: Array, repetition_penalty: Array):
|
||||
_, T = previous_tokens.shape
|
||||
|
||||
arange_t = mx.arange(T).reshape(1, -1)
|
||||
valid_mask = arange_t < valid_lens.reshape(-1, 1)
|
||||
|
||||
safe_tokens = mx.where(
|
||||
valid_mask,
|
||||
previous_tokens,
|
||||
mx.zeros_like(previous_tokens),
|
||||
) # [B, T]
|
||||
|
||||
# [B, T]
|
||||
score = mx.take_along_axis(logits, safe_tokens, axis=1)
|
||||
|
||||
rp = repetition_penalty.reshape(-1, 1)
|
||||
|
||||
score = mx.where(
|
||||
score < 0,
|
||||
score * rp,
|
||||
score / rp,
|
||||
)
|
||||
|
||||
score = mx.where(
|
||||
valid_mask,
|
||||
score,
|
||||
mx.take_along_axis(logits, safe_tokens, axis=1),
|
||||
)
|
||||
|
||||
logits = mx.put_along_axis(logits, safe_tokens, score, axis=1)
|
||||
|
||||
return logits
|
||||
|
||||
|
||||
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
|
||||
def apply_greedy_sampling(logits: Array):
|
||||
return mx.argmax(logits, axis=-1, keepdims=True).astype(mx.int32)
|
||||
|
||||
|
||||
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
|
||||
def apply_temperature(logits: Array, temperature: Array, temp_mask: Array):
|
||||
temp = temperature[:]
|
||||
temp[temp_mask] = 1
|
||||
return logits / temp
|
||||
|
||||
|
||||
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
|
||||
def apply_top_k(logits: Array, top_k: Array):
|
||||
sorted_logits = -mx.sort(-logits)
|
||||
pivot = mx.take_along_axis(
|
||||
sorted_logits,
|
||||
(top_k - 1).reshape(-1, 1),
|
||||
axis=1,
|
||||
)
|
||||
logits = mx.where(logits < pivot, -mx.inf, logits)
|
||||
return logits
|
||||
|
||||
|
||||
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
|
||||
def apply_top_p(logits: Array, top_p: Array):
|
||||
sorted_indices = mx.argsort(-logits, axis=-1)
|
||||
sorted_logits = mx.take_along_axis(logits, sorted_indices, axis=-1)
|
||||
cum_probs = mx.cumsum(mx.softmax(sorted_logits, axis=-1), axis=-1)
|
||||
sorted_indices_to_remove = cum_probs > top_p
|
||||
sorted_indices_to_remove[:, -1] = False
|
||||
indices_to_remove = mx.zeros_like(logits).astype(mx.bool_)
|
||||
indices_to_remove = mx.put_along_axis(indices_to_remove, sorted_indices, sorted_indices_to_remove, axis=1)
|
||||
logits = mx.where(indices_to_remove, -mx.inf, logits)
|
||||
return logits
|
||||
|
||||
|
||||
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
|
||||
def apply_sampling(logits: Array, greedy_mask: Array):
|
||||
gumbel_noise = mx.random.gumbel(shape=logits.shape, dtype=logits.dtype)
|
||||
idx_next = mx.argmax(logits + gumbel_noise, axis=-1, keepdims=True).astype(mx.int32)
|
||||
|
||||
if mx.any(greedy_mask):
|
||||
idx_greedy = mx.argmax(logits, axis=-1, keepdims=True).astype(mx.int32)
|
||||
idx_next = mx.where(greedy_mask.reshape(-1, 1), idx_greedy, idx_next)
|
||||
return idx_next
|
||||
|
||||
|
||||
class sample_naive_mlx(SampleProtocolMLX):
|
||||
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
|
||||
@staticmethod
|
||||
def __call__(
|
||||
logits: Array,
|
||||
valid_lens: Array,
|
||||
previous_tokens: Array,
|
||||
repetition_penalty: Array,
|
||||
temperature: Array,
|
||||
top_k: Array,
|
||||
top_p: Array,
|
||||
) -> Array:
|
||||
if mx.any(mx.not_equal(repetition_penalty, 1.0)):
|
||||
logits = apply_repetition_penalty(logits, previous_tokens, valid_lens, repetition_penalty)
|
||||
|
||||
greedy_mask = temperature <= 1e-5
|
||||
temp_mask = (temperature < 1.0) & (~greedy_mask)
|
||||
|
||||
if mx.any(temp_mask):
|
||||
logits = apply_temperature(logits, temperature, temp_mask)
|
||||
|
||||
if mx.any(top_k < 1025):
|
||||
logits = apply_top_k(logits, top_k)
|
||||
|
||||
if mx.any(top_p < 1.0):
|
||||
logits = apply_top_p(logits, top_p)
|
||||
|
||||
return apply_sampling(logits, greedy_mask)
|
||||
@ -1,183 +0,0 @@
|
||||
"""
|
||||
Modified From https://github.com/XXXXRT666/GPT-SoVITS
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import MutableSequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional, Protocol, Union
|
||||
|
||||
import mlx.core as mx
|
||||
from rich.progress import Progress, TaskID
|
||||
|
||||
from ...PyTorch.AR.structs import T2SEngineProtocol, T2SRequest, T2SRequestHandle, T2SResult, T2SStreamResponse
|
||||
|
||||
|
||||
Array = mx.array
|
||||
|
||||
|
||||
@dataclass
|
||||
class T2SRequestMLX:
|
||||
x: list[Array]
|
||||
x_lens: Array
|
||||
prompts: Array
|
||||
bert_feature: list[Array]
|
||||
valid_length: int
|
||||
top_k: int = 5
|
||||
top_p: float = 1
|
||||
early_stop_num: int = -1
|
||||
temperature: float = 1.0
|
||||
repetition_penalty: float = 1.35
|
||||
request_id: Union[str, int] = -1
|
||||
stream_interval: Optional[int] = None
|
||||
return_partial: bool = True
|
||||
debug: bool = False
|
||||
|
||||
@classmethod
|
||||
def from_torch(cls, request: T2SRequest) -> T2SRequestMLX:
|
||||
x = list(map(lambda tensor: mx.array(tensor.cpu()), request.x)) # type: ignore
|
||||
x_lens = mx.array(request.x_lens.cpu()) # type: ignore
|
||||
prompts = mx.array(request.prompts.cpu()) # type: ignore
|
||||
bert_feature = list(map(lambda tensor: mx.array(tensor.cpu()), request.bert_feature)) # type: ignore
|
||||
|
||||
return cls(
|
||||
x,
|
||||
x_lens,
|
||||
prompts,
|
||||
bert_feature,
|
||||
request.valid_length,
|
||||
request.top_k,
|
||||
request.top_p,
|
||||
request.early_stop_num,
|
||||
request.temperature,
|
||||
request.repetition_penalty,
|
||||
request.debug,
|
||||
)
|
||||
|
||||
|
||||
KVCache = tuple[Array, ...]
|
||||
|
||||
|
||||
class KVCacheProtocol(Protocol):
|
||||
@staticmethod
|
||||
def empty(kv_cache: KVCache) -> None: ...
|
||||
|
||||
@staticmethod
|
||||
def update_cache(input_pos: Array, k_val: Array, v_val: Array, kv_cache: KVCache) -> KVCache: ...
|
||||
|
||||
@staticmethod
|
||||
def prefill_kv(k_val: Array, v_val: Array, kv_cache: KVCache) -> None: ...
|
||||
|
||||
@staticmethod
|
||||
def init_cache(batch_size: int, max_seq_length: int, n_heads: int, head_dim: int, dtype: mx.Dtype) -> KVCache: ...
|
||||
|
||||
|
||||
class T2SDecoderProtocol(Protocol):
|
||||
max_seq_length: int
|
||||
EOS: int
|
||||
n_head: int
|
||||
|
||||
def embed(self, x: list[Array], y: Array, bert_features: list[Array]) -> Array: ...
|
||||
|
||||
|
||||
cpu = mx.Device(mx.cpu)
|
||||
|
||||
|
||||
class T2SSessionMLX:
|
||||
def __init__(
|
||||
self,
|
||||
decoder: T2SDecoderProtocol,
|
||||
request_torch: T2SRequest,
|
||||
device: mx.Device = cpu,
|
||||
dtype: mx.Dtype = mx.float32,
|
||||
):
|
||||
with mx.stream(device):
|
||||
request = T2SRequestMLX.from_torch(request_torch)
|
||||
|
||||
self.decoder = decoder
|
||||
self.request = request
|
||||
self.device = device
|
||||
self.dtype = dtype
|
||||
|
||||
bsz = len(request.x)
|
||||
prompt_len = request.prompts.shape[-1]
|
||||
self.bsz = bsz
|
||||
|
||||
self.step_count = 0
|
||||
self.request_id = request.request_id or id(self)
|
||||
self.stream_interval = request.stream_interval if request.stream_interval is not None else 0
|
||||
self.last_stream_step = 0
|
||||
|
||||
# Cache in prefill
|
||||
self.kv_cache: MutableSequence[KVCache]
|
||||
|
||||
# Forward args
|
||||
self.x = [i.astype(mx.int32) for i in request.x]
|
||||
self.x_lens = request.x_lens.astype(mx.int32)
|
||||
self.y = request.prompts.astype(mx.int32)
|
||||
self.prompt_len = prompt_len
|
||||
self.bert_feature = [i.astype(dtype) for i in request.bert_feature]
|
||||
|
||||
self.prefill_len = self.x_lens + request.prompts.shape[1]
|
||||
|
||||
self.input_pos = mx.zeros_like(self.prefill_len)
|
||||
self.input_pos += self.prefill_len
|
||||
if bsz == 1:
|
||||
self.input_pos = self.input_pos.squeeze(0) # 30% Performance Improvement in bsz=1
|
||||
|
||||
self.max_decode_steps = min(int(decoder.max_seq_length - int(self.input_pos.max().item())), 640)
|
||||
self.max_decode_steps = max(1, self.max_decode_steps)
|
||||
|
||||
# EOS
|
||||
self.completed = mx.array([False] * len(self.x)).astype(mx.bool_)
|
||||
self.y_results: list[Array] = [None] * len(self.x) # type: ignore
|
||||
|
||||
max_len = int(self.prefill_len.max(-1))
|
||||
attn_mask = mx.zeros(shape=(bsz, max_len, max_len), dtype=mx.bool_)
|
||||
|
||||
for bs in range(bsz):
|
||||
pos = int(self.x_lens[bs])
|
||||
seq_len = pos + prompt_len
|
||||
|
||||
attn_mask[bs, :seq_len, :pos] = True
|
||||
|
||||
ar_mask = ~mx.triu(
|
||||
x=mx.ones(
|
||||
shape=(
|
||||
prompt_len,
|
||||
prompt_len,
|
||||
),
|
||||
dtype=mx.bool_,
|
||||
),
|
||||
k=1,
|
||||
)
|
||||
attn_mask[bs, pos:seq_len, pos:seq_len] = ar_mask
|
||||
|
||||
attn_mask = mx.expand_dims(attn_mask, 1)
|
||||
self.attn_mask = attn_mask
|
||||
|
||||
self.prefill_hidden: Array
|
||||
|
||||
self.start_time: float = 0.0
|
||||
self.total_tokens: int = 0
|
||||
|
||||
self.progress_task: Optional[TaskID] = None
|
||||
self.progress: Optional[Progress] = None
|
||||
|
||||
self.id: int = id(self)
|
||||
self.slot_indices: list[int] = []
|
||||
|
||||
|
||||
__all__ = [
|
||||
"T2SRequestMLX",
|
||||
"T2SSessionMLX",
|
||||
"KVCache",
|
||||
"KVCacheProtocol",
|
||||
"T2SDecoderProtocol",
|
||||
"T2SEngineProtocol",
|
||||
"T2SRequest",
|
||||
"T2SRequestHandle",
|
||||
"T2SResult",
|
||||
"T2SStreamResponse",
|
||||
]
|
||||
@ -1,371 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from collections import deque
|
||||
from importlib import import_module
|
||||
from queue import Empty, SimpleQueue
|
||||
from typing import Literal, Optional, Union
|
||||
|
||||
import mlx.core as mx
|
||||
import torch
|
||||
from rich.progress import BarColumn, Progress, TextColumn
|
||||
|
||||
from ...logger import SpeedColumnToken, Timer, console, logger
|
||||
|
||||
from .runner_mlx import ModelRunner
|
||||
from .structs_mlx import (
|
||||
T2SEngineProtocol,
|
||||
T2SRequest,
|
||||
T2SRequestHandle,
|
||||
T2SResult,
|
||||
T2SSessionMLX as T2SSession,
|
||||
T2SStreamResponse,
|
||||
)
|
||||
from .t2s_model_abc_mlx import T2SDecoderABC
|
||||
|
||||
|
||||
timer = Timer("T2S Engine MLX")
|
||||
|
||||
cpu = mx.Device(mx.cpu)
|
||||
|
||||
empty_result = T2SResult(
|
||||
result=None,
|
||||
infer_speed=(0.0, 0.0),
|
||||
total_tokens=0,
|
||||
status="Error",
|
||||
exception=RuntimeError("Empty Result"),
|
||||
)
|
||||
|
||||
|
||||
def synchronize_device(device: torch.device) -> None:
|
||||
device_type = device.type
|
||||
if device_type == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
elif device_type == "mps":
|
||||
torch.mps.synchronize()
|
||||
elif device_type == "xpu":
|
||||
torch.xpu.synchronize()
|
||||
elif device_type == "mtia":
|
||||
torch.mtia.synchronize()
|
||||
elif device_type == "cpu":
|
||||
pass
|
||||
|
||||
|
||||
class T2SEngine(T2SEngineProtocol):
|
||||
def __init__(
|
||||
self,
|
||||
decoder_model: T2SDecoderABC,
|
||||
device: Union[mx.Device, torch.device] = cpu,
|
||||
dtype: Union[torch.dtype, mx.Dtype] = torch.float32,
|
||||
start_background: bool = True,
|
||||
*args,
|
||||
**kwds,
|
||||
) -> None:
|
||||
if isinstance(device, torch.device):
|
||||
device_type = device.type
|
||||
if device_type == "cpu":
|
||||
self.device = cpu
|
||||
elif device_type == "cuda" or device_type == "mps":
|
||||
self.device = mx.Device(mx.gpu)
|
||||
else:
|
||||
raise RuntimeError(f"Device {device} not supported")
|
||||
elif isinstance(device, mx.Device):
|
||||
self.device = device
|
||||
else:
|
||||
raise RuntimeError(f"Device {device} not supported")
|
||||
|
||||
if dtype == torch.float32:
|
||||
self.dtype = mx.float16 if self.device.type == mx.gpu else mx.float32
|
||||
elif dtype == torch.float16:
|
||||
self.dtype = mx.float16
|
||||
elif dtype == torch.bfloat16:
|
||||
self.dtype = mx.bfloat16
|
||||
elif dtype == mx.float16 or dtype == mx.bfloat16 or dtype == mx.float32:
|
||||
self.dtype = dtype
|
||||
else:
|
||||
raise RuntimeError(f"Dtype {dtype} Not Supported")
|
||||
|
||||
mx.set_default_device(self.device)
|
||||
decoder_model.set_dtype(self.dtype)
|
||||
|
||||
self.decoder_model: T2SDecoderABC = decoder_model
|
||||
self.waiting_bind: deque[T2SSession] = deque()
|
||||
|
||||
self.model_runner = ModelRunner(self.decoder_model, self.device, self.dtype, waiting_bind=self.waiting_bind)
|
||||
|
||||
self.pending_requests: SimpleQueue[tuple[T2SRequest, T2SRequestHandle, bool]] = SimpleQueue()
|
||||
self.handles: dict[Union[str, int], T2SRequestHandle] = {}
|
||||
self._stop_event = threading.Event()
|
||||
self._request_counter = 0
|
||||
self._loop_thread: Optional[threading.Thread] = None
|
||||
|
||||
if start_background:
|
||||
self._loop_thread = threading.Thread(target=self._background_loop, daemon=True)
|
||||
self._loop_thread.start()
|
||||
|
||||
def add_request(
|
||||
self,
|
||||
request: T2SRequest,
|
||||
stream_interval: Optional[int] = None,
|
||||
show_progress: bool = False,
|
||||
) -> T2SRequestHandle:
|
||||
if stream_interval is not None:
|
||||
request.stream_interval = stream_interval
|
||||
if request.request_id is None:
|
||||
self._request_counter += 1
|
||||
request.request_id = f"req-{self._request_counter}"
|
||||
|
||||
handle = T2SRequestHandle(request_id=request.request_id)
|
||||
self.handles[request.request_id] = handle
|
||||
self.pending_requests.put((request, handle, show_progress))
|
||||
|
||||
if self._loop_thread is None or not self._loop_thread.is_alive():
|
||||
self._loop_thread = threading.Thread(target=self._background_loop, daemon=True)
|
||||
self._loop_thread.start()
|
||||
|
||||
return handle
|
||||
|
||||
def stream_generate(self, request: T2SRequest, show_progress: bool = False):
|
||||
"""Generator yielding streaming responses until completion."""
|
||||
handle = self.add_request(request, stream_interval=request.stream_interval, show_progress=show_progress)
|
||||
while True:
|
||||
resp = handle.queue.get()
|
||||
yield resp
|
||||
if resp.finished:
|
||||
break
|
||||
|
||||
def generate(self, request: T2SRequest, show_progress: bool = False):
|
||||
"""Blocking generate that consumes the streaming queue until finished."""
|
||||
final_result = empty_result
|
||||
for response in self.stream_generate(request, show_progress=show_progress):
|
||||
if response.finished:
|
||||
final_result = response.result or T2SResult(
|
||||
status="Error",
|
||||
exception=response.exception,
|
||||
request_id=request.request_id,
|
||||
)
|
||||
return final_result
|
||||
|
||||
def shutdown(self):
|
||||
self._stop_event.set()
|
||||
if self._loop_thread is not None:
|
||||
self._loop_thread.join(timeout=1.0)
|
||||
self._loop_thread = None
|
||||
|
||||
def _emit_stream(
|
||||
self,
|
||||
session: T2SSession,
|
||||
tokens: Optional[list[torch.Tensor]],
|
||||
finished: bool = False,
|
||||
result: Optional[T2SResult] = None,
|
||||
exception: Optional[Exception] = None,
|
||||
):
|
||||
handle = self.handles.get(session.request_id)
|
||||
if handle is None:
|
||||
return
|
||||
|
||||
step = -1 if finished else session.step_count
|
||||
payload = T2SStreamResponse(
|
||||
request_id=session.request_id,
|
||||
step=step,
|
||||
tokens=tokens,
|
||||
finished=finished,
|
||||
result=result,
|
||||
exception=exception,
|
||||
)
|
||||
handle.queue.put(payload)
|
||||
if finished:
|
||||
handle.done = True
|
||||
self.handles.pop(session.request_id, None)
|
||||
|
||||
def _maybe_stream_partial(self, session: T2SSession):
|
||||
if session.stream_interval <= 0:
|
||||
return
|
||||
if session.step_count == 0 or session.step_count - session.last_stream_step < session.stream_interval:
|
||||
return
|
||||
|
||||
start = session.prompt_len + session.last_stream_step
|
||||
end = session.prompt_len + session.step_count
|
||||
tokens = [torch.tensor(self.model_runner.y_buf[session.slot_indices[i], start:end]) for i in range(session.bsz)]
|
||||
self._emit_stream(session, tokens=tokens, finished=False)
|
||||
session.last_stream_step = session.step_count
|
||||
|
||||
def _finalize_session(
|
||||
self,
|
||||
session: T2SSession,
|
||||
exception: Optional[Exception] = None,
|
||||
):
|
||||
request = session.request
|
||||
infer_time = max(time.perf_counter() - session.start_time, 1e-6)
|
||||
infer_speed = (session.total_tokens / infer_time if session.total_tokens else 0.0, infer_time)
|
||||
status: Literal["Success", "Error"] = "Error" if exception else "Success"
|
||||
|
||||
if exception:
|
||||
logger.error(f"T2S request {session.request_id} failed: {exception}")
|
||||
traceback.print_exc()
|
||||
|
||||
runner = self.model_runner
|
||||
tokens_out = [
|
||||
torch.tensor(
|
||||
runner.y_buf[session.slot_indices[i], session.prompt_len : session.prompt_len + session.step_count]
|
||||
)
|
||||
for i in range(min(request.valid_length, session.bsz))
|
||||
]
|
||||
|
||||
result = T2SResult(
|
||||
result=tokens_out if not exception else None,
|
||||
infer_speed=infer_speed,
|
||||
total_tokens=session.total_tokens,
|
||||
status=status,
|
||||
exception=exception,
|
||||
traceback=traceback.format_exc() if exception else None,
|
||||
request_id=session.request_id,
|
||||
)
|
||||
|
||||
self._emit_stream(
|
||||
session,
|
||||
tokens=tokens_out if result.result is not None else None,
|
||||
finished=True,
|
||||
result=result,
|
||||
exception=exception,
|
||||
)
|
||||
|
||||
if session.progress_task is not None and session.progress is not None:
|
||||
try:
|
||||
session.progress.update(
|
||||
session.progress_task,
|
||||
completed=session.progress.tasks[session.progress_task].total,
|
||||
)
|
||||
session.progress.remove_task(session.progress_task)
|
||||
session.progress.stop()
|
||||
except Exception:
|
||||
pass
|
||||
session.progress = None
|
||||
|
||||
def _drain_new_requests(self) -> bool:
|
||||
new_added = False
|
||||
while True:
|
||||
try:
|
||||
request, handle, show_progress = self.pending_requests.get_nowait()
|
||||
except Empty:
|
||||
break
|
||||
|
||||
try:
|
||||
session = self.model_runner.prefill(request)
|
||||
except Exception as e:
|
||||
logger.error(f"Prefill failed for request {request.request_id}: {e}")
|
||||
error_result = T2SResult(
|
||||
status="Error",
|
||||
exception=e,
|
||||
traceback=traceback.format_exc(),
|
||||
request_id=request.request_id,
|
||||
)
|
||||
handle.queue.put(
|
||||
T2SStreamResponse(
|
||||
request_id=request.request_id or "unknown",
|
||||
step=-1,
|
||||
tokens=None,
|
||||
finished=True,
|
||||
result=error_result,
|
||||
exception=e,
|
||||
)
|
||||
)
|
||||
handle.done = True
|
||||
self.handles.pop(request.request_id, None)
|
||||
continue
|
||||
|
||||
total_tokens = max(1, session.max_decode_steps * session.bsz)
|
||||
if show_progress:
|
||||
session.progress = Progress(
|
||||
TextColumn("[cyan]{task.description}"),
|
||||
BarColumn(),
|
||||
TextColumn("{task.completed}/{task.total} tokens"),
|
||||
SpeedColumnToken(show_speed=True),
|
||||
console=console,
|
||||
transient=True,
|
||||
)
|
||||
session.progress.start()
|
||||
session.progress_task = session.progress.add_task(f"T2S[{session.request_id}]", total=total_tokens)
|
||||
self.waiting_bind.append(session)
|
||||
new_added = True
|
||||
return new_added
|
||||
|
||||
def _background_loop(self):
|
||||
torch.set_grad_enabled(False)
|
||||
while not self._stop_event.is_set():
|
||||
self._drain_new_requests()
|
||||
|
||||
if not self.model_runner.bound_sessions:
|
||||
if not self.waiting_bind:
|
||||
time.sleep(0.001)
|
||||
continue
|
||||
|
||||
try:
|
||||
finished_sessions = self.model_runner.decode_step()
|
||||
except Exception as e:
|
||||
for session in list(self.model_runner.bound_sessions):
|
||||
self._finalize_session(session, exception=e)
|
||||
self.model_runner.unbind_session(session)
|
||||
continue
|
||||
|
||||
for session in list(self.model_runner.bound_sessions):
|
||||
self._maybe_stream_partial(session)
|
||||
if session.progress_task is not None and session.progress is not None:
|
||||
session.progress.update(session.progress_task, advance=session.bsz)
|
||||
|
||||
if finished_sessions:
|
||||
for session in finished_sessions:
|
||||
self._finalize_session(session, exception=None)
|
||||
|
||||
def __del__(self):
|
||||
self.shutdown()
|
||||
|
||||
@staticmethod
|
||||
def load_decoder(
|
||||
weights_path: os.PathLike,
|
||||
max_batch_size: int = 1,
|
||||
backend: str = "MLX-Varlen",
|
||||
quantize_mode: Optional[Literal["Affine", "MXFP8"]] = None,
|
||||
compile: bool = False,
|
||||
) -> T2SDecoderABC:
|
||||
logger.info(f"Loading Text2Semantic Weights from {weights_path} with {backend} Backend")
|
||||
dict_s1 = torch.load(weights_path, map_location="cpu", weights_only=True, mmap=True)
|
||||
config = dict_s1["config"]
|
||||
|
||||
module_path = f".backends.{backend.lower().replace('-', '_')}"
|
||||
decoder_cls_name = "T2SDecoder"
|
||||
decoder_mod = import_module(module_path, package=__package__)
|
||||
decoder_cls: type[T2SDecoderABC] = getattr(decoder_mod, decoder_cls_name)
|
||||
decoder: T2SDecoderABC = decoder_cls(config, max_batch_size=max_batch_size)
|
||||
state_dict = dict_s1["weight"]
|
||||
state_dict_mlx = T2SEngine.replace_key(state_dict)
|
||||
|
||||
decoder.load_weights(state_dict_mlx)
|
||||
|
||||
if quantize_mode is not None:
|
||||
decoder.quantize(quantize_mode)
|
||||
logger.info(
|
||||
f"Quantized to {decoder.bits}-Bit with Group Size {decoder.group_size} by {quantize_mode} Quantization"
|
||||
)
|
||||
|
||||
mx.eval(decoder)
|
||||
return decoder
|
||||
|
||||
@staticmethod
|
||||
def replace_key(state_dict: dict[str, torch.Tensor]):
|
||||
state_dict_mlx: list[tuple[str, mx.array]] = []
|
||||
for key, value in state_dict.items():
|
||||
key = (
|
||||
key.replace("model.", "")
|
||||
.replace("in_proj_", "in_proj.")
|
||||
.replace("self_attn", "attention")
|
||||
.replace("linear", "feed_forward.linear")
|
||||
.replace("norm1", "attention_norm")
|
||||
.replace("norm2", "ffn_norm")
|
||||
)
|
||||
value_mlx = mx.array(value.to(torch.float32).cpu().numpy())
|
||||
state_dict_mlx.append((key, value_mlx))
|
||||
return state_dict_mlx
|
||||
@ -1,455 +0,0 @@
|
||||
"""
|
||||
Modified From https://github.com/XXXXRT666/GPT-SoVITS
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable, MutableSequence
|
||||
from typing import TYPE_CHECKING, Any, Literal, Optional
|
||||
|
||||
import mlx.core as mx
|
||||
import mlx.nn as nn
|
||||
from mlx.core import Dtype
|
||||
|
||||
from .structs_mlx import KVCache, KVCacheProtocol, T2SSessionMLX as T2SSession
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .runner_mlx import ModelRunner
|
||||
|
||||
|
||||
Array = mx.array
|
||||
|
||||
|
||||
class TokenEmbedding(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
embedding_dim: int,
|
||||
vocab_size: int,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.vocab_size = vocab_size
|
||||
self.embedding_dim = embedding_dim
|
||||
|
||||
self.word_embeddings = nn.Embedding(self.vocab_size, self.embedding_dim)
|
||||
|
||||
@property
|
||||
def weight(self):
|
||||
return self.word_embeddings.weight
|
||||
|
||||
def embedding(self, index: int):
|
||||
return self.word_embeddings.weight[index]
|
||||
|
||||
def __call__(self, x: Array):
|
||||
x = self.word_embeddings(x)
|
||||
return x
|
||||
|
||||
|
||||
class SinePositionalEmbedding(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
embedding_dim: int,
|
||||
scale: bool = False,
|
||||
max_batch_size: int = 10,
|
||||
max_seq_length: int = 1024,
|
||||
):
|
||||
super().__init__()
|
||||
self.embedding_dim = embedding_dim
|
||||
self.x_scale = math.sqrt(embedding_dim) if scale else 1.0
|
||||
self.alpha = mx.ones(1)
|
||||
self.max_batch_size = max_batch_size
|
||||
self.max_seq_length = max_seq_length
|
||||
|
||||
self.reverse = False
|
||||
self.pe: Optional[Array] = None
|
||||
|
||||
def compute_pe(self, dtype: Dtype):
|
||||
"""Compute the positional encodings."""
|
||||
|
||||
if self.pe is not None and self.pe.dtype == dtype:
|
||||
return
|
||||
|
||||
if self.reverse:
|
||||
position = mx.expand_dims(mx.arange(self.max_seq_length - 1, -1, -1.0), axis=1)
|
||||
else:
|
||||
position = mx.expand_dims(mx.arange(self.max_seq_length), axis=1)
|
||||
div_term = mx.exp(
|
||||
mx.arange(
|
||||
0,
|
||||
self.embedding_dim,
|
||||
2,
|
||||
)
|
||||
* -(math.log(10000.0) / self.embedding_dim)
|
||||
).astype(dtype)
|
||||
pe = mx.zeros((self.max_batch_size, self.max_seq_length, self.embedding_dim)).astype(dtype)
|
||||
|
||||
pe[:, :, 0::2] = mx.sin(position * div_term).astype(dtype)
|
||||
pe[:, :, 1::2] = mx.cos(position * div_term).astype(dtype)
|
||||
|
||||
self.pe = pe
|
||||
|
||||
def __call__(self, input_pos: Array, x: Array):
|
||||
"""
|
||||
Args:
|
||||
input_pos (Array): [batch_size, ]
|
||||
x (Array): [batch_size, 1, embed_dim]
|
||||
|
||||
Returns:
|
||||
embedded_x (Array): [batch_size, 1, embed_dim]
|
||||
"""
|
||||
self.compute_pe(x.dtype)
|
||||
assert self.pe is not None
|
||||
|
||||
batch_size = x.shape[0]
|
||||
pe_values = self.pe[mx.arange(batch_size), input_pos - 1] # (batch_size, embed_dim)
|
||||
|
||||
return x * self.x_scale + self.alpha * mx.expand_dims(pe_values, 1) # (batch_size, 1, embed_dim)
|
||||
|
||||
def prefill(self, x: Array):
|
||||
"""
|
||||
Args:
|
||||
x (Array): [batch_size, seq_len, embed_dim]
|
||||
|
||||
Returns:
|
||||
embedded_x (Array): [batch_size, seq_len, embed_dim]
|
||||
"""
|
||||
self.compute_pe(x.dtype)
|
||||
assert self.pe is not None
|
||||
|
||||
batch_size = x.shape[0]
|
||||
pe_values = self.pe[mx.arange(batch_size), : x.shape[-2]]
|
||||
return x * self.x_scale + self.alpha * pe_values
|
||||
|
||||
|
||||
class KVCacheHND(KVCacheProtocol):
|
||||
@staticmethod
|
||||
def empty(kv_cache):
|
||||
assert len(kv_cache) == 2
|
||||
k_cache, v_cache = kv_cache
|
||||
|
||||
k_cache[:] = 0
|
||||
v_cache[:] = 0
|
||||
|
||||
@staticmethod
|
||||
def update_cache(input_pos, k_val, v_val, kv_cache):
|
||||
# input_pos: [B, ], k_val: [B, H, 1, D]
|
||||
assert len(kv_cache) == 2
|
||||
k_out, v_out = kv_cache
|
||||
ip0 = input_pos - 1
|
||||
|
||||
k_out[:] = mx.put_along_axis(k_out, ip0.reshape(-1, 1, 1, 1), k_val, axis=2)
|
||||
v_out[:] = mx.put_along_axis(v_out, ip0.reshape(-1, 1, 1, 1), v_val, axis=2)
|
||||
|
||||
return k_out, v_out
|
||||
|
||||
@staticmethod
|
||||
def prefill_kv(k_val, v_val, kv_cache):
|
||||
# k_val: [B, H, S, D]
|
||||
assert len(kv_cache) == 2
|
||||
k_cache, v_cache = kv_cache
|
||||
|
||||
k_cache[..., : k_val.shape[2], :] = k_val
|
||||
v_cache[..., : v_val.shape[2], :] = v_val
|
||||
|
||||
@staticmethod
|
||||
def init_cache(batch_size: int, max_seq_length: int, n_heads: int, head_dim: int, dtype: mx.Dtype) -> KVCache:
|
||||
cache_shape = (batch_size, n_heads, max_seq_length, head_dim)
|
||||
|
||||
return (mx.zeros(cache_shape, dtype=dtype), mx.zeros(cache_shape, dtype=dtype))
|
||||
|
||||
|
||||
class AttentionABC(nn.Module, ABC):
|
||||
def __init__(self, n_head: int, hidden_dim: int, max_seq_length: int, *args, **kwds):
|
||||
super().__init__()
|
||||
|
||||
self.n_head = n_head
|
||||
self.hidden_dim = hidden_dim
|
||||
assert hidden_dim % n_head == 0
|
||||
self.head_dim = hidden_dim // n_head
|
||||
|
||||
self.max_seq_length = max_seq_length
|
||||
|
||||
# key, query, value projections for all heads, but in a batch
|
||||
self.in_proj = nn.Linear(hidden_dim, hidden_dim * 3, bias=True)
|
||||
self.out_proj = nn.Linear(hidden_dim, hidden_dim, bias=True)
|
||||
|
||||
self.scale = 1 / math.sqrt(self.head_dim)
|
||||
|
||||
self.kv_class: KVCacheProtocol
|
||||
|
||||
@abstractmethod
|
||||
def __call__(self, x: Array, input_pos: Array, kv_cache: KVCache, attn_mask: Array) -> Array: ...
|
||||
|
||||
def prefill(self, x: Array, kv_cache: KVCache, attn_mask: Array):
|
||||
bsz, seqlen, _ = x.shape
|
||||
|
||||
qkv = self.in_proj(x)
|
||||
|
||||
q, k, v = mx.split(qkv, 3, -1)
|
||||
|
||||
q = q.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
|
||||
k = k.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
|
||||
v = v.reshape(bsz, seqlen, self.n_head, -1).transpose(0, 2, 1, 3)
|
||||
|
||||
self.kv_class.prefill_kv(k, v, kv_cache)
|
||||
|
||||
attn = mx.fast.scaled_dot_product_attention(q, k, v, mask=attn_mask, scale=self.scale)
|
||||
|
||||
attn = mx.nan_to_num(attn)
|
||||
|
||||
attn = attn.transpose(0, 2, 1, 3).reshape(bsz, seqlen, -1)
|
||||
|
||||
output = self.out_proj(attn)
|
||||
|
||||
return output
|
||||
|
||||
|
||||
class FeedForward(nn.Module):
|
||||
def __init__(self, dim: int, hidden_dim: int) -> None:
|
||||
super().__init__()
|
||||
|
||||
self.linear1 = nn.Linear(dim, hidden_dim, bias=True)
|
||||
self.linear2 = nn.Linear(hidden_dim, dim, bias=True)
|
||||
|
||||
def __call__(self, x: Array):
|
||||
return self.linear2(nn.relu(self.linear1(x)))
|
||||
|
||||
|
||||
class TransformerBlockABC(nn.Module, ABC):
|
||||
def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int, *args, **kwds) -> None:
|
||||
super().__init__()
|
||||
|
||||
self.hidden_dim = hidden_dim
|
||||
self.max_seq_length = max_seq_length
|
||||
|
||||
self.attention: AttentionABC
|
||||
|
||||
self.feed_forward = FeedForward(hidden_dim, ffn_dim)
|
||||
self.attention_norm = nn.LayerNorm(self.hidden_dim)
|
||||
self.ffn_norm = nn.LayerNorm(self.hidden_dim)
|
||||
|
||||
def __call__(self, x: Array, input_pos: Array, kv_cache: KVCache, attn_mask: Array):
|
||||
h = self.attention_norm(
|
||||
x
|
||||
+ self.attention(
|
||||
x,
|
||||
input_pos,
|
||||
kv_cache,
|
||||
attn_mask,
|
||||
)
|
||||
)
|
||||
out = self.ffn_norm(h + self.feed_forward(h))
|
||||
return out
|
||||
|
||||
def prefill(self, x: Array, kv_cache: KVCache, attn_mask: Array):
|
||||
h = self.attention_norm(
|
||||
x
|
||||
+ self.attention.prefill(
|
||||
x,
|
||||
kv_cache,
|
||||
attn_mask,
|
||||
)
|
||||
)
|
||||
out = self.ffn_norm(h + self.feed_forward(h))
|
||||
|
||||
return out
|
||||
|
||||
|
||||
class TransformerDecoderABC(nn.Module, ABC):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_dim: int,
|
||||
n_layer: int,
|
||||
n_head: int,
|
||||
ffn_dim: int,
|
||||
vocab_size: int,
|
||||
max_seq_length: int,
|
||||
max_batch_size: int,
|
||||
*args,
|
||||
**kwds,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
self.hidden_dim = hidden_dim
|
||||
self.n_head = n_head
|
||||
assert hidden_dim % n_head == 0
|
||||
|
||||
self.head_dim = hidden_dim // n_head
|
||||
self.vocab_size = vocab_size
|
||||
|
||||
self.n_layer = n_layer
|
||||
|
||||
self.layers: MutableSequence[TransformerBlockABC]
|
||||
|
||||
self.max_seq_length = max_seq_length
|
||||
self.max_batch_size = max_batch_size
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
x: Array,
|
||||
input_pos: Array,
|
||||
kv_caches: MutableSequence[KVCache],
|
||||
*args,
|
||||
**kwds,
|
||||
):
|
||||
for layer, kv_cache in zip(self.layers, kv_caches):
|
||||
x = layer(
|
||||
x,
|
||||
input_pos,
|
||||
kv_cache,
|
||||
*args,
|
||||
**kwds,
|
||||
)
|
||||
|
||||
return x
|
||||
|
||||
def prefill(self, x: Array, kv_caches: MutableSequence[KVCache], mask: Array):
|
||||
for layer, kv_cache in zip(self.layers, kv_caches):
|
||||
x = layer.prefill(
|
||||
x,
|
||||
kv_cache,
|
||||
mask,
|
||||
)
|
||||
return x
|
||||
|
||||
|
||||
class T2SDecoderABC(nn.Module, ABC):
|
||||
def __init__(
|
||||
self,
|
||||
config: dict,
|
||||
max_seq_length: int = 1024,
|
||||
max_batch_size: int = 10,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
hidden_dim: int = config["model"]["hidden_dim"]
|
||||
embedding_dim: int = config["model"]["embedding_dim"]
|
||||
n_head: int = config["model"]["head"]
|
||||
n_layer: int = config["model"]["n_layer"]
|
||||
vocab_size: int = config["model"]["vocab_size"]
|
||||
phoneme_vocab_size: int = config["model"]["phoneme_vocab_size"]
|
||||
EOS: int = config["model"]["EOS"]
|
||||
ffn_dim: int = hidden_dim * 4
|
||||
|
||||
self.n_layer = int(n_layer)
|
||||
self.hidden_dim = int(hidden_dim)
|
||||
self.n_head = int(n_head)
|
||||
assert hidden_dim % n_head == 0
|
||||
|
||||
self.head_dim = int(hidden_dim // n_head)
|
||||
self.embedding_dim = int(embedding_dim)
|
||||
self.ffn_dim = int(ffn_dim)
|
||||
self.vocab_size = int(vocab_size)
|
||||
self.phoneme_vocab_size = int(phoneme_vocab_size)
|
||||
self.max_seq_length = max_seq_length
|
||||
self.max_batch_size = max_batch_size
|
||||
self.EOS = EOS
|
||||
assert self.EOS == self.vocab_size - 1
|
||||
|
||||
self.bert_proj = nn.Linear(1024, self.embedding_dim)
|
||||
self.ar_predict_layer = nn.Linear(self.hidden_dim, self.vocab_size, bias=False)
|
||||
self.h: TransformerDecoderABC
|
||||
|
||||
self.ar_text_embedding = TokenEmbedding(self.embedding_dim, self.phoneme_vocab_size)
|
||||
self.ar_text_position = SinePositionalEmbedding(
|
||||
self.embedding_dim,
|
||||
scale=False,
|
||||
max_batch_size=max_batch_size,
|
||||
max_seq_length=max_seq_length,
|
||||
)
|
||||
self.ar_audio_embedding = TokenEmbedding(self.embedding_dim, self.vocab_size)
|
||||
self.ar_audio_position = SinePositionalEmbedding(
|
||||
self.embedding_dim,
|
||||
scale=False,
|
||||
max_batch_size=max_batch_size,
|
||||
max_seq_length=max_seq_length,
|
||||
)
|
||||
|
||||
self.kv_class: type[KVCacheProtocol]
|
||||
self.extra_buffer_factory: Callable[[int, T2SDecoderABC], dict[str, Array]] = lambda *_: {}
|
||||
|
||||
self.bits: int = -1
|
||||
self.group_size: int = -1
|
||||
|
||||
def init_cache(self, bsz: int = 0, *args, **kwds) -> MutableSequence[KVCache]:
|
||||
bsz = bsz or self.h.max_batch_size
|
||||
assert bsz <= self.h.max_batch_size
|
||||
seq_lens = self.h.max_seq_length
|
||||
dtype = self.bert_proj.bias.dtype
|
||||
cache: MutableSequence[KVCache] = [
|
||||
self.kv_class.init_cache(bsz, seq_lens, self.n_head, self.head_dim, dtype, *args, **kwds)
|
||||
for _ in range(self.n_layer)
|
||||
]
|
||||
mx.eval(cache)
|
||||
return cache
|
||||
|
||||
def embed(
|
||||
self,
|
||||
x: list[Array],
|
||||
y: Array,
|
||||
bert_features: list[Array],
|
||||
):
|
||||
x_len: list[int] = [i.shape[0] for i in x]
|
||||
x_len_max = max(x_len)
|
||||
xy_pos = mx.zeros(
|
||||
(
|
||||
len(x),
|
||||
x_len_max + y.shape[1],
|
||||
self.embedding_dim,
|
||||
),
|
||||
bert_features[0].dtype,
|
||||
)
|
||||
|
||||
bert_features = list(map(lambda x: x.swapaxes(0, 1), bert_features))
|
||||
|
||||
y_len = y.shape[1]
|
||||
y_emb = self.ar_audio_embedding(y)
|
||||
y_pos = self.ar_audio_position.prefill(y_emb)
|
||||
|
||||
for bs, (x_, len_, bert_feature) in enumerate(zip(x, x_len, bert_features)):
|
||||
x_emb = self.ar_text_embedding(x_)
|
||||
bert = self.bert_proj(bert_feature)
|
||||
x_emb = x_emb + bert
|
||||
x_pos = self.ar_text_position.prefill(mx.expand_dims(x_emb, 0))
|
||||
xy_pos[[bs], :len_] = x_pos
|
||||
xy_pos[[bs], len_ : len_ + y_len] = y_pos
|
||||
|
||||
mx.eval(xy_pos)
|
||||
return xy_pos
|
||||
|
||||
# Slot-aware hooks for runner-managed buffers.
|
||||
@abstractmethod
|
||||
def pre_forward_slots_hook(self, slots: list[int], runner: ModelRunner) -> dict[str, Any]:
|
||||
return {}
|
||||
|
||||
@abstractmethod
|
||||
def post_forward_slots_hook(self, slots: list[int], runner: ModelRunner) -> None:
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def bind_session_hook(self, session: T2SSession, runner: ModelRunner) -> None:
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def unbind_session_hook(self, session: T2SSession, runner: ModelRunner) -> None:
|
||||
return
|
||||
|
||||
def quantize(self, mode: Optional[Literal["Affine", "MXFP8"]] = None) -> None:
|
||||
if mode is None:
|
||||
return
|
||||
if mode not in {"Affine", "MXFP8"}:
|
||||
raise ValueError(f"Unsupported quantization mode: {mode}")
|
||||
if mode == "Affine":
|
||||
self.bits = 8
|
||||
self.group_size = 32
|
||||
nn.quantize(self.h, group_size=self.group_size, bits=self.bits, mode="affine")
|
||||
elif mode == "MXFP8":
|
||||
self.bits = 4
|
||||
self.group_size = 32
|
||||
nn.quantize(self.h, group_size=self.group_size, bits=self.bits, mode="mxfp8")
|
||||
|
||||
else:
|
||||
raise ValueError(f"Unsupported Quantization Mode for MLX: {mode}")
|
||||
@ -1,246 +0,0 @@
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import mlx.core as mx
|
||||
import mlx.nn as nn
|
||||
import torch
|
||||
from transformers import BertConfig
|
||||
|
||||
|
||||
Array = mx.array
|
||||
Tensor = torch.Tensor
|
||||
|
||||
|
||||
class MultiHeadAttention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
dims: int,
|
||||
num_heads: int,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
assert dims % num_heads == 0, "The input feature dimensions should be divisible by the number of heads"
|
||||
|
||||
self.num_heads = num_heads
|
||||
self.query_proj = nn.Linear(dims, dims)
|
||||
self.key_proj = nn.Linear(dims, dims)
|
||||
self.value_proj = nn.Linear(dims, dims)
|
||||
self.out_proj = nn.Linear(dims, dims)
|
||||
|
||||
self.scale = math.sqrt(1 / dims)
|
||||
|
||||
def __call__(self, x: Array):
|
||||
B, L, _ = x.shape
|
||||
queries = self.query_proj(x)
|
||||
keys = self.key_proj(x)
|
||||
values = self.value_proj(x)
|
||||
|
||||
num_heads = self.num_heads
|
||||
queries = queries.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3)
|
||||
keys = keys.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3)
|
||||
values = values.reshape(B, L, num_heads, -1).transpose(0, 2, 1, 3)
|
||||
output = mx.fast.scaled_dot_product_attention(queries, keys, values, scale=self.scale)
|
||||
output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
|
||||
return self.out_proj(output)
|
||||
|
||||
|
||||
class TransformerEncoderLayer(nn.Module):
|
||||
"""
|
||||
A transformer encoder layer with (the original BERT) post-normalization.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dims: int,
|
||||
num_heads: int,
|
||||
mlp_dims: int,
|
||||
layer_norm_eps: float = 1e-12,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.attention = MultiHeadAttention(dims, num_heads)
|
||||
self.attention_norm = nn.LayerNorm(dims, eps=layer_norm_eps)
|
||||
self.ffn_norm = nn.LayerNorm(dims, eps=layer_norm_eps)
|
||||
self.linear1 = nn.Linear(dims, mlp_dims)
|
||||
self.linear2 = nn.Linear(mlp_dims, dims)
|
||||
self.gelu = nn.GELU()
|
||||
|
||||
def __call__(self, x: Array) -> Array:
|
||||
attention_out = self.attention(x)
|
||||
add_and_norm = self.attention_norm(x + attention_out)
|
||||
|
||||
ff = self.linear1(add_and_norm)
|
||||
ff_gelu = self.gelu(ff)
|
||||
ff_out = self.linear2(ff_gelu)
|
||||
x = self.ffn_norm(ff_out + add_and_norm)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class TransformerEncoder(nn.Module):
|
||||
def __init__(self, num_layers: int, dims: int, num_heads: int, mlp_dims: int):
|
||||
super().__init__()
|
||||
self.layers = [TransformerEncoderLayer(dims, num_heads, mlp_dims) for _ in range(num_layers)]
|
||||
|
||||
def __call__(self, x: Array):
|
||||
for layer in self.layers:
|
||||
x = layer(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class BertEmbeddings(nn.Module):
|
||||
def __init__(self, config: BertConfig):
|
||||
super().__init__()
|
||||
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
|
||||
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
||||
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
||||
self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
||||
|
||||
def __call__(self, input_ids: Array) -> Array:
|
||||
words = self.word_embeddings(input_ids)
|
||||
position = self.position_embeddings.weight[: input_ids.shape[1]]
|
||||
token_types = self.token_type_embeddings.weight[0]
|
||||
|
||||
embeddings = position + words + token_types
|
||||
return self.norm(embeddings)
|
||||
|
||||
|
||||
class Bert(nn.Module):
|
||||
def __init__(self, config: BertConfig):
|
||||
super().__init__()
|
||||
self.embeddings = BertEmbeddings(config)
|
||||
self.encoder = TransformerEncoder(
|
||||
num_layers=config.num_hidden_layers,
|
||||
dims=config.hidden_size,
|
||||
num_heads=config.num_attention_heads,
|
||||
mlp_dims=config.intermediate_size,
|
||||
)
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
input_ids: Array,
|
||||
) -> Array:
|
||||
x = self.embeddings(input_ids)
|
||||
|
||||
y = self.encoder(x)
|
||||
return y
|
||||
|
||||
|
||||
class G2PW(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
num_labels: int = 1305,
|
||||
num_chars: int = 3582,
|
||||
num_pos_tags: int = 11,
|
||||
):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.num_labels = num_labels
|
||||
self.num_chars = num_chars
|
||||
self.num_pos_tags = num_pos_tags
|
||||
target_size = self.num_labels
|
||||
|
||||
self.bert = Bert(config)
|
||||
self.pos_classifier = nn.Linear(self.config.hidden_size, self.num_pos_tags)
|
||||
self.descriptor_bias = nn.Embedding(1, target_size)
|
||||
self.char_descriptor = nn.Embedding(self.num_chars, target_size)
|
||||
self.second_order_descriptor = nn.Embedding(self.num_chars * self.num_pos_tags, target_size)
|
||||
self.classifier = nn.Linear(self.config.hidden_size, self.num_labels)
|
||||
|
||||
@mx.compile
|
||||
@staticmethod
|
||||
def _weighted_softmax(logits: Array, weights: Array, eps: float) -> Array:
|
||||
max_logits = mx.max(logits, axis=-1, keepdims=True)
|
||||
weighted_exp_logits = mx.exp(logits - max_logits) * weights
|
||||
norm = mx.sum(weighted_exp_logits, axis=-1, keepdims=True)
|
||||
probs = weighted_exp_logits / norm
|
||||
probs = mx.minimum(probs, 1 - eps)
|
||||
probs = mx.maximum(probs, eps)
|
||||
|
||||
return probs
|
||||
|
||||
def _get_char_pos_ids(self, char_ids: Array, pos_ids: Array):
|
||||
return char_ids * self.num_pos_tags + pos_ids
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
input_ids_torch: Tensor,
|
||||
phoneme_mask_torch: Tensor,
|
||||
char_ids_torch: Tensor,
|
||||
position_ids_torch: Tensor,
|
||||
eps: float = 1e-6,
|
||||
):
|
||||
input_ids = mx.array(input_ids_torch.cpu()) # type: ignore
|
||||
phoneme_mask = mx.array(phoneme_mask_torch.cpu()) # type: ignore
|
||||
char_ids = mx.array(char_ids_torch.cpu()) # type: ignore
|
||||
position_ids = mx.array(position_ids_torch.cpu()) # type: ignore
|
||||
|
||||
sequence_output = self.bert(input_ids=input_ids)
|
||||
|
||||
orig_selected_hidden = mx.take_along_axis(
|
||||
sequence_output,
|
||||
position_ids.reshape(-1, 1, 1),
|
||||
axis=1,
|
||||
).squeeze(1)
|
||||
|
||||
pred_pos_ids = self.pos_classifier(orig_selected_hidden).argmax(axis=-1) # teacher mode while training
|
||||
|
||||
bias_tensor = self.descriptor_bias(mx.zeros_like(char_ids))
|
||||
|
||||
char_pos_ids = self._get_char_pos_ids(char_ids, pred_pos_ids)
|
||||
|
||||
affect_hidden = bias_tensor + self.char_descriptor(char_ids) + self.second_order_descriptor(char_pos_ids)
|
||||
|
||||
phoneme_mask = phoneme_mask * mx.sigmoid(affect_hidden)
|
||||
|
||||
logits = self.classifier(orig_selected_hidden)
|
||||
|
||||
probs: Array = self._weighted_softmax(logits, phoneme_mask, eps)
|
||||
|
||||
pred_idx = probs.argmax(axis=1)
|
||||
|
||||
return torch.tensor(pred_idx)
|
||||
|
||||
|
||||
def replace_key(key: str) -> str:
|
||||
key = key.replace(".layer.", ".layers.")
|
||||
key = key.replace(".self.key.", ".key_proj.")
|
||||
key = key.replace(".self.query.", ".query_proj.")
|
||||
key = key.replace(".self.value.", ".value_proj.")
|
||||
key = key.replace(".attention.output.dense.", ".attention.out_proj.")
|
||||
key = key.replace(".attention.output.LayerNorm.", ".attention_norm.")
|
||||
key = key.replace(".output.LayerNorm.", ".ffn_norm.")
|
||||
key = key.replace(".intermediate.dense.", ".linear1.")
|
||||
key = key.replace(".output.dense.", ".linear2.")
|
||||
key = key.replace(".LayerNorm.", ".norm.")
|
||||
key = key.replace("pooler.dense.", "pooler.")
|
||||
return key
|
||||
|
||||
|
||||
def load_g2pw_mlx(bert_model: str, weights_path: str, device: torch.device, dtype: torch.dtype) -> G2PW:
|
||||
if not Path(weights_path).exists():
|
||||
raise ValueError(f"No model weights found in {weights_path}")
|
||||
|
||||
config = BertConfig.from_pretrained(bert_model)
|
||||
|
||||
# create and update the model
|
||||
model = G2PW(config)
|
||||
state_dict = torch.load(weights_path, map_location="cpu")
|
||||
state_dict_mlx: list[tuple[str, Array]] = []
|
||||
for key, value in state_dict.items():
|
||||
key = replace_key(key)
|
||||
value_mlx = mx.array(value.to(torch.float32))
|
||||
state_dict_mlx.append((key, value_mlx))
|
||||
model.load_weights(state_dict_mlx)
|
||||
if dtype == torch.float16:
|
||||
model.set_dtype(mx.float16)
|
||||
elif dtype == torch.bfloat16:
|
||||
model.set_dtype(mx.bfloat16)
|
||||
elif dtype == torch.float32:
|
||||
model.set_dtype(mx.float16) if device.type != "cpu" else model.set_dtype(mx.float32)
|
||||
nn.quantize(model.bert.encoder, group_size=128, bits=4)
|
||||
mx.eval(model.parameters())
|
||||
|
||||
return model
|
||||
@ -1,18 +0,0 @@
|
||||
import importlib.util
|
||||
|
||||
|
||||
backends: list[str]
|
||||
|
||||
if importlib.util.find_spec("mlx") is not None:
|
||||
import mlx.utils as mxutils
|
||||
|
||||
from .AR.sample_funcs_mlx import sample_naive_mlx
|
||||
from .AR.t2s_engine_mlx import T2SEngine as T2SEngineMLX
|
||||
from .G2PW.model import load_g2pw_mlx
|
||||
|
||||
backends = ["mlx_static", "mlx_varlen"]
|
||||
else:
|
||||
backends = []
|
||||
|
||||
quantization_methods_mlx = [None, "MXFP8", "Affine"]
|
||||
__all__ = ["T2SEngineMLX", "sample_naive_mlx", "backends", "quantization_methods_mlx", "load_g2pw_mlx", "mxutils"]
|
||||
@ -1,152 +0,0 @@
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
from torch.nn import functional as F
|
||||
|
||||
from ... import nn
|
||||
from ..structs import KVCache
|
||||
from ..t2s_model_abc import (
|
||||
AttentionABC,
|
||||
FeedForward,
|
||||
KVCacheHND,
|
||||
T2SDecoderABC,
|
||||
TransformerBlockABC,
|
||||
TransformerDecoderABC,
|
||||
)
|
||||
|
||||
|
||||
Tensor = torch.Tensor
|
||||
|
||||
|
||||
class Attention(AttentionABC):
|
||||
def __init__(self, n_head, hidden_dim, max_seq_length):
|
||||
super().__init__(n_head, hidden_dim, max_seq_length)
|
||||
|
||||
# key, query, value projections for all heads, but in a batch
|
||||
self.in_proj = nn.Linear(hidden_dim, hidden_dim * 3, bias=True)
|
||||
self.out_proj = nn.Linear(hidden_dim, hidden_dim, bias=True)
|
||||
|
||||
self.kv_class = KVCacheHND
|
||||
|
||||
def __call__(self, x: Tensor, input_pos: Tensor, kv_cache: KVCache, attn_mask: Tensor, max_idx: Tensor):
|
||||
bsz, seqlen, _ = x.shape
|
||||
|
||||
q, k, v = self.in_proj(x).chunk(3, dim=-1)
|
||||
|
||||
q = q.view(bsz, seqlen, self.n_head, self.head_dim)
|
||||
k = k.view(bsz, seqlen, self.n_head, self.head_dim)
|
||||
v = v.view(bsz, seqlen, self.n_head, self.head_dim)
|
||||
|
||||
q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v))
|
||||
|
||||
k, v = self.kv_class.update(input_pos, k, v, kv_cache)
|
||||
|
||||
q, k, v = map(lambda x: x[..., :max_idx, :], (q, k, v))
|
||||
|
||||
mask = attn_mask[..., :max_idx]
|
||||
|
||||
attn = F.scaled_dot_product_attention(q, k, v, mask)
|
||||
|
||||
attn = attn.transpose(1, 2).contiguous().view(bsz, seqlen, self.hidden_dim)
|
||||
|
||||
attn = self.out_proj(attn)
|
||||
|
||||
return attn
|
||||
|
||||
|
||||
class TransformerBlock(TransformerBlockABC):
|
||||
def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int) -> None:
|
||||
super().__init__(n_head, ffn_dim, hidden_dim, max_seq_length)
|
||||
|
||||
self.attention = Attention(n_head, hidden_dim, max_seq_length)
|
||||
self.feed_forward = FeedForward(hidden_dim, ffn_dim)
|
||||
self.attention_norm = nn.LayerNorm([self.hidden_dim])
|
||||
self.ffn_norm = nn.LayerNorm([self.hidden_dim])
|
||||
|
||||
|
||||
class TransformerDecoder(TransformerDecoderABC):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_dim,
|
||||
n_layer,
|
||||
n_head,
|
||||
ffn_dim,
|
||||
vocab_size,
|
||||
max_seq_length,
|
||||
max_batch_size,
|
||||
) -> None:
|
||||
super().__init__(hidden_dim, n_layer, n_head, ffn_dim, vocab_size, max_seq_length, max_batch_size)
|
||||
|
||||
self.layers = nn.ModuleList( # type: ignore
|
||||
TransformerBlock(n_head, ffn_dim, hidden_dim, max_seq_length) for _ in range(n_layer)
|
||||
)
|
||||
|
||||
|
||||
class T2SDecoder(T2SDecoderABC):
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
max_seq_length=1024,
|
||||
max_batch_size=10,
|
||||
) -> None:
|
||||
super().__init__(config, max_seq_length, max_batch_size)
|
||||
|
||||
self.h: TransformerDecoderABC = TransformerDecoder(
|
||||
self.hidden_dim,
|
||||
self.n_layer,
|
||||
self.n_head,
|
||||
self.ffn_dim,
|
||||
self.vocab_size,
|
||||
max_seq_length,
|
||||
max_batch_size,
|
||||
)
|
||||
|
||||
self.kv_class = KVCacheHND
|
||||
self.device: torch.device
|
||||
|
||||
self.extra_buffer_factory: Callable[[int, T2SDecoderABC], dict[str, Tensor]] = lambda max_bs, dec: {
|
||||
"attn_mask_buf": torch.zeros(
|
||||
(
|
||||
max_bs,
|
||||
dec.n_head,
|
||||
1,
|
||||
dec.max_seq_length,
|
||||
),
|
||||
device=dec.device,
|
||||
dtype=torch.bool,
|
||||
)
|
||||
}
|
||||
|
||||
def capture(
|
||||
self,
|
||||
*args,
|
||||
**kwds,
|
||||
):
|
||||
raise NotImplementedError("Cuda Graph Is Not Supported For Varlen Model")
|
||||
|
||||
def pre_forward_slots_hook(self, slots, runner):
|
||||
attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
|
||||
max_idx = runner.input_pos_buf[slots].long().max().item()
|
||||
return {"attn_mask": attn_mask_buf[slots], "max_idx": max_idx}
|
||||
|
||||
def post_forward_slots_hook(self, slots, runner) -> None:
|
||||
attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
|
||||
pos = runner.input_pos_buf[slots].long()
|
||||
attn_mask_buf[slots, :, :, pos] = True
|
||||
|
||||
def bind_session_hook(self, session, runner) -> None:
|
||||
slots = session.slot_indices
|
||||
|
||||
prefill_len = session.prefill_len
|
||||
bsz = session.bsz
|
||||
|
||||
range_tensor = torch.arange(self.max_seq_length).view(1, 1, 1, self.max_seq_length)
|
||||
prefill_len_expanded = prefill_len.view(bsz, 1, 1, 1)
|
||||
attn_mask = range_tensor < prefill_len_expanded
|
||||
|
||||
runner.extra_buffers["attn_mask_buf"][slots] = attn_mask
|
||||
|
||||
def unbind_session_hook(self, session, runner) -> None:
|
||||
slots = session.slot_indices
|
||||
attn_mask_buf = runner.extra_buffers["attn_mask_buf"]
|
||||
attn_mask_buf[slots].zero_()
|
||||
@ -1,469 +0,0 @@
|
||||
import enum
|
||||
import os
|
||||
import os.path as osp
|
||||
import time
|
||||
from collections.abc import MutableSequence
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import typer
|
||||
from torch.export import Dim
|
||||
from torch.nn import functional as F
|
||||
|
||||
from ...logger import logger
|
||||
|
||||
from .. import nn
|
||||
from .t2s_model_abc import AttentionABC, FeedForward, T2SDecoderABC, TransformerBlockABC, TransformerDecoderABC
|
||||
|
||||
|
||||
Tensor = torch.Tensor
|
||||
|
||||
KVCache = tuple[Tensor, Tensor]
|
||||
|
||||
app = typer.Typer(
|
||||
context_settings={"help_option_names": ["-h", "--help"]},
|
||||
add_completion=False,
|
||||
)
|
||||
|
||||
|
||||
class Stage(str, enum.Enum):
|
||||
embed = "embed"
|
||||
decode = "decode"
|
||||
|
||||
|
||||
class KVCacheONNX:
|
||||
@staticmethod
|
||||
def empty(kv_cache):
|
||||
assert len(kv_cache) == 2
|
||||
k_cache, v_cache = kv_cache
|
||||
|
||||
k_cache[:] = 0
|
||||
v_cache[:] = 0
|
||||
|
||||
@staticmethod
|
||||
def update_cache(
|
||||
input_pos: Tensor, k_val: Tensor, v_val: Tensor, kv_cache: tuple[Tensor, Tensor], cache_idx: Tensor
|
||||
):
|
||||
# input_pos: [B, ], k_val: [B, H, 1, D]
|
||||
k_out, v_out = kv_cache
|
||||
ip0 = input_pos - 1
|
||||
|
||||
k_out[cache_idx, :, ip0, None] = k_val
|
||||
v_out[cache_idx, :, ip0, None] = v_val
|
||||
|
||||
return k_out, v_out
|
||||
|
||||
@staticmethod
|
||||
def prefill_kv(k_val: Tensor, v_val: Tensor, kv_cache: tuple[Tensor, Tensor]):
|
||||
# k_val: [B, S, H, D]
|
||||
k_cache, v_cache = kv_cache
|
||||
|
||||
k_cache[..., : k_val.shape[1], :] = k_val.transpose(1, 2)
|
||||
v_cache[..., : v_val.shape[1], :] = v_val.transpose(1, 2)
|
||||
|
||||
@staticmethod
|
||||
def init_cache(batch_size: int, max_seq_length: int, n_heads: int, head_dim: int, dtype: torch.dtype):
|
||||
cache_shape = (batch_size, n_heads, max_seq_length, head_dim)
|
||||
|
||||
return (torch.zeros(cache_shape, dtype=dtype), torch.zeros(cache_shape, dtype=dtype))
|
||||
|
||||
|
||||
class AttentionONNX(AttentionABC):
|
||||
def __init__(self, n_heads: int, head_dim: int, max_seq_length: int):
|
||||
super().__init__(n_heads, head_dim, max_seq_length)
|
||||
|
||||
self.in_proj = nn.Linear(self.hidden_dim, self.hidden_dim * 3, bias=True)
|
||||
self.out_proj = nn.Linear(self.hidden_dim, self.hidden_dim, bias=True)
|
||||
|
||||
def __call__(self, *args, **kwds): # type: ignore
|
||||
pass
|
||||
|
||||
def onnx_prefill(self, x: Tensor, kv_cache: KVCache, attn_mask: Tensor) -> Tensor:
|
||||
bsz, seqlen, _ = x.shape
|
||||
|
||||
torch._check(attn_mask.size(-2) == x.size(-2))
|
||||
|
||||
q, k, v = self.in_proj(x.unsqueeze(0)).chunk(3, dim=-1)
|
||||
|
||||
q, k, v = map(lambda x: x.contiguous().view(bsz, seqlen, self.n_head, self.head_dim), (q, k, v))
|
||||
|
||||
KVCacheONNX.prefill_kv(k, v, kv_cache)
|
||||
|
||||
q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v))
|
||||
|
||||
attn = F.scaled_dot_product_attention(q, k, v, attn_mask)
|
||||
|
||||
attn = attn.transpose(1, 2).contiguous().view(1, -1, self.hidden_dim)
|
||||
|
||||
output = self.out_proj(attn)
|
||||
|
||||
return output
|
||||
|
||||
def onnx_decode(self, x: Tensor, input_pos: Tensor, kv_cache: KVCache, cache_idx: Tensor, attn_mask: Tensor):
|
||||
bsz, seqlen, _ = x.shape
|
||||
|
||||
torch._check(attn_mask.size(-2) == 1)
|
||||
|
||||
q, k, v = self.in_proj(x).chunk(3, dim=-1)
|
||||
|
||||
q, k, v = map(lambda x: x.reshape(bsz, seqlen, self.n_head, self.head_dim), (q, k, v))
|
||||
|
||||
q, k, v = map(lambda x: x.swapaxes(1, 2), (q, k, v))
|
||||
|
||||
kv_cache = KVCacheONNX.update_cache(input_pos, k, v, kv_cache, cache_idx)
|
||||
|
||||
max_idx = int(input_pos.max())
|
||||
|
||||
q, k, v = map(lambda x: x[..., :max_idx, :], (q, *kv_cache))
|
||||
|
||||
mask = attn_mask[..., :max_idx]
|
||||
|
||||
attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
||||
|
||||
attn = attn.swapaxes(1, 2).reshape(bsz, seqlen, self.hidden_dim)
|
||||
|
||||
attn = self.out_proj(attn)
|
||||
|
||||
return attn
|
||||
|
||||
|
||||
class TransformerBlockONNX(TransformerBlockABC):
|
||||
def __init__(self, n_head: int, ffn_dim: int, hidden_dim: int, max_seq_length: int) -> None:
|
||||
super().__init__(n_head, ffn_dim, hidden_dim, max_seq_length)
|
||||
|
||||
self.attention: AttentionONNX = AttentionONNX(n_head, hidden_dim, max_seq_length) # type: ignore
|
||||
self.feed_forward = FeedForward(hidden_dim, ffn_dim)
|
||||
self.attention_norm = nn.LayerNorm(self.hidden_dim)
|
||||
self.ffn_norm = nn.LayerNorm(self.hidden_dim)
|
||||
|
||||
def onnx_prefill(self, x: Tensor, attn_mask: Tensor, kv_cache: KVCache):
|
||||
h = self.attention_norm(
|
||||
x
|
||||
+ self.attention.onnx_prefill(
|
||||
x,
|
||||
kv_cache,
|
||||
attn_mask,
|
||||
)
|
||||
)
|
||||
out = self.ffn_norm(h + self.feed_forward(h))
|
||||
|
||||
return out
|
||||
|
||||
def onnx_decode(self, x: Tensor, input_pos: Tensor, kv_cache: KVCache, cache_idx: Tensor, attn_mask: Tensor):
|
||||
h = self.attention_norm(
|
||||
x
|
||||
+ self.attention.onnx_decode(
|
||||
x,
|
||||
input_pos,
|
||||
kv_cache,
|
||||
cache_idx,
|
||||
attn_mask,
|
||||
)
|
||||
)
|
||||
out = self.ffn_norm(h + self.feed_forward(h))
|
||||
return out
|
||||
|
||||
|
||||
class TransformerDecoderONNX(TransformerDecoderABC):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_dim: int,
|
||||
n_layer: int,
|
||||
n_head: int,
|
||||
ffn_dim: int,
|
||||
vocab_size: int,
|
||||
max_seq_length: int,
|
||||
max_batch_size: int,
|
||||
) -> None:
|
||||
super().__init__(hidden_dim, n_layer, n_head, ffn_dim, vocab_size, max_seq_length, max_batch_size)
|
||||
|
||||
self.layers: MutableSequence[TransformerBlockONNX] = nn.ModuleList( # type: ignore
|
||||
TransformerBlockONNX(n_head, ffn_dim, hidden_dim, max_seq_length) for _ in range(n_layer)
|
||||
)
|
||||
|
||||
def onnx_prefill(self, x: Tensor, mask: Tensor, *kv_caches: KVCache):
|
||||
for layer, kv_cache in zip(self.layers, kv_caches):
|
||||
x = layer.onnx_prefill(
|
||||
x,
|
||||
mask,
|
||||
kv_cache,
|
||||
)
|
||||
return x
|
||||
|
||||
def onnx_decode(
|
||||
self,
|
||||
input_pos: Tensor,
|
||||
x: Tensor,
|
||||
cache_idx: Tensor,
|
||||
attn_mask: Tensor,
|
||||
*kv_caches: KVCache,
|
||||
):
|
||||
for layer, kv_cache in zip(self.layers, kv_caches):
|
||||
x = layer.onnx_decode(
|
||||
x,
|
||||
input_pos,
|
||||
kv_cache,
|
||||
cache_idx,
|
||||
attn_mask,
|
||||
)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class T2SDecoderONNX(T2SDecoderABC):
|
||||
def __init__(self, config: dict, max_seq_length: int = 1024, max_batch_size: int = 10) -> None:
|
||||
super().__init__(config, max_seq_length, max_batch_size)
|
||||
|
||||
self.bert_proj = nn.Linear(1024, self.embedding_dim)
|
||||
self.ar_predict_layer = nn.Linear(self.hidden_dim, self.vocab_size, bias=False)
|
||||
|
||||
self.h = TransformerDecoderONNX(
|
||||
self.hidden_dim, self.n_layer, self.n_head, self.ffn_dim, self.vocab_size, max_seq_length, max_batch_size
|
||||
)
|
||||
|
||||
def pre_forward(self, session) -> tuple[list[Tensor], dict[str, Tensor]]:
|
||||
return super().pre_forward(session)
|
||||
|
||||
def post_forward(self, idx: int, session) -> None:
|
||||
return super().post_forward(idx, session)
|
||||
|
||||
def embed_onnx_(
|
||||
self,
|
||||
x: Tensor,
|
||||
x_len: Tensor,
|
||||
y: torch.Tensor,
|
||||
bert_features: Tensor,
|
||||
):
|
||||
B = x.shape[0]
|
||||
D = self.embedding_dim
|
||||
T_TOTAL = 500
|
||||
xy_pos = torch.zeros((B, T_TOTAL, D)).to(bert_features[0].dtype)
|
||||
|
||||
bert_features = bert_features.transpose(1, 2)
|
||||
|
||||
y.shape[1]
|
||||
y_emb = self.ar_audio_embedding(y)
|
||||
self.ar_audio_position.prefill(y_emb)
|
||||
|
||||
for bs, x_, len_, bert_feature in zip(torch.arange(x.shape[0]), x, x_len, bert_features):
|
||||
x_emb = self.ar_text_embedding(x_[:len_])
|
||||
|
||||
bert = self.bert_proj(bert_feature[:len_])
|
||||
|
||||
print(bert.shape, bert_feature[:len_])
|
||||
|
||||
return bert, bert_feature[:len_].unsqueeze(0)
|
||||
|
||||
return bert[:20].unsqueeze(0), None
|
||||
x_emb = x_emb + bert
|
||||
self.ar_text_position.prefill(x_emb.unsqueeze(0))
|
||||
|
||||
xy_pos[None, bs, :len_] = bert
|
||||
# xy_pos[None, bs, len_ : len_ + y_len] = y_pos
|
||||
|
||||
return xy_pos[:, -1], None
|
||||
|
||||
return xy_pos[: x.shape[0]], x_len
|
||||
|
||||
def embed_onnx(
|
||||
self,
|
||||
x: torch.Tensor, # [B, Tx]
|
||||
x_len: torch.Tensor, # [B]
|
||||
y: torch.Tensor, # [1, Ty, D]
|
||||
bert_features: torch.Tensor, # [B, 1024, Tx]
|
||||
):
|
||||
# [B, 1024, Tx] -> [B, Tx, 1024]
|
||||
bert_features = bert_features.transpose(1, 2)
|
||||
|
||||
Ty = y.shape[1]
|
||||
Tx = x.shape[1]
|
||||
B = x.shape[0]
|
||||
D = self.embedding_dim
|
||||
T_TOTAL = 500
|
||||
|
||||
# mask: [B, Tx], [j] Col < x_len[i]
|
||||
col = torch.arange(Tx, device=x.device).unsqueeze(0) # [1, Tx]
|
||||
mask_x = col < x_len.view(-1, 1) # [B, Tx]
|
||||
mask_x3 = mask_x.unsqueeze(-1) # [B, Tx, 1]
|
||||
|
||||
torch._check((Ty >= 0) and (Ty <= 250), "y_len out of range")
|
||||
torch._check((Tx >= 0) and (Tx <= 250), "x_len out of range")
|
||||
|
||||
y_emb = self.ar_audio_embedding(y) # [1, Ty, D]
|
||||
y_pos = self.ar_audio_position.prefill(y_emb) # [1, Ty, D]
|
||||
|
||||
x_emb_full = self.ar_text_embedding(x) # [B, Tx, D]
|
||||
bert_full = self.bert_proj(bert_features[[0], : x_len[0]]) # [B, Tx, D]
|
||||
|
||||
print(bert_full[0].shape, bert_features[0, : x_len[0]])
|
||||
|
||||
return bert_full[0], bert_features[0, : x_len[0]]
|
||||
|
||||
x_sum_full = x_emb_full + bert_full # [B, Tx, D]
|
||||
x_pos_full = self.ar_text_position.prefill(x_sum_full) # [B, Tx, D]
|
||||
|
||||
xy_pos = torch.zeros((B, T_TOTAL, D), dtype=x_pos_full.dtype, device=x_pos_full.device)
|
||||
|
||||
xy_pos[:, :Tx, :] = torch.where(
|
||||
mask_x3,
|
||||
bert_full[:, :Tx, :].to(xy_pos.dtype),
|
||||
xy_pos[:, :Tx, :],
|
||||
)
|
||||
|
||||
return xy_pos[:, -1], None
|
||||
|
||||
# Start From offset=x_len, Ty
|
||||
# [Ty] Index: offsets + [0..Ty-1]
|
||||
offsets = x_len.clamp(min=0, max=T_TOTAL - Ty) # [B]
|
||||
idx_y = offsets.unsqueeze(1) + torch.arange(Ty, device=x_pos_full.device) # [B, Ty]
|
||||
# scatter to dim=1
|
||||
# expand index to [B, Ty, D]
|
||||
idx_y3 = idx_y.unsqueeze(-1).expand(B, Ty, D)
|
||||
y_pos_b = y_pos.expand(B, Ty, D).to(xy_pos.dtype) # [B, Ty, D]
|
||||
xy_pos = xy_pos.scatter(1, idx_y3, y_pos_b)
|
||||
|
||||
return xy_pos, x_len
|
||||
|
||||
|
||||
def torchscript_export(model: T2SDecoderONNX, stage="embed"):
|
||||
if stage == "embed":
|
||||
x = torch.randint(1, 600, (model.max_batch_size, 50))
|
||||
x_len = torch.randint(30, 50, (model.max_batch_size,))
|
||||
y = torch.randint(1, 600, (1, 200))
|
||||
bert_features = torch.rand((model.max_batch_size, 1024, 50))
|
||||
|
||||
x_len[-1] = 50
|
||||
|
||||
mask = torch.arange(x_len.max().item(), device=x.device).unsqueeze(0) < x_len.unsqueeze(1)
|
||||
|
||||
x = x * mask
|
||||
bert_features = bert_features * mask.unsqueeze(1)
|
||||
|
||||
try:
|
||||
a, c = model.embed_onnx_(x, x_len, y, bert_features)
|
||||
b, d = model.embed_onnx(x, x_len, y, bert_features)
|
||||
print("-" * 20)
|
||||
print(a - b, (a - b).sum(), (a - b).square().mean())
|
||||
# print(c - d, (c - d).sum(), (c - d).square().mean())
|
||||
exit()
|
||||
assert torch.allclose(a, b, atol=1e-6, rtol=1e-8), (a - b).square().mean()
|
||||
|
||||
model.forward = model.embed_onnx
|
||||
scripted_model = torch.jit.script(model, example_inputs=[(x, x_len, y, bert_features)])
|
||||
|
||||
onnx_program = torch.onnx.export(
|
||||
scripted_model,
|
||||
(x, x_len, y, bert_features),
|
||||
input_names=["text", "text_len", "prompt", "bert_features"],
|
||||
output_names=["xy_pos", "input_pos"],
|
||||
dynamic_axes={
|
||||
"text": {0: "Batch_Size", 1: "Sequence_Length_X"},
|
||||
"prompt": {0: "Batch_Size", 1: "Sequence_Length_Y"},
|
||||
"bert_features": {0: "Batch_Size", 1: "Sequence_Length_X"},
|
||||
},
|
||||
opset_version=21,
|
||||
training=False,
|
||||
do_constant_folding=True,
|
||||
external_data=False,
|
||||
)
|
||||
assert onnx_program
|
||||
onnx_program.save("onnx_export/AR_Embedding_TorchScript.onnx")
|
||||
|
||||
except Exception:
|
||||
logger.bind(show_locals=False).exception("")
|
||||
|
||||
|
||||
def dynamo_export(model: T2SDecoderONNX, stage="embed"):
|
||||
if stage == "embed":
|
||||
x = torch.randint(1, 600, (model.max_batch_size, 50))
|
||||
x_len = torch.randint(30, 50, (model.max_batch_size,))
|
||||
y = torch.randint(1, 600, (1, 200))
|
||||
bert_features = torch.rand((model.max_batch_size, 1024, 50))
|
||||
|
||||
x_len[-1] = 50
|
||||
|
||||
mask = torch.arange(x_len.max().item(), device=x.device).unsqueeze(0) < x_len.unsqueeze(1)
|
||||
|
||||
x = x * mask
|
||||
bert_features = (bert_features.transpose(1, 2) * mask.unsqueeze(-1)).transpose(1, 2)
|
||||
|
||||
dynamic_shapes = [
|
||||
{
|
||||
0: Dim("Batch_Size", min=1, max=4),
|
||||
1: Dim("Sequence_Length_X", min=1, max=50),
|
||||
},
|
||||
{
|
||||
0: Dim("Batch_Size", min=1, max=4),
|
||||
},
|
||||
{
|
||||
1: Dim("Sequence_Length_Y", min=1, max=250),
|
||||
},
|
||||
{
|
||||
0: Dim("Batch_Size", min=1, max=4),
|
||||
2: Dim("Sequence_Length_X", min=1, max=50),
|
||||
},
|
||||
]
|
||||
try:
|
||||
a = model.embed_onnx_(x, x_len, y, bert_features)[0]
|
||||
b = model.embed_onnx(x, x_len, y, bert_features)[0]
|
||||
print(a - b, (a - b).square().mean())
|
||||
exit()
|
||||
assert torch.allclose(a, b, atol=1e-6, rtol=1e-8), (a - b).square().mean()
|
||||
|
||||
model.forward = model.embed_onnx
|
||||
onnx_program = torch.onnx.export(
|
||||
model,
|
||||
(x, x_len, y, bert_features),
|
||||
input_names=["text", "text_len", "prompt", "bert_features"],
|
||||
output_names=["xy_pos", "input_pos"],
|
||||
dynamo=True,
|
||||
dynamic_shapes=dynamic_shapes,
|
||||
opset_version=21,
|
||||
training=False,
|
||||
do_constant_folding=True,
|
||||
external_data=False,
|
||||
)
|
||||
assert onnx_program
|
||||
onnx_program.save("onnx_export/AR_Embedding_Dynamo.onnx")
|
||||
except Exception:
|
||||
logger.bind(show_locals=False).exception("")
|
||||
|
||||
|
||||
@app.command()
|
||||
def export(
|
||||
ckpt_path: Path = typer.Option( # noqa: B008
|
||||
...,
|
||||
"--ckpt-path",
|
||||
file_okay=True,
|
||||
dir_okay=False,
|
||||
exists=True,
|
||||
readable=True,
|
||||
show_default=False,
|
||||
help="AR Checkpoint",
|
||||
),
|
||||
dynamo: bool = typer.Option(False, is_flag=True, flag_value=True, help="Use Torch Dynamo"),
|
||||
stages: list[Stage] = typer.Option([Stage.embed], "--stages", help="Stage to export"), # noqa: B008
|
||||
):
|
||||
os.makedirs("onnx_export", exist_ok=True)
|
||||
dict_s1 = torch.load(ckpt_path, "cpu", mmap=True)
|
||||
condig = dict_s1["config"]
|
||||
model = T2SDecoderONNX(condig, 1500, 4)
|
||||
state_dict = dict_s1["weight"]
|
||||
model.load_state_dict(state_dict)
|
||||
|
||||
for stage in stages:
|
||||
if dynamo:
|
||||
dynamo_export(model, stage)
|
||||
else:
|
||||
torchscript_export(model, stage)
|
||||
|
||||
|
||||
def get_prog_name() -> str:
|
||||
script_rel = ".".join(["GPT_SoVITS", "Accelerate", "PyTorch", osp.basename(__file__)]).strip(".py")
|
||||
return f"python -s -m {script_rel}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
t = time.perf_counter()
|
||||
app(prog_name=get_prog_name())
|
||||
logger.info(f"Exec Time: {time.perf_counter() - t:.2f} secs")
|
||||
@ -1,159 +0,0 @@
|
||||
from typing import Optional, cast
|
||||
|
||||
import torch
|
||||
|
||||
from .. import nn
|
||||
|
||||
|
||||
Tensor = torch.Tensor
|
||||
|
||||
|
||||
# based on ComfyUI's and MinusZoneAI's fp8_linear optimization
|
||||
def fp8_linear_forward(cls: nn.Linear, input: Tensor):
|
||||
weight_dtype = cls.weight.dtype
|
||||
base_dtype = input.dtype
|
||||
if weight_dtype in [torch.float8_e4m3fn, torch.float8_e5m2]:
|
||||
if len(input.shape) == 3:
|
||||
input_shape = input.shape
|
||||
|
||||
scale_weight: Optional[Tensor] = getattr(cls, "scale_weight", None)
|
||||
if scale_weight is None:
|
||||
scale_weight = torch.ones((), device=input.device, dtype=torch.float32)
|
||||
else:
|
||||
scale_weight = scale_weight.to(input.device).squeeze()
|
||||
|
||||
scale_input = torch.ones((), device=input.device, dtype=torch.float32)
|
||||
|
||||
input = torch.clamp(input, min=-448, max=448, out=input)
|
||||
inn = (
|
||||
input.reshape(-1, input_shape[2]).to(torch.float8_e4m3fn).contiguous()
|
||||
) # always e4m3fn because e5m2 * e5m2 is not supported
|
||||
|
||||
bias = cls.bias if cls.bias is not None else None
|
||||
|
||||
o = torch._scaled_mm(
|
||||
inn, cls.weight.t(), out_dtype=base_dtype, bias=bias, scale_a=scale_input, scale_b=scale_weight
|
||||
)
|
||||
|
||||
return o.reshape((-1, input_shape[1], cls.weight.shape[0]))
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
raise
|
||||
|
||||
|
||||
def convert_fp8_linear(
|
||||
module: nn.Module,
|
||||
):
|
||||
apply_fn = fp8_linear_forward
|
||||
|
||||
for _, sub in list(module.named_modules()):
|
||||
if isinstance(sub, nn.Linear):
|
||||
if getattr(sub, "_fp8", False):
|
||||
continue
|
||||
sub.forward = apply_fn
|
||||
sub._fp8 = True
|
||||
return module
|
||||
|
||||
|
||||
def per_tensor_quantize(tensor: torch.Tensor) -> tuple[Tensor, Tensor]:
|
||||
"""Quantize a tensor using per-tensor static scaling factor.
|
||||
Args:
|
||||
tensor: The input tensor.
|
||||
"""
|
||||
finfo = torch.finfo(torch.float8_e4m3fn)
|
||||
# Calculate the scale as dtype max divided by absmax.
|
||||
# Since .abs() creates a new tensor, we use aminmax to get
|
||||
# the min and max first and then calculate the absmax.
|
||||
if tensor.numel() == 0:
|
||||
# Deal with empty tensors (triggered by empty MoE experts)
|
||||
min_val, max_val = (
|
||||
torch.tensor(0.0, dtype=tensor.dtype),
|
||||
torch.tensor(1.0, dtype=tensor.dtype),
|
||||
)
|
||||
else:
|
||||
min_val, max_val = tensor.aminmax()
|
||||
amax = min_val.abs().max(max_val.abs())
|
||||
scale = finfo.max / amax.clamp(min=1e-12)
|
||||
# scale and clamp the tensor to bring it to
|
||||
# the representative range of float8 data type
|
||||
# (as default cast is unsaturated)
|
||||
qweight = (tensor * scale).clamp(min=finfo.min, max=finfo.max)
|
||||
# Return both float8 data and the inverse scale (as float),
|
||||
# as both required as inputs to torch._scaled_mm
|
||||
qweight = qweight.to(torch.float8_e4m3fn)
|
||||
scale = scale.float().reciprocal()
|
||||
return qweight, scale
|
||||
|
||||
|
||||
def fp8_gemm(A, A_scale, B, B_scale, bias, out_dtype):
|
||||
cuda_compute_capability = torch.cuda.get_device_capability()
|
||||
if cuda_compute_capability >= (9, 0):
|
||||
output, _ = torch._scaled_mm(
|
||||
A,
|
||||
B.t(),
|
||||
out_dtype=out_dtype,
|
||||
scale_a=A_scale,
|
||||
scale_b=B_scale,
|
||||
bias=bias,
|
||||
)
|
||||
else:
|
||||
output = torch.nn.functional.linear(
|
||||
A.to(out_dtype) * A_scale,
|
||||
B.to(out_dtype) * B_scale.to(out_dtype),
|
||||
bias=bias,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
class FP8DynamicLinear(nn.Module):
|
||||
def __init__(self, qweight: Tensor, scale: Tensor, bias: Tensor):
|
||||
super().__init__()
|
||||
self.weight = torch.nn.Parameter(qweight, requires_grad=False)
|
||||
self.weight_scale = torch.nn.Parameter(scale, requires_grad=False)
|
||||
self.bias = bias
|
||||
|
||||
def __call__(self, x):
|
||||
qinput, x_scale = per_tensor_quantize(x)
|
||||
output = fp8_gemm(
|
||||
A=qinput,
|
||||
A_scale=x_scale,
|
||||
B=self.weight,
|
||||
B_scale=self.weight_scale,
|
||||
bias=self.bias,
|
||||
out_dtype=x.dtype,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def replace_all_linear_with_fp8(model: nn.Module):
|
||||
"""
|
||||
Recursively replace every nn.Linear with FP8DynamicLinear in-place.
|
||||
"""
|
||||
|
||||
def _recursively_replace(parent: nn.Module):
|
||||
for child_name, child in list(parent.named_children()):
|
||||
child = cast(nn.Module, child)
|
||||
if isinstance(child, FP8DynamicLinear):
|
||||
continue
|
||||
|
||||
if isinstance(child, nn.Linear):
|
||||
device = child.weight.device
|
||||
|
||||
w = child.weight
|
||||
|
||||
b = child.bias.clone()
|
||||
|
||||
qw, qs = per_tensor_quantize(w)
|
||||
|
||||
quant_linear = FP8DynamicLinear(qw, qs, b)
|
||||
|
||||
quant_linear.to(device)
|
||||
|
||||
setattr(parent, child_name, quant_linear)
|
||||
|
||||
del child
|
||||
else:
|
||||
_recursively_replace(child)
|
||||
|
||||
_recursively_replace(model)
|
||||
@ -10,11 +10,10 @@ from typing import Optional, TypeVar
|
||||
import torch
|
||||
|
||||
from tools.acceleration import cuda_graph_available
|
||||
from ...logger import timer
|
||||
|
||||
from .sample_funcs import sample_naive
|
||||
from .structs import KVCache, T2SRequest, T2SSession
|
||||
from .t2s_model_abc import T2SDecoderABC, TorchProfiler
|
||||
from .t2s_model_abc import T2SDecoderABC
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
@ -34,17 +33,6 @@ def _slice_tensors(obj: T, bsz: int) -> T:
|
||||
return obj
|
||||
|
||||
|
||||
def _synchronize_device(device: torch.device) -> None:
|
||||
if device.type == "cuda":
|
||||
torch.cuda.synchronize()
|
||||
elif device.type == "mps":
|
||||
torch.mps.synchronize()
|
||||
elif device.type == "xpu":
|
||||
torch.xpu.synchronize()
|
||||
elif device.type == "mtia":
|
||||
torch.mtia.synchronize()
|
||||
elif device.type == "cpu":
|
||||
pass
|
||||
|
||||
|
||||
class ModelRunner:
|
||||
@ -180,14 +168,11 @@ class ModelRunner:
|
||||
|
||||
kv_cache = self.decoder.init_cache(session.bsz)
|
||||
|
||||
torch_profiler = TorchProfiler(request.debug)
|
||||
with torch_profiler.profiler(), timer("Torch.Prefill", debug=request.debug), torch.inference_mode():
|
||||
torch_profiler.start()
|
||||
with torch.inference_mode():
|
||||
xy_pos = self.decoder.embed(session.x, request.prompts, session.bert_feature)
|
||||
xy_dec = self.decoder.h.prefill(xy_pos, kv_cache, session.attn_mask)
|
||||
gather_index = (session.input_pos - 1).long().view(session.bsz, 1, 1)
|
||||
session.prefill_hidden = torch.take_along_dim(xy_dec, gather_index, dim=1)
|
||||
torch_profiler.end()
|
||||
|
||||
session.kv_cache = kv_cache
|
||||
|
||||
@ -290,118 +275,109 @@ class ModelRunner:
|
||||
|
||||
use_graph = self._should_use_graph() and bool(forward_slots)
|
||||
|
||||
debug = any(session.request.debug for session in self.bound_sessions)
|
||||
|
||||
try:
|
||||
with torch.inference_mode():
|
||||
if forward_slots:
|
||||
forward_len = max(forward_slots) + 1
|
||||
model_len = self._select_bsz(forward_len) if use_graph else forward_len
|
||||
kwds = decoder.pre_forward_slots_hook(list(range(model_len)), self)
|
||||
if use_graph:
|
||||
graph = self._acquire_graph(model_len)
|
||||
graph.replay()
|
||||
else:
|
||||
self.xy_dec_buf[:forward_len] = decoder.h(
|
||||
self.xy_pos_buf[:forward_len],
|
||||
self.input_pos_buf[:forward_len],
|
||||
_slice_tensors(self.kv_cache_buf, forward_len),
|
||||
**kwds,
|
||||
)
|
||||
|
||||
# Bind any newly ready sessions after decode and before sampling
|
||||
if self.waiting_bind and self.free_slots() > 0:
|
||||
self._bind_waiting_sessions()
|
||||
if not debug:
|
||||
debug = any(session.request.debug for session in self.bound_sessions)
|
||||
|
||||
for slot_idx, session in enumerate(self.slot_sessions):
|
||||
if session is None:
|
||||
continue
|
||||
if session.step_count == 0:
|
||||
prefill_slots.append(slot_idx)
|
||||
|
||||
active_slots = forward_slots + prefill_slots
|
||||
if not active_slots:
|
||||
return []
|
||||
|
||||
idx_tensor = torch.tensor(active_slots, device=self.device, dtype=torch.long)
|
||||
|
||||
logits_all = decoder.ar_predict_layer(self.xy_dec_buf[idx_tensor].squeeze(1))
|
||||
|
||||
first_step_mask = (self.step_buf[idx_tensor] == 0).bool()
|
||||
|
||||
if torch.any(first_step_mask):
|
||||
logits_all[first_step_mask, -1] = float("-inf")
|
||||
|
||||
sampler = self.sampler
|
||||
|
||||
samples = sampler(
|
||||
logits=logits_all,
|
||||
valid_lens=self.prompt_len_buf[idx_tensor] + self.step_buf[idx_tensor],
|
||||
previous_tokens=self.y_buf[idx_tensor],
|
||||
repetition_penalty=self.repetition_penalty_buf[idx_tensor],
|
||||
temperature=self.temperature_buf[idx_tensor],
|
||||
top_k=self.top_k_buf[idx_tensor],
|
||||
top_p=self.top_p_buf[idx_tensor],
|
||||
)
|
||||
|
||||
argmax_token = torch.argmax(logits_all, dim=-1)
|
||||
eos_mask_all = torch.logical_or((argmax_token == decoder.EOS), (samples.squeeze(1) == decoder.EOS))
|
||||
|
||||
y_emb_all = decoder.ar_audio_embedding(samples.clamp_max_(decoder.vocab_size - 2))
|
||||
pos_offset = self.step_buf[idx_tensor] + self.prompt_len_buf[idx_tensor] + 1
|
||||
next_xy_all = decoder.ar_audio_position(pos_offset, y_emb_all)
|
||||
|
||||
sample_vals = samples.squeeze(1)
|
||||
write_pos = self.prompt_len_buf[idx_tensor] + self.step_buf[idx_tensor]
|
||||
|
||||
# Only write for slots that are not already done and not EOS
|
||||
write_mask = (~self.completed_buf[idx_tensor]) & (~eos_mask_all)
|
||||
if torch.any(write_mask):
|
||||
write_slots = idx_tensor[write_mask]
|
||||
self.y_buf[write_slots, write_pos[write_mask]] = sample_vals[write_mask]
|
||||
self.input_pos_buf[write_slots] += 1
|
||||
|
||||
new_step = self.step_buf[idx_tensor].clone()
|
||||
new_step[write_mask] += 1
|
||||
forced_stop = new_step >= self.max_step_buf[idx_tensor]
|
||||
self.step_buf[idx_tensor] = new_step
|
||||
self.completed_buf[idx_tensor] |= eos_mask_all | forced_stop
|
||||
done_slots = idx_tensor[self.completed_buf[idx_tensor]]
|
||||
# Graph buckets also execute inactive rows, so their cache position must remain valid.
|
||||
self.input_pos_buf[done_slots] = 1
|
||||
|
||||
# Update next xy for continuing slots
|
||||
continue_mask = ~(self.completed_buf[idx_tensor])
|
||||
if torch.any(continue_mask):
|
||||
cont_slots = idx_tensor[continue_mask]
|
||||
cont_xy = next_xy_all[continue_mask]
|
||||
self.xy_pos_buf[cont_slots] = cont_xy
|
||||
|
||||
# Sync back
|
||||
for slots in list(self.session_slots.values()):
|
||||
if not slots:
|
||||
continue
|
||||
session = self.slot_sessions[slots[0]]
|
||||
if session is None:
|
||||
continue
|
||||
session.output_lengths = self.step_buf[slots].tolist()
|
||||
session.step_count = max(session.output_lengths)
|
||||
session.total_tokens = sum(session.output_lengths)
|
||||
session.completed = self.completed_buf[slots].clone()
|
||||
if bool(torch.all(session.completed)):
|
||||
session.y_results = [
|
||||
self.y_buf[slot, session.prompt_len : session.prompt_len + length].clone()
|
||||
for slot, length in zip(slots, session.output_lengths)
|
||||
]
|
||||
finished_sessions.append(session)
|
||||
self.unbind_session(session)
|
||||
|
||||
decoder.post_forward_slots_hook(forward_slots, self)
|
||||
|
||||
finally:
|
||||
if debug:
|
||||
_synchronize_device(self.device)
|
||||
with torch.inference_mode():
|
||||
if forward_slots:
|
||||
forward_len = max(forward_slots) + 1
|
||||
model_len = self._select_bsz(forward_len) if use_graph else forward_len
|
||||
kwds = decoder.pre_forward_slots_hook(list(range(model_len)), self)
|
||||
if use_graph:
|
||||
graph = self._acquire_graph(model_len)
|
||||
graph.replay()
|
||||
else:
|
||||
self.xy_dec_buf[:forward_len] = decoder.h(
|
||||
self.xy_pos_buf[:forward_len],
|
||||
self.input_pos_buf[:forward_len],
|
||||
_slice_tensors(self.kv_cache_buf, forward_len),
|
||||
**kwds,
|
||||
)
|
||||
|
||||
# Bind any newly ready sessions after decode and before sampling
|
||||
if self.waiting_bind and self.free_slots() > 0:
|
||||
self._bind_waiting_sessions()
|
||||
|
||||
for slot_idx, session in enumerate(self.slot_sessions):
|
||||
if session is None:
|
||||
continue
|
||||
if session.step_count == 0:
|
||||
prefill_slots.append(slot_idx)
|
||||
|
||||
active_slots = forward_slots + prefill_slots
|
||||
if not active_slots:
|
||||
return []
|
||||
|
||||
idx_tensor = torch.tensor(active_slots, device=self.device, dtype=torch.long)
|
||||
|
||||
logits_all = decoder.ar_predict_layer(self.xy_dec_buf[idx_tensor].squeeze(1))
|
||||
|
||||
first_step_mask = (self.step_buf[idx_tensor] == 0).bool()
|
||||
|
||||
if torch.any(first_step_mask):
|
||||
logits_all[first_step_mask, -1] = float("-inf")
|
||||
|
||||
sampler = self.sampler
|
||||
|
||||
samples = sampler(
|
||||
logits=logits_all,
|
||||
valid_lens=self.prompt_len_buf[idx_tensor] + self.step_buf[idx_tensor],
|
||||
previous_tokens=self.y_buf[idx_tensor],
|
||||
repetition_penalty=self.repetition_penalty_buf[idx_tensor],
|
||||
temperature=self.temperature_buf[idx_tensor],
|
||||
top_k=self.top_k_buf[idx_tensor],
|
||||
top_p=self.top_p_buf[idx_tensor],
|
||||
)
|
||||
|
||||
argmax_token = torch.argmax(logits_all, dim=-1)
|
||||
eos_mask_all = torch.logical_or((argmax_token == decoder.EOS), (samples.squeeze(1) == decoder.EOS))
|
||||
|
||||
y_emb_all = decoder.ar_audio_embedding(samples.clamp_max_(decoder.vocab_size - 2))
|
||||
pos_offset = self.step_buf[idx_tensor] + self.prompt_len_buf[idx_tensor] + 1
|
||||
next_xy_all = decoder.ar_audio_position(pos_offset, y_emb_all)
|
||||
|
||||
sample_vals = samples.squeeze(1)
|
||||
write_pos = self.prompt_len_buf[idx_tensor] + self.step_buf[idx_tensor]
|
||||
|
||||
# Only write for slots that are not already done and not EOS
|
||||
write_mask = (~self.completed_buf[idx_tensor]) & (~eos_mask_all)
|
||||
if torch.any(write_mask):
|
||||
write_slots = idx_tensor[write_mask]
|
||||
self.y_buf[write_slots, write_pos[write_mask]] = sample_vals[write_mask]
|
||||
self.input_pos_buf[write_slots] += 1
|
||||
|
||||
new_step = self.step_buf[idx_tensor].clone()
|
||||
new_step[write_mask] += 1
|
||||
forced_stop = new_step >= self.max_step_buf[idx_tensor]
|
||||
self.step_buf[idx_tensor] = new_step
|
||||
self.completed_buf[idx_tensor] |= eos_mask_all | forced_stop
|
||||
done_slots = idx_tensor[self.completed_buf[idx_tensor]]
|
||||
# Graph buckets also execute inactive rows, so their cache position must remain valid.
|
||||
self.input_pos_buf[done_slots] = 1
|
||||
|
||||
# Update next xy for continuing slots
|
||||
continue_mask = ~(self.completed_buf[idx_tensor])
|
||||
if torch.any(continue_mask):
|
||||
cont_slots = idx_tensor[continue_mask]
|
||||
cont_xy = next_xy_all[continue_mask]
|
||||
self.xy_pos_buf[cont_slots] = cont_xy
|
||||
|
||||
# Sync back
|
||||
for slots in list(self.session_slots.values()):
|
||||
if not slots:
|
||||
continue
|
||||
session = self.slot_sessions[slots[0]]
|
||||
if session is None:
|
||||
continue
|
||||
session.output_lengths = self.step_buf[slots].tolist()
|
||||
session.step_count = max(session.output_lengths)
|
||||
session.total_tokens = sum(session.output_lengths)
|
||||
session.completed = self.completed_buf[slots].clone()
|
||||
if bool(torch.all(session.completed)):
|
||||
session.y_results = [
|
||||
self.y_buf[slot, session.prompt_len : session.prompt_len + length].clone()
|
||||
for slot, length in zip(slots, session.output_lengths)
|
||||
]
|
||||
finished_sessions.append(session)
|
||||
self.unbind_session(session)
|
||||
|
||||
decoder.post_forward_slots_hook(forward_slots, self)
|
||||
|
||||
return finished_sessions
|
||||
|
||||
@ -50,7 +50,6 @@ class T2SRequest:
|
||||
request_id: Union[str, int] = -1
|
||||
stream_interval: Optional[int] = None
|
||||
return_partial: bool = True
|
||||
debug: bool = False
|
||||
max_decode_steps: Optional[int] = None
|
||||
|
||||
|
||||
|
||||
@ -13,7 +13,7 @@ from typing import Literal, Optional, Union
|
||||
import torch
|
||||
from rich.progress import BarColumn, Progress, TextColumn
|
||||
|
||||
from ...logger import SpeedColumnToken, Timer, console, logger
|
||||
from ...logger import SpeedColumnToken, console, logger
|
||||
|
||||
from .runner import ModelRunner
|
||||
from .structs import (
|
||||
@ -27,8 +27,6 @@ from .structs import (
|
||||
from .t2s_model_abc import T2SDecoderABC
|
||||
|
||||
|
||||
timer = Timer("T2S Engine Torch")
|
||||
|
||||
cpu = torch.device("cpu")
|
||||
|
||||
empty_result = T2SResult(
|
||||
@ -340,7 +338,6 @@ class T2SEngine(T2SEngineProtocol):
|
||||
weights_path: os.PathLike,
|
||||
max_batch_size: int = 1,
|
||||
backend: str = "Flash-Attn-Varlen-CUDAGraph",
|
||||
quantize_mode: Optional[Literal["Int8", "FP8", "FP8_E4M3FN"]] = None,
|
||||
max_seq_length: Optional[int] = None,
|
||||
) -> T2SDecoderABC:
|
||||
logger.info(f"Loading Text2Semantic Weights from {weights_path} with {backend} Backend")
|
||||
@ -360,8 +357,4 @@ class T2SEngine(T2SEngineProtocol):
|
||||
state_dict = dict_s1["weight"]
|
||||
decoder.load_state_dict(state_dict)
|
||||
|
||||
if quantize_mode is not None:
|
||||
decoder.quantize(quantize_mode)
|
||||
logger.info(f"Quantized by {quantize_mode} Quantization")
|
||||
|
||||
return decoder.eval()
|
||||
|
||||
@ -5,19 +5,14 @@ Modified From https://github.com/XXXXRT666/GPT-SoVITS
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable, MutableSequence
|
||||
from contextlib import nullcontext
|
||||
from typing import TYPE_CHECKING, Any, Literal, Optional
|
||||
from typing import TYPE_CHECKING, Any, Optional
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch.profiler import ProfilerAction, tensorboard_trace_handler
|
||||
|
||||
from .. import nn
|
||||
from .quantization import replace_all_linear_with_fp8
|
||||
from .structs import KVCache, KVCacheProtocol, T2SSession
|
||||
|
||||
|
||||
@ -422,9 +417,6 @@ class T2SDecoderABC(nn.Module, ABC):
|
||||
self.graph_applicable: bool = False
|
||||
self.extra_buffer_factory: Callable[[int, T2SDecoderABC], dict[str, torch.Tensor]] = lambda *_: {}
|
||||
|
||||
self.bits: int
|
||||
self.group_size: int
|
||||
|
||||
self._register_load_state_dict_pre_hook(self.load_hook)
|
||||
|
||||
def load_hook(self, state_dict: dict[str, Tensor], prefix, *args):
|
||||
@ -534,95 +526,4 @@ class T2SDecoderABC(nn.Module, ABC):
|
||||
mask[:bsz].zero_()
|
||||
mask[:bsz, :, :, 0] = True
|
||||
kwds["attn_mask"] = mask
|
||||
return args, kwds
|
||||
|
||||
def quantize(self, mode: Optional[Literal["Int8", "FP8", "FP8_E4M3FN"]] = None) -> None:
|
||||
if mode is None:
|
||||
return
|
||||
if mode not in {"Int8", "FP8", "FP8_E4M3FN"}:
|
||||
raise ValueError(f"Unsupported quantization mode: {mode}")
|
||||
if mode == "Int8":
|
||||
self.bits = 8
|
||||
self.group_size = 32
|
||||
import torchao
|
||||
|
||||
torchao.quantization.quantize_(self.h, torchao.quantization.Int8WeightOnlyConfig(self.group_size))
|
||||
|
||||
elif mode == "FP8":
|
||||
self.bits = 8
|
||||
import torchao
|
||||
|
||||
torchao.quantization.quantize_(self.h, torchao.quantization.Float8WeightOnlyConfig())
|
||||
|
||||
elif mode == "FP8_E4M3FN":
|
||||
self.bits = 8
|
||||
replace_all_linear_with_fp8(self.h)
|
||||
|
||||
else:
|
||||
raise ValueError(f"Unsupported Quantization Mode for PyTorch: {mode}")
|
||||
|
||||
|
||||
class TorchProfiler:
|
||||
def __init__(self, debug: bool, log_dir: str = "./profiler/torch") -> None:
|
||||
self.debug = debug and os.environ.get("TORCH_PROFILER") == "1"
|
||||
self.log_dir = log_dir + "/" + str(time.time())
|
||||
self.__profiler: torch.profiler.profile
|
||||
|
||||
if self.debug and not os.path.exists(self.log_dir):
|
||||
os.makedirs(self.log_dir, exist_ok=True)
|
||||
|
||||
self.tensorboard_handler = tensorboard_trace_handler(self.log_dir)
|
||||
|
||||
def profiler_callback(self, prof: torch.profiler.profile):
|
||||
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=30))
|
||||
print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=30))
|
||||
self.tensorboard_handler(prof)
|
||||
|
||||
@staticmethod
|
||||
def three_step_schedule(step: int) -> ProfilerAction:
|
||||
if step == 0:
|
||||
return ProfilerAction.NONE
|
||||
elif step == 1:
|
||||
return ProfilerAction.RECORD
|
||||
elif step == 2:
|
||||
return ProfilerAction.RECORD_AND_SAVE
|
||||
else:
|
||||
return ProfilerAction.RECORD_AND_SAVE
|
||||
|
||||
def start(self):
|
||||
if not self.debug:
|
||||
return
|
||||
assert self.__profiler is not None
|
||||
self.__profiler.step()
|
||||
|
||||
def end(self):
|
||||
if not self.debug:
|
||||
return
|
||||
assert self.__profiler is not None
|
||||
self.__profiler.step()
|
||||
|
||||
def profiler(self):
|
||||
if self.debug:
|
||||
activities_list = [torch.profiler.ProfilerActivity.CPU]
|
||||
if torch.cuda.is_available():
|
||||
activities_list.append(torch.profiler.ProfilerActivity.CUDA)
|
||||
|
||||
self.__profiler = torch.profiler.profile(
|
||||
activities=activities_list,
|
||||
record_shapes=True,
|
||||
with_stack=True,
|
||||
with_modules=True,
|
||||
with_flops=True,
|
||||
profile_memory=True,
|
||||
schedule=self.three_step_schedule,
|
||||
on_trace_ready=self.profiler_callback,
|
||||
)
|
||||
return self.__profiler
|
||||
else:
|
||||
return nullcontext()
|
||||
|
||||
def record(self, func_name: str):
|
||||
if self.debug:
|
||||
return torch.profiler.record_function(func_name)
|
||||
else:
|
||||
return nullcontext()
|
||||
return args, kwds
|
||||
|
||||
@ -1,238 +0,0 @@
|
||||
import math
|
||||
from collections.abc import MutableSequence
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from transformers import BertConfig
|
||||
|
||||
from .. import nn
|
||||
from ..nn import functional as F
|
||||
|
||||
|
||||
Tensor = torch.Tensor
|
||||
|
||||
|
||||
class MultiHeadAttention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
dims: int,
|
||||
num_heads: int,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
assert dims % num_heads == 0, "The input feature dimensions should be divisible by the number of heads"
|
||||
|
||||
self.num_heads = num_heads
|
||||
self.query_proj = nn.Linear(dims, dims)
|
||||
self.key_proj = nn.Linear(dims, dims)
|
||||
self.value_proj = nn.Linear(dims, dims)
|
||||
self.out_proj = nn.Linear(dims, dims)
|
||||
self.scale = math.sqrt(1 / dims)
|
||||
|
||||
def __call__(self, x: Tensor):
|
||||
B, L, _ = x.shape
|
||||
queries = self.query_proj(x)
|
||||
keys = self.key_proj(x)
|
||||
values = self.value_proj(x)
|
||||
|
||||
num_heads = self.num_heads
|
||||
queries = queries.view(B, L, num_heads, -1).transpose(1, 2)
|
||||
keys = keys.view(B, L, num_heads, -1).transpose(1, 2)
|
||||
values = values.view(B, L, num_heads, -1).transpose(1, 2)
|
||||
output = F.scaled_dot_product_attention(queries, keys, values, scale=self.scale)
|
||||
output = output.transpose(1, 2).reshape(B, L, -1)
|
||||
return self.out_proj(output)
|
||||
|
||||
|
||||
class TransformerEncoderLayer(nn.Module):
|
||||
"""
|
||||
A transformer encoder layer with (the original BERT) post-normalization.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dims: int,
|
||||
num_heads: int,
|
||||
mlp_dims: int,
|
||||
layer_norm_eps: float = 1e-12,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.attention = MultiHeadAttention(dims, num_heads)
|
||||
self.attention_norm = nn.LayerNorm(dims, eps=layer_norm_eps)
|
||||
self.ffn_norm = nn.LayerNorm(dims, eps=layer_norm_eps)
|
||||
self.linear1 = nn.Linear(dims, mlp_dims)
|
||||
self.linear2 = nn.Linear(mlp_dims, dims)
|
||||
self.gelu = nn.GELU()
|
||||
|
||||
def __call__(self, x: Tensor):
|
||||
attention_out = self.attention(x)
|
||||
add_and_norm = self.attention_norm(x + attention_out)
|
||||
|
||||
ff = self.linear1(add_and_norm)
|
||||
ff_gelu = self.gelu(ff)
|
||||
ff_out = self.linear2(ff_gelu)
|
||||
x = self.ffn_norm(ff_out + add_and_norm)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class TransformerEncoder(nn.Module):
|
||||
def __init__(self, num_layers: int, dims: int, num_heads: int, mlp_dims: int):
|
||||
super().__init__()
|
||||
self.layers: MutableSequence[TransformerEncoderLayer] = nn.ModuleList(
|
||||
[TransformerEncoderLayer(dims, num_heads, mlp_dims) for _ in range(num_layers)]
|
||||
) # type: ignore
|
||||
|
||||
def __call__(self, x: Tensor):
|
||||
for layer in self.layers:
|
||||
x = layer(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class BertEmbeddings(nn.Module):
|
||||
def __init__(self, config: BertConfig):
|
||||
super().__init__()
|
||||
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
|
||||
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
||||
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
||||
self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
||||
self.requires_grad_(False)
|
||||
|
||||
def __call__(self, input_ids: Tensor):
|
||||
words = self.word_embeddings(input_ids)
|
||||
position = self.position_embeddings.weight[: input_ids.shape[1]]
|
||||
token_types = self.token_type_embeddings.weight[0]
|
||||
|
||||
embeddings = position + words + token_types
|
||||
return self.norm(embeddings)
|
||||
|
||||
|
||||
class Bert(nn.Module):
|
||||
def __init__(self, config: BertConfig):
|
||||
super().__init__()
|
||||
self.embeddings = BertEmbeddings(config)
|
||||
self.encoder = TransformerEncoder(
|
||||
num_layers=config.num_hidden_layers,
|
||||
dims=config.hidden_size,
|
||||
num_heads=config.num_attention_heads,
|
||||
mlp_dims=config.intermediate_size,
|
||||
)
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
input_ids: Tensor,
|
||||
):
|
||||
x = self.embeddings(input_ids)
|
||||
|
||||
y = self.encoder(x)
|
||||
return y
|
||||
|
||||
|
||||
class G2PW(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
config: BertConfig,
|
||||
num_labels: int = 1305,
|
||||
num_chars: int = 3582,
|
||||
num_pos_tags: int = 11,
|
||||
):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.num_labels = num_labels
|
||||
self.num_chars = num_chars
|
||||
self.num_pos_tags = num_pos_tags
|
||||
target_size = self.num_labels
|
||||
|
||||
self.bert = Bert(config)
|
||||
self.pos_classifier = nn.Linear(self.config.hidden_size, self.num_pos_tags)
|
||||
self.descriptor_bias = nn.Embedding(1, target_size)
|
||||
self.char_descriptor = nn.Embedding(self.num_chars, target_size)
|
||||
self.second_order_descriptor = nn.Embedding(self.num_chars * self.num_pos_tags, target_size)
|
||||
self.classifier = nn.Linear(self.config.hidden_size, self.num_labels)
|
||||
|
||||
def _weighted_softmax(self, logits: Tensor, weights: Tensor, eps: float):
|
||||
max_logits, _ = torch.max(logits, dim=-1, keepdim=True)
|
||||
weighted_exp_logits = torch.exp(logits - max_logits) * weights
|
||||
norm = torch.sum(weighted_exp_logits, dim=-1, keepdim=True)
|
||||
probs = weighted_exp_logits / norm
|
||||
probs = torch.clamp(probs, min=eps, max=1 - eps)
|
||||
|
||||
return probs
|
||||
|
||||
def _get_char_pos_ids(self, char_ids: Tensor, pos_ids: Tensor):
|
||||
return char_ids * self.num_pos_tags + pos_ids
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
input_ids: Tensor,
|
||||
phoneme_mask: Tensor,
|
||||
char_ids: Tensor,
|
||||
position_ids: Tensor,
|
||||
eps: float = 1e-6,
|
||||
):
|
||||
input_ids = input_ids.to(self.device)
|
||||
phoneme_mask = phoneme_mask.to(self.device)
|
||||
char_ids = char_ids.to(self.device)
|
||||
position_ids = position_ids.to(self.device)
|
||||
|
||||
sequence_output = self.bert(
|
||||
input_ids=input_ids,
|
||||
)
|
||||
|
||||
orig_selected_hidden = torch.take_along_dim(
|
||||
sequence_output,
|
||||
position_ids.view(-1, 1, 1),
|
||||
dim=1,
|
||||
).squeeze(1)
|
||||
|
||||
pred_pos_ids = self.pos_classifier(orig_selected_hidden).argmax(dim=-1) # teacher mode while training
|
||||
|
||||
bias_tensor = self.descriptor_bias(torch.zeros_like(char_ids))
|
||||
|
||||
char_pos_ids = self._get_char_pos_ids(char_ids, pred_pos_ids)
|
||||
|
||||
affect_hidden = bias_tensor + self.char_descriptor(char_ids) + self.second_order_descriptor(char_pos_ids)
|
||||
|
||||
phoneme_mask = phoneme_mask * torch.sigmoid(affect_hidden)
|
||||
|
||||
logits = self.classifier(orig_selected_hidden)
|
||||
|
||||
probs = self._weighted_softmax(logits, phoneme_mask, eps)
|
||||
|
||||
pred_idx = probs.argmax(dim=1)
|
||||
|
||||
return pred_idx
|
||||
|
||||
|
||||
def replace_key(key: str) -> str:
|
||||
key = key.replace(".layer.", ".layers.")
|
||||
key = key.replace(".self.key.", ".key_proj.")
|
||||
key = key.replace(".self.query.", ".query_proj.")
|
||||
key = key.replace(".self.value.", ".value_proj.")
|
||||
key = key.replace(".attention.output.dense.", ".attention.out_proj.")
|
||||
key = key.replace(".attention.output.LayerNorm.", ".attention_norm.")
|
||||
key = key.replace(".output.LayerNorm.", ".ffn_norm.")
|
||||
key = key.replace(".intermediate.dense.", ".linear1.")
|
||||
key = key.replace(".output.dense.", ".linear2.")
|
||||
key = key.replace(".LayerNorm.", ".norm.")
|
||||
return key
|
||||
|
||||
|
||||
def load_g2pw_torch(bert_model: str, weights_path: str, device: torch.device, dtype: torch.dtype) -> G2PW:
|
||||
if not Path(weights_path).exists():
|
||||
raise ValueError(f"No model weights found in {weights_path}")
|
||||
|
||||
config = BertConfig.from_pretrained(bert_model)
|
||||
|
||||
# create and update the model
|
||||
model = G2PW(config)
|
||||
state_dict: dict[str, Tensor] = torch.load(weights_path, map_location="cpu")
|
||||
state_dict_torch: dict[str, Tensor] = {}
|
||||
for key, value in state_dict.items():
|
||||
key = replace_key(key)
|
||||
state_dict_torch[key] = value
|
||||
model.load_state_dict(state_dict_torch)
|
||||
|
||||
return model.to(device, dtype)
|
||||
@ -1,15 +1,7 @@
|
||||
import importlib.util
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
import torch
|
||||
|
||||
from .AR.sample_funcs import sample_naive
|
||||
from .AR.structs import T2SRequest, T2SResult
|
||||
from .AR.t2s_engine import T2SEngine as T2SEngineTorch
|
||||
from .G2PW.model import load_g2pw_torch
|
||||
|
||||
|
||||
torch.set_grad_enabled(False)
|
||||
|
||||
if torch.__version__ >= "2.9.0":
|
||||
@ -26,47 +18,4 @@ torch.backends.cudnn.enabled = True
|
||||
|
||||
cpu_count = os.cpu_count() or 1
|
||||
torch.set_num_threads(cpu_count)
|
||||
torch.set_num_interop_threads(cpu_count)
|
||||
|
||||
backends = ["torch_varlen"]
|
||||
if torch.cuda.is_available() and torch.version.cuda is not None:
|
||||
backends.append("torch_static_cuda_graph")
|
||||
# if importlib.util.find_spec("sageattention") is not None:
|
||||
# for i in range(torch.cuda.device_count()):
|
||||
# major, minor = torch.cuda.get_device_capability(i)
|
||||
# sm_version = major + minor / 10.0
|
||||
# if sm_version >= 7.0:
|
||||
# backends.append("sage_attn_varlen_cuda_graph")
|
||||
if importlib.util.find_spec("flash_attn") is not None:
|
||||
for i in range(torch.cuda.device_count()):
|
||||
major, minor = torch.cuda.get_device_capability(i)
|
||||
sm_version = major + minor / 10.0
|
||||
if sm_version >= 7.5:
|
||||
backends.append("flash_attn_varlen_cuda_graph")
|
||||
|
||||
BLACKWELL = False
|
||||
if torch.cuda.is_available() and torch.version.cuda is not None:
|
||||
for i in range(torch.cuda.device_count()):
|
||||
major, minor = torch.cuda.get_device_capability(i)
|
||||
sm_version = major + minor / 10.0
|
||||
if sm_version >= 9.0:
|
||||
BLACKWELL = True
|
||||
|
||||
quantization_methods_torch: list[Optional[str]] = [None]
|
||||
if importlib.util.find_spec("torchao") is not None:
|
||||
quantization_methods_torch.append("Int8")
|
||||
if BLACKWELL:
|
||||
quantization_methods_torch.append("FP8")
|
||||
if BLACKWELL:
|
||||
quantization_methods_torch.append("FP8_E4M3FN")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"T2SEngineTorch",
|
||||
"T2SRequest",
|
||||
"sample_naive",
|
||||
"T2SResult",
|
||||
"backends",
|
||||
"quantization_methods_torch",
|
||||
"load_g2pw_torch",
|
||||
]
|
||||
torch.set_num_interop_threads(cpu_count)
|
||||
|
||||
@ -1,62 +0,0 @@
|
||||
# Accel 通用运行说明
|
||||
|
||||
本目录及配套修改代码统一用于 `gsvv5/py312` 和 `gsvv5/py39` 下的四套包。各自 runtime 保留:py312 为 Torch 2.7.1+cu118 / 2.7.1+cu128,py39 为 Torch 2.0.0+cu118 / 2.7.0+cu128。运行依赖不随源码统一而替换。
|
||||
|
||||
## 目录与依赖
|
||||
|
||||
- `GPT_SoVITS/Accel` 包含 PyTorch/MLX 后端、适配器、日志模块和 `vendor/cuda/bin/cudart64_12.dll`。
|
||||
- py312 的 FlashAttention 2.8.3 通过标准 pip 安装在各自 `runtime/Lib/site-packages`;不从外置测试目录导入。两套 py39 未安装 FlashAttention,对应控件自动隐藏。
|
||||
- `tools/acceleration.py` 负责能力选择,`tools/portable_runtime.py` 负责便携环境、DLL 搜索路径和 Transformers 兼容初始化。
|
||||
- 正常推理不依赖 `others`;测试、备份、网络 requirements 和补丁 ZIP 均放在 `others`。
|
||||
- 超分配置 `tools/AP_BWE_main/24kto48k/config.json` 保留。原版 BigVGAN/UVR 运行文件、模型权重及 runtime 未删除。
|
||||
|
||||
## 自动推理路线
|
||||
|
||||
Graph 和外部 FlashAttention 分别识别,按实际推理设备、精度与用户开关选择:
|
||||
|
||||
| 启用 FlashAttention | 有效 CUDA Graph | 非流式 AR |
|
||||
| --- | --- | --- |
|
||||
| 是 | 是 | FlashAttention + Graph |
|
||||
| 是 | 否 | FlashAttention eager |
|
||||
| 否 | 是 | 纯 Torch SDPA Graph |
|
||||
| 否 | 否 | 原始普通 AR |
|
||||
|
||||
主 WebUI 未勾选“启用并行推理版本”时,普通子 WebUI 固定逐句 `bs=1`,Accel 容量为 1,只捕获单批 Graph,不提供 batch size 或并行开关。勾选后启动快速子 WebUI,保留原 `batch_size` 滑块(1–200,默认 20),固定并行,Accel 容量随滑块调整。
|
||||
|
||||
两个子 WebUI 都只提供 `CUDA Graph` 和 `flash_attn` 两个加速开关。启动时分别判断当前设备能力;支持时默认勾选、显示且可修改,不支持时默认关闭、隐藏且不可修改。用户可以独立关闭任一能力,`CUDAGraph=0` 仍禁用 Graph。真正 token 流式保留原实现,API 的 `parallel_infer` 参数保留。
|
||||
|
||||
Graph 实际捕获失败时,Flash 继续 eager,纯 Torch Graph 回普通 AR;记录失败状态,避免反复捕获。权重加载和实际推理错误正常抛出,不隐藏为能力缺失。尊重传入 dtype,不强制 FP32 转 FP16。换权重、设备或精度时关闭旧引擎。
|
||||
|
||||
## 中文 G2PW DLL 修复
|
||||
|
||||
普通版 ONNX Runtime 1.18.0 需要 CUDA 11 / cuDNN 8,而 Torch 自带 cuDNN 9。配套 cuDNN 8 已安装在 `runtime/Lib/site-packages/nvidia/*/bin`。初始化现会注册存在的 DLL 目录,并加入当前进程 PATH,以支持 cuDNN 动态加载其组件 DLL。
|
||||
|
||||
此处理也适用于 CUDA 12 环境的 Torch DLL。未修改系统 PATH、CUDA_PATH、库版本或 site-packages,未把 G2PW 改成 CPU。UVR5 的 `onnx_dereverb_By_FoxJoy` 创建 ONNX Runtime 会话前也调用同一 DLL 初始化,因此该模型可使用 CUDA/cuDNN。已经运行的推理窗口需要重新启动才能加载修改。
|
||||
|
||||
## 兼容与安装
|
||||
|
||||
Accel 源码采用 Python 3.9 兼容语法;旧 Torch 不支持的六项 `_inductor.config` 内部设置已移除,权重加载仅在支持时传 `mmap`。语法兼容不代表旧 py39 环境的全部功能已实测。
|
||||
|
||||
以下五项不再设置:`preferred_blas_library`、`ExecutionTraceObserver`、`torch.compiler.disable` 包装、`allow_fp16_accumulation=True`、`allow_fp16_bf16_reduction_math_sdp(True)`。原有可选 Torch profiler/TensorBoard 保留,uvloop 是可选依赖。
|
||||
|
||||
四份网络安装清单位于 `others/requirements-py312-win-flash_attention`,按 cu118/cu128 和国内 ModelScope/国外 Hugging Face 选择。适用于 Windows x64、CPython 3.12、Torch 2.7.1;先安装匹配 Torch,再使用清单。现有 FlashAttention cp312 Windows wheel 不能用于 Python 3.9 或 Linux。网络清单尚未在空白环境完成全部安装测试。
|
||||
|
||||
## 通用补丁
|
||||
|
||||
`gsvv5/py312/others/add_accel/GPT-SoVITS_add_accel.zip` 是四套包共用的唯一当前补丁。ZIP 保留项目相对路径,直接解压至目标项目根目录。四套 runtime 不互相覆盖。
|
||||
|
||||
包含 Accel 完整发布内容(Python 源码、此说明及 vendor CUDA DLL),加上目录外新增 3 个、修改 9 个文件;其中 `tools/portable_runtime.py` 已包含最新 G2PW DLL 修复,`tools/uvr5/mdxnet.py` 已包含 FoxJoy ONNX CUDA DLL 修复。不包含 runtime、site-packages、FlashAttention wheel、模型权重、测试结果或 `__pycache__`。
|
||||
|
||||
## 已完成的运行测试
|
||||
|
||||
本机 RTX 3090,两套 Python 3.12 环境均完成适配器模式切换、无参考文本、v2 TTS 四种 Graph/并行组合;各完成八种能力缺失/捕获失败/流式切换场景,均产生音频。
|
||||
|
||||
最新中文测试使用 `s1v3.ckpt` 与 `s2Gv2ProPlus.pth`:两套 G2PW 均使用 CUDAExecutionProvider,成功处理中文文本,并完成并行 Graph 和串行 eager 完整 TTS。
|
||||
|
||||
py312 普通子 WebUI 已完成四种 Flash/Graph 开关组合及重新开启双开的真实合成,均为 `bs=1`;关闭两者时使用原始 AR。快速子 WebUI 保留默认 `bs=20` 滑块,已检查 1、20、40、200 的参数绑定;本轮未重复执行用户已确认成功的四环境并行 TTS。py312 控件默认双开,py39 缺 Flash 时正确隐藏该控件,CPU 下两个控件均默认关闭且隐藏。
|
||||
|
||||
四套 runtime 均通过真实 `tools/uvr5/webui.py` 的 FoxJoy 去混响入口,性能记录每套含 278 次 `CUDAExecutionProvider` 节点执行、无 CPU 模型节点。人声与伴奏输出均为 44.1 kHz 双声道;py39 NVIDIA 的 MDX 初始化调用已补齐。测试输出位于各自 `others/<包名>/foxjoy_gpu_20261005_current`。
|
||||
|
||||
未测试所有模型版本、其他 GPU、Linux/MLX;未试听或证明不同路线音质/输出等价。浏览器测试页停留在 Gradio 加载画面,控件与调用检查取自实际 Gradio 配置和入口函数,本轮不宣称浏览器端完整交互已通过。
|
||||
|
||||
运行记录与报告位于 `others/<对应包名>`、`others/auto_acceleration_changes_20261005.md` 和 `others/onnx_chinese_fix_20261005.md`。历史分版结果保留在外置目录,不放进通用补丁。
|
||||
@ -1,40 +1,9 @@
|
||||
from . import runtime
|
||||
from .logger import console, logger, tb
|
||||
|
||||
from . import MLX, PyTorch
|
||||
from .MLX import quantization_methods_mlx
|
||||
from .PyTorch import T2SEngineTorch, T2SRequest, T2SResult, quantization_methods_torch
|
||||
from .PyTorch.AR.structs import T2SEngineProtocol
|
||||
|
||||
|
||||
import asyncio
|
||||
|
||||
if runtime.os.name != "nt":
|
||||
try:
|
||||
import uvloop
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
|
||||
|
||||
backends = PyTorch.backends + MLX.backends
|
||||
|
||||
backends = [
|
||||
b.replace("_", "-").title().replace("Mlx", "MLX").replace("Mps", "MPS").replace("Cuda", "CUDA") for b in backends
|
||||
]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"T2SEngineTorch",
|
||||
"T2SRequest",
|
||||
"T2SResult",
|
||||
"backends",
|
||||
"MLX",
|
||||
"PyTorch",
|
||||
"logger",
|
||||
"console",
|
||||
"tb",
|
||||
"T2SEngineProtocol",
|
||||
"quantization_methods_torch",
|
||||
"quantization_methods_mlx",
|
||||
]
|
||||
"""Optional PyTorch acceleration for the inference service."""
|
||||
|
||||
import os
|
||||
|
||||
from tools.portable_runtime import _prepare_dlls
|
||||
|
||||
|
||||
os.environ.setdefault("G2PW", "0")
|
||||
_prepare_dlls()
|
||||
|
||||
@ -1,7 +1,4 @@
|
||||
import sys
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from contextlib import nullcontext
|
||||
from typing import Optional
|
||||
|
||||
from loguru import logger
|
||||
@ -10,7 +7,7 @@ from rich.highlighter import Highlighter
|
||||
from rich.logging import RichHandler
|
||||
from rich.progress import Task, TextColumn
|
||||
from rich.style import StyleType
|
||||
from rich.table import Column, Table
|
||||
from rich.table import Column
|
||||
from rich.text import Text
|
||||
from rich.traceback import Traceback, install
|
||||
|
||||
@ -199,75 +196,3 @@ def tb(show_locals: bool = True):
|
||||
|
||||
|
||||
__all__ = ["logger", "console", "tb", "SpeedColumnToken", "SpeedColumnIteration"]
|
||||
|
||||
|
||||
class Timer:
|
||||
def __init__(self, table_name: str = "Default Timer"):
|
||||
self.records: dict[str, list[float]] = defaultdict(list)
|
||||
self._stack: list[tuple[str, int]] = []
|
||||
self.table_name = table_name
|
||||
|
||||
def __call__(self, category: str, debug=False):
|
||||
timer = self
|
||||
|
||||
class _Ctx:
|
||||
def __enter__(self):
|
||||
timer._stack.append((category, time.perf_counter_ns()))
|
||||
return timer
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
end = time.perf_counter_ns()
|
||||
if not timer._stack:
|
||||
raise RuntimeError("Timer stack underflow: __exit__ without matching __enter__")
|
||||
cat, start = timer._stack.pop()
|
||||
if cat != category:
|
||||
raise RuntimeError(f"Mismatched timer context: expected '{cat}', got '{category}'")
|
||||
elapsed_sec = (end - start) / 1e9
|
||||
timer.records[cat].append(elapsed_sec)
|
||||
return False
|
||||
|
||||
if debug:
|
||||
return _Ctx()
|
||||
else:
|
||||
return nullcontext()
|
||||
|
||||
def clear(self):
|
||||
self.records.clear()
|
||||
|
||||
def summary(self):
|
||||
if self.records.items():
|
||||
table = Table(title=self.table_name)
|
||||
|
||||
table.add_column("Category", justify="left", style="cyan", no_wrap=True)
|
||||
table.add_column("Count", justify="right", style="magenta")
|
||||
table.add_column("Total (s)", justify="right", style="green")
|
||||
table.add_column("Average (s)", justify="right", style="yellow")
|
||||
|
||||
for cat, times in self.records.items():
|
||||
total = sum(times)
|
||||
avg = total / len(times) if times else 0.0
|
||||
table.add_row(cat, str(len(times)), f"{total:.6f}", f"{avg:.6f}")
|
||||
|
||||
console.print(table)
|
||||
|
||||
|
||||
timer = Timer()
|
||||
|
||||
|
||||
def format_sig(x: float, sig=4):
|
||||
if x > 10**sig:
|
||||
s = f"{x:.{sig + 1}g}"
|
||||
elif x < 1:
|
||||
s = f"{x:.{sig}f}"
|
||||
else:
|
||||
s = f"{x:.{sig}g}"
|
||||
if "e" in s or "E" in s:
|
||||
s = f"{float(s):f}"
|
||||
return s
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise RuntimeError()
|
||||
except Exception:
|
||||
logger.bind(show_locals=False).exception("TEST")
|
||||
|
||||
@ -1,20 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||
ACCEL_ROOT = Path(__file__).resolve().parent
|
||||
VENDOR_ROOT = ACCEL_ROOT / "vendor"
|
||||
DLL_HANDLES = []
|
||||
|
||||
os.environ.setdefault("G2PW", "0")
|
||||
if os.name == "nt":
|
||||
for directory in (
|
||||
VENDOR_ROOT / "cuda" / "bin",
|
||||
Path(sys.executable).resolve().parent / "Lib" / "site-packages" / "torch" / "lib",
|
||||
):
|
||||
if directory.is_dir():
|
||||
DLL_HANDLES.append(os.add_dll_directory(str(directory)))
|
||||
@ -1,266 +0,0 @@
|
||||
## BigVGAN: A Universal Neural Vocoder with Large-Scale Training
|
||||
|
||||
#### Sang-gil Lee, Wei Ping, Boris Ginsburg, Bryan Catanzaro, Sungroh Yoon
|
||||
|
||||
[[Paper]](https://arxiv.org/abs/2206.04658) - [[Code]](https://github.com/NVIDIA/BigVGAN) - [[Showcase]](https://bigvgan-demo.github.io/) - [[Project Page]](https://research.nvidia.com/labs/adlr/projects/bigvgan/) - [[Weights]](https://huggingface.co/collections/nvidia/bigvgan-66959df3d97fd7d98d97dc9a) - [[Demo]](https://huggingface.co/spaces/nvidia/BigVGAN)
|
||||
|
||||
[](https://paperswithcode.com/sota/speech-synthesis-on-libritts?p=bigvgan-a-universal-neural-vocoder-with-large)
|
||||
|
||||
<center><img src="https://user-images.githubusercontent.com/15963413/218609148-881e39df-33af-4af9-ab95-1427c4ebf062.png" width="800"></center>
|
||||
|
||||
## News
|
||||
- **Sep 2024 (v2.4):**
|
||||
- We have updated the pretrained checkpoints trained for 5M steps. This is final release of the BigVGAN-v2 checkpoints.
|
||||
|
||||
- **Jul 2024 (v2.3):**
|
||||
- General refactor and code improvements for improved readability.
|
||||
- Fully fused CUDA kernel of anti-alised activation (upsampling + activation + downsampling) with inference speed benchmark.
|
||||
|
||||
- **Jul 2024 (v2.2):** The repository now includes an interactive local demo using gradio.
|
||||
|
||||
- **Jul 2024 (v2.1):** BigVGAN is now integrated with 🤗 Hugging Face Hub with easy access to inference using pretrained checkpoints. We also provide an interactive demo on Hugging Face Spaces.
|
||||
|
||||
- **Jul 2024 (v2):** We release BigVGAN-v2 along with pretrained checkpoints. Below are the highlights:
|
||||
- Custom CUDA kernel for inference: we provide a fused upsampling + activation kernel written in CUDA for accelerated inference speed. Our test shows 1.5 - 3x faster speed on a single A100 GPU.
|
||||
- Improved discriminator and loss: BigVGAN-v2 is trained using a [multi-scale sub-band CQT discriminator](https://arxiv.org/abs/2311.14957) and a [multi-scale mel spectrogram loss](https://arxiv.org/abs/2306.06546).
|
||||
- Larger training data: BigVGAN-v2 is trained using datasets containing diverse audio types, including speech in multiple languages, environmental sounds, and instruments.
|
||||
- We provide pretrained checkpoints of BigVGAN-v2 using diverse audio configurations, supporting up to 44 kHz sampling rate and 512x upsampling ratio.
|
||||
|
||||
## Installation
|
||||
|
||||
The codebase has been tested on Python `3.10` and PyTorch `2.3.1` conda packages with either `pytorch-cuda=12.1` or `pytorch-cuda=11.8`. Below is an example command to create the conda environment:
|
||||
|
||||
```shell
|
||||
conda create -n bigvgan python=3.10 pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia
|
||||
conda activate bigvgan
|
||||
```
|
||||
|
||||
Clone the repository and install dependencies:
|
||||
|
||||
```shell
|
||||
git clone https://github.com/NVIDIA/BigVGAN
|
||||
cd BigVGAN
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
## Inference Quickstart using 🤗 Hugging Face Hub
|
||||
|
||||
Below example describes how you can use BigVGAN: load the pretrained BigVGAN generator from Hugging Face Hub, compute mel spectrogram from input waveform, and generate synthesized waveform using the mel spectrogram as the model's input.
|
||||
|
||||
```python
|
||||
device = 'cuda'
|
||||
|
||||
import torch
|
||||
import bigvgan
|
||||
import librosa
|
||||
from meldataset import get_mel_spectrogram
|
||||
|
||||
# instantiate the model. You can optionally set use_cuda_kernel=True for faster inference.
|
||||
model = bigvgan.BigVGAN.from_pretrained('nvidia/bigvgan_v2_24khz_100band_256x', use_cuda_kernel=False)
|
||||
|
||||
# remove weight norm in the model and set to eval mode
|
||||
model.remove_weight_norm()
|
||||
model = model.eval().to(device)
|
||||
|
||||
# load wav file and compute mel spectrogram
|
||||
wav_path = '/path/to/your/audio.wav'
|
||||
wav, sr = librosa.load(wav_path, sr=model.h.sampling_rate, mono=True) # wav is np.ndarray with shape [T_time] and values in [-1, 1]
|
||||
wav = torch.FloatTensor(wav).unsqueeze(0) # wav is FloatTensor with shape [B(1), T_time]
|
||||
|
||||
# compute mel spectrogram from the ground truth audio
|
||||
mel = get_mel_spectrogram(wav, model.h).to(device) # mel is FloatTensor with shape [B(1), C_mel, T_frame]
|
||||
|
||||
# generate waveform from mel
|
||||
with torch.inference_mode():
|
||||
wav_gen = model(mel) # wav_gen is FloatTensor with shape [B(1), 1, T_time] and values in [-1, 1]
|
||||
wav_gen_float = wav_gen.squeeze(0).cpu() # wav_gen is FloatTensor with shape [1, T_time]
|
||||
|
||||
# you can convert the generated waveform to 16 bit linear PCM
|
||||
wav_gen_int16 = (wav_gen_float * 32767.0).numpy().astype('int16') # wav_gen is now np.ndarray with shape [1, T_time] and int16 dtype
|
||||
```
|
||||
|
||||
## Local gradio demo <a href='https://github.com/gradio-app/gradio'><img src='https://img.shields.io/github/stars/gradio-app/gradio'></a>
|
||||
|
||||
You can run a local gradio demo using below command:
|
||||
|
||||
```python
|
||||
pip install -r demo/requirements.txt
|
||||
python demo/app.py
|
||||
```
|
||||
|
||||
## Training
|
||||
|
||||
Create symbolic link to the root of the dataset. The codebase uses filelist with the relative path from the dataset. Below are the example commands for LibriTTS dataset:
|
||||
|
||||
```shell
|
||||
cd filelists/LibriTTS && \
|
||||
ln -s /path/to/your/LibriTTS/train-clean-100 train-clean-100 && \
|
||||
ln -s /path/to/your/LibriTTS/train-clean-360 train-clean-360 && \
|
||||
ln -s /path/to/your/LibriTTS/train-other-500 train-other-500 && \
|
||||
ln -s /path/to/your/LibriTTS/dev-clean dev-clean && \
|
||||
ln -s /path/to/your/LibriTTS/dev-other dev-other && \
|
||||
ln -s /path/to/your/LibriTTS/test-clean test-clean && \
|
||||
ln -s /path/to/your/LibriTTS/test-other test-other && \
|
||||
cd ../..
|
||||
```
|
||||
|
||||
Train BigVGAN model. Below is an example command for training BigVGAN-v2 using LibriTTS dataset at 24kHz with a full 100-band mel spectrogram as input:
|
||||
|
||||
```shell
|
||||
python train.py \
|
||||
--config configs/bigvgan_v2_24khz_100band_256x.json \
|
||||
--input_wavs_dir filelists/LibriTTS \
|
||||
--input_training_file filelists/LibriTTS/train-full.txt \
|
||||
--input_validation_file filelists/LibriTTS/val-full.txt \
|
||||
--list_input_unseen_wavs_dir filelists/LibriTTS filelists/LibriTTS \
|
||||
--list_input_unseen_validation_file filelists/LibriTTS/dev-clean.txt filelists/LibriTTS/dev-other.txt \
|
||||
--checkpoint_path exp/bigvgan_v2_24khz_100band_256x
|
||||
```
|
||||
|
||||
## Synthesis
|
||||
|
||||
Synthesize from BigVGAN model. Below is an example command for generating audio from the model.
|
||||
It computes mel spectrograms using wav files from `--input_wavs_dir` and saves the generated audio to `--output_dir`.
|
||||
|
||||
```shell
|
||||
python inference.py \
|
||||
--checkpoint_file /path/to/your/bigvgan_v2_24khz_100band_256x/bigvgan_generator.pt \
|
||||
--input_wavs_dir /path/to/your/input_wav \
|
||||
--output_dir /path/to/your/output_wav
|
||||
```
|
||||
|
||||
`inference_e2e.py` supports synthesis directly from the mel spectrogram saved in `.npy` format, with shapes `[1, channel, frame]` or `[channel, frame]`.
|
||||
It loads mel spectrograms from `--input_mels_dir` and saves the generated audio to `--output_dir`.
|
||||
|
||||
Make sure that the STFT hyperparameters for mel spectrogram are the same as the model, which are defined in `config.json` of the corresponding model.
|
||||
|
||||
```shell
|
||||
python inference_e2e.py \
|
||||
--checkpoint_file /path/to/your/bigvgan_v2_24khz_100band_256x/bigvgan_generator.pt \
|
||||
--input_mels_dir /path/to/your/input_mel \
|
||||
--output_dir /path/to/your/output_wav
|
||||
```
|
||||
|
||||
## Using Custom CUDA Kernel for Synthesis
|
||||
|
||||
You can apply the fast CUDA inference kernel by using a parameter `use_cuda_kernel` when instantiating BigVGAN:
|
||||
|
||||
```python
|
||||
generator = BigVGAN(h, use_cuda_kernel=True)
|
||||
```
|
||||
|
||||
You can also pass `--use_cuda_kernel` to `inference.py` and `inference_e2e.py` to enable this feature.
|
||||
|
||||
When applied for the first time, it builds the kernel using `nvcc` and `ninja`. If the build succeeds, the kernel is saved to `alias_free_activation/cuda/build` and the model automatically loads the kernel. The codebase has been tested using CUDA `12.1`.
|
||||
|
||||
Please make sure that both are installed in your system and `nvcc` installed in your system matches the version your PyTorch build is using.
|
||||
|
||||
We recommend running `test_cuda_vs_torch_model.py` first to build and check the correctness of the CUDA kernel. See below example command and its output, where it returns `[Success] test CUDA fused vs. plain torch BigVGAN inference`:
|
||||
|
||||
```python
|
||||
python tests/test_cuda_vs_torch_model.py \
|
||||
--checkpoint_file /path/to/your/bigvgan_generator.pt
|
||||
```
|
||||
|
||||
```shell
|
||||
loading plain Pytorch BigVGAN
|
||||
...
|
||||
loading CUDA kernel BigVGAN with auto-build
|
||||
Detected CUDA files, patching ldflags
|
||||
Emitting ninja build file /path/to/your/BigVGAN/alias_free_activation/cuda/build/build.ninja..
|
||||
Building extension module anti_alias_activation_cuda...
|
||||
...
|
||||
Loading extension module anti_alias_activation_cuda...
|
||||
...
|
||||
Loading '/path/to/your/bigvgan_generator.pt'
|
||||
...
|
||||
[Success] test CUDA fused vs. plain torch BigVGAN inference
|
||||
> mean_difference=0.0007238413265440613
|
||||
...
|
||||
```
|
||||
|
||||
If you see `[Fail] test CUDA fused vs. plain torch BigVGAN inference`, it means that the CUDA kernel inference is incorrect. Please check if `nvcc` installed in your system is compatible with your PyTorch version.
|
||||
|
||||
## Pretrained Models
|
||||
|
||||
We provide the [pretrained models on Hugging Face Collections](https://huggingface.co/collections/nvidia/bigvgan-66959df3d97fd7d98d97dc9a).
|
||||
One can download the checkpoints of the generator weight (named `bigvgan_generator.pt`) and its discriminator/optimizer states (named `bigvgan_discriminator_optimizer.pt`) within the listed model repositories.
|
||||
|
||||
| Model Name | Sampling Rate | Mel band | fmax | Upsampling Ratio | Params | Dataset | Steps | Fine-Tuned |
|
||||
|:--------------------------------------------------------------------------------------------------------:|:-------------:|:--------:|:-----:|:----------------:|:------:|:--------------------------:|:-----:|:----------:|
|
||||
| [bigvgan_v2_44khz_128band_512x](https://huggingface.co/nvidia/bigvgan_v2_44khz_128band_512x) | 44 kHz | 128 | 22050 | 512 | 122M | Large-scale Compilation | 5M | No |
|
||||
| [bigvgan_v2_44khz_128band_256x](https://huggingface.co/nvidia/bigvgan_v2_44khz_128band_256x) | 44 kHz | 128 | 22050 | 256 | 112M | Large-scale Compilation | 5M | No |
|
||||
| [bigvgan_v2_24khz_100band_256x](https://huggingface.co/nvidia/bigvgan_v2_24khz_100band_256x) | 24 kHz | 100 | 12000 | 256 | 112M | Large-scale Compilation | 5M | No |
|
||||
| [bigvgan_v2_22khz_80band_256x](https://huggingface.co/nvidia/bigvgan_v2_22khz_80band_256x) | 22 kHz | 80 | 11025 | 256 | 112M | Large-scale Compilation | 5M | No |
|
||||
| [bigvgan_v2_22khz_80band_fmax8k_256x](https://huggingface.co/nvidia/bigvgan_v2_22khz_80band_fmax8k_256x) | 22 kHz | 80 | 8000 | 256 | 112M | Large-scale Compilation | 5M | No |
|
||||
| [bigvgan_24khz_100band](https://huggingface.co/nvidia/bigvgan_24khz_100band) | 24 kHz | 100 | 12000 | 256 | 112M | LibriTTS | 5M | No |
|
||||
| [bigvgan_base_24khz_100band](https://huggingface.co/nvidia/bigvgan_base_24khz_100band) | 24 kHz | 100 | 12000 | 256 | 14M | LibriTTS | 5M | No |
|
||||
| [bigvgan_22khz_80band](https://huggingface.co/nvidia/bigvgan_22khz_80band) | 22 kHz | 80 | 8000 | 256 | 112M | LibriTTS + VCTK + LJSpeech | 5M | No |
|
||||
| [bigvgan_base_22khz_80band](https://huggingface.co/nvidia/bigvgan_base_22khz_80band) | 22 kHz | 80 | 8000 | 256 | 14M | LibriTTS + VCTK + LJSpeech | 5M | No |
|
||||
|
||||
The paper results are based on the original 24kHz BigVGAN models (`bigvgan_24khz_100band` and `bigvgan_base_24khz_100band`) trained on LibriTTS dataset.
|
||||
We also provide 22kHz BigVGAN models with band-limited setup (i.e., fmax=8000) for TTS applications.
|
||||
Note that the checkpoints use `snakebeta` activation with log scale parameterization, which have the best overall quality.
|
||||
|
||||
You can fine-tune the models by:
|
||||
|
||||
1. downloading the checkpoints (both the generator weight and its discriminator/optimizer states)
|
||||
2. resuming training using your audio dataset by specifying `--checkpoint_path` that includes the checkpoints when launching `train.py`
|
||||
|
||||
## Training Details of BigVGAN-v2
|
||||
|
||||
Comapred to the original BigVGAN, the pretrained checkpoints of BigVGAN-v2 used `batch_size=32` with a longer `segment_size=65536` and are trained using 8 A100 GPUs.
|
||||
|
||||
Note that the BigVGAN-v2 `json` config files in `./configs` use `batch_size=4` as default to fit in a single A100 GPU for training. You can fine-tune the models adjusting `batch_size` depending on your GPUs.
|
||||
|
||||
When training BigVGAN-v2 from scratch with small batch size, it can potentially encounter the early divergence problem mentioned in the paper. In such case, we recommend lowering the `clip_grad_norm` value (e.g. `100`) for the early training iterations (e.g. 20000 steps) and increase the value to the default `500`.
|
||||
|
||||
## Evaluation Results of BigVGAN-v2
|
||||
|
||||
Below are the objective results of the 24kHz model (`bigvgan_v2_24khz_100band_256x`) obtained from the LibriTTS `dev` sets. BigVGAN-v2 shows noticeable improvements of the metrics. The model also exhibits reduced perceptual artifacts, especially for non-speech audio.
|
||||
|
||||
| Model | Dataset | Steps | PESQ(↑) | M-STFT(↓) | MCD(↓) | Periodicity(↓) | V/UV F1(↑) |
|
||||
|:----------:|:-----------------------:|:-----:|:---------:|:----------:|:----------:|:--------------:|:----------:|
|
||||
| BigVGAN | LibriTTS | 1M | 4.027 | 0.7997 | 0.3745 | 0.1018 | 0.9598 |
|
||||
| BigVGAN | LibriTTS | 5M | 4.256 | 0.7409 | 0.2988 | 0.0809 | 0.9698 |
|
||||
| BigVGAN-v2 | Large-scale Compilation | 3M | 4.359 | 0.7134 | 0.3060 | 0.0621 | 0.9777 |
|
||||
| BigVGAN-v2 | Large-scale Compilation | 5M | **4.362** | **0.7026** | **0.2903** | **0.0593** | **0.9793** |
|
||||
|
||||
## Speed Benchmark
|
||||
|
||||
Below are the speed and VRAM usage benchmark results of BigVGAN from `tests/test_cuda_vs_torch_model.py`, using `bigvgan_v2_24khz_100band_256x` as a reference model.
|
||||
|
||||
| GPU | num_mel_frame | use_cuda_kernel | Speed (kHz) | Real-time Factor | VRAM (GB) |
|
||||
|:--------------------------:|:-------------:|:---------------:|:-----------:|:----------------:|:---------:|
|
||||
| NVIDIA A100 | 256 | False | 1672.1 | 69.7x | 1.3 |
|
||||
| | | True | 3916.5 | 163.2x | 1.3 |
|
||||
| | 2048 | False | 1899.6 | 79.2x | 1.7 |
|
||||
| | | True | 5330.1 | 222.1x | 1.7 |
|
||||
| | 16384 | False | 1973.8 | 82.2x | 5.0 |
|
||||
| | | True | 5761.7 | 240.1x | 4.4 |
|
||||
| NVIDIA GeForce RTX 3080 | 256 | False | 841.1 | 35.0x | 1.3 |
|
||||
| | | True | 1598.1 | 66.6x | 1.3 |
|
||||
| | 2048 | False | 929.9 | 38.7x | 1.7 |
|
||||
| | | True | 1971.3 | 82.1x | 1.6 |
|
||||
| | 16384 | False | 943.4 | 39.3x | 5.0 |
|
||||
| | | True | 2026.5 | 84.4x | 3.9 |
|
||||
| NVIDIA GeForce RTX 2080 Ti | 256 | False | 515.6 | 21.5x | 1.3 |
|
||||
| | | True | 811.3 | 33.8x | 1.3 |
|
||||
| | 2048 | False | 576.5 | 24.0x | 1.7 |
|
||||
| | | True | 1023.0 | 42.6x | 1.5 |
|
||||
| | 16384 | False | 589.4 | 24.6x | 5.0 |
|
||||
| | | True | 1068.1 | 44.5x | 3.2 |
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
We thank Vijay Anand Korthikanti and Kevin J. Shih for their generous support in implementing the CUDA kernel for inference.
|
||||
|
||||
## References
|
||||
|
||||
- [HiFi-GAN](https://github.com/jik876/hifi-gan) (for generator and multi-period discriminator)
|
||||
- [Snake](https://github.com/EdwardDixon/snake) (for periodic activation)
|
||||
- [Alias-free-torch](https://github.com/junjun3518/alias-free-torch) (for anti-aliasing)
|
||||
- [Julius](https://github.com/adefossez/julius) (for low-pass filter)
|
||||
- [UnivNet](https://github.com/mindslab-ai/univnet) (for multi-resolution discriminator)
|
||||
- [descript-audio-codec](https://github.com/descriptinc/descript-audio-codec) and [vocos](https://github.com/gemelo-ai/vocos) (for multi-band multi-scale STFT discriminator and multi-scale mel spectrogram loss)
|
||||
- [Amphion](https://github.com/open-mmlab/Amphion) (for multi-scale sub-band CQT discriminator)
|
||||
@ -4,10 +4,8 @@
|
||||
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
|
||||
# LICENSE is in incl_licenses directory.
|
||||
|
||||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union, Dict
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
@ -15,11 +13,22 @@ from torch.nn import Conv1d, ConvTranspose1d
|
||||
from torch.nn.utils import weight_norm, remove_weight_norm
|
||||
|
||||
from . import activations
|
||||
from .utils0 import init_weights, get_padding
|
||||
from .alias_free_activation.torch.act import Activation1d as TorchActivation1d
|
||||
from .env import AttrDict
|
||||
|
||||
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
|
||||
|
||||
class AttrDict(dict):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.__dict__ = self
|
||||
|
||||
|
||||
def init_weights(module, mean=0.0, std=0.01):
|
||||
if "Conv" in module.__class__.__name__:
|
||||
module.weight.data.normal_(mean, std)
|
||||
|
||||
|
||||
def get_padding(kernel_size, dilation=1):
|
||||
return int((kernel_size * dilation - dilation) / 2)
|
||||
|
||||
|
||||
def load_hparams_from_json(path) -> AttrDict:
|
||||
@ -203,16 +212,7 @@ class AMPBlock2(torch.nn.Module):
|
||||
remove_weight_norm(l)
|
||||
|
||||
|
||||
class BigVGAN(
|
||||
torch.nn.Module,
|
||||
PyTorchModelHubMixin,
|
||||
# library_name="bigvgan",
|
||||
# repo_url="https://github.com/NVIDIA/BigVGAN",
|
||||
# docs_url="https://github.com/NVIDIA/BigVGAN/blob/main/README.md",
|
||||
# pipeline_tag="audio-to-audio",
|
||||
# license="mit",
|
||||
# tags=["neural-vocoder", "audio-generation", "arxiv:2206.04658"],
|
||||
):
|
||||
class BigVGAN(torch.nn.Module):
|
||||
"""
|
||||
BigVGAN is a neural vocoder model that applies anti-aliased periodic activation for residual blocks (resblocks).
|
||||
|
||||
@ -334,83 +334,17 @@ class BigVGAN(
|
||||
print("[INFO] Model already removed weight norm. Skipping!")
|
||||
pass
|
||||
|
||||
# Additional methods for huggingface_hub support
|
||||
def _save_pretrained(self, save_directory: Path) -> None:
|
||||
"""Save weights and config.json from a Pytorch model to a local directory."""
|
||||
|
||||
model_path = save_directory / "bigvgan_generator.pt"
|
||||
torch.save({"generator": self.state_dict()}, model_path)
|
||||
|
||||
config_path = save_directory / "config.json"
|
||||
with open(config_path, "w") as config_file:
|
||||
json.dump(self.h, config_file, indent=4)
|
||||
|
||||
@classmethod
|
||||
def _from_pretrained(
|
||||
cls,
|
||||
*,
|
||||
model_id: str,
|
||||
revision: str,
|
||||
cache_dir: str,
|
||||
force_download: bool,
|
||||
proxies: Optional[Dict],
|
||||
resume_download: bool,
|
||||
local_files_only: bool,
|
||||
token: Union[str, bool, None],
|
||||
map_location: str = "cpu", # Additional argument
|
||||
strict: bool = False, # Additional argument
|
||||
**model_kwargs,
|
||||
):
|
||||
"""Load Pytorch pretrained weights and return the loaded model."""
|
||||
|
||||
# Download and load hyperparameters (h) used by BigVGAN
|
||||
if os.path.isdir(model_id):
|
||||
# print("Loading config.json from local directory")
|
||||
config_file = os.path.join(model_id, "config.json")
|
||||
else:
|
||||
config_file = hf_hub_download(
|
||||
repo_id=model_id,
|
||||
filename="config.json",
|
||||
revision=revision,
|
||||
cache_dir=cache_dir,
|
||||
force_download=force_download,
|
||||
proxies=proxies,
|
||||
resume_download=resume_download,
|
||||
token=token,
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
h = load_hparams_from_json(config_file)
|
||||
|
||||
# instantiate BigVGAN using h
|
||||
model = cls(h)
|
||||
|
||||
# Download and load pretrained generator weight
|
||||
if os.path.isdir(model_id):
|
||||
# print("Loading weights from local directory")
|
||||
model_file = os.path.join(model_id, "bigvgan_generator.pt")
|
||||
else:
|
||||
# print(f"Loading weights from {model_id}")
|
||||
model_file = hf_hub_download(
|
||||
repo_id=model_id,
|
||||
filename="bigvgan_generator.pt",
|
||||
revision=revision,
|
||||
cache_dir=cache_dir,
|
||||
force_download=force_download,
|
||||
proxies=proxies,
|
||||
resume_download=resume_download,
|
||||
token=token,
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
|
||||
checkpoint_dict = torch.load(model_file, map_location=map_location)
|
||||
|
||||
def from_pretrained(cls, model_id, *, use_cuda_kernel=False, map_location="cpu"):
|
||||
"""Load the local config.json and bigvgan_generator.pt inference bundle."""
|
||||
if use_cuda_kernel:
|
||||
raise ValueError("This runtime uses the PyTorch BigVGAN activation kernels")
|
||||
directory = Path(model_id)
|
||||
model = cls(load_hparams_from_json(directory / "config.json"))
|
||||
checkpoint = torch.load(directory / "bigvgan_generator.pt", map_location=map_location, weights_only=False)
|
||||
try:
|
||||
model.load_state_dict(checkpoint_dict["generator"])
|
||||
model.load_state_dict(checkpoint["generator"])
|
||||
except RuntimeError:
|
||||
print(
|
||||
"[INFO] the pretrained checkpoint does not contain weight norm. Loading the checkpoint after removing weight norm!"
|
||||
)
|
||||
model.remove_weight_norm()
|
||||
model.load_state_dict(checkpoint_dict["generator"])
|
||||
|
||||
model.load_state_dict(checkpoint["generator"])
|
||||
return model
|
||||
|
||||
@ -1,8 +0,0 @@
|
||||
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
|
||||
# LICENSE is in the incl_licenses directory.
|
||||
|
||||
|
||||
class AttrDict(dict):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(AttrDict, self).__init__(*args, **kwargs)
|
||||
self.__dict__ = self
|
||||
@ -1,12 +0,0 @@
|
||||
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
|
||||
# LICENSE is in the incl_licenses directory.
|
||||
|
||||
|
||||
def init_weights(m, mean=0.0, std=0.01):
|
||||
classname = m.__class__.__name__
|
||||
if classname.find("Conv") != -1:
|
||||
m.weight.data.normal_(mean, std)
|
||||
|
||||
|
||||
def get_padding(kernel_size, dilation=1):
|
||||
return int((kernel_size * dilation - dilation) / 2)
|
||||
@ -15,9 +15,8 @@ sys.path.append(now_dir)
|
||||
import os
|
||||
from typing import List, Tuple, Union
|
||||
|
||||
import ffmpeg
|
||||
from tools.acceleration import create_acceleration
|
||||
from tools.portable_runtime import FFMPEG_EXE, prepare_transformers_flash_attention
|
||||
from tools.portable_runtime import prepare_transformers_flash_attention
|
||||
|
||||
prepare_transformers_flash_attention()
|
||||
|
||||
@ -26,18 +25,18 @@ import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import yaml
|
||||
from AR.models.t2s_lightning_module import Text2SemanticLightningModule
|
||||
from AR.models.t2s_inference import Text2SemanticInference
|
||||
from BigVGAN.bigvgan import BigVGAN
|
||||
from feature_extractor.cnhubert import CNHubert
|
||||
from module.mel_processing import mel_spectrogram_torch, spectrogram_torch
|
||||
from module.models import SynthesizerTrn, SynthesizerTrnV3, Generator
|
||||
from module.models_v5 import synthesize_v5_mel, V5_VERSIONS
|
||||
from peft import LoraConfig, get_peft_model
|
||||
from process_ckpt import get_sovits_version_from_path_fast, load_sovits_new
|
||||
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
||||
from inference_loader import get_sovits_version_from_path_fast, load_sovits_new
|
||||
from transformers import AutoModel, AutoTokenizer
|
||||
|
||||
from tools.audio_sr import AP_BWE
|
||||
from tools.i18n.i18n import I18nAuto, scan_language_list
|
||||
from tools.i18n.i18n import I18nAuto
|
||||
from TTS_infer_pack.text_segmentation_method import splits
|
||||
from TTS_infer_pack.TextPreprocessor import TextPreprocessor
|
||||
from sv import SV
|
||||
@ -126,7 +125,6 @@ def load_audio_gpu(path, target_sr, device, mono=True, dtype=torch.float32, matc
|
||||
|
||||
|
||||
language = os.environ.get("language", "Auto")
|
||||
language = sys.argv[-1] if sys.argv[-1] in scan_language_list() else language
|
||||
i18n = I18nAuto(language=language)
|
||||
|
||||
|
||||
@ -171,27 +169,6 @@ mel_fn_v4 = lambda x: mel_spectrogram_torch(
|
||||
)
|
||||
|
||||
|
||||
def speed_change(input_audio: np.ndarray, speed: float, sr: int):
|
||||
# 将 NumPy 数组转换为原始 PCM 流
|
||||
raw_audio = input_audio.astype(np.int16).tobytes()
|
||||
|
||||
# 设置 ffmpeg 输入流
|
||||
input_stream = ffmpeg.input("pipe:", format="s16le", acodec="pcm_s16le", ar=str(sr), ac=1)
|
||||
|
||||
# 变速处理
|
||||
output_stream = input_stream.filter("atempo", speed)
|
||||
|
||||
# 输出流到管道
|
||||
out, _ = output_stream.output("pipe:", format="s16le", acodec="pcm_s16le").run(
|
||||
cmd=str(FFMPEG_EXE), input=raw_audio, capture_stdout=True, capture_stderr=True
|
||||
)
|
||||
|
||||
# 将管道输出解码为 NumPy 数组
|
||||
processed_audio = np.frombuffer(out, np.int16)
|
||||
|
||||
return processed_audio
|
||||
|
||||
|
||||
class DictToAttrRecursive(dict):
|
||||
def __init__(self, input_dict):
|
||||
super().__init__(input_dict)
|
||||
@ -384,13 +361,9 @@ class TTS_Config:
|
||||
def __init__(self, configs: Union[dict, str] = None):
|
||||
# 设置默认配置文件路径
|
||||
configs_base_path: str = "GPT_SoVITS/configs/"
|
||||
os.makedirs(configs_base_path, exist_ok=True)
|
||||
self.configs_path: str = os.path.join(configs_base_path, "tts_infer.yaml")
|
||||
|
||||
if configs in ["", None]:
|
||||
if not os.path.exists(self.configs_path):
|
||||
self.save_configs()
|
||||
print(f"Create default config file at {self.configs_path}")
|
||||
configs: dict = deepcopy(self.default_configs)
|
||||
|
||||
if isinstance(configs, str):
|
||||
@ -441,34 +414,22 @@ class TTS_Config:
|
||||
self.max_sec = None
|
||||
self.hz: int = 50
|
||||
self.semantic_frame_rate: str = "25hz"
|
||||
self.segment_size: int = 20480
|
||||
self.filter_length: int = 2048
|
||||
self.sampling_rate: int = 32000
|
||||
self.hop_length: int = 640
|
||||
self.win_length: int = 2048
|
||||
self.n_speakers: int = 300
|
||||
|
||||
def _load_configs(self, configs_path: str) -> dict:
|
||||
if os.path.exists(configs_path):
|
||||
...
|
||||
else:
|
||||
print(i18n("路径不存在,使用默认配置"))
|
||||
self.save_configs(configs_path)
|
||||
return deepcopy(self.default_configs)
|
||||
with open(configs_path, "r", encoding="utf-8") as f:
|
||||
configs = yaml.load(f, Loader=yaml.FullLoader)
|
||||
|
||||
return configs
|
||||
|
||||
def save_configs(self, configs_path: str = None) -> None:
|
||||
configs = deepcopy(self.default_configs)
|
||||
if self.configs is not None:
|
||||
configs["custom"] = self.update_configs()
|
||||
|
||||
if configs_path is None:
|
||||
configs_path = self.configs_path
|
||||
with open(configs_path, "w") as f:
|
||||
yaml.dump(configs, f)
|
||||
|
||||
def update_configs(self):
|
||||
self.config = {
|
||||
"device": str(self.device),
|
||||
@ -510,12 +471,12 @@ class TTS:
|
||||
else:
|
||||
self.configs: TTS_Config = TTS_Config(configs)
|
||||
|
||||
self.t2s_model: Text2SemanticLightningModule = None
|
||||
self.t2s_model: Text2SemanticInference = None
|
||||
self.t2s_accel = None
|
||||
self.streaming_accel = None
|
||||
self.vits_model: Union[SynthesizerTrn, SynthesizerTrnV3] = None
|
||||
self.bert_tokenizer: AutoTokenizer = None
|
||||
self.bert_model: AutoModelForMaskedLM = None
|
||||
self.bert_model: AutoModel = None
|
||||
self.cnhuhbert_model: CNHubert = None
|
||||
self.vocoder = None
|
||||
self.sr_model: AP_BWE = None
|
||||
@ -558,7 +519,6 @@ class TTS:
|
||||
self.init_vits_weights(self.configs.vits_weights_path)
|
||||
self.init_bert_weights(self.configs.bert_base_path)
|
||||
self.init_cnhuhbert_weights(self.configs.cnhuhbert_base_path)
|
||||
# self.enable_half_precision(self.configs.is_half)
|
||||
|
||||
def init_cnhuhbert_weights(self, base_path: str):
|
||||
print(f"Loading CNHuBERT weights from {base_path}")
|
||||
@ -571,7 +531,7 @@ class TTS:
|
||||
def init_bert_weights(self, base_path: str):
|
||||
print(f"Loading BERT weights from {base_path}")
|
||||
self.bert_tokenizer = AutoTokenizer.from_pretrained(base_path)
|
||||
self.bert_model = AutoModelForMaskedLM.from_pretrained(base_path)
|
||||
self.bert_model = AutoModel.from_pretrained(base_path, add_pooling_layer=False)
|
||||
self.bert_model = self.bert_model.eval()
|
||||
self.bert_model = self.bert_model.to(self.configs.device)
|
||||
if self.configs.is_half and str(self.configs.device) != "cpu":
|
||||
@ -609,11 +569,9 @@ class TTS:
|
||||
hps["model"]["version"] = model_version
|
||||
|
||||
self.configs.filter_length = hps["data"]["filter_length"]
|
||||
self.configs.segment_size = hps["train"]["segment_size"]
|
||||
self.configs.sampling_rate = hps["data"]["sampling_rate"]
|
||||
self.configs.hop_length = hps["data"]["hop_length"]
|
||||
self.configs.win_length = hps["data"]["win_length"]
|
||||
self.configs.n_speakers = hps["data"]["n_speakers"]
|
||||
self.configs.semantic_frame_rate = hps["model"]["semantic_frame_rate"]
|
||||
kwargs = hps["model"]
|
||||
# print(f"self.configs.sampling_rate:{self.configs.sampling_rate}")
|
||||
@ -625,8 +583,6 @@ class TTS:
|
||||
if model_version not in v3v4set:
|
||||
vits_model = SynthesizerTrn(
|
||||
self.configs.filter_length // 2 + 1,
|
||||
self.configs.segment_size // self.configs.hop_length,
|
||||
n_speakers=self.configs.n_speakers,
|
||||
**kwargs,
|
||||
)
|
||||
self.configs.use_vocoder = False
|
||||
@ -634,14 +590,10 @@ class TTS:
|
||||
kwargs["version"] = model_version
|
||||
vits_model = SynthesizerTrnV3(
|
||||
self.configs.filter_length // 2 + 1,
|
||||
self.configs.segment_size // self.configs.hop_length,
|
||||
n_speakers=self.configs.n_speakers,
|
||||
**kwargs,
|
||||
)
|
||||
self.configs.use_vocoder = True
|
||||
self.init_vocoder(model_version)
|
||||
if "pretrained" not in weights_path and hasattr(vits_model, "enc_q"):
|
||||
del vits_model.enc_q
|
||||
|
||||
self.is_v2pro = model_version in {"v2Pro", "v2ProPlus"}
|
||||
|
||||
@ -674,10 +626,6 @@ class TTS:
|
||||
if self.configs.is_half and str(self.configs.device) != "cpu":
|
||||
self.vits_model = self.vits_model.half()
|
||||
|
||||
self.configs.save_configs()
|
||||
|
||||
|
||||
|
||||
def init_t2s_weights(self, weights_path: str):
|
||||
if self.streaming_accel is not None:
|
||||
self.streaming_accel.close()
|
||||
@ -687,12 +635,11 @@ class TTS:
|
||||
self.t2s_accel = None
|
||||
print(f"Loading Text2Semantic weights from {weights_path}")
|
||||
self.configs.t2s_weights_path = weights_path
|
||||
self.configs.save_configs()
|
||||
self.configs.hz = 50
|
||||
dict_s1 = torch.load(weights_path, map_location=self.configs.device, weights_only=False)
|
||||
config = dict_s1["config"]
|
||||
self.configs.max_sec = config["data"]["max_sec"]
|
||||
t2s_model = Text2SemanticLightningModule(config, "****", is_train=False)
|
||||
t2s_model = Text2SemanticInference(config)
|
||||
t2s_model.load_state_dict(dict_s1["weight"])
|
||||
t2s_model = t2s_model.to(self.configs.device)
|
||||
t2s_model = t2s_model.eval()
|
||||
@ -784,78 +731,6 @@ class TTS:
|
||||
return
|
||||
self.sv_model = SV(self.configs.device, self.configs.is_half)
|
||||
|
||||
def enable_half_precision(self, enable: bool = True, save: bool = True):
|
||||
"""
|
||||
To enable half precision for the TTS model.
|
||||
Args:
|
||||
enable: bool, whether to enable half precision.
|
||||
|
||||
"""
|
||||
if str(self.configs.device) == "cpu" and enable:
|
||||
print("Half precision is not supported on CPU.")
|
||||
return
|
||||
|
||||
if self.streaming_accel is not None:
|
||||
self.streaming_accel.close()
|
||||
self.streaming_accel = None
|
||||
if self.t2s_accel is not None:
|
||||
self.t2s_accel.close()
|
||||
self.t2s_accel = None
|
||||
self.configs.is_half = enable
|
||||
self.precision = torch.float16 if enable else torch.float32
|
||||
if save:
|
||||
self.configs.save_configs()
|
||||
if enable:
|
||||
if self.t2s_model is not None:
|
||||
self.t2s_model = self.t2s_model.half()
|
||||
if self.vits_model is not None:
|
||||
self.vits_model = self.vits_model.half()
|
||||
if self.bert_model is not None:
|
||||
self.bert_model = self.bert_model.half()
|
||||
if self.cnhuhbert_model is not None:
|
||||
self.cnhuhbert_model = self.cnhuhbert_model.half()
|
||||
if self.vocoder is not None:
|
||||
self.vocoder = self.vocoder.half()
|
||||
else:
|
||||
if self.t2s_model is not None:
|
||||
self.t2s_model = self.t2s_model.float()
|
||||
if self.vits_model is not None:
|
||||
self.vits_model = self.vits_model.float()
|
||||
if self.bert_model is not None:
|
||||
self.bert_model = self.bert_model.float()
|
||||
if self.cnhuhbert_model is not None:
|
||||
self.cnhuhbert_model = self.cnhuhbert_model.float()
|
||||
if self.vocoder is not None:
|
||||
self.vocoder = self.vocoder.float()
|
||||
|
||||
def set_device(self, device: torch.device, save: bool = True):
|
||||
"""
|
||||
To set the device for all models.
|
||||
Args:
|
||||
device: torch.device, the device to use for all models.
|
||||
"""
|
||||
if self.streaming_accel is not None:
|
||||
self.streaming_accel.close()
|
||||
self.streaming_accel = None
|
||||
if self.t2s_accel is not None:
|
||||
self.t2s_accel.close()
|
||||
self.t2s_accel = None
|
||||
self.configs.device = device
|
||||
if save:
|
||||
self.configs.save_configs()
|
||||
if self.t2s_model is not None:
|
||||
self.t2s_model = self.t2s_model.to(device)
|
||||
if self.vits_model is not None:
|
||||
self.vits_model = self.vits_model.to(device)
|
||||
if self.bert_model is not None:
|
||||
self.bert_model = self.bert_model.to(device)
|
||||
if self.cnhuhbert_model is not None:
|
||||
self.cnhuhbert_model = self.cnhuhbert_model.to(device)
|
||||
if self.vocoder is not None:
|
||||
self.vocoder = self.vocoder.to(device)
|
||||
if self.sr_model is not None:
|
||||
self.sr_model = self.sr_model.to(device)
|
||||
|
||||
def set_ref_audio(self, ref_audio_path: str):
|
||||
"""
|
||||
To set the reference audio for the TTS model,
|
||||
@ -1822,12 +1697,6 @@ class TTS:
|
||||
audio = (audio * 32768).astype(np.int16)
|
||||
|
||||
|
||||
# try:
|
||||
# if speed_factor != 1.0:
|
||||
# audio = speed_change(audio, speed=speed_factor, sr=int(sr))
|
||||
# except Exception as e:
|
||||
# print(f"Failed to change speed of audio: \n{e}")
|
||||
|
||||
return sr, audio
|
||||
|
||||
def using_vocoder_synthesis(
|
||||
|
||||
@ -14,13 +14,12 @@ from text import chinese
|
||||
from typing import Dict, List, Tuple
|
||||
from text.cleaner import clean_text
|
||||
from text import cleaned_text_to_sequence
|
||||
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
||||
from transformers import AutoModel, AutoTokenizer
|
||||
from TTS_infer_pack.text_segmentation_method import split_big_text, splits, get_method as get_seg_method
|
||||
|
||||
from tools.i18n.i18n import I18nAuto, scan_language_list
|
||||
from tools.i18n.i18n import I18nAuto
|
||||
|
||||
language = os.environ.get("language", "Auto")
|
||||
language = sys.argv[-1] if sys.argv[-1] in scan_language_list() else language
|
||||
i18n = I18nAuto(language=language)
|
||||
punctuation = set(["!", "?", "…", ",", ".", "-"])
|
||||
|
||||
@ -50,7 +49,7 @@ def merge_short_text_in_array(texts: str, threshold: int) -> list:
|
||||
|
||||
|
||||
class TextPreprocessor:
|
||||
def __init__(self, bert_model: AutoModelForMaskedLM, tokenizer: AutoTokenizer, device: torch.device):
|
||||
def __init__(self, bert_model: AutoModel, tokenizer: AutoTokenizer, device: torch.device):
|
||||
self.bert_model = bert_model
|
||||
self.tokenizer = tokenizer
|
||||
self.device = device
|
||||
@ -236,4 +235,4 @@ class TextPreprocessor:
|
||||
punctuations = "".join(re.escape(p) for p in punctuation)
|
||||
pattern = f"([{punctuations}])([{punctuations}])+"
|
||||
result = re.sub(pattern, r"\1", text)
|
||||
return result
|
||||
return result
|
||||
|
||||
@ -182,8 +182,3 @@ def cut5(inp):
|
||||
|
||||
opt = [item for item in mergeitems if not set(item).issubset(punds)]
|
||||
return "\n".join(opt)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
method = get_method("cut5")
|
||||
print(method("你好,我是小明。你好,我是小红。你好,我是小刚。你好,我是小张。"))
|
||||
|
||||
@ -1,31 +0,0 @@
|
||||
train:
|
||||
seed: 1234
|
||||
epochs: 300
|
||||
batch_size: 8
|
||||
gradient_accumulation: 4
|
||||
save_every_n_epoch: 1
|
||||
precision: 16
|
||||
gradient_clip: 1.0
|
||||
optimizer:
|
||||
lr: 0.01
|
||||
lr_init: 0.00001
|
||||
lr_end: 0.0001
|
||||
warmup_steps: 2000
|
||||
decay_steps: 40000
|
||||
data:
|
||||
max_eval_sample: 8
|
||||
max_sec: 54
|
||||
num_workers: 1
|
||||
pad_val: 1024 # same with EOS in model
|
||||
model:
|
||||
vocab_size: 1025
|
||||
phoneme_vocab_size: 512
|
||||
embedding_dim: 512
|
||||
hidden_dim: 512
|
||||
head: 16
|
||||
linear_units: 2048
|
||||
n_layer: 12
|
||||
dropout: 0
|
||||
EOS: 1024
|
||||
inference:
|
||||
top_k: 5
|
||||
@ -1,31 +0,0 @@
|
||||
train:
|
||||
seed: 1234
|
||||
epochs: 300
|
||||
batch_size: 8
|
||||
gradient_accumulation: 4
|
||||
save_every_n_epoch: 1
|
||||
precision: 16-mixed
|
||||
gradient_clip: 1.0
|
||||
optimizer:
|
||||
lr: 0.01
|
||||
lr_init: 0.00001
|
||||
lr_end: 0.0001
|
||||
warmup_steps: 2000
|
||||
decay_steps: 40000
|
||||
data:
|
||||
max_eval_sample: 8
|
||||
max_sec: 54
|
||||
num_workers: 1
|
||||
pad_val: 1024 # same with EOS in model
|
||||
model:
|
||||
vocab_size: 1025
|
||||
phoneme_vocab_size: 512
|
||||
embedding_dim: 1024
|
||||
hidden_dim: 1024
|
||||
head: 16
|
||||
linear_units: 2048
|
||||
n_layer: 16
|
||||
dropout: 0
|
||||
EOS: 1024
|
||||
inference:
|
||||
top_k: 5
|
||||
@ -1,31 +0,0 @@
|
||||
train:
|
||||
seed: 1234
|
||||
epochs: 300
|
||||
batch_size: 12
|
||||
gradient_accumulation: 4
|
||||
save_every_n_epoch: 1
|
||||
precision: 16-mixed
|
||||
gradient_clip: 1.0
|
||||
optimizer:
|
||||
lr: 0.01
|
||||
lr_init: 0.00001
|
||||
lr_end: 0.0001
|
||||
warmup_steps: 2000
|
||||
decay_steps: 40000
|
||||
data:
|
||||
max_eval_sample: 8
|
||||
max_sec: 54
|
||||
num_workers: 1
|
||||
pad_val: 1024 # same with EOS in model
|
||||
model:
|
||||
vocab_size: 1025
|
||||
phoneme_vocab_size: 512
|
||||
embedding_dim: 1024
|
||||
hidden_dim: 1024
|
||||
head: 16
|
||||
linear_units: 2048
|
||||
n_layer: 6
|
||||
dropout: 0
|
||||
EOS: 1024
|
||||
inference:
|
||||
top_k: 5
|
||||
@ -1,31 +0,0 @@
|
||||
train:
|
||||
seed: 1234
|
||||
epochs: 20
|
||||
batch_size: 8
|
||||
save_every_n_epoch: 1
|
||||
precision: 16-mixed
|
||||
gradient_clip: 1.0
|
||||
optimizer:
|
||||
lr: 0.01
|
||||
lr_init: 0.00001
|
||||
lr_end: 0.0001
|
||||
warmup_steps: 2000
|
||||
decay_steps: 40000
|
||||
data:
|
||||
max_eval_sample: 8
|
||||
max_sec: 54
|
||||
num_workers: 4
|
||||
pad_val: 1024 # same with EOS in model
|
||||
model:
|
||||
vocab_size: 1025
|
||||
phoneme_vocab_size: 732
|
||||
embedding_dim: 512
|
||||
hidden_dim: 512
|
||||
head: 16
|
||||
linear_units: 2048
|
||||
n_layer: 24
|
||||
dropout: 0
|
||||
EOS: 1024
|
||||
random_bert: 0
|
||||
inference:
|
||||
top_k: 15
|
||||
@ -1,31 +0,0 @@
|
||||
train:
|
||||
seed: 1234
|
||||
epochs: 20
|
||||
batch_size: 8
|
||||
save_every_n_epoch: 1
|
||||
precision: 16-mixed
|
||||
gradient_clip: 1.0
|
||||
optimizer:
|
||||
lr: 0.01
|
||||
lr_init: 0.00001
|
||||
lr_end: 0.0001
|
||||
warmup_steps: 2000
|
||||
decay_steps: 40000
|
||||
data:
|
||||
max_eval_sample: 8
|
||||
max_sec: 54
|
||||
num_workers: 4
|
||||
pad_val: 1024 # same with EOS in model
|
||||
model:
|
||||
vocab_size: 1025
|
||||
phoneme_vocab_size: 512
|
||||
embedding_dim: 512
|
||||
hidden_dim: 512
|
||||
head: 16
|
||||
linear_units: 2048
|
||||
n_layer: 24
|
||||
dropout: 0
|
||||
EOS: 1024
|
||||
random_bert: 0
|
||||
inference:
|
||||
top_k: 5
|
||||
@ -1,77 +0,0 @@
|
||||
train:
|
||||
seed: 1234
|
||||
epochs: 100
|
||||
batch_size: 6
|
||||
gradient_accumulation: 4
|
||||
save_every_n_epoch: 1
|
||||
precision: 32
|
||||
gradient_clip: 1.0
|
||||
optimizer:
|
||||
lr: 0.01
|
||||
lr_init: 0.00001
|
||||
lr_end: 0.0001
|
||||
warmup_steps: 2000
|
||||
decay_steps: 40000
|
||||
data:
|
||||
max_eval_sample: 8
|
||||
max_sec: 40
|
||||
num_workers: 1
|
||||
pad_val: 1024 # same with EOS in model
|
||||
model:
|
||||
saving_path: "ckpt/"
|
||||
resume_checkpoint: null
|
||||
vocoder_config_path: "quantizer/new_ckpt/config.json"
|
||||
vocoder_ckpt_path: "quantizer/new_ckpt/g_00600000"
|
||||
datadir: "/home/liweiche/GigaSpeech/wavs"
|
||||
metapath: "/home/liweiche/GigaSpeech/train2.json"
|
||||
val_metapath: "/home/liweiche/GigaSpeech/dev2.json"
|
||||
sampledir: "logs/"
|
||||
pretrained_path: null
|
||||
lr: 0.0001
|
||||
batch_size: 200.0
|
||||
train_bucket_size: 8192
|
||||
training_step: 800000
|
||||
optim_flat_percent: 0.0
|
||||
warmup_step: 50
|
||||
adam_beta1: 0.9
|
||||
adam_beta2: 0.98
|
||||
ffd_size: 3072
|
||||
hidden_size: 768
|
||||
enc_nlayers: 6
|
||||
dec_nlayers: 6
|
||||
nheads: 12
|
||||
ar_layer: 4
|
||||
ar_ffd_size: 1024
|
||||
ar_hidden_size: 256
|
||||
ar_nheads: 4
|
||||
aligner_softmax_temp: 1.0
|
||||
layer_norm_eps: 0.00001
|
||||
speaker_embed_dropout: 0.05
|
||||
label_smoothing: 0.0
|
||||
val_check_interval: 5000
|
||||
check_val_every_n_epoch: 1
|
||||
precision: "fp16"
|
||||
nworkers: 16
|
||||
distributed: true
|
||||
accelerator: "ddp"
|
||||
version: null
|
||||
accumulate_grad_batches: 1
|
||||
use_repetition_token: true
|
||||
use_repetition_gating: false
|
||||
repetition_penalty: 1.0
|
||||
sampling_temperature: 1.0
|
||||
top_k: -1
|
||||
min_top_k: 3
|
||||
top_p: 0.8
|
||||
sample_num: 4
|
||||
length_penalty_max_length: 15000
|
||||
length_penalty_max_prob: 0.95
|
||||
max_input_length: 2048
|
||||
max_output_length: 2000
|
||||
sample_rate: 16000
|
||||
n_codes: 1024
|
||||
n_cluster_groups: 1
|
||||
phone_context_window: 4
|
||||
phoneset_size: 1000
|
||||
inference:
|
||||
top_k: 5
|
||||
@ -1,91 +0,0 @@
|
||||
{
|
||||
"train": {
|
||||
"log_interval": 100,
|
||||
"eval_interval": 500,
|
||||
"seed": 1234,
|
||||
"epochs": 100,
|
||||
"learning_rate": 0.0001,
|
||||
"betas": [
|
||||
0.8,
|
||||
0.99
|
||||
],
|
||||
"eps": 1e-09,
|
||||
"batch_size": 32,
|
||||
"fp16_run": true,
|
||||
"lr_decay": 0.999875,
|
||||
"segment_size": 20480,
|
||||
"init_lr_ratio": 1,
|
||||
"warmup_epochs": 0,
|
||||
"c_mel": 45,
|
||||
"c_kl": 1.0,
|
||||
"text_low_lr_rate": 0.4,
|
||||
"grad_ckpt": false
|
||||
},
|
||||
"data": {
|
||||
"max_wav_value": 32768.0,
|
||||
"sampling_rate": 32000,
|
||||
"filter_length": 2048,
|
||||
"hop_length": 640,
|
||||
"win_length": 2048,
|
||||
"n_mel_channels": 128,
|
||||
"mel_fmin": 0.0,
|
||||
"mel_fmax": null,
|
||||
"add_blank": true,
|
||||
"n_speakers": 300,
|
||||
"cleaned_text": true
|
||||
},
|
||||
"model": {
|
||||
"inter_channels": 192,
|
||||
"hidden_channels": 192,
|
||||
"filter_channels": 768,
|
||||
"n_heads": 2,
|
||||
"n_layers": 6,
|
||||
"kernel_size": 3,
|
||||
"p_dropout": 0.1,
|
||||
"resblock": "1",
|
||||
"resblock_kernel_sizes": [
|
||||
3,
|
||||
7,
|
||||
11
|
||||
],
|
||||
"resblock_dilation_sizes": [
|
||||
[
|
||||
1,
|
||||
3,
|
||||
5
|
||||
],
|
||||
[
|
||||
1,
|
||||
3,
|
||||
5
|
||||
],
|
||||
[
|
||||
1,
|
||||
3,
|
||||
5
|
||||
]
|
||||
],
|
||||
"upsample_rates": [
|
||||
10,
|
||||
8,
|
||||
2,
|
||||
2,
|
||||
2
|
||||
],
|
||||
"upsample_initial_channel": 512,
|
||||
"upsample_kernel_sizes": [
|
||||
16,
|
||||
16,
|
||||
8,
|
||||
2,
|
||||
2
|
||||
],
|
||||
"n_layers_q": 3,
|
||||
"use_spectral_norm": false,
|
||||
"gin_channels": 512,
|
||||
"semantic_frame_rate": "25hz",
|
||||
"freeze_quantizer": true
|
||||
},
|
||||
"s2_ckpt_dir": "logs/s2/big2k1",
|
||||
"content_module": "cnhubert"
|
||||
}
|
||||
@ -1,91 +0,0 @@
|
||||
{
|
||||
"train": {
|
||||
"log_interval": 100,
|
||||
"eval_interval": 500,
|
||||
"seed": 1234,
|
||||
"epochs": 100,
|
||||
"learning_rate": 0.0001,
|
||||
"betas": [
|
||||
0.8,
|
||||
0.99
|
||||
],
|
||||
"eps": 1e-09,
|
||||
"batch_size": 32,
|
||||
"fp16_run": true,
|
||||
"lr_decay": 0.999875,
|
||||
"segment_size": 20480,
|
||||
"init_lr_ratio": 1,
|
||||
"warmup_epochs": 0,
|
||||
"c_mel": 45,
|
||||
"c_kl": 1.0,
|
||||
"text_low_lr_rate": 0.4,
|
||||
"grad_ckpt": false
|
||||
},
|
||||
"data": {
|
||||
"max_wav_value": 32768.0,
|
||||
"sampling_rate": 32000,
|
||||
"filter_length": 2048,
|
||||
"hop_length": 640,
|
||||
"win_length": 2048,
|
||||
"n_mel_channels": 128,
|
||||
"mel_fmin": 0.0,
|
||||
"mel_fmax": null,
|
||||
"add_blank": true,
|
||||
"n_speakers": 300,
|
||||
"cleaned_text": true
|
||||
},
|
||||
"model": {
|
||||
"inter_channels": 192,
|
||||
"hidden_channels": 192,
|
||||
"filter_channels": 768,
|
||||
"n_heads": 2,
|
||||
"n_layers": 6,
|
||||
"kernel_size": 3,
|
||||
"p_dropout": 0.0,
|
||||
"resblock": "1",
|
||||
"resblock_kernel_sizes": [
|
||||
3,
|
||||
7,
|
||||
11
|
||||
],
|
||||
"resblock_dilation_sizes": [
|
||||
[
|
||||
1,
|
||||
3,
|
||||
5
|
||||
],
|
||||
[
|
||||
1,
|
||||
3,
|
||||
5
|
||||
],
|
||||
[
|
||||
1,
|
||||
3,
|
||||
5
|
||||
]
|
||||
],
|
||||
"upsample_rates": [
|
||||
10,
|
||||
8,
|
||||
2,
|
||||
2,
|
||||
2
|
||||
],
|
||||
"upsample_initial_channel": 512,
|
||||
"upsample_kernel_sizes": [
|
||||
16,
|
||||
16,
|
||||
8,
|
||||
2,
|
||||
2
|
||||
],
|
||||
"n_layers_q": 3,
|
||||
"use_spectral_norm": false,
|
||||
"gin_channels": 1024,
|
||||
"semantic_frame_rate": "25hz",
|
||||
"freeze_quantizer": true
|
||||
},
|
||||
"s2_ckpt_dir": "logs/s2/big2k1",
|
||||
"content_module": "cnhubert"
|
||||
}
|
||||
@ -1,91 +0,0 @@
|
||||
{
|
||||
"train": {
|
||||
"log_interval": 100,
|
||||
"eval_interval": 500,
|
||||
"seed": 1234,
|
||||
"epochs": 100,
|
||||
"learning_rate": 0.0001,
|
||||
"betas": [
|
||||
0.8,
|
||||
0.99
|
||||
],
|
||||
"eps": 1e-09,
|
||||
"batch_size": 32,
|
||||
"fp16_run": true,
|
||||
"lr_decay": 0.999875,
|
||||
"segment_size": 20480,
|
||||
"init_lr_ratio": 1,
|
||||
"warmup_epochs": 0,
|
||||
"c_mel": 45,
|
||||
"c_kl": 1.0,
|
||||
"text_low_lr_rate": 0.4,
|
||||
"grad_ckpt": false
|
||||
},
|
||||
"data": {
|
||||
"max_wav_value": 32768.0,
|
||||
"sampling_rate": 32000,
|
||||
"filter_length": 2048,
|
||||
"hop_length": 640,
|
||||
"win_length": 2048,
|
||||
"n_mel_channels": 128,
|
||||
"mel_fmin": 0.0,
|
||||
"mel_fmax": null,
|
||||
"add_blank": true,
|
||||
"n_speakers": 300,
|
||||
"cleaned_text": true
|
||||
},
|
||||
"model": {
|
||||
"inter_channels": 192,
|
||||
"hidden_channels": 192,
|
||||
"filter_channels": 768,
|
||||
"n_heads": 2,
|
||||
"n_layers": 6,
|
||||
"kernel_size": 3,
|
||||
"p_dropout": 0.0,
|
||||
"resblock": "1",
|
||||
"resblock_kernel_sizes": [
|
||||
3,
|
||||
7,
|
||||
11
|
||||
],
|
||||
"resblock_dilation_sizes": [
|
||||
[
|
||||
1,
|
||||
3,
|
||||
5
|
||||
],
|
||||
[
|
||||
1,
|
||||
3,
|
||||
5
|
||||
],
|
||||
[
|
||||
1,
|
||||
3,
|
||||
5
|
||||
]
|
||||
],
|
||||
"upsample_rates": [
|
||||
10,
|
||||
8,
|
||||
2,
|
||||
2,
|
||||
2
|
||||
],
|
||||
"upsample_initial_channel": 768,
|
||||
"upsample_kernel_sizes": [
|
||||
20,
|
||||
16,
|
||||
8,
|
||||
2,
|
||||
2
|
||||
],
|
||||
"n_layers_q": 3,
|
||||
"use_spectral_norm": false,
|
||||
"gin_channels": 1024,
|
||||
"semantic_frame_rate": "25hz",
|
||||
"freeze_quantizer": true
|
||||
},
|
||||
"s2_ckpt_dir": "logs/s2/big2k1",
|
||||
"content_module": "cnhubert"
|
||||
}
|
||||
@ -1,32 +0,0 @@
|
||||
gpu:
|
||||
n_card: 1
|
||||
n_process_per_card: 2
|
||||
io:
|
||||
text_path: D:\RVC1006\GPT-SoVITS\GPT_SoVITS
|
||||
save_every_n_epoch: 1
|
||||
precision: 16-mixed
|
||||
gradient_clip: 1.0
|
||||
optimizer:
|
||||
lr: 0.01
|
||||
lr_init: 0.00001
|
||||
lr_end: 0.0001
|
||||
warmup_steps: 2000
|
||||
decay_steps: 40000
|
||||
data:
|
||||
max_eval_sample: 8
|
||||
max_sec: 54
|
||||
num_workers: 1
|
||||
pad_val: 1024 # same with EOS in model
|
||||
model:
|
||||
vocab_size: 1025
|
||||
phoneme_vocab_size: 512
|
||||
embedding_dim: 512
|
||||
hidden_dim: 512
|
||||
head: 16
|
||||
linear_units: 2048
|
||||
n_layer: 24
|
||||
dropout: 0
|
||||
EOS: 1024
|
||||
random_bert: 0
|
||||
inference:
|
||||
top_k: 5
|
||||
@ -54,3 +54,19 @@ v4:
|
||||
t2s_weights_path: GPT_SoVITS/pretrained_models/s1v3.ckpt
|
||||
version: v4
|
||||
vits_weights_path: GPT_SoVITS/pretrained_models/gsv-v4-pretrained/s2Gv4.pth
|
||||
v5dev:
|
||||
bert_base_path: GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large
|
||||
cnhuhbert_base_path: GPT_SoVITS/pretrained_models/chinese-hubert-base
|
||||
device: cpu
|
||||
is_half: false
|
||||
t2s_weights_path: GPT_SoVITS/pretrained_models/s1v3.ckpt
|
||||
version: v5dev
|
||||
vits_weights_path: GPT_SoVITS/pretrained_models/gsv-v5-pretrained/s2Gv5dev.pth
|
||||
v5turbo:
|
||||
bert_base_path: GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large
|
||||
cnhuhbert_base_path: GPT_SoVITS/pretrained_models/chinese-hubert-base
|
||||
device: cpu
|
||||
is_half: false
|
||||
t2s_weights_path: GPT_SoVITS/pretrained_models/s1v3.ckpt
|
||||
version: v5turbo
|
||||
vits_weights_path: GPT_SoVITS/pretrained_models/gsv-v5-pretrained/s2Gv5turbo.pth
|
||||
|
||||
@ -1,13 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
|
||||
now_dir = os.getcwd()
|
||||
sys.path.insert(0, now_dir)
|
||||
from text.g2pw import G2PWPinyin
|
||||
|
||||
g2pw = G2PWPinyin(
|
||||
model_dir="GPT_SoVITS/text/G2PWModel",
|
||||
model_source="GPT_SoVITS/pretrained_models/chinese-roberta-wwm-ext-large",
|
||||
v_to_u=False,
|
||||
neutral_tone_with_five=True,
|
||||
)
|
||||
@ -12,8 +12,7 @@ import torch
|
||||
import math
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import pooling_layers as pooling_layers
|
||||
from fusion import AFF
|
||||
from .fusion import AFF
|
||||
|
||||
|
||||
class ReLU(nn.Hardtanh):
|
||||
@ -156,20 +155,12 @@ class ERes2NetV2(nn.Module):
|
||||
block_fuse=BasicBlockERes2NetV2AFF,
|
||||
num_blocks=[3, 4, 6, 3],
|
||||
m_channels=64,
|
||||
feat_dim=80,
|
||||
embedding_size=192,
|
||||
baseWidth=26,
|
||||
scale=2,
|
||||
expansion=2,
|
||||
pooling_func="TSTP",
|
||||
two_emb_layer=False,
|
||||
):
|
||||
super(ERes2NetV2, self).__init__()
|
||||
self.in_planes = m_channels
|
||||
self.feat_dim = feat_dim
|
||||
self.embedding_size = embedding_size
|
||||
self.stats_dim = int(feat_dim / 8) * m_channels * 8
|
||||
self.two_emb_layer = two_emb_layer
|
||||
self.baseWidth = baseWidth
|
||||
self.scale = scale
|
||||
self.expansion = expansion
|
||||
@ -194,16 +185,6 @@ class ERes2NetV2(nn.Module):
|
||||
# Bottom-up fusion module
|
||||
self.fuse34 = AFF(channels=m_channels * 8 * self.expansion, r=4)
|
||||
|
||||
self.n_stats = 1 if pooling_func == "TAP" or pooling_func == "TSDP" else 2
|
||||
self.pool = getattr(pooling_layers, pooling_func)(in_dim=self.stats_dim * self.expansion)
|
||||
self.seg_1 = nn.Linear(self.stats_dim * self.expansion * self.n_stats, embedding_size)
|
||||
if self.two_emb_layer:
|
||||
self.seg_bn_1 = nn.BatchNorm1d(embedding_size, affine=False)
|
||||
self.seg_2 = nn.Linear(embedding_size, embedding_size)
|
||||
else:
|
||||
self.seg_bn_1 = nn.Identity()
|
||||
self.seg_2 = nn.Identity()
|
||||
|
||||
def _make_layer(self, block, planes, num_blocks, stride):
|
||||
strides = [stride] + [1] * (num_blocks - 1)
|
||||
layers = []
|
||||
@ -216,27 +197,6 @@ class ERes2NetV2(nn.Module):
|
||||
self.in_planes = planes * self.expansion
|
||||
return nn.Sequential(*layers)
|
||||
|
||||
def forward(self, x):
|
||||
x = x.permute(0, 2, 1) # (B,T,F) => (B,F,T)
|
||||
x = x.unsqueeze_(1)
|
||||
out = F.relu(self.bn1(self.conv1(x)))
|
||||
out1 = self.layer1(out)
|
||||
out2 = self.layer2(out1)
|
||||
out3 = self.layer3(out2)
|
||||
out4 = self.layer4(out3)
|
||||
out3_ds = self.layer3_ds(out3)
|
||||
fuse_out34 = self.fuse34(out4, out3_ds)
|
||||
stats = self.pool(fuse_out34)
|
||||
|
||||
embed_a = self.seg_1(stats)
|
||||
if self.two_emb_layer:
|
||||
out = F.relu(embed_a)
|
||||
out = self.seg_bn_1(out)
|
||||
embed_b = self.seg_2(out)
|
||||
return embed_b
|
||||
else:
|
||||
return embed_a
|
||||
|
||||
def forward3(self, x):
|
||||
x = x.permute(0, 2, 1) # (B,T,F) => (B,F,T)
|
||||
x = x.unsqueeze_(1)
|
||||
@ -247,15 +207,4 @@ class ERes2NetV2(nn.Module):
|
||||
out4 = self.layer4(out3)
|
||||
out3_ds = self.layer3_ds(out3)
|
||||
fuse_out34 = self.fuse34(out4, out3_ds)
|
||||
# print(111111111,fuse_out34.shape)#111111111 torch.Size([16, 2048, 10, 72])
|
||||
return fuse_out34.flatten(start_dim=1, end_dim=2).mean(-1)
|
||||
# stats = self.pool(fuse_out34)
|
||||
#
|
||||
# embed_a = self.seg_1(stats)
|
||||
# if self.two_emb_layer:
|
||||
# out = F.relu(embed_a)
|
||||
# out = self.seg_bn_1(out)
|
||||
# embed_b = self.seg_2(out)
|
||||
# return embed_b
|
||||
# else:
|
||||
# return embed_a
|
||||
|
||||
@ -1,579 +1,59 @@
|
||||
"""Kaldi-compatible log-mel features used by the speaker inference model."""
|
||||
|
||||
import math
|
||||
from typing import Tuple
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor
|
||||
|
||||
__all__ = [
|
||||
"get_mel_banks",
|
||||
"inverse_mel_scale",
|
||||
"mel_scale",
|
||||
"mel_scale_scalar",
|
||||
"fbank",
|
||||
"vtln_warp_freq",
|
||||
"vtln_warp_mel_freq",
|
||||
]
|
||||
|
||||
# numeric_limits<float>::epsilon() 1.1920928955078125e-07
|
||||
EPSILON = torch.tensor(torch.finfo(torch.float).eps)
|
||||
# 1 milliseconds = 0.001 seconds
|
||||
MILLISECONDS_TO_SECONDS = 0.001
|
||||
|
||||
# window types
|
||||
HAMMING = "hamming"
|
||||
HANNING = "hanning"
|
||||
POVEY = "povey"
|
||||
RECTANGULAR = "rectangular"
|
||||
BLACKMAN = "blackman"
|
||||
WINDOWS = [HAMMING, HANNING, POVEY, RECTANGULAR, BLACKMAN]
|
||||
_EPSILON = torch.tensor(torch.finfo(torch.float).eps)
|
||||
_MEL_BANKS = {}
|
||||
|
||||
|
||||
def _get_epsilon(device, dtype):
|
||||
return EPSILON.to(device=device, dtype=dtype)
|
||||
def _mel_banks(num_bins, padded_size, sample_frequency, device, dtype):
|
||||
key = (num_bins, padded_size, sample_frequency, device, dtype)
|
||||
if key not in _MEL_BANKS:
|
||||
assert num_bins > 3, "Must have at least 3 mel bins"
|
||||
low_mel = 1127.0 * math.log(1.0 + 20.0 / 700.0)
|
||||
high_mel = 1127.0 * math.log(1.0 + sample_frequency * 0.5 / 700.0)
|
||||
delta = (high_mel - low_mel) / (num_bins + 1)
|
||||
bins = torch.arange(num_bins).unsqueeze(1)
|
||||
left = low_mel + bins * delta
|
||||
center = low_mel + (bins + 1.0) * delta
|
||||
right = low_mel + (bins + 2.0) * delta
|
||||
frequencies = (sample_frequency / padded_size) * torch.arange(padded_size / 2)
|
||||
mel = (1127.0 * (1.0 + frequencies / 700.0).log()).unsqueeze(0)
|
||||
up = (mel - left) / (center - left)
|
||||
down = (right - mel) / (right - center)
|
||||
banks = torch.max(torch.zeros(1), torch.min(up, down))
|
||||
_MEL_BANKS[key] = banks.to(device=device, dtype=dtype)
|
||||
return _MEL_BANKS[key]
|
||||
|
||||
|
||||
def _next_power_of_2(x: int) -> int:
|
||||
r"""Returns the smallest power of 2 that is greater than x"""
|
||||
return 1 if x == 0 else 2 ** (x - 1).bit_length()
|
||||
|
||||
|
||||
def _get_strided(waveform: Tensor, window_size: int, window_shift: int, snip_edges: bool) -> Tensor:
|
||||
r"""Given a waveform (1D tensor of size ``num_samples``), it returns a 2D tensor (m, ``window_size``)
|
||||
representing how the window is shifted along the waveform. Each row is a frame.
|
||||
|
||||
Args:
|
||||
waveform (Tensor): Tensor of size ``num_samples``
|
||||
window_size (int): Frame length
|
||||
window_shift (int): Frame shift
|
||||
snip_edges (bool): If True, end effects will be handled by outputting only frames that completely fit
|
||||
in the file, and the number of frames depends on the frame_length. If False, the number of frames
|
||||
depends only on the frame_shift, and we reflect the data at the ends.
|
||||
|
||||
Returns:
|
||||
Tensor: 2D tensor of size (m, ``window_size``) where each row is a frame
|
||||
"""
|
||||
assert waveform.dim() == 1
|
||||
num_samples = waveform.size(0)
|
||||
strides = (window_shift * waveform.stride(0), waveform.stride(0))
|
||||
|
||||
if snip_edges:
|
||||
if num_samples < window_size:
|
||||
return torch.empty((0, 0), dtype=waveform.dtype, device=waveform.device)
|
||||
else:
|
||||
m = 1 + (num_samples - window_size) // window_shift
|
||||
else:
|
||||
reversed_waveform = torch.flip(waveform, [0])
|
||||
m = (num_samples + (window_shift // 2)) // window_shift
|
||||
pad = window_size // 2 - window_shift // 2
|
||||
pad_right = reversed_waveform
|
||||
if pad > 0:
|
||||
# torch.nn.functional.pad returns [2,1,0,1,2] for 'reflect'
|
||||
# but we want [2, 1, 0, 0, 1, 2]
|
||||
pad_left = reversed_waveform[-pad:]
|
||||
waveform = torch.cat((pad_left, waveform, pad_right), dim=0)
|
||||
else:
|
||||
# pad is negative so we want to trim the waveform at the front
|
||||
waveform = torch.cat((waveform[-pad:], pad_right), dim=0)
|
||||
|
||||
sizes = (m, window_size)
|
||||
return waveform.as_strided(sizes, strides)
|
||||
|
||||
|
||||
def _feature_window_function(
|
||||
window_type: str,
|
||||
window_size: int,
|
||||
blackman_coeff: float,
|
||||
device: torch.device,
|
||||
dtype: int,
|
||||
) -> Tensor:
|
||||
r"""Returns a window function with the given type and size"""
|
||||
if window_type == HANNING:
|
||||
return torch.hann_window(window_size, periodic=False, device=device, dtype=dtype)
|
||||
elif window_type == HAMMING:
|
||||
return torch.hamming_window(window_size, periodic=False, alpha=0.54, beta=0.46, device=device, dtype=dtype)
|
||||
elif window_type == POVEY:
|
||||
# like hanning but goes to zero at edges
|
||||
return torch.hann_window(window_size, periodic=False, device=device, dtype=dtype).pow(0.85)
|
||||
elif window_type == RECTANGULAR:
|
||||
return torch.ones(window_size, device=device, dtype=dtype)
|
||||
elif window_type == BLACKMAN:
|
||||
a = 2 * math.pi / (window_size - 1)
|
||||
window_function = torch.arange(window_size, device=device, dtype=dtype)
|
||||
# can't use torch.blackman_window as they use different coefficients
|
||||
return (
|
||||
blackman_coeff
|
||||
- 0.5 * torch.cos(a * window_function)
|
||||
+ (0.5 - blackman_coeff) * torch.cos(2 * a * window_function)
|
||||
).to(device=device, dtype=dtype)
|
||||
else:
|
||||
raise Exception("Invalid window type " + window_type)
|
||||
|
||||
|
||||
def _get_log_energy(strided_input: Tensor, epsilon: Tensor, energy_floor: float) -> Tensor:
|
||||
r"""Returns the log energy of size (m) for a strided_input (m,*)"""
|
||||
device, dtype = strided_input.device, strided_input.dtype
|
||||
log_energy = torch.max(strided_input.pow(2).sum(1), epsilon).log() # size (m)
|
||||
if energy_floor == 0.0:
|
||||
return log_energy
|
||||
return torch.max(log_energy, torch.tensor(math.log(energy_floor), device=device, dtype=dtype))
|
||||
|
||||
|
||||
def _get_waveform_and_window_properties(
|
||||
waveform: Tensor,
|
||||
channel: int,
|
||||
sample_frequency: float,
|
||||
frame_shift: float,
|
||||
frame_length: float,
|
||||
round_to_power_of_two: bool,
|
||||
preemphasis_coefficient: float,
|
||||
) -> Tuple[Tensor, int, int, int]:
|
||||
r"""Gets the waveform and window properties"""
|
||||
channel = max(channel, 0)
|
||||
assert channel < waveform.size(0), "Invalid channel {} for size {}".format(channel, waveform.size(0))
|
||||
waveform = waveform[channel, :] # size (n)
|
||||
window_shift = int(sample_frequency * frame_shift * MILLISECONDS_TO_SECONDS)
|
||||
window_size = int(sample_frequency * frame_length * MILLISECONDS_TO_SECONDS)
|
||||
padded_window_size = _next_power_of_2(window_size) if round_to_power_of_two else window_size
|
||||
|
||||
assert 2 <= window_size <= len(waveform), "choose a window size {} that is [2, {}]".format(
|
||||
window_size, len(waveform)
|
||||
)
|
||||
assert 0 < window_shift, "`window_shift` must be greater than 0"
|
||||
assert padded_window_size % 2 == 0, (
|
||||
"the padded `window_size` must be divisible by two. use `round_to_power_of_two` or change `frame_length`"
|
||||
)
|
||||
assert 0.0 <= preemphasis_coefficient <= 1.0, "`preemphasis_coefficient` must be between [0,1]"
|
||||
assert sample_frequency > 0, "`sample_frequency` must be greater than zero"
|
||||
return waveform, window_shift, window_size, padded_window_size
|
||||
|
||||
|
||||
def _get_window(
|
||||
waveform: Tensor,
|
||||
padded_window_size: int,
|
||||
window_size: int,
|
||||
window_shift: int,
|
||||
window_type: str,
|
||||
blackman_coeff: float,
|
||||
snip_edges: bool,
|
||||
raw_energy: bool,
|
||||
energy_floor: float,
|
||||
dither: float,
|
||||
remove_dc_offset: bool,
|
||||
preemphasis_coefficient: float,
|
||||
) -> Tuple[Tensor, Tensor]:
|
||||
r"""Gets a window and its log energy
|
||||
|
||||
Returns:
|
||||
(Tensor, Tensor): strided_input of size (m, ``padded_window_size``) and signal_log_energy of size (m)
|
||||
"""
|
||||
def fbank(waveform: Tensor, num_mel_bins=80, sample_frequency=16000.0, dither=0.0) -> Tensor:
|
||||
"""Extract the 25 ms Povey-window log-mel features expected by ERes2NetV2."""
|
||||
assert waveform.dim() == 2 and waveform.size(0) > 0, "Expected audio of shape (channels, samples)"
|
||||
waveform = waveform[0, :]
|
||||
device, dtype = waveform.device, waveform.dtype
|
||||
epsilon = _get_epsilon(device, dtype)
|
||||
|
||||
# size (m, window_size)
|
||||
strided_input = _get_strided(waveform, window_size, window_shift, snip_edges)
|
||||
|
||||
window_shift = int(sample_frequency * 10.0 * 0.001)
|
||||
window_size = int(sample_frequency * 25.0 * 0.001)
|
||||
assert sample_frequency > 40, "sample_frequency must exceed the 20 Hz low cutoff"
|
||||
assert 2 <= window_size <= len(waveform), "Audio must contain at least one 25 ms frame"
|
||||
assert window_shift > 0, "window_shift must be greater than zero"
|
||||
padded_size = 2 ** (window_size - 1).bit_length()
|
||||
count = 1 + (waveform.size(0) - window_size) // window_shift
|
||||
frames = waveform.as_strided((count, window_size), (window_shift * waveform.stride(0), waveform.stride(0)))
|
||||
if dither != 0.0:
|
||||
rand_gauss = torch.randn(strided_input.shape, device=device, dtype=dtype)
|
||||
strided_input = strided_input + rand_gauss * dither
|
||||
|
||||
if remove_dc_offset:
|
||||
# Subtract each row/frame by its mean
|
||||
row_means = torch.mean(strided_input, dim=1).unsqueeze(1) # size (m, 1)
|
||||
strided_input = strided_input - row_means
|
||||
|
||||
if raw_energy:
|
||||
# Compute the log energy of each row/frame before applying preemphasis and
|
||||
# window function
|
||||
signal_log_energy = _get_log_energy(strided_input, epsilon, energy_floor) # size (m)
|
||||
|
||||
if preemphasis_coefficient != 0.0:
|
||||
# strided_input[i,j] -= preemphasis_coefficient * strided_input[i, max(0, j-1)] for all i,j
|
||||
offset_strided_input = torch.nn.functional.pad(strided_input.unsqueeze(0), (1, 0), mode="replicate").squeeze(
|
||||
0
|
||||
) # size (m, window_size + 1)
|
||||
strided_input = strided_input - preemphasis_coefficient * offset_strided_input[:, :-1]
|
||||
|
||||
# Apply window_function to each row/frame
|
||||
window_function = _feature_window_function(window_type, window_size, blackman_coeff, device, dtype).unsqueeze(
|
||||
0
|
||||
) # size (1, window_size)
|
||||
strided_input = strided_input * window_function # size (m, window_size)
|
||||
|
||||
# Pad columns with zero until we reach size (m, padded_window_size)
|
||||
if padded_window_size != window_size:
|
||||
padding_right = padded_window_size - window_size
|
||||
strided_input = torch.nn.functional.pad(
|
||||
strided_input.unsqueeze(0), (0, padding_right), mode="constant", value=0
|
||||
).squeeze(0)
|
||||
|
||||
# Compute energy after window function (not the raw one)
|
||||
if not raw_energy:
|
||||
signal_log_energy = _get_log_energy(strided_input, epsilon, energy_floor) # size (m)
|
||||
|
||||
return strided_input, signal_log_energy
|
||||
|
||||
|
||||
def _subtract_column_mean(tensor: Tensor, subtract_mean: bool) -> Tensor:
|
||||
# subtracts the column mean of the tensor size (m, n) if subtract_mean=True
|
||||
# it returns size (m, n)
|
||||
if subtract_mean:
|
||||
col_means = torch.mean(tensor, dim=0).unsqueeze(0)
|
||||
tensor = tensor - col_means
|
||||
return tensor
|
||||
|
||||
|
||||
def inverse_mel_scale(mel_freq: Tensor) -> Tensor:
|
||||
return 700.0 * ((mel_freq / 1127.0).exp() - 1.0)
|
||||
|
||||
|
||||
def mel_scale_scalar(freq: float) -> float:
|
||||
return 1127.0 * math.log(1.0 + freq / 700.0)
|
||||
|
||||
|
||||
def mel_scale(freq: Tensor) -> Tensor:
|
||||
return 1127.0 * (1.0 + freq / 700.0).log()
|
||||
|
||||
|
||||
def vtln_warp_freq(
|
||||
vtln_low_cutoff: float,
|
||||
vtln_high_cutoff: float,
|
||||
low_freq: float,
|
||||
high_freq: float,
|
||||
vtln_warp_factor: float,
|
||||
freq: Tensor,
|
||||
) -> Tensor:
|
||||
r"""This computes a VTLN warping function that is not the same as HTK's one,
|
||||
but has similar inputs (this function has the advantage of never producing
|
||||
empty bins).
|
||||
|
||||
This function computes a warp function F(freq), defined between low_freq
|
||||
and high_freq inclusive, with the following properties:
|
||||
F(low_freq) == low_freq
|
||||
F(high_freq) == high_freq
|
||||
The function is continuous and piecewise linear with two inflection
|
||||
points.
|
||||
The lower inflection point (measured in terms of the unwarped
|
||||
frequency) is at frequency l, determined as described below.
|
||||
The higher inflection point is at a frequency h, determined as
|
||||
described below.
|
||||
If l <= f <= h, then F(f) = f/vtln_warp_factor.
|
||||
If the higher inflection point (measured in terms of the unwarped
|
||||
frequency) is at h, then max(h, F(h)) == vtln_high_cutoff.
|
||||
Since (by the last point) F(h) == h/vtln_warp_factor, then
|
||||
max(h, h/vtln_warp_factor) == vtln_high_cutoff, so
|
||||
h = vtln_high_cutoff / max(1, 1/vtln_warp_factor).
|
||||
= vtln_high_cutoff * min(1, vtln_warp_factor).
|
||||
If the lower inflection point (measured in terms of the unwarped
|
||||
frequency) is at l, then min(l, F(l)) == vtln_low_cutoff
|
||||
This implies that l = vtln_low_cutoff / min(1, 1/vtln_warp_factor)
|
||||
= vtln_low_cutoff * max(1, vtln_warp_factor)
|
||||
Args:
|
||||
vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
|
||||
vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
|
||||
low_freq (float): Lower frequency cutoffs in mel computation
|
||||
high_freq (float): Upper frequency cutoffs in mel computation
|
||||
vtln_warp_factor (float): Vtln warp factor
|
||||
freq (Tensor): given frequency in Hz
|
||||
|
||||
Returns:
|
||||
Tensor: Freq after vtln warp
|
||||
"""
|
||||
assert vtln_low_cutoff > low_freq, "be sure to set the vtln_low option higher than low_freq"
|
||||
assert vtln_high_cutoff < high_freq, "be sure to set the vtln_high option lower than high_freq [or negative]"
|
||||
l = vtln_low_cutoff * max(1.0, vtln_warp_factor)
|
||||
h = vtln_high_cutoff * min(1.0, vtln_warp_factor)
|
||||
scale = 1.0 / vtln_warp_factor
|
||||
Fl = scale * l # F(l)
|
||||
Fh = scale * h # F(h)
|
||||
assert l > low_freq and h < high_freq
|
||||
# slope of left part of the 3-piece linear function
|
||||
scale_left = (Fl - low_freq) / (l - low_freq)
|
||||
# [slope of center part is just "scale"]
|
||||
|
||||
# slope of right part of the 3-piece linear function
|
||||
scale_right = (high_freq - Fh) / (high_freq - h)
|
||||
|
||||
res = torch.empty_like(freq)
|
||||
|
||||
outside_low_high_freq = torch.lt(freq, low_freq) | torch.gt(freq, high_freq) # freq < low_freq || freq > high_freq
|
||||
before_l = torch.lt(freq, l) # freq < l
|
||||
before_h = torch.lt(freq, h) # freq < h
|
||||
after_h = torch.ge(freq, h) # freq >= h
|
||||
|
||||
# order of operations matter here (since there is overlapping frequency regions)
|
||||
res[after_h] = high_freq + scale_right * (freq[after_h] - high_freq)
|
||||
res[before_h] = scale * freq[before_h]
|
||||
res[before_l] = low_freq + scale_left * (freq[before_l] - low_freq)
|
||||
res[outside_low_high_freq] = freq[outside_low_high_freq]
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def vtln_warp_mel_freq(
|
||||
vtln_low_cutoff: float,
|
||||
vtln_high_cutoff: float,
|
||||
low_freq,
|
||||
high_freq: float,
|
||||
vtln_warp_factor: float,
|
||||
mel_freq: Tensor,
|
||||
) -> Tensor:
|
||||
r"""
|
||||
Args:
|
||||
vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
|
||||
vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
|
||||
low_freq (float): Lower frequency cutoffs in mel computation
|
||||
high_freq (float): Upper frequency cutoffs in mel computation
|
||||
vtln_warp_factor (float): Vtln warp factor
|
||||
mel_freq (Tensor): Given frequency in Mel
|
||||
|
||||
Returns:
|
||||
Tensor: ``mel_freq`` after vtln warp
|
||||
"""
|
||||
return mel_scale(
|
||||
vtln_warp_freq(
|
||||
vtln_low_cutoff, vtln_high_cutoff, low_freq, high_freq, vtln_warp_factor, inverse_mel_scale(mel_freq)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def get_mel_banks(
|
||||
num_bins: int,
|
||||
window_length_padded: int,
|
||||
sample_freq: float,
|
||||
low_freq: float,
|
||||
high_freq: float,
|
||||
vtln_low: float,
|
||||
vtln_high: float,
|
||||
vtln_warp_factor: float,
|
||||
device=None,
|
||||
dtype=None,
|
||||
) -> Tuple[Tensor, Tensor]:
|
||||
"""
|
||||
Returns:
|
||||
(Tensor, Tensor): The tuple consists of ``bins`` (which is
|
||||
melbank of size (``num_bins``, ``num_fft_bins``)) and ``center_freqs`` (which is
|
||||
center frequencies of bins of size (``num_bins``)).
|
||||
"""
|
||||
assert num_bins > 3, "Must have at least 3 mel bins"
|
||||
assert window_length_padded % 2 == 0
|
||||
num_fft_bins = window_length_padded / 2
|
||||
nyquist = 0.5 * sample_freq
|
||||
|
||||
if high_freq <= 0.0:
|
||||
high_freq += nyquist
|
||||
|
||||
assert (0.0 <= low_freq < nyquist) and (0.0 < high_freq <= nyquist) and (low_freq < high_freq), (
|
||||
"Bad values in options: low-freq {} and high-freq {} vs. nyquist {}".format(low_freq, high_freq, nyquist)
|
||||
)
|
||||
|
||||
# fft-bin width [think of it as Nyquist-freq / half-window-length]
|
||||
fft_bin_width = sample_freq / window_length_padded
|
||||
mel_low_freq = mel_scale_scalar(low_freq)
|
||||
mel_high_freq = mel_scale_scalar(high_freq)
|
||||
|
||||
# divide by num_bins+1 in next line because of end-effects where the bins
|
||||
# spread out to the sides.
|
||||
mel_freq_delta = (mel_high_freq - mel_low_freq) / (num_bins + 1)
|
||||
|
||||
if vtln_high < 0.0:
|
||||
vtln_high += nyquist
|
||||
|
||||
assert vtln_warp_factor == 1.0 or (
|
||||
(low_freq < vtln_low < high_freq) and (0.0 < vtln_high < high_freq) and (vtln_low < vtln_high)
|
||||
), "Bad values in options: vtln-low {} and vtln-high {}, versus low-freq {} and high-freq {}".format(
|
||||
vtln_low, vtln_high, low_freq, high_freq
|
||||
)
|
||||
|
||||
bin = torch.arange(num_bins).unsqueeze(1)
|
||||
left_mel = mel_low_freq + bin * mel_freq_delta # size(num_bins, 1)
|
||||
center_mel = mel_low_freq + (bin + 1.0) * mel_freq_delta # size(num_bins, 1)
|
||||
right_mel = mel_low_freq + (bin + 2.0) * mel_freq_delta # size(num_bins, 1)
|
||||
|
||||
if vtln_warp_factor != 1.0:
|
||||
left_mel = vtln_warp_mel_freq(vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, left_mel)
|
||||
center_mel = vtln_warp_mel_freq(vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, center_mel)
|
||||
right_mel = vtln_warp_mel_freq(vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, right_mel)
|
||||
|
||||
# center_freqs = inverse_mel_scale(center_mel) # size (num_bins)
|
||||
# size(1, num_fft_bins)
|
||||
mel = mel_scale(fft_bin_width * torch.arange(num_fft_bins)).unsqueeze(0)
|
||||
|
||||
# size (num_bins, num_fft_bins)
|
||||
up_slope = (mel - left_mel) / (center_mel - left_mel)
|
||||
down_slope = (right_mel - mel) / (right_mel - center_mel)
|
||||
|
||||
if vtln_warp_factor == 1.0:
|
||||
# left_mel < center_mel < right_mel so we can min the two slopes and clamp negative values
|
||||
bins = torch.max(torch.zeros(1), torch.min(up_slope, down_slope))
|
||||
else:
|
||||
# warping can move the order of left_mel, center_mel, right_mel anywhere
|
||||
bins = torch.zeros_like(up_slope)
|
||||
up_idx = torch.gt(mel, left_mel) & torch.le(mel, center_mel) # left_mel < mel <= center_mel
|
||||
down_idx = torch.gt(mel, center_mel) & torch.lt(mel, right_mel) # center_mel < mel < right_mel
|
||||
bins[up_idx] = up_slope[up_idx]
|
||||
bins[down_idx] = down_slope[down_idx]
|
||||
|
||||
return bins.to(device=device, dtype=dtype) # , center_freqs
|
||||
|
||||
|
||||
cache = {}
|
||||
|
||||
|
||||
def fbank(
|
||||
waveform: Tensor,
|
||||
blackman_coeff: float = 0.42,
|
||||
channel: int = -1,
|
||||
dither: float = 0.0,
|
||||
energy_floor: float = 1.0,
|
||||
frame_length: float = 25.0,
|
||||
frame_shift: float = 10.0,
|
||||
high_freq: float = 0.0,
|
||||
htk_compat: bool = False,
|
||||
low_freq: float = 20.0,
|
||||
min_duration: float = 0.0,
|
||||
num_mel_bins: int = 23,
|
||||
preemphasis_coefficient: float = 0.97,
|
||||
raw_energy: bool = True,
|
||||
remove_dc_offset: bool = True,
|
||||
round_to_power_of_two: bool = True,
|
||||
sample_frequency: float = 16000.0,
|
||||
snip_edges: bool = True,
|
||||
subtract_mean: bool = False,
|
||||
use_energy: bool = False,
|
||||
use_log_fbank: bool = True,
|
||||
use_power: bool = True,
|
||||
vtln_high: float = -500.0,
|
||||
vtln_low: float = 100.0,
|
||||
vtln_warp: float = 1.0,
|
||||
window_type: str = POVEY,
|
||||
) -> Tensor:
|
||||
r"""Create a fbank from a raw audio signal. This matches the input/output of Kaldi's
|
||||
compute-fbank-feats.
|
||||
|
||||
Args:
|
||||
waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
|
||||
blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
|
||||
channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
|
||||
dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
|
||||
the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
|
||||
energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
|
||||
this floor is applied to the zeroth component, representing the total signal energy. The floor on the
|
||||
individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
|
||||
frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
|
||||
frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
|
||||
high_freq (float, optional): High cutoff frequency for mel bins (if <= 0, offset from Nyquist)
|
||||
(Default: ``0.0``)
|
||||
htk_compat (bool, optional): If true, put energy last. Warning: not sufficient to get HTK compatible features
|
||||
(need to change other parameters). (Default: ``False``)
|
||||
low_freq (float, optional): Low cutoff frequency for mel bins (Default: ``20.0``)
|
||||
min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
|
||||
num_mel_bins (int, optional): Number of triangular mel-frequency bins (Default: ``23``)
|
||||
preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
|
||||
raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
|
||||
remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
|
||||
round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
|
||||
to FFT. (Default: ``True``)
|
||||
sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
|
||||
specified there) (Default: ``16000.0``)
|
||||
snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
|
||||
in the file, and the number of frames depends on the frame_length. If False, the number of frames
|
||||
depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
|
||||
subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
|
||||
it this way. (Default: ``False``)
|
||||
use_energy (bool, optional): Add an extra dimension with energy to the FBANK output. (Default: ``False``)
|
||||
use_log_fbank (bool, optional):If true, produce log-filterbank, else produce linear. (Default: ``True``)
|
||||
use_power (bool, optional): If true, use power, else use magnitude. (Default: ``True``)
|
||||
vtln_high (float, optional): High inflection point in piecewise linear VTLN warping function (if
|
||||
negative, offset from high-mel-freq (Default: ``-500.0``)
|
||||
vtln_low (float, optional): Low inflection point in piecewise linear VTLN warping function (Default: ``100.0``)
|
||||
vtln_warp (float, optional): Vtln warp factor (only applicable if vtln_map not specified) (Default: ``1.0``)
|
||||
window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
|
||||
(Default: ``'povey'``)
|
||||
|
||||
Returns:
|
||||
Tensor: A fbank identical to what Kaldi would output. The shape is (m, ``num_mel_bins + use_energy``)
|
||||
where m is calculated in _get_strided
|
||||
"""
|
||||
device, dtype = waveform.device, waveform.dtype
|
||||
|
||||
waveform, window_shift, window_size, padded_window_size = _get_waveform_and_window_properties(
|
||||
waveform, channel, sample_frequency, frame_shift, frame_length, round_to_power_of_two, preemphasis_coefficient
|
||||
)
|
||||
|
||||
if len(waveform) < min_duration * sample_frequency:
|
||||
# signal is too short
|
||||
return torch.empty(0, device=device, dtype=dtype)
|
||||
|
||||
# strided_input, size (m, padded_window_size) and signal_log_energy, size (m)
|
||||
strided_input, signal_log_energy = _get_window(
|
||||
waveform,
|
||||
padded_window_size,
|
||||
window_size,
|
||||
window_shift,
|
||||
window_type,
|
||||
blackman_coeff,
|
||||
snip_edges,
|
||||
raw_energy,
|
||||
energy_floor,
|
||||
dither,
|
||||
remove_dc_offset,
|
||||
preemphasis_coefficient,
|
||||
)
|
||||
|
||||
# size (m, padded_window_size // 2 + 1)
|
||||
spectrum = torch.fft.rfft(strided_input).abs()
|
||||
if use_power:
|
||||
spectrum = spectrum.pow(2.0)
|
||||
|
||||
# size (num_mel_bins, padded_window_size // 2)
|
||||
# print(num_mel_bins, padded_window_size, sample_frequency, low_freq, high_freq, vtln_low, vtln_high, vtln_warp)
|
||||
|
||||
cache_key = "%s-%s-%s-%s-%s-%s-%s-%s-%s-%s" % (
|
||||
num_mel_bins,
|
||||
padded_window_size,
|
||||
sample_frequency,
|
||||
low_freq,
|
||||
high_freq,
|
||||
vtln_low,
|
||||
vtln_high,
|
||||
vtln_warp,
|
||||
device,
|
||||
dtype,
|
||||
)
|
||||
if cache_key not in cache:
|
||||
mel_energies = get_mel_banks(
|
||||
num_mel_bins,
|
||||
padded_window_size,
|
||||
sample_frequency,
|
||||
low_freq,
|
||||
high_freq,
|
||||
vtln_low,
|
||||
vtln_high,
|
||||
vtln_warp,
|
||||
device,
|
||||
dtype,
|
||||
)
|
||||
cache[cache_key] = mel_energies
|
||||
else:
|
||||
mel_energies = cache[cache_key]
|
||||
|
||||
# pad right column with zeros and add dimension, size (num_mel_bins, padded_window_size // 2 + 1)
|
||||
mel_energies = torch.nn.functional.pad(mel_energies, (0, 1), mode="constant", value=0)
|
||||
|
||||
# sum with mel fiterbanks over the power spectrum, size (m, num_mel_bins)
|
||||
mel_energies = torch.mm(spectrum, mel_energies.T)
|
||||
if use_log_fbank:
|
||||
# avoid log of zero (which should be prevented anyway by dithering)
|
||||
mel_energies = torch.max(mel_energies, _get_epsilon(device, dtype)).log()
|
||||
|
||||
# if use_energy then add it as the last column for htk_compat == true else first column
|
||||
if use_energy:
|
||||
signal_log_energy = signal_log_energy.unsqueeze(1) # size (m, 1)
|
||||
# returns size (m, num_mel_bins + 1)
|
||||
if htk_compat:
|
||||
mel_energies = torch.cat((mel_energies, signal_log_energy), dim=1)
|
||||
else:
|
||||
mel_energies = torch.cat((signal_log_energy, mel_energies), dim=1)
|
||||
|
||||
mel_energies = _subtract_column_mean(mel_energies, subtract_mean)
|
||||
return mel_energies
|
||||
frames = frames + torch.randn(frames.shape, device=device, dtype=dtype) * dither
|
||||
frames = frames - torch.mean(frames, dim=1).unsqueeze(1)
|
||||
previous = F.pad(frames.unsqueeze(0), (1, 0), mode="replicate").squeeze(0)
|
||||
frames = frames - 0.97 * previous[:, :-1]
|
||||
window = torch.hann_window(window_size, periodic=False, device=device, dtype=dtype).pow(0.85)
|
||||
frames = frames * window.unsqueeze(0)
|
||||
if padded_size != window_size:
|
||||
frames = F.pad(frames.unsqueeze(0), (0, padded_size - window_size), mode="constant", value=0).squeeze(0)
|
||||
spectrum = torch.fft.rfft(frames).abs().pow(2.0)
|
||||
banks = _mel_banks(num_mel_bins, padded_size, sample_frequency, device, dtype)
|
||||
banks = F.pad(banks, (0, 1), mode="constant", value=0)
|
||||
energies = torch.mm(spectrum, banks.T)
|
||||
return torch.max(energies, _EPSILON.to(device=device, dtype=dtype)).log()
|
||||
|
||||
@ -1,101 +0,0 @@
|
||||
# Copyright 3D-Speaker (https://github.com/alibaba-damo-academy/3D-Speaker). All Rights Reserved.
|
||||
# Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
||||
|
||||
"""This implementation is adapted from https://github.com/wenet-e2e/wespeaker."""
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
class TAP(nn.Module):
|
||||
"""
|
||||
Temporal average pooling, only first-order mean is considered
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(TAP, self).__init__()
|
||||
|
||||
def forward(self, x):
|
||||
pooling_mean = x.mean(dim=-1)
|
||||
# To be compatable with 2D input
|
||||
pooling_mean = pooling_mean.flatten(start_dim=1)
|
||||
return pooling_mean
|
||||
|
||||
|
||||
class TSDP(nn.Module):
|
||||
"""
|
||||
Temporal standard deviation pooling, only second-order std is considered
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(TSDP, self).__init__()
|
||||
|
||||
def forward(self, x):
|
||||
# The last dimension is the temporal axis
|
||||
pooling_std = torch.sqrt(torch.var(x, dim=-1) + 1e-8)
|
||||
pooling_std = pooling_std.flatten(start_dim=1)
|
||||
return pooling_std
|
||||
|
||||
|
||||
class TSTP(nn.Module):
|
||||
"""
|
||||
Temporal statistics pooling, concatenate mean and std, which is used in
|
||||
x-vector
|
||||
Comment: simple concatenation can not make full use of both statistics
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(TSTP, self).__init__()
|
||||
|
||||
def forward(self, x):
|
||||
# The last dimension is the temporal axis
|
||||
pooling_mean = x.mean(dim=-1)
|
||||
pooling_std = torch.sqrt(torch.var(x, dim=-1) + 1e-8)
|
||||
pooling_mean = pooling_mean.flatten(start_dim=1)
|
||||
pooling_std = pooling_std.flatten(start_dim=1)
|
||||
|
||||
stats = torch.cat((pooling_mean, pooling_std), 1)
|
||||
return stats
|
||||
|
||||
|
||||
class ASTP(nn.Module):
|
||||
"""Attentive statistics pooling: Channel- and context-dependent
|
||||
statistics pooling, first used in ECAPA_TDNN.
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim, bottleneck_dim=128, global_context_att=False):
|
||||
super(ASTP, self).__init__()
|
||||
self.global_context_att = global_context_att
|
||||
|
||||
# Use Conv1d with stride == 1 rather than Linear, then we don't
|
||||
# need to transpose inputs.
|
||||
if global_context_att:
|
||||
self.linear1 = nn.Conv1d(in_dim * 3, bottleneck_dim, kernel_size=1) # equals W and b in the paper
|
||||
else:
|
||||
self.linear1 = nn.Conv1d(in_dim, bottleneck_dim, kernel_size=1) # equals W and b in the paper
|
||||
self.linear2 = nn.Conv1d(bottleneck_dim, in_dim, kernel_size=1) # equals V and k in the paper
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
x: a 3-dimensional tensor in tdnn-based architecture (B,F,T)
|
||||
or a 4-dimensional tensor in resnet architecture (B,C,F,T)
|
||||
0-dim: batch-dimension, last-dim: time-dimension (frame-dimension)
|
||||
"""
|
||||
if len(x.shape) == 4:
|
||||
x = x.reshape(x.shape[0], x.shape[1] * x.shape[2], x.shape[3])
|
||||
assert len(x.shape) == 3
|
||||
|
||||
if self.global_context_att:
|
||||
context_mean = torch.mean(x, dim=-1, keepdim=True).expand_as(x)
|
||||
context_std = torch.sqrt(torch.var(x, dim=-1, keepdim=True) + 1e-10).expand_as(x)
|
||||
x_in = torch.cat((x, context_mean, context_std), dim=1)
|
||||
else:
|
||||
x_in = x
|
||||
|
||||
# DON'T use ReLU here! ReLU may be hard to converge.
|
||||
alpha = torch.tanh(self.linear1(x_in)) # alpha = F.relu(self.linear1(x_in))
|
||||
alpha = torch.softmax(self.linear2(alpha), dim=2)
|
||||
mean = torch.sum(alpha * x, dim=2)
|
||||
var = torch.sum(alpha * (x**2), dim=2) - mean**2
|
||||
std = torch.sqrt(var.clamp(min=1e-10))
|
||||
return torch.cat([mean, std], dim=1)
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,20 +0,0 @@
|
||||
## Backbones quick introduction
|
||||
|
||||
|
||||
### unett.py
|
||||
- flat unet transformer
|
||||
- structure same as in e2-tts & voicebox paper except using rotary pos emb
|
||||
- update: allow possible abs pos emb & convnextv2 blocks for embedded text before concat
|
||||
|
||||
### dit.py
|
||||
- adaln-zero dit
|
||||
- embedded timestep as condition
|
||||
- concatted noised_input + masked_cond + embedded_text, linear proj in
|
||||
- possible abs pos emb & convnextv2 blocks for embedded text before concat
|
||||
- possible long skip connection (first layer to last layer)
|
||||
|
||||
### mmdit.py
|
||||
- sd3 structure
|
||||
- timestep as condition
|
||||
- left stream: text embedded and applied a abs pos emb
|
||||
- right stream: masked_cond & noised_input concatted and with same conv pos emb as unett
|
||||
@ -12,7 +12,6 @@ from __future__ import annotations
|
||||
import torch
|
||||
from torch import nn
|
||||
import torch.nn.functional as F
|
||||
from torch.utils.checkpoint import checkpoint
|
||||
|
||||
from x_transformers.x_transformers import RotaryEmbedding
|
||||
|
||||
@ -99,7 +98,6 @@ class DiT(nn.Module):
|
||||
mel_dim=100,
|
||||
text_dim=None,
|
||||
conv_layers=0,
|
||||
long_skip_connection=False,
|
||||
use_step_embedding=True,
|
||||
):
|
||||
super().__init__()
|
||||
@ -119,18 +117,10 @@ class DiT(nn.Module):
|
||||
self.transformer_blocks = nn.ModuleList(
|
||||
[DiTBlock(dim=dim, heads=heads, dim_head=dim_head, ff_mult=ff_mult, dropout=dropout) for _ in range(depth)]
|
||||
)
|
||||
self.long_skip_connection = nn.Linear(dim * 2, dim, bias=False) if long_skip_connection else None
|
||||
|
||||
self.norm_out = AdaLayerNormZero_Final(dim) # final modulation
|
||||
self.proj_out = nn.Linear(dim, mel_dim)
|
||||
|
||||
def ckpt_wrapper(self, module):
|
||||
# https://github.com/chuanyangjin/fast-DiT/blob/main/models.py
|
||||
def ckpt_forward(*inputs):
|
||||
outputs = module(*inputs)
|
||||
return outputs
|
||||
|
||||
return ckpt_forward
|
||||
|
||||
def prepare_static_cache(self, cond0, x_lens, text0):
|
||||
text = text0.transpose(2, 1)
|
||||
@ -162,12 +152,10 @@ class DiT(nn.Module):
|
||||
time: float["b"] | float[""], # time step # noqa: F821 F722
|
||||
dt_base_bootstrap=None,
|
||||
text0=None, # : int["b nt"] # noqa: F722#####condition feature
|
||||
use_grad_ckpt=False, # bool
|
||||
###no-use
|
||||
drop_audio_cond=False, # cfg for cond audio
|
||||
drop_text=False, # cfg for text
|
||||
# mask: bool["b n"] | None = None, # noqa: F722
|
||||
infer=False, # bool
|
||||
text_cache=None, # torch tensor as text_embed
|
||||
dt_cache=None, # torch tensor as dt
|
||||
static_cache=None,
|
||||
@ -186,7 +174,7 @@ class DiT(nn.Module):
|
||||
t = self.time_embed(time)
|
||||
if self.d_embed is None:
|
||||
dt = None
|
||||
elif infer and dt_cache is not None:
|
||||
elif dt_cache is not None:
|
||||
dt = dt_cache
|
||||
else:
|
||||
dt = self.d_embed(dt_base_bootstrap)
|
||||
@ -197,7 +185,7 @@ class DiT(nn.Module):
|
||||
static = static_cache["negative_condition" if drop_audio_cond else "condition"]
|
||||
x = F.linear(x, self.input_embed.proj.weight[:, :x.shape[-1]]) + static
|
||||
x = self.input_embed.conv_pos_embed(x, mask=mask) + x
|
||||
elif infer and text_cache is not None:
|
||||
elif text_cache is not None:
|
||||
text_embed = text_cache
|
||||
x = self.input_embed(x, cond, text_embed, drop_audio_cond=drop_audio_cond)
|
||||
else:
|
||||
@ -207,22 +195,10 @@ class DiT(nn.Module):
|
||||
rope = (static_cache["rope"] if static_cache is not None
|
||||
else self.rotary_embed.forward_from_seq_len(seq_len))
|
||||
|
||||
if self.long_skip_connection is not None:
|
||||
residual = x
|
||||
|
||||
for block in self.transformer_blocks:
|
||||
if use_grad_ckpt:
|
||||
x = checkpoint(self.ckpt_wrapper(block), x, t, mask, rope, use_reentrant=False)
|
||||
else:
|
||||
x = block(x, t, mask=mask, rope=rope)
|
||||
|
||||
if self.long_skip_connection is not None:
|
||||
x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
|
||||
x = block(x, t, mask=mask, rope=rope)
|
||||
|
||||
x = self.norm_out(x, t)
|
||||
output = self.proj_out(x)
|
||||
|
||||
if infer:
|
||||
return output, text_embed if static_cache is None else None, dt
|
||||
else:
|
||||
return output
|
||||
return output, text_embed if static_cache is None else None, dt
|
||||
|
||||
@ -1,3 +1 @@
|
||||
from . import cnhubert, whisper_enc
|
||||
|
||||
content_module_map = {"cnhubert": cnhubert, "whisper": whisper_enc}
|
||||
"""Speech feature extraction for inference."""
|
||||
|
||||
@ -17,20 +17,12 @@ from transformers import (
|
||||
HubertModel,
|
||||
)
|
||||
|
||||
import utils
|
||||
import torch.nn as nn
|
||||
|
||||
cnhubert_base_path = None
|
||||
|
||||
|
||||
class CNHubert(nn.Module):
|
||||
def __init__(self, base_path: str = None):
|
||||
def __init__(self, base_path: str):
|
||||
super().__init__()
|
||||
if base_path is None:
|
||||
base_path = cnhubert_base_path
|
||||
if os.path.exists(base_path):
|
||||
...
|
||||
else:
|
||||
if not os.path.exists(base_path):
|
||||
raise FileNotFoundError(base_path)
|
||||
self.model = HubertModel.from_pretrained(base_path, local_files_only=True)
|
||||
self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(base_path, local_files_only=True)
|
||||
@ -39,72 +31,3 @@ class CNHubert(nn.Module):
|
||||
input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
|
||||
feats = self.model(input_values)["last_hidden_state"]
|
||||
return feats
|
||||
|
||||
|
||||
# class CNHubertLarge(nn.Module):
|
||||
# def __init__(self):
|
||||
# super().__init__()
|
||||
# self.model = HubertModel.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-hubert-large")
|
||||
# self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-hubert-large")
|
||||
# def forward(self, x):
|
||||
# input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
|
||||
# feats = self.model(input_values)["last_hidden_state"]
|
||||
# return feats
|
||||
#
|
||||
# class CVec(nn.Module):
|
||||
# def __init__(self):
|
||||
# super().__init__()
|
||||
# self.model = HubertModel.from_pretrained("/data/docker/liujing04/vc-webui-big/hubert_base")
|
||||
# self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("/data/docker/liujing04/vc-webui-big/hubert_base")
|
||||
# def forward(self, x):
|
||||
# input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
|
||||
# feats = self.model(input_values)["last_hidden_state"]
|
||||
# return feats
|
||||
#
|
||||
# class cnw2v2base(nn.Module):
|
||||
# def __init__(self):
|
||||
# super().__init__()
|
||||
# self.model = Wav2Vec2Model.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-wav2vec2-base")
|
||||
# self.feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("/data/docker/liujing04/gpt-vits/chinese-wav2vec2-base")
|
||||
# def forward(self, x):
|
||||
# input_values = self.feature_extractor(x, return_tensors="pt", sampling_rate=16000).input_values.to(x.device)
|
||||
# feats = self.model(input_values)["last_hidden_state"]
|
||||
# return feats
|
||||
|
||||
|
||||
def get_model():
|
||||
model = CNHubert()
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
|
||||
# def get_large_model():
|
||||
# model = CNHubertLarge()
|
||||
# model.eval()
|
||||
# return model
|
||||
#
|
||||
# def get_model_cvec():
|
||||
# model = CVec()
|
||||
# model.eval()
|
||||
# return model
|
||||
#
|
||||
# def get_model_cnw2v2base():
|
||||
# model = cnw2v2base()
|
||||
# model.eval()
|
||||
# return model
|
||||
|
||||
|
||||
def get_content(hmodel, wav_16k_tensor):
|
||||
with torch.no_grad():
|
||||
feats = hmodel(wav_16k_tensor)
|
||||
return feats.transpose(1, 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
model = get_model()
|
||||
src_path = "/Users/Shared/原音频2.wav"
|
||||
wav_16k_tensor = utils.load_wav_to_torch_and_resample(src_path, 16000)
|
||||
model = model
|
||||
wav_16k_tensor = wav_16k_tensor
|
||||
feats = get_content(model, wav_16k_tensor)
|
||||
print(feats.shape)
|
||||
|
||||
@ -1,23 +0,0 @@
|
||||
import torch
|
||||
|
||||
|
||||
def get_model():
|
||||
import whisper
|
||||
|
||||
model = whisper.load_model("small", device="cpu")
|
||||
|
||||
return model.encoder
|
||||
|
||||
|
||||
def get_content(model=None, wav_16k_tensor=None):
|
||||
from whisper import log_mel_spectrogram, pad_or_trim
|
||||
|
||||
dev = next(model.parameters()).device
|
||||
mel = log_mel_spectrogram(wav_16k_tensor).to(dev)[:, :3000]
|
||||
# if torch.cuda.is_available():
|
||||
# mel = mel.to(torch.float16)
|
||||
feature_len = mel.shape[-1] // 2
|
||||
assert mel.shape[-1] < 3000, "输入音频过长,只允许输入30以内音频"
|
||||
with torch.no_grad():
|
||||
feature = model(pad_or_trim(mel, 3000).unsqueeze(0))[:1, :feature_len, :].transpose(1, 2)
|
||||
return feature
|
||||
@ -1,86 +0,0 @@
|
||||
import argparse
|
||||
import os
|
||||
import soundfile as sf
|
||||
|
||||
from tools.i18n.i18n import I18nAuto
|
||||
from GPT_SoVITS.inference_webui import change_gpt_weights, change_sovits_weights, get_tts_wav
|
||||
|
||||
i18n = I18nAuto()
|
||||
|
||||
|
||||
def synthesize(
|
||||
GPT_model_path,
|
||||
SoVITS_model_path,
|
||||
ref_audio_path,
|
||||
ref_text_path,
|
||||
ref_language,
|
||||
target_text_path,
|
||||
target_language,
|
||||
output_path,
|
||||
):
|
||||
# Read reference text
|
||||
with open(ref_text_path, "r", encoding="utf-8") as file:
|
||||
ref_text = file.read()
|
||||
|
||||
# Read target text
|
||||
with open(target_text_path, "r", encoding="utf-8") as file:
|
||||
target_text = file.read()
|
||||
|
||||
# Change model weights
|
||||
change_gpt_weights(gpt_path=GPT_model_path)
|
||||
change_sovits_weights(sovits_path=SoVITS_model_path)
|
||||
|
||||
# Synthesize audio
|
||||
synthesis_result = get_tts_wav(
|
||||
ref_wav_path=ref_audio_path,
|
||||
prompt_text=ref_text,
|
||||
prompt_language=i18n(ref_language),
|
||||
text=target_text,
|
||||
text_language=i18n(target_language),
|
||||
top_p=1,
|
||||
temperature=1,
|
||||
)
|
||||
|
||||
result_list = list(synthesis_result)
|
||||
|
||||
if result_list:
|
||||
last_sampling_rate, last_audio_data = result_list[-1]
|
||||
output_wav_path = os.path.join(output_path, "output.wav")
|
||||
sf.write(output_wav_path, last_audio_data, last_sampling_rate)
|
||||
print(f"Audio saved to {output_wav_path}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="GPT-SoVITS Command Line Tool")
|
||||
parser.add_argument("--gpt_model", required=True, help="Path to the GPT model file")
|
||||
parser.add_argument("--sovits_model", required=True, help="Path to the SoVITS model file")
|
||||
parser.add_argument("--ref_audio", required=True, help="Path to the reference audio file")
|
||||
parser.add_argument("--ref_text", required=True, help="Path to the reference text file")
|
||||
parser.add_argument(
|
||||
"--ref_language", required=True, choices=["中文", "英文", "日文"], help="Language of the reference audio"
|
||||
)
|
||||
parser.add_argument("--target_text", required=True, help="Path to the target text file")
|
||||
parser.add_argument(
|
||||
"--target_language",
|
||||
required=True,
|
||||
choices=["中文", "英文", "日文", "中英混合", "日英混合", "多语种混合"],
|
||||
help="Language of the target text",
|
||||
)
|
||||
parser.add_argument("--output_path", required=True, help="Path to the output directory")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
synthesize(
|
||||
args.gpt_model,
|
||||
args.sovits_model,
|
||||
args.ref_audio,
|
||||
args.ref_text,
|
||||
args.ref_language,
|
||||
args.target_text,
|
||||
args.target_language,
|
||||
args.output_path,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,316 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
from PyQt5.QtCore import QEvent
|
||||
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QTextEdit
|
||||
from PyQt5.QtWidgets import QGridLayout, QVBoxLayout, QWidget, QFileDialog, QStatusBar, QComboBox
|
||||
import soundfile as sf
|
||||
|
||||
from tools.i18n.i18n import I18nAuto
|
||||
|
||||
i18n = I18nAuto()
|
||||
|
||||
from inference_webui import gpt_path, sovits_path, change_gpt_weights, change_sovits_weights, get_tts_wav
|
||||
|
||||
|
||||
class GPTSoVITSGUI(QMainWindow):
|
||||
GPT_Path = gpt_path
|
||||
SoVITS_Path = sovits_path
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.setWindowTitle("GPT-SoVITS GUI")
|
||||
self.setGeometry(800, 450, 950, 850)
|
||||
|
||||
self.setStyleSheet("""
|
||||
QWidget {
|
||||
background-color: #a3d3b1;
|
||||
}
|
||||
|
||||
QTabWidget::pane {
|
||||
background-color: #a3d3b1;
|
||||
}
|
||||
|
||||
QTabWidget::tab-bar {
|
||||
alignment: left;
|
||||
}
|
||||
|
||||
QTabBar::tab {
|
||||
background: #8da4bf;
|
||||
color: #ffffff;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
QTabBar::tab:selected {
|
||||
background: #2a3f54;
|
||||
}
|
||||
|
||||
QLabel {
|
||||
color: #000000;
|
||||
}
|
||||
|
||||
QPushButton {
|
||||
background-color: #4CAF50;
|
||||
color: white;
|
||||
padding: 8px;
|
||||
border: 1px solid #4CAF50;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
QPushButton:hover {
|
||||
background-color: #45a049;
|
||||
border: 1px solid #45a049;
|
||||
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
""")
|
||||
|
||||
license_text = (
|
||||
"本软件以MIT协议开源, 作者不对软件具备任何控制力, 使用软件者、传播软件导出的声音者自负全责. "
|
||||
"如不认可该条款, 则不能使用或引用软件包内任何代码和文件. 详见根目录LICENSE."
|
||||
)
|
||||
license_label = QLabel(license_text)
|
||||
license_label.setWordWrap(True)
|
||||
|
||||
self.GPT_model_label = QLabel("选择GPT模型:")
|
||||
self.GPT_model_input = QLineEdit()
|
||||
self.GPT_model_input.setPlaceholderText("拖拽或选择文件")
|
||||
self.GPT_model_input.setText(self.GPT_Path)
|
||||
self.GPT_model_input.setReadOnly(True)
|
||||
self.GPT_model_button = QPushButton("选择GPT模型文件")
|
||||
self.GPT_model_button.clicked.connect(self.select_GPT_model)
|
||||
|
||||
self.SoVITS_model_label = QLabel("选择SoVITS模型:")
|
||||
self.SoVITS_model_input = QLineEdit()
|
||||
self.SoVITS_model_input.setPlaceholderText("拖拽或选择文件")
|
||||
self.SoVITS_model_input.setText(self.SoVITS_Path)
|
||||
self.SoVITS_model_input.setReadOnly(True)
|
||||
self.SoVITS_model_button = QPushButton("选择SoVITS模型文件")
|
||||
self.SoVITS_model_button.clicked.connect(self.select_SoVITS_model)
|
||||
|
||||
self.ref_audio_label = QLabel("上传参考音频:")
|
||||
self.ref_audio_input = QLineEdit()
|
||||
self.ref_audio_input.setPlaceholderText("拖拽或选择文件")
|
||||
self.ref_audio_input.setReadOnly(True)
|
||||
self.ref_audio_button = QPushButton("选择音频文件")
|
||||
self.ref_audio_button.clicked.connect(self.select_ref_audio)
|
||||
|
||||
self.ref_text_label = QLabel("参考音频文本:")
|
||||
self.ref_text_input = QLineEdit()
|
||||
self.ref_text_input.setPlaceholderText("直接输入文字或上传文本")
|
||||
self.ref_text_button = QPushButton("上传文本")
|
||||
self.ref_text_button.clicked.connect(self.upload_ref_text)
|
||||
|
||||
self.ref_language_label = QLabel("参考音频语言:")
|
||||
self.ref_language_combobox = QComboBox()
|
||||
self.ref_language_combobox.addItems(["中文", "英文", "日文", "中英混合", "日英混合", "多语种混合"])
|
||||
self.ref_language_combobox.setCurrentText("多语种混合")
|
||||
|
||||
self.target_text_label = QLabel("合成目标文本:")
|
||||
self.target_text_input = QLineEdit()
|
||||
self.target_text_input.setPlaceholderText("直接输入文字或上传文本")
|
||||
self.target_text_button = QPushButton("上传文本")
|
||||
self.target_text_button.clicked.connect(self.upload_target_text)
|
||||
|
||||
self.target_language_label = QLabel("合成音频语言:")
|
||||
self.target_language_combobox = QComboBox()
|
||||
self.target_language_combobox.addItems(["中文", "英文", "日文", "中英混合", "日英混合", "多语种混合"])
|
||||
self.target_language_combobox.setCurrentText("多语种混合")
|
||||
|
||||
self.output_label = QLabel("输出音频路径:")
|
||||
self.output_input = QLineEdit()
|
||||
self.output_input.setPlaceholderText("拖拽或选择文件")
|
||||
self.output_input.setReadOnly(True)
|
||||
self.output_button = QPushButton("选择文件夹")
|
||||
self.output_button.clicked.connect(self.select_output_path)
|
||||
|
||||
self.output_text = QTextEdit()
|
||||
self.output_text.setReadOnly(True)
|
||||
|
||||
self.add_drag_drop_events(
|
||||
[
|
||||
self.GPT_model_input,
|
||||
self.SoVITS_model_input,
|
||||
self.ref_audio_input,
|
||||
self.ref_text_input,
|
||||
self.target_text_input,
|
||||
self.output_input,
|
||||
]
|
||||
)
|
||||
|
||||
self.synthesize_button = QPushButton("合成")
|
||||
self.synthesize_button.clicked.connect(self.synthesize)
|
||||
|
||||
self.clear_output_button = QPushButton("清空输出")
|
||||
self.clear_output_button.clicked.connect(self.clear_output)
|
||||
|
||||
self.status_bar = QStatusBar()
|
||||
|
||||
main_layout = QVBoxLayout()
|
||||
|
||||
input_layout = QGridLayout(self)
|
||||
input_layout.setSpacing(10)
|
||||
|
||||
input_layout.addWidget(license_label, 0, 0, 1, 3)
|
||||
|
||||
input_layout.addWidget(self.GPT_model_label, 1, 0)
|
||||
input_layout.addWidget(self.GPT_model_input, 2, 0, 1, 2)
|
||||
input_layout.addWidget(self.GPT_model_button, 2, 2)
|
||||
|
||||
input_layout.addWidget(self.SoVITS_model_label, 3, 0)
|
||||
input_layout.addWidget(self.SoVITS_model_input, 4, 0, 1, 2)
|
||||
input_layout.addWidget(self.SoVITS_model_button, 4, 2)
|
||||
|
||||
input_layout.addWidget(self.ref_audio_label, 5, 0)
|
||||
input_layout.addWidget(self.ref_audio_input, 6, 0, 1, 2)
|
||||
input_layout.addWidget(self.ref_audio_button, 6, 2)
|
||||
|
||||
input_layout.addWidget(self.ref_language_label, 7, 0)
|
||||
input_layout.addWidget(self.ref_language_combobox, 8, 0, 1, 1)
|
||||
input_layout.addWidget(self.ref_text_label, 9, 0)
|
||||
input_layout.addWidget(self.ref_text_input, 10, 0, 1, 2)
|
||||
input_layout.addWidget(self.ref_text_button, 10, 2)
|
||||
|
||||
input_layout.addWidget(self.target_language_label, 11, 0)
|
||||
input_layout.addWidget(self.target_language_combobox, 12, 0, 1, 1)
|
||||
input_layout.addWidget(self.target_text_label, 13, 0)
|
||||
input_layout.addWidget(self.target_text_input, 14, 0, 1, 2)
|
||||
input_layout.addWidget(self.target_text_button, 14, 2)
|
||||
|
||||
input_layout.addWidget(self.output_label, 15, 0)
|
||||
input_layout.addWidget(self.output_input, 16, 0, 1, 2)
|
||||
input_layout.addWidget(self.output_button, 16, 2)
|
||||
|
||||
main_layout.addLayout(input_layout)
|
||||
|
||||
output_layout = QVBoxLayout()
|
||||
output_layout.addWidget(self.output_text)
|
||||
main_layout.addLayout(output_layout)
|
||||
|
||||
main_layout.addWidget(self.synthesize_button)
|
||||
|
||||
main_layout.addWidget(self.clear_output_button)
|
||||
|
||||
main_layout.addWidget(self.status_bar)
|
||||
|
||||
self.central_widget = QWidget()
|
||||
self.central_widget.setLayout(main_layout)
|
||||
self.setCentralWidget(self.central_widget)
|
||||
|
||||
def dragEnterEvent(self, event):
|
||||
if event.mimeData().hasUrls():
|
||||
event.acceptProposedAction()
|
||||
|
||||
def dropEvent(self, event):
|
||||
if event.mimeData().hasUrls():
|
||||
file_paths = [url.toLocalFile() for url in event.mimeData().urls()]
|
||||
if len(file_paths) == 1:
|
||||
self.update_ref_audio(file_paths[0])
|
||||
else:
|
||||
self.update_ref_audio(", ".join(file_paths))
|
||||
|
||||
def add_drag_drop_events(self, widgets):
|
||||
for widget in widgets:
|
||||
widget.setAcceptDrops(True)
|
||||
widget.installEventFilter(self)
|
||||
|
||||
def eventFilter(self, obj, event):
|
||||
if event.type() in (QEvent.DragEnter, QEvent.Drop):
|
||||
mime_data = event.mimeData()
|
||||
if mime_data.hasUrls():
|
||||
event.acceptProposedAction()
|
||||
|
||||
return super().eventFilter(obj, event)
|
||||
|
||||
def select_GPT_model(self):
|
||||
file_path, _ = QFileDialog.getOpenFileName(self, "选择GPT模型文件", "", "GPT Files (*.ckpt)")
|
||||
if file_path:
|
||||
self.GPT_model_input.setText(file_path)
|
||||
|
||||
def select_SoVITS_model(self):
|
||||
file_path, _ = QFileDialog.getOpenFileName(self, "选择SoVITS模型文件", "", "SoVITS Files (*.pth)")
|
||||
if file_path:
|
||||
self.SoVITS_model_input.setText(file_path)
|
||||
|
||||
def select_ref_audio(self):
|
||||
file_path, _ = QFileDialog.getOpenFileName(self, "选择参考音频文件", "", "Audio Files (*.wav *.mp3)")
|
||||
if file_path:
|
||||
self.update_ref_audio(file_path)
|
||||
|
||||
def upload_ref_text(self):
|
||||
file_path, _ = QFileDialog.getOpenFileName(self, "选择文本文件", "", "Text Files (*.txt)")
|
||||
if file_path:
|
||||
with open(file_path, "r", encoding="utf-8") as file:
|
||||
content = file.read()
|
||||
self.ref_text_input.setText(content)
|
||||
|
||||
def upload_target_text(self):
|
||||
file_path, _ = QFileDialog.getOpenFileName(self, "选择文本文件", "", "Text Files (*.txt)")
|
||||
if file_path:
|
||||
with open(file_path, "r", encoding="utf-8") as file:
|
||||
content = file.read()
|
||||
self.target_text_input.setText(content)
|
||||
|
||||
def select_output_path(self):
|
||||
options = QFileDialog.Options()
|
||||
options |= QFileDialog.DontUseNativeDialog
|
||||
options |= QFileDialog.ShowDirsOnly
|
||||
|
||||
folder_dialog = QFileDialog()
|
||||
folder_dialog.setOptions(options)
|
||||
folder_dialog.setFileMode(QFileDialog.Directory)
|
||||
|
||||
if folder_dialog.exec_():
|
||||
folder_path = folder_dialog.selectedFiles()[0]
|
||||
self.output_input.setText(folder_path)
|
||||
|
||||
def update_ref_audio(self, file_path):
|
||||
self.ref_audio_input.setText(file_path)
|
||||
|
||||
def clear_output(self):
|
||||
self.output_text.clear()
|
||||
|
||||
def synthesize(self):
|
||||
GPT_model_path = self.GPT_model_input.text()
|
||||
SoVITS_model_path = self.SoVITS_model_input.text()
|
||||
ref_audio_path = self.ref_audio_input.text()
|
||||
language_combobox = self.ref_language_combobox.currentText()
|
||||
language_combobox = i18n(language_combobox)
|
||||
ref_text = self.ref_text_input.text()
|
||||
target_language_combobox = self.target_language_combobox.currentText()
|
||||
target_language_combobox = i18n(target_language_combobox)
|
||||
target_text = self.target_text_input.text()
|
||||
output_path = self.output_input.text()
|
||||
|
||||
if GPT_model_path != self.GPT_Path:
|
||||
change_gpt_weights(gpt_path=GPT_model_path)
|
||||
self.GPT_Path = GPT_model_path
|
||||
if SoVITS_model_path != self.SoVITS_Path:
|
||||
change_sovits_weights(sovits_path=SoVITS_model_path)
|
||||
self.SoVITS_Path = SoVITS_model_path
|
||||
|
||||
synthesis_result = get_tts_wav(
|
||||
ref_wav_path=ref_audio_path,
|
||||
prompt_text=ref_text,
|
||||
prompt_language=language_combobox,
|
||||
text=target_text,
|
||||
text_language=target_language_combobox,
|
||||
)
|
||||
|
||||
result_list = list(synthesis_result)
|
||||
|
||||
if result_list:
|
||||
last_sampling_rate, last_audio_data = result_list[-1]
|
||||
output_wav_path = os.path.join(output_path, "output.wav")
|
||||
sf.write(output_wav_path, last_audio_data, last_sampling_rate)
|
||||
|
||||
result = "Audio saved to " + output_wav_path
|
||||
|
||||
self.status_bar.showMessage("合成完成!输出路径:" + output_wav_path, 5000)
|
||||
self.output_text.append("处理结果:\n" + result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = QApplication(sys.argv)
|
||||
mainWin = GPTSoVITSGUI()
|
||||
mainWin.show()
|
||||
sys.exit(app.exec_())
|
||||
74
GPT_SoVITS/inference_loader.py
Normal file
74
GPT_SoVITS/inference_loader.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""Checkpoint loading helpers used by the inference service."""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from io import BytesIO
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
_HEAD_TO_VERSION = {
|
||||
b"00": ("v1", "v1", False),
|
||||
b"01": ("v2", "v2", False),
|
||||
b"02": ("v2", "v3", False),
|
||||
b"03": ("v2", "v3", True),
|
||||
b"04": ("v2", "v4", True),
|
||||
b"05": ("v2", "v2Pro", False),
|
||||
b"06": ("v2", "v2ProPlus", False),
|
||||
b"07": ("v2", "v5dev", True),
|
||||
b"08": ("v2", "v5turbo", True),
|
||||
}
|
||||
|
||||
_PRETRAINED_HASH_TO_VERSION = {
|
||||
"dc3c97e17592963677a4a1681f30c653": ("v2", "v2", False),
|
||||
"43797be674a37c1c83ee81081941ed0f": ("v2", "v3", False),
|
||||
"6642b37f3dbb1f76882b69937c95a5f3": ("v2", "v2", False),
|
||||
"4f26b9476d0c5033e04162c486074374": ("v2", "v4", False),
|
||||
"c7e9fce2223f3db685cdfa1e6368728a": ("v2", "v2Pro", False),
|
||||
"66b313e39455b57ab1b0bc0b239c9d0a": ("v2", "v2ProPlus", False),
|
||||
"c4ce1f839a0d271e41963f9fb16ade76": ("v2", "v5dev", False),
|
||||
"6bc5cb2a195cc8ec22b2e723cd4d6f47": ("v2", "v5turbo", False),
|
||||
}
|
||||
|
||||
|
||||
def get_hash_from_file(path: str) -> str:
|
||||
"""Return the MD5 of the first 8 KiB used for pretrained identification."""
|
||||
|
||||
with open(path, "rb") as stream:
|
||||
return hashlib.md5(stream.read(8192)).hexdigest()
|
||||
|
||||
|
||||
def get_sovits_version_from_path_fast(path: str):
|
||||
"""Identify a SoVITS checkpoint without loading its full state dict."""
|
||||
|
||||
pretrained_version = _PRETRAINED_HASH_TO_VERSION.get(get_hash_from_file(path))
|
||||
if pretrained_version is not None:
|
||||
return pretrained_version
|
||||
|
||||
with open(path, "rb") as stream:
|
||||
header = stream.read(2)
|
||||
if header != b"PK":
|
||||
try:
|
||||
return _HEAD_TO_VERSION[header]
|
||||
except KeyError as exc:
|
||||
raise ValueError(f"Unsupported SoVITS checkpoint header: {header!r}") from exc
|
||||
|
||||
size = os.path.getsize(path)
|
||||
if size < 82978 * 1024:
|
||||
return "v1", "v1", False
|
||||
if size < 700 * 1024 * 1024:
|
||||
return "v2", "v2", False
|
||||
return "v2", "v3", False
|
||||
|
||||
|
||||
def load_sovits_new(path: str):
|
||||
"""Load both legacy and ZIP-based checkpoints into a CPU state dict."""
|
||||
|
||||
with open(path, "rb") as stream:
|
||||
header = stream.read(2)
|
||||
if header != b"PK":
|
||||
payload = b"PK" + stream.read()
|
||||
buffer = BytesIO(payload)
|
||||
buffer.seek(0)
|
||||
return torch.load(buffer, map_location="cpu", weights_only=False)
|
||||
return torch.load(path, map_location="cpu", weights_only=False)
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,558 +0,0 @@
|
||||
"""
|
||||
按中英混合识别
|
||||
按日英混合识别
|
||||
多语种启动切分识别语种
|
||||
全部按中文识别
|
||||
全部按英文识别
|
||||
全部按日文识别
|
||||
"""
|
||||
from tools.portable_runtime import activate as activate_portable_runtime
|
||||
|
||||
activate_portable_runtime(change_cwd=True)
|
||||
|
||||
import psutil
|
||||
import os
|
||||
|
||||
def set_high_priority():
|
||||
"""把当前 Python 进程设为 HIGH_PRIORITY_CLASS"""
|
||||
if os.name != "nt":
|
||||
return # 仅 Windows 有效
|
||||
p = psutil.Process(os.getpid())
|
||||
try:
|
||||
p.nice(psutil.HIGH_PRIORITY_CLASS)
|
||||
print("已将进程优先级设为 High")
|
||||
except psutil.AccessDenied:
|
||||
print("权限不足,无法修改优先级(请用管理员运行)")
|
||||
set_high_priority()
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
|
||||
import torch
|
||||
|
||||
now_dir = os.getcwd()
|
||||
sys.path.append(now_dir)
|
||||
sys.path.append("%s/GPT_SoVITS" % (now_dir))
|
||||
|
||||
logging.getLogger("markdown_it").setLevel(logging.ERROR)
|
||||
logging.getLogger("urllib3").setLevel(logging.ERROR)
|
||||
logging.getLogger("httpcore").setLevel(logging.ERROR)
|
||||
logging.getLogger("httpx").setLevel(logging.ERROR)
|
||||
logging.getLogger("asyncio").setLevel(logging.ERROR)
|
||||
logging.getLogger("charset_normalizer").setLevel(logging.ERROR)
|
||||
logging.getLogger("torchaudio._extension").setLevel(logging.ERROR)
|
||||
|
||||
|
||||
infer_ttswebui = os.environ.get("infer_ttswebui", 9872)
|
||||
infer_ttswebui = int(infer_ttswebui)
|
||||
is_share = os.environ.get("is_share", "False")
|
||||
is_share = eval(is_share)
|
||||
if "_CUDA_VISIBLE_DEVICES" in os.environ:
|
||||
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["_CUDA_VISIBLE_DEVICES"]
|
||||
|
||||
is_half = eval(os.environ.get("is_half", "True")) and torch.cuda.is_available()
|
||||
gpt_path = os.environ.get("gpt_path", None)
|
||||
sovits_path = os.environ.get("sovits_path", None)
|
||||
cnhubert_base_path = os.environ.get("cnhubert_base_path", None)
|
||||
bert_path = os.environ.get("bert_path", None)
|
||||
version = model_version = os.environ.get("version", "v2")
|
||||
|
||||
import gradio as gr
|
||||
from TTS_infer_pack.text_segmentation_method import get_method
|
||||
from TTS_infer_pack.TTS import NO_PROMPT_ERROR, TTS, TTS_Config
|
||||
from module.models_v5 import V5_VERSIONS
|
||||
|
||||
from tools.acceleration import cuda_graph_available, flash_attention_available
|
||||
from tools.assets import css, js, top_html
|
||||
from tools.i18n.i18n import I18nAuto, scan_language_list
|
||||
|
||||
language = os.environ.get("language", "Auto")
|
||||
language = sys.argv[-1] if sys.argv[-1] in scan_language_list() else language
|
||||
i18n = I18nAuto(language=language)
|
||||
|
||||
|
||||
# os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' # 确保直接启动推理UI时也能够设置。
|
||||
|
||||
if torch.cuda.is_available():
|
||||
device = "cuda"
|
||||
# elif torch.backends.mps.is_available():
|
||||
# device = "mps"
|
||||
else:
|
||||
device = "cpu"
|
||||
|
||||
accel_dtype = torch.float16 if is_half else torch.float32
|
||||
graph_available = cuda_graph_available(device)
|
||||
flash_attn_supported = flash_attention_available(device, accel_dtype)
|
||||
|
||||
# is_half = False
|
||||
# device = "cpu"
|
||||
|
||||
dict_language_v1 = {
|
||||
i18n("中文"): "all_zh", # 全部按中文识别
|
||||
i18n("英文"): "en", # 全部按英文识别#######不变
|
||||
i18n("日文"): "all_ja", # 全部按日文识别
|
||||
i18n("中英混合"): "zh", # 按中英混合识别####不变
|
||||
i18n("日英混合"): "ja", # 按日英混合识别####不变
|
||||
i18n("多语种混合"): "auto", # 多语种启动切分识别语种
|
||||
}
|
||||
dict_language_v2 = {
|
||||
i18n("中文"): "all_zh", # 全部按中文识别
|
||||
i18n("英文"): "en", # 全部按英文识别#######不变
|
||||
i18n("日文"): "all_ja", # 全部按日文识别
|
||||
i18n("粤语"): "all_yue", # 全部按中文识别
|
||||
i18n("韩文"): "all_ko", # 全部按韩文识别
|
||||
i18n("中英混合"): "zh", # 按中英混合识别####不变
|
||||
i18n("日英混合"): "ja", # 按日英混合识别####不变
|
||||
i18n("粤英混合"): "yue", # 按粤英混合识别####不变
|
||||
i18n("韩英混合"): "ko", # 按韩英混合识别####不变
|
||||
i18n("多语种混合"): "auto", # 多语种启动切分识别语种
|
||||
i18n("多语种混合(粤语)"): "auto_yue", # 多语种启动切分识别语种
|
||||
}
|
||||
dict_language = dict_language_v1 if version == "v1" else dict_language_v2
|
||||
|
||||
cut_method = {
|
||||
i18n("不切"): "cut0",
|
||||
i18n("凑四句一切"): "cut1",
|
||||
i18n("凑50字一切"): "cut2",
|
||||
i18n("按中文句号。切"): "cut3",
|
||||
i18n("按英文句号.切"): "cut4",
|
||||
i18n("按标点符号切"): "cut5",
|
||||
}
|
||||
|
||||
from config import change_choices, get_weights_names, name2gpt_path, name2sovits_path
|
||||
|
||||
SoVITS_names, GPT_names = get_weights_names()
|
||||
from config import pretrained_sovits_name
|
||||
|
||||
tts_config = TTS_Config("GPT_SoVITS/configs/tts_infer.yaml")
|
||||
tts_config.device = device
|
||||
tts_config.is_half = is_half
|
||||
# tts_config.version = version
|
||||
tts_config.update_version(version)
|
||||
if gpt_path is not None:
|
||||
if "!" in gpt_path or "!" in gpt_path:
|
||||
gpt_path = name2gpt_path[gpt_path]
|
||||
tts_config.t2s_weights_path = gpt_path
|
||||
if sovits_path is not None:
|
||||
if "!" in sovits_path or "!" in sovits_path:
|
||||
sovits_path = name2sovits_path[sovits_path]
|
||||
tts_config.vits_weights_path = sovits_path
|
||||
if cnhubert_base_path is not None:
|
||||
tts_config.cnhuhbert_base_path = cnhubert_base_path
|
||||
if bert_path is not None:
|
||||
tts_config.bert_base_path = bert_path
|
||||
|
||||
print(tts_config)
|
||||
tts_pipeline = TTS(tts_config)
|
||||
gpt_path = tts_config.t2s_weights_path
|
||||
sovits_path = tts_config.vits_weights_path
|
||||
version = tts_config.version
|
||||
|
||||
|
||||
def inference(
|
||||
text,
|
||||
text_lang,
|
||||
ref_audio_path,
|
||||
aux_ref_audio_paths,
|
||||
prompt_text,
|
||||
prompt_lang,
|
||||
top_k,
|
||||
top_p,
|
||||
temperature,
|
||||
text_split_method,
|
||||
batch_size,
|
||||
speed_factor,
|
||||
ref_text_free,
|
||||
split_bucket,
|
||||
fragment_interval,
|
||||
seed,
|
||||
keep_random,
|
||||
use_cuda_graph,
|
||||
use_flash_attention,
|
||||
repetition_penalty,
|
||||
sample_steps=None,
|
||||
super_sampling=False,
|
||||
cfg_rate=None,
|
||||
):
|
||||
if sample_steps is None:
|
||||
sample_steps = 4 if tts_pipeline.configs.version == "v5turbo" else 32
|
||||
if cfg_rate is None:
|
||||
cfg_rate = 1.30 if tts_pipeline.configs.version == "v5dev" else 0.0
|
||||
sample_steps, cfg_rate = int(sample_steps), float(cfg_rate)
|
||||
seed = -1 if keep_random else seed
|
||||
actual_seed = seed if seed not in [-1, "", None] else random.randint(0, 2**32 - 1)
|
||||
inputs = {
|
||||
"text": text,
|
||||
"text_lang": dict_language[text_lang],
|
||||
"ref_audio_path": ref_audio_path,
|
||||
"aux_ref_audio_paths": [item.name for item in aux_ref_audio_paths] if aux_ref_audio_paths is not None else [],
|
||||
"prompt_text": prompt_text if not ref_text_free else "",
|
||||
"prompt_lang": dict_language[prompt_lang],
|
||||
"top_k": top_k,
|
||||
"top_p": top_p,
|
||||
"temperature": temperature,
|
||||
"text_split_method": cut_method[text_split_method],
|
||||
"batch_size": int(batch_size),
|
||||
"speed_factor": float(speed_factor),
|
||||
"split_bucket": split_bucket,
|
||||
"return_fragment": False,
|
||||
"fragment_interval": fragment_interval,
|
||||
"seed": actual_seed,
|
||||
"parallel_infer": True,
|
||||
"use_cuda_graph": use_cuda_graph,
|
||||
"use_flash_attention": use_flash_attention,
|
||||
"repetition_penalty": repetition_penalty,
|
||||
"sample_steps": int(sample_steps),
|
||||
"cfg_rate": float(cfg_rate),
|
||||
"super_sampling": super_sampling,
|
||||
}
|
||||
try:
|
||||
for item in tts_pipeline.run(inputs):
|
||||
yield item, actual_seed
|
||||
except NO_PROMPT_ERROR:
|
||||
gr.Warning(i18n("V3不支持无参考文本模式,请填写参考文本!"))
|
||||
|
||||
|
||||
def custom_sort_key(s):
|
||||
# 使用正则表达式提取字符串中的数字部分和非数字部分
|
||||
parts = re.split("(\d+)", s)
|
||||
# 将数字部分转换为整数,非数字部分保持不变
|
||||
parts = [int(part) if part.isdigit() else part for part in parts]
|
||||
return parts
|
||||
|
||||
|
||||
if os.path.exists("./weight.json"):
|
||||
pass
|
||||
else:
|
||||
with open("./weight.json", "w", encoding="utf-8") as file:
|
||||
json.dump({"GPT": {}, "SoVITS": {}}, file)
|
||||
|
||||
with open("./weight.json", "r", encoding="utf-8") as file:
|
||||
weight_data = file.read()
|
||||
weight_data = json.loads(weight_data)
|
||||
gpt_path = os.environ.get("gpt_path", weight_data.get("GPT", {}).get(version, GPT_names[-1]))
|
||||
sovits_path = os.environ.get("sovits_path", weight_data.get("SoVITS", {}).get(version, SoVITS_names[0]))
|
||||
if isinstance(gpt_path, list):
|
||||
gpt_path = gpt_path[0]
|
||||
if isinstance(sovits_path, list):
|
||||
sovits_path = sovits_path[0]
|
||||
|
||||
from process_ckpt import get_sovits_version_from_path_fast
|
||||
|
||||
v3v4set = {"v3", "v4"} | V5_VERSIONS
|
||||
|
||||
|
||||
def change_sovits_weights(sovits_path, prompt_language=None, text_language=None):
|
||||
if "!" in sovits_path or "!" in sovits_path:
|
||||
sovits_path = name2sovits_path[sovits_path]
|
||||
global version, model_version, dict_language, if_lora_v3
|
||||
version, model_version, if_lora_v3 = get_sovits_version_from_path_fast(sovits_path)
|
||||
# print(sovits_path,version, model_version, if_lora_v3)
|
||||
path_sovits = pretrained_sovits_name[model_version]
|
||||
is_exist = os.path.exists(path_sovits)
|
||||
if if_lora_v3 == True and is_exist == False:
|
||||
info = path_sovits + "SoVITS %s" % model_version + i18n("底模缺失,无法加载相应 LoRA 权重")
|
||||
gr.Warning(info)
|
||||
raise FileExistsError(info)
|
||||
dict_language = dict_language_v1 if version == "v1" else dict_language_v2
|
||||
prompt_text_update = prompt_language_update = text_update = text_language_update = {"__type__": "update"}
|
||||
visible_sample_steps = model_version in v3v4set
|
||||
visible_inp_refs = not visible_sample_steps
|
||||
if prompt_language is not None and text_language is not None:
|
||||
if prompt_language in list(dict_language.keys()):
|
||||
prompt_text_update, prompt_language_update = (
|
||||
{"__type__": "update"},
|
||||
{"__type__": "update", "value": prompt_language},
|
||||
)
|
||||
else:
|
||||
prompt_text_update = {"__type__": "update", "value": ""}
|
||||
prompt_language_update = {"__type__": "update", "value": i18n("中文")}
|
||||
if text_language in list(dict_language.keys()):
|
||||
text_update, text_language_update = {"__type__": "update"}, {"__type__": "update", "value": text_language}
|
||||
else:
|
||||
text_update = {"__type__": "update", "value": ""}
|
||||
text_language_update = {"__type__": "update", "value": i18n("中文")}
|
||||
if model_version in v3v4set:
|
||||
visible_sample_steps = True
|
||||
visible_inp_refs = False
|
||||
else:
|
||||
visible_sample_steps = False
|
||||
visible_inp_refs = True
|
||||
yield (
|
||||
{"__type__": "update", "choices": list(dict_language.keys())},
|
||||
{"__type__": "update", "choices": list(dict_language.keys())},
|
||||
prompt_text_update,
|
||||
prompt_language_update,
|
||||
text_update,
|
||||
text_language_update,
|
||||
{"__type__": "update", "interactive": visible_sample_steps, "value": (4 if model_version == "v5turbo" else 32)},
|
||||
{"__type__": "update", "visible": visible_inp_refs},
|
||||
{"__type__": "update", "interactive": True if model_version not in v3v4set else False},
|
||||
{"__type__": "update", "value": i18n("模型加载中,请等待"), "interactive": False},
|
||||
{"__type__": "update", "visible": model_version in V5_VERSIONS, "value": (1.30 if model_version == "v5dev" else 0.0)},
|
||||
)
|
||||
|
||||
tts_pipeline.init_vits_weights(sovits_path)
|
||||
yield (
|
||||
{"__type__": "update", "choices": list(dict_language.keys())},
|
||||
{"__type__": "update", "choices": list(dict_language.keys())},
|
||||
prompt_text_update,
|
||||
prompt_language_update,
|
||||
text_update,
|
||||
text_language_update,
|
||||
{"__type__": "update", "interactive": visible_sample_steps, "value": (4 if model_version == "v5turbo" else 32)},
|
||||
{"__type__": "update", "visible": visible_inp_refs},
|
||||
{"__type__": "update", "interactive": True if model_version not in v3v4set else False},
|
||||
{"__type__": "update", "value": i18n("合成语音"), "interactive": True},
|
||||
{"__type__": "update", "visible": model_version in V5_VERSIONS, "value": (1.30 if model_version == "v5dev" else 0.0)},
|
||||
)
|
||||
with open("./weight.json") as f:
|
||||
data = f.read()
|
||||
data = json.loads(data)
|
||||
data["SoVITS"][version] = sovits_path
|
||||
with open("./weight.json", "w") as f:
|
||||
f.write(json.dumps(data))
|
||||
|
||||
|
||||
def change_gpt_weights(gpt_path):
|
||||
if "!" in gpt_path or "!" in gpt_path:
|
||||
gpt_path = name2gpt_path[gpt_path]
|
||||
tts_pipeline.init_t2s_weights(gpt_path)
|
||||
|
||||
|
||||
with gr.Blocks(title="GPT-SoVITS WebUI", analytics_enabled=False, js=js, css=css) as app:
|
||||
gr.HTML(
|
||||
top_html.format(
|
||||
i18n("本软件以MIT协议开源, 作者不对软件具备任何控制力, 使用软件者、传播软件导出的声音者自负全责.")
|
||||
+ i18n("如不认可该条款, 则不能使用或引用软件包内任何代码和文件. 详见根目录LICENSE.")
|
||||
),
|
||||
elem_classes="markdown",
|
||||
)
|
||||
|
||||
with gr.Column():
|
||||
# with gr.Group():
|
||||
gr.Markdown(value=i18n("模型切换"))
|
||||
with gr.Row():
|
||||
GPT_dropdown = gr.Dropdown(
|
||||
label=i18n("GPT模型列表"),
|
||||
choices=sorted(GPT_names, key=custom_sort_key),
|
||||
value=next((name for name, path in name2gpt_path.items() if path == gpt_path), gpt_path),
|
||||
interactive=True,
|
||||
)
|
||||
SoVITS_dropdown = gr.Dropdown(
|
||||
label=i18n("SoVITS模型列表"),
|
||||
choices=sorted(SoVITS_names, key=custom_sort_key),
|
||||
value=next((name for name, path in name2sovits_path.items() if path == sovits_path), sovits_path),
|
||||
interactive=True,
|
||||
)
|
||||
refresh_button = gr.Button(i18n("刷新模型路径"), variant="primary")
|
||||
refresh_button.click(fn=change_choices, inputs=[], outputs=[SoVITS_dropdown, GPT_dropdown])
|
||||
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
gr.Markdown(value=i18n("*请上传并填写参考信息"))
|
||||
with gr.Row():
|
||||
inp_ref = gr.Audio(label=i18n("主参考音频(请上传3~10秒内参考音频,超过会报错!)"), type="filepath")
|
||||
inp_refs = gr.File(
|
||||
label=i18n("辅参考音频(可选多个,或不选)"),
|
||||
file_count="multiple",
|
||||
visible=True if model_version != "v3" else False,
|
||||
)
|
||||
prompt_text = gr.Textbox(label=i18n("主参考音频的文本"), value="", lines=2)
|
||||
with gr.Row():
|
||||
prompt_language = gr.Dropdown(
|
||||
label=i18n("主参考音频的语种"), choices=list(dict_language.keys()), value=i18n("中文"), scale=1
|
||||
)
|
||||
cfg_rate = gr.Slider(
|
||||
minimum=0, maximum=2, step=0.05,
|
||||
value=(1.30 if model_version == "v5dev" else 0.0), label="CFG",
|
||||
visible=model_version in V5_VERSIONS, interactive=True, scale=1,
|
||||
)
|
||||
with gr.Column():
|
||||
ref_text_free = gr.Checkbox(
|
||||
label=i18n("开启无参考文本模式。不填参考文本亦相当于开启。"),
|
||||
value=False,
|
||||
interactive=True if model_version != "v3" else False,
|
||||
show_label=True,
|
||||
)
|
||||
gr.Markdown(
|
||||
i18n("使用无参考文本模式时建议使用微调的GPT")
|
||||
+ "<br>"
|
||||
+ i18n("听不清参考音频说的啥(不晓得写啥)可以开。开启后无视填写的参考文本。")
|
||||
)
|
||||
|
||||
with gr.Column():
|
||||
gr.Markdown(value=i18n("*请填写需要合成的目标文本和语种模式"))
|
||||
text = gr.Textbox(label=i18n("需要合成的文本"), value="", lines=20, max_lines=20)
|
||||
text_language = gr.Dropdown(
|
||||
label=i18n("需要合成的文本的语种"), choices=list(dict_language.keys()), value=i18n("中文")
|
||||
)
|
||||
|
||||
with gr.Group():
|
||||
gr.Markdown(value=i18n("推理设置"))
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
with gr.Row():
|
||||
batch_size = gr.Slider(
|
||||
minimum=1, maximum=200, step=1, label=i18n("batch_size"),
|
||||
value=1 if model_version in V5_VERSIONS else 20, interactive=True
|
||||
)
|
||||
sample_steps = gr.Radio(
|
||||
label="Euler steps (V3/V4/V5)", value=(4 if model_version == "v5turbo" else 32), choices=[4, 8, 16, 32], visible=True
|
||||
)
|
||||
with gr.Row():
|
||||
fragment_interval = gr.Slider(
|
||||
minimum=0.01, maximum=1, step=0.01, label=i18n("分段间隔(秒)"), value=0.3, interactive=True
|
||||
)
|
||||
speed_factor = gr.Slider(
|
||||
minimum=0.6, maximum=1.65, step=0.05, label="语速", value=1.0, interactive=True
|
||||
)
|
||||
with gr.Row():
|
||||
top_k = gr.Slider(minimum=1, maximum=100, step=1, label=i18n("top_k"), value=15, interactive=True)
|
||||
top_p = gr.Slider(minimum=0, maximum=1, step=0.05, label=i18n("top_p"), value=1, interactive=True)
|
||||
with gr.Row():
|
||||
temperature = gr.Slider(
|
||||
minimum=0, maximum=1, step=0.05, label=i18n("temperature"), value=1, interactive=True
|
||||
)
|
||||
repetition_penalty = gr.Slider(
|
||||
minimum=0, maximum=2, step=0.05, label=i18n("重复惩罚"), value=1.35, interactive=True
|
||||
)
|
||||
|
||||
with gr.Column():
|
||||
with gr.Row():
|
||||
how_to_cut = gr.Dropdown(
|
||||
label=i18n("怎么切"),
|
||||
choices=[
|
||||
i18n("不切"),
|
||||
i18n("凑四句一切"),
|
||||
i18n("凑50字一切"),
|
||||
i18n("按中文句号。切"),
|
||||
i18n("按英文句号.切"),
|
||||
i18n("按标点符号切"),
|
||||
],
|
||||
value=i18n("凑四句一切"),
|
||||
interactive=True,
|
||||
scale=1,
|
||||
)
|
||||
super_sampling = gr.Checkbox(
|
||||
label=i18n("音频超采样(仅对V3生效))"), value=False, interactive=True, show_label=True
|
||||
)
|
||||
|
||||
with gr.Row():
|
||||
use_cuda_graph = gr.Checkbox(
|
||||
label="CUDA Graph", value=graph_available, visible=graph_available, interactive=graph_available
|
||||
)
|
||||
use_flash_attention = gr.Checkbox(
|
||||
label="flash_attn加速", value=flash_attn_supported, visible=flash_attn_supported,
|
||||
interactive=flash_attn_supported
|
||||
)
|
||||
split_bucket = gr.Checkbox(
|
||||
label=i18n("数据分桶(并行推理时会降低一点计算量)"),
|
||||
value=True,
|
||||
interactive=True,
|
||||
show_label=True,
|
||||
)
|
||||
|
||||
with gr.Row():
|
||||
seed = gr.Number(label=i18n("随机种子"), value=-1)
|
||||
keep_random = gr.Checkbox(label=i18n("保持随机"), value=True, interactive=True, show_label=True)
|
||||
|
||||
output = gr.Audio(label=i18n("输出的语音"))
|
||||
with gr.Row():
|
||||
inference_button = gr.Button(i18n("合成语音"), variant="primary")
|
||||
stop_infer = gr.Button(i18n("终止合成"), variant="primary")
|
||||
|
||||
inference_button.click(
|
||||
inference,
|
||||
[
|
||||
text,
|
||||
text_language,
|
||||
inp_ref,
|
||||
inp_refs,
|
||||
prompt_text,
|
||||
prompt_language,
|
||||
top_k,
|
||||
top_p,
|
||||
temperature,
|
||||
how_to_cut,
|
||||
batch_size,
|
||||
speed_factor,
|
||||
ref_text_free,
|
||||
split_bucket,
|
||||
fragment_interval,
|
||||
seed,
|
||||
keep_random,
|
||||
use_cuda_graph,
|
||||
use_flash_attention,
|
||||
repetition_penalty,
|
||||
sample_steps,
|
||||
super_sampling,
|
||||
cfg_rate,
|
||||
],
|
||||
[output, seed],
|
||||
)
|
||||
stop_infer.click(tts_pipeline.stop, [], [])
|
||||
SoVITS_dropdown.change(
|
||||
change_sovits_weights,
|
||||
[SoVITS_dropdown, prompt_language, text_language],
|
||||
[
|
||||
prompt_language,
|
||||
text_language,
|
||||
prompt_text,
|
||||
prompt_language,
|
||||
text,
|
||||
text_language,
|
||||
sample_steps,
|
||||
inp_refs,
|
||||
ref_text_free,
|
||||
inference_button,
|
||||
cfg_rate,
|
||||
],
|
||||
) #
|
||||
GPT_dropdown.change(change_gpt_weights, [GPT_dropdown], [])
|
||||
|
||||
with gr.Group():
|
||||
gr.Markdown(
|
||||
value=i18n(
|
||||
"文本切分工具。太长的文本合成出来效果不一定好,所以太长建议先切。合成会根据文本的换行分开合成再拼起来。"
|
||||
)
|
||||
)
|
||||
with gr.Row():
|
||||
text_inp = gr.Textbox(label=i18n("需要合成的切分前文本"), value="", lines=4)
|
||||
with gr.Column():
|
||||
_how_to_cut = gr.Radio(
|
||||
label=i18n("怎么切"),
|
||||
choices=[
|
||||
i18n("不切"),
|
||||
i18n("凑四句一切"),
|
||||
i18n("凑50字一切"),
|
||||
i18n("按中文句号。切"),
|
||||
i18n("按英文句号.切"),
|
||||
i18n("按标点符号切"),
|
||||
],
|
||||
value=i18n("凑四句一切"),
|
||||
interactive=True,
|
||||
)
|
||||
cut_text = gr.Button(i18n("切分"), variant="primary")
|
||||
|
||||
def to_cut(text_inp, how_to_cut):
|
||||
if len(text_inp.strip()) == 0 or text_inp == []:
|
||||
return ""
|
||||
method = get_method(cut_method[how_to_cut])
|
||||
return method(text_inp)
|
||||
|
||||
text_opt = gr.Textbox(label=i18n("切分后文本"), value="", lines=4)
|
||||
cut_text.click(to_cut, [text_inp, _how_to_cut], [text_opt])
|
||||
gr.Markdown(value=i18n("后续将支持转音素、手工修改音素、语音合成分步执行。"))
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.queue().launch( # concurrency_count=511, max_size=1022
|
||||
server_name="0.0.0.0",
|
||||
inbrowser=True,
|
||||
share=is_share,
|
||||
server_port=infer_ttswebui,
|
||||
# quiet=True,
|
||||
)
|
||||
@ -17,8 +17,6 @@ class Encoder(nn.Module):
|
||||
kernel_size=1,
|
||||
p_dropout=0.0,
|
||||
window_size=4,
|
||||
isflow=False,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
self.hidden_channels = hidden_channels
|
||||
@ -55,24 +53,12 @@ class Encoder(nn.Module):
|
||||
)
|
||||
)
|
||||
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
||||
if isflow:
|
||||
cond_layer = torch.nn.Conv1d(kwargs["gin_channels"], 2 * hidden_channels * n_layers, 1)
|
||||
self.cond_pre = torch.nn.Conv1d(hidden_channels, 2 * hidden_channels, 1)
|
||||
self.cond_layer = weight_norm_modules(cond_layer, name="weight")
|
||||
self.gin_channels = kwargs["gin_channels"]
|
||||
|
||||
def forward(self, x, x_mask, g=None):
|
||||
def forward(self, x, x_mask):
|
||||
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
||||
x = x * x_mask
|
||||
if g is not None:
|
||||
g = self.cond_layer(g)
|
||||
|
||||
for i in range(self.n_layers):
|
||||
if g is not None:
|
||||
x = self.cond_pre(x)
|
||||
cond_offset = i * 2 * self.hidden_channels
|
||||
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
|
||||
x = commons.fused_add_tanh_sigmoid_multiply(x, g_l, torch.IntTensor([self.hidden_channels]))
|
||||
y = self.attn_layers[i](x, x, attn_mask)
|
||||
y = self.drop(y)
|
||||
x = self.norm_layers_1[i](x + y)
|
||||
@ -84,88 +70,6 @@ class Encoder(nn.Module):
|
||||
return x
|
||||
|
||||
|
||||
class Decoder(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_channels,
|
||||
filter_channels,
|
||||
n_heads,
|
||||
n_layers,
|
||||
kernel_size=1,
|
||||
p_dropout=0.0,
|
||||
proximal_bias=False,
|
||||
proximal_init=True,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
self.hidden_channels = hidden_channels
|
||||
self.filter_channels = filter_channels
|
||||
self.n_heads = n_heads
|
||||
self.n_layers = n_layers
|
||||
self.kernel_size = kernel_size
|
||||
self.p_dropout = p_dropout
|
||||
self.proximal_bias = proximal_bias
|
||||
self.proximal_init = proximal_init
|
||||
|
||||
self.drop = nn.Dropout(p_dropout)
|
||||
self.self_attn_layers = nn.ModuleList()
|
||||
self.norm_layers_0 = nn.ModuleList()
|
||||
self.encdec_attn_layers = nn.ModuleList()
|
||||
self.norm_layers_1 = nn.ModuleList()
|
||||
self.ffn_layers = nn.ModuleList()
|
||||
self.norm_layers_2 = nn.ModuleList()
|
||||
for i in range(self.n_layers):
|
||||
self.self_attn_layers.append(
|
||||
MultiHeadAttention(
|
||||
hidden_channels,
|
||||
hidden_channels,
|
||||
n_heads,
|
||||
p_dropout=p_dropout,
|
||||
proximal_bias=proximal_bias,
|
||||
proximal_init=proximal_init,
|
||||
)
|
||||
)
|
||||
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
||||
self.encdec_attn_layers.append(
|
||||
MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout)
|
||||
)
|
||||
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
||||
self.ffn_layers.append(
|
||||
FFN(
|
||||
hidden_channels,
|
||||
hidden_channels,
|
||||
filter_channels,
|
||||
kernel_size,
|
||||
p_dropout=p_dropout,
|
||||
causal=True,
|
||||
)
|
||||
)
|
||||
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
||||
|
||||
def forward(self, x, x_mask, h, h_mask):
|
||||
"""
|
||||
x: decoder input
|
||||
h: encoder output
|
||||
"""
|
||||
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
|
||||
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
||||
x = x * x_mask
|
||||
for i in range(self.n_layers):
|
||||
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
||||
y = self.drop(y)
|
||||
x = self.norm_layers_0[i](x + y)
|
||||
|
||||
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
||||
y = self.drop(y)
|
||||
x = self.norm_layers_1[i](x + y)
|
||||
|
||||
y = self.ffn_layers[i](x, x_mask)
|
||||
y = self.drop(y)
|
||||
x = self.norm_layers_2[i](x + y)
|
||||
x = x * x_mask
|
||||
return x
|
||||
|
||||
|
||||
class MultiHeadAttention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
@ -174,10 +78,6 @@ class MultiHeadAttention(nn.Module):
|
||||
n_heads,
|
||||
p_dropout=0.0,
|
||||
window_size=None,
|
||||
heads_share=True,
|
||||
block_length=None,
|
||||
proximal_bias=False,
|
||||
proximal_init=False,
|
||||
):
|
||||
super().__init__()
|
||||
assert channels % n_heads == 0
|
||||
@ -187,10 +87,6 @@ class MultiHeadAttention(nn.Module):
|
||||
self.n_heads = n_heads
|
||||
self.p_dropout = p_dropout
|
||||
self.window_size = window_size
|
||||
self.heads_share = heads_share
|
||||
self.block_length = block_length
|
||||
self.proximal_bias = proximal_bias
|
||||
self.proximal_init = proximal_init
|
||||
self.attn = None
|
||||
|
||||
self.k_channels = channels // n_heads
|
||||
@ -201,18 +97,13 @@ class MultiHeadAttention(nn.Module):
|
||||
self.drop = nn.Dropout(p_dropout)
|
||||
|
||||
if window_size is not None:
|
||||
n_heads_rel = 1 if heads_share else n_heads
|
||||
rel_stddev = self.k_channels**-0.5
|
||||
self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
||||
self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
||||
self.emb_rel_k = nn.Parameter(torch.randn(1, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
||||
self.emb_rel_v = nn.Parameter(torch.randn(1, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
||||
|
||||
nn.init.xavier_uniform_(self.conv_q.weight)
|
||||
nn.init.xavier_uniform_(self.conv_k.weight)
|
||||
nn.init.xavier_uniform_(self.conv_v.weight)
|
||||
if proximal_init:
|
||||
with torch.no_grad():
|
||||
self.conv_k.weight.copy_(self.conv_q.weight)
|
||||
self.conv_k.bias.copy_(self.conv_q.bias)
|
||||
|
||||
def forward(self, x, c, attn_mask=None):
|
||||
q = self.conv_q(x)
|
||||
@ -238,15 +129,8 @@ class MultiHeadAttention(nn.Module):
|
||||
rel_logits = self._matmul_with_relative_keys(query / math.sqrt(self.k_channels), key_relative_embeddings)
|
||||
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
||||
scores = scores + scores_local
|
||||
if self.proximal_bias:
|
||||
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
||||
scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
|
||||
if mask is not None:
|
||||
scores = scores.masked_fill(mask == 0, -1e4)
|
||||
if self.block_length is not None:
|
||||
assert t_s == t_t, "Local attention is only available for self-attention."
|
||||
block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
|
||||
scores = scores.masked_fill(block_mask == 0, -1e4)
|
||||
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
|
||||
p_attn = self.drop(p_attn)
|
||||
output = torch.matmul(p_attn, value)
|
||||
@ -322,18 +206,6 @@ class MultiHeadAttention(nn.Module):
|
||||
x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
|
||||
return x_final
|
||||
|
||||
def _attention_bias_proximal(self, length):
|
||||
"""Bias for self-attention to encourage attention to close positions.
|
||||
Args:
|
||||
length: an integer scalar.
|
||||
Returns:
|
||||
a Tensor with shape [1, 1, length, length]
|
||||
"""
|
||||
r = torch.arange(length, dtype=torch.float32)
|
||||
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
||||
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
||||
|
||||
|
||||
class FFN(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
@ -390,270 +262,3 @@ class FFN(nn.Module):
|
||||
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
||||
x = F.pad(x, commons.convert_pad_shape(padding))
|
||||
return x
|
||||
|
||||
|
||||
import torch.nn as nn
|
||||
from torch.nn.utils import remove_weight_norm, weight_norm
|
||||
|
||||
|
||||
class Depthwise_Separable_Conv1D(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride=1,
|
||||
padding=0,
|
||||
dilation=1,
|
||||
bias=True,
|
||||
padding_mode="zeros", # TODO: refine this type
|
||||
device=None,
|
||||
dtype=None,
|
||||
):
|
||||
super().__init__()
|
||||
self.depth_conv = nn.Conv1d(
|
||||
in_channels=in_channels,
|
||||
out_channels=in_channels,
|
||||
kernel_size=kernel_size,
|
||||
groups=in_channels,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=bias,
|
||||
padding_mode=padding_mode,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
self.point_conv = nn.Conv1d(
|
||||
in_channels=in_channels,
|
||||
out_channels=out_channels,
|
||||
kernel_size=1,
|
||||
bias=bias,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
|
||||
def forward(self, input):
|
||||
return self.point_conv(self.depth_conv(input))
|
||||
|
||||
def weight_norm(self):
|
||||
self.depth_conv = weight_norm(self.depth_conv, name="weight")
|
||||
self.point_conv = weight_norm(self.point_conv, name="weight")
|
||||
|
||||
def remove_weight_norm(self):
|
||||
self.depth_conv = remove_weight_norm(self.depth_conv, name="weight")
|
||||
self.point_conv = remove_weight_norm(self.point_conv, name="weight")
|
||||
|
||||
|
||||
class Depthwise_Separable_TransposeConv1D(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride=1,
|
||||
padding=0,
|
||||
output_padding=0,
|
||||
bias=True,
|
||||
dilation=1,
|
||||
padding_mode="zeros", # TODO: refine this type
|
||||
device=None,
|
||||
dtype=None,
|
||||
):
|
||||
super().__init__()
|
||||
self.depth_conv = nn.ConvTranspose1d(
|
||||
in_channels=in_channels,
|
||||
out_channels=in_channels,
|
||||
kernel_size=kernel_size,
|
||||
groups=in_channels,
|
||||
stride=stride,
|
||||
output_padding=output_padding,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=bias,
|
||||
padding_mode=padding_mode,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
self.point_conv = nn.Conv1d(
|
||||
in_channels=in_channels,
|
||||
out_channels=out_channels,
|
||||
kernel_size=1,
|
||||
bias=bias,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
|
||||
def forward(self, input):
|
||||
return self.point_conv(self.depth_conv(input))
|
||||
|
||||
def weight_norm(self):
|
||||
self.depth_conv = weight_norm(self.depth_conv, name="weight")
|
||||
self.point_conv = weight_norm(self.point_conv, name="weight")
|
||||
|
||||
def remove_weight_norm(self):
|
||||
remove_weight_norm(self.depth_conv, name="weight")
|
||||
remove_weight_norm(self.point_conv, name="weight")
|
||||
|
||||
|
||||
def weight_norm_modules(module, name="weight", dim=0):
|
||||
if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(module, Depthwise_Separable_TransposeConv1D):
|
||||
module.weight_norm()
|
||||
return module
|
||||
else:
|
||||
return weight_norm(module, name, dim)
|
||||
|
||||
|
||||
def remove_weight_norm_modules(module, name="weight"):
|
||||
if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(module, Depthwise_Separable_TransposeConv1D):
|
||||
module.remove_weight_norm()
|
||||
else:
|
||||
remove_weight_norm(module, name)
|
||||
|
||||
|
||||
class FFT(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_channels,
|
||||
filter_channels,
|
||||
n_heads,
|
||||
n_layers=1,
|
||||
kernel_size=1,
|
||||
p_dropout=0.0,
|
||||
proximal_bias=False,
|
||||
proximal_init=True,
|
||||
isflow=False,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
self.hidden_channels = hidden_channels
|
||||
self.filter_channels = filter_channels
|
||||
self.n_heads = n_heads
|
||||
self.n_layers = n_layers
|
||||
self.kernel_size = kernel_size
|
||||
self.p_dropout = p_dropout
|
||||
self.proximal_bias = proximal_bias
|
||||
self.proximal_init = proximal_init
|
||||
if isflow:
|
||||
cond_layer = torch.nn.Conv1d(kwargs["gin_channels"], 2 * hidden_channels * n_layers, 1)
|
||||
self.cond_pre = torch.nn.Conv1d(hidden_channels, 2 * hidden_channels, 1)
|
||||
self.cond_layer = weight_norm_modules(cond_layer, name="weight")
|
||||
self.gin_channels = kwargs["gin_channels"]
|
||||
self.drop = nn.Dropout(p_dropout)
|
||||
self.self_attn_layers = nn.ModuleList()
|
||||
self.norm_layers_0 = nn.ModuleList()
|
||||
self.ffn_layers = nn.ModuleList()
|
||||
self.norm_layers_1 = nn.ModuleList()
|
||||
for i in range(self.n_layers):
|
||||
self.self_attn_layers.append(
|
||||
MultiHeadAttention(
|
||||
hidden_channels,
|
||||
hidden_channels,
|
||||
n_heads,
|
||||
p_dropout=p_dropout,
|
||||
proximal_bias=proximal_bias,
|
||||
proximal_init=proximal_init,
|
||||
)
|
||||
)
|
||||
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
||||
self.ffn_layers.append(
|
||||
FFN(
|
||||
hidden_channels,
|
||||
hidden_channels,
|
||||
filter_channels,
|
||||
kernel_size,
|
||||
p_dropout=p_dropout,
|
||||
causal=True,
|
||||
)
|
||||
)
|
||||
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
||||
|
||||
def forward(self, x, x_mask, g=None):
|
||||
"""
|
||||
x: decoder input
|
||||
h: encoder output
|
||||
"""
|
||||
if g is not None:
|
||||
g = self.cond_layer(g)
|
||||
|
||||
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
|
||||
x = x * x_mask
|
||||
for i in range(self.n_layers):
|
||||
if g is not None:
|
||||
x = self.cond_pre(x)
|
||||
cond_offset = i * 2 * self.hidden_channels
|
||||
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
|
||||
x = commons.fused_add_tanh_sigmoid_multiply(x, g_l, torch.IntTensor([self.hidden_channels]))
|
||||
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
||||
y = self.drop(y)
|
||||
x = self.norm_layers_0[i](x + y)
|
||||
|
||||
y = self.ffn_layers[i](x, x_mask)
|
||||
y = self.drop(y)
|
||||
x = self.norm_layers_1[i](x + y)
|
||||
x = x * x_mask
|
||||
return x
|
||||
|
||||
|
||||
class TransformerCouplingLayer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
channels,
|
||||
hidden_channels,
|
||||
kernel_size,
|
||||
n_layers,
|
||||
n_heads,
|
||||
p_dropout=0,
|
||||
filter_channels=0,
|
||||
mean_only=False,
|
||||
wn_sharing_parameter=None,
|
||||
gin_channels=0,
|
||||
):
|
||||
assert channels % 2 == 0, "channels should be divisible by 2"
|
||||
super().__init__()
|
||||
self.channels = channels
|
||||
self.hidden_channels = hidden_channels
|
||||
self.kernel_size = kernel_size
|
||||
self.n_layers = n_layers
|
||||
self.half_channels = channels // 2
|
||||
self.mean_only = mean_only
|
||||
|
||||
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
||||
self.enc = (
|
||||
Encoder(
|
||||
hidden_channels,
|
||||
filter_channels,
|
||||
n_heads,
|
||||
n_layers,
|
||||
kernel_size,
|
||||
p_dropout,
|
||||
isflow=True,
|
||||
gin_channels=gin_channels,
|
||||
)
|
||||
if wn_sharing_parameter is None
|
||||
else wn_sharing_parameter
|
||||
)
|
||||
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
||||
self.post.weight.data.zero_()
|
||||
self.post.bias.data.zero_()
|
||||
|
||||
def forward(self, x, x_mask, g=None, reverse=False):
|
||||
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
|
||||
h = self.pre(x0) * x_mask
|
||||
h = self.enc(h, x_mask, g=g)
|
||||
stats = self.post(h) * x_mask
|
||||
if not self.mean_only:
|
||||
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
|
||||
else:
|
||||
m = stats
|
||||
logs = torch.zeros_like(m)
|
||||
|
||||
if not reverse:
|
||||
x1 = m + x1 * torch.exp(logs) * x_mask
|
||||
x = torch.cat([x0, x1], 1)
|
||||
logdet = torch.sum(logs, [1, 2])
|
||||
return x, logdet
|
||||
else:
|
||||
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
||||
x = torch.cat([x0, x1], 1)
|
||||
return x
|
||||
|
||||
@ -1,385 +0,0 @@
|
||||
import math
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.nn import functional as F
|
||||
|
||||
from module import commons
|
||||
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class LayerNorm(nn.Module):
|
||||
def __init__(self, channels, eps=1e-5):
|
||||
super().__init__()
|
||||
self.channels = channels
|
||||
self.eps = eps
|
||||
|
||||
self.gamma = nn.Parameter(torch.ones(channels))
|
||||
self.beta = nn.Parameter(torch.zeros(channels))
|
||||
|
||||
def forward(self, x):
|
||||
x = x.transpose(1, -1)
|
||||
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
||||
return x.transpose(1, -1)
|
||||
|
||||
|
||||
@torch.jit.script
|
||||
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
||||
n_channels_int = n_channels[0]
|
||||
in_act = input_a + input_b
|
||||
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
||||
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
||||
acts = t_act * s_act
|
||||
return acts
|
||||
|
||||
|
||||
class Encoder(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_channels,
|
||||
filter_channels,
|
||||
n_heads,
|
||||
n_layers,
|
||||
kernel_size=1,
|
||||
p_dropout=0.0,
|
||||
window_size=4,
|
||||
isflow=True,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
self.hidden_channels = hidden_channels
|
||||
self.filter_channels = filter_channels
|
||||
self.n_heads = n_heads
|
||||
self.n_layers = n_layers
|
||||
self.kernel_size = kernel_size
|
||||
self.p_dropout = p_dropout
|
||||
self.window_size = window_size
|
||||
# if isflow:
|
||||
# cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
|
||||
# self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
|
||||
# self.cond_layer = weight_norm(cond_layer, name='weight')
|
||||
# self.gin_channels = 256
|
||||
self.cond_layer_idx = self.n_layers
|
||||
self.spk_emb_linear = nn.Linear(256, self.hidden_channels)
|
||||
if "gin_channels" in kwargs:
|
||||
self.gin_channels = kwargs["gin_channels"]
|
||||
if self.gin_channels != 0:
|
||||
self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
|
||||
# vits2 says 3rd block, so idx is 2 by default
|
||||
self.cond_layer_idx = kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
|
||||
logging.debug(self.gin_channels, self.cond_layer_idx)
|
||||
assert self.cond_layer_idx < self.n_layers, "cond_layer_idx should be less than n_layers"
|
||||
self.drop = nn.Dropout(p_dropout)
|
||||
self.attn_layers = nn.ModuleList()
|
||||
self.norm_layers_1 = nn.ModuleList()
|
||||
self.ffn_layers = nn.ModuleList()
|
||||
self.norm_layers_2 = nn.ModuleList()
|
||||
for i in range(self.n_layers):
|
||||
self.attn_layers.append(
|
||||
MultiHeadAttention(
|
||||
hidden_channels,
|
||||
hidden_channels,
|
||||
n_heads,
|
||||
p_dropout=p_dropout,
|
||||
window_size=window_size,
|
||||
)
|
||||
)
|
||||
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
||||
self.ffn_layers.append(
|
||||
FFN(
|
||||
hidden_channels,
|
||||
hidden_channels,
|
||||
filter_channels,
|
||||
kernel_size,
|
||||
p_dropout=p_dropout,
|
||||
)
|
||||
)
|
||||
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
||||
|
||||
# def forward(self, x, x_mask, g=None):
|
||||
# attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
||||
# x = x * x_mask
|
||||
# for i in range(self.n_layers):
|
||||
# if i == self.cond_layer_idx and g is not None:
|
||||
# g = self.spk_emb_linear(g.transpose(1, 2))
|
||||
# g = g.transpose(1, 2)
|
||||
# x = x + g
|
||||
# x = x * x_mask
|
||||
# y = self.attn_layers[i](x, x, attn_mask)
|
||||
# y = self.drop(y)
|
||||
# x = self.norm_layers_1[i](x + y)
|
||||
|
||||
# y = self.ffn_layers[i](x, x_mask)
|
||||
# y = self.drop(y)
|
||||
# x = self.norm_layers_2[i](x + y)
|
||||
# x = x * x_mask
|
||||
# return x
|
||||
|
||||
def forward(self, x, x_mask):
|
||||
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
||||
x = x * x_mask
|
||||
for attn_layers, norm_layers_1, ffn_layers, norm_layers_2 in zip(
|
||||
self.attn_layers, self.norm_layers_1, self.ffn_layers, self.norm_layers_2
|
||||
):
|
||||
y = attn_layers(x, x, attn_mask)
|
||||
y = self.drop(y)
|
||||
x = norm_layers_1(x + y)
|
||||
|
||||
y = ffn_layers(x, x_mask)
|
||||
y = self.drop(y)
|
||||
x = norm_layers_2(x + y)
|
||||
x = x * x_mask
|
||||
return x
|
||||
|
||||
|
||||
class MultiHeadAttention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
channels,
|
||||
out_channels,
|
||||
n_heads,
|
||||
p_dropout=0.0,
|
||||
window_size=None,
|
||||
heads_share=True,
|
||||
block_length=None,
|
||||
proximal_bias=False,
|
||||
proximal_init=False,
|
||||
):
|
||||
super().__init__()
|
||||
assert channels % n_heads == 0
|
||||
|
||||
self.channels = channels
|
||||
self.out_channels = out_channels
|
||||
self.n_heads = n_heads
|
||||
self.p_dropout = p_dropout
|
||||
self.window_size = window_size
|
||||
self.heads_share = heads_share
|
||||
self.block_length = block_length
|
||||
self.proximal_bias = proximal_bias
|
||||
self.proximal_init = proximal_init
|
||||
self.attn = None
|
||||
|
||||
self.k_channels = channels // n_heads
|
||||
self.conv_q = nn.Conv1d(channels, channels, 1)
|
||||
self.conv_k = nn.Conv1d(channels, channels, 1)
|
||||
self.conv_v = nn.Conv1d(channels, channels, 1)
|
||||
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
||||
self.drop = nn.Dropout(p_dropout)
|
||||
|
||||
if window_size is not None:
|
||||
n_heads_rel = 1 if heads_share else n_heads
|
||||
rel_stddev = self.k_channels**-0.5
|
||||
self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
||||
self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
||||
|
||||
nn.init.xavier_uniform_(self.conv_q.weight)
|
||||
nn.init.xavier_uniform_(self.conv_k.weight)
|
||||
nn.init.xavier_uniform_(self.conv_v.weight)
|
||||
if proximal_init:
|
||||
with torch.no_grad():
|
||||
self.conv_k.weight.copy_(self.conv_q.weight)
|
||||
self.conv_k.bias.copy_(self.conv_q.bias)
|
||||
|
||||
def forward(self, x, c, attn_mask: Optional[torch.Tensor] = None):
|
||||
q = self.conv_q(x)
|
||||
k = self.conv_k(c)
|
||||
v = self.conv_v(c)
|
||||
|
||||
# x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
||||
x, _ = self.attention(q, k, v, mask=attn_mask)
|
||||
|
||||
x = self.conv_o(x)
|
||||
return x
|
||||
|
||||
def attention(self, query, key, value, mask: Optional[torch.Tensor] = None):
|
||||
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
||||
b, d, t_s, _ = (*key.size(), query.size(2))
|
||||
query = query.view(b, self.n_heads, self.k_channels, -1).transpose(2, 3)
|
||||
key = key.view(b, self.n_heads, self.k_channels, -1).transpose(2, 3)
|
||||
value = value.view(b, self.n_heads, self.k_channels, -1).transpose(2, 3)
|
||||
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
|
||||
|
||||
if self.window_size is not None:
|
||||
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
|
||||
rel_logits = self._matmul_with_relative_keys(query / math.sqrt(self.k_channels), key_relative_embeddings)
|
||||
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
||||
scores = scores + scores_local
|
||||
|
||||
if mask is not None:
|
||||
scores = scores.masked_fill(mask == 0, -1e4)
|
||||
|
||||
p_attn = F.softmax(scores, dim=-1)
|
||||
p_attn = self.drop(p_attn)
|
||||
output = torch.matmul(p_attn, value)
|
||||
|
||||
if self.window_size is not None:
|
||||
relative_weights = self._absolute_position_to_relative_position(p_attn)
|
||||
value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
|
||||
output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
|
||||
|
||||
output = output.transpose(2, 3).contiguous().view(b, d, -1)
|
||||
return output, p_attn
|
||||
|
||||
def _matmul_with_relative_values(self, x, y):
|
||||
"""
|
||||
x: [b, h, l, m]
|
||||
y: [h or 1, m, d]
|
||||
ret: [b, h, l, d]
|
||||
"""
|
||||
ret = torch.matmul(x, y.unsqueeze(0))
|
||||
return ret
|
||||
|
||||
def _matmul_with_relative_keys(self, x, y):
|
||||
"""
|
||||
x: [b, h, l, d]
|
||||
y: [h or 1, m, d]
|
||||
ret: [b, h, l, m]
|
||||
"""
|
||||
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
||||
return ret
|
||||
|
||||
def _get_relative_embeddings(self, relative_embeddings, length):
|
||||
max_relative_position = 2 * self.window_size + 1
|
||||
# Pad first before slice to avoid using cond ops.
|
||||
pad_l = torch.zeros((1), dtype=torch.int64) + length - (self.window_size + 1)
|
||||
pad_s = torch.zeros((1), dtype=torch.int64) + (self.window_size + 1) - length
|
||||
pad_length = torch.max(pad_l, other=torch.zeros((1), dtype=torch.int64))
|
||||
slice_start_position = torch.max(pad_s, other=torch.zeros((1), dtype=torch.int64))
|
||||
|
||||
slice_end_position = slice_start_position + 2 * length - 1
|
||||
padded_relative_embeddings = F.pad(
|
||||
relative_embeddings,
|
||||
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
|
||||
)
|
||||
used_relative_embeddings = padded_relative_embeddings[:, slice_start_position:slice_end_position]
|
||||
return used_relative_embeddings
|
||||
|
||||
def _relative_position_to_absolute_position(self, x):
|
||||
"""
|
||||
x: [b, h, l, 2*l-1]
|
||||
ret: [b, h, l, l]
|
||||
"""
|
||||
batch, heads, length, _ = x.size()
|
||||
# Concat columns of pad to shift from relative to absolute indexing.
|
||||
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
|
||||
|
||||
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
||||
x_flat = x.view([batch, heads, length * 2 * length])
|
||||
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]]))
|
||||
|
||||
# Reshape and slice out the padded elements.
|
||||
x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[:, :, :length, length - 1 :]
|
||||
return x_final
|
||||
|
||||
def _absolute_position_to_relative_position(self, x):
|
||||
"""
|
||||
x: [b, h, l, l]
|
||||
ret: [b, h, l, 2*l-1]
|
||||
"""
|
||||
batch, heads, length, _ = x.size()
|
||||
# padd along column
|
||||
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]]))
|
||||
x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
|
||||
# add 0's in the beginning that will skew the elements after reshape
|
||||
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
|
||||
x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
|
||||
return x_final
|
||||
|
||||
def _attention_bias_proximal(self, length):
|
||||
"""Bias for self-attention to encourage attention to close positions.
|
||||
Args:
|
||||
length: an integer scalar.
|
||||
Returns:
|
||||
a Tensor with shape [1, 1, length, length]
|
||||
"""
|
||||
r = torch.arange(length, dtype=torch.float32)
|
||||
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
||||
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
||||
|
||||
|
||||
class FFN(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
filter_channels,
|
||||
kernel_size,
|
||||
p_dropout=0.0,
|
||||
activation="",
|
||||
causal=False,
|
||||
):
|
||||
super().__init__()
|
||||
self.in_channels = in_channels
|
||||
self.out_channels = out_channels
|
||||
self.filter_channels = filter_channels
|
||||
self.kernel_size = kernel_size
|
||||
self.p_dropout = p_dropout
|
||||
self.activation = activation
|
||||
self.causal = causal
|
||||
|
||||
# 从上下文看这里一定是 False
|
||||
# if causal:
|
||||
# self.padding = self._causal_padding
|
||||
# else:
|
||||
# self.padding = self._same_padding
|
||||
|
||||
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
||||
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
||||
self.drop = nn.Dropout(p_dropout)
|
||||
|
||||
def forward(self, x, x_mask):
|
||||
x = self.conv_1(self.padding(x * x_mask))
|
||||
if self.activation == "gelu":
|
||||
x = x * torch.sigmoid(1.702 * x)
|
||||
else:
|
||||
x = torch.relu(x)
|
||||
x = self.drop(x)
|
||||
x = self.conv_2(self.padding(x * x_mask))
|
||||
return x * x_mask
|
||||
|
||||
def padding(self, x):
|
||||
return self._same_padding(x)
|
||||
|
||||
def _causal_padding(self, x):
|
||||
if self.kernel_size == 1:
|
||||
return x
|
||||
pad_l = self.kernel_size - 1
|
||||
pad_r = 0
|
||||
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
||||
x = F.pad(x, commons.convert_pad_shape(padding))
|
||||
return x
|
||||
|
||||
def _same_padding(self, x):
|
||||
if self.kernel_size == 1:
|
||||
return x
|
||||
pad_l = (self.kernel_size - 1) // 2
|
||||
pad_r = self.kernel_size // 2
|
||||
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
||||
x = F.pad(x, commons.convert_pad_shape(padding))
|
||||
return x
|
||||
|
||||
|
||||
class MRTE(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
content_enc_channels=192,
|
||||
hidden_size=512,
|
||||
out_channels=192,
|
||||
kernel_size=5,
|
||||
n_heads=4,
|
||||
ge_layer=2,
|
||||
):
|
||||
super(MRTE, self).__init__()
|
||||
self.cross_attention = MultiHeadAttention(hidden_size, hidden_size, n_heads)
|
||||
self.c_pre = nn.Conv1d(content_enc_channels, hidden_size, 1)
|
||||
self.text_pre = nn.Conv1d(content_enc_channels, hidden_size, 1)
|
||||
self.c_post = nn.Conv1d(hidden_size, out_channels, 1)
|
||||
|
||||
def forward(self, ssl_enc, ssl_mask, text, text_mask, ge):
|
||||
attn_mask = text_mask.unsqueeze(2) * ssl_mask.unsqueeze(-1)
|
||||
|
||||
ssl_enc = self.c_pre(ssl_enc * ssl_mask)
|
||||
text_enc = self.text_pre(text * text_mask)
|
||||
x = self.cross_attention(ssl_enc * ssl_mask, text_enc * text_mask, attn_mask) + ssl_enc + ge
|
||||
x = self.c_post(x * ssl_mask)
|
||||
return x
|
||||
@ -1,6 +1,4 @@
|
||||
import math
|
||||
import torch
|
||||
from torch.nn import functional as F
|
||||
|
||||
|
||||
def init_weights(m, mean=0.0, std=0.01):
|
||||
@ -13,86 +11,6 @@ def get_padding(kernel_size, dilation=1):
|
||||
return int((kernel_size * dilation - dilation) / 2)
|
||||
|
||||
|
||||
# def convert_pad_shape(pad_shape):
|
||||
# l = pad_shape[::-1]
|
||||
# pad_shape = [item for sublist in l for item in sublist]
|
||||
# return pad_shape
|
||||
|
||||
|
||||
def intersperse(lst, item):
|
||||
result = [item] * (len(lst) * 2 + 1)
|
||||
result[1::2] = lst
|
||||
return result
|
||||
|
||||
|
||||
def kl_divergence(m_p, logs_p, m_q, logs_q):
|
||||
"""KL(P||Q)"""
|
||||
kl = (logs_q - logs_p) - 0.5
|
||||
kl += 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
|
||||
return kl
|
||||
|
||||
|
||||
def rand_gumbel(shape):
|
||||
"""Sample from the Gumbel distribution, protect from overflows."""
|
||||
uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
|
||||
return -torch.log(-torch.log(uniform_samples))
|
||||
|
||||
|
||||
def rand_gumbel_like(x):
|
||||
g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
|
||||
return g
|
||||
|
||||
|
||||
def slice_segments(x, ids_str, segment_size=4):
|
||||
ret = torch.zeros_like(x[:, :, :segment_size])
|
||||
for i in range(x.size(0)):
|
||||
idx_str = ids_str[i]
|
||||
idx_end = idx_str + segment_size
|
||||
ret[i] = x[i, :, idx_str:idx_end]
|
||||
return ret
|
||||
|
||||
|
||||
def rand_slice_segments(x, x_lengths=None, segment_size=4):
|
||||
b, d, t = x.size()
|
||||
if x_lengths is None:
|
||||
x_lengths = t
|
||||
ids_str_max = x_lengths - segment_size + 1
|
||||
ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
|
||||
ret = slice_segments(x, ids_str, segment_size)
|
||||
return ret, ids_str
|
||||
|
||||
|
||||
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
|
||||
position = torch.arange(length, dtype=torch.float)
|
||||
num_timescales = channels // 2
|
||||
log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (num_timescales - 1)
|
||||
inv_timescales = min_timescale * torch.exp(
|
||||
torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
|
||||
)
|
||||
scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
|
||||
signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
|
||||
signal = F.pad(signal, [0, 0, 0, channels % 2])
|
||||
signal = signal.view(1, channels, length)
|
||||
return signal
|
||||
|
||||
|
||||
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
|
||||
b, channels, length = x.size()
|
||||
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
||||
return x + signal.to(dtype=x.dtype, device=x.device)
|
||||
|
||||
|
||||
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
|
||||
b, channels, length = x.size()
|
||||
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
||||
return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
|
||||
|
||||
|
||||
def subsequent_mask(length):
|
||||
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
|
||||
return mask
|
||||
|
||||
|
||||
@torch.jit.script
|
||||
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
||||
n_channels_int = n_channels[0]
|
||||
@ -109,77 +27,8 @@ def convert_pad_shape(pad_shape):
|
||||
return pad_shape
|
||||
|
||||
|
||||
def shift_1d(x):
|
||||
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
|
||||
return x
|
||||
|
||||
|
||||
def sequence_mask(length, max_length=None):
|
||||
if max_length is None:
|
||||
max_length = length.max()
|
||||
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
|
||||
return x.unsqueeze(0) < length.unsqueeze(1)
|
||||
|
||||
|
||||
def generate_path(duration, mask):
|
||||
"""
|
||||
duration: [b, 1, t_x]
|
||||
mask: [b, 1, t_y, t_x]
|
||||
"""
|
||||
device = duration.device
|
||||
|
||||
b, _, t_y, t_x = mask.shape
|
||||
cum_duration = torch.cumsum(duration, -1)
|
||||
|
||||
cum_duration_flat = cum_duration.view(b * t_x)
|
||||
path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
|
||||
path = path.view(b, t_x, t_y)
|
||||
path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
|
||||
path = path.unsqueeze(1).transpose(2, 3) * mask
|
||||
return path
|
||||
|
||||
|
||||
def clip_grad_value_(parameters, clip_value, norm_type=2):
|
||||
if isinstance(parameters, torch.Tensor):
|
||||
parameters = [parameters]
|
||||
parameters = list(filter(lambda p: p.grad is not None, parameters))
|
||||
norm_type = float(norm_type)
|
||||
if clip_value is not None:
|
||||
clip_value = float(clip_value)
|
||||
|
||||
total_norm = 0
|
||||
for p in parameters:
|
||||
param_norm = p.grad.data.norm(norm_type)
|
||||
total_norm += param_norm.item() ** norm_type
|
||||
if clip_value is not None:
|
||||
p.grad.data.clamp_(min=-clip_value, max=clip_value)
|
||||
total_norm = total_norm ** (1.0 / norm_type)
|
||||
return total_norm
|
||||
|
||||
|
||||
def squeeze(x, x_mask=None, n_sqz=2):
|
||||
b, c, t = x.size()
|
||||
|
||||
t = (t // n_sqz) * n_sqz
|
||||
x = x[:, :, :t]
|
||||
x_sqz = x.view(b, c, t // n_sqz, n_sqz)
|
||||
x_sqz = x_sqz.permute(0, 3, 1, 2).contiguous().view(b, c * n_sqz, t // n_sqz)
|
||||
|
||||
if x_mask is not None:
|
||||
x_mask = x_mask[:, :, n_sqz - 1 :: n_sqz]
|
||||
else:
|
||||
x_mask = torch.ones(b, 1, t // n_sqz).to(device=x.device, dtype=x.dtype)
|
||||
return x_sqz * x_mask, x_mask
|
||||
|
||||
|
||||
def unsqueeze(x, x_mask=None, n_sqz=2):
|
||||
b, c, t = x.size()
|
||||
|
||||
x_unsqz = x.view(b, n_sqz, c // n_sqz, t)
|
||||
x_unsqz = x_unsqz.permute(0, 2, 3, 1).contiguous().view(b, c // n_sqz, t * n_sqz)
|
||||
|
||||
if x_mask is not None:
|
||||
x_mask = x_mask.unsqueeze(-1).repeat(1, 1, 1, n_sqz).view(b, 1, t * n_sqz)
|
||||
else:
|
||||
x_mask = torch.ones(b, 1, t * n_sqz).to(device=x.device, dtype=x.dtype)
|
||||
return x_unsqz * x_mask, x_mask
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user