mirror of
https://github.com/malarinv/tacotron2
synced 2026-03-08 09:42:34 +00:00
Compare commits
3 Commits
42a85d177e
...
latest_mod
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8128e0e98f | ||
|
|
e0c7e0e928 | ||
|
|
f03692c73d |
166
.gitignore
vendored
166
.gitignore
vendored
@@ -1,166 +0,0 @@
|
||||
|
||||
# Created by https://www.gitignore.io/api/python
|
||||
# Edit at https://www.gitignore.io/?templates=python
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
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
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
|
||||
# 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
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
.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
|
||||
|
||||
# celery beat schedule file
|
||||
celerybeat-schedule
|
||||
|
||||
# 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/
|
||||
|
||||
# End of https://www.gitignore.io/api/python
|
||||
|
||||
# Created by https://www.gitignore.io/api/macos
|
||||
# Edit at https://www.gitignore.io/?templates=macos
|
||||
|
||||
### macOS ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# End of https://www.gitignore.io/api/macos
|
||||
|
||||
*.pkl
|
||||
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
[submodule "waveglow"]
|
||||
path = waveglow
|
||||
url = https://github.com/NVIDIA/waveglow
|
||||
@@ -1,8 +0,0 @@
|
||||
=======
|
||||
Credits
|
||||
=======
|
||||
|
||||
Contributors
|
||||
------------
|
||||
|
||||
* Malar Kannan <malarkannan.invention@gmail.com>
|
||||
2
Dockerfile
Normal file
2
Dockerfile
Normal file
@@ -0,0 +1,2 @@
|
||||
FROM pytorch/pytorch:0.4_cuda9_cudnn7
|
||||
RUN pip install numpy scipy matplotlib librosa==0.6.0 tensorflow tensorboardX inflect==0.2.5 Unidecode==1.0.22 jupyter
|
||||
13
HISTORY.rst
13
HISTORY.rst
@@ -1,13 +0,0 @@
|
||||
=======
|
||||
History
|
||||
=======
|
||||
|
||||
0.2.0 (2019-10-04)
|
||||
------------------
|
||||
* Add Griffin Lim support
|
||||
* Allow passing hyper-parameters to TTSModel.
|
||||
|
||||
|
||||
0.1.0 (2019-09-20)
|
||||
------------------
|
||||
* First release on PyPI.
|
||||
29
LICENSE
Normal file
29
LICENSE
Normal file
@@ -0,0 +1,29 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2018, NVIDIA Corporation
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
10
MANIFEST.in
10
MANIFEST.in
@@ -1,10 +0,0 @@
|
||||
include AUTHORS.rst
|
||||
include HISTORY.rst
|
||||
include LICENSE
|
||||
include README.md
|
||||
|
||||
recursive-include tests *
|
||||
recursive-exclude * __pycache__
|
||||
recursive-exclude * *.py[co]
|
||||
|
||||
recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif
|
||||
89
Makefile
89
Makefile
@@ -1,89 +0,0 @@
|
||||
# Suitable for python monorepo with packages in subdirectories(contains project.mk)
|
||||
.PHONY : _forward Makefile common.mk
|
||||
.DEFAULT_GOAL := help
|
||||
MAKE_PATH := $(dir $(realpath $(firstword $(MAKEFILE_LIST))))
|
||||
|
||||
include ${MAKE_PATH}/common.mk
|
||||
|
||||
clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts
|
||||
|
||||
clean-build: ## remove build artifacts
|
||||
rm -fr build/
|
||||
rm -fr dist/
|
||||
rm -fr .eggs/
|
||||
find . -name '*.egg-info' -exec rm -fr {} +
|
||||
find . -name '*.egg' -exec rm -f {} +
|
||||
|
||||
clean-pyc: ## remove Python file artifacts
|
||||
find . -name '*.pyc' -exec rm -f {} +
|
||||
find . -name '*.pyo' -exec rm -f {} +
|
||||
find . -name '*~' -exec rm -f {} +
|
||||
find . -name '__pycache__' -exec rm -fr {} +
|
||||
|
||||
clean-test: ## remove test and coverage artifacts
|
||||
rm -fr .tox/
|
||||
rm -f .coverage
|
||||
rm -fr htmlcov/
|
||||
rm -fr .pytest_cache
|
||||
|
||||
lint: ## check style with flake8
|
||||
flake8 sia tests
|
||||
|
||||
test: ## run tests quickly with the default Python
|
||||
python setup.py test
|
||||
|
||||
test-all: ## run tests on every Python version with tox
|
||||
tox
|
||||
|
||||
coverage: ## check code coverage quickly with the default Python
|
||||
coverage run --source sia -m pytest
|
||||
coverage report -m
|
||||
coverage html
|
||||
$(BROWSER) htmlcov/index.html
|
||||
|
||||
docs: ## generate Sphinx HTML documentation, including API docs
|
||||
rm -f docs/sia.rst
|
||||
rm -f docs/modules.rst
|
||||
sphinx-apidoc -o docs/ sia
|
||||
$(MAKE) -C docs clean
|
||||
$(MAKE) -C docs html
|
||||
$(BROWSER) docs/_build/html/index.html
|
||||
|
||||
servedocs: docs ## compile the docs watching for changes
|
||||
watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D .
|
||||
|
||||
release: dist pypi ## package and upload a release to local pypi server
|
||||
twine upload -u "" -p "" --repository-url http://localhost:8080 dist/*
|
||||
|
||||
dist: clean ## builds source and wheel package
|
||||
python setup.py sdist
|
||||
python setup.py bdist_wheel
|
||||
ls -l dist
|
||||
|
||||
install: clean pypi ## install the package to the active Python's site-packages
|
||||
python setup.py install
|
||||
|
||||
check: ## lint project using pre-commit hooks installed for git
|
||||
pre-commit run --all-files
|
||||
|
||||
setup:
|
||||
python -m nltk.downloader stopwords
|
||||
rm -rf logs
|
||||
mkdir logs
|
||||
|
||||
install-reqs:
|
||||
pip install -r requirements.txt
|
||||
|
||||
install-dev-reqs:
|
||||
pip install -r requirements_dev.txt
|
||||
|
||||
install: uninstall pypi install-reqs setup ## installs the requirements and download components
|
||||
|
||||
uninstall: ## uninstalls the pip dependencies
|
||||
pip uninstall -y -r requirements.txt
|
||||
|
||||
deploy: ## deploys the services by starting supervisord
|
||||
supervisord
|
||||
|
||||
develop: uninstall pypi install-dev-reqs setup ## installs the requirements and setup development hooks
|
||||
pre-commit install
|
||||
80
README.md
80
README.md
@@ -1,37 +1,63 @@
|
||||
# Taco2 TTS
|
||||
# Tacotron 2 (without wavenet)
|
||||
|
||||
[](https://github.com/python/black)
|
||||
Tacotron 2 PyTorch implementation of [Natural TTS Synthesis By Conditioning
|
||||
Wavenet On Mel Spectrogram Predictions](https://arxiv.org/pdf/1712.05884.pdf).
|
||||
|
||||
> Generates speech audio from text
|
||||
---
|
||||
This implementation includes **distributed** and **fp16** support
|
||||
and uses the [LJSpeech dataset](https://keithito.com/LJ-Speech-Dataset/).
|
||||
|
||||
# Table of Contents
|
||||
Distributed and FP16 support relies on work by Christian Sarofeen and NVIDIA's
|
||||
[Apex Library](https://github.com/nvidia/apex).
|
||||
|
||||
* [Features](#features)
|
||||
* [Installation](#installation)
|
||||
* [Usage](#usage)
|
||||

|
||||
|
||||
# Features
|
||||
[Download demo audio](https://github.com/NVIDIA/tacotron2/blob/master/demo.wav) trained on LJS and using Ryuchi Yamamoto's [pre-trained Mixture of Logistics
|
||||
wavenet](https://github.com/r9y9/wavenet_vocoder/)
|
||||
"Scientists at the CERN laboratory say they have discovered a new particle."
|
||||
|
||||
* TTS using Tacotron2
|
||||
## Pre-requisites
|
||||
1. NVIDIA GPU + CUDA cuDNN
|
||||
|
||||
## Setup
|
||||
1. Download and extract the [LJ Speech dataset](https://keithito.com/LJ-Speech-Dataset/)
|
||||
2. Clone this repo: `git clone https://github.com/NVIDIA/tacotron2.git`
|
||||
3. CD into this repo: `cd tacotron2`
|
||||
4. Update .wav paths: `sed -i -- 's,DUMMY,ljs_dataset_folder/wavs,g' filelists/*.txt`
|
||||
- Alternatively, set `load_mel_from_disk=True` in `hparams.py` and update mel-spectrogram paths
|
||||
5. Install [pytorch 0.4](https://github.com/pytorch/pytorch)
|
||||
6. Install python requirements or build docker image
|
||||
- Install python requirements: `pip install -r requirements.txt`
|
||||
- **OR**
|
||||
- Build docker image: `docker build --tag tacotron2 .`
|
||||
|
||||
## Training
|
||||
1. `python train.py --output_directory=outdir --log_directory=logdir`
|
||||
2. (OPTIONAL) `tensorboard --logdir=outdir/logdir`
|
||||
|
||||
## Multi-GPU (distributed) and FP16 Training
|
||||
1. `python -m multiproc train.py --output_directory=outdir --log_directory=logdir --hparams=distributed_run=True,fp16_run=True`
|
||||
|
||||
## Inference
|
||||
When performing Mel-Spectrogram to Audio synthesis with a WaveNet model, make sure Tacotron 2 and WaveNet were trained on the same mel-spectrogram representation. Follow these steps to use a a simple inference pipeline using griffin-lim:
|
||||
|
||||
1. `jupyter notebook --ip=127.0.0.1 --port=31337`
|
||||
2. load inference.ipynb
|
||||
|
||||
|
||||
# Installation
|
||||
To install the packages and its dependencies run.
|
||||
```bash
|
||||
python setup.py install
|
||||
```
|
||||
or with pip
|
||||
```bash
|
||||
pip install .
|
||||
```
|
||||
|
||||
The installation should work on Python 3.6 or newer. Untested on Python 2.7
|
||||
## Related repos
|
||||
[nv-wavenet](https://github.com/NVIDIA/nv-wavenet/): Faster than real-time
|
||||
wavenet inference
|
||||
|
||||
## Acknowledgements
|
||||
This implementation uses code from the following repos: [Keith
|
||||
Ito](https://github.com/keithito/tacotron/), [Prem
|
||||
Seetharaman](https://github.com/pseeth/pytorch-stft) as described in our code.
|
||||
|
||||
We are inspired by [Ryuchi Yamamoto's](https://github.com/r9y9/tacotron_pytorch)
|
||||
Tacotron PyTorch implementation.
|
||||
|
||||
We are thankful to the Tacotron 2 paper authors, specially Jonathan Shen, Yuxuan
|
||||
Wang and Zongheng Yang.
|
||||
|
||||
|
||||
# Usage
|
||||
```python
|
||||
from taco2.tts import TTSModel
|
||||
tts_model = TTSModel("/path/to/tacotron2_model","/path/to/waveglow_model") # Loads the models
|
||||
SPEECH_AUDIO = tts_model.synth_speech(TEXT) # Returns the wav buffer
|
||||
```
|
||||
If `'/path/to/waveglow_model'` is `None` *Griffin-Lim vocoder* will be used.
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import torch
|
||||
import numpy as np
|
||||
from scipy.signal import get_window
|
||||
import librosa.util as librosa_util
|
||||
from librosa import resample
|
||||
from librosa.effects import time_stretch
|
||||
|
||||
|
||||
def window_sumsquare(
|
||||
window,
|
||||
n_frames,
|
||||
hop_length=200,
|
||||
win_length=800,
|
||||
n_fft=800,
|
||||
dtype=np.float32,
|
||||
norm=None,
|
||||
):
|
||||
def window_sumsquare(window, n_frames, hop_length=200, win_length=800,
|
||||
n_fft=800, dtype=np.float32, norm=None):
|
||||
"""
|
||||
# from librosa 0.6
|
||||
Compute the sum-square envelope of a window function at a given hop length.
|
||||
@@ -56,13 +46,13 @@ def window_sumsquare(
|
||||
|
||||
# Compute the squared window at the desired length
|
||||
win_sq = get_window(window, win_length, fftbins=True)
|
||||
win_sq = librosa_util.normalize(win_sq, norm=norm) ** 2
|
||||
win_sq = librosa_util.normalize(win_sq, norm=norm)**2
|
||||
win_sq = librosa_util.pad_center(win_sq, n_fft)
|
||||
|
||||
# Fill the envelope
|
||||
for i in range(n_frames):
|
||||
sample = i * hop_length
|
||||
x[sample : min(n, sample + n_fft)] += win_sq[: max(0, min(n_fft, n - sample))]
|
||||
x[sample:min(n, sample + n_fft)] += win_sq[:max(0, min(n_fft, n - sample))]
|
||||
return x
|
||||
|
||||
|
||||
@@ -101,48 +91,3 @@ def dynamic_range_decompression(x, C=1):
|
||||
C: compression factor used to compress
|
||||
"""
|
||||
return torch.exp(x) / C
|
||||
|
||||
|
||||
# adapted from
|
||||
# https://github.com/mgeier/python-audio/blob/master/audio-files/utility.py
|
||||
def float2pcm(sig, dtype="int16"):
|
||||
"""Convert floating point signal with a range from -1 to 1 to PCM.
|
||||
Any signal values outside the interval [-1.0, 1.0) are clipped.
|
||||
No dithering is used.
|
||||
Note that there are different possibilities for scaling floating
|
||||
point numbers to PCM numbers, this function implements just one of
|
||||
them. For an overview of alternatives see
|
||||
http://blog.bjornroche.com/2009/12/int-float-int-its-jungle-out-there.html
|
||||
Parameters
|
||||
----------
|
||||
sig : array_like
|
||||
Input array, must have floating point type.
|
||||
dtype : data type, optional
|
||||
Desired (integer) data type.
|
||||
Returns
|
||||
-------
|
||||
numpy.ndarray
|
||||
Integer data, scaled and clipped to the range of the given
|
||||
*dtype*.
|
||||
See Also
|
||||
--------
|
||||
pcm2float, dtype
|
||||
"""
|
||||
sig = np.asarray(sig)
|
||||
if sig.dtype.kind != "f":
|
||||
raise TypeError("'sig' must be a float array")
|
||||
dtype = np.dtype(dtype)
|
||||
if dtype.kind not in "iu":
|
||||
raise TypeError("'dtype' must be an integer type")
|
||||
|
||||
i = np.iinfo(dtype)
|
||||
abs_max = 2 ** (i.bits - 1)
|
||||
offset = i.min + abs_max
|
||||
return (sig * abs_max + offset).clip(i.min, i.max).astype(dtype)
|
||||
|
||||
|
||||
def postprocess_audio(audio, tempo=0.8, src_rate=22050, dst_rate=16000):
|
||||
slow_data = time_stretch(audio, tempo)
|
||||
float_data = resample(slow_data, 22050, dst_rate)
|
||||
data = float2pcm(float_data)
|
||||
return data.tobytes()
|
||||
33
common.mk
33
common.mk
@@ -1,33 +0,0 @@
|
||||
# Contains automatic help generator based comments on target
|
||||
# and other utilities
|
||||
|
||||
define BROWSER_PYSCRIPT
|
||||
import os, webbrowser, sys
|
||||
|
||||
try:
|
||||
from urllib import pathname2url
|
||||
except:
|
||||
from urllib.request import pathname2url
|
||||
|
||||
webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1])))
|
||||
endef
|
||||
export BROWSER_PYSCRIPT
|
||||
|
||||
define PRINT_HELP_PYSCRIPT
|
||||
import re, sys
|
||||
|
||||
for line in sys.stdin:
|
||||
match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
|
||||
if match:
|
||||
target, help = match.groups()
|
||||
print("%-20s %s" % (target, help))
|
||||
endef
|
||||
export PRINT_HELP_PYSCRIPT
|
||||
|
||||
BROWSER := python -c "$$BROWSER_PYSCRIPT"
|
||||
|
||||
|
||||
|
||||
|
||||
help: ## make TARGET forwards the TARGET to sub packages
|
||||
@cat $(MAKEFILE_LIST) | python -c "$$PRINT_HELP_PYSCRIPT"
|
||||
@@ -1,13 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import random
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.utils.data
|
||||
|
||||
from . import layers
|
||||
from .utils import load_wav_to_torch, load_filepaths_and_text
|
||||
from .text import text_to_sequence
|
||||
# from text_codec import text_to_sequence
|
||||
import layers
|
||||
from utils import load_wav_to_torch, load_filepaths_and_text
|
||||
from text import text_to_sequence
|
||||
|
||||
|
||||
class TextMelLoader(torch.utils.data.Dataset):
|
||||
@@ -16,7 +14,6 @@ class TextMelLoader(torch.utils.data.Dataset):
|
||||
2) normalizes text and converts them to sequences of one-hot vectors
|
||||
3) computes mel-spectrograms from audio files.
|
||||
"""
|
||||
|
||||
def __init__(self, audiopaths_and_text, hparams):
|
||||
self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)
|
||||
self.text_cleaners = hparams.text_cleaners
|
||||
@@ -24,14 +21,9 @@ class TextMelLoader(torch.utils.data.Dataset):
|
||||
self.sampling_rate = hparams.sampling_rate
|
||||
self.load_mel_from_disk = hparams.load_mel_from_disk
|
||||
self.stft = layers.TacotronSTFT(
|
||||
hparams.filter_length,
|
||||
hparams.hop_length,
|
||||
hparams.win_length,
|
||||
hparams.n_mel_channels,
|
||||
hparams.sampling_rate,
|
||||
hparams.mel_fmin,
|
||||
hparams.mel_fmax,
|
||||
)
|
||||
hparams.filter_length, hparams.hop_length, hparams.win_length,
|
||||
hparams.n_mel_channels, hparams.sampling_rate, hparams.mel_fmin,
|
||||
hparams.mel_fmax)
|
||||
random.seed(1234)
|
||||
random.shuffle(self.audiopaths_and_text)
|
||||
|
||||
@@ -46,25 +38,18 @@ class TextMelLoader(torch.utils.data.Dataset):
|
||||
if not self.load_mel_from_disk:
|
||||
audio, sampling_rate = load_wav_to_torch(filename)
|
||||
if sampling_rate != self.stft.sampling_rate:
|
||||
raise ValueError(
|
||||
"{} {} SR doesn't match target {} SR".format(
|
||||
sampling_rate, self.stft.sampling_rate
|
||||
)
|
||||
)
|
||||
raise ValueError("{} {} SR doesn't match target {} SR".format(
|
||||
sampling_rate, self.stft.sampling_rate))
|
||||
audio_norm = audio / self.max_wav_value
|
||||
audio_norm = audio_norm.unsqueeze(0)
|
||||
audio_norm = torch.autograd.Variable(
|
||||
audio_norm, requires_grad=False
|
||||
)
|
||||
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
|
||||
melspec = self.stft.mel_spectrogram(audio_norm)
|
||||
melspec = torch.squeeze(melspec, 0)
|
||||
else:
|
||||
melspec = torch.from_numpy(np.load(filename))
|
||||
assert (
|
||||
melspec.size(0) == self.stft.n_mel_channels
|
||||
), "Mel dimension mismatch: given {}, expected {}".format(
|
||||
melspec.size(0), self.stft.n_mel_channels
|
||||
)
|
||||
assert melspec.size(0) == self.stft.n_mel_channels, (
|
||||
'Mel dimension mismatch: given {}, expected {}'.format(
|
||||
melspec.size(0), self.stft.n_mel_channels))
|
||||
|
||||
return melspec
|
||||
|
||||
@@ -79,10 +64,9 @@ class TextMelLoader(torch.utils.data.Dataset):
|
||||
return len(self.audiopaths_and_text)
|
||||
|
||||
|
||||
class TextMelCollate:
|
||||
class TextMelCollate():
|
||||
""" Zero-pads model inputs and targets based on number of frames per setep
|
||||
"""
|
||||
|
||||
def __init__(self, n_frames_per_step):
|
||||
self.n_frames_per_step = n_frames_per_step
|
||||
|
||||
@@ -95,23 +79,20 @@ class TextMelCollate:
|
||||
# Right zero-pad all one-hot text sequences to max input length
|
||||
input_lengths, ids_sorted_decreasing = torch.sort(
|
||||
torch.LongTensor([len(x[0]) for x in batch]),
|
||||
dim=0,
|
||||
descending=True,
|
||||
)
|
||||
dim=0, descending=True)
|
||||
max_input_len = input_lengths[0]
|
||||
|
||||
text_padded = torch.LongTensor(len(batch), max_input_len)
|
||||
text_padded.zero_()
|
||||
for i in range(len(ids_sorted_decreasing)):
|
||||
text = batch[ids_sorted_decreasing[i]][0]
|
||||
text_padded[i, : text.size(0)] = text
|
||||
text_padded[i, :text.size(0)] = text
|
||||
|
||||
# Right zero-pad mel-spec
|
||||
num_mels = batch[0][1].size(0)
|
||||
max_target_len = max([x[1].size(1) for x in batch])
|
||||
if max_target_len % self.n_frames_per_step != 0:
|
||||
rest = max_target_len % self.n_frames_per_step
|
||||
max_target_len += self.n_frames_per_step - rest
|
||||
max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step
|
||||
assert max_target_len % self.n_frames_per_step == 0
|
||||
|
||||
# include mel padded and gate padded
|
||||
@@ -122,14 +103,9 @@ class TextMelCollate:
|
||||
output_lengths = torch.LongTensor(len(batch))
|
||||
for i in range(len(ids_sorted_decreasing)):
|
||||
mel = batch[ids_sorted_decreasing[i]][1]
|
||||
mel_padded[i, :, : mel.size(1)] = mel
|
||||
gate_padded[i, mel.size(1) - 1 :] = 1
|
||||
mel_padded[i, :, :mel.size(1)] = mel
|
||||
gate_padded[i, mel.size(1)-1:] = 1
|
||||
output_lengths[i] = mel.size(1)
|
||||
|
||||
return (
|
||||
text_padded,
|
||||
input_lengths,
|
||||
mel_padded,
|
||||
gate_padded,
|
||||
output_lengths,
|
||||
)
|
||||
return text_padded, input_lengths, mel_padded, gate_padded, \
|
||||
output_lengths
|
||||
172
distributed.py
Normal file
172
distributed.py
Normal file
@@ -0,0 +1,172 @@
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.nn.modules import Module
|
||||
|
||||
def _flatten_dense_tensors(tensors):
|
||||
"""Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of
|
||||
same dense type.
|
||||
Since inputs are dense, the resulting tensor will be a concatenated 1D
|
||||
buffer. Element-wise operation on this buffer will be equivalent to
|
||||
operating individually.
|
||||
Arguments:
|
||||
tensors (Iterable[Tensor]): dense tensors to flatten.
|
||||
Returns:
|
||||
A contiguous 1D buffer containing input tensors.
|
||||
"""
|
||||
if len(tensors) == 1:
|
||||
return tensors[0].contiguous().view(-1)
|
||||
flat = torch.cat([t.contiguous().view(-1) for t in tensors], dim=0)
|
||||
return flat
|
||||
|
||||
def _unflatten_dense_tensors(flat, tensors):
|
||||
"""View a flat buffer using the sizes of tensors. Assume that tensors are of
|
||||
same dense type, and that flat is given by _flatten_dense_tensors.
|
||||
Arguments:
|
||||
flat (Tensor): flattened dense tensors to unflatten.
|
||||
tensors (Iterable[Tensor]): dense tensors whose sizes will be used to
|
||||
unflatten flat.
|
||||
Returns:
|
||||
Unflattened dense tensors with sizes same as tensors and values from
|
||||
flat.
|
||||
"""
|
||||
outputs = []
|
||||
offset = 0
|
||||
for tensor in tensors:
|
||||
numel = tensor.numel()
|
||||
outputs.append(flat.narrow(0, offset, numel).view_as(tensor))
|
||||
offset += numel
|
||||
return tuple(outputs)
|
||||
|
||||
|
||||
'''
|
||||
This version of DistributedDataParallel is designed to be used in conjunction with the multiproc.py
|
||||
launcher included with this example. It assumes that your run is using multiprocess with 1
|
||||
GPU/process, that the model is on the correct device, and that torch.set_device has been
|
||||
used to set the device.
|
||||
|
||||
Parameters are broadcasted to the other processes on initialization of DistributedDataParallel,
|
||||
and will be allreduced at the finish of the backward pass.
|
||||
'''
|
||||
class DistributedDataParallel(Module):
|
||||
|
||||
def __init__(self, module):
|
||||
super(DistributedDataParallel, self).__init__()
|
||||
#fallback for PyTorch 0.3
|
||||
if not hasattr(dist, '_backend'):
|
||||
self.warn_on_half = True
|
||||
else:
|
||||
self.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False
|
||||
|
||||
self.module = module
|
||||
|
||||
for p in self.module.state_dict().values():
|
||||
if not torch.is_tensor(p):
|
||||
continue
|
||||
dist.broadcast(p, 0)
|
||||
|
||||
def allreduce_params():
|
||||
if(self.needs_reduction):
|
||||
self.needs_reduction = False
|
||||
buckets = {}
|
||||
for param in self.module.parameters():
|
||||
if param.requires_grad and param.grad is not None:
|
||||
tp = type(param.data)
|
||||
if tp not in buckets:
|
||||
buckets[tp] = []
|
||||
buckets[tp].append(param)
|
||||
if self.warn_on_half:
|
||||
if torch.cuda.HalfTensor in buckets:
|
||||
print("WARNING: gloo dist backend for half parameters may be extremely slow." +
|
||||
" It is recommended to use the NCCL backend in this case. This currently requires" +
|
||||
"PyTorch built from top of tree master.")
|
||||
self.warn_on_half = False
|
||||
|
||||
for tp in buckets:
|
||||
bucket = buckets[tp]
|
||||
grads = [param.grad.data for param in bucket]
|
||||
coalesced = _flatten_dense_tensors(grads)
|
||||
dist.all_reduce(coalesced)
|
||||
coalesced /= dist.get_world_size()
|
||||
for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)):
|
||||
buf.copy_(synced)
|
||||
|
||||
for param in list(self.module.parameters()):
|
||||
def allreduce_hook(*unused):
|
||||
param._execution_engine.queue_callback(allreduce_params)
|
||||
if param.requires_grad:
|
||||
param.register_hook(allreduce_hook)
|
||||
|
||||
def forward(self, *inputs, **kwargs):
|
||||
self.needs_reduction = True
|
||||
return self.module(*inputs, **kwargs)
|
||||
|
||||
'''
|
||||
def _sync_buffers(self):
|
||||
buffers = list(self.module._all_buffers())
|
||||
if len(buffers) > 0:
|
||||
# cross-node buffer sync
|
||||
flat_buffers = _flatten_dense_tensors(buffers)
|
||||
dist.broadcast(flat_buffers, 0)
|
||||
for buf, synced in zip(buffers, _unflatten_dense_tensors(flat_buffers, buffers)):
|
||||
buf.copy_(synced)
|
||||
def train(self, mode=True):
|
||||
# Clear NCCL communicator and CUDA event cache of the default group ID,
|
||||
# These cache will be recreated at the later call. This is currently a
|
||||
# work-around for a potential NCCL deadlock.
|
||||
if dist._backend == dist.dist_backend.NCCL:
|
||||
dist._clear_group_cache()
|
||||
super(DistributedDataParallel, self).train(mode)
|
||||
self.module.train(mode)
|
||||
'''
|
||||
'''
|
||||
Modifies existing model to do gradient allreduce, but doesn't change class
|
||||
so you don't need "module"
|
||||
'''
|
||||
def apply_gradient_allreduce(module):
|
||||
if not hasattr(dist, '_backend'):
|
||||
module.warn_on_half = True
|
||||
else:
|
||||
module.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False
|
||||
|
||||
for p in module.state_dict().values():
|
||||
if not torch.is_tensor(p):
|
||||
continue
|
||||
dist.broadcast(p, 0)
|
||||
|
||||
def allreduce_params():
|
||||
if(module.needs_reduction):
|
||||
module.needs_reduction = False
|
||||
buckets = {}
|
||||
for param in module.parameters():
|
||||
if param.requires_grad and param.grad is not None:
|
||||
tp = type(param.data)
|
||||
if tp not in buckets:
|
||||
buckets[tp] = []
|
||||
buckets[tp].append(param)
|
||||
if module.warn_on_half:
|
||||
if torch.cuda.HalfTensor in buckets:
|
||||
print("WARNING: gloo dist backend for half parameters may be extremely slow." +
|
||||
" It is recommended to use the NCCL backend in this case. This currently requires" +
|
||||
"PyTorch built from top of tree master.")
|
||||
module.warn_on_half = False
|
||||
|
||||
for tp in buckets:
|
||||
bucket = buckets[tp]
|
||||
grads = [param.grad.data for param in bucket]
|
||||
coalesced = _flatten_dense_tensors(grads)
|
||||
dist.all_reduce(coalesced)
|
||||
coalesced /= dist.get_world_size()
|
||||
for buf, synced in zip(grads, _unflatten_dense_tensors(coalesced, grads)):
|
||||
buf.copy_(synced)
|
||||
|
||||
for param in list(module.parameters()):
|
||||
def allreduce_hook(*unused):
|
||||
param._execution_engine.queue_callback(allreduce_params)
|
||||
if param.requires_grad:
|
||||
param.register_hook(allreduce_hook)
|
||||
|
||||
def set_needs_reduction(self, input, output):
|
||||
self.needs_reduction = True
|
||||
|
||||
module.register_forward_hook(set_needs_reduction)
|
||||
return module
|
||||
500
filelists/ljs_audio_text_test_filelist.txt
Executable file
500
filelists/ljs_audio_text_test_filelist.txt
Executable file
@@ -0,0 +1,500 @@
|
||||
DUMMY/LJ045-0096.wav|Mrs. De Mohrenschildt thought that Oswald,
|
||||
DUMMY/LJ049-0022.wav|The Secret Service believed that it was very doubtful that any President would ride regularly in a vehicle with a fixed top, even though transparent.
|
||||
DUMMY/LJ033-0042.wav|Between the hours of eight and nine p.m. they were occupied with the children in the bedrooms located at the extreme east end of the house.
|
||||
DUMMY/LJ016-0117.wav|The prisoner had nothing to deal with but wooden panels, and by dint of cutting and chopping he got both the lower panels out.
|
||||
DUMMY/LJ025-0157.wav|Under these circumstances, unnatural as they are, with proper management, the bean will thrust forth its radicle and its plumule;
|
||||
DUMMY/LJ042-0219.wav|Oswald demonstrated his thinking in connection with his return to the United States by preparing two sets of identical questions of the type which he might have thought
|
||||
DUMMY/LJ032-0164.wav|it is not possible to state with scientific certainty that a particular small group of fibers come from a certain piece of clothing
|
||||
DUMMY/LJ046-0092.wav|has confidence in the dedicated Secret Service men who are ready to lay down their lives for him
|
||||
DUMMY/LJ050-0118.wav|Since these agencies are already obliged constantly to evaluate the activities of such groups,
|
||||
DUMMY/LJ043-0016.wav|Jeanne De Mohrenschildt said, quote,
|
||||
DUMMY/LJ021-0078.wav|no economic panacea, which could simply revive over-night the heavy industries and the trades dependent upon them.
|
||||
DUMMY/LJ039-0148.wav|Examination of the cartridge cases found on the sixth floor of the Depository Building
|
||||
DUMMY/LJ047-0202.wav|testified that the information available to the Federal Government about Oswald before the assassination would, if known to PRS,
|
||||
DUMMY/LJ023-0056.wav|It is an easy document to understand when you remember that it was called into being
|
||||
DUMMY/LJ021-0025.wav|And in many directions, the intervention of that organized control which we call government
|
||||
DUMMY/LJ030-0105.wav|Communications in the motorcade.
|
||||
DUMMY/LJ021-0012.wav|with respect to industry and business, but nearly all are agreed that private enterprise in times such as these
|
||||
DUMMY/LJ019-0169.wav|and one or two men were allowed to mend clothes and make shoes. The rules made by the Secretary of State were hung up in conspicuous parts of the prison;
|
||||
DUMMY/LJ039-0088.wav|It just is an aid in seeing in the fact that you only have the one element, the crosshair,
|
||||
DUMMY/LJ016-0192.wav|"I think I could do that sort of job," said Calcraft, on the spur of the moment.
|
||||
DUMMY/LJ014-0142.wav|was strewn in front of the dock, and sprinkled it towards the bench with a contemptuous gesture.
|
||||
DUMMY/LJ012-0015.wav|Weedon and Lecasser to twelve and six months respectively in Coldbath Fields.
|
||||
DUMMY/LJ048-0033.wav|Prior to November twenty-two, nineteen sixty-three
|
||||
DUMMY/LJ028-0349.wav|who were each required to send so large a number to Babylon, that in all there were collected no fewer than fifty thousand.
|
||||
DUMMY/LJ030-0197.wav|At first Mrs. Connally thought that her husband had been killed,
|
||||
DUMMY/LJ017-0133.wav|Palmer speedily found imitators.
|
||||
DUMMY/LJ034-0123.wav|Although Brennan testified that the man in the window was standing when he fired the shots, most probably he was either sitting or kneeling.
|
||||
DUMMY/LJ003-0282.wav|Many years were to elapse before these objections should be fairly met and universally overcome.
|
||||
DUMMY/LJ032-0204.wav|Special Agent Lyndal L. Shaneyfelt, a photography expert with the FBI,
|
||||
DUMMY/LJ016-0241.wav|Calcraft served the city of London till eighteen seventy-four, when he was pensioned at the rate of twenty-five shillings per week.
|
||||
DUMMY/LJ023-0033.wav|we will not allow ourselves to run around in new circles of futile discussion and debate, always postponing the day of decision.
|
||||
DUMMY/LJ009-0286.wav|There has never been much science in the system of carrying out the extreme penalty in this country; the "finisher of the law"
|
||||
DUMMY/LJ008-0181.wav|he had his pockets filled with bread and cheese, and it was generally supposed that he had come a long distance to see the fatal show.
|
||||
DUMMY/LJ015-0052.wav|to the value of twenty thousand pounds.
|
||||
DUMMY/LJ016-0314.wav|Sir George Grey thought there was a growing feeling in favor of executions within the prison precincts.
|
||||
DUMMY/LJ047-0056.wav|From August nineteen sixty-two
|
||||
DUMMY/LJ010-0027.wav|Nor did the methods by which they were perpetrated greatly vary from those in times past.
|
||||
DUMMY/LJ010-0065.wav|At the former the "Provisional Government" was to be established,
|
||||
DUMMY/LJ046-0113.wav|The Commission has concluded that at the time of the assassination
|
||||
DUMMY/LJ028-0410.wav|There among the ruins they still live in the same kind of houses,
|
||||
DUMMY/LJ044-0137.wav|More seriously, the facts of his defection had become known, leaving him open to almost unanswerable attack by those who opposed his views.
|
||||
DUMMY/LJ008-0215.wav|One by one the huge uprights of black timber were fitted together,
|
||||
DUMMY/LJ030-0084.wav|or when the press of the crowd made it impossible for the escort motorcycles to stay in position on the car's rear flanks.
|
||||
DUMMY/LJ020-0092.wav|Have yourself called on biscuit mornings an hour earlier than usual.
|
||||
DUMMY/LJ029-0096.wav|On November fourteen, Lawson and Sorrels attended a meeting at Love Field
|
||||
DUMMY/LJ015-0308.wav|and others who swore to the meetings of the conspirators and their movements. Saward was found guilty,
|
||||
DUMMY/LJ012-0067.wav|But Mrs. Solomons could not resist the temptation to dabble in stolen goods, and she was found shipping watches of the wrong category to New York.
|
||||
DUMMY/LJ018-0231.wav|namely, to suppress it and substitute another.
|
||||
DUMMY/LJ014-0265.wav|and later he became manager of the newly rebuilt Olympic at Wych Street.
|
||||
DUMMY/LJ024-0102.wav|would be the first to exclaim as soon as an amendment was proposed
|
||||
DUMMY/LJ007-0233.wav|it consists of several circular perforations, about two inches in diameter,
|
||||
DUMMY/LJ013-0213.wav|This seems to have decided Courvoisier,
|
||||
DUMMY/LJ032-0045.wav|This price included nineteen dollars, ninety-five cents for the rifle and the scope, and one dollar, fifty cents for postage and handling.
|
||||
DUMMY/LJ011-0048.wav|Wherefore let him that thinketh he standeth take heed lest he fall," and was full of the most pointed allusions to the culprit.
|
||||
DUMMY/LJ005-0294.wav|It was frequently stated in evidence that the jail of the borough was in so unfit a state for the reception of prisoners,
|
||||
DUMMY/LJ016-0007.wav|There were others less successful.
|
||||
DUMMY/LJ028-0138.wav|perhaps the tales that travelers told him were exaggerated as travelers' tales are likely to be,
|
||||
DUMMY/LJ050-0029.wav|that is reflected in definite and comprehensive operating procedures.
|
||||
DUMMY/LJ014-0121.wav|The prisoners were in due course transferred to Newgate, to be put upon their trial at the Central Criminal Court.
|
||||
DUMMY/LJ014-0146.wav|They had to handcuff her by force against the most violent resistance, and still she raged and stormed,
|
||||
DUMMY/LJ046-0111.wav|The Secret Service has attempted to perform this function through the activities of its Protective Research Section
|
||||
DUMMY/LJ012-0257.wav|But the affair still remained a profound mystery. No light was thrown upon it till, towards the end of March,
|
||||
DUMMY/LJ002-0260.wav|Yet the public opinion of the whole body seems to have checked dissipation.
|
||||
DUMMY/LJ031-0014.wav|the Presidential limousine arrived at the emergency entrance of the Parkland Hospital at about twelve:thirty-five p.m.
|
||||
DUMMY/LJ047-0093.wav|Oswald was arrested and jailed by the New Orleans Police Department for disturbing the peace, in connection with a street fight which broke out when he was accosted
|
||||
DUMMY/LJ003-0324.wav|gaming of all sorts should be peremptorily forbidden under heavy pains and penalties.
|
||||
DUMMY/LJ021-0115.wav|we have reached into the heart of the problem which is to provide such annual earnings for the lowest paid worker as will meet his minimum needs.
|
||||
DUMMY/LJ046-0191.wav|it had established periodic regular review of the status of four hundred individuals;
|
||||
DUMMY/LJ034-0197.wav|who was one of the first witnesses to alert the police to the Depository as the source of the shots, as has been discussed in chapter three.
|
||||
DUMMY/LJ002-0253.wav|were governed by rules which they themselves had framed, and under which subscriptions were levied
|
||||
DUMMY/LJ048-0288.wav|might have been more alert in the Dallas motorcade if they had retired promptly in Fort Worth.
|
||||
DUMMY/LJ007-0112.wav|Many of the old customs once prevalent in the State Side, so properly condemned and abolished,
|
||||
DUMMY/LJ017-0189.wav|who was presently attacked in the same way as the others, but, but, thanks to the prompt administration of remedies, he recovered.
|
||||
DUMMY/LJ042-0230.wav|basically, although I hate the USSR and socialist system I still think marxism can work under different circumstances, end quote.
|
||||
DUMMY/LJ050-0161.wav|The Secret Service should not and does not plan to develop its own intelligence gathering facilities to duplicate the existing facilities of other Federal agencies.
|
||||
DUMMY/LJ003-0011.wav|that not more than one bottle of wine or one quart of beer could be issued at one time. No account was taken of the amount of liquors admitted in one day,
|
||||
DUMMY/LJ008-0206.wav|and caused a number of stout additional barriers to be erected in front of the scaffold,
|
||||
DUMMY/LJ002-0261.wav|The poorer prisoners were not in abject want, as in other prisons,
|
||||
DUMMY/LJ012-0189.wav|Hunt, in consideration of the information he had given, escaped death, and was sentenced to transportation for life.
|
||||
DUMMY/LJ019-0317.wav|The former, which consisted principally of the tread-wheel, cranks, capstans, shot-drill,
|
||||
DUMMY/LJ011-0041.wav|Visited Mr. Fauntleroy. My application for books for him not having been attended, I had no prayer-book to give him.
|
||||
DUMMY/LJ023-0089.wav|That is not only my accusation.
|
||||
DUMMY/LJ044-0224.wav|would not agree with that particular wording, end quote.
|
||||
DUMMY/LJ013-0104.wav|He found them at length residing at the latter place, one as a landed proprietor, the other as a publican.
|
||||
DUMMY/LJ013-0055.wav|The jury did not believe him, and the verdict was for the defendants.
|
||||
DUMMY/LJ014-0306.wav|These had been attributed to political action; some thought that the large purchases in foreign grains, effected at losing prices,
|
||||
DUMMY/LJ029-0052.wav|To supplement the PRS files, the Secret Service depends largely on local police departments and local offices of other Federal agencies
|
||||
DUMMY/LJ028-0459.wav|Its bricks, measuring about thirteen inches square and three inches in thickness, were burned and stamped with the usual short inscription:
|
||||
DUMMY/LJ017-0183.wav|Soon afterwards Dixon died, showing all the symptoms already described.
|
||||
DUMMY/LJ009-0084.wav|At length the ordinary pauses, and then, in a deep tone, which, though hardly above a whisper, is audible to all, says,
|
||||
DUMMY/LJ007-0170.wav|That in this vast metropolis, the center of wealth, civilization, and information;
|
||||
DUMMY/LJ016-0277.wav|This is proved by contemporary accounts, especially one graphic and realistic article which appeared in the 'Times,'
|
||||
DUMMY/LJ009-0061.wav|He staggers towards the pew, reels into it, stumbles forward, flings himself on the ground, and, by a curious twist of the spine,
|
||||
DUMMY/LJ019-0201.wav|to select a sufficiently spacious piece of ground, and erect a prison which from foundations to roofs should be in conformity with the newest ideas.
|
||||
DUMMY/LJ030-0063.wav|He had repeated this wish only a few days before, during his visit to Tampa, Florida.
|
||||
DUMMY/LJ010-0257.wav|a third miscreant made a similar but far less serious attempt in the month of July following.
|
||||
DUMMY/LJ009-0106.wav|The keeper tries to appear unmoved, but his eye wanders anxiously over the combustible assembly.
|
||||
DUMMY/LJ008-0121.wav|After the construction and action of the machine had been explained, the doctor asked the governor what kind of men he had commanded at Goree,
|
||||
DUMMY/LJ050-0069.wav|the Secret Service had received from the FBI some nine thousand reports on members of the Communist Party.
|
||||
DUMMY/LJ006-0202.wav|The news-vendor was also a tobacconist,
|
||||
DUMMY/LJ012-0230.wav|Shortly before the day fixed for execution, Bishop made a full confession, the bulk of which bore the impress of truth,
|
||||
DUMMY/LJ005-0248.wav|and stated that in his opinion Newgate, as the common jail of Middlesex, was wholly inadequate to the proper confinement of its prisoners.
|
||||
DUMMY/LJ037-0053.wav|who had been greatly upset by her experience, was able to view a lineup of four men handcuffed together at the police station.
|
||||
DUMMY/LJ045-0177.wav|For the first time
|
||||
DUMMY/LJ004-0036.wav|it was hoped that their rulers would hire accommodation in the county prisons, and that the inferior establishments would in course of time disappear.
|
||||
DUMMY/LJ026-0054.wav|carbohydrates (starch, cellulose) and fats.
|
||||
DUMMY/LJ020-0085.wav|Break apart from one another and pile on a plate, throwing a clean doily or a small napkin over them. Break open at table.
|
||||
DUMMY/LJ046-0226.wav|The several military intelligence agencies reported crank mail and similar threats involving the President.
|
||||
DUMMY/LJ014-0233.wav|he shot an old soldier who had attempted to detain him. He was convicted and executed.
|
||||
DUMMY/LJ033-0152.wav|The portion of the palm which was identified was the heel of the right palm, i.e., the area near the wrist, on the little finger side.
|
||||
DUMMY/LJ004-0009.wav|as indefatigable and self-sacrificing, found by personal visitation that the condition of jails throughout the kingdom was,
|
||||
DUMMY/LJ017-0134.wav|Within a few weeks occurred the Leeds poisoning case, in which the murderer undoubtedly was inspired by the facts made public at Palmer's trial.
|
||||
DUMMY/LJ019-0318.wav|was to be the rule for all convicted prisoners throughout the early stages of their detention;
|
||||
DUMMY/LJ020-0093.wav|Rise, wash face and hands, rinse the mouth out and brush back the hair.
|
||||
DUMMY/LJ012-0188.wav|Probert was then admitted as a witness, and the case was fully proved against Thurtell, who was hanged in front of Hertford Jail.
|
||||
DUMMY/LJ019-0202.wav|The preference given to the Pentonville system destroyed all hopes of a complete reformation of Newgate.
|
||||
DUMMY/LJ039-0027.wav|Oswald's revolver
|
||||
DUMMY/LJ040-0176.wav|He admitted to fantasies about being powerful and sometimes hurting and killing people, but refused to elaborate on them.
|
||||
DUMMY/LJ018-0354.wav|Doubts were long entertained whether Thomas Wainwright,
|
||||
DUMMY/LJ031-0185.wav|From the Presidential airplane, the Vice President telephoned Attorney General Robert F. Kennedy,
|
||||
DUMMY/LJ006-0137.wav|They were not obliged to attend chapel, and seldom if ever went; "prisoners," said one of them under examination, "did not like the trouble of going to chapel."
|
||||
DUMMY/LJ032-0085.wav|The Hidell signature on the notice of classification was in the handwriting of Oswald.
|
||||
DUMMY/LJ009-0037.wav|the schoolmaster and the juvenile prisoners being seated round the communion-table, opposite the pulpit.
|
||||
DUMMY/LJ006-0021.wav|Later on he had devoted himself to the personal investigation of the prisons of the United States.
|
||||
DUMMY/LJ006-0082.wav|and this particular official took excellent care to select as residents for his own ward those most suitable from his own point of view.
|
||||
DUMMY/LJ016-0380.wav|with hope to the last. There is always the chance of a flaw in the indictment, of a missing witness, or extenuating circumstances.
|
||||
DUMMY/LJ019-0344.wav|monitor, or schoolmaster, nor to be engaged in the service of any officer of the prison.
|
||||
DUMMY/LJ019-0161.wav|These disciplinary improvements were, however, only slowly and gradually introduced.
|
||||
DUMMY/LJ028-0145.wav|And here I may not omit to tell the use to which the mould dug out of the great moat was turned, nor the manner wherein the wall was wrought.
|
||||
DUMMY/LJ018-0349.wav|His disclaimer, distinct and detailed on every point, was intended simply for effect.
|
||||
DUMMY/LJ043-0010.wav|Some of the members of that group saw a good deal of the Oswalds through the fall of nineteen sixty-three,
|
||||
DUMMY/LJ027-0178.wav|These were undoubtedly perennibranchs. In the Permian and Triassic higher forms appeared, which were certainly caducibranch.
|
||||
DUMMY/LJ041-0070.wav|He did not rise above the rank of private first class, even though he had passed a qualifying examination for the rank of corporal.
|
||||
DUMMY/LJ008-0266.wav|Thus in the years between May first, eighteen twenty-seven, and thirtieth April, eighteen thirty-one,
|
||||
DUMMY/LJ021-0091.wav|In this recent reorganization we have recognized three distinct functions:
|
||||
DUMMY/LJ019-0129.wav|which marked the growth of public interest in prison affairs, and which was the germ of the new system
|
||||
DUMMY/LJ018-0215.wav|William Roupell was the eldest but illegitimate son of a wealthy man who subsequently married Roupell's mother, and had further legitimate issue.
|
||||
DUMMY/LJ015-0194.wav|and behaved so as to justify a belief that he had been a jail-bird all his life.
|
||||
DUMMY/LJ016-0137.wav|that numbers of men, "lifers," and others with ten, fourteen, or twenty years to do, can be trusted to work out of doors without bolts and bars
|
||||
DUMMY/LJ002-0289.wav|the latter raised eighteen pence among them to pay for a truss of straw for the poor woman to lie on.
|
||||
DUMMY/LJ023-0016.wav|In nineteen thirty-three you and I knew that we must never let our economic system get completely out of joint again
|
||||
DUMMY/LJ011-0141.wav|There were at the moment in Newgate six convicts sentenced to death for forging wills.
|
||||
DUMMY/LJ016-0283.wav|to do them mere justice, there was at least till then a half-drunken ribald gaiety among the crowd that made them all akin."
|
||||
DUMMY/LJ035-0082.wav|The only interval was the time necessary to ride in the elevator from the second to the sixth floor and walk back to the southeast corner.
|
||||
DUMMY/LJ045-0194.wav|Anyone who was familiar with that area of Dallas would have known that the motorcade would probably pass the Texas School Book Depository to get from Main Street
|
||||
DUMMY/LJ009-0124.wav|occupied when they saw it last, but a few hours ago, by their comrades who are now dead;
|
||||
DUMMY/LJ030-0162.wav|In the Presidential Limousine
|
||||
DUMMY/LJ050-0223.wav|The plan provides for an additional two hundred five agents for the Secret Service. Seventeen of this number are proposed for the Protective Research Section;
|
||||
DUMMY/LJ008-0228.wav|their harsh and half-cracked voices full of maudlin, besotted sympathy for those about to die.
|
||||
DUMMY/LJ002-0096.wav|The eight courts above enumerated were well supplied with water;
|
||||
DUMMY/LJ018-0288.wav|After this the other conspirators traveled to obtain genuine bills and master the system of the leading houses at home and abroad.
|
||||
DUMMY/LJ002-0106.wav|in which latterly a copper had been fixed for the cooking of provisions sent in by charitable persons.
|
||||
DUMMY/LJ025-0129.wav|On each lobe of the bi-lobed leaf of Venus flytrap are three delicate filaments which stand out at right angles from the surface of the leaf.
|
||||
DUMMY/LJ044-0013.wav|Hands Off Cuba, end quote, an application form for, and a membership card in,
|
||||
DUMMY/LJ049-0115.wav|of the person who is actually in the exercise of the executive power, or
|
||||
DUMMY/LJ019-0145.wav|But reformation was only skin deep. Below the surface many of the old evils still rankled.
|
||||
DUMMY/LJ019-0355.wav|came up in all respects to modern requirements.
|
||||
DUMMY/LJ019-0289.wav|There was unrestrained association of untried and convicted, juvenile with adult prisoners, vagrants, misdemeanants, felons.
|
||||
DUMMY/LJ048-0222.wav|in Fort Worth, there occurred a breach of discipline by some members of the Secret Service who were officially traveling with the President.
|
||||
DUMMY/LJ016-0367.wav|Under the new system the whole of the arrangements from first to last fell upon the officers.
|
||||
DUMMY/LJ047-0097.wav|Agent Quigley did not know of Oswald's prior FBI record when he interviewed him,
|
||||
DUMMY/LJ007-0075.wav|as effectually to rebuke and abash the profane spirit of the more insolent and daring of the criminals.
|
||||
DUMMY/LJ047-0022.wav|provided by other agencies.
|
||||
DUMMY/LJ007-0085.wav|at Newgate and York Castle as long as five years; "at Ilchester and Morpeth for seven years; at Warwick for eight years,
|
||||
DUMMY/LJ047-0075.wav|Hosty had inquired earlier and found no evidence that it was functioning in the Dallas area.
|
||||
DUMMY/LJ008-0098.wav|One was the "yeoman of the halter," a Newgate official, the executioner's assistant, whom Mr. J. T. Smith, who was present at the execution,
|
||||
DUMMY/LJ017-0102.wav|The second attack was fatal, and ended in Cook's death from tetanus.
|
||||
DUMMY/LJ046-0105.wav|Second, the adequacy of other advance preparations for the security of the President, during his visit to Dallas,
|
||||
DUMMY/LJ018-0206.wav|He was a tall, slender man, with a long face and iron-gray hair.
|
||||
DUMMY/LJ012-0271.wav|Whether it was greed or a quarrel that drove Greenacre to the desperate deed remains obscure.
|
||||
DUMMY/LJ005-0086.wav|with such further separation as the justices should deem conducive to good order and discipline.
|
||||
DUMMY/LJ042-0097.wav|and considerably better living quarters than those accorded to Soviet citizens of equal age and station.
|
||||
DUMMY/LJ047-0126.wav|we would handle it in due course, in accord with the whole context of the investigation. End quote.
|
||||
DUMMY/LJ041-0022.wav|Oswald first wrote, quote, Edward Vogel, end quote, an obvious misspelling of Voebel's name,
|
||||
DUMMY/LJ015-0025.wav|The bank enjoyed an excellent reputation, it had a good connection, and was supposed to be perfectly sound.
|
||||
DUMMY/LJ012-0194.wav|But Burke and Hare had their imitators further south,
|
||||
DUMMY/LJ028-0416.wav|(if man may speak so confidently of His great impenetrable counsels), for an eternal Testimony of His great work in the confusion of Man's pride,
|
||||
DUMMY/LJ007-0130.wav|are all huddled together without discrimination, oversight, or control."
|
||||
DUMMY/LJ015-0005.wav|About this time Davidson and Gordon, the people above-mentioned,
|
||||
DUMMY/LJ016-0125.wav|with this, placed against the wall near the chevaux-de-frise, he made an escalade.
|
||||
DUMMY/LJ014-0224.wav|As Dwyer survived, Cannon escaped the death sentence, which was commuted to penal servitude for life.
|
||||
DUMMY/LJ005-0019.wav|refuted by abundant evidence, and having no foundation whatever in truth.
|
||||
DUMMY/LJ042-0221.wav|With either great ambivalence, or cold calculation he prepared completely different answers to the same questions.
|
||||
DUMMY/LJ001-0063.wav|which was generally more formally Gothic than the printing of the German workmen,
|
||||
DUMMY/LJ030-0006.wav|They took off in the Presidential plane, Air Force One, at eleven a.m., arriving at San Antonio at one:thirty p.m., Eastern Standard Time.
|
||||
DUMMY/LJ024-0054.wav|democracy will have failed far beyond the importance to it of any king of precedent concerning the judiciary.
|
||||
DUMMY/LJ006-0044.wav|the same callous indifference to the moral well-being of the prisoners, the same want of employment and of all disciplinary control.
|
||||
DUMMY/LJ039-0154.wav|four point eight to five point six seconds if the second shot missed,
|
||||
DUMMY/LJ050-0090.wav|they seem unduly restrictive in continuing to require some manifestation of animus against a Government official.
|
||||
DUMMY/LJ028-0421.wav|it was the beginning of the great collections of Babylonian antiquities in the museums of the Western world.
|
||||
DUMMY/LJ033-0205.wav|then I would say the possibility exists, these fibers could have come from this blanket, end quote.
|
||||
DUMMY/LJ019-0335.wav|The books and journals he was to keep were minutely specified, and his constant presence in or near the jail was insisted upon.
|
||||
DUMMY/LJ013-0045.wav|Wallace's relations warned him against his Liverpool friend,
|
||||
DUMMY/LJ037-0002.wav|Chapter four. The Assassin: Part six.
|
||||
DUMMY/LJ018-0159.wav|This was all the police wanted to know.
|
||||
DUMMY/LJ026-0140.wav|In the plant as in the animal metabolism must consist of anabolic and catabolic processes.
|
||||
DUMMY/LJ014-0171.wav|I will briefly describe one or two of the more remarkable murders in the years immediately following, then pass on to another branch of crime.
|
||||
DUMMY/LJ037-0007.wav|Three others subsequently identified Oswald from a photograph.
|
||||
DUMMY/LJ033-0174.wav|microscopic and UV (ultra violet) characteristics, end quote.
|
||||
DUMMY/LJ040-0110.wav|he apparently adjusted well enough there to have had an average, although gradually deteriorating, school record
|
||||
DUMMY/LJ039-0192.wav|he had a total of between four point eight and five point six seconds between the two shots which hit
|
||||
DUMMY/LJ032-0261.wav|When he appeared before the Commission, Michael Paine lifted the blanket
|
||||
DUMMY/LJ040-0097.wav|Lee was brought up in this atmosphere of constant money problems, and I am sure it had quite an effect on him, and also Robert, end quote.
|
||||
DUMMY/LJ037-0249.wav|Mrs. Earlene Roberts, the housekeeper at Oswald's roominghouse and the last person known to have seen him before he reached tenth Street and Patton Avenue,
|
||||
DUMMY/LJ016-0248.wav|Marwood was proud of his calling, and when questioned as to whether his process was satisfactory, replied that he heard "no complaints."
|
||||
DUMMY/LJ004-0083.wav|As Mr. Buxton pointed out, many old acts of parliament designed to protect the prisoner were still in full force.
|
||||
DUMMY/LJ014-0029.wav|This was Delarue's watch, fully identified as such, which Hocker told his brother Delarue had given him the morning of the murder.
|
||||
DUMMY/LJ021-0110.wav|have been best calculated to promote industrial recovery and a permanent improvement of business and labor conditions.
|
||||
DUMMY/LJ003-0107.wav|he slept in the same bed with a highwayman on one side, and a man charged with murder on the other.
|
||||
DUMMY/LJ039-0076.wav|Ronald Simmons, chief of the U.S. Army Infantry Weapons Evaluation Branch of the Ballistics Research Laboratory, said, quote,
|
||||
DUMMY/LJ016-0347.wav|had undoubtedly a solemn, impressive effect upon those outside.
|
||||
DUMMY/LJ001-0072.wav|After the end of the fifteenth century the degradation of printing, especially in Germany and Italy,
|
||||
DUMMY/LJ024-0018.wav|Consequently, although there never can be more than fifteen, there may be only fourteen, or thirteen, or twelve.
|
||||
DUMMY/LJ032-0180.wav|that the fibers were caught in the crevice of the rifle's butt plate, quote, in the recent past, end quote,
|
||||
DUMMY/LJ010-0083.wav|and measures taken to arrest them when their plans were so far developed that no doubt could remain as to their guilt.
|
||||
DUMMY/LJ002-0299.wav|and gave the garnish for the common side at that sum, which is five shillings more than Mr. Neild says was extorted on the common side.
|
||||
DUMMY/LJ048-0143.wav|the Secret Service did not at the time of the assassination have any established procedure governing its relationships with them.
|
||||
DUMMY/LJ012-0054.wav|Solomons, while waiting to appear in court, persuaded the turnkeys to take him to a public-house, where all might "refresh."
|
||||
DUMMY/LJ019-0270.wav|Vegetables, especially the potato, that most valuable anti-scorbutic, was too often omitted.
|
||||
DUMMY/LJ035-0164.wav|three minutes after the shooting.
|
||||
DUMMY/LJ014-0326.wav|Maltby and Co. would issue warrants on them deliverable to the importer, and the goods were then passed to be stored in neighboring warehouses.
|
||||
DUMMY/LJ001-0173.wav|The essential point to be remembered is that the ornament, whatever it is, whether picture or pattern-work, should form part of the page,
|
||||
DUMMY/LJ050-0056.wav|On December twenty-six, nineteen sixty-three, the FBI circulated additional instructions to all its agents,
|
||||
DUMMY/LJ003-0319.wav|provided only that their security was not jeopardized, and dependent upon the enforcement of another new rule,
|
||||
DUMMY/LJ006-0040.wav|The fact was that the years as they passed, nearly twenty in all, had worked but little permanent improvement in this detestable prison.
|
||||
DUMMY/LJ017-0231.wav|His body was found lying in a pool of blood in a night-dress, stabbed over and over again in the left side.
|
||||
DUMMY/LJ017-0226.wav|One half of the mutineers fell upon him unawares with handspikes and capstan-bars.
|
||||
DUMMY/LJ004-0239.wav|He had been committed for an offense for which he was acquitted.
|
||||
DUMMY/LJ048-0112.wav|The Commission also regards the security arrangements worked out by Lawson and Sorrels at Love Field as entirely adequate.
|
||||
DUMMY/LJ039-0125.wav|that Oswald was a good shot, somewhat better than or equal to -- better than the average let us say.
|
||||
DUMMY/LJ030-0196.wav|He cried out, quote, Oh, no, no, no. My God, they are going to kill us all, end quote,
|
||||
DUMMY/LJ010-0228.wav|He was released from Broadmoor in eighteen seventy-eight, and went abroad.
|
||||
DUMMY/LJ045-0228.wav|On the other hand, he could have traveled some distance with the money he did have and he did return to his room where he obtained his revolver.
|
||||
DUMMY/LJ028-0168.wav|in the other was the sacred precinct of Jupiter Belus,
|
||||
DUMMY/LJ021-0140.wav|and in such an effort we should be able to secure for employers and employees and consumers
|
||||
DUMMY/LJ009-0280.wav|Again the wretched creature succeeded in obtaining foothold, but this time on the left side of the drop.
|
||||
DUMMY/LJ003-0159.wav|To constitute this the aristocratic quarter, unwarrantable demands were made upon the space properly allotted to the female felons,
|
||||
DUMMY/LJ016-0274.wav|and the windows of the opposite houses, which commanded a good view, as usual fetched high prices.
|
||||
DUMMY/LJ035-0014.wav|it sounded high and I immediately kind of looked up,
|
||||
DUMMY/LJ033-0120.wav|which he believed was where the bag reached when it was laid on the seat with one edge against the door.
|
||||
DUMMY/LJ045-0015.wav|which Johnson said he did not receive until after the assassination. The letter said in part, quote,
|
||||
DUMMY/LJ003-0299.wav|the latter end of the nineteenth century, several of which still fall far short of our English ideal,
|
||||
DUMMY/LJ032-0206.wav|After comparing the rifle in the simulated photograph with the rifle in Exhibit Number one thirty-three A, Shaneyfelt testified, quote,
|
||||
DUMMY/LJ028-0494.wav|Between the several sections were wide spaces where foot soldiers and charioteers might fight.
|
||||
DUMMY/LJ005-0099.wav|and report at length upon the condition of the prisons of the country.
|
||||
DUMMY/LJ015-0144.wav|developed to a colossal extent the frauds he had already practiced as a subordinate.
|
||||
DUMMY/LJ019-0221.wav|It was intended as far as possible that, except awaiting trial, no prisoner should find himself relegated to Newgate.
|
||||
DUMMY/LJ003-0088.wav|in one, for seven years -- that of a man sentenced to death, for whom great interest had been made, but whom it was not thought right to pardon.
|
||||
DUMMY/LJ045-0216.wav|nineteen sixty-three, merely to disarm her and to provide a justification of sorts,
|
||||
DUMMY/LJ042-0135.wav|that he was not yet twenty years old when he went to the Soviet Union with such high hopes and not quite twenty-three when he returned bitterly disappointed.
|
||||
DUMMY/LJ049-0196.wav|On the other hand, it is urged that all features of the protection of the President and his family should be committed to an elite and independent corps.
|
||||
DUMMY/LJ018-0278.wav|This was the well and astutely devised plot of the brothers Bidwell,
|
||||
DUMMY/LJ030-0238.wav|and then looked around again and saw more of this movement, and so I proceeded to go to the back seat and get on top of him.
|
||||
DUMMY/LJ018-0309.wav|where probably the money still remains.
|
||||
DUMMY/LJ041-0199.wav|is shown most clearly by his employment relations after his return from the Soviet Union. Of course, he made his real problems worse to the extent
|
||||
DUMMY/LJ007-0076.wav|The lax discipline maintained in Newgate was still further deteriorated by the presence of two other classes of prisoners who ought never to have been inmates of such a jail.
|
||||
DUMMY/LJ039-0118.wav|He had high motivation. He had presumably a good to excellent rifle and good ammunition.
|
||||
DUMMY/LJ024-0019.wav|And there may be only nine.
|
||||
DUMMY/LJ008-0085.wav|The fire had not quite burnt out at twelve, in nearly four hours, that is to say.
|
||||
DUMMY/LJ018-0031.wav|This fixed the crime pretty certainly upon Müller, who had already left the country, thus increasing suspicion under which he lay.
|
||||
DUMMY/LJ030-0032.wav|Dallas police stood at intervals along the fence and Dallas plain clothes men mixed in the crowd.
|
||||
DUMMY/LJ050-0004.wav|General Supervision of the Secret Service
|
||||
DUMMY/LJ039-0096.wav|This is a definite advantage to the shooter, the vehicle moving directly away from him and the downgrade of the street, and he being in an elevated position
|
||||
DUMMY/LJ041-0195.wav|Oswald's interest in Marxism led some people to avoid him,
|
||||
DUMMY/LJ047-0158.wav|After a moment's hesitation, she told me that he worked at the Texas School Book Depository near the downtown area of Dallas.
|
||||
DUMMY/LJ050-0162.wav|In planning its data processing techniques,
|
||||
DUMMY/LJ001-0051.wav|and paying great attention to the "press work" or actual process of printing,
|
||||
DUMMY/LJ028-0136.wav|Of all the ancient descriptions of the famous walls and the city they protected, that of Herodotus is the fullest.
|
||||
DUMMY/LJ034-0134.wav|Shortly after the assassination Brennan noticed
|
||||
DUMMY/LJ019-0348.wav|Every facility was promised. The sanction of the Secretary of State would not be withheld if plans and estimates were duly submitted,
|
||||
DUMMY/LJ010-0219.wav|While one stood over the fire with the papers, another stood with lighted torch to fire the house.
|
||||
DUMMY/LJ011-0245.wav|Mr. Mullay called again, taking with him five hundred pounds in cash. Howard discovered this, and his manner was very suspicious;
|
||||
DUMMY/LJ030-0035.wav|Organization of the Motorcade
|
||||
DUMMY/LJ044-0135.wav|While he had drawn some attention to himself and had actually appeared on two radio programs, he had been attacked by Cuban exiles and arrested,
|
||||
DUMMY/LJ045-0090.wav|He was very much interested in autobiographical works of outstanding statesmen of the United States, to whom his wife thought he compared himself.
|
||||
DUMMY/LJ026-0034.wav|When any given "protist" has to be classified the case must be decided on its individual merits;
|
||||
DUMMY/LJ045-0092.wav|as to the fact that he was an outstanding man, end quote.
|
||||
DUMMY/LJ017-0050.wav|Palmer, who was only thirty-one at the time of his trial, was in appearance short and stout, with a round head
|
||||
DUMMY/LJ036-0104.wav|Whaley picked Oswald.
|
||||
DUMMY/LJ019-0055.wav|High authorities were in favor of continuous separation.
|
||||
DUMMY/LJ010-0030.wav|The brutal ferocity of the wild beast once aroused, the same means, the same weapons were employed to do the dreadful deed,
|
||||
DUMMY/LJ038-0047.wav|Some of the officers saw Oswald strike McDonald with his fist. Most of them heard a click which they assumed to be a click of the hammer of the revolver.
|
||||
DUMMY/LJ009-0074.wav|Let us pass on.
|
||||
DUMMY/LJ048-0069.wav|Efforts made by the Bureau since the assassination, on the other hand,
|
||||
DUMMY/LJ003-0211.wav|They were never left quite alone for fear of suicide, and for the same reason they were searched for weapons or poisons.
|
||||
DUMMY/LJ048-0053.wav|It is the conclusion of the Commission that, even in the absence of Secret Service criteria
|
||||
DUMMY/LJ033-0093.wav|Frazier estimated that the bag was two feet long, quote, give and take a few inches, end quote, and about five or six inches wide.
|
||||
DUMMY/LJ006-0149.wav|The turnkeys left the prisoners very much to themselves, never entering the wards after locking-up time, at dusk, till unlocking next morning,
|
||||
DUMMY/LJ018-0211.wav|The false coin was bought by an agent from an agent, and dealings were carried on secretly at the "Clock House" in Seven Dials.
|
||||
DUMMY/LJ008-0054.wav|This contrivance appears to have been copied with improvements from that which had been used in Dublin at a still earlier date,
|
||||
DUMMY/LJ040-0052.wav|that his commitment to Marxism was an important factor influencing his conduct during his adult years.
|
||||
DUMMY/LJ028-0023.wav|Two weeks pass, and at last you stand on the eastern edge of the plateau
|
||||
DUMMY/LJ009-0184.wav|Lord Ferrers' body was brought to Surgeons' Hall after execution in his own carriage and six;
|
||||
DUMMY/LJ005-0252.wav|A committee was appointed, under the presidency of the Duke of Richmond
|
||||
DUMMY/LJ015-0266.wav|has probably no parallel in the annals of crime. Saward himself is a striking and in some respects an unique figure in criminal history.
|
||||
DUMMY/LJ017-0059.wav|even after sentence, and until within a few hours of execution, he was buoyed up with the hope of reprieve.
|
||||
DUMMY/LJ024-0034.wav|What do they mean by the words "packing the Court"?
|
||||
DUMMY/LJ016-0089.wav|He was engaged in whitewashing and cleaning; the officer who had him in charge left him on the stairs leading to the gallery.
|
||||
DUMMY/LJ039-0227.wav|with two hits, within four point eight and five point six seconds.
|
||||
DUMMY/LJ001-0096.wav|have now come into general use and are obviously a great improvement on the ordinary "modern style" in use in England, which is in fact the Bodoni type
|
||||
DUMMY/LJ018-0129.wav|who threatened to betray the theft. But Brewer, either before or after this, succumbed to temptation,
|
||||
DUMMY/LJ010-0157.wav|and that, as he was starving, he had resolved on this desperate deed,
|
||||
DUMMY/LJ038-0264.wav|He concluded that, quote, the general rifling characteristics of the rifle are of the same type as those found on the bullet
|
||||
DUMMY/LJ031-0165.wav|When security arrangements at the airport were complete, the Secret Service made the necessary arrangements for the Vice President to leave the hospital.
|
||||
DUMMY/LJ018-0244.wav|The effect of establishing the forgeries would be to restore to the Roupell family lands for which a price had already been paid
|
||||
DUMMY/LJ007-0071.wav|in the face of impediments confessedly discouraging
|
||||
DUMMY/LJ028-0340.wav|Such of the Babylonians as witnessed the treachery took refuge in the temple of Jupiter Belus;
|
||||
DUMMY/LJ017-0164.wav|with the idea of subjecting her to the irritant poison slowly but surely until the desired effect, death, was achieved.
|
||||
DUMMY/LJ048-0197.wav|I then told the officers that their primary duty was traffic and crowd control and that they should be alert for any persons who might attempt to throw anything
|
||||
DUMMY/LJ013-0098.wav|Mr. Oxenford having denied that he had made any transfer of stock, the matter was at once put into the hands of the police.
|
||||
DUMMY/LJ012-0049.wav|led him to think seriously of trying his fortunes in another land.
|
||||
DUMMY/LJ030-0014.wav|quote, that the crowd was about the same as the one which came to see him before but there were one hundred thousand extra people on hand who came to see Mrs. Kennedy.
|
||||
DUMMY/LJ014-0186.wav|A milliner's porter,
|
||||
DUMMY/LJ015-0027.wav|Yet even so early as the death of the first Sir John Paul,
|
||||
DUMMY/LJ047-0049.wav|Marina Oswald, however, recalled that her husband was upset by this interview.
|
||||
DUMMY/LJ012-0021.wav|at fourteen he was a pickpocket and a "duffer," or a seller of sham goods.
|
||||
DUMMY/LJ003-0140.wav|otherwise he would have been stripped of his clothes. End quote.
|
||||
DUMMY/LJ042-0130.wav|Shortly thereafter, less than eighteen months after his defection, about six weeks before he met Marina Prusakova,
|
||||
DUMMY/LJ019-0180.wav|His letter to the Corporation, under date fourth June,
|
||||
DUMMY/LJ017-0108.wav|He was struck with the appearance of the corpse, which was not emaciated, as after a long disease ending in death;
|
||||
DUMMY/LJ006-0268.wav|Women saw men if they merely pretended to be wives; even boys were visited by their sweethearts.
|
||||
DUMMY/LJ044-0125.wav|of residence in the U.S.S.R. against any cause which I join, by association,
|
||||
DUMMY/LJ015-0231.wav|It was Tester's business, who had access to the railway company's books, to watch for this.
|
||||
DUMMY/LJ002-0225.wav|The rentals of rooms and fees went to the warden, whose income was two thousand three hundred seventy-two pounds.
|
||||
DUMMY/LJ034-0072.wav|The employees raced the elevators to the first floor. Givens saw Oswald standing at the gate on the fifth floor as the elevator went by.
|
||||
DUMMY/LJ045-0033.wav|He began to treat me better. He helped me more -- although he always did help. But he was more attentive, end quote.
|
||||
DUMMY/LJ031-0058.wav|to infuse blood and fluids into the circulatory system.
|
||||
DUMMY/LJ029-0197.wav|During November the Dallas papers reported frequently on the plans for protecting the President, stressing the thoroughness of the preparations.
|
||||
DUMMY/LJ043-0047.wav|Oswald and his family lived for a brief period with his mother at her urging, but Oswald soon decided to move out.
|
||||
DUMMY/LJ021-0026.wav|seems necessary to produce the same result of justice and right conduct
|
||||
DUMMY/LJ003-0230.wav|The prison allowances were eked out by the broken victuals generously given by several eating-house keepers in the city,
|
||||
DUMMY/LJ037-0252.wav|Ted Callaway, who saw the gunman moments after the shooting, testified that Commission Exhibit Number one sixty-two
|
||||
DUMMY/LJ031-0008.wav|Meanwhile, Chief Curry ordered the police base station to notify Parkland Hospital that the wounded President was en route.
|
||||
DUMMY/LJ030-0021.wav|all one had to do was get a high building someday with a telescopic rifle, and there was nothing anybody could do to defend against such an attempt.
|
||||
DUMMY/LJ046-0179.wav|being reviewed regularly.
|
||||
DUMMY/LJ025-0118.wav|and that, however diverse may be the fabrics or tissues of which their bodies are composed, all these varied structures result
|
||||
DUMMY/LJ028-0278.wav|Zopyrus, when they told him, not thinking that it could be true, went and saw the colt with his own eyes;
|
||||
DUMMY/LJ007-0090.wav|Not only did their presence tend greatly to interfere with the discipline of the prison, but their condition was deplorable in the extreme.
|
||||
DUMMY/LJ045-0045.wav|that she would be able to leave the Soviet Union. Marina Oswald has denied this.
|
||||
DUMMY/LJ028-0289.wav|For he cut off his own nose and ears, and then, clipping his hair close and flogging himself with a scourge,
|
||||
DUMMY/LJ009-0276.wav|Calcraft, the moment he had adjusted the cap and rope, ran down the steps, drew the bolt, and disappeared.
|
||||
DUMMY/LJ031-0122.wav|treated the gunshot wound in the left thigh.
|
||||
DUMMY/LJ016-0205.wav|he received a retaining fee of five pounds, five shillings, with the usual guinea for each job;
|
||||
DUMMY/LJ019-0248.wav|leading to an inequality, uncertainty, and inefficiency of punishment productive of the most prejudicial results.
|
||||
DUMMY/LJ033-0183.wav|it was not surprising that the replica sack made on December one, nineteen sixty-three,
|
||||
DUMMY/LJ037-0001.wav|Report of the President's Commission on the Assassination of President Kennedy. The Warren Commission Report. By The President's Commission on the Assassination of President Kennedy.
|
||||
DUMMY/LJ018-0218.wav|In eighteen fifty-five
|
||||
DUMMY/LJ001-0102.wav|Here and there a book is printed in France or Germany with some pretension to good taste,
|
||||
DUMMY/LJ007-0125.wav|It was diverted from its proper uses, and, as the "place of the greatest comfort," was allotted to persons who should not have been sent to Newgate at all.
|
||||
DUMMY/LJ050-0022.wav|A formal and thorough description of the responsibilities of the advance agent is now in preparation by the Service.
|
||||
DUMMY/LJ028-0212.wav|On the night of the eleventh day Gobrias killed the son of the King.
|
||||
DUMMY/LJ028-0357.wav|yet we may be sure that Babylon was taken by Darius only by use of stratagem. Its walls were impregnable.
|
||||
DUMMY/LJ014-0199.wav|there was no case to make out; why waste money on lawyers for the defense? His demeanor was cool and collected throughout;
|
||||
DUMMY/LJ016-0077.wav|A man named Lears, under sentence of transportation for an attempt at murder on board ship, got up part of the way,
|
||||
DUMMY/LJ009-0194.wav|and that executors or persons having lawful possession of the bodies
|
||||
DUMMY/LJ014-0094.wav|Discovery of the murder came in this wise. O'Connor, a punctual and well-conducted official, was at once missed at the London Docks.
|
||||
DUMMY/LJ001-0079.wav|Caslon's type is clear and neat, and fairly well designed;
|
||||
DUMMY/LJ026-0052.wav|In the nutrition of the animal the most essential and characteristic part of the food supply is derived from vegetable
|
||||
DUMMY/LJ013-0005.wav|One of the earliest of the big operators in fraudulent finance was Edward Beaumont Smith,
|
||||
DUMMY/LJ033-0072.wav|I then stepped off of it and the officer picked it up in the middle and it bent so.
|
||||
DUMMY/LJ036-0067.wav|According to McWatters, the Beckley bus was behind the Marsalis bus, but he did not actually see it.
|
||||
DUMMY/LJ025-0098.wav|and it is probable that amyloid substances are universally present in the animal organism, though not in the precise form of starch.
|
||||
DUMMY/LJ005-0257.wav|during which time a host of witnesses were examined, and the committee presented three separate reports,
|
||||
DUMMY/LJ004-0024.wav|Thus in eighteen thirteen the exaction of jail fees had been forbidden by law,
|
||||
DUMMY/LJ049-0154.wav|In eighteen ninety-four,
|
||||
DUMMY/LJ039-0059.wav|(three) his experience and practice after leaving the Marine Corps, and (four) the accuracy of the weapon and the quality of the ammunition.
|
||||
DUMMY/LJ007-0150.wav|He is allowed intercourse with prostitutes who, in nine cases out of ten, have originally conduced to his ruin;
|
||||
DUMMY/LJ015-0001.wav|Chronicles of Newgate, Volume two. By Arthur Griffiths. Section eighteen: Newgate notorieties continued, part three.
|
||||
DUMMY/LJ010-0158.wav|feeling, as he said, that he might as well be shot or hanged as remain in such a state.
|
||||
DUMMY/LJ010-0281.wav|who had borne the Queen's commission, first as cornet, and then lieutenant, in the tenth Hussars.
|
||||
DUMMY/LJ033-0055.wav|and he could disassemble it more rapidly.
|
||||
DUMMY/LJ015-0218.wav|A new accomplice was now needed within the company's establishment, and Pierce looked about long before he found the right person.
|
||||
DUMMY/LJ027-0006.wav|In all these lines the facts are drawn together by a strong thread of unity.
|
||||
DUMMY/LJ016-0049.wav|He had here completed his ascent.
|
||||
DUMMY/LJ006-0088.wav|It was not likely that a system which left innocent men -- for the great bulk of new arrivals were still untried
|
||||
DUMMY/LJ042-0133.wav|a great change must have occurred in Oswald's thinking to induce him to return to the United States.
|
||||
DUMMY/LJ045-0234.wav|While he did become enraged at at least one point in his interrogation,
|
||||
DUMMY/LJ046-0033.wav|The adequacy of existing procedures can fairly be assessed only after full consideration of the difficulty of the protective assignment,
|
||||
DUMMY/LJ037-0061.wav|and having, quote, somewhat bushy, end quote, hair.
|
||||
DUMMY/LJ032-0025.wav|the officers of Klein's discovered that a rifle bearing serial number C two seven six six had been shipped to one A. Hidell,
|
||||
DUMMY/LJ047-0197.wav|in view of all the information concerning Oswald in its files, should have alerted the Secret Service to Oswald's presence in Dallas
|
||||
DUMMY/LJ018-0130.wav|and stole paper on a much larger scale than Brown.
|
||||
DUMMY/LJ005-0265.wav|It was recommended that the dietaries should be submitted and approved like the rules; that convicted prisoners should not receive any food but the jail allowance;
|
||||
DUMMY/LJ044-0105.wav|He presented Arnold Johnson, Gus Hall,
|
||||
DUMMY/LJ015-0043.wav|This went on for some time, and might never have been discovered had some good stroke of luck provided any of the partners
|
||||
DUMMY/LJ030-0125.wav|On several occasions when the Vice President's car was slowed down by the throng, Special Agent Youngblood stepped out to hold the crowd back.
|
||||
DUMMY/LJ043-0140.wav|He also studied Dallas bus schedules to prepare for his later use of buses to travel to and from General Walker's house.
|
||||
DUMMY/LJ002-0220.wav|In consequence of these disclosures, both Bambridge and Huggin, his predecessor in the office, were committed to Newgate,
|
||||
DUMMY/LJ034-0117.wav|At one:twenty-nine p.m. the police radio reported
|
||||
DUMMY/LJ018-0276.wav|The first plot was against Mr. Harry Emmanuel, but he escaped, and the attempt was made upon Loudon and Ryder.
|
||||
DUMMY/LJ004-0077.wav|nor has he a right to poison or starve his fellow-creatures."
|
||||
DUMMY/LJ042-0194.wav|they should not be confused with slowness, indecision or fear. Only the intellectually fearless could even be remotely attracted to our doctrine,
|
||||
DUMMY/LJ029-0114.wav|The route chosen from the airport to Main Street was the normal one, except where Harwood Street was selected as the means of access to Main Street
|
||||
DUMMY/LJ014-0194.wav|The policemen were now in possession;
|
||||
DUMMY/LJ032-0027.wav|According to its microfilm records, Klein's received an order for a rifle on March thirteen, nineteen sixty-three,
|
||||
DUMMY/LJ048-0289.wav|However, there is no evidence that these men failed to take any action in Dallas within their power that would have averted the tragedy.
|
||||
DUMMY/LJ043-0188.wav|that he was the leader of a fascist organization, and when I said that even though all of that might be true, just the same he had no right to take his life,
|
||||
DUMMY/LJ011-0118.wav|In eighteen twenty-nine the gallows claimed two more victims for this offense.
|
||||
DUMMY/LJ040-0201.wav|After her interview with Mrs. Oswald,
|
||||
DUMMY/LJ033-0056.wav|While the rifle may have already been disassembled when Oswald arrived home on Thursday, he had ample time that evening to disassemble the rifle
|
||||
DUMMY/LJ047-0073.wav|Hosty considered the information to be, quote, stale, unquote, by that time, and did not attempt to verify Oswald's reported statement.
|
||||
DUMMY/LJ001-0153.wav|only nominally so, however, in many cases, since when he uses a headline he counts that in,
|
||||
DUMMY/LJ007-0158.wav|or any kind of moral improvement was impossible; the prisoner's career was inevitably downward, till he struck the lowest depths.
|
||||
DUMMY/LJ028-0502.wav|The Ishtar gateway leading to the palace was encased with beautiful blue glazed bricks,
|
||||
DUMMY/LJ028-0226.wav|Though Herodotus wrote nearly a hundred years after Babylon fell, his story seems to bear the stamp of truth.
|
||||
DUMMY/LJ010-0038.wav|as there had been before; as in the year eighteen forty-nine, a year memorable for the Rush murders at Norwich,
|
||||
DUMMY/LJ019-0241.wav|But in the interval very comprehensive and, I think it must be admitted, salutary changes were successively introduced into the management of prisons.
|
||||
DUMMY/LJ001-0094.wav|were induced to cut punches for a series of "old style" letters.
|
||||
DUMMY/LJ001-0015.wav|the forms of printed letters should be beautiful, and that their arrangement on the page should be reasonable and a help to the shapeliness of the letters themselves.
|
||||
DUMMY/LJ047-0015.wav|From defection to return to Fort Worth.
|
||||
DUMMY/LJ044-0139.wav|since there was no background to the New Orleans FPCC, quote, organization, end quote, which consisted solely of Oswald.
|
||||
DUMMY/LJ050-0031.wav|that the Secret Service consciously set about the task of inculcating and maintaining the highest standard of excellence and esprit, for all of its personnel.
|
||||
DUMMY/LJ050-0235.wav|It has also used other Federal law enforcement agents during Presidential visits to cities in which such agents are stationed.
|
||||
DUMMY/LJ050-0137.wav|FBI, and the Secret Service.
|
||||
DUMMY/LJ031-0109.wav|At one:thirty-five p.m., after Governor Connally had been moved to the operating room, Dr. Shaw started the first operation
|
||||
DUMMY/LJ031-0041.wav|He noted that the President was blue-white or ashen in color; had slow, spasmodic, agonal respiration without any coordination;
|
||||
DUMMY/LJ021-0139.wav|There should be at least a full and fair trial given to these means of ending industrial warfare;
|
||||
DUMMY/LJ029-0004.wav|The narrative of these events is based largely on the recollections of the participants,
|
||||
DUMMY/LJ023-0122.wav|It was said in last year's Democratic platform,
|
||||
DUMMY/LJ005-0264.wav|inspectors of prisons should be appointed, who should visit all the prisons from time to time and report to the Secretary of State.
|
||||
DUMMY/LJ002-0105.wav|and beyond it was a room called the "wine room," because formerly used for the sale of wine, but
|
||||
DUMMY/LJ017-0035.wav|in the interests and for the due protection of the public, that the fullest and fairest inquiry should be made,
|
||||
DUMMY/LJ048-0252.wav|Three of these agents occupied positions on the running boards of the car, and the fourth was seated in the car.
|
||||
DUMMY/LJ013-0109.wav|The proceeds of the robbery were lodged in a Boston bank,
|
||||
DUMMY/LJ039-0139.wav|Oswald obtained a hunting license, joined a hunting club and went hunting about six times, as discussed more fully in chapter six.
|
||||
DUMMY/LJ044-0047.wav|that anyone ever attacked any street demonstration in which Oswald was involved, except for the Bringuier incident mentioned above,
|
||||
DUMMY/LJ016-0417.wav|Catherine Wilson, the poisoner, was reserved and reticent to the last, expressing no contrition, but also no fear --
|
||||
DUMMY/LJ045-0178.wav|he left his wedding ring in a cup on the dresser in his room. He also left one hundred seventy dollars in a wallet in one of the dresser drawers.
|
||||
DUMMY/LJ009-0172.wav|While in London, for instance, in eighteen twenty-nine, twenty-four persons had been executed for crimes other than murder,
|
||||
DUMMY/LJ049-0202.wav|incident to its responsibilities.
|
||||
DUMMY/LJ032-0103.wav|The name "Hidell" was stamped on some of the "Chapter's" printed literature and on the membership application blanks.
|
||||
DUMMY/LJ013-0091.wav|and Elder had to be assisted by two bank porters, who carried it for him to a carriage waiting near the Mansion House.
|
||||
DUMMY/LJ037-0208.wav|nineteen dollars, ninety-five cents, plus one dollar, twenty-seven cents shipping charge, had been collected from the consignee, Hidell.
|
||||
DUMMY/LJ014-0128.wav|her hair was dressed in long crepe bands. She had lace ruffles at her wrist, and wore primrose-colored kid gloves.
|
||||
DUMMY/LJ015-0007.wav|This affected Cole's credit, and ugly reports were in circulation charging him with the issue of simulated warrants.
|
||||
DUMMY/LJ036-0169.wav|he would have reached his destination at approximately twelve:fifty-four p.m.
|
||||
DUMMY/LJ021-0040.wav|The second step we have taken in the restoration of normal business enterprise
|
||||
DUMMY/LJ015-0036.wav|The bank was already insolvent,
|
||||
DUMMY/LJ034-0041.wav|Although Bureau experiments had shown that twenty-four hours was a likely maximum time, Latona stated
|
||||
DUMMY/LJ009-0192.wav|The dissection of executed criminals was abolished soon after the discovery of the crime of burking,
|
||||
DUMMY/LJ037-0248.wav|The eyewitnesses vary in their identification of the jacket.
|
||||
DUMMY/LJ015-0289.wav|As each transaction was carried out from a different address, and a different messenger always employed,
|
||||
DUMMY/LJ005-0072.wav|After a few years of active exertion the Society was rewarded by fresh legislation.
|
||||
DUMMY/LJ023-0047.wav|The three horses are, of course, the three branches of government -- the Congress, the Executive and the courts.
|
||||
DUMMY/LJ009-0126.wav|Hardly any one.
|
||||
DUMMY/LJ034-0097.wav|The window was approximately one hundred twenty feet away.
|
||||
DUMMY/LJ028-0462.wav|They were laid in bitumen.
|
||||
DUMMY/LJ046-0055.wav|It is now possible for Presidents to travel the length and breadth of a land far larger than the United States
|
||||
DUMMY/LJ019-0371.wav|Yet the law was seldom if ever enforced.
|
||||
DUMMY/LJ039-0207.wav|Although all of the shots were a few inches high and to the right of the target,
|
||||
DUMMY/LJ002-0174.wav|Mr. Buxton's friends at once paid the forty shillings, and the boy was released.
|
||||
DUMMY/LJ016-0233.wav|In his own profession
|
||||
DUMMY/LJ026-0108.wav|It is clear that there are upward and downward currents of water containing food (comparable to blood of an animal),
|
||||
DUMMY/LJ038-0035.wav|Oswald rose from his seat, bringing up both hands.
|
||||
DUMMY/LJ026-0148.wav|water which is lost by evaporation, especially from the leaf surface through the stomata;
|
||||
DUMMY/LJ001-0186.wav|the position of our Society that a work of utility might be also a work of art, if we cared to make it so.
|
||||
DUMMY/LJ016-0264.wav|The upturned faces of the eager spectators resembled those of the 'gods' at Drury Lane on Boxing Night;
|
||||
DUMMY/LJ009-0041.wav|The occupants of this terrible black pew were the last always to enter the chapel.
|
||||
DUMMY/LJ010-0297.wav|But there were other notorious cases of forgery.
|
||||
DUMMY/LJ040-0018.wav|the Commission is not able to reach any definite conclusions as to whether or not he was, quote, sane, unquote, under prevailing legal standards.
|
||||
DUMMY/LJ005-0253.wav|"to inquire into and report upon the several jails and houses of correction in the counties, cities, and corporate towns within England and Wales
|
||||
DUMMY/LJ027-0176.wav|Fishes first appeared in the Devonian and Upper Silurian in very reptilian or rather amphibian forms.
|
||||
DUMMY/LJ034-0035.wav|The position of this palmprint on the carton was parallel with the long axis of the box, and at right angles with the short axis;
|
||||
DUMMY/LJ016-0054.wav|But he did not like the risk of entering a room by the fireplace, and the chances of detection it offered.
|
||||
DUMMY/LJ018-0262.wav|Roupell received the announcement with a cheerful countenance,
|
||||
DUMMY/LJ044-0237.wav|with thirteen dollars, eighty-seven cents when considerably greater resources were available to him.
|
||||
DUMMY/LJ034-0166.wav|Two other witnesses were able to offer partial descriptions of a man they saw in the southeast corner window
|
||||
DUMMY/LJ016-0238.wav|"just to steady their legs a little;" in other words, to add his weight to that of the hanging bodies.
|
||||
DUMMY/LJ042-0198.wav|The discussion above has already set forth examples of his expression of hatred for the United States.
|
||||
DUMMY/LJ031-0189.wav|At two:thirty-eight p.m., Eastern Standard Time, Lyndon Baines Johnson took the oath of office as the thirty-sixth President of the United States.
|
||||
DUMMY/LJ050-0084.wav|or, quote, other high government officials in the nature of a complaint coupled with an expressed or implied determination to use a means,
|
||||
DUMMY/LJ044-0158.wav|As for my return entrance visa please consider it separately. End quote.
|
||||
DUMMY/LJ045-0082.wav|it appears that Marina Oswald also complained that her husband was not able to provide more material things for her.
|
||||
DUMMY/LJ045-0190.wav|appeared in The Dallas Times Herald on November fifteen, nineteen sixty-three.
|
||||
DUMMY/LJ035-0155.wav|The only exit from the office in the direction Oswald was moving was through the door to the front stairway.
|
||||
DUMMY/LJ044-0004.wav|Political Activities
|
||||
DUMMY/LJ046-0016.wav|The Commission has not undertaken a comprehensive examination of all facets of this subject;
|
||||
DUMMY/LJ019-0368.wav|The latter too was to be laid before the House of Commons.
|
||||
DUMMY/LJ010-0062.wav|But they proceeded in all seriousness, and would have shrunk from no outrage or atrocity in furtherance of their foolhardy enterprise.
|
||||
DUMMY/LJ033-0159.wav|It was from Oswald's right hand, in which he carried the long package as he walked from Frazier's car to the building.
|
||||
DUMMY/LJ002-0171.wav|The boy declared he saw no one, and accordingly passed through without paying the toll of a penny.
|
||||
DUMMY/LJ002-0298.wav|in his evidence in eighteen fourteen, said it was more,
|
||||
DUMMY/LJ012-0219.wav|and in one corner, at some depth, a bundle of clothes were unearthed, which, with a hairy cap,
|
||||
DUMMY/LJ017-0190.wav|After this came the charge of administering oil of vitriol, which failed, as has been described.
|
||||
DUMMY/LJ019-0179.wav|This, with a scheme for limiting the jail to untried prisoners, had been urgently recommended by Lord John Russell in eighteen thirty.
|
||||
DUMMY/LJ050-0188.wav|each patrolman might be given a prepared booklet of instructions explaining what is expected of him. The Secret Service has expressed concern
|
||||
DUMMY/LJ006-0043.wav|The disgraceful overcrowding had been partially ended, but the same evils of indiscriminate association were still present; there was the old neglect of decency,
|
||||
DUMMY/LJ029-0060.wav|A number of people who resembled some of those in the photographs were placed under surveillance at the Trade Mart.
|
||||
DUMMY/LJ019-0052.wav|Both systems came to us from the United States. The difference was really more in degree than in principle,
|
||||
DUMMY/LJ037-0081.wav|Later in the day each woman found an empty shell on the ground near the house. These two shells were delivered to the police.
|
||||
DUMMY/LJ048-0200.wav|paying particular attention to the crowd for any unusual activity.
|
||||
DUMMY/LJ016-0426.wav|come along, gallows.
|
||||
DUMMY/LJ008-0182.wav|A tremendous crowd assembled when Bellingham was executed in eighteen twelve for the murder of Spencer Percival, at that time prime minister;
|
||||
DUMMY/LJ043-0107.wav|Upon moving to New Orleans on April twenty-four, nineteen sixty-three,
|
||||
DUMMY/LJ006-0084.wav|and so numerous were his opportunities of showing favoritism, that all the prisoners may be said to be in his power.
|
||||
DUMMY/LJ025-0081.wav|has no permanent digestive cavity or mouth, but takes in its food anywhere and digests, so to speak, all over its body.
|
||||
DUMMY/LJ019-0042.wav|These were either satisfied with a makeshift, and modified existing buildings, without close regard to their suitability, or for a long time did nothing at all.
|
||||
DUMMY/LJ047-0240.wav|They agree that Hosty told Revill
|
||||
DUMMY/LJ032-0012.wav|the resistance to arrest and the attempted shooting of another police officer by the man (Lee Harvey Oswald) subsequently accused of assassinating President Kennedy
|
||||
DUMMY/LJ050-0209.wav|The assistant to the Director of the FBI testified that
|
||||
12500
filelists/ljs_audio_text_train_filelist.txt
Executable file
12500
filelists/ljs_audio_text_train_filelist.txt
Executable file
File diff suppressed because it is too large
Load Diff
100
filelists/ljs_audio_text_val_filelist.txt
Executable file
100
filelists/ljs_audio_text_val_filelist.txt
Executable file
@@ -0,0 +1,100 @@
|
||||
DUMMY/LJ022-0023.wav|The overwhelming majority of people in this country know how to sift the wheat from the chaff in what they hear and what they read.
|
||||
DUMMY/LJ043-0030.wav|If somebody did that to me, a lousy trick like that, to take my wife away, and all the furniture, I would be mad as hell, too.
|
||||
DUMMY/LJ005-0201.wav|as is shown by the report of the Commissioners to inquire into the state of the municipal corporations in eighteen thirty-five.
|
||||
DUMMY/LJ001-0110.wav|Even the Caslon type when enlarged shows great shortcomings in this respect:
|
||||
DUMMY/LJ003-0345.wav|All the committee could do in this respect was to throw the responsibility on others.
|
||||
DUMMY/LJ007-0154.wav|These pungent and well-grounded strictures applied with still greater force to the unconvicted prisoner, the man who came to the prison innocent, and still uncontaminated,
|
||||
DUMMY/LJ018-0098.wav|and recognized as one of the frequenters of the bogus law-stationers. His arrest led to that of others.
|
||||
DUMMY/LJ047-0044.wav|Oswald was, however, willing to discuss his contacts with Soviet authorities. He denied having any involvement with Soviet intelligence agencies
|
||||
DUMMY/LJ031-0038.wav|The first physician to see the President at Parkland Hospital was Dr. Charles J. Carrico, a resident in general surgery.
|
||||
DUMMY/LJ048-0194.wav|during the morning of November twenty-two prior to the motorcade.
|
||||
DUMMY/LJ049-0026.wav|On occasion the Secret Service has been permitted to have an agent riding in the passenger compartment with the President.
|
||||
DUMMY/LJ004-0152.wav|although at Mr. Buxton's visit a new jail was in process of erection, the first step towards reform since Howard's visitation in seventeen seventy-four.
|
||||
DUMMY/LJ008-0278.wav|or theirs might be one of many, and it might be considered necessary to "make an example."
|
||||
DUMMY/LJ043-0002.wav|The Warren Commission Report. By The President's Commission on the Assassination of President Kennedy. Chapter seven. Lee Harvey Oswald:
|
||||
DUMMY/LJ009-0114.wav|Mr. Wakefield winds up his graphic but somewhat sensational account by describing another religious service, which may appropriately be inserted here.
|
||||
DUMMY/LJ028-0506.wav|A modern artist would have difficulty in doing such accurate work.
|
||||
DUMMY/LJ050-0168.wav|with the particular purposes of the agency involved. The Commission recognizes that this is a controversial area
|
||||
DUMMY/LJ039-0223.wav|Oswald's Marine training in marksmanship, his other rifle experience and his established familiarity with this particular weapon
|
||||
DUMMY/LJ029-0032.wav|According to O'Donnell, quote, we had a motorcade wherever we went, end quote.
|
||||
DUMMY/LJ031-0070.wav|Dr. Clark, who most closely observed the head wound,
|
||||
DUMMY/LJ034-0198.wav|Euins, who was on the southwest corner of Elm and Houston Streets testified that he could not describe the man he saw in the window.
|
||||
DUMMY/LJ026-0068.wav|Energy enters the plant, to a small extent,
|
||||
DUMMY/LJ039-0075.wav|once you know that you must put the crosshairs on the target and that is all that is necessary.
|
||||
DUMMY/LJ004-0096.wav|the fatal consequences whereof might be prevented if the justices of the peace were duly authorized
|
||||
DUMMY/LJ005-0014.wav|Speaking on a debate on prison matters, he declared that
|
||||
DUMMY/LJ012-0161.wav|he was reported to have fallen away to a shadow.
|
||||
DUMMY/LJ018-0239.wav|His disappearance gave color and substance to evil reports already in circulation that the will and conveyance above referred to
|
||||
DUMMY/LJ019-0257.wav|Here the tread-wheel was in use, there cellular cranks, or hard-labor machines.
|
||||
DUMMY/LJ028-0008.wav|you tap gently with your heel upon the shoulder of the dromedary to urge her on.
|
||||
DUMMY/LJ024-0083.wav|This plan of mine is no attack on the Court;
|
||||
DUMMY/LJ042-0129.wav|No night clubs or bowling alleys, no places of recreation except the trade union dances. I have had enough.
|
||||
DUMMY/LJ036-0103.wav|The police asked him whether he could pick out his passenger from the lineup.
|
||||
DUMMY/LJ046-0058.wav|During his Presidency, Franklin D. Roosevelt made almost four hundred journeys and traveled more than three hundred fifty thousand miles.
|
||||
DUMMY/LJ014-0076.wav|He was seen afterwards smoking and talking with his hosts in their back parlor, and never seen again alive.
|
||||
DUMMY/LJ002-0043.wav|long narrow rooms -- one thirty-six feet, six twenty-three feet, and the eighth eighteen,
|
||||
DUMMY/LJ009-0076.wav|We come to the sermon.
|
||||
DUMMY/LJ017-0131.wav|even when the high sheriff had told him there was no possibility of a reprieve, and within a few hours of execution.
|
||||
DUMMY/LJ046-0184.wav|but there is a system for the immediate notification of the Secret Service by the confining institution when a subject is released or escapes.
|
||||
DUMMY/LJ014-0263.wav|When other pleasures palled he took a theatre, and posed as a munificent patron of the dramatic art.
|
||||
DUMMY/LJ042-0096.wav|(old exchange rate) in addition to his factory salary of approximately equal amount
|
||||
DUMMY/LJ049-0050.wav|Hill had both feet on the car and was climbing aboard to assist President and Mrs. Kennedy.
|
||||
DUMMY/LJ019-0186.wav|seeing that since the establishment of the Central Criminal Court, Newgate received prisoners for trial from several counties,
|
||||
DUMMY/LJ028-0307.wav|then let twenty days pass, and at the end of that time station near the Chaldasan gates a body of four thousand.
|
||||
DUMMY/LJ012-0235.wav|While they were in a state of insensibility the murder was committed.
|
||||
DUMMY/LJ034-0053.wav|reached the same conclusion as Latona that the prints found on the cartons were those of Lee Harvey Oswald.
|
||||
DUMMY/LJ014-0030.wav|These were damnatory facts which well supported the prosecution.
|
||||
DUMMY/LJ015-0203.wav|but were the precautions too minute, the vigilance too close to be eluded or overcome?
|
||||
DUMMY/LJ028-0093.wav|but his scribe wrote it in the manner customary for the scribes of those days to write of their royal masters.
|
||||
DUMMY/LJ002-0018.wav|The inadequacy of the jail was noticed and reported upon again and again by the grand juries of the city of London,
|
||||
DUMMY/LJ028-0275.wav|At last, in the twentieth month,
|
||||
DUMMY/LJ012-0042.wav|which he kept concealed in a hiding-place with a trap-door just under his bed.
|
||||
DUMMY/LJ011-0096.wav|He married a lady also belonging to the Society of Friends, who brought him a large fortune, which, and his own money, he put into a city firm,
|
||||
DUMMY/LJ036-0077.wav|Roger D. Craig, a deputy sheriff of Dallas County,
|
||||
DUMMY/LJ016-0318.wav|Other officials, great lawyers, governors of prisons, and chaplains supported this view.
|
||||
DUMMY/LJ013-0164.wav|who came from his room ready dressed, a suspicious circumstance, as he was always late in the morning.
|
||||
DUMMY/LJ027-0141.wav|is closely reproduced in the life-history of existing deer. Or, in other words,
|
||||
DUMMY/LJ028-0335.wav|accordingly they committed to him the command of their whole army, and put the keys of their city into his hands.
|
||||
DUMMY/LJ031-0202.wav|Mrs. Kennedy chose the hospital in Bethesda for the autopsy because the President had served in the Navy.
|
||||
DUMMY/LJ021-0145.wav|From those willing to join in establishing this hoped-for period of peace,
|
||||
DUMMY/LJ016-0288.wav|"Müller, Müller, He's the man," till a diversion was created by the appearance of the gallows, which was received with continuous yells.
|
||||
DUMMY/LJ028-0081.wav|Years later, when the archaeologists could readily distinguish the false from the true,
|
||||
DUMMY/LJ018-0081.wav|his defense being that he had intended to commit suicide, but that, on the appearance of this officer who had wronged him,
|
||||
DUMMY/LJ021-0066.wav|together with a great increase in the payrolls, there has come a substantial rise in the total of industrial profits
|
||||
DUMMY/LJ009-0238.wav|After this the sheriffs sent for another rope, but the spectators interfered, and the man was carried back to jail.
|
||||
DUMMY/LJ005-0079.wav|and improve the morals of the prisoners, and shall insure the proper measure of punishment to convicted offenders.
|
||||
DUMMY/LJ035-0019.wav|drove to the northwest corner of Elm and Houston, and parked approximately ten feet from the traffic signal.
|
||||
DUMMY/LJ036-0174.wav|This is the approximate time he entered the roominghouse, according to Earlene Roberts, the housekeeper there.
|
||||
DUMMY/LJ046-0146.wav|The criteria in effect prior to November twenty-two, nineteen sixty-three, for determining whether to accept material for the PRS general files
|
||||
DUMMY/LJ017-0044.wav|and the deepest anxiety was felt that the crime, if crime there had been, should be brought home to its perpetrator.
|
||||
DUMMY/LJ017-0070.wav|but his sporting operations did not prosper, and he became a needy man, always driven to desperate straits for cash.
|
||||
DUMMY/LJ014-0020.wav|He was soon afterwards arrested on suspicion, and a search of his lodgings brought to light several garments saturated with blood;
|
||||
DUMMY/LJ016-0020.wav|He never reached the cistern, but fell back into the yard, injuring his legs severely.
|
||||
DUMMY/LJ045-0230.wav|when he was finally apprehended in the Texas Theatre. Although it is not fully corroborated by others who were present,
|
||||
DUMMY/LJ035-0129.wav|and she must have run down the stairs ahead of Oswald and would probably have seen or heard him.
|
||||
DUMMY/LJ008-0307.wav|afterwards express a wish to murder the Recorder for having kept them so long in suspense.
|
||||
DUMMY/LJ008-0294.wav|nearly indefinitely deferred.
|
||||
DUMMY/LJ047-0148.wav|On October twenty-five,
|
||||
DUMMY/LJ008-0111.wav|They entered a "stone cold room," and were presently joined by the prisoner.
|
||||
DUMMY/LJ034-0042.wav|that he could only testify with certainty that the print was less than three days old.
|
||||
DUMMY/LJ037-0234.wav|Mrs. Mary Brock, the wife of a mechanic who worked at the station, was there at the time and she saw a white male,
|
||||
DUMMY/LJ040-0002.wav|Chapter seven. Lee Harvey Oswald: Background and Possible Motives, Part one.
|
||||
DUMMY/LJ045-0140.wav|The arguments he used to justify his use of the alias suggest that Oswald may have come to think that the whole world was becoming involved
|
||||
DUMMY/LJ012-0035.wav|the number and names on watches, were carefully removed or obliterated after the goods passed out of his hands.
|
||||
DUMMY/LJ012-0250.wav|On the seventh July, eighteen thirty-seven,
|
||||
DUMMY/LJ016-0179.wav|contracted with sheriffs and conveners to work by the job.
|
||||
DUMMY/LJ016-0138.wav|at a distance from the prison.
|
||||
DUMMY/LJ027-0052.wav|These principles of homology are essential to a correct interpretation of the facts of morphology.
|
||||
DUMMY/LJ031-0134.wav|On one occasion Mrs. Johnson, accompanied by two Secret Service agents, left the room to see Mrs. Kennedy and Mrs. Connally.
|
||||
DUMMY/LJ019-0273.wav|which Sir Joshua Jebb told the committee he considered the proper elements of penal discipline.
|
||||
DUMMY/LJ014-0110.wav|At the first the boxes were impounded, opened, and found to contain many of O'Connor's effects.
|
||||
DUMMY/LJ034-0160.wav|on Brennan's subsequent certain identification of Lee Harvey Oswald as the man he saw fire the rifle.
|
||||
DUMMY/LJ038-0199.wav|eleven. If I am alive and taken prisoner,
|
||||
DUMMY/LJ014-0010.wav|yet he could not overcome the strange fascination it had for him, and remained by the side of the corpse till the stretcher came.
|
||||
DUMMY/LJ033-0047.wav|I noticed when I went out that the light was on, end quote,
|
||||
DUMMY/LJ040-0027.wav|He was never satisfied with anything.
|
||||
DUMMY/LJ048-0228.wav|and others who were present say that no agent was inebriated or acted improperly.
|
||||
DUMMY/LJ003-0111.wav|He was in consequence put out of the protection of their internal law, end quote. Their code was a subject of some curiosity.
|
||||
DUMMY/LJ008-0258.wav|Let me retrace my steps, and speak more in detail of the treatment of the condemned in those bloodthirsty and brutally indifferent days,
|
||||
DUMMY/LJ029-0022.wav|The original plan called for the President to spend only one day in the State, making whirlwind visits to Dallas, Fort Worth, San Antonio, and Houston.
|
||||
DUMMY/LJ004-0045.wav|Mr. Sturges Bourne, Sir James Mackintosh, Sir James Scarlett, and William Wilberforce.
|
||||
381
fp16_optimizer.py
Normal file
381
fp16_optimizer.py
Normal file
@@ -0,0 +1,381 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.autograd import Variable
|
||||
from torch.nn.parameter import Parameter
|
||||
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
|
||||
|
||||
from loss_scaler import DynamicLossScaler, LossScaler
|
||||
|
||||
FLOAT_TYPES = (torch.FloatTensor, torch.cuda.FloatTensor)
|
||||
HALF_TYPES = (torch.HalfTensor, torch.cuda.HalfTensor)
|
||||
|
||||
def conversion_helper(val, conversion):
|
||||
"""Apply conversion to val. Recursively apply conversion if `val` is a nested tuple/list structure."""
|
||||
if not isinstance(val, (tuple, list)):
|
||||
return conversion(val)
|
||||
rtn = [conversion_helper(v, conversion) for v in val]
|
||||
if isinstance(val, tuple):
|
||||
rtn = tuple(rtn)
|
||||
return rtn
|
||||
|
||||
def fp32_to_fp16(val):
|
||||
"""Convert fp32 `val` to fp16"""
|
||||
def half_conversion(val):
|
||||
val_typecheck = val
|
||||
if isinstance(val_typecheck, (Parameter, Variable)):
|
||||
val_typecheck = val.data
|
||||
if isinstance(val_typecheck, FLOAT_TYPES):
|
||||
val = val.half()
|
||||
return val
|
||||
return conversion_helper(val, half_conversion)
|
||||
|
||||
def fp16_to_fp32(val):
|
||||
"""Convert fp16 `val` to fp32"""
|
||||
def float_conversion(val):
|
||||
val_typecheck = val
|
||||
if isinstance(val_typecheck, (Parameter, Variable)):
|
||||
val_typecheck = val.data
|
||||
if isinstance(val_typecheck, HALF_TYPES):
|
||||
val = val.float()
|
||||
return val
|
||||
return conversion_helper(val, float_conversion)
|
||||
|
||||
class FP16_Module(nn.Module):
|
||||
def __init__(self, module):
|
||||
super(FP16_Module, self).__init__()
|
||||
self.add_module('module', module.half())
|
||||
|
||||
def forward(self, *inputs, **kwargs):
|
||||
return fp16_to_fp32(self.module(*(fp32_to_fp16(inputs)), **kwargs))
|
||||
|
||||
class FP16_Optimizer(object):
|
||||
"""
|
||||
FP16_Optimizer is designed to wrap an existing PyTorch optimizer,
|
||||
and enable an fp16 model to be trained using a master copy of fp32 weights.
|
||||
|
||||
Args:
|
||||
optimizer (torch.optim.optimizer): Existing optimizer containing initialized fp16 parameters. Internally, FP16_Optimizer replaces the passed optimizer's fp16 parameters with new fp32 parameters copied from the original ones. FP16_Optimizer also stores references to the original fp16 parameters, and updates these fp16 parameters from the master fp32 copy after each step.
|
||||
static_loss_scale (float, optional, default=1.0): Loss scale used internally to scale fp16 gradients computed by the model. Scaled gradients will be copied to fp32, then downscaled before being applied to the fp32 master params, so static_loss_scale should not affect learning rate.
|
||||
dynamic_loss_scale (bool, optional, default=False): Use dynamic loss scaling. If True, this will override any static_loss_scale option.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, optimizer, static_loss_scale=1.0, dynamic_loss_scale=False):
|
||||
if not torch.cuda.is_available:
|
||||
raise SystemError('Cannot use fp16 without CUDA')
|
||||
|
||||
self.fp16_param_groups = []
|
||||
self.fp32_param_groups = []
|
||||
self.fp32_flattened_groups = []
|
||||
for i, param_group in enumerate(optimizer.param_groups):
|
||||
print("FP16_Optimizer processing param group {}:".format(i))
|
||||
fp16_params_this_group = []
|
||||
fp32_params_this_group = []
|
||||
for param in param_group['params']:
|
||||
if param.requires_grad:
|
||||
if param.type() == 'torch.cuda.HalfTensor':
|
||||
print("FP16_Optimizer received torch.cuda.HalfTensor with {}"
|
||||
.format(param.size()))
|
||||
fp16_params_this_group.append(param)
|
||||
elif param.type() == 'torch.cuda.FloatTensor':
|
||||
print("FP16_Optimizer received torch.cuda.FloatTensor with {}"
|
||||
.format(param.size()))
|
||||
fp32_params_this_group.append(param)
|
||||
else:
|
||||
raise TypeError("Wrapped parameters must be either "
|
||||
"torch.cuda.FloatTensor or torch.cuda.HalfTensor. "
|
||||
"Received {}".format(param.type()))
|
||||
|
||||
fp32_flattened_this_group = None
|
||||
if len(fp16_params_this_group) > 0:
|
||||
fp32_flattened_this_group = _flatten_dense_tensors(
|
||||
[param.detach().data.clone().float() for param in fp16_params_this_group])
|
||||
|
||||
fp32_flattened_this_group = Variable(fp32_flattened_this_group, requires_grad = True)
|
||||
|
||||
fp32_flattened_this_group.grad = fp32_flattened_this_group.new(
|
||||
*fp32_flattened_this_group.size())
|
||||
|
||||
# python's lovely list concatenation via +
|
||||
if fp32_flattened_this_group is not None:
|
||||
param_group['params'] = [fp32_flattened_this_group] + fp32_params_this_group
|
||||
else:
|
||||
param_group['params'] = fp32_params_this_group
|
||||
|
||||
self.fp16_param_groups.append(fp16_params_this_group)
|
||||
self.fp32_param_groups.append(fp32_params_this_group)
|
||||
self.fp32_flattened_groups.append(fp32_flattened_this_group)
|
||||
|
||||
# print("self.fp32_flattened_groups = ", self.fp32_flattened_groups)
|
||||
# print("self.fp16_param_groups = ", self.fp16_param_groups)
|
||||
|
||||
self.optimizer = optimizer.__class__(optimizer.param_groups)
|
||||
|
||||
# self.optimizer.load_state_dict(optimizer.state_dict())
|
||||
|
||||
self.param_groups = self.optimizer.param_groups
|
||||
|
||||
if dynamic_loss_scale:
|
||||
self.dynamic_loss_scale = True
|
||||
self.loss_scaler = DynamicLossScaler()
|
||||
else:
|
||||
self.dynamic_loss_scale = False
|
||||
self.loss_scaler = LossScaler(static_loss_scale)
|
||||
|
||||
self.overflow = False
|
||||
self.first_closure_call_this_step = True
|
||||
|
||||
def zero_grad(self):
|
||||
"""
|
||||
Zero fp32 and fp16 parameter grads.
|
||||
"""
|
||||
self.optimizer.zero_grad()
|
||||
for fp16_group in self.fp16_param_groups:
|
||||
for param in fp16_group:
|
||||
if param.grad is not None:
|
||||
param.grad.detach_() # This does appear in torch.optim.optimizer.zero_grad(),
|
||||
# but I'm not sure why it's needed.
|
||||
param.grad.zero_()
|
||||
|
||||
def _check_overflow(self):
|
||||
params = []
|
||||
for group in self.fp16_param_groups:
|
||||
for param in group:
|
||||
params.append(param)
|
||||
for group in self.fp32_param_groups:
|
||||
for param in group:
|
||||
params.append(param)
|
||||
self.overflow = self.loss_scaler.has_overflow(params)
|
||||
|
||||
def _update_scale(self, has_overflow=False):
|
||||
self.loss_scaler.update_scale(has_overflow)
|
||||
|
||||
def _copy_grads_fp16_to_fp32(self):
|
||||
for fp32_group, fp16_group in zip(self.fp32_flattened_groups, self.fp16_param_groups):
|
||||
if len(fp16_group) > 0:
|
||||
# This might incur one more deep copy than is necessary.
|
||||
fp32_group.grad.data.copy_(
|
||||
_flatten_dense_tensors([fp16_param.grad.data for fp16_param in fp16_group]))
|
||||
|
||||
def _downscale_fp32(self):
|
||||
if self.loss_scale != 1.0:
|
||||
for param_group in self.optimizer.param_groups:
|
||||
for param in param_group['params']:
|
||||
param.grad.data.mul_(1./self.loss_scale)
|
||||
|
||||
def clip_fp32_grads(self, clip=-1):
|
||||
if not self.overflow:
|
||||
fp32_params = []
|
||||
for param_group in self.optimizer.param_groups:
|
||||
for param in param_group['params']:
|
||||
fp32_params.append(param)
|
||||
if clip > 0:
|
||||
return torch.nn.utils.clip_grad_norm(fp32_params, clip)
|
||||
|
||||
def _copy_params_fp32_to_fp16(self):
|
||||
for fp16_group, fp32_group in zip(self.fp16_param_groups, self.fp32_flattened_groups):
|
||||
if len(fp16_group) > 0:
|
||||
for fp16_param, fp32_data in zip(fp16_group,
|
||||
_unflatten_dense_tensors(fp32_group.data, fp16_group)):
|
||||
fp16_param.data.copy_(fp32_data)
|
||||
|
||||
def state_dict(self):
|
||||
"""
|
||||
Returns a dict containing the current state of this FP16_Optimizer instance.
|
||||
This dict contains attributes of FP16_Optimizer, as well as the state_dict
|
||||
of the contained Pytorch optimizer.
|
||||
|
||||
Untested.
|
||||
"""
|
||||
state_dict = {}
|
||||
state_dict['loss_scaler'] = self.loss_scaler
|
||||
state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale
|
||||
state_dict['overflow'] = self.overflow
|
||||
state_dict['first_closure_call_this_step'] = self.first_closure_call_this_step
|
||||
state_dict['optimizer_state_dict'] = self.optimizer.state_dict()
|
||||
return state_dict
|
||||
|
||||
def load_state_dict(self, state_dict):
|
||||
"""
|
||||
Loads a state_dict created by an earlier call to state_dict.
|
||||
|
||||
Untested.
|
||||
"""
|
||||
self.loss_scaler = state_dict['loss_scaler']
|
||||
self.dynamic_loss_scale = state_dict['dynamic_loss_scale']
|
||||
self.overflow = state_dict['overflow']
|
||||
self.first_closure_call_this_step = state_dict['first_closure_call_this_step']
|
||||
self.optimizer.load_state_dict(state_dict['optimizer_state_dict'])
|
||||
|
||||
def step(self, closure=None): # could add clip option.
|
||||
"""
|
||||
If no closure is supplied, step should be called after fp16_optimizer_obj.backward(loss).
|
||||
step updates the fp32 master copy of parameters using the optimizer supplied to
|
||||
FP16_Optimizer's constructor, then copies the updated fp32 params into the fp16 params
|
||||
originally referenced by Fp16_Optimizer's constructor, so the user may immediately run
|
||||
another forward pass using their model.
|
||||
|
||||
If a closure is supplied, step may be called without a prior call to self.backward(loss).
|
||||
However, the user should take care that any loss.backward() call within the closure
|
||||
has been replaced by fp16_optimizer_obj.backward(loss).
|
||||
|
||||
Args:
|
||||
closure (optional): Closure that will be supplied to the underlying optimizer originally passed to FP16_Optimizer's constructor. closure should call zero_grad on the FP16_Optimizer object, compute the loss, call .backward(loss), and return the loss.
|
||||
|
||||
Closure example::
|
||||
|
||||
# optimizer is assumed to be an FP16_Optimizer object, previously constructed from an
|
||||
# existing pytorch optimizer.
|
||||
for input, target in dataset:
|
||||
def closure():
|
||||
optimizer.zero_grad()
|
||||
output = model(input)
|
||||
loss = loss_fn(output, target)
|
||||
optimizer.backward(loss)
|
||||
return loss
|
||||
optimizer.step(closure)
|
||||
|
||||
.. note::
|
||||
The only changes that need to be made compared to
|
||||
`ordinary optimizer closures`_ are that "optimizer" itself should be an instance of
|
||||
FP16_Optimizer, and that the call to loss.backward should be replaced by
|
||||
optimizer.backward(loss).
|
||||
|
||||
.. warning::
|
||||
Currently, calling step with a closure is not compatible with dynamic loss scaling.
|
||||
|
||||
.. _`ordinary optimizer closures`:
|
||||
http://pytorch.org/docs/master/optim.html#optimizer-step-closure
|
||||
"""
|
||||
if closure is not None and isinstance(self.loss_scaler, DynamicLossScaler):
|
||||
raise TypeError("Using step with a closure is currently not "
|
||||
"compatible with dynamic loss scaling.")
|
||||
|
||||
scale = self.loss_scaler.loss_scale
|
||||
self._update_scale(self.overflow)
|
||||
|
||||
if self.overflow:
|
||||
print("OVERFLOW! Skipping step. Attempted loss scale: {}".format(scale))
|
||||
return
|
||||
|
||||
if closure is not None:
|
||||
self._step_with_closure(closure)
|
||||
else:
|
||||
self.optimizer.step()
|
||||
|
||||
self._copy_params_fp32_to_fp16()
|
||||
|
||||
return
|
||||
|
||||
def _step_with_closure(self, closure):
|
||||
def wrapped_closure():
|
||||
if self.first_closure_call_this_step:
|
||||
"""
|
||||
We expect that the fp16 params are initially fresh on entering self.step(),
|
||||
so _copy_params_fp32_to_fp16() is unnecessary the first time wrapped_closure()
|
||||
is called within self.optimizer.step().
|
||||
"""
|
||||
self.first_closure_call_this_step = False
|
||||
else:
|
||||
"""
|
||||
If self.optimizer.step() internally calls wrapped_closure more than once,
|
||||
it may update the fp32 params after each call. However, self.optimizer
|
||||
doesn't know about the fp16 params at all. If the fp32 params get updated,
|
||||
we can't rely on self.optimizer to refresh the fp16 params. We need
|
||||
to handle that manually:
|
||||
"""
|
||||
self._copy_params_fp32_to_fp16()
|
||||
|
||||
"""
|
||||
Our API expects the user to give us ownership of the backward() call by
|
||||
replacing all calls to loss.backward() with optimizer.backward(loss).
|
||||
This requirement holds whether or not the call to backward() is made within
|
||||
a closure.
|
||||
If the user is properly calling optimizer.backward(loss) within "closure,"
|
||||
calling closure() here will give the fp32 master params fresh gradients
|
||||
for the optimizer to play with,
|
||||
so all wrapped_closure needs to do is call closure() and return the loss.
|
||||
"""
|
||||
temp_loss = closure()
|
||||
return temp_loss
|
||||
|
||||
self.optimizer.step(wrapped_closure)
|
||||
|
||||
self.first_closure_call_this_step = True
|
||||
|
||||
def backward(self, loss, update_fp32_grads=True):
|
||||
"""
|
||||
fp16_optimizer_obj.backward performs the following conceptual operations:
|
||||
|
||||
fp32_loss = loss.float() (see first Note below)
|
||||
|
||||
scaled_loss = fp32_loss*loss_scale
|
||||
|
||||
scaled_loss.backward(), which accumulates scaled gradients into the .grad attributes of the
|
||||
fp16 model's leaves.
|
||||
|
||||
fp16 grads are then copied to the stored fp32 params' .grad attributes (see second Note).
|
||||
|
||||
Finally, fp32 grads are divided by loss_scale.
|
||||
|
||||
In this way, after fp16_optimizer_obj.backward, the fp32 parameters have fresh gradients,
|
||||
and fp16_optimizer_obj.step may be called.
|
||||
|
||||
.. note::
|
||||
Converting the loss to fp32 before applying the loss scale provides some
|
||||
additional safety against overflow if the user has supplied an fp16 value.
|
||||
However, for maximum overflow safety, the user should
|
||||
compute the loss criterion (MSE, cross entropy, etc) in fp32 before supplying it to
|
||||
fp16_optimizer_obj.backward.
|
||||
|
||||
.. note::
|
||||
The gradients found in an fp16 model's leaves after a call to
|
||||
fp16_optimizer_obj.backward should not be regarded as valid in general,
|
||||
because it's possible
|
||||
they have been scaled (and in the case of dynamic loss scaling,
|
||||
the scale factor may silently change over time).
|
||||
If the user wants to inspect gradients after a call to fp16_optimizer_obj.backward,
|
||||
he/she should query the .grad attribute of FP16_Optimizer's stored fp32 parameters.
|
||||
|
||||
Args:
|
||||
loss: The loss output by the user's model. loss may be either float or half (but see first Note above).
|
||||
update_fp32_grads (bool, optional, default=True): Option to copy fp16 grads to fp32 grads on this call. By setting this to False, the user can delay this copy, which is useful to eliminate redundant fp16->fp32 grad copies if fp16_optimizer_obj.backward is being called on multiple losses in one iteration. If set to False, the user becomes responsible for calling fp16_optimizer_obj.update_fp32_grads before calling fp16_optimizer_obj.step.
|
||||
|
||||
Example::
|
||||
|
||||
# Ordinary operation:
|
||||
optimizer.backward(loss)
|
||||
|
||||
# Naive operation with multiple losses (technically valid, but less efficient):
|
||||
# fp32 grads will be correct after the second call, but
|
||||
# the first call incurs an unnecessary fp16->fp32 grad copy.
|
||||
optimizer.backward(loss1)
|
||||
optimizer.backward(loss2)
|
||||
|
||||
# More efficient way to handle multiple losses:
|
||||
# The fp16->fp32 grad copy is delayed until fp16 grads from all
|
||||
# losses have been accumulated.
|
||||
optimizer.backward(loss1, update_fp32_grads=False)
|
||||
optimizer.backward(loss2, update_fp32_grads=False)
|
||||
optimizer.update_fp32_grads()
|
||||
"""
|
||||
self.loss_scaler.backward(loss.float())
|
||||
if update_fp32_grads:
|
||||
self.update_fp32_grads()
|
||||
|
||||
def update_fp32_grads(self):
|
||||
"""
|
||||
Copy the .grad attribute from stored references to fp16 parameters to
|
||||
the .grad attribute of the master fp32 parameters that are directly
|
||||
updated by the optimizer. :attr:`update_fp32_grads` only needs to be called if
|
||||
fp16_optimizer_obj.backward was called with update_fp32_grads=False.
|
||||
"""
|
||||
if self.dynamic_loss_scale:
|
||||
self._check_overflow()
|
||||
if self.overflow: return
|
||||
self._copy_grads_fp16_to_fp32()
|
||||
self._downscale_fp32()
|
||||
|
||||
@property
|
||||
def loss_scale(self):
|
||||
return self.loss_scaler.loss_scale
|
||||
327
glow/__init__.py
327
glow/__init__.py
@@ -1,327 +0,0 @@
|
||||
# *****************************************************************************
|
||||
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
# * Neither the name of the NVIDIA CORPORATION nor the
|
||||
# names of its contributors may be used to endorse or promote products
|
||||
# derived from this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
|
||||
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
# *****************************************************************************
|
||||
import copy
|
||||
import torch
|
||||
from torch.autograd import Variable
|
||||
import torch.nn.functional as F
|
||||
|
||||
DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
||||
|
||||
@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.nn.functional.tanh(in_act[:, :n_channels_int, :])
|
||||
s_act = torch.nn.functional.sigmoid(in_act[:, n_channels_int:, :])
|
||||
acts = t_act * s_act
|
||||
return acts
|
||||
|
||||
|
||||
class WaveGlowLoss(torch.nn.Module):
|
||||
def __init__(self, sigma=1.0):
|
||||
super(WaveGlowLoss, self).__init__()
|
||||
self.sigma = sigma
|
||||
|
||||
def forward(self, model_output):
|
||||
z, log_s_list, log_det_W_list = model_output
|
||||
for i, log_s in enumerate(log_s_list):
|
||||
if i == 0:
|
||||
log_s_total = torch.sum(log_s)
|
||||
log_det_W_total = log_det_W_list[i]
|
||||
else:
|
||||
log_s_total = log_s_total + torch.sum(log_s)
|
||||
log_det_W_total += log_det_W_list[i]
|
||||
|
||||
loss = torch.sum(z*z)/(2*self.sigma*self.sigma) - log_s_total - log_det_W_total
|
||||
return loss/(z.size(0)*z.size(1)*z.size(2))
|
||||
|
||||
|
||||
class Invertible1x1Conv(torch.nn.Module):
|
||||
"""
|
||||
The layer outputs both the convolution, and the log determinant
|
||||
of its weight matrix. If reverse=True it does convolution with
|
||||
inverse
|
||||
"""
|
||||
def __init__(self, c):
|
||||
super(Invertible1x1Conv, self).__init__()
|
||||
self.conv = torch.nn.Conv1d(c, c, kernel_size=1, stride=1, padding=0,
|
||||
bias=False)
|
||||
|
||||
# Sample a random orthonormal matrix to initialize weights
|
||||
W = torch.qr(torch.FloatTensor(c, c).normal_())[0]
|
||||
|
||||
# Ensure determinant is 1.0 not -1.0
|
||||
if torch.det(W) < 0:
|
||||
W[:,0] = -1*W[:,0]
|
||||
W = W.view(c, c, 1)
|
||||
self.conv.weight.data = W
|
||||
|
||||
def forward(self, z, reverse=False):
|
||||
# shape
|
||||
batch_size, group_size, n_of_groups = z.size()
|
||||
|
||||
W = self.conv.weight.squeeze()
|
||||
|
||||
if reverse:
|
||||
if not hasattr(self, 'W_inverse'):
|
||||
# Reverse computation
|
||||
W_inverse = W.float().inverse()
|
||||
W_inverse = Variable(W_inverse[..., None])
|
||||
if z.type() == 'torch.cuda.HalfTensor' or z.type() == 'torch.HalfTensor':
|
||||
W_inverse = W_inverse.half()
|
||||
self.W_inverse = W_inverse
|
||||
z = F.conv1d(z, self.W_inverse, bias=None, stride=1, padding=0)
|
||||
return z
|
||||
else:
|
||||
# Forward computation
|
||||
log_det_W = batch_size * n_of_groups * torch.logdet(W)
|
||||
z = self.conv(z)
|
||||
return z, log_det_W
|
||||
|
||||
|
||||
class WN(torch.nn.Module):
|
||||
"""
|
||||
This is the WaveNet like layer for the affine coupling. The primary difference
|
||||
from WaveNet is the convolutions need not be causal. There is also no dilation
|
||||
size reset. The dilation only doubles on each layer
|
||||
"""
|
||||
def __init__(self, n_in_channels, n_mel_channels, n_layers, n_channels,
|
||||
kernel_size):
|
||||
super(WN, self).__init__()
|
||||
assert(kernel_size % 2 == 1)
|
||||
assert(n_channels % 2 == 0)
|
||||
self.n_layers = n_layers
|
||||
self.n_channels = n_channels
|
||||
self.in_layers = torch.nn.ModuleList()
|
||||
self.res_skip_layers = torch.nn.ModuleList()
|
||||
self.cond_layers = torch.nn.ModuleList()
|
||||
|
||||
start = torch.nn.Conv1d(n_in_channels, n_channels, 1)
|
||||
start = torch.nn.utils.weight_norm(start, name='weight')
|
||||
self.start = start
|
||||
|
||||
# Initializing last layer to 0 makes the affine coupling layers
|
||||
# do nothing at first. This helps with training stability
|
||||
end = torch.nn.Conv1d(n_channels, 2*n_in_channels, 1)
|
||||
end.weight.data.zero_()
|
||||
end.bias.data.zero_()
|
||||
self.end = end
|
||||
|
||||
for i in range(n_layers):
|
||||
dilation = 2 ** i
|
||||
padding = int((kernel_size*dilation - dilation)/2)
|
||||
in_layer = torch.nn.Conv1d(n_channels, 2*n_channels, kernel_size,
|
||||
dilation=dilation, padding=padding)
|
||||
in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
|
||||
self.in_layers.append(in_layer)
|
||||
|
||||
cond_layer = torch.nn.Conv1d(n_mel_channels, 2*n_channels, 1)
|
||||
cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
|
||||
self.cond_layers.append(cond_layer)
|
||||
|
||||
# last one is not necessary
|
||||
if i < n_layers - 1:
|
||||
res_skip_channels = 2*n_channels
|
||||
else:
|
||||
res_skip_channels = n_channels
|
||||
res_skip_layer = torch.nn.Conv1d(n_channels, res_skip_channels, 1)
|
||||
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
|
||||
self.res_skip_layers.append(res_skip_layer)
|
||||
|
||||
def forward(self, forward_input):
|
||||
audio, spect = forward_input
|
||||
audio = self.start(audio)
|
||||
|
||||
for i in range(self.n_layers):
|
||||
acts = fused_add_tanh_sigmoid_multiply(
|
||||
self.in_layers[i](audio),
|
||||
self.cond_layers[i](spect),
|
||||
torch.IntTensor([self.n_channels]))
|
||||
|
||||
res_skip_acts = self.res_skip_layers[i](acts)
|
||||
if i < self.n_layers - 1:
|
||||
audio = res_skip_acts[:,:self.n_channels,:] + audio
|
||||
skip_acts = res_skip_acts[:,self.n_channels:,:]
|
||||
else:
|
||||
skip_acts = res_skip_acts
|
||||
|
||||
if i == 0:
|
||||
output = skip_acts
|
||||
else:
|
||||
output = skip_acts + output
|
||||
return self.end(output)
|
||||
|
||||
|
||||
class WaveGlow(torch.nn.Module):
|
||||
def __init__(self, n_mel_channels, n_flows, n_group, n_early_every,
|
||||
n_early_size, WN_config):
|
||||
super(WaveGlow, self).__init__()
|
||||
|
||||
self.upsample = torch.nn.ConvTranspose1d(n_mel_channels,
|
||||
n_mel_channels,
|
||||
1024, stride=256)
|
||||
assert(n_group % 2 == 0)
|
||||
self.n_flows = n_flows
|
||||
self.n_group = n_group
|
||||
self.n_early_every = n_early_every
|
||||
self.n_early_size = n_early_size
|
||||
self.WN = torch.nn.ModuleList()
|
||||
self.convinv = torch.nn.ModuleList()
|
||||
|
||||
n_half = int(n_group/2)
|
||||
|
||||
# Set up layers with the right sizes based on how many dimensions
|
||||
# have been output already
|
||||
n_remaining_channels = n_group
|
||||
for k in range(n_flows):
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
n_half = n_half - int(self.n_early_size/2)
|
||||
n_remaining_channels = n_remaining_channels - self.n_early_size
|
||||
self.convinv.append(Invertible1x1Conv(n_remaining_channels))
|
||||
self.WN.append(WN(n_half, n_mel_channels*n_group, **WN_config))
|
||||
self.n_remaining_channels = n_remaining_channels # Useful during inference
|
||||
|
||||
def forward(self, forward_input):
|
||||
"""
|
||||
forward_input[0] = mel_spectrogram: batch x n_mel_channels x frames
|
||||
forward_input[1] = audio: batch x time
|
||||
"""
|
||||
spect, audio = forward_input
|
||||
|
||||
# Upsample spectrogram to size of audio
|
||||
spect = self.upsample(spect)
|
||||
assert(spect.size(2) >= audio.size(1))
|
||||
if spect.size(2) > audio.size(1):
|
||||
spect = spect[:, :, :audio.size(1)]
|
||||
|
||||
spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3)
|
||||
spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1)
|
||||
|
||||
audio = audio.unfold(1, self.n_group, self.n_group).permute(0, 2, 1)
|
||||
output_audio = []
|
||||
log_s_list = []
|
||||
log_det_W_list = []
|
||||
|
||||
for k in range(self.n_flows):
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
output_audio.append(audio[:,:self.n_early_size,:])
|
||||
audio = audio[:,self.n_early_size:,:]
|
||||
|
||||
audio, log_det_W = self.convinv[k](audio)
|
||||
log_det_W_list.append(log_det_W)
|
||||
|
||||
n_half = int(audio.size(1)/2)
|
||||
audio_0 = audio[:,:n_half,:]
|
||||
audio_1 = audio[:,n_half:,:]
|
||||
|
||||
output = self.WN[k]((audio_0, spect))
|
||||
log_s = output[:, n_half:, :]
|
||||
b = output[:, :n_half, :]
|
||||
audio_1 = torch.exp(log_s)*audio_1 + b
|
||||
log_s_list.append(log_s)
|
||||
|
||||
audio = torch.cat([audio_0, audio_1],1)
|
||||
|
||||
output_audio.append(audio)
|
||||
return torch.cat(output_audio,1), log_s_list, log_det_W_list
|
||||
|
||||
def infer(self, spect, sigma=1.0):
|
||||
spect = self.upsample(spect)
|
||||
# trim conv artifacts. maybe pad spec to kernel multiple
|
||||
time_cutoff = self.upsample.kernel_size[0] - self.upsample.stride[0]
|
||||
spect = spect[:, :, :-time_cutoff]
|
||||
|
||||
spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3)
|
||||
spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1)
|
||||
|
||||
if torch.cuda.is_available():
|
||||
if spect.type() == 'torch.cuda.HalfTensor':
|
||||
audio = torch.cuda.HalfTensor(spect.size(0),
|
||||
self.n_remaining_channels,
|
||||
spect.size(2)).normal_()
|
||||
else:
|
||||
audio = torch.cuda.FloatTensor(spect.size(0),
|
||||
self.n_remaining_channels,
|
||||
spect.size(2)).normal_()
|
||||
else:
|
||||
if spect.type() == 'torch.HalfTensor':
|
||||
audio = torch.HalfTensor(spect.size(0),
|
||||
self.n_remaining_channels,
|
||||
spect.size(2)).normal_()
|
||||
else:
|
||||
audio = torch.FloatTensor(spect.size(0),
|
||||
self.n_remaining_channels,
|
||||
spect.size(2)).normal_()
|
||||
|
||||
audio = torch.autograd.Variable(sigma*audio)
|
||||
|
||||
for k in reversed(range(self.n_flows)):
|
||||
n_half = int(audio.size(1)/2)
|
||||
audio_0 = audio[:,:n_half,:]
|
||||
audio_1 = audio[:,n_half:,:]
|
||||
|
||||
output = self.WN[k]((audio_0, spect))
|
||||
s = output[:, n_half:, :]
|
||||
b = output[:, :n_half, :]
|
||||
audio_1 = (audio_1 - b)/torch.exp(s)
|
||||
audio = torch.cat([audio_0, audio_1],1)
|
||||
|
||||
audio = self.convinv[k](audio, reverse=True)
|
||||
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
if torch.cuda.is_available():
|
||||
if spect.type() == 'torch.cuda.HalfTensor':
|
||||
z = torch.cuda.HalfTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_()
|
||||
else:
|
||||
z = torch.cuda.FloatTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_()
|
||||
else:
|
||||
if spect.type() == 'torch.HalfTensor':
|
||||
z = torch.HalfTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_()
|
||||
else:
|
||||
z = torch.FloatTensor(spect.size(0), self.n_early_size, spect.size(2)).normal_()
|
||||
audio = torch.cat((sigma*z, audio),1)
|
||||
|
||||
audio = audio.permute(0,2,1).contiguous().view(audio.size(0), -1).data
|
||||
return audio
|
||||
|
||||
@staticmethod
|
||||
def remove_weightnorm(model):
|
||||
waveglow = model
|
||||
for WN in waveglow.WN:
|
||||
WN.start = torch.nn.utils.remove_weight_norm(WN.start)
|
||||
WN.in_layers = remove(WN.in_layers)
|
||||
WN.cond_layers = remove(WN.cond_layers)
|
||||
WN.res_skip_layers = remove(WN.res_skip_layers)
|
||||
return waveglow
|
||||
|
||||
|
||||
def remove(conv_list):
|
||||
new_conv_list = torch.nn.ModuleList()
|
||||
for old_conv in conv_list:
|
||||
old_conv = torch.nn.utils.remove_weight_norm(old_conv)
|
||||
new_conv_list.append(old_conv)
|
||||
return new_conv_list
|
||||
349
glow_old.py
349
glow_old.py
@@ -1,349 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# *****************************************************************************
|
||||
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
# * Neither the name of the NVIDIA CORPORATION nor the
|
||||
# names of its contributors may be used to endorse or promote products
|
||||
# derived from this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
# ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
|
||||
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
# *****************************************************************************
|
||||
import torch
|
||||
from torch.autograd import Variable
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
@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.nn.functional.tanh(in_act[:, :n_channels_int, :])
|
||||
s_act = torch.nn.functional.sigmoid(in_act[:, n_channels_int:, :])
|
||||
acts = t_act * s_act
|
||||
return acts
|
||||
|
||||
|
||||
class WaveGlowLoss(torch.nn.Module):
|
||||
def __init__(self, sigma=1.0):
|
||||
super(WaveGlowLoss, self).__init__()
|
||||
self.sigma = sigma
|
||||
|
||||
def forward(self, model_output):
|
||||
z, log_s_list, log_det_W_list = model_output
|
||||
for i, log_s in enumerate(log_s_list):
|
||||
if i == 0:
|
||||
log_s_total = torch.sum(log_s)
|
||||
log_det_W_total = log_det_W_list[i]
|
||||
else:
|
||||
log_s_total = log_s_total + torch.sum(log_s)
|
||||
log_det_W_total += log_det_W_list[i]
|
||||
|
||||
loss = (
|
||||
torch.sum(z * z) / (2 * self.sigma * self.sigma)
|
||||
- log_s_total
|
||||
- log_det_W_total
|
||||
)
|
||||
return loss / (z.size(0) * z.size(1) * z.size(2))
|
||||
|
||||
|
||||
class Invertible1x1Conv(torch.nn.Module):
|
||||
"""
|
||||
The layer outputs both the convolution, and the log determinant
|
||||
of its weight matrix. If reverse=True it does convolution with
|
||||
inverse
|
||||
"""
|
||||
|
||||
def __init__(self, c):
|
||||
super(Invertible1x1Conv, self).__init__()
|
||||
self.conv = torch.nn.Conv1d(
|
||||
c, c, kernel_size=1, stride=1, padding=0, bias=False
|
||||
)
|
||||
|
||||
# Sample a random orthonormal matrix to initialize weights
|
||||
W = torch.qr(torch.FloatTensor(c, c).normal_())[0]
|
||||
|
||||
# Ensure determinant is 1.0 not -1.0
|
||||
if torch.det(W) < 0:
|
||||
W[:, 0] = -1 * W[:, 0]
|
||||
W = W.view(c, c, 1)
|
||||
self.conv.weight.data = W
|
||||
|
||||
def forward(self, z, reverse=False):
|
||||
# shape
|
||||
batch_size, group_size, n_of_groups = z.size()
|
||||
|
||||
W = self.conv.weight.squeeze()
|
||||
|
||||
if reverse:
|
||||
if not hasattr(self, "W_inverse"):
|
||||
# Reverse computation
|
||||
W_inverse = W.inverse()
|
||||
W_inverse = Variable(W_inverse[..., None])
|
||||
if z.type() == "torch.cuda.HalfTensor":
|
||||
W_inverse = W_inverse.half()
|
||||
self.W_inverse = W_inverse
|
||||
z = F.conv1d(z, self.W_inverse, bias=None, stride=1, padding=0)
|
||||
return z
|
||||
else:
|
||||
# Forward computation
|
||||
log_det_W = batch_size * n_of_groups * torch.logdet(W)
|
||||
z = self.conv(z)
|
||||
return z, log_det_W
|
||||
|
||||
|
||||
class WN(torch.nn.Module):
|
||||
"""
|
||||
This is the WaveNet like layer for the affine coupling. The primary
|
||||
difference from WaveNet is the convolutions need not be causal. There is
|
||||
also no dilation size reset. The dilation only doubles on each layer
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, n_in_channels, n_mel_channels, n_layers, n_channels, kernel_size
|
||||
):
|
||||
super(WN, self).__init__()
|
||||
assert kernel_size % 2 == 1
|
||||
assert n_channels % 2 == 0
|
||||
self.n_layers = n_layers
|
||||
self.n_channels = n_channels
|
||||
self.in_layers = torch.nn.ModuleList()
|
||||
self.res_skip_layers = torch.nn.ModuleList()
|
||||
self.cond_layers = torch.nn.ModuleList()
|
||||
|
||||
start = torch.nn.Conv1d(n_in_channels, n_channels, 1)
|
||||
start = torch.nn.utils.weight_norm(start, name="weight")
|
||||
self.start = start
|
||||
|
||||
# Initializing last layer to 0 makes the affine coupling layers
|
||||
# do nothing at first. This helps with training stability
|
||||
end = torch.nn.Conv1d(n_channels, 2 * n_in_channels, 1)
|
||||
end.weight.data.zero_()
|
||||
end.bias.data.zero_()
|
||||
self.end = end
|
||||
|
||||
for i in range(n_layers):
|
||||
dilation = 2 ** i
|
||||
padding = int((kernel_size * dilation - dilation) / 2)
|
||||
in_layer = torch.nn.Conv1d(
|
||||
n_channels,
|
||||
2 * n_channels,
|
||||
kernel_size,
|
||||
dilation=dilation,
|
||||
padding=padding,
|
||||
)
|
||||
in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
|
||||
self.in_layers.append(in_layer)
|
||||
|
||||
cond_layer = torch.nn.Conv1d(n_mel_channels, 2 * n_channels, 1)
|
||||
cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
|
||||
self.cond_layers.append(cond_layer)
|
||||
|
||||
# last one is not necessary
|
||||
if i < n_layers - 1:
|
||||
res_skip_channels = 2 * n_channels
|
||||
else:
|
||||
res_skip_channels = n_channels
|
||||
res_skip_layer = torch.nn.Conv1d(n_channels, res_skip_channels, 1)
|
||||
res_skip_layer = torch.nn.utils.weight_norm(
|
||||
res_skip_layer, name="weight"
|
||||
)
|
||||
self.res_skip_layers.append(res_skip_layer)
|
||||
|
||||
def forward(self, forward_input):
|
||||
audio, spect = forward_input
|
||||
audio = self.start(audio)
|
||||
for i in range(self.n_layers):
|
||||
acts = fused_add_tanh_sigmoid_multiply(
|
||||
self.in_layers[i](audio),
|
||||
self.cond_layers[i](spect),
|
||||
torch.IntTensor([self.n_channels]),
|
||||
)
|
||||
|
||||
res_skip_acts = self.res_skip_layers[i](acts)
|
||||
if i < self.n_layers - 1:
|
||||
audio = res_skip_acts[:, : self.n_channels, :] + audio
|
||||
skip_acts = res_skip_acts[:, self.n_channels :, :]
|
||||
else:
|
||||
skip_acts = res_skip_acts
|
||||
|
||||
if i == 0:
|
||||
output = skip_acts
|
||||
else:
|
||||
output = skip_acts + output
|
||||
return self.end(output)
|
||||
|
||||
|
||||
class WaveGlow(torch.nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
n_mel_channels,
|
||||
n_flows,
|
||||
n_group,
|
||||
n_early_every,
|
||||
n_early_size,
|
||||
WN_config,
|
||||
):
|
||||
super(WaveGlow, self).__init__()
|
||||
|
||||
self.upsample = torch.nn.ConvTranspose1d(
|
||||
n_mel_channels, n_mel_channels, 1024, stride=256
|
||||
)
|
||||
assert n_group % 2 == 0
|
||||
self.n_flows = n_flows
|
||||
self.n_group = n_group
|
||||
self.n_early_every = n_early_every
|
||||
self.n_early_size = n_early_size
|
||||
self.WN = torch.nn.ModuleList()
|
||||
self.convinv = torch.nn.ModuleList()
|
||||
|
||||
n_half = int(n_group / 2)
|
||||
|
||||
# Set up layers with the right sizes based on how many dimensions
|
||||
# have been output already
|
||||
n_remaining_channels = n_group
|
||||
for k in range(n_flows):
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
n_half = n_half - int(self.n_early_size / 2)
|
||||
n_remaining_channels = n_remaining_channels - self.n_early_size
|
||||
self.convinv.append(Invertible1x1Conv(n_remaining_channels))
|
||||
self.WN.append(WN(n_half, n_mel_channels * n_group, **WN_config))
|
||||
self.n_remaining_channels = n_remaining_channels
|
||||
# Useful during inference
|
||||
|
||||
def forward(self, forward_input):
|
||||
"""
|
||||
forward_input[0] = mel_spectrogram: batch x n_mel_channels x frames
|
||||
forward_input[1] = audio: batch x time
|
||||
"""
|
||||
spect, audio = forward_input
|
||||
|
||||
# Upsample spectrogram to size of audio
|
||||
spect = self.upsample(spect)
|
||||
assert spect.size(2) >= audio.size(1)
|
||||
if spect.size(2) > audio.size(1):
|
||||
spect = spect[:, :, : audio.size(1)]
|
||||
|
||||
spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3)
|
||||
spect = (
|
||||
spect.contiguous()
|
||||
.view(spect.size(0), spect.size(1), -1)
|
||||
.permute(0, 2, 1)
|
||||
)
|
||||
|
||||
audio = audio.unfold(1, self.n_group, self.n_group).permute(0, 2, 1)
|
||||
output_audio = []
|
||||
log_s_list = []
|
||||
log_det_W_list = []
|
||||
|
||||
for k in range(self.n_flows):
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
output_audio.append(audio[:, : self.n_early_size, :])
|
||||
audio = audio[:, self.n_early_size :, :]
|
||||
|
||||
audio, log_det_W = self.convinv[k](audio)
|
||||
log_det_W_list.append(log_det_W)
|
||||
|
||||
n_half = int(audio.size(1) / 2)
|
||||
audio_0 = audio[:, :n_half, :]
|
||||
audio_1 = audio[:, n_half:, :]
|
||||
|
||||
output = self.WN[k]((audio_0, spect))
|
||||
log_s = output[:, n_half:, :]
|
||||
b = output[:, :n_half, :]
|
||||
audio_1 = torch.exp(log_s) * audio_1 + b
|
||||
log_s_list.append(log_s)
|
||||
|
||||
audio = torch.cat([audio_0, audio_1], 1)
|
||||
|
||||
output_audio.append(audio)
|
||||
return torch.cat(output_audio, 1), log_s_list, log_det_W_list
|
||||
|
||||
def infer(self, spect, sigma=1.0):
|
||||
spect = self.upsample(spect)
|
||||
# trim conv artifacts. maybe pad spec to kernel multiple
|
||||
time_cutoff = self.upsample.kernel_size[0] - self.upsample.stride[0]
|
||||
spect = spect[:, :, :-time_cutoff]
|
||||
|
||||
spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3)
|
||||
spect = (
|
||||
spect.contiguous()
|
||||
.view(spect.size(0), spect.size(1), -1)
|
||||
.permute(0, 2, 1)
|
||||
)
|
||||
|
||||
if spect.type() == "torch.cuda.HalfTensor":
|
||||
audio = torch.cuda.HalfTensor(
|
||||
spect.size(0), self.n_remaining_channels, spect.size(2)
|
||||
).normal_()
|
||||
else:
|
||||
# cuda.FloatTensor -> FloatTensor
|
||||
audio = torch.FloatTensor(
|
||||
spect.size(0), self.n_remaining_channels, spect.size(2)
|
||||
).normal_()
|
||||
|
||||
audio = torch.autograd.Variable(sigma * audio)
|
||||
|
||||
for k in reversed(range(self.n_flows)):
|
||||
n_half = int(audio.size(1) / 2)
|
||||
audio_0 = audio[:, :n_half, :]
|
||||
audio_1 = audio[:, n_half:, :]
|
||||
|
||||
output = self.WN[k]((audio_0, spect))
|
||||
s = output[:, n_half:, :]
|
||||
b = output[:, :n_half, :]
|
||||
audio_1 = (audio_1 - b) / torch.exp(s)
|
||||
audio = torch.cat([audio_0, audio_1], 1)
|
||||
|
||||
audio = self.convinv[k](audio, reverse=True)
|
||||
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
if spect.type() == "torch.cuda.HalfTensor":
|
||||
z = torch.cuda.HalfTensor(
|
||||
spect.size(0), self.n_early_size, spect.size(2)
|
||||
).normal_()
|
||||
else:
|
||||
# cuda.FloatTensor -> FloatTensor
|
||||
z = torch.FloatTensor(
|
||||
spect.size(0), self.n_early_size, spect.size(2)
|
||||
).normal_()
|
||||
audio = torch.cat((sigma * z, audio), 1)
|
||||
|
||||
audio = (
|
||||
audio.permute(0, 2, 1).contiguous().view(audio.size(0), -1).data
|
||||
)
|
||||
return audio
|
||||
|
||||
@staticmethod
|
||||
def remove_weightnorm(model):
|
||||
waveglow = model
|
||||
for WN in waveglow.WN:
|
||||
WN.start = torch.nn.utils.remove_weight_norm(WN.start)
|
||||
WN.in_layers = remove(WN.in_layers)
|
||||
WN.cond_layers = remove(WN.cond_layers)
|
||||
WN.res_skip_layers = remove(WN.res_skip_layers)
|
||||
return waveglow
|
||||
|
||||
|
||||
def remove(conv_list):
|
||||
new_conv_list = torch.nn.ModuleList()
|
||||
for old_conv in conv_list:
|
||||
old_conv = torch.nn.utils.remove_weight_norm(old_conv)
|
||||
new_conv_list.append(old_conv)
|
||||
return new_conv_list
|
||||
94
hparams.py
Normal file
94
hparams.py
Normal file
@@ -0,0 +1,94 @@
|
||||
import tensorflow as tf
|
||||
from text import symbols
|
||||
|
||||
|
||||
def create_hparams(hparams_string=None, verbose=False):
|
||||
"""Create model hyperparameters. Parse nondefault from given string."""
|
||||
|
||||
hparams = tf.contrib.training.HParams(
|
||||
################################
|
||||
# Experiment Parameters #
|
||||
################################
|
||||
epochs=500,
|
||||
iters_per_checkpoint=1000,
|
||||
seed=1234,
|
||||
dynamic_loss_scaling=True,
|
||||
fp16_run=False,
|
||||
distributed_run=False,
|
||||
dist_backend="nccl",
|
||||
dist_url="file://distributed.dpt",
|
||||
cudnn_enabled=True,
|
||||
cudnn_benchmark=False,
|
||||
|
||||
################################
|
||||
# Data Parameters #
|
||||
################################
|
||||
load_mel_from_disk=False,
|
||||
training_files='filelists/ljs_audio22khz_text_train_filelist.txt',
|
||||
validation_files='filelists/ljs_audio22khz_text_val_filelist.txt',
|
||||
text_cleaners=['english_cleaners'],
|
||||
|
||||
################################
|
||||
# Audio Parameters #
|
||||
################################
|
||||
max_wav_value=32768.0,
|
||||
sampling_rate=22050,
|
||||
filter_length=1024,
|
||||
hop_length=256,
|
||||
win_length=1024,
|
||||
n_mel_channels=80,
|
||||
mel_fmin=0.0,
|
||||
mel_fmax=8000.0,
|
||||
|
||||
################################
|
||||
# Model Parameters #
|
||||
################################
|
||||
n_symbols=len(symbols),
|
||||
symbols_embedding_dim=512,
|
||||
|
||||
# Encoder parameters
|
||||
encoder_kernel_size=5,
|
||||
encoder_n_convolutions=3,
|
||||
encoder_embedding_dim=512,
|
||||
|
||||
# Decoder parameters
|
||||
n_frames_per_step=1, # currently only 1 is supported
|
||||
decoder_rnn_dim=1024,
|
||||
prenet_dim=256,
|
||||
max_decoder_steps=1000,
|
||||
gate_threshold=0.5,
|
||||
p_attention_dropout=0.1,
|
||||
p_decoder_dropout=0.1,
|
||||
|
||||
# Attention parameters
|
||||
attention_rnn_dim=1024,
|
||||
attention_dim=128,
|
||||
|
||||
# Location Layer parameters
|
||||
attention_location_n_filters=32,
|
||||
attention_location_kernel_size=31,
|
||||
|
||||
# Mel-post processing network parameters
|
||||
postnet_embedding_dim=512,
|
||||
postnet_kernel_size=5,
|
||||
postnet_n_convolutions=5,
|
||||
|
||||
################################
|
||||
# Optimization Hyperparameters #
|
||||
################################
|
||||
use_saved_learning_rate=False,
|
||||
learning_rate=1e-3,
|
||||
weight_decay=1e-6,
|
||||
grad_clip_thresh=1.0,
|
||||
batch_size=64,
|
||||
mask_padding=True # set model's padded outputs to padded values
|
||||
)
|
||||
|
||||
if hparams_string:
|
||||
tf.logging.info('Parsing command line hparams: %s', hparams_string)
|
||||
hparams.parse(hparams_string)
|
||||
|
||||
if verbose:
|
||||
tf.logging.info('Final parsed hparams: %s', hparams.values())
|
||||
|
||||
return hparams
|
||||
246
inference.ipynb
Executable file
246
inference.ipynb
Executable file
File diff suppressed because one or more lines are too long
@@ -1,55 +1,38 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import torch
|
||||
from librosa.filters import mel as librosa_mel_fn
|
||||
from .audio_processing import dynamic_range_compression
|
||||
from .audio_processing import dynamic_range_decompression
|
||||
from .stft import STFT
|
||||
from audio_processing import dynamic_range_compression
|
||||
from audio_processing import dynamic_range_decompression
|
||||
from stft import STFT
|
||||
|
||||
|
||||
class LinearNorm(torch.nn.Module):
|
||||
def __init__(self, in_dim, out_dim, bias=True, w_init_gain="linear"):
|
||||
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
|
||||
super(LinearNorm, self).__init__()
|
||||
self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
|
||||
|
||||
torch.nn.init.xavier_uniform_(
|
||||
self.linear_layer.weight,
|
||||
gain=torch.nn.init.calculate_gain(w_init_gain),
|
||||
)
|
||||
gain=torch.nn.init.calculate_gain(w_init_gain))
|
||||
|
||||
def forward(self, x):
|
||||
return self.linear_layer(x)
|
||||
|
||||
|
||||
class ConvNorm(torch.nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size=1,
|
||||
stride=1,
|
||||
padding=None,
|
||||
dilation=1,
|
||||
bias=True,
|
||||
w_init_gain="linear",
|
||||
):
|
||||
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1,
|
||||
padding=None, dilation=1, bias=True, w_init_gain='linear'):
|
||||
super(ConvNorm, self).__init__()
|
||||
if padding is None:
|
||||
assert kernel_size % 2 == 1
|
||||
assert(kernel_size % 2 == 1)
|
||||
padding = int(dilation * (kernel_size - 1) / 2)
|
||||
|
||||
self.conv = torch.nn.Conv1d(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size=kernel_size,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=bias,
|
||||
)
|
||||
self.conv = torch.nn.Conv1d(in_channels, out_channels,
|
||||
kernel_size=kernel_size, stride=stride,
|
||||
padding=padding, dilation=dilation,
|
||||
bias=bias)
|
||||
|
||||
torch.nn.init.xavier_uniform_(
|
||||
self.conv.weight, gain=torch.nn.init.calculate_gain(w_init_gain)
|
||||
)
|
||||
self.conv.weight, gain=torch.nn.init.calculate_gain(w_init_gain))
|
||||
|
||||
def forward(self, signal):
|
||||
conv_signal = self.conv(signal)
|
||||
@@ -57,25 +40,17 @@ class ConvNorm(torch.nn.Module):
|
||||
|
||||
|
||||
class TacotronSTFT(torch.nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
filter_length=1024,
|
||||
hop_length=256,
|
||||
win_length=1024,
|
||||
n_mel_channels=80,
|
||||
sampling_rate=22050,
|
||||
mel_fmin=0.0,
|
||||
mel_fmax=8000.0,
|
||||
):
|
||||
def __init__(self, filter_length=1024, hop_length=256, win_length=1024,
|
||||
n_mel_channels=80, sampling_rate=22050, mel_fmin=0.0,
|
||||
mel_fmax=8000.0):
|
||||
super(TacotronSTFT, self).__init__()
|
||||
self.n_mel_channels = n_mel_channels
|
||||
self.sampling_rate = sampling_rate
|
||||
self.stft_fn = STFT(filter_length, hop_length, win_length)
|
||||
mel_basis = librosa_mel_fn(
|
||||
sampling_rate, filter_length, n_mel_channels, mel_fmin, mel_fmax
|
||||
)
|
||||
sampling_rate, filter_length, n_mel_channels, mel_fmin, mel_fmax)
|
||||
mel_basis = torch.from_numpy(mel_basis).float()
|
||||
self.register_buffer("mel_basis", mel_basis)
|
||||
self.register_buffer('mel_basis', mel_basis)
|
||||
|
||||
def spectral_normalize(self, magnitudes):
|
||||
output = dynamic_range_compression(magnitudes)
|
||||
@@ -95,8 +70,8 @@ class TacotronSTFT(torch.nn.Module):
|
||||
-------
|
||||
mel_output: torch.FloatTensor of shape (B, n_mel_channels, T)
|
||||
"""
|
||||
assert torch.min(y.data) >= -1
|
||||
assert torch.max(y.data) <= 1
|
||||
assert(torch.min(y.data) >= -1)
|
||||
assert(torch.max(y.data) <= 1)
|
||||
|
||||
magnitudes, phases = self.stft_fn.transform(y)
|
||||
magnitudes = magnitudes.data
|
||||
48
logger.py
Normal file
48
logger.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import random
|
||||
import torch.nn.functional as F
|
||||
from tensorboardX import SummaryWriter
|
||||
from plotting_utils import plot_alignment_to_numpy, plot_spectrogram_to_numpy
|
||||
from plotting_utils import plot_gate_outputs_to_numpy
|
||||
|
||||
|
||||
class Tacotron2Logger(SummaryWriter):
|
||||
def __init__(self, logdir):
|
||||
super(Tacotron2Logger, self).__init__(logdir)
|
||||
|
||||
def log_training(self, reduced_loss, grad_norm, learning_rate, duration,
|
||||
iteration):
|
||||
self.add_scalar("training.loss", reduced_loss, iteration)
|
||||
self.add_scalar("grad.norm", grad_norm, iteration)
|
||||
self.add_scalar("learning.rate", learning_rate, iteration)
|
||||
self.add_scalar("duration", duration, iteration)
|
||||
|
||||
def log_validation(self, reduced_loss, model, y, y_pred, iteration):
|
||||
self.add_scalar("validation.loss", reduced_loss, iteration)
|
||||
_, mel_outputs, gate_outputs, alignments = y_pred
|
||||
mel_targets, gate_targets = y
|
||||
|
||||
# plot distribution of parameters
|
||||
for tag, value in model.named_parameters():
|
||||
tag = tag.replace('.', '/')
|
||||
self.add_histogram(tag, value.data.cpu().numpy(), iteration)
|
||||
|
||||
# plot alignment, mel target and predicted, gate target and predicted
|
||||
idx = random.randint(0, alignments.size(0) - 1)
|
||||
self.add_image(
|
||||
"alignment",
|
||||
plot_alignment_to_numpy(alignments[idx].data.cpu().numpy().T),
|
||||
iteration)
|
||||
self.add_image(
|
||||
"mel_target",
|
||||
plot_spectrogram_to_numpy(mel_targets[idx].data.cpu().numpy()),
|
||||
iteration)
|
||||
self.add_image(
|
||||
"mel_predicted",
|
||||
plot_spectrogram_to_numpy(mel_outputs[idx].data.cpu().numpy()),
|
||||
iteration)
|
||||
self.add_image(
|
||||
"gate",
|
||||
plot_gate_outputs_to_numpy(
|
||||
gate_targets[idx].data.cpu().numpy(),
|
||||
F.sigmoid(gate_outputs[idx]).data.cpu().numpy()),
|
||||
iteration)
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from torch import nn
|
||||
|
||||
|
||||
@@ -14,8 +13,7 @@ class Tacotron2Loss(nn.Module):
|
||||
|
||||
mel_out, mel_out_postnet, gate_out, _ = model_output
|
||||
gate_out = gate_out.view(-1, 1)
|
||||
mel_loss = nn.MSELoss()(mel_out, mel_target) + nn.MSELoss()(
|
||||
mel_out_postnet, mel_target
|
||||
)
|
||||
mel_loss = nn.MSELoss()(mel_out, mel_target) + \
|
||||
nn.MSELoss()(mel_out_postnet, mel_target)
|
||||
gate_loss = nn.BCEWithLogitsLoss()(gate_out, gate_target)
|
||||
return mel_loss + gate_loss
|
||||
131
loss_scaler.py
Normal file
131
loss_scaler.py
Normal file
@@ -0,0 +1,131 @@
|
||||
import torch
|
||||
|
||||
class LossScaler:
|
||||
|
||||
def __init__(self, scale=1):
|
||||
self.cur_scale = scale
|
||||
|
||||
# `params` is a list / generator of torch.Variable
|
||||
def has_overflow(self, params):
|
||||
return False
|
||||
|
||||
# `x` is a torch.Tensor
|
||||
def _has_inf_or_nan(x):
|
||||
return False
|
||||
|
||||
# `overflow` is boolean indicating whether we overflowed in gradient
|
||||
def update_scale(self, overflow):
|
||||
pass
|
||||
|
||||
@property
|
||||
def loss_scale(self):
|
||||
return self.cur_scale
|
||||
|
||||
def scale_gradient(self, module, grad_in, grad_out):
|
||||
return tuple(self.loss_scale * g for g in grad_in)
|
||||
|
||||
def backward(self, loss):
|
||||
scaled_loss = loss*self.loss_scale
|
||||
scaled_loss.backward()
|
||||
|
||||
class DynamicLossScaler:
|
||||
|
||||
def __init__(self,
|
||||
init_scale=2**32,
|
||||
scale_factor=2.,
|
||||
scale_window=1000):
|
||||
self.cur_scale = init_scale
|
||||
self.cur_iter = 0
|
||||
self.last_overflow_iter = -1
|
||||
self.scale_factor = scale_factor
|
||||
self.scale_window = scale_window
|
||||
|
||||
# `params` is a list / generator of torch.Variable
|
||||
def has_overflow(self, params):
|
||||
# return False
|
||||
for p in params:
|
||||
if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
# `x` is a torch.Tensor
|
||||
def _has_inf_or_nan(x):
|
||||
cpu_sum = float(x.float().sum())
|
||||
if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum:
|
||||
return True
|
||||
return False
|
||||
|
||||
# `overflow` is boolean indicating whether we overflowed in gradient
|
||||
def update_scale(self, overflow):
|
||||
if overflow:
|
||||
#self.cur_scale /= self.scale_factor
|
||||
self.cur_scale = max(self.cur_scale/self.scale_factor, 1)
|
||||
self.last_overflow_iter = self.cur_iter
|
||||
else:
|
||||
if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0:
|
||||
self.cur_scale *= self.scale_factor
|
||||
# self.cur_scale = 1
|
||||
self.cur_iter += 1
|
||||
|
||||
@property
|
||||
def loss_scale(self):
|
||||
return self.cur_scale
|
||||
|
||||
def scale_gradient(self, module, grad_in, grad_out):
|
||||
return tuple(self.loss_scale * g for g in grad_in)
|
||||
|
||||
def backward(self, loss):
|
||||
scaled_loss = loss*self.loss_scale
|
||||
scaled_loss.backward()
|
||||
|
||||
##############################################################
|
||||
# Example usage below here -- assuming it's in a separate file
|
||||
##############################################################
|
||||
if __name__ == "__main__":
|
||||
import torch
|
||||
from torch.autograd import Variable
|
||||
from dynamic_loss_scaler import DynamicLossScaler
|
||||
|
||||
# N is batch size; D_in is input dimension;
|
||||
# H is hidden dimension; D_out is output dimension.
|
||||
N, D_in, H, D_out = 64, 1000, 100, 10
|
||||
|
||||
# Create random Tensors to hold inputs and outputs, and wrap them in Variables.
|
||||
x = Variable(torch.randn(N, D_in), requires_grad=False)
|
||||
y = Variable(torch.randn(N, D_out), requires_grad=False)
|
||||
|
||||
w1 = Variable(torch.randn(D_in, H), requires_grad=True)
|
||||
w2 = Variable(torch.randn(H, D_out), requires_grad=True)
|
||||
parameters = [w1, w2]
|
||||
|
||||
learning_rate = 1e-6
|
||||
optimizer = torch.optim.SGD(parameters, lr=learning_rate)
|
||||
loss_scaler = DynamicLossScaler()
|
||||
|
||||
for t in range(500):
|
||||
y_pred = x.mm(w1).clamp(min=0).mm(w2)
|
||||
loss = (y_pred - y).pow(2).sum() * loss_scaler.loss_scale
|
||||
print('Iter {} loss scale: {}'.format(t, loss_scaler.loss_scale))
|
||||
print('Iter {} scaled loss: {}'.format(t, loss.data[0]))
|
||||
print('Iter {} unscaled loss: {}'.format(t, loss.data[0] / loss_scaler.loss_scale))
|
||||
|
||||
# Run backprop
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
|
||||
# Check for overflow
|
||||
has_overflow = DynamicLossScaler.has_overflow(parameters)
|
||||
|
||||
# If no overflow, unscale grad and update as usual
|
||||
if not has_overflow:
|
||||
for param in parameters:
|
||||
param.grad.data.mul_(1. / loss_scaler.loss_scale)
|
||||
optimizer.step()
|
||||
# Otherwise, don't do anything -- ie, skip iteration
|
||||
else:
|
||||
print('OVERFLOW!')
|
||||
|
||||
# Update loss scale for next iteration
|
||||
loss_scaler.update_scale(has_overflow)
|
||||
|
||||
@@ -1,31 +1,24 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from math import sqrt
|
||||
import torch
|
||||
from torch.autograd import Variable
|
||||
from torch import nn
|
||||
from torch.nn import functional as F
|
||||
from .layers import ConvNorm, LinearNorm
|
||||
from .utils import to_gpu, get_mask_from_lengths
|
||||
from layers import ConvNorm, LinearNorm
|
||||
from utils import to_gpu, get_mask_from_lengths
|
||||
from fp16_optimizer import fp32_to_fp16, fp16_to_fp32
|
||||
|
||||
|
||||
class LocationLayer(nn.Module):
|
||||
def __init__(
|
||||
self, attention_n_filters, attention_kernel_size, attention_dim
|
||||
):
|
||||
def __init__(self, attention_n_filters, attention_kernel_size,
|
||||
attention_dim):
|
||||
super(LocationLayer, self).__init__()
|
||||
padding = int((attention_kernel_size - 1) / 2)
|
||||
self.location_conv = ConvNorm(
|
||||
2,
|
||||
attention_n_filters,
|
||||
self.location_conv = ConvNorm(2, attention_n_filters,
|
||||
kernel_size=attention_kernel_size,
|
||||
padding=padding,
|
||||
bias=False,
|
||||
stride=1,
|
||||
dilation=1,
|
||||
)
|
||||
self.location_dense = LinearNorm(
|
||||
attention_n_filters, attention_dim, bias=False, w_init_gain="tanh"
|
||||
)
|
||||
padding=padding, bias=False, stride=1,
|
||||
dilation=1)
|
||||
self.location_dense = LinearNorm(attention_n_filters, attention_dim,
|
||||
bias=False, w_init_gain='tanh')
|
||||
|
||||
def forward(self, attention_weights_cat):
|
||||
processed_attention = self.location_conv(attention_weights_cat)
|
||||
@@ -35,38 +28,27 @@ class LocationLayer(nn.Module):
|
||||
|
||||
|
||||
class Attention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
attention_rnn_dim,
|
||||
embedding_dim,
|
||||
attention_dim,
|
||||
attention_location_n_filters,
|
||||
attention_location_kernel_size,
|
||||
):
|
||||
def __init__(self, attention_rnn_dim, embedding_dim, attention_dim,
|
||||
attention_location_n_filters, attention_location_kernel_size):
|
||||
super(Attention, self).__init__()
|
||||
self.query_layer = LinearNorm(
|
||||
attention_rnn_dim, attention_dim, bias=False, w_init_gain="tanh"
|
||||
)
|
||||
self.memory_layer = LinearNorm(
|
||||
embedding_dim, attention_dim, bias=False, w_init_gain="tanh"
|
||||
)
|
||||
self.query_layer = LinearNorm(attention_rnn_dim, attention_dim,
|
||||
bias=False, w_init_gain='tanh')
|
||||
self.memory_layer = LinearNorm(embedding_dim, attention_dim, bias=False,
|
||||
w_init_gain='tanh')
|
||||
self.v = LinearNorm(attention_dim, 1, bias=False)
|
||||
self.location_layer = LocationLayer(
|
||||
attention_location_n_filters,
|
||||
self.location_layer = LocationLayer(attention_location_n_filters,
|
||||
attention_location_kernel_size,
|
||||
attention_dim,
|
||||
)
|
||||
attention_dim)
|
||||
self.score_mask_value = -float("inf")
|
||||
|
||||
def get_alignment_energies(
|
||||
self, query, processed_memory, attention_weights_cat
|
||||
):
|
||||
def get_alignment_energies(self, query, processed_memory,
|
||||
attention_weights_cat):
|
||||
"""
|
||||
PARAMS
|
||||
------
|
||||
query: decoder output (batch, n_mel_channels * n_frames_per_step)
|
||||
processed_memory: processed encoder outputs (B, T_in, attention_dim)
|
||||
attention_weights_cat: cumul. and prev. att weights (B, 2, max_time)
|
||||
attention_weights_cat: cumulative and prev. att weights (B, 2, max_time)
|
||||
|
||||
RETURNS
|
||||
-------
|
||||
@@ -74,28 +56,15 @@ class Attention(nn.Module):
|
||||
"""
|
||||
|
||||
processed_query = self.query_layer(query.unsqueeze(1))
|
||||
processed_attention_weights = self.location_layer(
|
||||
attention_weights_cat
|
||||
)
|
||||
energies = self.v(
|
||||
torch.tanh(
|
||||
processed_query
|
||||
+ processed_attention_weights
|
||||
+ processed_memory
|
||||
)
|
||||
)
|
||||
processed_attention_weights = self.location_layer(attention_weights_cat)
|
||||
energies = self.v(torch.tanh(
|
||||
processed_query + processed_attention_weights + processed_memory))
|
||||
|
||||
energies = energies.squeeze(-1)
|
||||
return energies
|
||||
|
||||
def forward(
|
||||
self,
|
||||
attention_hidden_state,
|
||||
memory,
|
||||
processed_memory,
|
||||
attention_weights_cat,
|
||||
mask,
|
||||
):
|
||||
def forward(self, attention_hidden_state, memory, processed_memory,
|
||||
attention_weights_cat, mask):
|
||||
"""
|
||||
PARAMS
|
||||
------
|
||||
@@ -106,8 +75,7 @@ class Attention(nn.Module):
|
||||
mask: binary mask for padded data
|
||||
"""
|
||||
alignment = self.get_alignment_energies(
|
||||
attention_hidden_state, processed_memory, attention_weights_cat
|
||||
)
|
||||
attention_hidden_state, processed_memory, attention_weights_cat)
|
||||
|
||||
if mask is not None:
|
||||
alignment.data.masked_fill_(mask, self.score_mask_value)
|
||||
@@ -124,11 +92,8 @@ class Prenet(nn.Module):
|
||||
super(Prenet, self).__init__()
|
||||
in_sizes = [in_dim] + sizes[:-1]
|
||||
self.layers = nn.ModuleList(
|
||||
[
|
||||
LinearNorm(in_size, out_size, bias=False)
|
||||
for (in_size, out_size) in zip(in_sizes, sizes)
|
||||
]
|
||||
)
|
||||
[LinearNorm(in_size, out_size, bias=False)
|
||||
for (in_size, out_size) in zip(in_sizes, sizes)])
|
||||
|
||||
def forward(self, x):
|
||||
for linear in self.layers:
|
||||
@@ -147,55 +112,36 @@ class Postnet(nn.Module):
|
||||
|
||||
self.convolutions.append(
|
||||
nn.Sequential(
|
||||
ConvNorm(
|
||||
hparams.n_mel_channels,
|
||||
hparams.postnet_embedding_dim,
|
||||
kernel_size=hparams.postnet_kernel_size,
|
||||
stride=1,
|
||||
ConvNorm(hparams.n_mel_channels, hparams.postnet_embedding_dim,
|
||||
kernel_size=hparams.postnet_kernel_size, stride=1,
|
||||
padding=int((hparams.postnet_kernel_size - 1) / 2),
|
||||
dilation=1,
|
||||
w_init_gain="tanh",
|
||||
),
|
||||
nn.BatchNorm1d(hparams.postnet_embedding_dim),
|
||||
)
|
||||
dilation=1, w_init_gain='tanh'),
|
||||
nn.BatchNorm1d(hparams.postnet_embedding_dim))
|
||||
)
|
||||
|
||||
for i in range(1, hparams.postnet_n_convolutions - 1):
|
||||
self.convolutions.append(
|
||||
nn.Sequential(
|
||||
ConvNorm(
|
||||
ConvNorm(hparams.postnet_embedding_dim,
|
||||
hparams.postnet_embedding_dim,
|
||||
hparams.postnet_embedding_dim,
|
||||
kernel_size=hparams.postnet_kernel_size,
|
||||
stride=1,
|
||||
kernel_size=hparams.postnet_kernel_size, stride=1,
|
||||
padding=int((hparams.postnet_kernel_size - 1) / 2),
|
||||
dilation=1,
|
||||
w_init_gain="tanh",
|
||||
),
|
||||
nn.BatchNorm1d(hparams.postnet_embedding_dim),
|
||||
)
|
||||
dilation=1, w_init_gain='tanh'),
|
||||
nn.BatchNorm1d(hparams.postnet_embedding_dim))
|
||||
)
|
||||
|
||||
self.convolutions.append(
|
||||
nn.Sequential(
|
||||
ConvNorm(
|
||||
hparams.postnet_embedding_dim,
|
||||
hparams.n_mel_channels,
|
||||
kernel_size=hparams.postnet_kernel_size,
|
||||
stride=1,
|
||||
ConvNorm(hparams.postnet_embedding_dim, hparams.n_mel_channels,
|
||||
kernel_size=hparams.postnet_kernel_size, stride=1,
|
||||
padding=int((hparams.postnet_kernel_size - 1) / 2),
|
||||
dilation=1,
|
||||
w_init_gain="linear",
|
||||
),
|
||||
nn.BatchNorm1d(hparams.n_mel_channels),
|
||||
)
|
||||
dilation=1, w_init_gain='linear'),
|
||||
nn.BatchNorm1d(hparams.n_mel_channels))
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
for i in range(len(self.convolutions) - 1):
|
||||
x = F.dropout(
|
||||
torch.tanh(self.convolutions[i](x)), 0.5, self.training
|
||||
)
|
||||
x = F.dropout(torch.tanh(self.convolutions[i](x)), 0.5, self.training)
|
||||
x = F.dropout(self.convolutions[-1](x), 0.5, self.training)
|
||||
|
||||
return x
|
||||
@@ -206,34 +152,24 @@ class Encoder(nn.Module):
|
||||
- Three 1-d convolution banks
|
||||
- Bidirectional LSTM
|
||||
"""
|
||||
|
||||
def __init__(self, hparams):
|
||||
super(Encoder, self).__init__()
|
||||
|
||||
convolutions = []
|
||||
for _ in range(hparams.encoder_n_convolutions):
|
||||
conv_layer = nn.Sequential(
|
||||
ConvNorm(
|
||||
ConvNorm(hparams.encoder_embedding_dim,
|
||||
hparams.encoder_embedding_dim,
|
||||
hparams.encoder_embedding_dim,
|
||||
kernel_size=hparams.encoder_kernel_size,
|
||||
stride=1,
|
||||
kernel_size=hparams.encoder_kernel_size, stride=1,
|
||||
padding=int((hparams.encoder_kernel_size - 1) / 2),
|
||||
dilation=1,
|
||||
w_init_gain="relu",
|
||||
),
|
||||
nn.BatchNorm1d(hparams.encoder_embedding_dim),
|
||||
)
|
||||
dilation=1, w_init_gain='relu'),
|
||||
nn.BatchNorm1d(hparams.encoder_embedding_dim))
|
||||
convolutions.append(conv_layer)
|
||||
self.convolutions = nn.ModuleList(convolutions)
|
||||
|
||||
self.lstm = nn.LSTM(
|
||||
hparams.encoder_embedding_dim,
|
||||
int(hparams.encoder_embedding_dim / 2),
|
||||
1,
|
||||
batch_first=True,
|
||||
bidirectional=True,
|
||||
)
|
||||
self.lstm = nn.LSTM(hparams.encoder_embedding_dim,
|
||||
int(hparams.encoder_embedding_dim / 2), 1,
|
||||
batch_first=True, bidirectional=True)
|
||||
|
||||
def forward(self, x, input_lengths):
|
||||
for conv in self.convolutions:
|
||||
@@ -244,15 +180,13 @@ class Encoder(nn.Module):
|
||||
# pytorch tensor are not reversible, hence the conversion
|
||||
input_lengths = input_lengths.cpu().numpy()
|
||||
x = nn.utils.rnn.pack_padded_sequence(
|
||||
x, input_lengths, batch_first=True
|
||||
)
|
||||
x, input_lengths, batch_first=True)
|
||||
|
||||
self.lstm.flatten_parameters()
|
||||
outputs, _ = self.lstm(x)
|
||||
|
||||
outputs, _ = nn.utils.rnn.pad_packed_sequence(
|
||||
outputs, batch_first=True
|
||||
)
|
||||
outputs, batch_first=True)
|
||||
|
||||
return outputs
|
||||
|
||||
@@ -284,39 +218,28 @@ class Decoder(nn.Module):
|
||||
|
||||
self.prenet = Prenet(
|
||||
hparams.n_mel_channels * hparams.n_frames_per_step,
|
||||
[hparams.prenet_dim, hparams.prenet_dim],
|
||||
)
|
||||
[hparams.prenet_dim, hparams.prenet_dim])
|
||||
|
||||
self.attention_rnn = nn.LSTMCell(
|
||||
hparams.prenet_dim + hparams.encoder_embedding_dim,
|
||||
hparams.attention_rnn_dim,
|
||||
)
|
||||
hparams.attention_rnn_dim)
|
||||
|
||||
self.attention_layer = Attention(
|
||||
hparams.attention_rnn_dim,
|
||||
hparams.encoder_embedding_dim,
|
||||
hparams.attention_dim,
|
||||
hparams.attention_location_n_filters,
|
||||
hparams.attention_location_kernel_size,
|
||||
)
|
||||
hparams.attention_rnn_dim, hparams.encoder_embedding_dim,
|
||||
hparams.attention_dim, hparams.attention_location_n_filters,
|
||||
hparams.attention_location_kernel_size)
|
||||
|
||||
self.decoder_rnn = nn.LSTMCell(
|
||||
hparams.attention_rnn_dim + hparams.encoder_embedding_dim,
|
||||
hparams.decoder_rnn_dim,
|
||||
1,
|
||||
)
|
||||
hparams.decoder_rnn_dim, 1)
|
||||
|
||||
self.linear_projection = LinearNorm(
|
||||
hparams.decoder_rnn_dim + hparams.encoder_embedding_dim,
|
||||
hparams.n_mel_channels * hparams.n_frames_per_step,
|
||||
)
|
||||
hparams.n_mel_channels * hparams.n_frames_per_step)
|
||||
|
||||
self.gate_layer = LinearNorm(
|
||||
hparams.decoder_rnn_dim + hparams.encoder_embedding_dim,
|
||||
1,
|
||||
bias=True,
|
||||
w_init_gain="sigmoid",
|
||||
)
|
||||
hparams.decoder_rnn_dim + hparams.encoder_embedding_dim, 1,
|
||||
bias=True, w_init_gain='sigmoid')
|
||||
|
||||
def get_go_frame(self, memory):
|
||||
""" Gets all zeros frames to use as first decoder input
|
||||
@@ -329,11 +252,8 @@ class Decoder(nn.Module):
|
||||
decoder_input: all zeros frames
|
||||
"""
|
||||
B = memory.size(0)
|
||||
decoder_input = Variable(
|
||||
memory.data.new(
|
||||
B, self.n_mel_channels * self.n_frames_per_step
|
||||
).zero_()
|
||||
)
|
||||
decoder_input = Variable(memory.data.new(
|
||||
B, self.n_mel_channels * self.n_frames_per_step).zero_())
|
||||
return decoder_input
|
||||
|
||||
def initialize_decoder_states(self, memory, mask):
|
||||
@@ -348,27 +268,22 @@ class Decoder(nn.Module):
|
||||
B = memory.size(0)
|
||||
MAX_TIME = memory.size(1)
|
||||
|
||||
self.attention_hidden = Variable(
|
||||
memory.data.new(B, self.attention_rnn_dim).zero_()
|
||||
)
|
||||
self.attention_cell = Variable(
|
||||
memory.data.new(B, self.attention_rnn_dim).zero_()
|
||||
)
|
||||
self.attention_hidden = Variable(memory.data.new(
|
||||
B, self.attention_rnn_dim).zero_())
|
||||
self.attention_cell = Variable(memory.data.new(
|
||||
B, self.attention_rnn_dim).zero_())
|
||||
|
||||
self.decoder_hidden = Variable(
|
||||
memory.data.new(B, self.decoder_rnn_dim).zero_()
|
||||
)
|
||||
self.decoder_cell = Variable(
|
||||
memory.data.new(B, self.decoder_rnn_dim).zero_()
|
||||
)
|
||||
self.decoder_hidden = Variable(memory.data.new(
|
||||
B, self.decoder_rnn_dim).zero_())
|
||||
self.decoder_cell = Variable(memory.data.new(
|
||||
B, self.decoder_rnn_dim).zero_())
|
||||
|
||||
self.attention_weights = Variable(memory.data.new(B, MAX_TIME).zero_())
|
||||
self.attention_weights_cum = Variable(
|
||||
memory.data.new(B, MAX_TIME).zero_()
|
||||
)
|
||||
self.attention_context = Variable(
|
||||
memory.data.new(B, self.encoder_embedding_dim).zero_()
|
||||
)
|
||||
self.attention_weights = Variable(memory.data.new(
|
||||
B, MAX_TIME).zero_())
|
||||
self.attention_weights_cum = Variable(memory.data.new(
|
||||
B, MAX_TIME).zero_())
|
||||
self.attention_context = Variable(memory.data.new(
|
||||
B, self.encoder_embedding_dim).zero_())
|
||||
|
||||
self.memory = memory
|
||||
self.processed_memory = self.attention_layer.memory_layer(memory)
|
||||
@@ -389,9 +304,7 @@ class Decoder(nn.Module):
|
||||
decoder_inputs = decoder_inputs.transpose(1, 2)
|
||||
decoder_inputs = decoder_inputs.view(
|
||||
decoder_inputs.size(0),
|
||||
int(decoder_inputs.size(1) / self.n_frames_per_step),
|
||||
-1,
|
||||
)
|
||||
int(decoder_inputs.size(1)/self.n_frames_per_step), -1)
|
||||
# (B, T_out, n_mel_channels) -> (T_out, B, n_mel_channels)
|
||||
decoder_inputs = decoder_inputs.transpose(0, 1)
|
||||
return decoder_inputs
|
||||
@@ -419,8 +332,7 @@ class Decoder(nn.Module):
|
||||
mel_outputs = torch.stack(mel_outputs).transpose(0, 1).contiguous()
|
||||
# decouple frames per step
|
||||
mel_outputs = mel_outputs.view(
|
||||
mel_outputs.size(0), -1, self.n_mel_channels
|
||||
)
|
||||
mel_outputs.size(0), -1, self.n_mel_channels)
|
||||
# (B, T_out, n_mel_channels) -> (B, n_mel_channels, T_out)
|
||||
mel_outputs = mel_outputs.transpose(1, 2)
|
||||
|
||||
@@ -440,44 +352,33 @@ class Decoder(nn.Module):
|
||||
"""
|
||||
cell_input = torch.cat((decoder_input, self.attention_context), -1)
|
||||
self.attention_hidden, self.attention_cell = self.attention_rnn(
|
||||
cell_input, (self.attention_hidden, self.attention_cell)
|
||||
)
|
||||
cell_input, (self.attention_hidden, self.attention_cell))
|
||||
self.attention_hidden = F.dropout(
|
||||
self.attention_hidden, self.p_attention_dropout, self.training
|
||||
)
|
||||
self.attention_hidden, self.p_attention_dropout, self.training)
|
||||
self.attention_cell = F.dropout(
|
||||
self.attention_cell, self.p_attention_dropout, self.training)
|
||||
|
||||
attention_weights_cat = torch.cat(
|
||||
(
|
||||
self.attention_weights.unsqueeze(1),
|
||||
self.attention_weights_cum.unsqueeze(1),
|
||||
),
|
||||
dim=1,
|
||||
)
|
||||
(self.attention_weights.unsqueeze(1),
|
||||
self.attention_weights_cum.unsqueeze(1)), dim=1)
|
||||
self.attention_context, self.attention_weights = self.attention_layer(
|
||||
self.attention_hidden,
|
||||
self.memory,
|
||||
self.processed_memory,
|
||||
attention_weights_cat,
|
||||
self.mask,
|
||||
)
|
||||
self.attention_hidden, self.memory, self.processed_memory,
|
||||
attention_weights_cat, self.mask)
|
||||
|
||||
self.attention_weights_cum += self.attention_weights
|
||||
decoder_input = torch.cat(
|
||||
(self.attention_hidden, self.attention_context), -1
|
||||
)
|
||||
(self.attention_hidden, self.attention_context), -1)
|
||||
self.decoder_hidden, self.decoder_cell = self.decoder_rnn(
|
||||
decoder_input, (self.decoder_hidden, self.decoder_cell)
|
||||
)
|
||||
decoder_input, (self.decoder_hidden, self.decoder_cell))
|
||||
self.decoder_hidden = F.dropout(
|
||||
self.decoder_hidden, self.p_decoder_dropout, self.training
|
||||
)
|
||||
self.decoder_hidden, self.p_decoder_dropout, self.training)
|
||||
self.decoder_cell = F.dropout(
|
||||
self.decoder_cell, self.p_decoder_dropout, self.training)
|
||||
|
||||
decoder_hidden_attention_context = torch.cat(
|
||||
(self.decoder_hidden, self.attention_context), dim=1
|
||||
)
|
||||
(self.decoder_hidden, self.attention_context), dim=1)
|
||||
decoder_output = self.linear_projection(
|
||||
decoder_hidden_attention_context
|
||||
)
|
||||
decoder_hidden_attention_context)
|
||||
|
||||
gate_prediction = self.gate_layer(decoder_hidden_attention_context)
|
||||
return decoder_output, gate_prediction, self.attention_weights
|
||||
@@ -503,22 +404,19 @@ class Decoder(nn.Module):
|
||||
decoder_inputs = self.prenet(decoder_inputs)
|
||||
|
||||
self.initialize_decoder_states(
|
||||
memory, mask=~get_mask_from_lengths(memory_lengths)
|
||||
)
|
||||
memory, mask=~get_mask_from_lengths(memory_lengths))
|
||||
|
||||
mel_outputs, gate_outputs, alignments = [], [], []
|
||||
while len(mel_outputs) < decoder_inputs.size(0) - 1:
|
||||
decoder_input = decoder_inputs[len(mel_outputs)]
|
||||
mel_output, gate_output, attention_weights = self.decode(
|
||||
decoder_input
|
||||
)
|
||||
decoder_input)
|
||||
mel_outputs += [mel_output.squeeze(1)]
|
||||
gate_outputs += [gate_output.squeeze()]
|
||||
alignments += [attention_weights]
|
||||
|
||||
mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs(
|
||||
mel_outputs, gate_outputs, alignments
|
||||
)
|
||||
mel_outputs, gate_outputs, alignments)
|
||||
|
||||
return mel_outputs, gate_outputs, alignments
|
||||
|
||||
@@ -556,8 +454,7 @@ class Decoder(nn.Module):
|
||||
decoder_input = mel_output
|
||||
|
||||
mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs(
|
||||
mel_outputs, gate_outputs, alignments
|
||||
)
|
||||
mel_outputs, gate_outputs, alignments)
|
||||
|
||||
return mel_outputs, gate_outputs, alignments
|
||||
|
||||
@@ -570,8 +467,7 @@ class Tacotron2(nn.Module):
|
||||
self.n_mel_channels = hparams.n_mel_channels
|
||||
self.n_frames_per_step = hparams.n_frames_per_step
|
||||
self.embedding = nn.Embedding(
|
||||
hparams.n_symbols, hparams.symbols_embedding_dim
|
||||
)
|
||||
hparams.n_symbols, hparams.symbols_embedding_dim)
|
||||
std = sqrt(2.0 / (hparams.n_symbols + hparams.symbols_embedding_dim))
|
||||
val = sqrt(3.0) * std # uniform bounds for std
|
||||
self.embedding.weight.data.uniform_(-val, val)
|
||||
@@ -580,9 +476,8 @@ class Tacotron2(nn.Module):
|
||||
self.postnet = Postnet(hparams)
|
||||
|
||||
def parse_batch(self, batch):
|
||||
text_padded, input_lengths, mel_padded, gate_padded, output_lengths = (
|
||||
batch
|
||||
)
|
||||
text_padded, input_lengths, mel_padded, gate_padded, \
|
||||
output_lengths = batch
|
||||
text_padded = to_gpu(text_padded).long()
|
||||
input_lengths = to_gpu(input_lengths).long()
|
||||
max_len = torch.max(input_lengths.data).item()
|
||||
@@ -592,8 +487,11 @@ class Tacotron2(nn.Module):
|
||||
|
||||
return (
|
||||
(text_padded, input_lengths, mel_padded, max_len, output_lengths),
|
||||
(mel_padded, gate_padded),
|
||||
)
|
||||
(mel_padded, gate_padded))
|
||||
|
||||
def parse_input(self, inputs):
|
||||
inputs = fp32_to_fp16(inputs) if self.fp16_run else inputs
|
||||
return inputs
|
||||
|
||||
def parse_output(self, outputs, output_lengths=None):
|
||||
if self.mask_padding and output_lengths is not None:
|
||||
@@ -605,40 +503,39 @@ class Tacotron2(nn.Module):
|
||||
outputs[1].data.masked_fill_(mask, 0.0)
|
||||
outputs[2].data.masked_fill_(mask[:, 0, :], 1e3) # gate energies
|
||||
|
||||
outputs = fp16_to_fp32(outputs) if self.fp16_run else outputs
|
||||
return outputs
|
||||
|
||||
def forward(self, inputs):
|
||||
text_inputs, text_lengths, mels, max_len, output_lengths = inputs
|
||||
text_lengths, output_lengths = text_lengths.data, output_lengths.data
|
||||
inputs, input_lengths, targets, max_len, \
|
||||
output_lengths = self.parse_input(inputs)
|
||||
input_lengths, output_lengths = input_lengths.data, output_lengths.data
|
||||
|
||||
embedded_inputs = self.embedding(text_inputs).transpose(1, 2)
|
||||
embedded_inputs = self.embedding(inputs).transpose(1, 2)
|
||||
|
||||
encoder_outputs = self.encoder(embedded_inputs, text_lengths)
|
||||
encoder_outputs = self.encoder(embedded_inputs, input_lengths)
|
||||
|
||||
mel_outputs, gate_outputs, alignments = self.decoder(
|
||||
encoder_outputs, mels, memory_lengths=text_lengths
|
||||
)
|
||||
encoder_outputs, targets, memory_lengths=input_lengths)
|
||||
|
||||
mel_outputs_postnet = self.postnet(mel_outputs)
|
||||
mel_outputs_postnet = mel_outputs + mel_outputs_postnet
|
||||
|
||||
return self.parse_output(
|
||||
[mel_outputs, mel_outputs_postnet, gate_outputs, alignments],
|
||||
output_lengths,
|
||||
)
|
||||
output_lengths)
|
||||
|
||||
def inference(self, inputs):
|
||||
inputs = self.parse_input(inputs)
|
||||
embedded_inputs = self.embedding(inputs).transpose(1, 2)
|
||||
encoder_outputs = self.encoder.inference(embedded_inputs)
|
||||
mel_outputs, gate_outputs, alignments = self.decoder.inference(
|
||||
encoder_outputs
|
||||
)
|
||||
encoder_outputs)
|
||||
|
||||
mel_outputs_postnet = self.postnet(mel_outputs)
|
||||
mel_outputs_postnet = mel_outputs + mel_outputs_postnet
|
||||
|
||||
outputs = self.parse_output(
|
||||
[mel_outputs, mel_outputs_postnet, gate_outputs, alignments]
|
||||
)
|
||||
[mel_outputs, mel_outputs_postnet, gate_outputs, alignments])
|
||||
|
||||
return outputs
|
||||
23
multiproc.py
Normal file
23
multiproc.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import time
|
||||
import torch
|
||||
import sys
|
||||
import subprocess
|
||||
|
||||
argslist = list(sys.argv)[1:]
|
||||
num_gpus = torch.cuda.device_count()
|
||||
argslist.append('--n_gpus={}'.format(num_gpus))
|
||||
workers = []
|
||||
job_id = time.strftime("%Y_%m_%d-%H%M%S")
|
||||
argslist.append("--group_name=group_{}".format(job_id))
|
||||
|
||||
for i in range(num_gpus):
|
||||
argslist.append('--rank={}'.format(i))
|
||||
stdout = None if i == 0 else open("logs/{}_GPU_{}.log".format(job_id, i),
|
||||
"w")
|
||||
print(argslist)
|
||||
p = subprocess.Popen([str(sys.executable)]+argslist, stdout=stdout)
|
||||
workers.append(p)
|
||||
argslist = argslist[:-1]
|
||||
|
||||
for p in workers:
|
||||
p.wait()
|
||||
61
plotting_utils.py
Normal file
61
plotting_utils.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pylab as plt
|
||||
import numpy as np
|
||||
|
||||
|
||||
def save_figure_to_numpy(fig):
|
||||
# save it to a numpy array.
|
||||
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
|
||||
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
||||
return data
|
||||
|
||||
|
||||
def plot_alignment_to_numpy(alignment, info=None):
|
||||
fig, ax = plt.subplots(figsize=(6, 4))
|
||||
im = ax.imshow(alignment, aspect='auto', origin='lower',
|
||||
interpolation='none')
|
||||
fig.colorbar(im, ax=ax)
|
||||
xlabel = 'Decoder timestep'
|
||||
if info is not None:
|
||||
xlabel += '\n\n' + info
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel('Encoder timestep')
|
||||
plt.tight_layout()
|
||||
|
||||
fig.canvas.draw()
|
||||
data = save_figure_to_numpy(fig)
|
||||
plt.close()
|
||||
return data
|
||||
|
||||
|
||||
def plot_spectrogram_to_numpy(spectrogram):
|
||||
fig, ax = plt.subplots(figsize=(12, 3))
|
||||
im = ax.imshow(spectrogram, aspect="auto", origin="lower",
|
||||
interpolation='none')
|
||||
plt.colorbar(im, ax=ax)
|
||||
plt.xlabel("Frames")
|
||||
plt.ylabel("Channels")
|
||||
plt.tight_layout()
|
||||
|
||||
fig.canvas.draw()
|
||||
data = save_figure_to_numpy(fig)
|
||||
plt.close()
|
||||
return data
|
||||
|
||||
|
||||
def plot_gate_outputs_to_numpy(gate_targets, gate_outputs):
|
||||
fig, ax = plt.subplots(figsize=(12, 3))
|
||||
ax.scatter(range(len(gate_targets)), gate_targets, alpha=0.5,
|
||||
color='green', marker='+', s=1, label='target')
|
||||
ax.scatter(range(len(gate_outputs)), gate_outputs, alpha=0.5,
|
||||
color='red', marker='.', s=1, label='predicted')
|
||||
|
||||
plt.xlabel("Frames (Green target, Red predicted)")
|
||||
plt.ylabel("Gate State")
|
||||
plt.tight_layout()
|
||||
|
||||
fig.canvas.draw()
|
||||
data = save_figure_to_numpy(fig)
|
||||
plt.close()
|
||||
return data
|
||||
10
requirements.txt
Normal file
10
requirements.txt
Normal file
@@ -0,0 +1,10 @@
|
||||
torch==0.4.0
|
||||
matplotlib==2.1.0
|
||||
tensorflow
|
||||
numpy==1.13.3
|
||||
inflect==0.2.5
|
||||
librosa==0.6.0
|
||||
scipy==1.0.0
|
||||
tensorboardX==1.1
|
||||
Unidecode==1.0.22
|
||||
pillow
|
||||
25
setup.cfg
25
setup.cfg
@@ -1,25 +0,0 @@
|
||||
[bumpversion]
|
||||
current_version = 0.1.0
|
||||
commit = True
|
||||
tag = True
|
||||
|
||||
[bumpversion:file:setup.py]
|
||||
search = version='{current_version}'
|
||||
replace = version='{new_version}'
|
||||
|
||||
[bumpversion:file:taco2/__init__.py]
|
||||
search = __version__ = '{current_version}'
|
||||
replace = __version__ = '{new_version}'
|
||||
|
||||
[bdist_wheel]
|
||||
universal = 1
|
||||
|
||||
[flake8]
|
||||
exclude = docs
|
||||
|
||||
[aliases]
|
||||
# Define setup.py command aliases here
|
||||
test = pytest
|
||||
|
||||
[tool:pytest]
|
||||
collect_ignore = ['setup.py']
|
||||
59
setup.py
59
setup.py
@@ -1,59 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""The setup script."""
|
||||
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
with open("README.md") as readme_file:
|
||||
readme = readme_file.read()
|
||||
|
||||
with open("HISTORY.rst") as history_file:
|
||||
history = history_file.read()
|
||||
|
||||
requirements = [
|
||||
"klepto==0.1.6",
|
||||
"numpy~=1.16.4",
|
||||
"inflect==0.2.5",
|
||||
"librosa==0.6.0",
|
||||
"scipy~=1.3.0",
|
||||
"Unidecode==1.0.22",
|
||||
"torch~=1.1.0",
|
||||
"PyAudio==0.2.11"
|
||||
]
|
||||
|
||||
setup_requirements = ["pytest-runner"]
|
||||
|
||||
test_requirements = ["pytest"]
|
||||
|
||||
packages = find_packages()
|
||||
|
||||
setup(
|
||||
author="Malar Kannan",
|
||||
author_email="malarkannan.invention@gmail.com",
|
||||
classifiers=[
|
||||
"Development Status :: 2 - Pre-Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"Natural Language :: English",
|
||||
"Programming Language :: Python :: 2",
|
||||
"Programming Language :: Python :: 2.7",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.4",
|
||||
"Programming Language :: Python :: 3.5",
|
||||
"Programming Language :: Python :: 3.6",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
],
|
||||
description="Taco2 TTS package.",
|
||||
install_requires=requirements,
|
||||
long_description=readme + "\n\n" + history,
|
||||
include_package_data=True,
|
||||
keywords="tacotron2 tts",
|
||||
name="taco2-tts",
|
||||
packages=packages,
|
||||
setup_requires=setup_requirements,
|
||||
test_suite="tests",
|
||||
tests_require=test_requirements,
|
||||
url="https://github.com/malarinv/tacotron2",
|
||||
version="0.3.0",
|
||||
zip_safe=False,
|
||||
entry_points={"console_scripts": ("tts_debug = taco2.tts:main",)},
|
||||
)
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
BSD 3-Clause License
|
||||
|
||||
@@ -11,8 +10,8 @@ All rights reserved.
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this
|
||||
list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
@@ -22,9 +21,8 @@ All rights reserved.
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
@@ -38,19 +36,13 @@ import torch.nn.functional as F
|
||||
from torch.autograd import Variable
|
||||
from scipy.signal import get_window
|
||||
from librosa.util import pad_center, tiny
|
||||
from .audio_processing import window_sumsquare
|
||||
from audio_processing import window_sumsquare
|
||||
|
||||
DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
||||
|
||||
class STFT(torch.nn.Module):
|
||||
"""
|
||||
adapted from Prem Seetharaman's
|
||||
https://github.com/pseeth/pytorch-stft
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, filter_length=800, hop_length=200, win_length=800, window="hann"
|
||||
):
|
||||
"""adapted from Prem Seetharaman's https://github.com/pseeth/pytorch-stft"""
|
||||
def __init__(self, filter_length=800, hop_length=200, win_length=800,
|
||||
window='hann'):
|
||||
super(STFT, self).__init__()
|
||||
self.filter_length = filter_length
|
||||
self.hop_length = hop_length
|
||||
@@ -61,20 +53,15 @@ class STFT(torch.nn.Module):
|
||||
fourier_basis = np.fft.fft(np.eye(self.filter_length))
|
||||
|
||||
cutoff = int((self.filter_length / 2 + 1))
|
||||
fourier_basis = np.vstack(
|
||||
[
|
||||
np.real(fourier_basis[:cutoff, :]),
|
||||
np.imag(fourier_basis[:cutoff, :]),
|
||||
]
|
||||
)
|
||||
fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
|
||||
np.imag(fourier_basis[:cutoff, :])])
|
||||
|
||||
forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
|
||||
inverse_basis = torch.FloatTensor(
|
||||
np.linalg.pinv(scale * fourier_basis).T[:, None, :]
|
||||
)
|
||||
np.linalg.pinv(scale * fourier_basis).T[:, None, :])
|
||||
|
||||
if window is not None:
|
||||
assert filter_length >= win_length
|
||||
assert(filter_length >= win_length)
|
||||
# get window and zero center pad it to filter_length
|
||||
fft_window = get_window(window, win_length, fftbins=True)
|
||||
fft_window = pad_center(fft_window, filter_length)
|
||||
@@ -84,8 +71,8 @@ class STFT(torch.nn.Module):
|
||||
forward_basis *= fft_window
|
||||
inverse_basis *= fft_window
|
||||
|
||||
self.register_buffer("forward_basis", forward_basis.float().to(DEVICE))
|
||||
self.register_buffer("inverse_basis", inverse_basis.float().to(DEVICE))
|
||||
self.register_buffer('forward_basis', forward_basis.float())
|
||||
self.register_buffer('inverse_basis', inverse_basis.float())
|
||||
|
||||
def transform(self, input_data):
|
||||
num_batches = input_data.size(0)
|
||||
@@ -98,69 +85,52 @@ class STFT(torch.nn.Module):
|
||||
input_data = F.pad(
|
||||
input_data.unsqueeze(1),
|
||||
(int(self.filter_length / 2), int(self.filter_length / 2), 0, 0),
|
||||
mode="reflect",
|
||||
)
|
||||
mode='reflect')
|
||||
input_data = input_data.squeeze(1)
|
||||
|
||||
forward_transform = F.conv1d(
|
||||
input_data,
|
||||
Variable(self.forward_basis, requires_grad=False),
|
||||
stride=self.hop_length,
|
||||
padding=0,
|
||||
)
|
||||
padding=0)
|
||||
|
||||
cutoff = int((self.filter_length / 2) + 1)
|
||||
real_part = forward_transform[:, :cutoff, :]
|
||||
imag_part = forward_transform[:, cutoff:, :]
|
||||
|
||||
magnitude = torch.sqrt(real_part ** 2 + imag_part ** 2)
|
||||
magnitude = torch.sqrt(real_part**2 + imag_part**2)
|
||||
phase = torch.autograd.Variable(
|
||||
torch.atan2(imag_part.data, real_part.data)
|
||||
)
|
||||
torch.atan2(imag_part.data, real_part.data))
|
||||
|
||||
return magnitude, phase
|
||||
|
||||
def inverse(self, magnitude, phase):
|
||||
phase = phase.to(DEVICE)
|
||||
recombine_magnitude_phase = torch.cat(
|
||||
[magnitude * torch.cos(phase), magnitude * torch.sin(phase)], dim=1
|
||||
)
|
||||
[magnitude*torch.cos(phase), magnitude*torch.sin(phase)], dim=1)
|
||||
|
||||
inverse_transform = F.conv_transpose1d(
|
||||
recombine_magnitude_phase,
|
||||
Variable(self.inverse_basis, requires_grad=False),
|
||||
stride=self.hop_length,
|
||||
padding=0,
|
||||
)
|
||||
padding=0)
|
||||
|
||||
if self.window is not None:
|
||||
window_sum = window_sumsquare(
|
||||
self.window,
|
||||
magnitude.size(-1),
|
||||
hop_length=self.hop_length,
|
||||
win_length=self.win_length,
|
||||
n_fft=self.filter_length,
|
||||
dtype=np.float32,
|
||||
)
|
||||
self.window, magnitude.size(-1), hop_length=self.hop_length,
|
||||
win_length=self.win_length, n_fft=self.filter_length,
|
||||
dtype=np.float32)
|
||||
# remove modulation effects
|
||||
approx_nonzero_indices = torch.from_numpy(
|
||||
np.where(window_sum > tiny(window_sum))[0]
|
||||
).to(DEVICE)
|
||||
np.where(window_sum > tiny(window_sum))[0])
|
||||
window_sum = torch.autograd.Variable(
|
||||
torch.from_numpy(window_sum), requires_grad=False
|
||||
).to(DEVICE)
|
||||
inverse_transform[:, :, approx_nonzero_indices] /= window_sum[
|
||||
approx_nonzero_indices
|
||||
]
|
||||
torch.from_numpy(window_sum), requires_grad=False)
|
||||
inverse_transform[:, :, approx_nonzero_indices] /= window_sum[approx_nonzero_indices]
|
||||
|
||||
# scale by hop ratio
|
||||
inverse_transform *= float(self.filter_length) / self.hop_length
|
||||
|
||||
inverse_transform = inverse_transform[
|
||||
:, :, int(self.filter_length / 2) :
|
||||
]
|
||||
inverse_transform = inverse_transform[
|
||||
:, :, : -int(self.filter_length / 2) :
|
||||
]
|
||||
inverse_transform = inverse_transform[:, :, int(self.filter_length/2):]
|
||||
inverse_transform = inverse_transform[:, :, :-int(self.filter_length/2):]
|
||||
|
||||
return inverse_transform
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import sys
|
||||
import copy
|
||||
import torch
|
||||
|
||||
def _check_model_old_version(model):
|
||||
if hasattr(model.WN[0], 'res_layers') or hasattr(model.WN[0], 'cond_layers'):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def _update_model_res_skip(old_model, new_model):
|
||||
for idx in range(0, len(new_model.WN)):
|
||||
wavenet = new_model.WN[idx]
|
||||
n_channels = wavenet.n_channels
|
||||
n_layers = wavenet.n_layers
|
||||
wavenet.res_skip_layers = torch.nn.ModuleList()
|
||||
for i in range(0, n_layers):
|
||||
if i < n_layers - 1:
|
||||
res_skip_channels = 2*n_channels
|
||||
else:
|
||||
res_skip_channels = n_channels
|
||||
res_skip_layer = torch.nn.Conv1d(n_channels, res_skip_channels, 1)
|
||||
skip_layer = torch.nn.utils.remove_weight_norm(wavenet.skip_layers[i])
|
||||
if i < n_layers - 1:
|
||||
res_layer = torch.nn.utils.remove_weight_norm(wavenet.res_layers[i])
|
||||
res_skip_layer.weight = torch.nn.Parameter(torch.cat([res_layer.weight, skip_layer.weight]))
|
||||
res_skip_layer.bias = torch.nn.Parameter(torch.cat([res_layer.bias, skip_layer.bias]))
|
||||
else:
|
||||
res_skip_layer.weight = torch.nn.Parameter(skip_layer.weight)
|
||||
res_skip_layer.bias = torch.nn.Parameter(skip_layer.bias)
|
||||
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
|
||||
wavenet.res_skip_layers.append(res_skip_layer)
|
||||
del wavenet.res_layers
|
||||
del wavenet.skip_layers
|
||||
|
||||
def _update_model_cond(old_model, new_model):
|
||||
for idx in range(0, len(new_model.WN)):
|
||||
wavenet = new_model.WN[idx]
|
||||
n_channels = wavenet.n_channels
|
||||
n_layers = wavenet.n_layers
|
||||
n_mel_channels = wavenet.cond_layers[0].weight.shape[1]
|
||||
cond_layer = torch.nn.Conv1d(n_mel_channels, 2*n_channels*n_layers, 1)
|
||||
cond_layer_weight = []
|
||||
cond_layer_bias = []
|
||||
for i in range(0, n_layers):
|
||||
_cond_layer = torch.nn.utils.remove_weight_norm(wavenet.cond_layers[i])
|
||||
cond_layer_weight.append(_cond_layer.weight)
|
||||
cond_layer_bias.append(_cond_layer.bias)
|
||||
cond_layer.weight = torch.nn.Parameter(torch.cat(cond_layer_weight))
|
||||
cond_layer.bias = torch.nn.Parameter(torch.cat(cond_layer_bias))
|
||||
cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
|
||||
wavenet.cond_layer = cond_layer
|
||||
del wavenet.cond_layers
|
||||
|
||||
def update_model(old_model):
|
||||
if not _check_model_old_version(old_model):
|
||||
return old_model
|
||||
new_model = copy.deepcopy(old_model)
|
||||
if hasattr(old_model.WN[0], 'res_layers'):
|
||||
_update_model_res_skip(old_model, new_model)
|
||||
if hasattr(old_model.WN[0], 'cond_layers'):
|
||||
_update_model_cond(old_model, new_model)
|
||||
return new_model
|
||||
|
||||
if __name__ == '__main__':
|
||||
old_model_path = sys.argv[1]
|
||||
new_model_path = sys.argv[2]
|
||||
model = torch.load(old_model_path)
|
||||
model['model'] = update_model(model['model'])
|
||||
torch.save(model, new_model_path)
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import sys
|
||||
import torch
|
||||
from .layers import STFT
|
||||
|
||||
|
||||
class Denoiser(torch.nn.Module):
|
||||
""" Removes model bias from audio produced with waveglow """
|
||||
|
||||
def __init__(self, waveglow, filter_length=1024, n_overlap=4,
|
||||
win_length=1024, mode='zeros', n_mel_channels=80,):
|
||||
super(Denoiser, self).__init__()
|
||||
if torch.cuda.is_available():
|
||||
self.stft = STFT(filter_length=filter_length,
|
||||
hop_length=int(filter_length/n_overlap),
|
||||
win_length=win_length).cuda()
|
||||
else:
|
||||
self.stft = STFT(filter_length=filter_length,
|
||||
hop_length=int(filter_length/n_overlap),
|
||||
win_length=win_length).cpu()
|
||||
if mode == 'zeros':
|
||||
mel_input = torch.zeros(
|
||||
(1, n_mel_channels, 88),
|
||||
dtype=waveglow.upsample.weight.dtype,
|
||||
device=waveglow.upsample.weight.device)
|
||||
elif mode == 'normal':
|
||||
mel_input = torch.randn(
|
||||
(1, n_mel_channels, 88),
|
||||
dtype=waveglow.upsample.weight.dtype,
|
||||
device=waveglow.upsample.weight.device)
|
||||
else:
|
||||
raise Exception("Mode {} if not supported".format(mode))
|
||||
|
||||
with torch.no_grad():
|
||||
bias_audio = waveglow.infer(mel_input, sigma=0.0).float()
|
||||
bias_spec, _ = self.stft.transform(bias_audio)
|
||||
|
||||
self.register_buffer('bias_spec', bias_spec[:, :, 0][:, :, None])
|
||||
|
||||
def forward(self, audio, strength=0.1):
|
||||
if torch.cuda.is_available():
|
||||
audio_spec, audio_angles = self.stft.transform(audio.cuda().float())
|
||||
else:
|
||||
audio_spec, audio_angles = self.stft.transform(audio.cpu().float())
|
||||
audio_spec_denoised = audio_spec - self.bias_spec * strength
|
||||
audio_spec_denoised = torch.clamp(audio_spec_denoised, 0.0)
|
||||
audio_denoised = self.stft.inverse(audio_spec_denoised, audio_angles)
|
||||
return audio_denoised
|
||||
@@ -1,63 +0,0 @@
|
||||
from .tts import TTSModel, OUTPUT_SAMPLE_RATE
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import wave
|
||||
|
||||
|
||||
def synthesize_corpus(
|
||||
corpus_path=Path("corpus.txt"),
|
||||
tacotron_path=Path("/path/to/tacotron.pt"),
|
||||
waveglow_path=Path("/path/to/waveglow.pt"),
|
||||
output_dir=Path("./out_dir"),
|
||||
):
|
||||
tts_model = TTSModel(str(tacotron_path), str(waveglow_path))
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
for (i, line) in enumerate(open(str(corpus_path)).readlines()):
|
||||
print(f'synthesizing... "{line.strip()}"')
|
||||
data = tts_model.synth_speech(line.strip())
|
||||
out_file = str(output_dir / Path(str(i) + ".wav"))
|
||||
with wave.open(out_file, "w") as out_file_h:
|
||||
out_file_h.setnchannels(1) # mono
|
||||
out_file_h.setsampwidth(2) # pcm int16 2bytes
|
||||
out_file_h.setframerate(OUTPUT_SAMPLE_RATE)
|
||||
out_file_h.writeframes(data)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t",
|
||||
"--tacotron_path",
|
||||
type=Path,
|
||||
default="./tacotron.pt",
|
||||
help="Path to a tacotron2 model",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w",
|
||||
"--waveglow_path",
|
||||
type=Path,
|
||||
default="./waveglow_256channels.pt",
|
||||
help="Path to a waveglow model",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-c",
|
||||
"--corpus_path",
|
||||
type=Path,
|
||||
default="./corpus.txt",
|
||||
help="Path to a corpus file",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o",
|
||||
"--output_dir",
|
||||
type=Path,
|
||||
default="./synth",
|
||||
help="Path to a output directory",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
synthesize_corpus(**vars(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,80 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# import tensorflow as tf
|
||||
from dataclasses import dataclass
|
||||
from .text import symbols
|
||||
|
||||
# from .text_codec import symbols
|
||||
|
||||
|
||||
@dataclass
|
||||
class HParams(object):
|
||||
"""docstring for HParams."""
|
||||
|
||||
################################
|
||||
# Experiment Parameters #
|
||||
################################
|
||||
epochs = 500
|
||||
iters_per_checkpoint = 1000
|
||||
seed = 1234
|
||||
dynamic_loss_scaling = True
|
||||
fp16_run = False
|
||||
distributed_run = False
|
||||
dist_backend = "nccl"
|
||||
dist_url = "tcp://localhost:54321"
|
||||
cudnn_enabled = True
|
||||
cudnn_benchmark = False
|
||||
ignore_layers = ["embedding.weight"]
|
||||
################################
|
||||
# Data Parameters #
|
||||
################################
|
||||
load_mel_from_disk = False
|
||||
training_files = "lists/tts_data_train_processed.txt"
|
||||
validation_files = "filelists/tts_data_val_processed.txt"
|
||||
text_cleaners = ["english_cleaners"]
|
||||
################################
|
||||
# Audio Parameters #
|
||||
################################
|
||||
max_wav_value = 32768.0
|
||||
sampling_rate = 22050
|
||||
filter_length = 1024
|
||||
hop_length = 256
|
||||
win_length = 1024
|
||||
n_mel_channels: int = 80
|
||||
mel_fmin: float = 0.0
|
||||
mel_fmax: float = 8000.0
|
||||
################################
|
||||
# Model Parameters #
|
||||
################################
|
||||
n_symbols = len(symbols)
|
||||
symbols_embedding_dim = 512
|
||||
# Encoder parameters
|
||||
encoder_kernel_size = 5
|
||||
encoder_n_convolutions = 3
|
||||
encoder_embedding_dim = 512
|
||||
# Decoder parameters
|
||||
n_frames_per_step = 1 # currently only 1 is supported
|
||||
decoder_rnn_dim = 1024
|
||||
prenet_dim = 256
|
||||
max_decoder_steps = 1000
|
||||
gate_threshold = 0.5
|
||||
p_attention_dropout = 0.1
|
||||
p_decoder_dropout = 0.1
|
||||
# Attention parameters
|
||||
attention_rnn_dim = 1024
|
||||
attention_dim = 128
|
||||
# Location Layer parameters
|
||||
attention_location_n_filters = 32
|
||||
attention_location_kernel_size = 31
|
||||
# Mel-post processing network parameters
|
||||
postnet_embedding_dim = 512
|
||||
postnet_kernel_size = 5
|
||||
postnet_n_convolutions = 5
|
||||
################################
|
||||
# Optimization Hyperparameters #
|
||||
################################
|
||||
use_saved_learning_rate = False
|
||||
learning_rate = 1e-3
|
||||
weight_decay = 1e-6
|
||||
grad_clip_thresh = 1.0
|
||||
batch_size = 4
|
||||
mask_padding = True # set model's padded outputs to padded values
|
||||
@@ -1,77 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
import re
|
||||
from . import cleaners
|
||||
from .symbols import symbols
|
||||
|
||||
# Mappings from symbol to numeric ID and vice versa:
|
||||
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
|
||||
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
|
||||
|
||||
# Regular expression matching text enclosed in curly braces:
|
||||
_curly_re = re.compile(r"(.*?)\{(.+?)\}(.*)")
|
||||
|
||||
|
||||
def text_to_sequence(text, cleaner_names):
|
||||
"""Converts a string of text to a sequence of IDs corresponding to the
|
||||
symbols in the text.
|
||||
|
||||
The text can optionally have ARPAbet sequences enclosed in curly braces
|
||||
embedded in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street."
|
||||
|
||||
Args:
|
||||
text: string to convert to a sequence
|
||||
cleaner_names: names of the cleaner functions to run the text through
|
||||
|
||||
Returns:
|
||||
List of integers corresponding to the symbols in the text
|
||||
"""
|
||||
sequence = []
|
||||
|
||||
# Check for curly braces and treat their contents as ARPAbet:
|
||||
while len(text):
|
||||
m = _curly_re.match(text)
|
||||
if not m:
|
||||
sequence += _symbols_to_sequence(_clean_text(text, cleaner_names))
|
||||
break
|
||||
sequence += _symbols_to_sequence(
|
||||
_clean_text(m.group(1), cleaner_names)
|
||||
)
|
||||
sequence += _arpabet_to_sequence(m.group(2))
|
||||
text = m.group(3)
|
||||
|
||||
return sequence
|
||||
|
||||
|
||||
def sequence_to_text(sequence):
|
||||
"""Converts a sequence of IDs back to a string"""
|
||||
result = ""
|
||||
for symbol_id in sequence:
|
||||
if symbol_id in _id_to_symbol:
|
||||
s = _id_to_symbol[symbol_id]
|
||||
# Enclose ARPAbet back in curly braces:
|
||||
if len(s) > 1 and s[0] == "@":
|
||||
s = "{%s}" % s[1:]
|
||||
result += s
|
||||
return result.replace("}{", " ")
|
||||
|
||||
|
||||
def _clean_text(text, cleaner_names):
|
||||
for name in cleaner_names:
|
||||
cleaner = getattr(cleaners, name)
|
||||
if not cleaner:
|
||||
raise Exception("Unknown cleaner: %s" % name)
|
||||
text = cleaner(text)
|
||||
return text
|
||||
|
||||
|
||||
def _symbols_to_sequence(symbols):
|
||||
return [_symbol_to_id[s] for s in symbols if _should_keep_symbol(s)]
|
||||
|
||||
|
||||
def _arpabet_to_sequence(text):
|
||||
return _symbols_to_sequence(["@" + s for s in text.split()])
|
||||
|
||||
|
||||
def _should_keep_symbol(s):
|
||||
return s in _symbol_to_id and s != "_" and s != "~"
|
||||
@@ -1,99 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import re
|
||||
from unidecode import unidecode
|
||||
from .numbers import normalize_numbers
|
||||
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
"""
|
||||
Cleaners are transformations that run over the input text at both training and
|
||||
eval time.
|
||||
|
||||
Cleaners can be selected by passing a comma-delimited list of cleaner names as
|
||||
the "cleaners"
|
||||
hyperparameter. Some cleaners are English-specific. You'll typically want to
|
||||
use:
|
||||
1. "english_cleaners" for English text
|
||||
2. "transliteration_cleaners" for non-English text that can be transliterated
|
||||
to ASCII using
|
||||
the Unidecode library (https://pypi.python.org/pypi/Unidecode)
|
||||
3. "basic_cleaners" if you do not want to transliterate (in this case, you
|
||||
should also update
|
||||
the symbols in symbols.py to match your data).
|
||||
"""
|
||||
|
||||
# Regular expression matching whitespace:
|
||||
_whitespace_re = re.compile(r"\s+")
|
||||
|
||||
# List of (regular expression, replacement) pairs for abbreviations:
|
||||
_abbreviations = [
|
||||
(re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
|
||||
for x in [
|
||||
("mrs", "misess"),
|
||||
("mr", "mister"),
|
||||
("dr", "doctor"),
|
||||
("st", "saint"),
|
||||
("co", "company"),
|
||||
("jr", "junior"),
|
||||
("maj", "major"),
|
||||
("gen", "general"),
|
||||
("drs", "doctors"),
|
||||
("rev", "reverend"),
|
||||
("lt", "lieutenant"),
|
||||
("hon", "honorable"),
|
||||
("sgt", "sergeant"),
|
||||
("capt", "captain"),
|
||||
("esq", "esquire"),
|
||||
("ltd", "limited"),
|
||||
("col", "colonel"),
|
||||
("ft", "fort"),
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
def expand_abbreviations(text):
|
||||
for regex, replacement in _abbreviations:
|
||||
text = re.sub(regex, replacement, text)
|
||||
return text
|
||||
|
||||
|
||||
def expand_numbers(text):
|
||||
return normalize_numbers(text)
|
||||
|
||||
|
||||
def lowercase(text):
|
||||
return text.lower()
|
||||
|
||||
|
||||
def collapse_whitespace(text):
|
||||
return re.sub(_whitespace_re, " ", text)
|
||||
|
||||
|
||||
def convert_to_ascii(text):
|
||||
return unidecode(text)
|
||||
|
||||
|
||||
def basic_cleaners(text):
|
||||
"""Basic pipeline that lowercases and collapses whitespace without
|
||||
transliteration."""
|
||||
text = lowercase(text)
|
||||
text = collapse_whitespace(text)
|
||||
return text
|
||||
|
||||
|
||||
def transliteration_cleaners(text):
|
||||
"""Pipeline for non-English text that transliterates to ASCII."""
|
||||
text = convert_to_ascii(text)
|
||||
text = lowercase(text)
|
||||
text = collapse_whitespace(text)
|
||||
return text
|
||||
|
||||
|
||||
def english_cleaners(text):
|
||||
"""Pipeline for English text, including number and abbreviation
|
||||
expansion."""
|
||||
text = convert_to_ascii(text)
|
||||
text = lowercase(text)
|
||||
text = expand_numbers(text)
|
||||
text = expand_abbreviations(text)
|
||||
text = collapse_whitespace(text)
|
||||
return text
|
||||
@@ -1,143 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
|
||||
import re
|
||||
|
||||
valid_symbols = [
|
||||
"AA",
|
||||
"AA0",
|
||||
"AA1",
|
||||
"AA2",
|
||||
"AE",
|
||||
"AE0",
|
||||
"AE1",
|
||||
"AE2",
|
||||
"AH",
|
||||
"AH0",
|
||||
"AH1",
|
||||
"AH2",
|
||||
"AO",
|
||||
"AO0",
|
||||
"AO1",
|
||||
"AO2",
|
||||
"AW",
|
||||
"AW0",
|
||||
"AW1",
|
||||
"AW2",
|
||||
"AY",
|
||||
"AY0",
|
||||
"AY1",
|
||||
"AY2",
|
||||
"B",
|
||||
"CH",
|
||||
"D",
|
||||
"DH",
|
||||
"EH",
|
||||
"EH0",
|
||||
"EH1",
|
||||
"EH2",
|
||||
"ER",
|
||||
"ER0",
|
||||
"ER1",
|
||||
"ER2",
|
||||
"EY",
|
||||
"EY0",
|
||||
"EY1",
|
||||
"EY2",
|
||||
"F",
|
||||
"G",
|
||||
"HH",
|
||||
"IH",
|
||||
"IH0",
|
||||
"IH1",
|
||||
"IH2",
|
||||
"IY",
|
||||
"IY0",
|
||||
"IY1",
|
||||
"IY2",
|
||||
"JH",
|
||||
"K",
|
||||
"L",
|
||||
"M",
|
||||
"N",
|
||||
"NG",
|
||||
"OW",
|
||||
"OW0",
|
||||
"OW1",
|
||||
"OW2",
|
||||
"OY",
|
||||
"OY0",
|
||||
"OY1",
|
||||
"OY2",
|
||||
"P",
|
||||
"R",
|
||||
"S",
|
||||
"SH",
|
||||
"T",
|
||||
"TH",
|
||||
"UH",
|
||||
"UH0",
|
||||
"UH1",
|
||||
"UH2",
|
||||
"UW",
|
||||
"UW0",
|
||||
"UW1",
|
||||
"UW2",
|
||||
"V",
|
||||
"W",
|
||||
"Y",
|
||||
"Z",
|
||||
"ZH",
|
||||
]
|
||||
|
||||
_valid_symbol_set = set(valid_symbols)
|
||||
|
||||
|
||||
class CMUDict:
|
||||
"""Thin wrapper around CMUDict data.
|
||||
http://www.speech.cs.cmu.edu/cgi-bin/cmudict"""
|
||||
|
||||
def __init__(self, file_or_path, keep_ambiguous=True):
|
||||
if isinstance(file_or_path, str):
|
||||
with open(file_or_path, encoding="latin-1") as f:
|
||||
entries = _parse_cmudict(f)
|
||||
else:
|
||||
entries = _parse_cmudict(file_or_path)
|
||||
if not keep_ambiguous:
|
||||
entries = {
|
||||
word: pron for word, pron in entries.items() if len(pron) == 1
|
||||
}
|
||||
self._entries = entries
|
||||
|
||||
def __len__(self):
|
||||
return len(self._entries)
|
||||
|
||||
def lookup(self, word):
|
||||
"""Returns list of ARPAbet pronunciations of the given word."""
|
||||
return self._entries.get(word.upper())
|
||||
|
||||
|
||||
_alt_re = re.compile(r"\([0-9]+\)")
|
||||
|
||||
|
||||
def _parse_cmudict(file):
|
||||
cmudict = {}
|
||||
for line in file:
|
||||
if len(line) and (line[0] >= "A" and line[0] <= "Z" or line[0] == "'"):
|
||||
parts = line.split(" ")
|
||||
word = re.sub(_alt_re, "", parts[0])
|
||||
pronunciation = _get_pronunciation(parts[1])
|
||||
if pronunciation:
|
||||
if word in cmudict:
|
||||
cmudict[word].append(pronunciation)
|
||||
else:
|
||||
cmudict[word] = [pronunciation]
|
||||
return cmudict
|
||||
|
||||
|
||||
def _get_pronunciation(s):
|
||||
parts = s.strip().split(" ")
|
||||
for part in parts:
|
||||
if part not in _valid_symbol_set:
|
||||
return None
|
||||
return " ".join(parts)
|
||||
@@ -1,73 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
|
||||
import inflect
|
||||
import re
|
||||
|
||||
_inflect = inflect.engine()
|
||||
_comma_number_re = re.compile(r"([0-9][0-9\,]+[0-9])")
|
||||
_decimal_number_re = re.compile(r"([0-9]+\.[0-9]+)")
|
||||
_pounds_re = re.compile(r"£([0-9\,]*[0-9]+)")
|
||||
_dollars_re = re.compile(r"\$([0-9\.\,]*[0-9]+)")
|
||||
_ordinal_re = re.compile(r"[0-9]+(st|nd|rd|th)")
|
||||
_number_re = re.compile(r"[0-9]+")
|
||||
|
||||
|
||||
def _remove_commas(m):
|
||||
return m.group(1).replace(",", "")
|
||||
|
||||
|
||||
def _expand_decimal_point(m):
|
||||
return m.group(1).replace(".", " point ")
|
||||
|
||||
|
||||
def _expand_dollars(m):
|
||||
match = m.group(1)
|
||||
parts = match.split(".")
|
||||
if len(parts) > 2:
|
||||
return match + " dollars" # Unexpected format
|
||||
dollars = int(parts[0]) if parts[0] else 0
|
||||
cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
|
||||
if dollars and cents:
|
||||
dollar_unit = "dollar" if dollars == 1 else "dollars"
|
||||
cent_unit = "cent" if cents == 1 else "cents"
|
||||
return "%s %s, %s %s" % (dollars, dollar_unit, cents, cent_unit)
|
||||
elif dollars:
|
||||
dollar_unit = "dollar" if dollars == 1 else "dollars"
|
||||
return "%s %s" % (dollars, dollar_unit)
|
||||
elif cents:
|
||||
cent_unit = "cent" if cents == 1 else "cents"
|
||||
return "%s %s" % (cents, cent_unit)
|
||||
else:
|
||||
return "zero dollars"
|
||||
|
||||
|
||||
def _expand_ordinal(m):
|
||||
return _inflect.number_to_words(m.group(0))
|
||||
|
||||
|
||||
def _expand_number(m):
|
||||
num = int(m.group(0))
|
||||
if num > 1000 and num < 3000:
|
||||
if num == 2000:
|
||||
return "two thousand"
|
||||
elif num > 2000 and num < 2010:
|
||||
return "two thousand " + _inflect.number_to_words(num % 100)
|
||||
elif num % 100 == 0:
|
||||
return _inflect.number_to_words(num // 100) + " hundred"
|
||||
else:
|
||||
return _inflect.number_to_words(
|
||||
num, andword="", zero="oh", group=2
|
||||
).replace(", ", " ")
|
||||
else:
|
||||
return _inflect.number_to_words(num, andword="")
|
||||
|
||||
|
||||
def normalize_numbers(text):
|
||||
text = re.sub(_comma_number_re, _remove_commas, text)
|
||||
text = re.sub(_pounds_re, r"\1 pounds", text)
|
||||
text = re.sub(_dollars_re, _expand_dollars, text)
|
||||
text = re.sub(_decimal_number_re, _expand_decimal_point, text)
|
||||
text = re.sub(_ordinal_re, _expand_ordinal, text)
|
||||
text = re.sub(_number_re, _expand_number, text)
|
||||
return text
|
||||
@@ -1,24 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from . import cmudict
|
||||
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
"""
|
||||
Defines the set of symbols used in text input to the model.
|
||||
|
||||
The default is a set of ASCII characters that works well for English or text
|
||||
that has been run through Unidecode. For other data, you can modify
|
||||
_characters. See TRAINING_DATA.md for details. """
|
||||
|
||||
_pad = "_"
|
||||
_punctuation = "!'(),.:;? "
|
||||
_special = "-"
|
||||
_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
# Prepend "@" to ARPAbet symbols to ensure uniqueness (some are the same as
|
||||
# uppercase letters):
|
||||
_arpabet = ["@" + s for s in cmudict.valid_symbols]
|
||||
|
||||
# Export all symbols:
|
||||
symbols = (
|
||||
[_pad] + list(_special) + list(_punctuation) + list(_letters) + _arpabet
|
||||
)
|
||||
@@ -1,81 +0,0 @@
|
||||
from .utils import load_filepaths_and_text
|
||||
|
||||
from .text import text_to_sequence, sequence_to_text
|
||||
|
||||
|
||||
import sentencepiece as spm
|
||||
from .text import symbols
|
||||
from bpemb import BPEmb
|
||||
|
||||
|
||||
SPM_CORPUS_FILE = "filelists/text_corpus.txt"
|
||||
SPM_MODEL_PREFIX = "spm"
|
||||
SPM_VOCAB_SIZE = 1000
|
||||
|
||||
|
||||
def _create_sentencepiece_corpus():
|
||||
from .hparams import HParams
|
||||
hparams = HParams()
|
||||
def get_text_list(text_file):
|
||||
return [i[1] + "\n" for i in load_filepaths_and_text(text_file)]
|
||||
|
||||
full_text_list = get_text_list(hparams.training_files) + get_text_list(
|
||||
hparams.validation_files
|
||||
)
|
||||
with open(SPM_CORPUS_FILE, "w") as fd:
|
||||
fd.writelines(full_text_list)
|
||||
|
||||
|
||||
def _create_sentencepiece_vocab(vocab_size=SPM_VOCAB_SIZE):
|
||||
train_params = "--input={} --model_type=unigram --character_coverage=1.0 --model_prefix={} --vocab_size={}".format(
|
||||
SPM_CORPUS_FILE, SPM_MODEL_PREFIX, vocab_size
|
||||
)
|
||||
spm.SentencePieceTrainer.Train(train_params)
|
||||
|
||||
|
||||
def _spm_text_codecs():
|
||||
sp = spm.SentencePieceProcessor()
|
||||
sp.Load("{}.model".format(SPM_MODEL_PREFIX))
|
||||
|
||||
def ttseq(text, cleaners):
|
||||
return sp.EncodeAsIds(text)
|
||||
|
||||
def seqtt(sequence):
|
||||
return sp.DecodeIds(sequence)
|
||||
|
||||
return ttseq, seqtt
|
||||
|
||||
|
||||
def _bpemb_text_codecs():
|
||||
global bpemb_en
|
||||
bpemb_en = BPEmb(lang="en", dim=50, vs=1000)
|
||||
def ttseq(text, cleaners):
|
||||
return bpemb_en.encode_ids(text)
|
||||
|
||||
def seqtt(sequence):
|
||||
return bpemb_en.decode_ids(sequence)
|
||||
|
||||
return ttseq, seqtt
|
||||
|
||||
# text_to_sequence, sequence_to_text = _spm_text_codecs()
|
||||
text_to_sequence, sequence_to_text = _bpemb_text_codecs()
|
||||
symbols = bpemb_en.words
|
||||
|
||||
def _interactive_test():
|
||||
from .hparams import HParams
|
||||
hparams = HParams()
|
||||
prompt = "Hello world; how are you, doing ?"
|
||||
while prompt not in ["q", "quit"]:
|
||||
oup = sequence_to_text(text_to_sequence(prompt, hparams.text_cleaners))
|
||||
print('==> ',oup)
|
||||
prompt = input("> ")
|
||||
|
||||
|
||||
def main():
|
||||
# _create_sentencepiece_corpus()
|
||||
# _create_sentencepiece_vocab()
|
||||
_interactive_test()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
208
taco2/tts.py
208
taco2/tts.py
@@ -1,208 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import pyaudio
|
||||
import klepto
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from .model import Tacotron2
|
||||
from glow import WaveGlow
|
||||
from .hparams import HParams
|
||||
from .layers import TacotronSTFT
|
||||
from .text import text_to_sequence
|
||||
from .denoiser import Denoiser
|
||||
from .audio_processing import griffin_lim, postprocess_audio
|
||||
|
||||
OUTPUT_SAMPLE_RATE = 22050
|
||||
GL_ITERS = 30
|
||||
VOCODER_WAVEGLOW, VOCODER_GL = "wavglow", "gl"
|
||||
|
||||
# config from
|
||||
# https://github.com/NVIDIA/waveglow/blob/master/config.json
|
||||
WAVEGLOW_CONFIG = {
|
||||
"n_mel_channels": 40,
|
||||
"n_flows": 12,
|
||||
"n_group": 8,
|
||||
"n_early_every": 4,
|
||||
"n_early_size": 2,
|
||||
"WN_config": {"n_layers": 8, "n_channels": 256, "kernel_size": 3},
|
||||
}
|
||||
|
||||
|
||||
class TTSModel(object):
|
||||
"""docstring for TTSModel."""
|
||||
|
||||
def __init__(self, tacotron2_path, waveglow_path, **kwargs):
|
||||
super(TTSModel, self).__init__()
|
||||
hparams = HParams(**kwargs)
|
||||
self.hparams = hparams
|
||||
self.model = Tacotron2(hparams)
|
||||
if torch.cuda.is_available():
|
||||
self.model.load_state_dict(torch.load(tacotron2_path)["state_dict"])
|
||||
self.model.cuda().eval()
|
||||
else:
|
||||
self.model.load_state_dict(
|
||||
torch.load(tacotron2_path, map_location="cpu")["state_dict"]
|
||||
)
|
||||
self.model.eval()
|
||||
self.k_cache = klepto.archives.file_archive(cached=False)
|
||||
if waveglow_path:
|
||||
if torch.cuda.is_available():
|
||||
wave_params = torch.load(waveglow_path)
|
||||
else:
|
||||
wave_params = torch.load(waveglow_path, map_location="cpu")
|
||||
try:
|
||||
self.waveglow = WaveGlow(**WAVEGLOW_CONFIG)
|
||||
self.waveglow.load_state_dict(wave_params)
|
||||
except:
|
||||
self.waveglow = wave_params["model"]
|
||||
self.waveglow = self.waveglow.remove_weightnorm(self.waveglow)
|
||||
if torch.cuda.is_available():
|
||||
self.waveglow.cuda().eval()
|
||||
else:
|
||||
self.waveglow.eval()
|
||||
# workaround from
|
||||
# https://github.com/NVIDIA/waveglow/issues/127
|
||||
for m in self.waveglow.modules():
|
||||
if "Conv" in str(type(m)):
|
||||
setattr(m, "padding_mode", "zeros")
|
||||
for k in self.waveglow.convinv:
|
||||
k.float().half()
|
||||
self.denoiser = Denoiser(
|
||||
self.waveglow, n_mel_channels=hparams.n_mel_channels
|
||||
)
|
||||
self.synth_speech = klepto.safe.inf_cache(cache=self.k_cache)(
|
||||
self._synth_speech
|
||||
)
|
||||
else:
|
||||
self.synth_speech = klepto.safe.inf_cache(cache=self.k_cache)(
|
||||
self._synth_speech_fast
|
||||
)
|
||||
self.taco_stft = TacotronSTFT(
|
||||
hparams.filter_length,
|
||||
hparams.hop_length,
|
||||
hparams.win_length,
|
||||
n_mel_channels=hparams.n_mel_channels,
|
||||
sampling_rate=hparams.sampling_rate,
|
||||
mel_fmax=4000,
|
||||
)
|
||||
|
||||
def _generate_mel_postnet(self, text):
|
||||
sequence = np.array(text_to_sequence(text, ["english_cleaners"]))[None, :]
|
||||
if torch.cuda.is_available():
|
||||
sequence = torch.autograd.Variable(torch.from_numpy(sequence)).cuda().long()
|
||||
else:
|
||||
sequence = torch.autograd.Variable(torch.from_numpy(sequence)).long()
|
||||
with torch.no_grad():
|
||||
mel_outputs, mel_outputs_postnet, _, alignments = self.model.inference(
|
||||
sequence
|
||||
)
|
||||
return mel_outputs_postnet
|
||||
|
||||
def synth_speech_array(self, text, vocoder):
|
||||
mel_outputs_postnet = self._generate_mel_postnet(text)
|
||||
|
||||
if vocoder == VOCODER_WAVEGLOW:
|
||||
with torch.no_grad():
|
||||
audio_t = self.waveglow.infer(mel_outputs_postnet, sigma=0.666)
|
||||
audio_t = self.denoiser(audio_t, 0.1)[0]
|
||||
audio = audio_t[0].data
|
||||
elif vocoder == VOCODER_GL:
|
||||
mel_decompress = self.taco_stft.spectral_de_normalize(mel_outputs_postnet)
|
||||
mel_decompress = mel_decompress.transpose(1, 2).data.cpu()
|
||||
spec_from_mel_scaling = 1000
|
||||
spec_from_mel = torch.mm(mel_decompress[0], self.taco_stft.mel_basis)
|
||||
spec_from_mel = spec_from_mel.transpose(0, 1).unsqueeze(0)
|
||||
spec_from_mel = spec_from_mel * spec_from_mel_scaling
|
||||
spec_from_mel = (
|
||||
spec_from_mel.cuda() if torch.cuda.is_available() else spec_from_mel
|
||||
)
|
||||
audio = griffin_lim(
|
||||
torch.autograd.Variable(spec_from_mel[:, :, :-1]),
|
||||
self.taco_stft.stft_fn,
|
||||
GL_ITERS,
|
||||
)
|
||||
audio = audio.squeeze()
|
||||
else:
|
||||
raise ValueError("vocoder arg should be one of [wavglow|gl]")
|
||||
audio = audio.cpu().numpy()
|
||||
return audio
|
||||
|
||||
def _synth_speech(
|
||||
self, text, speed: float = 1.0, sample_rate: int = OUTPUT_SAMPLE_RATE
|
||||
):
|
||||
audio = self.synth_speech_array(text, VOCODER_WAVEGLOW)
|
||||
|
||||
return postprocess_audio(
|
||||
audio,
|
||||
src_rate=self.hparams.sampling_rate,
|
||||
dst_rate=sample_rate,
|
||||
tempo=speed,
|
||||
)
|
||||
|
||||
def _synth_speech_fast(
|
||||
self, text, speed: float = 1.0, sample_rate: int = OUTPUT_SAMPLE_RATE
|
||||
):
|
||||
audio = self.synth_speech_array(text, VOCODER_GL)
|
||||
|
||||
return postprocess_audio(
|
||||
audio,
|
||||
tempo=speed,
|
||||
src_rate=self.hparams.sampling_rate,
|
||||
dst_rate=sample_rate,
|
||||
)
|
||||
|
||||
|
||||
def player_gen():
|
||||
audio_interface = pyaudio.PyAudio()
|
||||
_audio_stream = audio_interface.open(
|
||||
format=pyaudio.paInt16, channels=1, rate=OUTPUT_SAMPLE_RATE, output=True
|
||||
)
|
||||
|
||||
def play_device(data):
|
||||
_audio_stream.write(data)
|
||||
# _audio_stream.close()
|
||||
|
||||
return play_device
|
||||
|
||||
|
||||
def repl(tts_model):
|
||||
player = player_gen()
|
||||
|
||||
def loop():
|
||||
text = input("tts >")
|
||||
data = tts_model.synth_speech(text.strip())
|
||||
player(data)
|
||||
|
||||
return loop
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t",
|
||||
"--tacotron2_path",
|
||||
type=Path,
|
||||
default="./tacotron.pt",
|
||||
help="Path to a tacotron2 model",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w",
|
||||
"--waveglow_path",
|
||||
type=Path,
|
||||
default="./waveglow_256channels.pt",
|
||||
help="Path to a waveglow model",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
tts_model = TTSModel(**vars(args))
|
||||
interactive_loop = repl(tts_model)
|
||||
while True:
|
||||
interactive_loop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
BIN
tensorboard.png
Normal file
BIN
tensorboard.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 170 KiB |
74
text/__init__.py
Normal file
74
text/__init__.py
Normal file
@@ -0,0 +1,74 @@
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
import re
|
||||
from text import cleaners
|
||||
from text.symbols import symbols
|
||||
|
||||
|
||||
# Mappings from symbol to numeric ID and vice versa:
|
||||
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
|
||||
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
|
||||
|
||||
# Regular expression matching text enclosed in curly braces:
|
||||
_curly_re = re.compile(r'(.*?)\{(.+?)\}(.*)')
|
||||
|
||||
|
||||
def text_to_sequence(text, cleaner_names):
|
||||
'''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
|
||||
|
||||
The text can optionally have ARPAbet sequences enclosed in curly braces embedded
|
||||
in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street."
|
||||
|
||||
Args:
|
||||
text: string to convert to a sequence
|
||||
cleaner_names: names of the cleaner functions to run the text through
|
||||
|
||||
Returns:
|
||||
List of integers corresponding to the symbols in the text
|
||||
'''
|
||||
sequence = []
|
||||
|
||||
# Check for curly braces and treat their contents as ARPAbet:
|
||||
while len(text):
|
||||
m = _curly_re.match(text)
|
||||
if not m:
|
||||
sequence += _symbols_to_sequence(_clean_text(text, cleaner_names))
|
||||
break
|
||||
sequence += _symbols_to_sequence(_clean_text(m.group(1), cleaner_names))
|
||||
sequence += _arpabet_to_sequence(m.group(2))
|
||||
text = m.group(3)
|
||||
|
||||
return sequence
|
||||
|
||||
|
||||
def sequence_to_text(sequence):
|
||||
'''Converts a sequence of IDs back to a string'''
|
||||
result = ''
|
||||
for symbol_id in sequence:
|
||||
if symbol_id in _id_to_symbol:
|
||||
s = _id_to_symbol[symbol_id]
|
||||
# Enclose ARPAbet back in curly braces:
|
||||
if len(s) > 1 and s[0] == '@':
|
||||
s = '{%s}' % s[1:]
|
||||
result += s
|
||||
return result.replace('}{', ' ')
|
||||
|
||||
|
||||
def _clean_text(text, cleaner_names):
|
||||
for name in cleaner_names:
|
||||
cleaner = getattr(cleaners, name)
|
||||
if not cleaner:
|
||||
raise Exception('Unknown cleaner: %s' % name)
|
||||
text = cleaner(text)
|
||||
return text
|
||||
|
||||
|
||||
def _symbols_to_sequence(symbols):
|
||||
return [_symbol_to_id[s] for s in symbols if _should_keep_symbol(s)]
|
||||
|
||||
|
||||
def _arpabet_to_sequence(text):
|
||||
return _symbols_to_sequence(['@' + s for s in text.split()])
|
||||
|
||||
|
||||
def _should_keep_symbol(s):
|
||||
return s in _symbol_to_id and s is not '_' and s is not '~'
|
||||
90
text/cleaners.py
Normal file
90
text/cleaners.py
Normal file
@@ -0,0 +1,90 @@
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
|
||||
'''
|
||||
Cleaners are transformations that run over the input text at both training and eval time.
|
||||
|
||||
Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
|
||||
hyperparameter. Some cleaners are English-specific. You'll typically want to use:
|
||||
1. "english_cleaners" for English text
|
||||
2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
|
||||
the Unidecode library (https://pypi.python.org/pypi/Unidecode)
|
||||
3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
|
||||
the symbols in symbols.py to match your data).
|
||||
'''
|
||||
|
||||
import re
|
||||
from unidecode import unidecode
|
||||
from .numbers import normalize_numbers
|
||||
|
||||
|
||||
# Regular expression matching whitespace:
|
||||
_whitespace_re = re.compile(r'\s+')
|
||||
|
||||
# List of (regular expression, replacement) pairs for abbreviations:
|
||||
_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
|
||||
('mrs', 'misess'),
|
||||
('mr', 'mister'),
|
||||
('dr', 'doctor'),
|
||||
('st', 'saint'),
|
||||
('co', 'company'),
|
||||
('jr', 'junior'),
|
||||
('maj', 'major'),
|
||||
('gen', 'general'),
|
||||
('drs', 'doctors'),
|
||||
('rev', 'reverend'),
|
||||
('lt', 'lieutenant'),
|
||||
('hon', 'honorable'),
|
||||
('sgt', 'sergeant'),
|
||||
('capt', 'captain'),
|
||||
('esq', 'esquire'),
|
||||
('ltd', 'limited'),
|
||||
('col', 'colonel'),
|
||||
('ft', 'fort'),
|
||||
]]
|
||||
|
||||
|
||||
def expand_abbreviations(text):
|
||||
for regex, replacement in _abbreviations:
|
||||
text = re.sub(regex, replacement, text)
|
||||
return text
|
||||
|
||||
|
||||
def expand_numbers(text):
|
||||
return normalize_numbers(text)
|
||||
|
||||
|
||||
def lowercase(text):
|
||||
return text.lower()
|
||||
|
||||
|
||||
def collapse_whitespace(text):
|
||||
return re.sub(_whitespace_re, ' ', text)
|
||||
|
||||
|
||||
def convert_to_ascii(text):
|
||||
return unidecode(text)
|
||||
|
||||
|
||||
def basic_cleaners(text):
|
||||
'''Basic pipeline that lowercases and collapses whitespace without transliteration.'''
|
||||
text = lowercase(text)
|
||||
text = collapse_whitespace(text)
|
||||
return text
|
||||
|
||||
|
||||
def transliteration_cleaners(text):
|
||||
'''Pipeline for non-English text that transliterates to ASCII.'''
|
||||
text = convert_to_ascii(text)
|
||||
text = lowercase(text)
|
||||
text = collapse_whitespace(text)
|
||||
return text
|
||||
|
||||
|
||||
def english_cleaners(text):
|
||||
'''Pipeline for English text, including number and abbreviation expansion.'''
|
||||
text = convert_to_ascii(text)
|
||||
text = lowercase(text)
|
||||
text = expand_numbers(text)
|
||||
text = expand_abbreviations(text)
|
||||
text = collapse_whitespace(text)
|
||||
return text
|
||||
65
text/cmudict.py
Normal file
65
text/cmudict.py
Normal file
@@ -0,0 +1,65 @@
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
|
||||
import re
|
||||
|
||||
|
||||
valid_symbols = [
|
||||
'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2',
|
||||
'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2',
|
||||
'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'ER2', 'EY',
|
||||
'EY0', 'EY1', 'EY2', 'F', 'G', 'HH', 'IH', 'IH0', 'IH1', 'IH2', 'IY', 'IY0', 'IY1',
|
||||
'IY2', 'JH', 'K', 'L', 'M', 'N', 'NG', 'OW', 'OW0', 'OW1', 'OW2', 'OY', 'OY0',
|
||||
'OY1', 'OY2', 'P', 'R', 'S', 'SH', 'T', 'TH', 'UH', 'UH0', 'UH1', 'UH2', 'UW',
|
||||
'UW0', 'UW1', 'UW2', 'V', 'W', 'Y', 'Z', 'ZH'
|
||||
]
|
||||
|
||||
_valid_symbol_set = set(valid_symbols)
|
||||
|
||||
|
||||
class CMUDict:
|
||||
'''Thin wrapper around CMUDict data. http://www.speech.cs.cmu.edu/cgi-bin/cmudict'''
|
||||
def __init__(self, file_or_path, keep_ambiguous=True):
|
||||
if isinstance(file_or_path, str):
|
||||
with open(file_or_path, encoding='latin-1') as f:
|
||||
entries = _parse_cmudict(f)
|
||||
else:
|
||||
entries = _parse_cmudict(file_or_path)
|
||||
if not keep_ambiguous:
|
||||
entries = {word: pron for word, pron in entries.items() if len(pron) == 1}
|
||||
self._entries = entries
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return len(self._entries)
|
||||
|
||||
|
||||
def lookup(self, word):
|
||||
'''Returns list of ARPAbet pronunciations of the given word.'''
|
||||
return self._entries.get(word.upper())
|
||||
|
||||
|
||||
|
||||
_alt_re = re.compile(r'\([0-9]+\)')
|
||||
|
||||
|
||||
def _parse_cmudict(file):
|
||||
cmudict = {}
|
||||
for line in file:
|
||||
if len(line) and (line[0] >= 'A' and line[0] <= 'Z' or line[0] == "'"):
|
||||
parts = line.split(' ')
|
||||
word = re.sub(_alt_re, '', parts[0])
|
||||
pronunciation = _get_pronunciation(parts[1])
|
||||
if pronunciation:
|
||||
if word in cmudict:
|
||||
cmudict[word].append(pronunciation)
|
||||
else:
|
||||
cmudict[word] = [pronunciation]
|
||||
return cmudict
|
||||
|
||||
|
||||
def _get_pronunciation(s):
|
||||
parts = s.strip().split(' ')
|
||||
for part in parts:
|
||||
if part not in _valid_symbol_set:
|
||||
return None
|
||||
return ' '.join(parts)
|
||||
71
text/numbers.py
Normal file
71
text/numbers.py
Normal file
@@ -0,0 +1,71 @@
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
|
||||
import inflect
|
||||
import re
|
||||
|
||||
|
||||
_inflect = inflect.engine()
|
||||
_comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])')
|
||||
_decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)')
|
||||
_pounds_re = re.compile(r'£([0-9\,]*[0-9]+)')
|
||||
_dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)')
|
||||
_ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)')
|
||||
_number_re = re.compile(r'[0-9]+')
|
||||
|
||||
|
||||
def _remove_commas(m):
|
||||
return m.group(1).replace(',', '')
|
||||
|
||||
|
||||
def _expand_decimal_point(m):
|
||||
return m.group(1).replace('.', ' point ')
|
||||
|
||||
|
||||
def _expand_dollars(m):
|
||||
match = m.group(1)
|
||||
parts = match.split('.')
|
||||
if len(parts) > 2:
|
||||
return match + ' dollars' # Unexpected format
|
||||
dollars = int(parts[0]) if parts[0] else 0
|
||||
cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
|
||||
if dollars and cents:
|
||||
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
|
||||
cent_unit = 'cent' if cents == 1 else 'cents'
|
||||
return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit)
|
||||
elif dollars:
|
||||
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
|
||||
return '%s %s' % (dollars, dollar_unit)
|
||||
elif cents:
|
||||
cent_unit = 'cent' if cents == 1 else 'cents'
|
||||
return '%s %s' % (cents, cent_unit)
|
||||
else:
|
||||
return 'zero dollars'
|
||||
|
||||
|
||||
def _expand_ordinal(m):
|
||||
return _inflect.number_to_words(m.group(0))
|
||||
|
||||
|
||||
def _expand_number(m):
|
||||
num = int(m.group(0))
|
||||
if num > 1000 and num < 3000:
|
||||
if num == 2000:
|
||||
return 'two thousand'
|
||||
elif num > 2000 and num < 2010:
|
||||
return 'two thousand ' + _inflect.number_to_words(num % 100)
|
||||
elif num % 100 == 0:
|
||||
return _inflect.number_to_words(num // 100) + ' hundred'
|
||||
else:
|
||||
return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ')
|
||||
else:
|
||||
return _inflect.number_to_words(num, andword='')
|
||||
|
||||
|
||||
def normalize_numbers(text):
|
||||
text = re.sub(_comma_number_re, _remove_commas, text)
|
||||
text = re.sub(_pounds_re, r'\1 pounds', text)
|
||||
text = re.sub(_dollars_re, _expand_dollars, text)
|
||||
text = re.sub(_decimal_number_re, _expand_decimal_point, text)
|
||||
text = re.sub(_ordinal_re, _expand_ordinal, text)
|
||||
text = re.sub(_number_re, _expand_number, text)
|
||||
return text
|
||||
18
text/symbols.py
Normal file
18
text/symbols.py
Normal file
@@ -0,0 +1,18 @@
|
||||
""" from https://github.com/keithito/tacotron """
|
||||
|
||||
'''
|
||||
Defines the set of symbols used in text input to the model.
|
||||
|
||||
The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. '''
|
||||
from text import cmudict
|
||||
|
||||
_pad = '_'
|
||||
_punctuation = '!\'(),.:;? '
|
||||
_special = '-'
|
||||
_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
||||
|
||||
# Prepend "@" to ARPAbet symbols to ensure uniqueness (some are the same as uppercase letters):
|
||||
_arpabet = ['@' + s for s in cmudict.valid_symbols]
|
||||
|
||||
# Export all symbols:
|
||||
symbols = [_pad] + list(_special) + list(_punctuation) + list(_letters) + _arpabet
|
||||
285
train.py
Normal file
285
train.py
Normal file
@@ -0,0 +1,285 @@
|
||||
import os
|
||||
import time
|
||||
import argparse
|
||||
import math
|
||||
from numpy import finfo
|
||||
|
||||
import torch
|
||||
from distributed import apply_gradient_allreduce
|
||||
import torch.distributed as dist
|
||||
from torch.utils.data.distributed import DistributedSampler
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
from fp16_optimizer import FP16_Optimizer
|
||||
|
||||
from model import Tacotron2
|
||||
from data_utils import TextMelLoader, TextMelCollate
|
||||
from loss_function import Tacotron2Loss
|
||||
from logger import Tacotron2Logger
|
||||
from hparams import create_hparams
|
||||
|
||||
|
||||
def batchnorm_to_float(module):
|
||||
"""Converts batch norm modules to FP32"""
|
||||
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
|
||||
module.float()
|
||||
for child in module.children():
|
||||
batchnorm_to_float(child)
|
||||
return module
|
||||
|
||||
|
||||
def reduce_tensor(tensor, num_gpus):
|
||||
rt = tensor.clone()
|
||||
dist.all_reduce(rt, op=dist.reduce_op.SUM)
|
||||
rt /= num_gpus
|
||||
return rt
|
||||
|
||||
|
||||
def init_distributed(hparams, n_gpus, rank, group_name):
|
||||
assert torch.cuda.is_available(), "Distributed mode requires CUDA."
|
||||
print("Initializing Distributed")
|
||||
|
||||
# Set cuda device so everything is done on the right GPU.
|
||||
torch.cuda.set_device(rank % torch.cuda.device_count())
|
||||
|
||||
# Initialize distributed communication
|
||||
dist.init_process_group(
|
||||
backend=hparams.dist_backend, init_method=hparams.dist_url,
|
||||
world_size=n_gpus, rank=rank, group_name=group_name)
|
||||
|
||||
print("Done initializing distributed")
|
||||
|
||||
|
||||
def prepare_dataloaders(hparams):
|
||||
# Get data, data loaders and collate function ready
|
||||
trainset = TextMelLoader(hparams.training_files, hparams)
|
||||
valset = TextMelLoader(hparams.validation_files, hparams)
|
||||
collate_fn = TextMelCollate(hparams.n_frames_per_step)
|
||||
|
||||
train_sampler = DistributedSampler(trainset) \
|
||||
if hparams.distributed_run else None
|
||||
|
||||
train_loader = DataLoader(trainset, num_workers=1, shuffle=False,
|
||||
sampler=train_sampler,
|
||||
batch_size=hparams.batch_size, pin_memory=False,
|
||||
drop_last=True, collate_fn=collate_fn)
|
||||
return train_loader, valset, collate_fn
|
||||
|
||||
|
||||
def prepare_directories_and_logger(output_directory, log_directory, rank):
|
||||
if rank == 0:
|
||||
if not os.path.isdir(output_directory):
|
||||
os.makedirs(output_directory)
|
||||
os.chmod(output_directory, 0o775)
|
||||
logger = Tacotron2Logger(os.path.join(output_directory, log_directory))
|
||||
else:
|
||||
logger = None
|
||||
return logger
|
||||
|
||||
|
||||
def load_model(hparams):
|
||||
model = Tacotron2(hparams).cuda()
|
||||
if hparams.fp16_run:
|
||||
model = batchnorm_to_float(model.half())
|
||||
model.decoder.attention_layer.score_mask_value = float(finfo('float16').min)
|
||||
|
||||
if hparams.distributed_run:
|
||||
model = DistributedDataParallel(model)
|
||||
elif torch.cuda.device_count() > 1:
|
||||
model = DataParallel(model)
|
||||
|
||||
return model
|
||||
|
||||
|
||||
def warm_start_model(checkpoint_path, model):
|
||||
assert os.path.isfile(checkpoint_path)
|
||||
print("Warm starting model from checkpoint '{}'".format(checkpoint_path))
|
||||
checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
|
||||
model.load_state_dict(checkpoint_dict['state_dict'])
|
||||
return model
|
||||
|
||||
|
||||
def load_checkpoint(checkpoint_path, model, optimizer):
|
||||
assert os.path.isfile(checkpoint_path)
|
||||
print("Loading checkpoint '{}'".format(checkpoint_path))
|
||||
checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
|
||||
model.load_state_dict(checkpoint_dict['state_dict'])
|
||||
optimizer.load_state_dict(checkpoint_dict['optimizer'])
|
||||
learning_rate = checkpoint_dict['learning_rate']
|
||||
iteration = checkpoint_dict['iteration']
|
||||
print("Loaded checkpoint '{}' from iteration {}" .format(
|
||||
checkpoint_path, iteration))
|
||||
return model, optimizer, learning_rate, iteration
|
||||
|
||||
|
||||
def save_checkpoint(model, optimizer, learning_rate, iteration, filepath):
|
||||
print("Saving model and optimizer state at iteration {} to {}".format(
|
||||
iteration, filepath))
|
||||
torch.save({'iteration': iteration,
|
||||
'state_dict': model.state_dict(),
|
||||
'optimizer': optimizer.state_dict(),
|
||||
'learning_rate': learning_rate}, filepath)
|
||||
|
||||
|
||||
def validate(model, criterion, valset, iteration, batch_size, n_gpus,
|
||||
collate_fn, logger, distributed_run, rank):
|
||||
"""Handles all the validation scoring and printing"""
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
val_sampler = DistributedSampler(valset) if distributed_run else None
|
||||
val_loader = DataLoader(valset, sampler=val_sampler, num_workers=1,
|
||||
shuffle=False, batch_size=batch_size,
|
||||
pin_memory=False, collate_fn=collate_fn)
|
||||
|
||||
val_loss = 0.0
|
||||
for i, batch in enumerate(val_loader):
|
||||
x, y = model.parse_batch(batch)
|
||||
y_pred = model(x)
|
||||
loss = criterion(y_pred, y)
|
||||
if distributed_run:
|
||||
reduced_val_loss = reduce_tensor(loss.data, num_gpus).item()
|
||||
else:
|
||||
reduced_val_loss = loss.item()
|
||||
val_loss += reduced_val_loss
|
||||
val_loss = val_loss / (i + 1)
|
||||
|
||||
model.train()
|
||||
print("Validation loss {}: {:9f} ".format(iteration, reduced_val_loss))
|
||||
logger.log_validation(reduced_val_loss, model, y, y_pred, iteration)
|
||||
|
||||
|
||||
def train(output_directory, log_directory, checkpoint_path, warm_start, n_gpus,
|
||||
rank, group_name, hparams):
|
||||
"""Training and validation logging results to tensorboard and stdout
|
||||
|
||||
Params
|
||||
------
|
||||
output_directory (string): directory to save checkpoints
|
||||
log_directory (string) directory to save tensorboard logs
|
||||
checkpoint_path(string): checkpoint path
|
||||
n_gpus (int): number of gpus
|
||||
rank (int): rank of current gpu
|
||||
hparams (object): comma separated list of "name=value" pairs.
|
||||
"""
|
||||
if hparams.distributed_run:
|
||||
init_distributed(hparams, n_gpus, rank, group_name)
|
||||
|
||||
torch.manual_seed(hparams.seed)
|
||||
torch.cuda.manual_seed(hparams.seed)
|
||||
|
||||
model = load_model(hparams)
|
||||
learning_rate = hparams.learning_rate
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
|
||||
weight_decay=hparams.weight_decay)
|
||||
if hparams.fp16_run:
|
||||
optimizer = FP16_Optimizer(
|
||||
optimizer, dynamic_loss_scale=hparams.dynamic_loss_scaling)
|
||||
|
||||
if hparams.distributed_run:
|
||||
model = apply_gradient_allreduce(model)
|
||||
|
||||
criterion = Tacotron2Loss()
|
||||
|
||||
logger = prepare_directories_and_logger(
|
||||
output_directory, log_directory, rank)
|
||||
|
||||
train_loader, valset, collate_fn = prepare_dataloaders(hparams)
|
||||
|
||||
# Load checkpoint if one exists
|
||||
iteration = 0
|
||||
epoch_offset = 0
|
||||
if checkpoint_path is not None:
|
||||
if warm_start:
|
||||
model = warm_start_model(checkpoint_path, model)
|
||||
else:
|
||||
model, optimizer, _learning_rate, iteration = load_checkpoint(
|
||||
checkpoint_path, model, optimizer)
|
||||
if hparams.use_saved_learning_rate:
|
||||
learning_rate = _learning_rate
|
||||
iteration += 1 # next iteration is iteration + 1
|
||||
epoch_offset = max(0, int(iteration / len(train_loader)))
|
||||
|
||||
model.train()
|
||||
# ================ MAIN TRAINNIG LOOP! ===================
|
||||
for epoch in range(epoch_offset, hparams.epochs):
|
||||
print("Epoch: {}".format(epoch))
|
||||
for i, batch in enumerate(train_loader):
|
||||
start = time.perf_counter()
|
||||
for param_group in optimizer.param_groups:
|
||||
param_group['lr'] = learning_rate
|
||||
|
||||
model.zero_grad()
|
||||
x, y = model.parse_batch(batch)
|
||||
y_pred = model(x)
|
||||
|
||||
loss = criterion(y_pred, y)
|
||||
if hparams.distributed_run:
|
||||
reduced_loss = reduce_tensor(loss.data, num_gpus).item()
|
||||
else:
|
||||
reduced_loss = loss.item()
|
||||
|
||||
if hparams.fp16_run:
|
||||
optimizer.backward(loss)
|
||||
grad_norm = optimizer.clip_fp32_grads(hparams.grad_clip_thresh)
|
||||
else:
|
||||
loss.backward()
|
||||
grad_norm = torch.nn.utils.clip_grad_norm_(
|
||||
model.parameters(), hparams.grad_clip_thresh)
|
||||
|
||||
optimizer.step()
|
||||
|
||||
overflow = optimizer.overflow if hparams.fp16_run else False
|
||||
|
||||
if not overflow and not math.isnan(reduced_loss) and rank == 0:
|
||||
duration = time.perf_counter() - start
|
||||
print("Train loss {} {:.6f} Grad Norm {:.6f} {:.2f}s/it".format(
|
||||
iteration, reduced_loss, grad_norm, duration))
|
||||
logger.log_training(
|
||||
reduced_loss, grad_norm, learning_rate, duration, iteration)
|
||||
|
||||
if not overflow and (iteration % hparams.iters_per_checkpoint == 0):
|
||||
validate(model, criterion, valset, iteration, hparams.batch_size,
|
||||
n_gpus, collate_fn, logger, hparams.distributed_run, rank)
|
||||
|
||||
if rank == 0:
|
||||
checkpoint_path = os.path.join(
|
||||
output_directory, "checkpoint_{}".format(iteration))
|
||||
save_checkpoint(model, optimizer, learning_rate, iteration,
|
||||
checkpoint_path)
|
||||
|
||||
iteration += 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-o', '--output_directory', type=str,
|
||||
help='directory to save checkpoints')
|
||||
parser.add_argument('-l', '--log_directory', type=str,
|
||||
help='directory to save tensorboard logs')
|
||||
parser.add_argument('-c', '--checkpoint_path', type=str, default=None,
|
||||
required=False, help='checkpoint path')
|
||||
parser.add_argument('--warm_start', action='store_true',
|
||||
help='load the model only (warm start)')
|
||||
parser.add_argument('--n_gpus', type=int, default=1,
|
||||
required=False, help='number of gpus')
|
||||
parser.add_argument('--rank', type=int, default=0,
|
||||
required=False, help='rank of current gpu')
|
||||
parser.add_argument('--group_name', type=str, default='group_name',
|
||||
required=False, help='Distributed group name')
|
||||
parser.add_argument('--hparams', type=str,
|
||||
required=False, help='comma separated name=value pairs')
|
||||
|
||||
args = parser.parse_args()
|
||||
hparams = create_hparams(args.hparams)
|
||||
|
||||
torch.backends.cudnn.enabled = hparams.cudnn_enabled
|
||||
torch.backends.cudnn.benchmark = hparams.cudnn_benchmark
|
||||
|
||||
print("FP16 Run:", hparams.fp16_run)
|
||||
print("Dynamic Loss Scaling:", hparams.dynamic_loss_scaling)
|
||||
print("Distributed Run:", hparams.distributed_run)
|
||||
print("cuDNN Enabled:", hparams.cudnn_enabled)
|
||||
print("cuDNN Benchmark:", hparams.cudnn_benchmark)
|
||||
|
||||
train(args.output_directory, args.log_directory, args.checkpoint_path,
|
||||
args.warm_start, args.n_gpus, args.rank, args.group_name, hparams)
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import numpy as np
|
||||
from scipy.io.wavfile import read
|
||||
import torch
|
||||
@@ -6,9 +5,7 @@ import torch
|
||||
|
||||
def get_mask_from_lengths(lengths):
|
||||
max_len = torch.max(lengths).item()
|
||||
ids = torch.arange(
|
||||
0, max_len, out=torch.LongTensor(max_len)
|
||||
) # initially out = torch.LongTensor(max_len)
|
||||
ids = torch.arange(0, max_len, out=torch.cuda.LongTensor(max_len))
|
||||
mask = (ids < lengths.unsqueeze(1)).byte()
|
||||
return mask
|
||||
|
||||
@@ -19,7 +16,7 @@ def load_wav_to_torch(full_path):
|
||||
|
||||
|
||||
def load_filepaths_and_text(filename, split="|"):
|
||||
with open(filename, encoding="utf-8") as f:
|
||||
with open(filename, encoding='utf-8') as f:
|
||||
filepaths_and_text = [line.strip().split(split) for line in f]
|
||||
return filepaths_and_text
|
||||
|
||||
@@ -27,6 +24,6 @@ def load_filepaths_and_text(filename, split="|"):
|
||||
def to_gpu(x):
|
||||
x = x.contiguous()
|
||||
|
||||
if torch.cuda.is_available(): #initially not commented out
|
||||
x = x.cuda(non_blocking=True) # initially not commented out
|
||||
if torch.cuda.is_available():
|
||||
x = x.cuda(non_blocking=True)
|
||||
return torch.autograd.Variable(x)
|
||||
1
waveglow
Submodule
1
waveglow
Submodule
Submodule waveglow added at 4b1001fa33
Reference in New Issue
Block a user