diff --git a/.gitattributes b/.gitattributes
index f133638ba4ce4ecd503e2e31832ada20b01d3586..83762360087ec9a03c46706f5dcfe69bbf98b004 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -34,3 +34,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
vocoder filter=lfs diff=lfs merge=lfs -text
+matcha/utils/monotonic_align/core.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
diff --git a/matcha/VERSION b/matcha/VERSION
new file mode 100644
index 0000000000000000000000000000000000000000..5bcb0a7f3b37aee6eaa0bbff8d5cde2c79fbe7ec
--- /dev/null
+++ b/matcha/VERSION
@@ -0,0 +1 @@
+0.0.6.0
diff --git a/matcha/__init__.py b/matcha/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/__pycache__/__init__.cpython-310.pyc b/matcha/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57840a29f43c5a0d8c54e49969fe1e29d3c21b36
Binary files /dev/null and b/matcha/__pycache__/__init__.cpython-310.pyc differ
diff --git a/matcha/__pycache__/__init__.cpython-311.pyc b/matcha/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6f94eb411fc989d75c0bb21c40f4225f98f57b2
Binary files /dev/null and b/matcha/__pycache__/__init__.cpython-311.pyc differ
diff --git a/matcha/__pycache__/__init__.py b/matcha/__pycache__/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/__pycache__/cli.cpython-310.pyc b/matcha/__pycache__/cli.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa539db21c8178b795afc4b3c0b06ae922e3f870
Binary files /dev/null and b/matcha/__pycache__/cli.cpython-310.pyc differ
diff --git a/matcha/data/__init__.py b/matcha/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/data/__pycache__/__init__.cpython-310.pyc b/matcha/data/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..114703bd4c51fc0aa590f871aa1e79beade06303
Binary files /dev/null and b/matcha/data/__pycache__/__init__.cpython-310.pyc differ
diff --git a/matcha/data/__pycache__/__init__.py b/matcha/data/__pycache__/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/data/__pycache__/text_mel_datamodule.cpython-310.pyc b/matcha/data/__pycache__/text_mel_datamodule.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6796422cb4ac55d63a4cb1c1015a73d2e90dda1
Binary files /dev/null and b/matcha/data/__pycache__/text_mel_datamodule.cpython-310.pyc differ
diff --git a/matcha/data/components/__init__.py b/matcha/data/components/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/data/text_mel_datamodule.py b/matcha/data/text_mel_datamodule.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce18036b55dd0ae9e67ec56d6f6f6c7273a4db2d
--- /dev/null
+++ b/matcha/data/text_mel_datamodule.py
@@ -0,0 +1,275 @@
+import random
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+import numpy as np
+import torch
+import torchaudio as ta
+from lightning import LightningDataModule
+from torch.utils.data.dataloader import DataLoader
+
+from matcha.text import text_to_sequence
+from matcha.utils.audio import mel_spectrogram
+from matcha.utils.model import fix_len_compatibility, normalize
+from matcha.utils.utils import intersperse
+
+
+def parse_filelist(filelist_path, split_char="|"):
+ with open(filelist_path, encoding="utf-8") as f:
+ filepaths_and_text = [line.strip().split(split_char) for line in f]
+ return filepaths_and_text
+
+
+class TextMelDataModule(LightningDataModule):
+ def __init__( # pylint: disable=unused-argument
+ self,
+ name,
+ train_filelist_path,
+ valid_filelist_path,
+ batch_size,
+ num_workers,
+ pin_memory,
+ cleaners,
+ add_blank,
+ n_spks,
+ n_fft,
+ n_feats,
+ sample_rate,
+ hop_length,
+ win_length,
+ f_min,
+ f_max,
+ data_statistics,
+ seed,
+ load_durations,
+ ):
+ super().__init__()
+
+ # this line allows to access init params with 'self.hparams' attribute
+ # also ensures init params will be stored in ckpt
+ self.save_hyperparameters(logger=False)
+
+ def setup(self, stage: Optional[str] = None): # pylint: disable=unused-argument
+ """Load data. Set variables: `self.data_train`, `self.data_val`, `self.data_test`.
+
+ This method is called by lightning with both `trainer.fit()` and `trainer.test()`, so be
+ careful not to execute things like random split twice!
+ """
+ # load and split datasets only if not loaded already
+
+ self.trainset = TextMelDataset( # pylint: disable=attribute-defined-outside-init
+ self.hparams.train_filelist_path,
+ self.hparams.n_spks,
+ self.hparams.cleaners,
+ self.hparams.add_blank,
+ self.hparams.n_fft,
+ self.hparams.n_feats,
+ self.hparams.sample_rate,
+ self.hparams.hop_length,
+ self.hparams.win_length,
+ self.hparams.f_min,
+ self.hparams.f_max,
+ self.hparams.data_statistics,
+ self.hparams.seed,
+ self.hparams.load_durations,
+ )
+ self.validset = TextMelDataset( # pylint: disable=attribute-defined-outside-init
+ self.hparams.valid_filelist_path,
+ self.hparams.n_spks,
+ self.hparams.cleaners,
+ self.hparams.add_blank,
+ self.hparams.n_fft,
+ self.hparams.n_feats,
+ self.hparams.sample_rate,
+ self.hparams.hop_length,
+ self.hparams.win_length,
+ self.hparams.f_min,
+ self.hparams.f_max,
+ self.hparams.data_statistics,
+ self.hparams.seed,
+ self.hparams.load_durations,
+ )
+
+ def train_dataloader(self):
+ return DataLoader(
+ dataset=self.trainset,
+ batch_size=self.hparams.batch_size,
+ num_workers=self.hparams.num_workers,
+ pin_memory=self.hparams.pin_memory,
+ shuffle=True,
+ collate_fn=TextMelBatchCollate(self.hparams.n_spks),
+ )
+
+ def val_dataloader(self):
+ return DataLoader(
+ dataset=self.validset,
+ batch_size=self.hparams.batch_size,
+ num_workers=self.hparams.num_workers,
+ pin_memory=self.hparams.pin_memory,
+ shuffle=False,
+ collate_fn=TextMelBatchCollate(self.hparams.n_spks),
+ )
+
+ def teardown(self, stage: Optional[str] = None):
+ """Clean up after fit or test."""
+ pass # pylint: disable=unnecessary-pass
+
+ def state_dict(self):
+ """Extra things to save to checkpoint."""
+ return {}
+
+ def load_state_dict(self, state_dict: Dict[str, Any]):
+ """Things to do when loading checkpoint."""
+ pass # pylint: disable=unnecessary-pass
+
+
+class TextMelDataset(torch.utils.data.Dataset):
+ def __init__(
+ self,
+ filelist_path,
+ n_spks,
+ cleaners,
+ add_blank=True,
+ n_fft=1024,
+ n_mels=80,
+ sample_rate=22050,
+ hop_length=256,
+ win_length=1024,
+ f_min=0.0,
+ f_max=8000,
+ data_parameters=None,
+ seed=None,
+ load_durations=False,
+ ):
+ self.filepaths_and_text = parse_filelist(filelist_path)
+ self.n_spks = n_spks
+ self.cleaners = cleaners
+ self.add_blank = add_blank
+ self.n_fft = n_fft
+ self.n_mels = n_mels
+ self.sample_rate = sample_rate
+ self.hop_length = hop_length
+ self.win_length = win_length
+ self.f_min = f_min
+ self.f_max = f_max
+ self.load_durations = load_durations
+
+ if data_parameters is not None:
+ self.data_parameters = data_parameters
+ else:
+ self.data_parameters = {"mel_mean": 0, "mel_std": 1}
+ random.seed(seed)
+ random.shuffle(self.filepaths_and_text)
+
+ def get_datapoint(self, filepath_and_text):
+ if self.n_spks > 1:
+ filepath, spk, text = (
+ filepath_and_text[0],
+ int(filepath_and_text[1]),
+ filepath_and_text[2],
+ )
+ else:
+ filepath, text = filepath_and_text[0], filepath_and_text[1]
+ spk = None
+
+ text, cleaned_text = self.get_text(text, add_blank=self.add_blank)
+ mel = self.get_mel(filepath)
+
+ durations = self.get_durations(filepath, text) if self.load_durations else None
+
+ return {"x": text, "y": mel, "spk": spk, "filepath": filepath, "x_text": cleaned_text, "durations": durations}
+
+ def get_durations(self, filepath, text):
+ filepath = Path(filepath)
+ data_dir, name = filepath.parent.parent, filepath.stem
+
+ try:
+ dur_loc = data_dir / "durations" / f"{name}.npy"
+ durs = torch.from_numpy(np.load(dur_loc).astype(int))
+
+ except FileNotFoundError as e:
+ raise FileNotFoundError(
+ f"Tried loading the durations but durations didn't exist at {dur_loc}, make sure you've generate the durations first using: python matcha/utils/get_durations_from_trained_model.py \n"
+ ) from e
+
+ assert len(durs) == len(text), f"Length of durations {len(durs)} and text {len(text)} do not match"
+
+ return durs
+
+ def get_mel(self, filepath):
+ audio, sr = ta.load(filepath)
+ assert sr == self.sample_rate
+ mel = mel_spectrogram(
+ audio,
+ self.n_fft,
+ self.n_mels,
+ self.sample_rate,
+ self.hop_length,
+ self.win_length,
+ self.f_min,
+ self.f_max,
+ center=False,
+ ).squeeze()
+ mel = normalize(mel, self.data_parameters["mel_mean"], self.data_parameters["mel_std"])
+ return mel
+
+ def get_text(self, text, add_blank=True):
+ text_norm, cleaned_text = text_to_sequence(text, self.cleaners)
+ if self.add_blank:
+ text_norm = intersperse(text_norm, 0)
+ text_norm = torch.IntTensor(text_norm)
+ return text_norm, cleaned_text
+
+ def __getitem__(self, index):
+ datapoint = self.get_datapoint(self.filepaths_and_text[index])
+ return datapoint
+
+ def __len__(self):
+ return len(self.filepaths_and_text)
+
+
+class TextMelBatchCollate:
+ def __init__(self, n_spks):
+ self.n_spks = n_spks
+
+ def __call__(self, batch):
+ B = len(batch)
+ y_max_length = max([item["y"].shape[-1] for item in batch])
+ y_max_length = fix_len_compatibility(y_max_length)
+ x_max_length = max([item["x"].shape[-1] for item in batch])
+ n_feats = batch[0]["y"].shape[-2]
+
+ y = torch.zeros((B, n_feats, y_max_length), dtype=torch.float32)
+ x = torch.zeros((B, x_max_length), dtype=torch.long)
+ durations = torch.zeros((B, x_max_length), dtype=torch.long)
+
+ y_lengths, x_lengths = [], []
+ spks = []
+ filepaths, x_texts = [], []
+ for i, item in enumerate(batch):
+ y_, x_ = item["y"], item["x"]
+ y_lengths.append(y_.shape[-1])
+ x_lengths.append(x_.shape[-1])
+ #here
+ y[i, :, : y_.shape[-1]] = y_
+ x[i, : x_.shape[-1]] = x_
+ spks.append(item["spk"])
+ filepaths.append(item["filepath"])
+ x_texts.append(item["x_text"])
+ if item["durations"] is not None:
+ durations[i, : item["durations"].shape[-1]] = item["durations"]
+
+ y_lengths = torch.tensor(y_lengths, dtype=torch.long)
+ x_lengths = torch.tensor(x_lengths, dtype=torch.long)
+ spks = torch.tensor(spks, dtype=torch.long) if self.n_spks > 1 else None
+
+ return {
+ "x": x,
+ "x_lengths": x_lengths,
+ "y": y,
+ "y_lengths": y_lengths,
+ "spks": spks,
+ "filepaths": filepaths,
+ "x_texts": x_texts,
+ "durations": durations if not torch.eq(durations, 0).all() else None,
+ }
diff --git a/matcha/hifigan/LICENSE b/matcha/hifigan/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..91751daed806f63ac594cf077a3065f719a41662
--- /dev/null
+++ b/matcha/hifigan/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020 Jungil Kong
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/matcha/hifigan/README.md b/matcha/hifigan/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..5db25850451a794b1db1b15b08e82c1d802edbb3
--- /dev/null
+++ b/matcha/hifigan/README.md
@@ -0,0 +1,101 @@
+# HiFi-GAN: Generative Adversarial Networks for Efficient and High Fidelity Speech Synthesis
+
+### Jungil Kong, Jaehyeon Kim, Jaekyoung Bae
+
+In our [paper](https://arxiv.org/abs/2010.05646),
+we proposed HiFi-GAN: a GAN-based model capable of generating high fidelity speech efficiently.
+We provide our implementation and pretrained models as open source in this repository.
+
+**Abstract :**
+Several recent work on speech synthesis have employed generative adversarial networks (GANs) to produce raw waveforms.
+Although such methods improve the sampling efficiency and memory usage,
+their sample quality has not yet reached that of autoregressive and flow-based generative models.
+In this work, we propose HiFi-GAN, which achieves both efficient and high-fidelity speech synthesis.
+As speech audio consists of sinusoidal signals with various periods,
+we demonstrate that modeling periodic patterns of an audio is crucial for enhancing sample quality.
+A subjective human evaluation (mean opinion score, MOS) of a single speaker dataset indicates that our proposed method
+demonstrates similarity to human quality while generating 22.05 kHz high-fidelity audio 167.9 times faster than
+real-time on a single V100 GPU. We further show the generality of HiFi-GAN to the mel-spectrogram inversion of unseen
+speakers and end-to-end speech synthesis. Finally, a small footprint version of HiFi-GAN generates samples 13.4 times
+faster than real-time on CPU with comparable quality to an autoregressive counterpart.
+
+Visit our [demo website](https://jik876.github.io/hifi-gan-demo/) for audio samples.
+
+## Pre-requisites
+
+1. Python >= 3.6
+2. Clone this repository.
+3. Install python requirements. Please refer [requirements.txt](requirements.txt)
+4. Download and extract the [LJ Speech dataset](https://keithito.com/LJ-Speech-Dataset/).
+ And move all wav files to `LJSpeech-1.1/wavs`
+
+## Training
+
+```
+python train.py --config config_v1.json
+```
+
+To train V2 or V3 Generator, replace `config_v1.json` with `config_v2.json` or `config_v3.json`.
+Checkpoints and copy of the configuration file are saved in `cp_hifigan` directory by default.
+You can change the path by adding `--checkpoint_path` option.
+
+Validation loss during training with V1 generator.
+
+
+## Pretrained Model
+
+You can also use pretrained models we provide.
+[Download pretrained models](https://drive.google.com/drive/folders/1-eEYTB5Av9jNql0WGBlRoi-WH2J7bp5Y?usp=sharing)
+Details of each folder are as in follows:
+
+| Folder Name | Generator | Dataset | Fine-Tuned |
+| ------------ | --------- | --------- | ------------------------------------------------------ |
+| LJ_V1 | V1 | LJSpeech | No |
+| LJ_V2 | V2 | LJSpeech | No |
+| LJ_V3 | V3 | LJSpeech | No |
+| LJ_FT_T2_V1 | V1 | LJSpeech | Yes ([Tacotron2](https://github.com/NVIDIA/tacotron2)) |
+| LJ_FT_T2_V2 | V2 | LJSpeech | Yes ([Tacotron2](https://github.com/NVIDIA/tacotron2)) |
+| LJ_FT_T2_V3 | V3 | LJSpeech | Yes ([Tacotron2](https://github.com/NVIDIA/tacotron2)) |
+| VCTK_V1 | V1 | VCTK | No |
+| VCTK_V2 | V2 | VCTK | No |
+| VCTK_V3 | V3 | VCTK | No |
+| UNIVERSAL_V1 | V1 | Universal | No |
+
+We provide the universal model with discriminator weights that can be used as a base for transfer learning to other datasets.
+
+## Fine-Tuning
+
+1. Generate mel-spectrograms in numpy format using [Tacotron2](https://github.com/NVIDIA/tacotron2) with teacher-forcing.
+ The file name of the generated mel-spectrogram should match the audio file and the extension should be `.npy`.
+ Example:
+ ` Audio File : LJ001-0001.wav
+Mel-Spectrogram File : LJ001-0001.npy`
+2. Create `ft_dataset` folder and copy the generated mel-spectrogram files into it.
+3. Run the following command.
+ ```
+ python train.py --fine_tuning True --config config_v1.json
+ ```
+ For other command line options, please refer to the training section.
+
+## Inference from wav file
+
+1. Make `test_files` directory and copy wav files into the directory.
+2. Run the following command.
+ ` python inference.py --checkpoint_file [generator checkpoint file path]`
+ Generated wav files are saved in `generated_files` by default.
+ You can change the path by adding `--output_dir` option.
+
+## Inference for end-to-end speech synthesis
+
+1. Make `test_mel_files` directory and copy generated mel-spectrogram files into the directory.
+ You can generate mel-spectrograms using [Tacotron2](https://github.com/NVIDIA/tacotron2),
+ [Glow-TTS](https://github.com/jaywalnut310/glow-tts) and so forth.
+2. Run the following command.
+ ` python inference_e2e.py --checkpoint_file [generator checkpoint file path]`
+ Generated wav files are saved in `generated_files_from_mel` by default.
+ You can change the path by adding `--output_dir` option.
+
+## Acknowledgements
+
+We referred to [WaveGlow](https://github.com/NVIDIA/waveglow), [MelGAN](https://github.com/descriptinc/melgan-neurips)
+and [Tacotron2](https://github.com/NVIDIA/tacotron2) to implement this.
diff --git a/matcha/hifigan/__init__.py b/matcha/hifigan/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/hifigan/__pycache__/__init__.cpython-310.pyc b/matcha/hifigan/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80ebe95e2f4c5da6d40ff41c3e9df5b46d152ffc
Binary files /dev/null and b/matcha/hifigan/__pycache__/__init__.cpython-310.pyc differ
diff --git a/matcha/hifigan/__pycache__/__init__.cpython-311.pyc b/matcha/hifigan/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..335a506243e861e21fc98fc911ff1eb7f0c2e2f8
Binary files /dev/null and b/matcha/hifigan/__pycache__/__init__.cpython-311.pyc differ
diff --git a/matcha/hifigan/__pycache__/__init__.py b/matcha/hifigan/__pycache__/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/hifigan/__pycache__/config.cpython-310.pyc b/matcha/hifigan/__pycache__/config.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ae0fa44f202d41a2cbc7da3bbd7cb74ae357314
Binary files /dev/null and b/matcha/hifigan/__pycache__/config.cpython-310.pyc differ
diff --git a/matcha/hifigan/__pycache__/config.cpython-311.pyc b/matcha/hifigan/__pycache__/config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..002cafefeb2fba0b40607fdee222dc861fc0671d
Binary files /dev/null and b/matcha/hifigan/__pycache__/config.cpython-311.pyc differ
diff --git a/matcha/hifigan/__pycache__/denoiser.cpython-310.pyc b/matcha/hifigan/__pycache__/denoiser.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c4302715df3f9d88dab6d912290a0fb562492cd
Binary files /dev/null and b/matcha/hifigan/__pycache__/denoiser.cpython-310.pyc differ
diff --git a/matcha/hifigan/__pycache__/denoiser.cpython-311.pyc b/matcha/hifigan/__pycache__/denoiser.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5bf06433789e72d95a23d9ac3ed9708947e3fa15
Binary files /dev/null and b/matcha/hifigan/__pycache__/denoiser.cpython-311.pyc differ
diff --git a/matcha/hifigan/__pycache__/env.cpython-310.pyc b/matcha/hifigan/__pycache__/env.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8737e46a3f1562b221797532e230d19ed03369a
Binary files /dev/null and b/matcha/hifigan/__pycache__/env.cpython-310.pyc differ
diff --git a/matcha/hifigan/__pycache__/models.cpython-310.pyc b/matcha/hifigan/__pycache__/models.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d5e56a2adc16fd449fb03a7d47457829d82e3fc
Binary files /dev/null and b/matcha/hifigan/__pycache__/models.cpython-310.pyc differ
diff --git a/matcha/hifigan/__pycache__/models.cpython-311.pyc b/matcha/hifigan/__pycache__/models.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e3c96473604518196a014daab14c97f455a118d
Binary files /dev/null and b/matcha/hifigan/__pycache__/models.cpython-311.pyc differ
diff --git a/matcha/hifigan/__pycache__/xutils.cpython-310.pyc b/matcha/hifigan/__pycache__/xutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8b22e268132199aae2b46110ba61e7df5eef24d
Binary files /dev/null and b/matcha/hifigan/__pycache__/xutils.cpython-310.pyc differ
diff --git a/matcha/hifigan/__pycache__/xutils.cpython-311.pyc b/matcha/hifigan/__pycache__/xutils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c72ba63fa30fc88499d2f15c83dcbd41434c088e
Binary files /dev/null and b/matcha/hifigan/__pycache__/xutils.cpython-311.pyc differ
diff --git a/matcha/hifigan/config.py b/matcha/hifigan/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3abea9e151a08864353d32066bd4935e24b82e7
--- /dev/null
+++ b/matcha/hifigan/config.py
@@ -0,0 +1,28 @@
+v1 = {
+ "resblock": "1",
+ "num_gpus": 0,
+ "batch_size": 16,
+ "learning_rate": 0.0004,
+ "adam_b1": 0.8,
+ "adam_b2": 0.99,
+ "lr_decay": 0.999,
+ "seed": 1234,
+ "upsample_rates": [8, 8, 2, 2],
+ "upsample_kernel_sizes": [16, 16, 4, 4],
+ "upsample_initial_channel": 512,
+ "resblock_kernel_sizes": [3, 7, 11],
+ "resblock_dilation_sizes": [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
+ "resblock_initial_channel": 256,
+ "segment_size": 8192,
+ "num_mels": 80,
+ "num_freq": 1025,
+ "n_fft": 1024,
+ "hop_size": 256,
+ "win_size": 1024,
+ "sampling_rate": 22050,
+ "fmin": 0,
+ "fmax": 8000,
+ "fmax_loss": None,
+ "num_workers": 4,
+ "dist_config": {"dist_backend": "nccl", "dist_url": "tcp://localhost:54321", "world_size": 1},
+}
diff --git a/matcha/hifigan/denoiser.py b/matcha/hifigan/denoiser.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fd33312a09b1940374a0e29a97fe3a1a1dac7d2
--- /dev/null
+++ b/matcha/hifigan/denoiser.py
@@ -0,0 +1,64 @@
+# Code modified from Rafael Valle's implementation https://github.com/NVIDIA/waveglow/blob/5bc2a53e20b3b533362f974cfa1ea0267ae1c2b1/denoiser.py
+
+"""Waveglow style denoiser can be used to remove the artifacts from the HiFiGAN generated audio."""
+import torch
+
+
+class Denoiser(torch.nn.Module):
+ """Removes model bias from audio produced with waveglow"""
+
+ def __init__(self, vocoder, filter_length=1024, n_overlap=4, win_length=1024, mode="zeros"):
+ super().__init__()
+ self.filter_length = filter_length
+ self.hop_length = int(filter_length / n_overlap)
+ self.win_length = win_length
+
+ dtype, device = next(vocoder.parameters()).dtype, next(vocoder.parameters()).device
+ self.device = device
+ if mode == "zeros":
+ mel_input = torch.zeros((1, 80, 88), dtype=dtype, device=device)
+ elif mode == "normal":
+ mel_input = torch.randn((1, 80, 88), dtype=dtype, device=device)
+ else:
+ raise Exception(f"Mode {mode} if not supported")
+
+ def stft_fn(audio, n_fft, hop_length, win_length, window):
+ spec = torch.stft(
+ audio,
+ n_fft=n_fft,
+ hop_length=hop_length,
+ win_length=win_length,
+ window=window,
+ return_complex=True,
+ )
+ spec = torch.view_as_real(spec)
+ return torch.sqrt(spec.pow(2).sum(-1)), torch.atan2(spec[..., -1], spec[..., 0])
+
+ self.stft = lambda x: stft_fn(
+ audio=x,
+ n_fft=self.filter_length,
+ hop_length=self.hop_length,
+ win_length=self.win_length,
+ window=torch.hann_window(self.win_length, device=device),
+ )
+ self.istft = lambda x, y: torch.istft(
+ torch.complex(x * torch.cos(y), x * torch.sin(y)),
+ n_fft=self.filter_length,
+ hop_length=self.hop_length,
+ win_length=self.win_length,
+ window=torch.hann_window(self.win_length, device=device),
+ )
+
+ with torch.no_grad():
+ bias_audio = vocoder(mel_input).float().squeeze(0)
+ bias_spec, _ = self.stft(bias_audio)
+
+ self.register_buffer("bias_spec", bias_spec[:, :, 0][:, :, None])
+
+ @torch.inference_mode()
+ def forward(self, audio, strength=0.0005):
+ audio_spec, audio_angles = self.stft(audio)
+ audio_spec_denoised = audio_spec - self.bias_spec.to(audio.device) * strength
+ audio_spec_denoised = torch.clamp(audio_spec_denoised, 0.0)
+ audio_denoised = self.istft(audio_spec_denoised, audio_angles)
+ return audio_denoised
diff --git a/matcha/hifigan/env.py b/matcha/hifigan/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ea4f948a3f002921bf9bc24f52cbc1c0b1fc2ec
--- /dev/null
+++ b/matcha/hifigan/env.py
@@ -0,0 +1,17 @@
+""" from https://github.com/jik876/hifi-gan """
+
+import os
+import shutil
+
+
+class AttrDict(dict):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.__dict__ = self
+
+
+def build_env(config, config_name, path):
+ t_path = os.path.join(path, config_name)
+ if config != t_path:
+ os.makedirs(path, exist_ok=True)
+ shutil.copyfile(config, os.path.join(path, config_name))
diff --git a/matcha/hifigan/meldataset.py b/matcha/hifigan/meldataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b43ea7965e04a52d5427a485ee911b743057c4a
--- /dev/null
+++ b/matcha/hifigan/meldataset.py
@@ -0,0 +1,217 @@
+""" from https://github.com/jik876/hifi-gan """
+
+import math
+import os
+import random
+
+import numpy as np
+import torch
+import torch.utils.data
+from librosa.filters import mel as librosa_mel_fn
+from librosa.util import normalize
+from scipy.io.wavfile import read
+
+MAX_WAV_VALUE = 32768.0
+
+
+def load_wav(full_path):
+ sampling_rate, data = read(full_path)
+ return data, sampling_rate
+
+
+def dynamic_range_compression(x, C=1, clip_val=1e-5):
+ return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
+
+
+def dynamic_range_decompression(x, C=1):
+ return np.exp(x) / C
+
+
+def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
+ return torch.log(torch.clamp(x, min=clip_val) * C)
+
+
+def dynamic_range_decompression_torch(x, C=1):
+ return torch.exp(x) / C
+
+
+def spectral_normalize_torch(magnitudes):
+ output = dynamic_range_compression_torch(magnitudes)
+ return output
+
+
+def spectral_de_normalize_torch(magnitudes):
+ output = dynamic_range_decompression_torch(magnitudes)
+ return output
+
+
+mel_basis = {}
+hann_window = {}
+
+
+def mel_spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
+ if torch.min(y) < -1.0:
+ print("min value is ", torch.min(y))
+ if torch.max(y) > 1.0:
+ print("max value is ", torch.max(y))
+
+ global mel_basis, hann_window # pylint: disable=global-statement
+ if fmax not in mel_basis:
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
+ mel_basis[str(fmax) + "_" + str(y.device)] = torch.from_numpy(mel).float().to(y.device)
+ hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)
+
+ y = torch.nn.functional.pad(
+ y.unsqueeze(1), (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)), mode="reflect"
+ )
+ y = y.squeeze(1)
+
+ spec = torch.view_as_real(
+ torch.stft(
+ y,
+ n_fft,
+ hop_length=hop_size,
+ win_length=win_size,
+ window=hann_window[str(y.device)],
+ center=center,
+ pad_mode="reflect",
+ normalized=False,
+ onesided=True,
+ return_complex=True,
+ )
+ )
+
+ spec = torch.sqrt(spec.pow(2).sum(-1) + (1e-9))
+
+ spec = torch.matmul(mel_basis[str(fmax) + "_" + str(y.device)], spec)
+ spec = spectral_normalize_torch(spec)
+
+ return spec
+
+
+def get_dataset_filelist(a):
+ with open(a.input_training_file, encoding="utf-8") as fi:
+ training_files = [
+ os.path.join(a.input_wavs_dir, x.split("|")[0] + ".wav") for x in fi.read().split("\n") if len(x) > 0
+ ]
+
+ with open(a.input_validation_file, encoding="utf-8") as fi:
+ validation_files = [
+ os.path.join(a.input_wavs_dir, x.split("|")[0] + ".wav") for x in fi.read().split("\n") if len(x) > 0
+ ]
+ return training_files, validation_files
+
+
+class MelDataset(torch.utils.data.Dataset):
+ def __init__(
+ self,
+ training_files,
+ segment_size,
+ n_fft,
+ num_mels,
+ hop_size,
+ win_size,
+ sampling_rate,
+ fmin,
+ fmax,
+ split=True,
+ shuffle=True,
+ n_cache_reuse=1,
+ device=None,
+ fmax_loss=None,
+ fine_tuning=False,
+ base_mels_path=None,
+ ):
+ self.audio_files = training_files
+ random.seed(1234)
+ if shuffle:
+ random.shuffle(self.audio_files)
+ self.segment_size = segment_size
+ self.sampling_rate = sampling_rate
+ self.split = split
+ self.n_fft = n_fft
+ self.num_mels = num_mels
+ self.hop_size = hop_size
+ self.win_size = win_size
+ self.fmin = fmin
+ self.fmax = fmax
+ self.fmax_loss = fmax_loss
+ self.cached_wav = None
+ self.n_cache_reuse = n_cache_reuse
+ self._cache_ref_count = 0
+ self.device = device
+ self.fine_tuning = fine_tuning
+ self.base_mels_path = base_mels_path
+
+ def __getitem__(self, index):
+ filename = self.audio_files[index]
+ if self._cache_ref_count == 0:
+ audio, sampling_rate = load_wav(filename)
+ audio = audio / MAX_WAV_VALUE
+ if not self.fine_tuning:
+ audio = normalize(audio) * 0.95
+ self.cached_wav = audio
+ if sampling_rate != self.sampling_rate:
+ raise ValueError(f"{sampling_rate} SR doesn't match target {self.sampling_rate} SR")
+ self._cache_ref_count = self.n_cache_reuse
+ else:
+ audio = self.cached_wav
+ self._cache_ref_count -= 1
+
+ audio = torch.FloatTensor(audio)
+ audio = audio.unsqueeze(0)
+
+ if not self.fine_tuning:
+ if self.split:
+ if audio.size(1) >= self.segment_size:
+ max_audio_start = audio.size(1) - self.segment_size
+ audio_start = random.randint(0, max_audio_start)
+ audio = audio[:, audio_start : audio_start + self.segment_size]
+ else:
+ audio = torch.nn.functional.pad(audio, (0, self.segment_size - audio.size(1)), "constant")
+
+ mel = mel_spectrogram(
+ audio,
+ self.n_fft,
+ self.num_mels,
+ self.sampling_rate,
+ self.hop_size,
+ self.win_size,
+ self.fmin,
+ self.fmax,
+ center=False,
+ )
+ else:
+ mel = np.load(os.path.join(self.base_mels_path, os.path.splitext(os.path.split(filename)[-1])[0] + ".npy"))
+ mel = torch.from_numpy(mel)
+
+ if len(mel.shape) < 3:
+ mel = mel.unsqueeze(0)
+
+ if self.split:
+ frames_per_seg = math.ceil(self.segment_size / self.hop_size)
+
+ if audio.size(1) >= self.segment_size:
+ mel_start = random.randint(0, mel.size(2) - frames_per_seg - 1)
+ mel = mel[:, :, mel_start : mel_start + frames_per_seg]
+ audio = audio[:, mel_start * self.hop_size : (mel_start + frames_per_seg) * self.hop_size]
+ else:
+ mel = torch.nn.functional.pad(mel, (0, frames_per_seg - mel.size(2)), "constant")
+ audio = torch.nn.functional.pad(audio, (0, self.segment_size - audio.size(1)), "constant")
+
+ mel_loss = mel_spectrogram(
+ audio,
+ self.n_fft,
+ self.num_mels,
+ self.sampling_rate,
+ self.hop_size,
+ self.win_size,
+ self.fmin,
+ self.fmax_loss,
+ center=False,
+ )
+
+ return (mel.squeeze(), audio.squeeze(0), filename, mel_loss.squeeze())
+
+ def __len__(self):
+ return len(self.audio_files)
diff --git a/matcha/hifigan/models.py b/matcha/hifigan/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..d209d9a4e99ec29e4167a5a2eaa62d72b3eff694
--- /dev/null
+++ b/matcha/hifigan/models.py
@@ -0,0 +1,368 @@
+""" from https://github.com/jik876/hifi-gan """
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
+from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
+
+from .xutils import get_padding, init_weights
+
+LRELU_SLOPE = 0.1
+
+
+class ResBlock1(torch.nn.Module):
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)):
+ super().__init__()
+ self.h = h
+ self.convs1 = nn.ModuleList(
+ [
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=dilation[0],
+ padding=get_padding(kernel_size, dilation[0]),
+ )
+ ),
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=dilation[1],
+ padding=get_padding(kernel_size, dilation[1]),
+ )
+ ),
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=dilation[2],
+ padding=get_padding(kernel_size, dilation[2]),
+ )
+ ),
+ ]
+ )
+ self.convs1.apply(init_weights)
+
+ self.convs2 = nn.ModuleList(
+ [
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=1,
+ padding=get_padding(kernel_size, 1),
+ )
+ ),
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=1,
+ padding=get_padding(kernel_size, 1),
+ )
+ ),
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=1,
+ padding=get_padding(kernel_size, 1),
+ )
+ ),
+ ]
+ )
+ self.convs2.apply(init_weights)
+
+ def forward(self, x):
+ for c1, c2 in zip(self.convs1, self.convs2):
+ xt = F.leaky_relu(x, LRELU_SLOPE)
+ xt = c1(xt)
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
+ xt = c2(xt)
+ x = xt + x
+ return x
+
+ def remove_weight_norm(self):
+ for l in self.convs1:
+ remove_weight_norm(l)
+ for l in self.convs2:
+ remove_weight_norm(l)
+
+
+class ResBlock2(torch.nn.Module):
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)):
+ super().__init__()
+ self.h = h
+ self.convs = nn.ModuleList(
+ [
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=dilation[0],
+ padding=get_padding(kernel_size, dilation[0]),
+ )
+ ),
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=dilation[1],
+ padding=get_padding(kernel_size, dilation[1]),
+ )
+ ),
+ ]
+ )
+ self.convs.apply(init_weights)
+
+ def forward(self, x):
+ for c in self.convs:
+ xt = F.leaky_relu(x, LRELU_SLOPE)
+ xt = c(xt)
+ x = xt + x
+ return x
+
+ def remove_weight_norm(self):
+ for l in self.convs:
+ remove_weight_norm(l)
+
+
+class Generator(torch.nn.Module):
+ def __init__(self, h):
+ super().__init__()
+ self.h = h
+ self.num_kernels = len(h.resblock_kernel_sizes)
+ self.num_upsamples = len(h.upsample_rates)
+ self.conv_pre = weight_norm(Conv1d(80, h.upsample_initial_channel, 7, 1, padding=3))
+ resblock = ResBlock1 if h.resblock == "1" else ResBlock2
+
+ self.ups = nn.ModuleList()
+ for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
+ self.ups.append(
+ weight_norm(
+ ConvTranspose1d(
+ h.upsample_initial_channel // (2**i),
+ h.upsample_initial_channel // (2 ** (i + 1)),
+ k,
+ u,
+ padding=(k - u) // 2,
+ )
+ )
+ )
+
+ self.resblocks = nn.ModuleList()
+ for i in range(len(self.ups)):
+ ch = h.upsample_initial_channel // (2 ** (i + 1))
+ for _, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
+ self.resblocks.append(resblock(h, ch, k, d))
+
+ self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
+ self.ups.apply(init_weights)
+ self.conv_post.apply(init_weights)
+
+ def forward(self, x):
+ x = self.conv_pre(x)
+ for i in range(self.num_upsamples):
+ x = F.leaky_relu(x, LRELU_SLOPE)
+ x = self.ups[i](x)
+ xs = None
+ for j in range(self.num_kernels):
+ if xs is None:
+ xs = self.resblocks[i * self.num_kernels + j](x)
+ else:
+ xs += self.resblocks[i * self.num_kernels + j](x)
+ x = xs / self.num_kernels
+ x = F.leaky_relu(x)
+ x = self.conv_post(x)
+ x = torch.tanh(x)
+
+ return x
+
+ def remove_weight_norm(self):
+ print("Removing weight norm...")
+ for l in self.ups:
+ remove_weight_norm(l)
+ for l in self.resblocks:
+ l.remove_weight_norm()
+ remove_weight_norm(self.conv_pre)
+ remove_weight_norm(self.conv_post)
+
+
+class DiscriminatorP(torch.nn.Module):
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
+ super().__init__()
+ self.period = period
+ norm_f = weight_norm if use_spectral_norm is False else spectral_norm
+ self.convs = nn.ModuleList(
+ [
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(2, 0))),
+ ]
+ )
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
+
+ def forward(self, x):
+ fmap = []
+
+ # 1d to 2d
+ b, c, t = x.shape
+ if t % self.period != 0: # pad first
+ n_pad = self.period - (t % self.period)
+ x = F.pad(x, (0, n_pad), "reflect")
+ t = t + n_pad
+ x = x.view(b, c, t // self.period, self.period)
+
+ for l in self.convs:
+ x = l(x)
+ x = F.leaky_relu(x, LRELU_SLOPE)
+ fmap.append(x)
+ x = self.conv_post(x)
+ fmap.append(x)
+ x = torch.flatten(x, 1, -1)
+
+ return x, fmap
+
+
+class MultiPeriodDiscriminator(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.discriminators = nn.ModuleList(
+ [
+ DiscriminatorP(2),
+ DiscriminatorP(3),
+ DiscriminatorP(5),
+ DiscriminatorP(7),
+ DiscriminatorP(11),
+ ]
+ )
+
+ def forward(self, y, y_hat):
+ y_d_rs = []
+ y_d_gs = []
+ fmap_rs = []
+ fmap_gs = []
+ for _, d in enumerate(self.discriminators):
+ y_d_r, fmap_r = d(y)
+ y_d_g, fmap_g = d(y_hat)
+ y_d_rs.append(y_d_r)
+ fmap_rs.append(fmap_r)
+ y_d_gs.append(y_d_g)
+ fmap_gs.append(fmap_g)
+
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
+
+
+class DiscriminatorS(torch.nn.Module):
+ def __init__(self, use_spectral_norm=False):
+ super().__init__()
+ norm_f = weight_norm if use_spectral_norm is False else spectral_norm
+ self.convs = nn.ModuleList(
+ [
+ norm_f(Conv1d(1, 128, 15, 1, padding=7)),
+ norm_f(Conv1d(128, 128, 41, 2, groups=4, padding=20)),
+ norm_f(Conv1d(128, 256, 41, 2, groups=16, padding=20)),
+ norm_f(Conv1d(256, 512, 41, 4, groups=16, padding=20)),
+ norm_f(Conv1d(512, 1024, 41, 4, groups=16, padding=20)),
+ norm_f(Conv1d(1024, 1024, 41, 1, groups=16, padding=20)),
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
+ ]
+ )
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
+
+ def forward(self, x):
+ fmap = []
+ for l in self.convs:
+ x = l(x)
+ x = F.leaky_relu(x, LRELU_SLOPE)
+ fmap.append(x)
+ x = self.conv_post(x)
+ fmap.append(x)
+ x = torch.flatten(x, 1, -1)
+
+ return x, fmap
+
+
+class MultiScaleDiscriminator(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.discriminators = nn.ModuleList(
+ [
+ DiscriminatorS(use_spectral_norm=True),
+ DiscriminatorS(),
+ DiscriminatorS(),
+ ]
+ )
+ self.meanpools = nn.ModuleList([AvgPool1d(4, 2, padding=2), AvgPool1d(4, 2, padding=2)])
+
+ def forward(self, y, y_hat):
+ y_d_rs = []
+ y_d_gs = []
+ fmap_rs = []
+ fmap_gs = []
+ for i, d in enumerate(self.discriminators):
+ if i != 0:
+ y = self.meanpools[i - 1](y)
+ y_hat = self.meanpools[i - 1](y_hat)
+ y_d_r, fmap_r = d(y)
+ y_d_g, fmap_g = d(y_hat)
+ y_d_rs.append(y_d_r)
+ fmap_rs.append(fmap_r)
+ y_d_gs.append(y_d_g)
+ fmap_gs.append(fmap_g)
+
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
+
+
+def feature_loss(fmap_r, fmap_g):
+ loss = 0
+ for dr, dg in zip(fmap_r, fmap_g):
+ for rl, gl in zip(dr, dg):
+ loss += torch.mean(torch.abs(rl - gl))
+
+ return loss * 2
+
+
+def discriminator_loss(disc_real_outputs, disc_generated_outputs):
+ loss = 0
+ r_losses = []
+ g_losses = []
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
+ r_loss = torch.mean((1 - dr) ** 2)
+ g_loss = torch.mean(dg**2)
+ loss += r_loss + g_loss
+ r_losses.append(r_loss.item())
+ g_losses.append(g_loss.item())
+
+ return loss, r_losses, g_losses
+
+
+def generator_loss(disc_outputs):
+ loss = 0
+ gen_losses = []
+ for dg in disc_outputs:
+ l = torch.mean((1 - dg) ** 2)
+ gen_losses.append(l)
+ loss += l
+
+ return loss, gen_losses
diff --git a/matcha/hifigan/xutils.py b/matcha/hifigan/xutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..eefadcb7a1d0bf9015e636b88fee3e22c9771bc5
--- /dev/null
+++ b/matcha/hifigan/xutils.py
@@ -0,0 +1,60 @@
+""" from https://github.com/jik876/hifi-gan """
+
+import glob
+import os
+
+import matplotlib
+import torch
+from torch.nn.utils import weight_norm
+
+matplotlib.use("Agg")
+import matplotlib.pylab as plt
+
+
+def plot_spectrogram(spectrogram):
+ fig, ax = plt.subplots(figsize=(10, 2))
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
+ plt.colorbar(im, ax=ax)
+
+ fig.canvas.draw()
+ plt.close()
+
+ return fig
+
+
+def init_weights(m, mean=0.0, std=0.01):
+ classname = m.__class__.__name__
+ if classname.find("Conv") != -1:
+ m.weight.data.normal_(mean, std)
+
+
+def apply_weight_norm(m):
+ classname = m.__class__.__name__
+ if classname.find("Conv") != -1:
+ weight_norm(m)
+
+
+def get_padding(kernel_size, dilation=1):
+ return int((kernel_size * dilation - dilation) / 2)
+
+
+def load_checkpoint(filepath, device):
+ assert os.path.isfile(filepath)
+ print(f"Loading '{filepath}'")
+ checkpoint_dict = torch.load(filepath, map_location=device)
+ print("Complete.")
+ return checkpoint_dict
+
+
+def save_checkpoint(filepath, obj):
+ print(f"Saving checkpoint to {filepath}")
+ torch.save(obj, filepath)
+ print("Complete.")
+
+
+def scan_checkpoint(cp_dir, prefix):
+ pattern = os.path.join(cp_dir, prefix + "????????")
+ cp_list = glob.glob(pattern)
+ if len(cp_list) == 0:
+ return None
+ return sorted(cp_list)[-1]
diff --git a/matcha/models/__init__.py b/matcha/models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/models/__pycache__/__init__.cpython-310.pyc b/matcha/models/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..010ec6af846ef49b6b2749d45534f19f45150a02
Binary files /dev/null and b/matcha/models/__pycache__/__init__.cpython-310.pyc differ
diff --git a/matcha/models/__pycache__/__init__.cpython-311.pyc b/matcha/models/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..487a5c21184e34875745821076cc3766b3efe086
Binary files /dev/null and b/matcha/models/__pycache__/__init__.cpython-311.pyc differ
diff --git a/matcha/models/__pycache__/__init__.py b/matcha/models/__pycache__/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/models/__pycache__/baselightningmodule.cpython-310.pyc b/matcha/models/__pycache__/baselightningmodule.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6978498c3d2620faa07470055f6d1b9d55ae996
Binary files /dev/null and b/matcha/models/__pycache__/baselightningmodule.cpython-310.pyc differ
diff --git a/matcha/models/__pycache__/baselightningmodule.cpython-311.pyc b/matcha/models/__pycache__/baselightningmodule.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9de635b13544eaf34cf627f80232c74f94c4960
Binary files /dev/null and b/matcha/models/__pycache__/baselightningmodule.cpython-311.pyc differ
diff --git a/matcha/models/__pycache__/matcha_tts.cpython-310.pyc b/matcha/models/__pycache__/matcha_tts.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e5b90a9a218001bd275154d3605745f92457464
Binary files /dev/null and b/matcha/models/__pycache__/matcha_tts.cpython-310.pyc differ
diff --git a/matcha/models/__pycache__/matcha_tts.cpython-311.pyc b/matcha/models/__pycache__/matcha_tts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26bd826d3da62d2e2fce164da6c8c9194d5eb4fa
Binary files /dev/null and b/matcha/models/__pycache__/matcha_tts.cpython-311.pyc differ
diff --git a/matcha/models/baselightningmodule.py b/matcha/models/baselightningmodule.py
new file mode 100644
index 0000000000000000000000000000000000000000..972b8b622148080524c90d737bb859fe61737d25
--- /dev/null
+++ b/matcha/models/baselightningmodule.py
@@ -0,0 +1,219 @@
+"""
+This is a base lightning module that can be used to train a model.
+The benefit of this abstraction is that all the logic outside of model definition can be reused for different models.
+"""
+import inspect
+from abc import ABC
+from typing import Any, Dict
+
+import torch
+from lightning import LightningModule
+from lightning.pytorch.utilities import grad_norm
+
+from matcha import utils
+from matcha.utils.utils import plot_tensor
+
+log = utils.get_pylogger(__name__)
+
+
+class BaseLightningClass(LightningModule, ABC):
+ def update_data_statistics(self, data_statistics):
+ if data_statistics is None:
+ data_statistics = {
+ "mel_mean": 0.0,
+ "mel_std": 1.0,
+ }
+
+ self.register_buffer("mel_mean", torch.tensor(data_statistics["mel_mean"]))
+ self.register_buffer("mel_std", torch.tensor(data_statistics["mel_std"]))
+
+ def configure_optimizers(self) -> Any:
+ optimizer = self.hparams.optimizer(params=self.parameters())
+ if self.hparams.scheduler not in (None, {}):
+ scheduler_args = {}
+ # Manage last epoch for exponential schedulers
+ if "last_epoch" in inspect.signature(self.hparams.scheduler.scheduler).parameters:
+ if hasattr(self, "ckpt_loaded_epoch"):
+ current_epoch = self.ckpt_loaded_epoch - 1
+ else:
+ current_epoch = -1
+
+ scheduler_args.update({"optimizer": optimizer})
+ scheduler = self.hparams.scheduler.scheduler(**scheduler_args)
+ scheduler.last_epoch = current_epoch
+ return {
+ "optimizer": optimizer,
+ "lr_scheduler": {
+ "scheduler": scheduler,
+ "interval": self.hparams.scheduler.lightning_args.interval,
+ "frequency": self.hparams.scheduler.lightning_args.frequency,
+ "name": "learning_rate",
+ },
+ }
+
+ return {"optimizer": optimizer}
+
+ def get_losses(self, batch):
+ x, x_lengths = batch["x"], batch["x_lengths"]
+ y, y_lengths = batch["y"], batch["y_lengths"]
+ spks = batch["spks"]
+
+ dur_loss, prior_loss, diff_loss, *_ = self(
+ x=x,
+ x_lengths=x_lengths,
+ y=y,
+ y_lengths=y_lengths,
+ spks=spks,
+ out_size=self.out_size,
+ durations=batch["durations"],
+ )
+ return {
+ "dur_loss": dur_loss,
+ "prior_loss": prior_loss,
+ "diff_loss": diff_loss,
+ }
+
+ def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None:
+ self.ckpt_loaded_epoch = checkpoint["epoch"] # pylint: disable=attribute-defined-outside-init
+
+ def training_step(self, batch: Any, batch_idx: int):
+ loss_dict = self.get_losses(batch)
+ self.log(
+ "step",
+ float(self.global_step),
+ on_step=True,
+ prog_bar=True,
+ logger=True,
+ sync_dist=True,
+ batch_size=2
+ )
+
+ self.log(
+ "sub_loss/train_dur_loss",
+ loss_dict["dur_loss"],
+ on_step=True,
+ on_epoch=True,
+ logger=True,
+ sync_dist=True,
+ batch_size=2
+ )
+ self.log(
+ "sub_loss/train_prior_loss",
+ loss_dict["prior_loss"],
+ on_step=True,
+ on_epoch=True,
+ logger=True,
+ sync_dist=True,
+ batch_size=2
+ )
+ self.log(
+ "sub_loss/train_diff_loss",
+ loss_dict["diff_loss"],
+ on_step=True,
+ on_epoch=True,
+ logger=True,
+ sync_dist=True,
+ batch_size=2
+ )
+
+ total_loss = sum(loss_dict.values())
+ self.log(
+ "loss/train",
+ total_loss,
+ on_step=True,
+ on_epoch=True,
+ logger=True,
+ prog_bar=True,
+ sync_dist=True,
+ batch_size=2
+ )
+
+ return {"loss": total_loss, "log": loss_dict}
+
+ def validation_step(self, batch: Any, batch_idx: int):
+ loss_dict = self.get_losses(batch)
+ self.log(
+ "sub_loss/val_dur_loss",
+ loss_dict["dur_loss"],
+ on_step=True,
+ on_epoch=True,
+ logger=True,
+ sync_dist=True,
+ batch_size=2
+ )
+ self.log(
+ "sub_loss/val_prior_loss",
+ loss_dict["prior_loss"],
+ on_step=True,
+ on_epoch=True,
+ logger=True,
+ sync_dist=True,
+ batch_size=2
+ )
+ self.log(
+ "sub_loss/val_diff_loss",
+ loss_dict["diff_loss"],
+ on_step=True,
+ on_epoch=True,
+ logger=True,
+ sync_dist=True,
+ batch_size=2
+ )
+
+ total_loss = sum(loss_dict.values())
+ self.log(
+ "loss/val",
+ total_loss,
+ on_step=True,
+ on_epoch=True,
+ logger=True,
+ prog_bar=True,
+ sync_dist=True,
+ batch_size=2
+ )
+
+ return total_loss
+
+ def on_validation_end(self) -> None:
+ if self.trainer.is_global_zero:
+ one_batch = next(iter(self.trainer.val_dataloaders))
+ if self.current_epoch == 0:
+ log.debug("Plotting original samples")
+ for i in range(2):
+ y = one_batch["y"][i].unsqueeze(0).to(self.device)
+ self.logger.experiment.add_image(
+ f"original/{i}",
+ plot_tensor(y.squeeze().cpu()),
+ self.current_epoch,
+ dataformats="HWC",
+ )
+
+ log.debug("Synthesising...")
+ for i in range(2):
+ x = one_batch["x"][i].unsqueeze(0).to(self.device)
+ x_lengths = one_batch["x_lengths"][i].unsqueeze(0).to(self.device)
+ spks = one_batch["spks"][i].unsqueeze(0).to(self.device) if one_batch["spks"] is not None else None
+ output = self.synthesise(x[:, :x_lengths], x_lengths, n_timesteps=10, spks=spks)
+ y_enc, y_dec = output["encoder_outputs"], output["decoder_outputs"]
+ attn = output["attn"]
+ self.logger.experiment.add_image(
+ f"generated_enc/{i}",
+ plot_tensor(y_enc.squeeze().cpu()),
+ self.current_epoch,
+ dataformats="HWC",
+ )
+ self.logger.experiment.add_image(
+ f"generated_dec/{i}",
+ plot_tensor(y_dec.squeeze().cpu()),
+ self.current_epoch,
+ dataformats="HWC",
+ )
+ self.logger.experiment.add_image(
+ f"alignment/{i}",
+ plot_tensor(attn.squeeze().cpu()),
+ self.current_epoch,
+ dataformats="HWC",
+ )
+
+ def on_before_optimizer_step(self, optimizer):
+ self.log_dict({f"grad_norm/{k}": v for k, v in grad_norm(self, norm_type=2).items()})
diff --git a/matcha/models/components/__init__.py b/matcha/models/components/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/models/components/__pycache__/__init__.cpython-310.pyc b/matcha/models/components/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e89060f4f24f2c697d0d275a4ab5a5d87b21704f
Binary files /dev/null and b/matcha/models/components/__pycache__/__init__.cpython-310.pyc differ
diff --git a/matcha/models/components/__pycache__/__init__.cpython-311.pyc b/matcha/models/components/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b2957b371af3e96e2364f2498c294023481d4da3
Binary files /dev/null and b/matcha/models/components/__pycache__/__init__.cpython-311.pyc differ
diff --git a/matcha/models/components/__pycache__/__init__.py b/matcha/models/components/__pycache__/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/models/components/__pycache__/decoder.cpython-310.pyc b/matcha/models/components/__pycache__/decoder.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5b6b4e7d3a208dda9de2153217523319173a2bc
Binary files /dev/null and b/matcha/models/components/__pycache__/decoder.cpython-310.pyc differ
diff --git a/matcha/models/components/__pycache__/decoder.cpython-311.pyc b/matcha/models/components/__pycache__/decoder.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc7b3d12b9341ff41a07536ece82788c9aee29b5
Binary files /dev/null and b/matcha/models/components/__pycache__/decoder.cpython-311.pyc differ
diff --git a/matcha/models/components/__pycache__/flow_matching.cpython-310.pyc b/matcha/models/components/__pycache__/flow_matching.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6552965839eb5cfcfdead2d83d9566e5bb6c368a
Binary files /dev/null and b/matcha/models/components/__pycache__/flow_matching.cpython-310.pyc differ
diff --git a/matcha/models/components/__pycache__/flow_matching.cpython-311.pyc b/matcha/models/components/__pycache__/flow_matching.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84838b972258d95c694e7060cbcd5f5d12f16066
Binary files /dev/null and b/matcha/models/components/__pycache__/flow_matching.cpython-311.pyc differ
diff --git a/matcha/models/components/__pycache__/text_encoder.cpython-310.pyc b/matcha/models/components/__pycache__/text_encoder.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..413dd56ce59640d86e1ba50738598bc0a0333046
Binary files /dev/null and b/matcha/models/components/__pycache__/text_encoder.cpython-310.pyc differ
diff --git a/matcha/models/components/__pycache__/text_encoder.cpython-311.pyc b/matcha/models/components/__pycache__/text_encoder.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9af0ed384ac378f6ca2dc0872ccfb38f537aede9
Binary files /dev/null and b/matcha/models/components/__pycache__/text_encoder.cpython-311.pyc differ
diff --git a/matcha/models/components/__pycache__/transformer.cpython-310.pyc b/matcha/models/components/__pycache__/transformer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..02900bde61e8dd3e990de810272bea0d1f6519d8
Binary files /dev/null and b/matcha/models/components/__pycache__/transformer.cpython-310.pyc differ
diff --git a/matcha/models/components/__pycache__/transformer.cpython-311.pyc b/matcha/models/components/__pycache__/transformer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df845ac65962334108613edf11ad8ee11d78d091
Binary files /dev/null and b/matcha/models/components/__pycache__/transformer.cpython-311.pyc differ
diff --git a/matcha/models/components/decoder.py b/matcha/models/components/decoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..1137cd7008e9d07b4f306926a82e44c2b2cddbdf
--- /dev/null
+++ b/matcha/models/components/decoder.py
@@ -0,0 +1,443 @@
+import math
+from typing import Optional
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from conformer import ConformerBlock
+from diffusers.models.activations import get_activation
+from einops import pack, rearrange, repeat
+
+from matcha.models.components.transformer import BasicTransformerBlock
+
+
+class SinusoidalPosEmb(torch.nn.Module):
+ def __init__(self, dim):
+ super().__init__()
+ self.dim = dim
+ assert self.dim % 2 == 0, "SinusoidalPosEmb requires dim to be even"
+
+ def forward(self, x, scale=1000):
+ if x.ndim < 1:
+ x = x.unsqueeze(0)
+ device = x.device
+ half_dim = self.dim // 2
+ emb = math.log(10000) / (half_dim - 1)
+ emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
+ emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
+ return emb
+
+
+class Block1D(torch.nn.Module):
+ def __init__(self, dim, dim_out, groups=8):
+ super().__init__()
+ self.block = torch.nn.Sequential(
+ torch.nn.Conv1d(dim, dim_out, 3, padding=1),
+ torch.nn.GroupNorm(groups, dim_out),
+ nn.Mish(),
+ )
+
+ def forward(self, x, mask):
+ output = self.block(x * mask)
+ return output * mask
+
+
+class ResnetBlock1D(torch.nn.Module):
+ def __init__(self, dim, dim_out, time_emb_dim, groups=8):
+ super().__init__()
+ self.mlp = torch.nn.Sequential(nn.Mish(), torch.nn.Linear(time_emb_dim, dim_out))
+
+ self.block1 = Block1D(dim, dim_out, groups=groups)
+ self.block2 = Block1D(dim_out, dim_out, groups=groups)
+
+ self.res_conv = torch.nn.Conv1d(dim, dim_out, 1)
+
+ def forward(self, x, mask, time_emb):
+ h = self.block1(x, mask)
+ h += self.mlp(time_emb).unsqueeze(-1)
+ h = self.block2(h, mask)
+ output = h + self.res_conv(x * mask)
+ return output
+
+
+class Downsample1D(nn.Module):
+ def __init__(self, dim):
+ super().__init__()
+ self.conv = torch.nn.Conv1d(dim, dim, 3, 2, 1)
+
+ def forward(self, x):
+ return self.conv(x)
+
+
+class TimestepEmbedding(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ time_embed_dim: int,
+ act_fn: str = "silu",
+ out_dim: int = None,
+ post_act_fn: Optional[str] = None,
+ cond_proj_dim=None,
+ ):
+ super().__init__()
+
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim)
+
+ if cond_proj_dim is not None:
+ self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
+ else:
+ self.cond_proj = None
+
+ self.act = get_activation(act_fn)
+
+ if out_dim is not None:
+ time_embed_dim_out = out_dim
+ else:
+ time_embed_dim_out = time_embed_dim
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out)
+
+ if post_act_fn is None:
+ self.post_act = None
+ else:
+ self.post_act = get_activation(post_act_fn)
+
+ def forward(self, sample, condition=None):
+ if condition is not None:
+ sample = sample + self.cond_proj(condition)
+ sample = self.linear_1(sample)
+
+ if self.act is not None:
+ sample = self.act(sample)
+
+ sample = self.linear_2(sample)
+
+ if self.post_act is not None:
+ sample = self.post_act(sample)
+ return sample
+
+
+class Upsample1D(nn.Module):
+ """A 1D upsampling layer with an optional convolution.
+
+ Parameters:
+ channels (`int`):
+ number of channels in the inputs and outputs.
+ use_conv (`bool`, default `False`):
+ option to use a convolution.
+ use_conv_transpose (`bool`, default `False`):
+ option to use a convolution transpose.
+ out_channels (`int`, optional):
+ number of output channels. Defaults to `channels`.
+ """
+
+ def __init__(self, channels, use_conv=False, use_conv_transpose=True, out_channels=None, name="conv"):
+ super().__init__()
+ self.channels = channels
+ self.out_channels = out_channels or channels
+ self.use_conv = use_conv
+ self.use_conv_transpose = use_conv_transpose
+ self.name = name
+
+ self.conv = None
+ if use_conv_transpose:
+ self.conv = nn.ConvTranspose1d(channels, self.out_channels, 4, 2, 1)
+ elif use_conv:
+ self.conv = nn.Conv1d(self.channels, self.out_channels, 3, padding=1)
+
+ def forward(self, inputs):
+ assert inputs.shape[1] == self.channels
+ if self.use_conv_transpose:
+ return self.conv(inputs)
+
+ outputs = F.interpolate(inputs, scale_factor=2.0, mode="nearest")
+
+ if self.use_conv:
+ outputs = self.conv(outputs)
+
+ return outputs
+
+
+class ConformerWrapper(ConformerBlock):
+ def __init__( # pylint: disable=useless-super-delegation
+ self,
+ *,
+ dim,
+ dim_head=64,
+ heads=8,
+ ff_mult=4,
+ conv_expansion_factor=2,
+ conv_kernel_size=31,
+ attn_dropout=0,
+ ff_dropout=0,
+ conv_dropout=0,
+ conv_causal=False,
+ ):
+ super().__init__(
+ dim=dim,
+ dim_head=dim_head,
+ heads=heads,
+ ff_mult=ff_mult,
+ conv_expansion_factor=conv_expansion_factor,
+ conv_kernel_size=conv_kernel_size,
+ attn_dropout=attn_dropout,
+ ff_dropout=ff_dropout,
+ conv_dropout=conv_dropout,
+ conv_causal=conv_causal,
+ )
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ timestep=None,
+ ):
+ return super().forward(x=hidden_states, mask=attention_mask.bool())
+
+
+class Decoder(nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ channels=(256, 256),
+ dropout=0.05,
+ attention_head_dim=64,
+ n_blocks=1,
+ num_mid_blocks=2,
+ num_heads=4,
+ act_fn="snake",
+ down_block_type="transformer",
+ mid_block_type="transformer",
+ up_block_type="transformer",
+ ):
+ super().__init__()
+ channels = tuple(channels)
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+
+ self.time_embeddings = SinusoidalPosEmb(in_channels)
+ time_embed_dim = channels[0] * 4
+ self.time_mlp = TimestepEmbedding(
+ in_channels=in_channels,
+ time_embed_dim=time_embed_dim,
+ act_fn="silu",
+ )
+
+ self.down_blocks = nn.ModuleList([])
+ self.mid_blocks = nn.ModuleList([])
+ self.up_blocks = nn.ModuleList([])
+
+ output_channel = in_channels
+ for i in range(len(channels)): # pylint: disable=consider-using-enumerate
+ input_channel = output_channel
+ output_channel = channels[i]
+ is_last = i == len(channels) - 1
+ resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+ transformer_blocks = nn.ModuleList(
+ [
+ self.get_block(
+ down_block_type,
+ output_channel,
+ attention_head_dim,
+ num_heads,
+ dropout,
+ act_fn,
+ )
+ for _ in range(n_blocks)
+ ]
+ )
+ downsample = (
+ Downsample1D(output_channel) if not is_last else nn.Conv1d(output_channel, output_channel, 3, padding=1)
+ )
+
+ self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))
+
+ for i in range(num_mid_blocks):
+ input_channel = channels[-1]
+ out_channels = channels[-1]
+
+ resnet = ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+
+ transformer_blocks = nn.ModuleList(
+ [
+ self.get_block(
+ mid_block_type,
+ output_channel,
+ attention_head_dim,
+ num_heads,
+ dropout,
+ act_fn,
+ )
+ for _ in range(n_blocks)
+ ]
+ )
+
+ self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))
+
+ channels = channels[::-1] + (channels[0],)
+ for i in range(len(channels) - 1):
+ input_channel = channels[i]
+ output_channel = channels[i + 1]
+ is_last = i == len(channels) - 2
+
+ resnet = ResnetBlock1D(
+ dim=2 * input_channel,
+ dim_out=output_channel,
+ time_emb_dim=time_embed_dim,
+ )
+ transformer_blocks = nn.ModuleList(
+ [
+ self.get_block(
+ up_block_type,
+ output_channel,
+ attention_head_dim,
+ num_heads,
+ dropout,
+ act_fn,
+ )
+ for _ in range(n_blocks)
+ ]
+ )
+ upsample = (
+ Upsample1D(output_channel, use_conv_transpose=True)
+ if not is_last
+ else nn.Conv1d(output_channel, output_channel, 3, padding=1)
+ )
+
+ self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))
+
+ self.final_block = Block1D(channels[-1], channels[-1])
+ self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
+
+ self.initialize_weights()
+ # nn.init.normal_(self.final_proj.weight)
+
+ @staticmethod
+ def get_block(block_type, dim, attention_head_dim, num_heads, dropout, act_fn):
+ if block_type == "conformer":
+ block = ConformerWrapper(
+ dim=dim,
+ dim_head=attention_head_dim,
+ heads=num_heads,
+ ff_mult=1,
+ conv_expansion_factor=2,
+ ff_dropout=dropout,
+ attn_dropout=dropout,
+ conv_dropout=dropout,
+ conv_kernel_size=31,
+ )
+ elif block_type == "transformer":
+ block = BasicTransformerBlock(
+ dim=dim,
+ num_attention_heads=num_heads,
+ attention_head_dim=attention_head_dim,
+ dropout=dropout,
+ activation_fn=act_fn,
+ )
+ else:
+ raise ValueError(f"Unknown block type {block_type}")
+
+ return block
+
+ def initialize_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Conv1d):
+ nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
+
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+
+ elif isinstance(m, nn.GroupNorm):
+ nn.init.constant_(m.weight, 1)
+ nn.init.constant_(m.bias, 0)
+
+ elif isinstance(m, nn.Linear):
+ nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
+
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+
+ def forward(self, x, mask, mu, t, spks=None, cond=None):
+ """Forward pass of the UNet1DConditional model.
+
+ Args:
+ x (torch.Tensor): shape (batch_size, in_channels, time)
+ mask (_type_): shape (batch_size, 1, time)
+ t (_type_): shape (batch_size)
+ spks (_type_, optional): shape: (batch_size, condition_channels). Defaults to None.
+ cond (_type_, optional): placeholder for future use. Defaults to None.
+
+ Raises:
+ ValueError: _description_
+ ValueError: _description_
+
+ Returns:
+ _type_: _description_
+ """
+
+ t = self.time_embeddings(t)
+ t = self.time_mlp(t)
+
+ x = pack([x, mu], "b * t")[0]
+
+ if spks is not None:
+ spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
+ x = pack([x, spks], "b * t")[0]
+
+ hiddens = []
+ masks = [mask]
+ for resnet, transformer_blocks, downsample in self.down_blocks:
+ mask_down = masks[-1]
+ x = resnet(x, mask_down, t)
+ x = rearrange(x, "b c t -> b t c")
+ mask_down = rearrange(mask_down, "b 1 t -> b t")
+ for transformer_block in transformer_blocks:
+ x = transformer_block(
+ hidden_states=x,
+ attention_mask=mask_down,
+ timestep=t,
+ )
+ x = rearrange(x, "b t c -> b c t")
+ mask_down = rearrange(mask_down, "b t -> b 1 t")
+ hiddens.append(x) # Save hidden states for skip connections
+ x = downsample(x * mask_down)
+ masks.append(mask_down[:, :, ::2])
+
+ masks = masks[:-1]
+ mask_mid = masks[-1]
+
+ for resnet, transformer_blocks in self.mid_blocks:
+ x = resnet(x, mask_mid, t)
+ x = rearrange(x, "b c t -> b t c")
+ mask_mid = rearrange(mask_mid, "b 1 t -> b t")
+ for transformer_block in transformer_blocks:
+ x = transformer_block(
+ hidden_states=x,
+ attention_mask=mask_mid,
+ timestep=t,
+ )
+ x = rearrange(x, "b t c -> b c t")
+ mask_mid = rearrange(mask_mid, "b t -> b 1 t")
+
+ for resnet, transformer_blocks, upsample in self.up_blocks:
+ mask_up = masks.pop()
+ x = resnet(pack([x, hiddens.pop()], "b * t")[0], mask_up, t)
+ x = rearrange(x, "b c t -> b t c")
+ mask_up = rearrange(mask_up, "b 1 t -> b t")
+ for transformer_block in transformer_blocks:
+ x = transformer_block(
+ hidden_states=x,
+ attention_mask=mask_up,
+ timestep=t,
+ )
+ x = rearrange(x, "b t c -> b c t")
+ mask_up = rearrange(mask_up, "b t -> b 1 t")
+ x = upsample(x * mask_up)
+
+ x = self.final_block(x, mask_up)
+ output = self.final_proj(x * mask_up)
+
+ return output * mask
diff --git a/matcha/models/components/flow_matching.py b/matcha/models/components/flow_matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cad7431ef66a8d11da32a77c1af7f6e31d6b774
--- /dev/null
+++ b/matcha/models/components/flow_matching.py
@@ -0,0 +1,132 @@
+from abc import ABC
+
+import torch
+import torch.nn.functional as F
+
+from matcha.models.components.decoder import Decoder
+from matcha.utils.pylogger import get_pylogger
+
+log = get_pylogger(__name__)
+
+
+class BASECFM(torch.nn.Module, ABC):
+ def __init__(
+ self,
+ n_feats,
+ cfm_params,
+ n_spks=1,
+ spk_emb_dim=128,
+ ):
+ super().__init__()
+ self.n_feats = n_feats
+ self.n_spks = n_spks
+ self.spk_emb_dim = spk_emb_dim
+ self.solver = cfm_params.solver
+ if hasattr(cfm_params, "sigma_min"):
+ self.sigma_min = cfm_params.sigma_min
+ else:
+ self.sigma_min = 1e-4
+
+ self.estimator = None
+
+ @torch.inference_mode()
+ def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
+ """Forward diffusion
+
+ Args:
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): output_mask
+ shape: (batch_size, 1, mel_timesteps)
+ n_timesteps (int): number of diffusion steps
+ temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+ cond: Not used but kept for future purposes
+
+ Returns:
+ sample: generated mel-spectrogram
+ shape: (batch_size, n_feats, mel_timesteps)
+ """
+ z = torch.randn_like(mu) * temperature
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device)
+ return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)
+
+ def solve_euler(self, x, t_span, mu, mask, spks, cond):
+ """
+ Fixed euler solver for ODEs.
+ Args:
+ x (torch.Tensor): random noise
+ t_span (torch.Tensor): n_timesteps interpolated
+ shape: (n_timesteps + 1,)
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): output_mask
+ shape: (batch_size, 1, mel_timesteps)
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+ cond: Not used but kept for future purposes
+ """
+ t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
+
+ # I am storing this because I can later plot it by putting a debugger here and saving it to a file
+ # Or in future might add like a return_all_steps flag
+ sol = []
+
+ for step in range(1, len(t_span)):
+ dphi_dt = self.estimator(x, mask, mu, t, spks, cond)
+
+ x = x + dt * dphi_dt
+ t = t + dt
+ sol.append(x)
+ if step < len(t_span) - 1:
+ dt = t_span[step + 1] - t
+
+ return sol[-1]
+
+ def compute_loss(self, x1, mask, mu, spks=None, cond=None):
+ """Computes diffusion loss
+
+ Args:
+ x1 (torch.Tensor): Target
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): target mask
+ shape: (batch_size, 1, mel_timesteps)
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ spks (torch.Tensor, optional): speaker embedding. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+
+ Returns:
+ loss: conditional flow matching loss
+ y: conditional flow
+ shape: (batch_size, n_feats, mel_timesteps)
+ """
+ b, _, t = mu.shape
+
+ # random timestep
+ t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
+ # sample noise p(x_0)
+ z = torch.randn_like(x1)
+
+ y = (1 - (1 - self.sigma_min) * t) * z + t * x1
+ u = x1 - (1 - self.sigma_min) * z
+
+ loss = F.mse_loss(self.estimator(y, mask, mu, t.squeeze(), spks), u, reduction="sum") / (
+ torch.sum(mask) * u.shape[1]
+ )
+ return loss, y
+
+
+class CFM(BASECFM):
+ def __init__(self, in_channels, out_channel, cfm_params, decoder_params, n_spks=1, spk_emb_dim=64):
+ super().__init__(
+ n_feats=in_channels,
+ cfm_params=cfm_params,
+ n_spks=n_spks,
+ spk_emb_dim=spk_emb_dim,
+ )
+
+ in_channels = in_channels + (spk_emb_dim if n_spks > 1 else 0)
+ # Just change the architecture of the estimator here
+ self.estimator = Decoder(in_channels=in_channels, out_channels=out_channel, **decoder_params)
diff --git a/matcha/models/components/text_encoder.py b/matcha/models/components/text_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..a388d05d6351fa2c9d9632fed0942d51fbec067b
--- /dev/null
+++ b/matcha/models/components/text_encoder.py
@@ -0,0 +1,410 @@
+""" from https://github.com/jaywalnut310/glow-tts """
+
+import math
+
+import torch
+import torch.nn as nn
+from einops import rearrange
+
+import matcha.utils as utils
+from matcha.utils.model import sequence_mask
+
+log = utils.get_pylogger(__name__)
+
+
+class LayerNorm(nn.Module):
+ def __init__(self, channels, eps=1e-4):
+ super().__init__()
+ self.channels = channels
+ self.eps = eps
+
+ self.gamma = torch.nn.Parameter(torch.ones(channels))
+ self.beta = torch.nn.Parameter(torch.zeros(channels))
+
+ def forward(self, x):
+ n_dims = len(x.shape)
+ mean = torch.mean(x, 1, keepdim=True)
+ variance = torch.mean((x - mean) ** 2, 1, keepdim=True)
+
+ x = (x - mean) * torch.rsqrt(variance + self.eps)
+
+ shape = [1, -1] + [1] * (n_dims - 2)
+ x = x * self.gamma.view(*shape) + self.beta.view(*shape)
+ return x
+
+
+class ConvReluNorm(nn.Module):
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
+ super().__init__()
+ self.in_channels = in_channels
+ self.hidden_channels = hidden_channels
+ self.out_channels = out_channels
+ self.kernel_size = kernel_size
+ self.n_layers = n_layers
+ self.p_dropout = p_dropout
+
+ self.conv_layers = torch.nn.ModuleList()
+ self.norm_layers = torch.nn.ModuleList()
+ self.conv_layers.append(torch.nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size // 2))
+ self.norm_layers.append(LayerNorm(hidden_channels))
+ self.relu_drop = torch.nn.Sequential(torch.nn.ReLU(), torch.nn.Dropout(p_dropout))
+ for _ in range(n_layers - 1):
+ self.conv_layers.append(
+ torch.nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size // 2)
+ )
+ self.norm_layers.append(LayerNorm(hidden_channels))
+ self.proj = torch.nn.Conv1d(hidden_channels, out_channels, 1)
+ self.proj.weight.data.zero_()
+ self.proj.bias.data.zero_()
+
+ def forward(self, x, x_mask):
+ x_org = x
+ for i in range(self.n_layers):
+ x = self.conv_layers[i](x * x_mask)
+ x = self.norm_layers[i](x)
+ x = self.relu_drop(x)
+ x = x_org + self.proj(x)
+ return x * x_mask
+
+
+class DurationPredictor(nn.Module):
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout):
+ super().__init__()
+ self.in_channels = in_channels
+ self.filter_channels = filter_channels
+ self.p_dropout = p_dropout
+
+ self.drop = torch.nn.Dropout(p_dropout)
+ self.conv_1 = torch.nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
+ self.norm_1 = LayerNorm(filter_channels)
+ self.conv_2 = torch.nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
+ self.norm_2 = LayerNorm(filter_channels)
+ self.proj = torch.nn.Conv1d(filter_channels, 1, 1)
+
+ def forward(self, x, x_mask):
+ x = self.conv_1(x * x_mask)
+ x = torch.relu(x)
+ x = self.norm_1(x)
+ x = self.drop(x)
+ x = self.conv_2(x * x_mask)
+ x = torch.relu(x)
+ x = self.norm_2(x)
+ x = self.drop(x)
+ x = self.proj(x * x_mask)
+ return x * x_mask
+
+
+class RotaryPositionalEmbeddings(nn.Module):
+ """
+ ## RoPE module
+
+ Rotary encoding transforms pairs of features by rotating in the 2D plane.
+ That is, it organizes the $d$ features as $\frac{d}{2}$ pairs.
+ Each pair can be considered a coordinate in a 2D plane, and the encoding will rotate it
+ by an angle depending on the position of the token.
+ """
+
+ def __init__(self, d: int, base: int = 10_000):
+ r"""
+ * `d` is the number of features $d$
+ * `base` is the constant used for calculating $\Theta$
+ """
+ super().__init__()
+
+ self.base = base
+ self.d = int(d)
+ self.cos_cached = None
+ self.sin_cached = None
+
+ def _build_cache(self, x: torch.Tensor):
+ r"""
+ Cache $\cos$ and $\sin$ values
+ """
+ # Return if cache is already built
+ if self.cos_cached is not None and x.shape[0] <= self.cos_cached.shape[0]:
+ return
+
+ # Get sequence length
+ seq_len = x.shape[0]
+
+ # $\Theta = {\theta_i = 10000^{-\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
+ theta = 1.0 / (self.base ** (torch.arange(0, self.d, 2).float() / self.d)).to(x.device)
+
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
+ seq_idx = torch.arange(seq_len, device=x.device).float().to(x.device)
+
+ # Calculate the product of position index and $\theta_i$
+ idx_theta = torch.einsum("n,d->nd", seq_idx, theta)
+
+ # Concatenate so that for row $m$ we have
+ # $[m \theta_0, m \theta_1, ..., m \theta_{\frac{d}{2}}, m \theta_0, m \theta_1, ..., m \theta_{\frac{d}{2}}]$
+ idx_theta2 = torch.cat([idx_theta, idx_theta], dim=1)
+
+ # Cache them
+ self.cos_cached = idx_theta2.cos()[:, None, None, :]
+ self.sin_cached = idx_theta2.sin()[:, None, None, :]
+
+ def _neg_half(self, x: torch.Tensor):
+ # $\frac{d}{2}$
+ d_2 = self.d // 2
+
+ # Calculate $[-x^{(\frac{d}{2} + 1)}, -x^{(\frac{d}{2} + 2)}, ..., -x^{(d)}, x^{(1)}, x^{(2)}, ..., x^{(\frac{d}{2})}]$
+ return torch.cat([-x[:, :, :, d_2:], x[:, :, :, :d_2]], dim=-1)
+
+ def forward(self, x: torch.Tensor):
+ """
+ * `x` is the Tensor at the head of a key or a query with shape `[seq_len, batch_size, n_heads, d]`
+ """
+ # Cache $\cos$ and $\sin$ values
+ x = rearrange(x, "b h t d -> t b h d")
+
+ self._build_cache(x)
+
+ # Split the features, we can choose to apply rotary embeddings only to a partial set of features.
+ x_rope, x_pass = x[..., : self.d], x[..., self.d :]
+
+ # Calculate
+ # $[-x^{(\frac{d}{2} + 1)}, -x^{(\frac{d}{2} + 2)}, ..., -x^{(d)}, x^{(1)}, x^{(2)}, ..., x^{(\frac{d}{2})}]$
+ neg_half_x = self._neg_half(x_rope)
+
+ x_rope = (x_rope * self.cos_cached[: x.shape[0]]) + (neg_half_x * self.sin_cached[: x.shape[0]])
+
+ return rearrange(torch.cat((x_rope, x_pass), dim=-1), "t b h d -> b h t d")
+
+
+class MultiHeadAttention(nn.Module):
+ def __init__(
+ self,
+ channels,
+ out_channels,
+ n_heads,
+ heads_share=True,
+ p_dropout=0.0,
+ proximal_bias=False,
+ proximal_init=False,
+ ):
+ super().__init__()
+ assert channels % n_heads == 0
+
+ self.channels = channels
+ self.out_channels = out_channels
+ self.n_heads = n_heads
+ self.heads_share = heads_share
+ self.proximal_bias = proximal_bias
+ self.p_dropout = p_dropout
+ self.attn = None
+
+ self.k_channels = channels // n_heads
+ self.conv_q = torch.nn.Conv1d(channels, channels, 1)
+ self.conv_k = torch.nn.Conv1d(channels, channels, 1)
+ self.conv_v = torch.nn.Conv1d(channels, channels, 1)
+
+ # from https://nn.labml.ai/transformers/rope/index.html
+ self.query_rotary_pe = RotaryPositionalEmbeddings(self.k_channels * 0.5)
+ self.key_rotary_pe = RotaryPositionalEmbeddings(self.k_channels * 0.5)
+
+ self.conv_o = torch.nn.Conv1d(channels, out_channels, 1)
+ self.drop = torch.nn.Dropout(p_dropout)
+
+ torch.nn.init.xavier_uniform_(self.conv_q.weight)
+ torch.nn.init.xavier_uniform_(self.conv_k.weight)
+ if proximal_init:
+ self.conv_k.weight.data.copy_(self.conv_q.weight.data)
+ self.conv_k.bias.data.copy_(self.conv_q.bias.data)
+ torch.nn.init.xavier_uniform_(self.conv_v.weight)
+
+ def forward(self, x, c, attn_mask=None):
+ q = self.conv_q(x)
+ k = self.conv_k(c)
+ v = self.conv_v(c)
+
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
+
+ x = self.conv_o(x)
+ return x
+
+ def attention(self, query, key, value, mask=None):
+ b, d, t_s, t_t = (*key.size(), query.size(2))
+ query = rearrange(query, "b (h c) t-> b h t c", h=self.n_heads)
+ key = rearrange(key, "b (h c) t-> b h t c", h=self.n_heads)
+ value = rearrange(value, "b (h c) t-> b h t c", h=self.n_heads)
+
+ query = self.query_rotary_pe(query)
+ key = self.key_rotary_pe(key)
+
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.k_channels)
+
+ if self.proximal_bias:
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
+ if mask is not None:
+ scores = scores.masked_fill(mask == 0, -1e4)
+ p_attn = torch.nn.functional.softmax(scores, dim=-1)
+ p_attn = self.drop(p_attn)
+ output = torch.matmul(p_attn, value)
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t)
+ return output, p_attn
+
+ @staticmethod
+ def _attention_bias_proximal(length):
+ r = torch.arange(length, dtype=torch.float32)
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
+
+
+class FFN(nn.Module):
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0.0):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.filter_channels = filter_channels
+ self.kernel_size = kernel_size
+ self.p_dropout = p_dropout
+
+ self.conv_1 = torch.nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
+ self.conv_2 = torch.nn.Conv1d(filter_channels, out_channels, kernel_size, padding=kernel_size // 2)
+ self.drop = torch.nn.Dropout(p_dropout)
+
+ def forward(self, x, x_mask):
+ x = self.conv_1(x * x_mask)
+ x = torch.relu(x)
+ x = self.drop(x)
+ x = self.conv_2(x * x_mask)
+ return x * x_mask
+
+
+class Encoder(nn.Module):
+ def __init__(
+ self,
+ hidden_channels,
+ filter_channels,
+ n_heads,
+ n_layers,
+ kernel_size=1,
+ p_dropout=0.0,
+ **kwargs,
+ ):
+ super().__init__()
+ self.hidden_channels = hidden_channels
+ self.filter_channels = filter_channels
+ self.n_heads = n_heads
+ self.n_layers = n_layers
+ self.kernel_size = kernel_size
+ self.p_dropout = p_dropout
+
+ self.drop = torch.nn.Dropout(p_dropout)
+ self.attn_layers = torch.nn.ModuleList()
+ self.norm_layers_1 = torch.nn.ModuleList()
+ self.ffn_layers = torch.nn.ModuleList()
+ self.norm_layers_2 = torch.nn.ModuleList()
+ for _ in range(self.n_layers):
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
+ self.ffn_layers.append(
+ FFN(
+ hidden_channels,
+ hidden_channels,
+ filter_channels,
+ kernel_size,
+ p_dropout=p_dropout,
+ )
+ )
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
+
+ def forward(self, x, x_mask):
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
+ for i in range(self.n_layers):
+ x = x * x_mask
+ y = self.attn_layers[i](x, x, attn_mask)
+ y = self.drop(y)
+ x = self.norm_layers_1[i](x + y)
+ y = self.ffn_layers[i](x, x_mask)
+ y = self.drop(y)
+ x = self.norm_layers_2[i](x + y)
+ x = x * x_mask
+ return x
+
+
+class TextEncoder(nn.Module):
+ def __init__(
+ self,
+ encoder_type,
+ encoder_params,
+ duration_predictor_params,
+ n_vocab,
+ n_spks=1,
+ spk_emb_dim=128,
+ ):
+ super().__init__()
+ self.encoder_type = encoder_type
+ self.n_vocab = n_vocab
+ self.n_feats = encoder_params.n_feats
+ self.n_channels = encoder_params.n_channels
+ self.spk_emb_dim = spk_emb_dim
+ self.n_spks = n_spks
+
+ self.emb = torch.nn.Embedding(n_vocab, self.n_channels)
+ torch.nn.init.normal_(self.emb.weight, 0.0, self.n_channels**-0.5)
+
+ if encoder_params.prenet:
+ self.prenet = ConvReluNorm(
+ self.n_channels,
+ self.n_channels,
+ self.n_channels,
+ kernel_size=5,
+ n_layers=3,
+ p_dropout=0.5,
+ )
+ else:
+ self.prenet = lambda x, x_mask: x
+
+ self.encoder = Encoder(
+ encoder_params.n_channels + (spk_emb_dim if n_spks > 1 else 0),
+ encoder_params.filter_channels,
+ encoder_params.n_heads,
+ encoder_params.n_layers,
+ encoder_params.kernel_size,
+ encoder_params.p_dropout,
+ )
+
+ self.proj_m = torch.nn.Conv1d(self.n_channels + (spk_emb_dim if n_spks > 1 else 0), self.n_feats, 1)
+ self.proj_w = DurationPredictor(
+ self.n_channels + (spk_emb_dim if n_spks > 1 else 0),
+ duration_predictor_params.filter_channels_dp,
+ duration_predictor_params.kernel_size,
+ duration_predictor_params.p_dropout,
+ )
+
+ def forward(self, x, x_lengths, spks=None):
+ """Run forward pass to the transformer based encoder and duration predictor
+
+ Args:
+ x (torch.Tensor): text input
+ shape: (batch_size, max_text_length)
+ x_lengths (torch.Tensor): text input lengths
+ shape: (batch_size,)
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
+ shape: (batch_size,)
+
+ Returns:
+ mu (torch.Tensor): average output of the encoder
+ shape: (batch_size, n_feats, max_text_length)
+ logw (torch.Tensor): log duration predicted by the duration predictor
+ shape: (batch_size, 1, max_text_length)
+ x_mask (torch.Tensor): mask for the text input
+ shape: (batch_size, 1, max_text_length)
+ """
+ x = self.emb(x) * math.sqrt(self.n_channels)
+ x = torch.transpose(x, 1, -1)
+ x_mask = torch.unsqueeze(sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
+
+ x = self.prenet(x, x_mask)
+ if self.n_spks > 1:
+ x = torch.cat([x, spks.unsqueeze(-1).repeat(1, 1, x.shape[-1])], dim=1)
+ x = self.encoder(x, x_mask)
+ mu = self.proj_m(x) * x_mask
+
+ x_dp = torch.detach(x)
+ logw = self.proj_w(x_dp, x_mask)
+
+ return mu, logw, x_mask
diff --git a/matcha/models/components/transformer.py b/matcha/models/components/transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd1afa3aff5383912209e508676c6885e13ef4ee
--- /dev/null
+++ b/matcha/models/components/transformer.py
@@ -0,0 +1,316 @@
+from typing import Any, Dict, Optional
+
+import torch
+import torch.nn as nn
+from diffusers.models.attention import (
+ GEGLU,
+ GELU,
+ AdaLayerNorm,
+ AdaLayerNormZero,
+ ApproximateGELU,
+)
+from diffusers.models.attention_processor import Attention
+from diffusers.models.lora import LoRACompatibleLinear
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+
+
+class SnakeBeta(nn.Module):
+ """
+ A modified Snake function which uses separate parameters for the magnitude of the periodic components
+ Shape:
+ - Input: (B, C, T)
+ - Output: (B, C, T), same shape as the input
+ Parameters:
+ - alpha - trainable parameter that controls frequency
+ - beta - trainable parameter that controls magnitude
+ References:
+ - This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
+ https://arxiv.org/abs/2006.08195
+ Examples:
+ >>> a1 = snakebeta(256)
+ >>> x = torch.randn(256)
+ >>> x = a1(x)
+ """
+
+ def __init__(self, in_features, out_features, alpha=1.0, alpha_trainable=True, alpha_logscale=True):
+ """
+ Initialization.
+ INPUT:
+ - in_features: shape of the input
+ - alpha - trainable parameter that controls frequency
+ - beta - trainable parameter that controls magnitude
+ alpha is initialized to 1 by default, higher values = higher-frequency.
+ beta is initialized to 1 by default, higher values = higher-magnitude.
+ alpha will be trained along with the rest of your model.
+ """
+ super().__init__()
+ self.in_features = out_features if isinstance(out_features, list) else [out_features]
+ self.proj = LoRACompatibleLinear(in_features, out_features)
+
+ # initialize alpha
+ self.alpha_logscale = alpha_logscale
+ if self.alpha_logscale: # log scale alphas initialized to zeros
+ self.alpha = nn.Parameter(torch.zeros(self.in_features) * alpha)
+ self.beta = nn.Parameter(torch.zeros(self.in_features) * alpha)
+ else: # linear scale alphas initialized to ones
+ self.alpha = nn.Parameter(torch.ones(self.in_features) * alpha)
+ self.beta = nn.Parameter(torch.ones(self.in_features) * alpha)
+
+ self.alpha.requires_grad = alpha_trainable
+ self.beta.requires_grad = alpha_trainable
+
+ self.no_div_by_zero = 0.000000001
+
+ def forward(self, x):
+ """
+ Forward pass of the function.
+ Applies the function to the input elementwise.
+ SnakeBeta ∶= x + 1/b * sin^2 (xa)
+ """
+ x = self.proj(x)
+ if self.alpha_logscale:
+ alpha = torch.exp(self.alpha)
+ beta = torch.exp(self.beta)
+ else:
+ alpha = self.alpha
+ beta = self.beta
+
+ x = x + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(torch.sin(x * alpha), 2)
+
+ return x
+
+
+class FeedForward(nn.Module):
+ r"""
+ A feed-forward layer.
+
+ Parameters:
+ dim (`int`): The number of channels in the input.
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ dim_out: Optional[int] = None,
+ mult: int = 4,
+ dropout: float = 0.0,
+ activation_fn: str = "geglu",
+ final_dropout: bool = False,
+ ):
+ super().__init__()
+ inner_dim = int(dim * mult)
+ dim_out = dim_out if dim_out is not None else dim
+
+ if activation_fn == "gelu":
+ act_fn = GELU(dim, inner_dim)
+ if activation_fn == "gelu-approximate":
+ act_fn = GELU(dim, inner_dim, approximate="tanh")
+ elif activation_fn == "geglu":
+ act_fn = GEGLU(dim, inner_dim)
+ elif activation_fn == "geglu-approximate":
+ act_fn = ApproximateGELU(dim, inner_dim)
+ elif activation_fn == "snakebeta":
+ act_fn = SnakeBeta(dim, inner_dim)
+
+ self.net = nn.ModuleList([])
+ # project in
+ self.net.append(act_fn)
+ # project dropout
+ self.net.append(nn.Dropout(dropout))
+ # project out
+ self.net.append(LoRACompatibleLinear(inner_dim, dim_out))
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
+ if final_dropout:
+ self.net.append(nn.Dropout(dropout))
+
+ def forward(self, hidden_states):
+ for module in self.net:
+ hidden_states = module(hidden_states)
+ return hidden_states
+
+
+@maybe_allow_in_graph
+class BasicTransformerBlock(nn.Module):
+ r"""
+ A basic Transformer block.
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
+ only_cross_attention (`bool`, *optional*):
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
+ double_self_attention (`bool`, *optional*):
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ num_embeds_ada_norm (:
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
+ attention_bias (:
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ num_attention_heads: int,
+ attention_head_dim: int,
+ dropout=0.0,
+ cross_attention_dim: Optional[int] = None,
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ attention_bias: bool = False,
+ only_cross_attention: bool = False,
+ double_self_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_elementwise_affine: bool = True,
+ norm_type: str = "layer_norm",
+ final_dropout: bool = False,
+ ):
+ super().__init__()
+ self.only_cross_attention = only_cross_attention
+
+ self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
+ self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
+
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
+ raise ValueError(
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
+ )
+
+ # Define 3 blocks. Each block has its own normalization layer.
+ # 1. Self-Attn
+ if self.use_ada_layer_norm:
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
+ elif self.use_ada_layer_norm_zero:
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
+ else:
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
+ upcast_attention=upcast_attention,
+ )
+
+ # 2. Cross-Attn
+ if cross_attention_dim is not None or double_self_attention:
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
+ # the second cross attention block.
+ self.norm2 = (
+ AdaLayerNorm(dim, num_embeds_ada_norm)
+ if self.use_ada_layer_norm
+ else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ )
+ self.attn2 = Attention(
+ query_dim=dim,
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ upcast_attention=upcast_attention,
+ # scale_qk=False, # uncomment this to not to use flash attention
+ ) # is self-attn if encoder_hidden_states is none
+ else:
+ self.norm2 = None
+ self.attn2 = None
+
+ # 3. Feed-forward
+ self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout)
+
+ # let chunk size default to None
+ self._chunk_size = None
+ self._chunk_dim = 0
+
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int):
+ # Sets chunk feed-forward
+ self._chunk_size = chunk_size
+ self._chunk_dim = dim
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ timestep: Optional[torch.LongTensor] = None,
+ cross_attention_kwargs: Dict[str, Any] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ ):
+ # Notice that normalization is always applied before the real computation in the following blocks.
+ # 1. Self-Attention
+ if self.use_ada_layer_norm:
+ norm_hidden_states = self.norm1(hidden_states, timestep)
+ elif self.use_ada_layer_norm_zero:
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
+ )
+ else:
+ norm_hidden_states = self.norm1(hidden_states)
+
+ cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
+
+ attn_output = self.attn1(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
+ attention_mask=encoder_attention_mask if self.only_cross_attention else attention_mask,
+ **cross_attention_kwargs,
+ )
+ if self.use_ada_layer_norm_zero:
+ attn_output = gate_msa.unsqueeze(1) * attn_output
+ hidden_states = attn_output + hidden_states
+
+ # 2. Cross-Attention
+ if self.attn2 is not None:
+ norm_hidden_states = (
+ self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
+ )
+
+ attn_output = self.attn2(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ **cross_attention_kwargs,
+ )
+ hidden_states = attn_output + hidden_states
+
+ # 3. Feed-forward
+ norm_hidden_states = self.norm3(hidden_states)
+
+ if self.use_ada_layer_norm_zero:
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
+
+ if self._chunk_size is not None:
+ # "feed_forward_chunk_size" can be used to save memory
+ if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
+ raise ValueError(
+ f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
+ )
+
+ num_chunks = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
+ ff_output = torch.cat(
+ [self.ff(hid_slice) for hid_slice in norm_hidden_states.chunk(num_chunks, dim=self._chunk_dim)],
+ dim=self._chunk_dim,
+ )
+ else:
+ ff_output = self.ff(norm_hidden_states)
+
+ if self.use_ada_layer_norm_zero:
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
+
+ hidden_states = ff_output + hidden_states
+
+ return hidden_states
diff --git a/matcha/models/matcha_tts.py b/matcha/models/matcha_tts.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cec48c996db0106983b6217e971dfdbd05b637b
--- /dev/null
+++ b/matcha/models/matcha_tts.py
@@ -0,0 +1,262 @@
+import datetime as dt
+import math
+import random
+
+import torch
+
+import matcha.utils.monotonic_align as monotonic_align
+from matcha import utils
+from matcha.models.baselightningmodule import BaseLightningClass
+from matcha.models.components.flow_matching import CFM
+from matcha.models.components.text_encoder import TextEncoder
+from matcha.utils.model import (
+ denormalize,
+ duration_loss,
+ fix_len_compatibility,
+ generate_path,
+ sequence_mask,
+)
+
+WORD_STRETCH = 1.8
+WORD_COMPRESS = 1
+
+log = utils.get_pylogger(__name__)
+
+
+class MatchaTTS(BaseLightningClass): # 🍵
+ def __init__(
+ self,
+ n_vocab,
+ n_spks,
+ spk_emb_dim,
+ n_feats,
+ encoder,
+ decoder,
+ cfm,
+ data_statistics,
+ out_size,
+ optimizer=None,
+ scheduler=None,
+ prior_loss=True,
+ use_precomputed_durations=False,
+ ):
+ super().__init__()
+
+ self.save_hyperparameters(logger=False)
+
+ self.n_vocab = n_vocab
+ self.n_spks = n_spks
+ self.spk_emb_dim = spk_emb_dim
+ self.n_feats = n_feats
+ self.out_size = out_size
+ self.prior_loss = prior_loss
+ self.use_precomputed_durations = use_precomputed_durations
+
+ if n_spks > 1:
+ self.spk_emb = torch.nn.Embedding(n_spks, spk_emb_dim)
+
+ self.encoder = TextEncoder(
+ encoder.encoder_type,
+ encoder.encoder_params,
+ encoder.duration_predictor_params,
+ n_vocab,
+ n_spks,
+ spk_emb_dim,
+ )
+
+ self.decoder = CFM(
+ in_channels=2 * encoder.encoder_params.n_feats,
+ out_channel=encoder.encoder_params.n_feats,
+ cfm_params=cfm,
+ decoder_params=decoder,
+ n_spks=n_spks,
+ spk_emb_dim=spk_emb_dim,
+ )
+
+ self.update_data_statistics(data_statistics)
+ @torch.inference_mode()
+ def synthesise(self, x, x_lengths, n_timesteps, temperature=1.0, spks=None, length_scale=1.0, latent_shift=None, alpha=1.0):
+ """
+ Generates mel-spectrogram from text. Returns:
+ 1. encoder outputs
+ 2. decoder outputs
+ 3. generated alignment
+
+ Args:
+ x (torch.Tensor): batch of texts, converted to a tensor with phoneme embedding ids.
+ shape: (batch_size, max_text_length)
+ x_lengths (torch.Tensor): lengths of texts in batch.
+ shape: (batch_size,)
+ n_timesteps (int): number of steps to use for reverse diffusion in decoder.
+ temperature (float, optional): controls variance of terminal distribution.
+ spks (bool, optional): speaker ids.
+ shape: (batch_size,)
+ length_scale (float, optional): controls speech pace.
+ Increase value to slow down generated speech and vice versa.
+ latent_shift (torch.Tensor, optional): The extracted emotion/accent vector to apply.
+ alpha (float, optional): The intensity multiplier for the latent shift.
+
+ Returns:
+ dict: {
+ "encoder_outputs": torch.Tensor, shape: (batch_size, n_feats, max_mel_length),
+ # Average mel spectrogram generated by the encoder
+ "decoder_outputs": torch.Tensor, shape: (batch_size, n_feats, max_mel_length),
+ # Refined mel spectrogram improved by the CFM
+ "attn": torch.Tensor, shape: (batch_size, max_text_length, max_mel_length),
+ # Alignment map between text and mel spectrogram
+ "mel": torch.Tensor, shape: (batch_size, n_feats, max_mel_length),
+ # Denormalized mel spectrogram
+ "mel_lengths": torch.Tensor, shape: (batch_size,),
+ # Lengths of mel spectrograms
+ "rtf": float,
+ # Real-time factor
+ """
+
+ # For RTF computation
+ t = dt.datetime.now()
+
+ if self.n_spks > 1 and spks is not None:
+ # Get speaker embedding
+ spks = self.spk_emb(spks.long())
+
+ # --- Adding vector injection ---
+ if latent_shift is not None:
+ # Ensure the vector is on the same device as the model (CPU/GPU)
+ shift_tensor = latent_shift.to(spks.device).squeeze()
+ # Mathematically shift the vocal tract!
+ spks = spks + (shift_tensor * alpha)
+ # -------------------------------------
+ else:
+ spks = None
+
+ # Get encoder_outputs `mu_x` and log-scaled token durations `logw`
+ mu_x, logw, x_mask = self.encoder(x, x_lengths, spks)
+
+ w = torch.exp(logw) * x_mask
+ w_ceil = torch.ceil(w) * length_scale
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
+ y_max_length = y_lengths.max()
+ y_max_length_ = fix_len_compatibility(y_max_length)
+
+ # Using obtained durations `w` construct alignment map `attn`
+ y_mask = sequence_mask(y_lengths, y_max_length_).unsqueeze(1).to(x_mask.dtype)
+ attn_mask = x_mask.unsqueeze(-1) * y_mask.unsqueeze(2)
+ attn = generate_path(w_ceil.squeeze(1), attn_mask.squeeze(1)).unsqueeze(1)
+
+ # Align encoded text and get mu_y
+ mu_y = torch.matmul(attn.squeeze(1).transpose(1, 2), mu_x.transpose(1, 2))
+ mu_y = mu_y.transpose(1, 2)
+ encoder_outputs = mu_y[:, :, :y_max_length]
+
+ # Generate sample tracing the probability flow
+ decoder_outputs = self.decoder(mu_y, y_mask, n_timesteps, temperature, spks)
+ decoder_outputs = decoder_outputs[:, :, :y_max_length]
+
+ t = (dt.datetime.now() - t).total_seconds()
+ rtf = t * 22050 / (decoder_outputs.shape[-1] * 256)
+
+ return {
+ "encoder_outputs": encoder_outputs,
+ "decoder_outputs": decoder_outputs,
+ "attn": attn[:, :, :y_max_length],
+ "mel": denormalize(decoder_outputs, self.mel_mean, self.mel_std),
+ "mel_lengths": y_lengths,
+ "rtf": rtf,
+ }
+
+ def forward(self, x, x_lengths, y, y_lengths, spks=None, out_size=None, cond=None, durations=None):
+ """
+ Computes 3 losses:
+ 1. duration loss: loss between predicted token durations and those extracted by Monotinic Alignment Search (MAS).
+ 2. prior loss: loss between mel-spectrogram and encoder outputs.
+ 3. flow matching loss: loss between mel-spectrogram and decoder outputs.
+
+ Args:
+ x (torch.Tensor): batch of texts, converted to a tensor with phoneme embedding ids.
+ shape: (batch_size, max_text_length)
+ x_lengths (torch.Tensor): lengths of texts in batch.
+ shape: (batch_size,)
+ y (torch.Tensor): batch of corresponding mel-spectrograms.
+ shape: (batch_size, n_feats, max_mel_length)
+ y_lengths (torch.Tensor): lengths of mel-spectrograms in batch.
+ shape: (batch_size,)
+ out_size (int, optional): length (in mel's sampling rate) of segment to cut, on which decoder will be trained.
+ Should be divisible by 2^{num of UNet downsamplings}. Needed to increase batch size.
+ spks (torch.Tensor, optional): speaker ids.
+ shape: (batch_size,)
+ """
+ if self.n_spks > 1 and spks is not None:
+ # Get speaker embedding
+ spks = self.spk_emb(spks)
+ else:
+ # If single speaker, the decoder must receive None, not a 1D ID tensor
+ spks = None
+
+ # Get encoder_outputs `mu_x` and log-scaled token durations `logw`
+ mu_x, logw, x_mask = self.encoder(x, x_lengths, spks)
+ y_max_length = y.shape[-1]
+
+ y_mask = sequence_mask(y_lengths, y_max_length).unsqueeze(1).to(x_mask)
+ attn_mask = x_mask.unsqueeze(-1) * y_mask.unsqueeze(2)
+
+ if self.use_precomputed_durations:
+ attn = generate_path(durations.squeeze(1), attn_mask.squeeze(1))
+ else:
+ # Use MAS to find most likely alignment `attn` between text and mel-spectrogram
+ with torch.no_grad():
+ const = -0.5 * math.log(2 * math.pi) * self.n_feats
+ factor = -0.5 * torch.ones(mu_x.shape, dtype=mu_x.dtype, device=mu_x.device)
+ y_square = torch.matmul(factor.transpose(1, 2), y**2)
+ y_mu_double = torch.matmul(2.0 * (factor * mu_x).transpose(1, 2), y)
+ mu_square = torch.sum(factor * (mu_x**2), 1).unsqueeze(-1)
+ log_prior = y_square - y_mu_double + mu_square + const
+
+ attn = monotonic_align.maximum_path(log_prior, attn_mask.squeeze(1))
+ attn = attn.detach() # b, t_text, T_mel
+
+ # Compute loss between predicted log-scaled durations and those obtained from MAS
+ # refered to as prior loss in the paper
+ logw_ = torch.log(1e-8 + torch.sum(attn.unsqueeze(1), -1)) * x_mask
+ dur_loss = duration_loss(logw, logw_, x_lengths)
+
+ # Cut a small segment of mel-spectrogram in order to increase batch size
+ # - "Hack" taken from Grad-TTS, in case of Grad-TTS, we cannot train batch size 32 on a 24GB GPU without it
+ # - Do not need this hack for Matcha-TTS, but it works with it as well
+ if not isinstance(out_size, type(None)):
+ max_offset = (y_lengths - out_size).clamp(0)
+ offset_ranges = list(zip([0] * max_offset.shape[0], max_offset.cpu().numpy()))
+ out_offset = torch.LongTensor(
+ [torch.tensor(random.choice(range(start, end)) if end > start else 0) for start, end in offset_ranges]
+ ).to(y_lengths)
+ attn_cut = torch.zeros(attn.shape[0], attn.shape[1], out_size, dtype=attn.dtype, device=attn.device)
+ y_cut = torch.zeros(y.shape[0], self.n_feats, out_size, dtype=y.dtype, device=y.device)
+
+ y_cut_lengths = []
+ for i, (y_, out_offset_) in enumerate(zip(y, out_offset)):
+ y_cut_length = out_size + (y_lengths[i] - out_size).clamp(None, 0)
+ y_cut_lengths.append(y_cut_length)
+ cut_lower, cut_upper = out_offset_, out_offset_ + y_cut_length
+ y_cut[i, :, :y_cut_length] = y_[:, cut_lower:cut_upper]
+ attn_cut[i, :, :y_cut_length] = attn[i, :, cut_lower:cut_upper]
+
+ y_cut_lengths = torch.LongTensor(y_cut_lengths)
+ y_cut_mask = sequence_mask(y_cut_lengths).unsqueeze(1).to(y_mask)
+
+ attn = attn_cut
+ y = y_cut
+ y_mask = y_cut_mask
+
+ # Align encoded text with mel-spectrogram and get mu_y segment
+ mu_y = torch.matmul(attn.squeeze(1).transpose(1, 2), mu_x.transpose(1, 2))
+ mu_y = mu_y.transpose(1, 2)
+
+ # Compute loss of the decoder
+ diff_loss, _ = self.decoder.compute_loss(x1=y, mask=y_mask, mu=mu_y, spks=spks, cond=cond)
+
+ if self.prior_loss:
+ prior_loss = torch.sum(0.5 * ((y - mu_y) ** 2 + math.log(2 * math.pi)) * y_mask)
+ prior_loss = prior_loss / (torch.sum(y_mask) * self.n_feats)
+ else:
+ prior_loss = 0
+
+ return dur_loss, prior_loss, diff_loss, attn
\ No newline at end of file
diff --git a/matcha/onnx/__init__.py b/matcha/onnx/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/onnx/export.py b/matcha/onnx/export.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b795086158e1ad8a4bb5cd92306f3fa765f71ea
--- /dev/null
+++ b/matcha/onnx/export.py
@@ -0,0 +1,181 @@
+import argparse
+import random
+from pathlib import Path
+
+import numpy as np
+import torch
+from lightning import LightningModule
+
+from matcha.cli import VOCODER_URLS, load_matcha, load_vocoder
+
+DEFAULT_OPSET = 15
+
+SEED = 1234
+random.seed(SEED)
+np.random.seed(SEED)
+torch.manual_seed(SEED)
+torch.cuda.manual_seed(SEED)
+torch.backends.cudnn.deterministic = True
+torch.backends.cudnn.benchmark = False
+
+
+class MatchaWithVocoder(LightningModule):
+ def __init__(self, matcha, vocoder):
+ super().__init__()
+ self.matcha = matcha
+ self.vocoder = vocoder
+
+ def forward(self, x, x_lengths, scales, spks=None):
+ mel, mel_lengths = self.matcha(x, x_lengths, scales, spks)
+ wavs = self.vocoder(mel).clamp(-1, 1)
+ lengths = mel_lengths * 256
+ return wavs.squeeze(1), lengths
+
+
+def get_exportable_module(matcha, vocoder, n_timesteps):
+ """
+ Return an appropriate `LighteningModule` and output-node names
+ based on whether the vocoder is embedded in the final graph
+ """
+
+ def onnx_forward_func(x, x_lengths, scales, spks=None):
+ """
+ Custom forward function for accepting
+ scaler parameters as tensors
+ """
+ # Extract scaler parameters from tensors
+ temperature = scales[0]
+ length_scale = scales[1]
+ output = matcha.synthesise(x, x_lengths, n_timesteps, temperature, spks, length_scale)
+ return output["mel"], output["mel_lengths"]
+
+ # Monkey-patch Matcha's forward function
+ matcha.forward = onnx_forward_func
+
+ if vocoder is None:
+ model, output_names = matcha, ["mel", "mel_lengths"]
+ else:
+ model = MatchaWithVocoder(matcha, vocoder)
+ output_names = ["wav", "wav_lengths"]
+ return model, output_names
+
+
+def get_inputs(is_multi_speaker):
+ """
+ Create dummy inputs for tracing
+ """
+ dummy_input_length = 50
+ x = torch.randint(low=0, high=20, size=(1, dummy_input_length), dtype=torch.long)
+ x_lengths = torch.LongTensor([dummy_input_length])
+
+ # Scales
+ temperature = 0.667
+ length_scale = 1.0
+ scales = torch.Tensor([temperature, length_scale])
+
+ model_inputs = [x, x_lengths, scales]
+ input_names = [
+ "x",
+ "x_lengths",
+ "scales",
+ ]
+
+ if is_multi_speaker:
+ spks = torch.LongTensor([1])
+ model_inputs.append(spks)
+ input_names.append("spks")
+
+ return tuple(model_inputs), input_names
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Export 🍵 Matcha-TTS to ONNX")
+
+ parser.add_argument(
+ "checkpoint_path",
+ type=str,
+ help="Path to the model checkpoint",
+ )
+ parser.add_argument("output", type=str, help="Path to output `.onnx` file")
+ parser.add_argument(
+ "--n-timesteps", type=int, default=5, help="Number of steps to use for reverse diffusion in decoder (default 5)"
+ )
+ parser.add_argument(
+ "--vocoder-name",
+ type=str,
+ choices=list(VOCODER_URLS.keys()),
+ default=None,
+ help="Name of the vocoder to embed in the ONNX graph",
+ )
+ parser.add_argument(
+ "--vocoder-checkpoint-path",
+ type=str,
+ default=None,
+ help="Vocoder checkpoint to embed in the ONNX graph for an `e2e` like experience",
+ )
+ parser.add_argument("--opset", type=int, default=DEFAULT_OPSET, help="ONNX opset version to use (default 15")
+
+ args = parser.parse_args()
+
+ print(f"[🍵] Loading Matcha checkpoint from {args.checkpoint_path}")
+ print(f"Setting n_timesteps to {args.n_timesteps}")
+
+ checkpoint_path = Path(args.checkpoint_path)
+ matcha = load_matcha(checkpoint_path.stem, checkpoint_path, "cpu")
+
+ if args.vocoder_name or args.vocoder_checkpoint_path:
+ assert (
+ args.vocoder_name and args.vocoder_checkpoint_path
+ ), "Both vocoder_name and vocoder-checkpoint are required when embedding the vocoder in the ONNX graph."
+ vocoder, _ = load_vocoder(args.vocoder_name, args.vocoder_checkpoint_path, "cpu")
+ else:
+ vocoder = None
+
+ is_multi_speaker = matcha.n_spks > 1
+
+ dummy_input, input_names = get_inputs(is_multi_speaker)
+ model, output_names = get_exportable_module(matcha, vocoder, args.n_timesteps)
+
+ # Set dynamic shape for inputs/outputs
+ dynamic_axes = {
+ "x": {0: "batch_size", 1: "time"},
+ "x_lengths": {0: "batch_size"},
+ }
+
+ if vocoder is None:
+ dynamic_axes.update(
+ {
+ "mel": {0: "batch_size", 2: "time"},
+ "mel_lengths": {0: "batch_size"},
+ }
+ )
+ else:
+ print("Embedding the vocoder in the ONNX graph")
+ dynamic_axes.update(
+ {
+ "wav": {0: "batch_size", 1: "time"},
+ "wav_lengths": {0: "batch_size"},
+ }
+ )
+
+ if is_multi_speaker:
+ dynamic_axes["spks"] = {0: "batch_size"}
+
+ # Create the output directory (if not exists)
+ Path(args.output).parent.mkdir(parents=True, exist_ok=True)
+
+ model.to_onnx(
+ args.output,
+ dummy_input,
+ input_names=input_names,
+ output_names=output_names,
+ dynamic_axes=dynamic_axes,
+ opset_version=args.opset,
+ export_params=True,
+ do_constant_folding=True,
+ )
+ print(f"[🍵] ONNX model exported to {args.output}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/matcha/onnx/infer.py b/matcha/onnx/infer.py
new file mode 100644
index 0000000000000000000000000000000000000000..89ca92559c6df3776a07a038d7838242a3d19189
--- /dev/null
+++ b/matcha/onnx/infer.py
@@ -0,0 +1,168 @@
+import argparse
+import os
+import warnings
+from pathlib import Path
+from time import perf_counter
+
+import numpy as np
+import onnxruntime as ort
+import soundfile as sf
+import torch
+
+from matcha.cli import plot_spectrogram_to_numpy, process_text
+
+
+def validate_args(args):
+ assert (
+ args.text or args.file
+ ), "Either text or file must be provided Matcha-T(ea)TTS need sometext to whisk the waveforms."
+ assert args.temperature >= 0, "Sampling temperature cannot be negative"
+ assert args.speaking_rate >= 0, "Speaking rate must be greater than 0"
+ return args
+
+
+def write_wavs(model, inputs, output_dir, external_vocoder=None):
+ if external_vocoder is None:
+ print("The provided model has the vocoder embedded in the graph.\nGenerating waveform directly")
+ t0 = perf_counter()
+ wavs, wav_lengths = model.run(None, inputs)
+ infer_secs = perf_counter() - t0
+ mel_infer_secs = vocoder_infer_secs = None
+ else:
+ print("[🍵] Generating mel using Matcha")
+ mel_t0 = perf_counter()
+ mels, mel_lengths = model.run(None, inputs)
+ mel_infer_secs = perf_counter() - mel_t0
+ print("Generating waveform from mel using external vocoder")
+ vocoder_inputs = {external_vocoder.get_inputs()[0].name: mels}
+ vocoder_t0 = perf_counter()
+ wavs = external_vocoder.run(None, vocoder_inputs)[0]
+ vocoder_infer_secs = perf_counter() - vocoder_t0
+ wavs = wavs.squeeze(1)
+ wav_lengths = mel_lengths * 256
+ infer_secs = mel_infer_secs + vocoder_infer_secs
+
+ output_dir = Path(output_dir)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ for i, (wav, wav_length) in enumerate(zip(wavs, wav_lengths)):
+ output_filename = output_dir.joinpath(f"output_{i + 1}.wav")
+ audio = wav[:wav_length]
+ print(f"Writing audio to {output_filename}")
+ sf.write(output_filename, audio, 22050, "PCM_24")
+
+ wav_secs = wav_lengths.sum() / 22050
+ print(f"Inference seconds: {infer_secs}")
+ print(f"Generated wav seconds: {wav_secs}")
+ rtf = infer_secs / wav_secs
+ if mel_infer_secs is not None:
+ mel_rtf = mel_infer_secs / wav_secs
+ print(f"Matcha RTF: {mel_rtf}")
+ if vocoder_infer_secs is not None:
+ vocoder_rtf = vocoder_infer_secs / wav_secs
+ print(f"Vocoder RTF: {vocoder_rtf}")
+ print(f"Overall RTF: {rtf}")
+
+
+def write_mels(model, inputs, output_dir):
+ t0 = perf_counter()
+ mels, mel_lengths = model.run(None, inputs)
+ infer_secs = perf_counter() - t0
+
+ output_dir = Path(output_dir)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ for i, mel in enumerate(mels):
+ output_stem = output_dir.joinpath(f"output_{i + 1}")
+ plot_spectrogram_to_numpy(mel.squeeze(), output_stem.with_suffix(".png"))
+ np.save(output_stem.with_suffix(".numpy"), mel)
+
+ wav_secs = (mel_lengths * 256).sum() / 22050
+ print(f"Inference seconds: {infer_secs}")
+ print(f"Generated wav seconds: {wav_secs}")
+ rtf = infer_secs / wav_secs
+ print(f"RTF: {rtf}")
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description=" 🍵 Matcha-TTS: A fast TTS architecture with conditional flow matching"
+ )
+ parser.add_argument(
+ "model",
+ type=str,
+ help="ONNX model to use",
+ )
+ parser.add_argument("--vocoder", type=str, default=None, help="Vocoder to use (defaults to None)")
+ parser.add_argument("--text", type=str, default=None, help="Text to synthesize")
+ parser.add_argument("--file", type=str, default=None, help="Text file to synthesize")
+ parser.add_argument("--spk", type=int, default=None, help="Speaker ID")
+ parser.add_argument(
+ "--temperature",
+ type=float,
+ default=0.667,
+ help="Variance of the x0 noise (default: 0.667)",
+ )
+ parser.add_argument(
+ "--speaking-rate",
+ type=float,
+ default=1.0,
+ help="change the speaking rate, a higher value means slower speaking rate (default: 1.0)",
+ )
+ parser.add_argument("--gpu", action="store_true", help="Use CPU for inference (default: use GPU if available)")
+ parser.add_argument(
+ "--output-dir",
+ type=str,
+ default=os.getcwd(),
+ help="Output folder to save results (default: current dir)",
+ )
+
+ args = parser.parse_args()
+ args = validate_args(args)
+
+ if args.gpu:
+ providers = ["GPUExecutionProvider"]
+ else:
+ providers = ["CPUExecutionProvider"]
+ model = ort.InferenceSession(args.model, providers=providers)
+
+ model_inputs = model.get_inputs()
+ model_outputs = list(model.get_outputs())
+
+ if args.text:
+ text_lines = args.text.splitlines()
+ else:
+ with open(args.file, encoding="utf-8") as file:
+ text_lines = file.read().splitlines()
+
+ processed_lines = [process_text(0, line, "cpu") for line in text_lines]
+ x = [line["x"].squeeze() for line in processed_lines]
+ # Pad
+ x = torch.nn.utils.rnn.pad_sequence(x, batch_first=True)
+ x = x.detach().cpu().numpy()
+ x_lengths = np.array([line["x_lengths"].item() for line in processed_lines], dtype=np.int64)
+ inputs = {
+ "x": x,
+ "x_lengths": x_lengths,
+ "scales": np.array([args.temperature, args.speaking_rate], dtype=np.float32),
+ }
+ is_multi_speaker = len(model_inputs) == 4
+ if is_multi_speaker:
+ if args.spk is None:
+ args.spk = 0
+ warn = "[!] Speaker ID not provided! Using speaker ID 0"
+ warnings.warn(warn, UserWarning)
+ inputs["spks"] = np.repeat(args.spk, x.shape[0]).astype(np.int64)
+
+ has_vocoder_embedded = model_outputs[0].name == "wav"
+ if has_vocoder_embedded:
+ write_wavs(model, inputs, args.output_dir)
+ elif args.vocoder:
+ external_vocoder = ort.InferenceSession(args.vocoder, providers=providers)
+ write_wavs(model, inputs, args.output_dir, external_vocoder=external_vocoder)
+ else:
+ warn = "[!] A vocoder is not embedded in the graph nor an external vocoder is provided. The mel output will be written as numpy arrays to `*.npy` files in the output directory"
+ warnings.warn(warn, UserWarning)
+ write_mels(model, inputs, args.output_dir)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/matcha/text/__init__.py b/matcha/text/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c75d6b5714a0a2d30b95e00a5377c13f29d9b8a
--- /dev/null
+++ b/matcha/text/__init__.py
@@ -0,0 +1,53 @@
+""" from https://github.com/keithito/tacotron """
+from matcha.text import cleaners
+from matcha.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)} # pylint: disable=unnecessary-comprehension
+
+
+def text_to_sequence(text, cleaner_names):
+ """Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
+ 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 = []
+
+ clean_text = _clean_text(text, cleaner_names)
+ for symbol in clean_text:
+ symbol_id = _symbol_to_id[symbol]
+ sequence += [symbol_id]
+ return sequence, clean_text
+
+
+def cleaned_text_to_sequence(cleaned_text):
+ """Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
+ Args:
+ text: string to convert to a sequence
+ Returns:
+ List of integers corresponding to the symbols in the text
+ """
+ sequence = [_symbol_to_id[symbol] for symbol in cleaned_text]
+ return sequence
+
+
+def sequence_to_text(sequence):
+ """Converts a sequence of IDs back to a string"""
+ result = ""
+ for symbol_id in sequence:
+ s = _id_to_symbol[symbol_id]
+ result += s
+ return result
+
+
+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
diff --git a/matcha/text/__pycache__/__init__.cpython-310.pyc b/matcha/text/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c34165d9df87fff0623b596602db9c46457d14e5
Binary files /dev/null and b/matcha/text/__pycache__/__init__.cpython-310.pyc differ
diff --git a/matcha/text/__pycache__/__init__.cpython-311.pyc b/matcha/text/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b67d45025e1982474bd99fe472041e9bc79cc9d6
Binary files /dev/null and b/matcha/text/__pycache__/__init__.cpython-311.pyc differ
diff --git a/matcha/text/__pycache__/__init__.py b/matcha/text/__pycache__/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/text/__pycache__/cleaners.cpython-310.pyc b/matcha/text/__pycache__/cleaners.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2811460141ce7d8d4a35e34a1d1cf1a605abfac0
Binary files /dev/null and b/matcha/text/__pycache__/cleaners.cpython-310.pyc differ
diff --git a/matcha/text/__pycache__/cleaners.cpython-311.pyc b/matcha/text/__pycache__/cleaners.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7eb4debdc581bb741da7746740b849a9b08a0c2
Binary files /dev/null and b/matcha/text/__pycache__/cleaners.cpython-311.pyc differ
diff --git a/matcha/text/__pycache__/numbers.cpython-310.pyc b/matcha/text/__pycache__/numbers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e707b04d2c7d28f04914d3a64865853a1483fe5
Binary files /dev/null and b/matcha/text/__pycache__/numbers.cpython-310.pyc differ
diff --git a/matcha/text/__pycache__/symbols.cpython-310.pyc b/matcha/text/__pycache__/symbols.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6e971f2caa646ee3fa5cd9db569481abafcf144
Binary files /dev/null and b/matcha/text/__pycache__/symbols.cpython-310.pyc differ
diff --git a/matcha/text/__pycache__/symbols.cpython-311.pyc b/matcha/text/__pycache__/symbols.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..950f0a551c79f18d6b09af6dc1c796855bb6a718
Binary files /dev/null and b/matcha/text/__pycache__/symbols.cpython-311.pyc differ
diff --git a/matcha/text/cleaners.py b/matcha/text/cleaners.py
new file mode 100644
index 0000000000000000000000000000000000000000..04f5199de0f4779473c8e2f1e2418073026f7b1a
--- /dev/null
+++ b/matcha/text/cleaners.py
@@ -0,0 +1,136 @@
+import logging
+import re
+import os
+import phonemizer
+from unidecode import unidecode
+
+# Set logging to critical to avoid excessive output
+critical_logger = logging.getLogger("phonemizer")
+critical_logger.setLevel(logging.CRITICAL)
+
+# --- THE DEFENSIVE BLOCK ---
+# We keep these global but empty so they don't crash on import
+_global_phonemizer = None
+_tried_phonemizer = False
+
+def get_phonemizer():
+ """Retrieve or initialize the English phonemizer only when needed."""
+ global _global_phonemizer, _tried_phonemizer
+
+ if _global_phonemizer is None and not _tried_phonemizer:
+ _tried_phonemizer = True
+ try:
+ import phonemizer
+ possible_binaries = [
+ "/home/ak8224/.local/bin/espeak-ng",
+ "/rds/general/user/ak8224/home/.local/bin/espeak-ng",
+ "espeak-ng",
+ "espeak"
+ ]
+
+ for binary in possible_binaries:
+ try:
+ _global_phonemizer = phonemizer.backend.EspeakBackend(
+ language="en-us",
+ preserve_punctuation=True,
+ with_stress=True,
+ language_switch="remove-flags",
+ logger=critical_logger,
+ espeak_ng_binary=binary
+ )
+ print(f"✅ Successfully initialized espeak using: {binary}")
+ break
+ except Exception:
+ continue
+ except ImportError:
+ pass
+
+ if _global_phonemizer is None:
+ print("⚠️ WARNING: espeak-ng not found. Falling back to character-based cleaning.")
+
+ return _global_phonemizer
+
+# --- ENGLISH TEXT LOGIC ---
+_whitespace_re = re.compile(r"\s+")
+
+# --- Added aphasia-specific tokens ---
+_clinical_tokens_re = re.compile(r'(@|\.\.\.|~|\*)')
+
+_abbreviations_en = [
+ (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
+ for x in [
+ ("mrs", "misess"), ("ms", "miss"), ("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"),
+ ]
+]
+
+# Note: Removed the old ELLIPSIS_MARKER logic, it is handled dynamically now.
+_replacements_en = [
+ (re.compile(r"\$(\d+)\.(\d+)"), r"\1 dollars and \2 cents"),
+ (re.compile(r"(?<=\D)\.(?=\D)(?!\s)", re.IGNORECASE), " dot "),
+ (re.compile(r"(?<=\d)\.(?=\d)(?!\s)"), " point "),
+ (re.compile(r"\$(\d+)"), r"\1 dollars"),
+]
+
+def lowercase(text):
+ return text.lower()
+
+def collapse_whitespace(text):
+ return re.sub(_whitespace_re, " ", text)
+
+def english_cleaners2(text):
+ """Pipeline for English text. Custom clinical tokens bypass espeak entirely."""
+
+ try:
+ from phonemizer import phonemize
+ except ImportError:
+ return collapse_whitespace(text.lower())
+
+ text = text.encode("utf-8").decode("utf-8")
+ text = lowercase(text)
+
+ for regex, replacement in _abbreviations_en:
+ text = re.sub(regex, replacement, text)
+ for regex, replacement in _replacements_en:
+ text = regex.sub(replacement, text)
+
+ # Step 1: Slice the text based on the custom tokens
+ # "hello @ world..." -> ["hello ", "@", " world", "...", ""]
+ parts = _clinical_tokens_re.split(text)
+
+ cleaned_parts = []
+
+ for part in parts:
+ # Step 2: If the part is a clinical token, bypass espeak!
+ if part in ["@", "...", "~", "*"]:
+ cleaned_parts.append(part)
+ else:
+ # Step 3: If it is normal text, send it to espeak
+ if part.strip() == "":
+ cleaned_parts.append(part)
+ continue
+
+ try:
+ phonemes = phonemize(
+ part,
+ language='en-us',
+ backend='espeak',
+ strip=True,
+ preserve_punctuation=True,
+ with_stress=True
+ )
+ cleaned_parts.append(phonemes)
+ except Exception as e:
+ print(f"⚠️ Phonemization CRITICAL FAILURE: {e}")
+ cleaned_parts.append(part)
+
+ # Step 4: Glue it all back together
+ final_text = " ".join(cleaned_parts)
+ return collapse_whitespace(final_text)
+
+# Keep a dummy basic_cleaners just in case Hydra calls it
+def basic_cleaners(text):
+ return collapse_whitespace(lowercase(text))
\ No newline at end of file
diff --git a/matcha/text/numbers.py b/matcha/text/numbers.py
new file mode 100644
index 0000000000000000000000000000000000000000..f99a8686dcb73532091122613e74bd643a8a327f
--- /dev/null
+++ b/matcha/text/numbers.py
@@ -0,0 +1,71 @@
+""" from https://github.com/keithito/tacotron """
+
+import re
+
+import inflect
+
+_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"
+ 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 f"{dollars} {dollar_unit}, {cents} {cent_unit}"
+ elif dollars:
+ dollar_unit = "dollar" if dollars == 1 else "dollars"
+ return f"{dollars} {dollar_unit}"
+ elif cents:
+ cent_unit = "cent" if cents == 1 else "cents"
+ return f"{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
diff --git a/matcha/text/symbols.py b/matcha/text/symbols.py
new file mode 100644
index 0000000000000000000000000000000000000000..75540957e0874b011726518dd84fbca6ad795010
--- /dev/null
+++ b/matcha/text/symbols.py
@@ -0,0 +1,20 @@
+""" from https://github.com/keithito/tacotron
+
+Defines the set of symbols used in text input to the model.
+"""
+_pad = "_"
+_punctuation = ';:,.!?¡¿—…"«»“” '
+_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+_letters_ipa = (
+ "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ'̃'-'̞ᵝʨʦũĩʣʥ%+]\\()["
+)
+
+# Define your new custom tokens safely here:
+_custom_clinical = "@#*~"
+
+
+# Export all symbols: Concatenate the custom tokens at the VERY END
+symbols = [_pad] + list(_punctuation) + list(_letters) + list(_letters_ipa) + list(_custom_clinical)
+
+# Special symbol ids
+SPACE_ID = symbols.index(" ")
\ No newline at end of file
diff --git a/matcha/utils/__init__.py b/matcha/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..074db6461184e8cbb86d977cb41d9ebd918e958a
--- /dev/null
+++ b/matcha/utils/__init__.py
@@ -0,0 +1,5 @@
+from matcha.utils.instantiators import instantiate_callbacks, instantiate_loggers
+from matcha.utils.logging_utils import log_hyperparameters
+from matcha.utils.pylogger import get_pylogger
+from matcha.utils.rich_utils import enforce_tags, print_config_tree
+from matcha.utils.utils import extras, get_metric_value, task_wrapper
diff --git a/matcha/utils/__pycache__/__init__.cpython-310.pyc b/matcha/utils/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7370d0c5351bf04a0e881efa7d812608cf1e69e2
Binary files /dev/null and b/matcha/utils/__pycache__/__init__.cpython-310.pyc differ
diff --git a/matcha/utils/__pycache__/__init__.cpython-311.pyc b/matcha/utils/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e268377beb4997a953ce6885f3e439d354ce1a38
Binary files /dev/null and b/matcha/utils/__pycache__/__init__.cpython-311.pyc differ
diff --git a/matcha/utils/__pycache__/__init__.py b/matcha/utils/__pycache__/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/utils/__pycache__/audio.cpython-310.pyc b/matcha/utils/__pycache__/audio.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74b5ba528ea0fcd6674059bbe471c5590be5aaa0
Binary files /dev/null and b/matcha/utils/__pycache__/audio.cpython-310.pyc differ
diff --git a/matcha/utils/__pycache__/instantiators.cpython-310.pyc b/matcha/utils/__pycache__/instantiators.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab00e5fa02b4c002da73aaf32e787af50841421f
Binary files /dev/null and b/matcha/utils/__pycache__/instantiators.cpython-310.pyc differ
diff --git a/matcha/utils/__pycache__/instantiators.cpython-311.pyc b/matcha/utils/__pycache__/instantiators.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b9557933b419f3d3ba4665b341ac930dce75fac
Binary files /dev/null and b/matcha/utils/__pycache__/instantiators.cpython-311.pyc differ
diff --git a/matcha/utils/__pycache__/logging_utils.cpython-310.pyc b/matcha/utils/__pycache__/logging_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..004fc35268cbb45365ce414a73a2e3da15adce0f
Binary files /dev/null and b/matcha/utils/__pycache__/logging_utils.cpython-310.pyc differ
diff --git a/matcha/utils/__pycache__/logging_utils.cpython-311.pyc b/matcha/utils/__pycache__/logging_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76f5a11919fb8053e5bb8e29d65d91b23efdee3f
Binary files /dev/null and b/matcha/utils/__pycache__/logging_utils.cpython-311.pyc differ
diff --git a/matcha/utils/__pycache__/model.cpython-310.pyc b/matcha/utils/__pycache__/model.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96e37642bfa1ffa7213b42cf6f57a4add05ad081
Binary files /dev/null and b/matcha/utils/__pycache__/model.cpython-310.pyc differ
diff --git a/matcha/utils/__pycache__/model.cpython-311.pyc b/matcha/utils/__pycache__/model.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..caa9469edd529017bae9a7c835494c12d30c2bbd
Binary files /dev/null and b/matcha/utils/__pycache__/model.cpython-311.pyc differ
diff --git a/matcha/utils/__pycache__/pylogger.cpython-310.pyc b/matcha/utils/__pycache__/pylogger.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68437d66ab6a80b7bd5ef36bc7dee845b05653eb
Binary files /dev/null and b/matcha/utils/__pycache__/pylogger.cpython-310.pyc differ
diff --git a/matcha/utils/__pycache__/pylogger.cpython-311.pyc b/matcha/utils/__pycache__/pylogger.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c802d4dcd6a5579c42571b0dae67dbaccafcf08e
Binary files /dev/null and b/matcha/utils/__pycache__/pylogger.cpython-311.pyc differ
diff --git a/matcha/utils/__pycache__/rich_utils.cpython-310.pyc b/matcha/utils/__pycache__/rich_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67ba7d8910636f8ed70423c15450430a5cd929f7
Binary files /dev/null and b/matcha/utils/__pycache__/rich_utils.cpython-310.pyc differ
diff --git a/matcha/utils/__pycache__/rich_utils.cpython-311.pyc b/matcha/utils/__pycache__/rich_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd1da388babc2f6baba54cf612d752230565d13b
Binary files /dev/null and b/matcha/utils/__pycache__/rich_utils.cpython-311.pyc differ
diff --git a/matcha/utils/__pycache__/utils.cpython-310.pyc b/matcha/utils/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6f74011893b87261ab583d7cc105ea8d5accde4
Binary files /dev/null and b/matcha/utils/__pycache__/utils.cpython-310.pyc differ
diff --git a/matcha/utils/__pycache__/utils.cpython-311.pyc b/matcha/utils/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9ecf1235202ce2c2b5c552236229a8ffd8e1fdd
Binary files /dev/null and b/matcha/utils/__pycache__/utils.cpython-311.pyc differ
diff --git a/matcha/utils/audio.py b/matcha/utils/audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bcd74df47fb006f68deb5a5f4a4c2fb0aa84f57
--- /dev/null
+++ b/matcha/utils/audio.py
@@ -0,0 +1,82 @@
+import numpy as np
+import torch
+import torch.utils.data
+from librosa.filters import mel as librosa_mel_fn
+from scipy.io.wavfile import read
+
+MAX_WAV_VALUE = 32768.0
+
+
+def load_wav(full_path):
+ sampling_rate, data = read(full_path)
+ return data, sampling_rate
+
+
+def dynamic_range_compression(x, C=1, clip_val=1e-5):
+ return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
+
+
+def dynamic_range_decompression(x, C=1):
+ return np.exp(x) / C
+
+
+def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
+ return torch.log(torch.clamp(x, min=clip_val) * C)
+
+
+def dynamic_range_decompression_torch(x, C=1):
+ return torch.exp(x) / C
+
+
+def spectral_normalize_torch(magnitudes):
+ output = dynamic_range_compression_torch(magnitudes)
+ return output
+
+
+def spectral_de_normalize_torch(magnitudes):
+ output = dynamic_range_decompression_torch(magnitudes)
+ return output
+
+
+mel_basis = {}
+hann_window = {}
+
+
+def mel_spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
+ if torch.min(y) < -1.0:
+ print("min value is ", torch.min(y))
+ if torch.max(y) > 1.0:
+ print("max value is ", torch.max(y))
+
+ global mel_basis, hann_window # pylint: disable=global-statement
+ if f"{str(fmax)}_{str(y.device)}" not in mel_basis:
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
+ mel_basis[str(fmax) + "_" + str(y.device)] = torch.from_numpy(mel).float().to(y.device)
+ hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)
+
+ y = torch.nn.functional.pad(
+ y.unsqueeze(1), (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)), mode="reflect"
+ )
+ y = y.squeeze(1)
+
+ spec = torch.view_as_real(
+ torch.stft(
+ y,
+ n_fft,
+ hop_length=hop_size,
+ win_length=win_size,
+ window=hann_window[str(y.device)],
+ center=center,
+ pad_mode="reflect",
+ normalized=False,
+ onesided=True,
+ return_complex=True,
+ )
+ )
+
+ spec = torch.sqrt(spec.pow(2).sum(-1) + (1e-9))
+
+ spec = torch.matmul(mel_basis[str(fmax) + "_" + str(y.device)], spec)
+ spec = spectral_normalize_torch(spec)
+
+ return spec
diff --git a/matcha/utils/generate_data_statistics.py b/matcha/utils/generate_data_statistics.py
new file mode 100644
index 0000000000000000000000000000000000000000..49ed3c1b072cc3292c899b200d657a8beec197f8
--- /dev/null
+++ b/matcha/utils/generate_data_statistics.py
@@ -0,0 +1,112 @@
+r"""
+The file creates a pickle file where the values needed for loading of dataset is stored and the model can load it
+when needed.
+
+Parameters from hparam.py will be used
+"""
+import argparse
+import json
+import os
+import sys
+from pathlib import Path
+
+import rootutils
+import torch
+from hydra import compose, initialize
+from omegaconf import open_dict
+from tqdm.auto import tqdm
+
+from matcha.data.text_mel_datamodule import TextMelDataModule
+from matcha.utils.logging_utils import pylogger
+
+log = pylogger.get_pylogger(__name__)
+
+
+def compute_data_statistics(data_loader: torch.utils.data.DataLoader, out_channels: int):
+ """Generate data mean and standard deviation helpful in data normalisation
+
+ Args:
+ data_loader (torch.utils.data.Dataloader): _description_
+ out_channels (int): mel spectrogram channels
+ """
+ total_mel_sum = 0
+ total_mel_sq_sum = 0
+ total_mel_len = 0
+
+ for batch in tqdm(data_loader, leave=False):
+ mels = batch["y"]
+ mel_lengths = batch["y_lengths"]
+
+ total_mel_len += torch.sum(mel_lengths)
+ total_mel_sum += torch.sum(mels)
+ total_mel_sq_sum += torch.sum(torch.pow(mels, 2))
+
+ data_mean = total_mel_sum / (total_mel_len * out_channels)
+ data_std = torch.sqrt((total_mel_sq_sum / (total_mel_len * out_channels)) - torch.pow(data_mean, 2))
+
+ return {"mel_mean": data_mean.item(), "mel_std": data_std.item()}
+
+
+def main():
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "-i",
+ "--input-config",
+ type=str,
+ default="vctk.yaml",
+ help="The name of the yaml config file under configs/data",
+ )
+
+ parser.add_argument(
+ "-b",
+ "--batch-size",
+ type=int,
+ default="256",
+ help="Can have increased batch size for faster computation",
+ )
+
+ parser.add_argument(
+ "-f",
+ "--force",
+ action="store_true",
+ default=False,
+ required=False,
+ help="force overwrite the file",
+ )
+ args = parser.parse_args()
+ output_file = Path(args.input_config).with_suffix(".json")
+
+ if os.path.exists(output_file) and not args.force:
+ print("File already exists. Use -f to force overwrite")
+ sys.exit(1)
+
+ with initialize(version_base="1.3", config_path="../../configs/data"):
+ cfg = compose(config_name=args.input_config, return_hydra_config=True, overrides=[])
+
+ root_path = rootutils.find_root(search_from=__file__, indicator=".project-root")
+
+ with open_dict(cfg):
+ del cfg["hydra"]
+ del cfg["_target_"]
+ cfg["data_statistics"] = None
+ cfg["seed"] = 1234
+ cfg["batch_size"] = args.batch_size
+ cfg["train_filelist_path"] = str(os.path.join(root_path, cfg["train_filelist_path"]))
+ cfg["valid_filelist_path"] = str(os.path.join(root_path, cfg["valid_filelist_path"]))
+ cfg["load_durations"] = False
+
+ text_mel_datamodule = TextMelDataModule(**cfg)
+ text_mel_datamodule.setup()
+ data_loader = text_mel_datamodule.train_dataloader()
+ log.info("Dataloader loaded! Now computing stats...")
+ params = compute_data_statistics(data_loader, cfg["n_feats"])
+ print(params)
+ json.dump(
+ params,
+ open(output_file, "w"),
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/matcha/utils/get_durations_from_trained_model.py b/matcha/utils/get_durations_from_trained_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fe2f35c4238756158370ed1463bfa06f05f7e3d
--- /dev/null
+++ b/matcha/utils/get_durations_from_trained_model.py
@@ -0,0 +1,195 @@
+r"""
+The file creates a pickle file where the values needed for loading of dataset is stored and the model can load it
+when needed.
+
+Parameters from hparam.py will be used
+"""
+import argparse
+import json
+import os
+import sys
+from pathlib import Path
+
+import lightning
+import numpy as np
+import rootutils
+import torch
+from hydra import compose, initialize
+from omegaconf import open_dict
+from torch import nn
+from tqdm.auto import tqdm
+
+from matcha.cli import get_device
+from matcha.data.text_mel_datamodule import TextMelDataModule
+from matcha.models.matcha_tts import MatchaTTS
+from matcha.utils.logging_utils import pylogger
+from matcha.utils.utils import get_phoneme_durations
+
+log = pylogger.get_pylogger(__name__)
+
+
+def save_durations_to_folder(
+ attn: torch.Tensor, x_length: int, y_length: int, filepath: str, output_folder: Path, text: str
+):
+ durations = attn.squeeze().sum(1)[:x_length].numpy()
+ durations_json = get_phoneme_durations(durations, text)
+ output = output_folder / Path(filepath).name.replace(".wav", ".npy")
+ with open(output.with_suffix(".json"), "w", encoding="utf-8") as f:
+ json.dump(durations_json, f, indent=4, ensure_ascii=False)
+
+ np.save(output, durations)
+
+
+@torch.inference_mode()
+def compute_durations(data_loader: torch.utils.data.DataLoader, model: nn.Module, device: torch.device, output_folder):
+ """Generate durations from the model for each datapoint and save it in a folder
+
+ Args:
+ data_loader (torch.utils.data.DataLoader): Dataloader
+ model (nn.Module): MatchaTTS model
+ device (torch.device): GPU or CPU
+ """
+
+ for batch in tqdm(data_loader, desc="🍵 Computing durations 🍵:"):
+ x, x_lengths = batch["x"], batch["x_lengths"]
+ y, y_lengths = batch["y"], batch["y_lengths"]
+ spks = batch["spks"]
+ x = x.to(device)
+ y = y.to(device)
+ x_lengths = x_lengths.to(device)
+ y_lengths = y_lengths.to(device)
+ spks = spks.to(device) if spks is not None else None
+
+ _, _, _, attn = model(
+ x=x,
+ x_lengths=x_lengths,
+ y=y,
+ y_lengths=y_lengths,
+ spks=spks,
+ )
+ attn = attn.cpu()
+ for i in range(attn.shape[0]):
+ save_durations_to_folder(
+ attn[i],
+ x_lengths[i].item(),
+ y_lengths[i].item(),
+ batch["filepaths"][i],
+ output_folder,
+ batch["x_texts"][i],
+ )
+
+
+def main():
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "-i",
+ "--input-config",
+ type=str,
+ default="ljspeech.yaml",
+ help="The name of the yaml config file under configs/data",
+ )
+
+ parser.add_argument(
+ "-b",
+ "--batch-size",
+ type=int,
+ default="32",
+ help="Can have increased batch size for faster computation",
+ )
+
+ parser.add_argument(
+ "-f",
+ "--force",
+ action="store_true",
+ default=False,
+ required=False,
+ help="force overwrite the file",
+ )
+ parser.add_argument(
+ "-c",
+ "--checkpoint_path",
+ type=str,
+ required=True,
+ help="Path to the checkpoint file to load the model from",
+ )
+
+ parser.add_argument(
+ "-o",
+ "--output-folder",
+ type=str,
+ default=None,
+ help="Output folder to save the data statistics",
+ )
+
+ parser.add_argument(
+ "--cpu", action="store_true", help="Use CPU for inference, not recommended (default: use GPU if available)"
+ )
+
+ args = parser.parse_args()
+
+ with initialize(version_base="1.3", config_path="../../configs/data"):
+ cfg = compose(config_name=args.input_config, return_hydra_config=True, overrides=[])
+
+ root_path = rootutils.find_root(search_from=__file__, indicator=".project-root")
+
+ with open_dict(cfg):
+ del cfg["hydra"]
+ del cfg["_target_"]
+ cfg["seed"] = 1234
+ cfg["batch_size"] = args.batch_size
+ cfg["train_filelist_path"] = str(os.path.join(root_path, cfg["train_filelist_path"]))
+ cfg["valid_filelist_path"] = str(os.path.join(root_path, cfg["valid_filelist_path"]))
+ cfg["load_durations"] = False
+
+ if args.output_folder is not None:
+ output_folder = Path(args.output_folder)
+ else:
+ output_folder = Path(cfg["train_filelist_path"]).parent / "durations"
+
+ print(f"Output folder set to: {output_folder}")
+
+ if os.path.exists(output_folder) and not args.force:
+ print("Folder already exists. Use -f to force overwrite")
+ sys.exit(1)
+
+ output_folder.mkdir(parents=True, exist_ok=True)
+
+ print(f"Preprocessing: {cfg['name']} from training filelist: {cfg['train_filelist_path']}")
+ print("Loading model...")
+ device = get_device(args)
+ model = MatchaTTS.load_from_checkpoint(args.checkpoint_path, map_location=device)
+
+ text_mel_datamodule = TextMelDataModule(**cfg)
+ text_mel_datamodule.setup()
+ try:
+ print("Computing stats for training set if exists...")
+ train_dataloader = text_mel_datamodule.train_dataloader()
+ compute_durations(train_dataloader, model, device, output_folder)
+ except lightning.fabric.utilities.exceptions.MisconfigurationException:
+ print("No training set found")
+
+ try:
+ print("Computing stats for validation set if exists...")
+ val_dataloader = text_mel_datamodule.val_dataloader()
+ compute_durations(val_dataloader, model, device, output_folder)
+ except lightning.fabric.utilities.exceptions.MisconfigurationException:
+ print("No validation set found")
+
+ try:
+ print("Computing stats for test set if exists...")
+ test_dataloader = text_mel_datamodule.test_dataloader()
+ compute_durations(test_dataloader, model, device, output_folder)
+ except lightning.fabric.utilities.exceptions.MisconfigurationException:
+ print("No test set found")
+
+ print(f"[+] Done! Data statistics saved to: {output_folder}")
+
+
+if __name__ == "__main__":
+ # Helps with generating durations for the dataset to train other architectures
+ # that cannot learn to align due to limited size of dataset
+ # Example usage:
+ # python python matcha/utils/get_durations_from_trained_model.py -i ljspeech.yaml -c pretrained_model
+ # This will create a folder in data/processed_data/durations/ljspeech with the durations
+ main()
diff --git a/matcha/utils/instantiators.py b/matcha/utils/instantiators.py
new file mode 100644
index 0000000000000000000000000000000000000000..5547b4ed61ed8c21e63c528f58526a949879a94f
--- /dev/null
+++ b/matcha/utils/instantiators.py
@@ -0,0 +1,56 @@
+from typing import List
+
+import hydra
+from lightning import Callback
+from lightning.pytorch.loggers import Logger
+from omegaconf import DictConfig
+
+from matcha.utils import pylogger
+
+log = pylogger.get_pylogger(__name__)
+
+
+def instantiate_callbacks(callbacks_cfg: DictConfig) -> List[Callback]:
+ """Instantiates callbacks from config.
+
+ :param callbacks_cfg: A DictConfig object containing callback configurations.
+ :return: A list of instantiated callbacks.
+ """
+ callbacks: List[Callback] = []
+
+ if not callbacks_cfg:
+ log.warning("No callback configs found! Skipping..")
+ return callbacks
+
+ if not isinstance(callbacks_cfg, DictConfig):
+ raise TypeError("Callbacks config must be a DictConfig!")
+
+ for _, cb_conf in callbacks_cfg.items():
+ if isinstance(cb_conf, DictConfig) and "_target_" in cb_conf:
+ log.info(f"Instantiating callback <{cb_conf._target_}>") # pylint: disable=protected-access
+ callbacks.append(hydra.utils.instantiate(cb_conf))
+
+ return callbacks
+
+
+def instantiate_loggers(logger_cfg: DictConfig) -> List[Logger]:
+ """Instantiates loggers from config.
+
+ :param logger_cfg: A DictConfig object containing logger configurations.
+ :return: A list of instantiated loggers.
+ """
+ logger: List[Logger] = []
+
+ if not logger_cfg:
+ log.warning("No logger configs found! Skipping...")
+ return logger
+
+ if not isinstance(logger_cfg, DictConfig):
+ raise TypeError("Logger config must be a DictConfig!")
+
+ for _, lg_conf in logger_cfg.items():
+ if isinstance(lg_conf, DictConfig) and "_target_" in lg_conf:
+ log.info(f"Instantiating logger <{lg_conf._target_}>") # pylint: disable=protected-access
+ logger.append(hydra.utils.instantiate(lg_conf))
+
+ return logger
diff --git a/matcha/utils/logging_utils.py b/matcha/utils/logging_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a12d1ddafa25ca3ae8e497bcd7de2191f13659b
--- /dev/null
+++ b/matcha/utils/logging_utils.py
@@ -0,0 +1,53 @@
+from typing import Any, Dict
+
+from lightning.pytorch.utilities import rank_zero_only
+from omegaconf import OmegaConf
+
+from matcha.utils import pylogger
+
+log = pylogger.get_pylogger(__name__)
+
+
+@rank_zero_only
+def log_hyperparameters(object_dict: Dict[str, Any]) -> None:
+ """Controls which config parts are saved by Lightning loggers.
+
+ Additionally saves:
+ - Number of model parameters
+
+ :param object_dict: A dictionary containing the following objects:
+ - `"cfg"`: A DictConfig object containing the main config.
+ - `"model"`: The Lightning model.
+ - `"trainer"`: The Lightning trainer.
+ """
+ hparams = {}
+
+ cfg = OmegaConf.to_container(object_dict["cfg"])
+ model = object_dict["model"]
+ trainer = object_dict["trainer"]
+
+ if not trainer.logger:
+ log.warning("Logger not found! Skipping hyperparameter logging...")
+ return
+
+ hparams["model"] = cfg["model"]
+
+ # save number of model parameters
+ hparams["model/params/total"] = sum(p.numel() for p in model.parameters())
+ hparams["model/params/trainable"] = sum(p.numel() for p in model.parameters() if p.requires_grad)
+ hparams["model/params/non_trainable"] = sum(p.numel() for p in model.parameters() if not p.requires_grad)
+
+ hparams["data"] = cfg["data"]
+ hparams["trainer"] = cfg["trainer"]
+
+ hparams["callbacks"] = cfg.get("callbacks")
+ hparams["extras"] = cfg.get("extras")
+
+ hparams["task_name"] = cfg.get("task_name")
+ hparams["tags"] = cfg.get("tags")
+ hparams["ckpt_path"] = cfg.get("ckpt_path")
+ hparams["seed"] = cfg.get("seed")
+
+ # send hparams to all loggers
+ for logger in trainer.loggers:
+ logger.log_hyperparams(hparams)
diff --git a/matcha/utils/model.py b/matcha/utils/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..869cc6092f5952930534c47544fae88308e96abf
--- /dev/null
+++ b/matcha/utils/model.py
@@ -0,0 +1,90 @@
+""" from https://github.com/jaywalnut310/glow-tts """
+
+import numpy as np
+import torch
+
+
+def sequence_mask(length, max_length=None):
+ if max_length is None:
+ max_length = length.max()
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
+ return x.unsqueeze(0) < length.unsqueeze(1)
+
+
+def fix_len_compatibility(length, num_downsamplings_in_unet=2):
+ factor = torch.scalar_tensor(2).pow(num_downsamplings_in_unet)
+ length = (length / factor).ceil() * factor
+ if not torch.onnx.is_in_onnx_export():
+ return length.int().item()
+ else:
+ return length
+
+
+def convert_pad_shape(pad_shape):
+ inverted_shape = pad_shape[::-1]
+ pad_shape = [item for sublist in inverted_shape for item in sublist]
+ return pad_shape
+
+
+def generate_path(duration, mask):
+ device = duration.device
+
+ b, t_x, t_y = mask.shape
+ cum_duration = torch.cumsum(duration, 1)
+ path = torch.zeros(b, t_x, t_y, dtype=mask.dtype).to(device=device)
+
+ cum_duration_flat = cum_duration.view(b * t_x)
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
+ path = path.view(b, t_x, t_y)
+ path = path - torch.nn.functional.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
+ path = path * mask
+ return path
+
+
+def duration_loss(logw, logw_, lengths):
+ loss = torch.sum((logw - logw_) ** 2) / torch.sum(lengths)
+ return loss
+
+
+def normalize(data, mu, std):
+ if not isinstance(mu, (float, int)):
+ if isinstance(mu, list):
+ mu = torch.tensor(mu, dtype=data.dtype, device=data.device)
+ elif isinstance(mu, torch.Tensor):
+ mu = mu.to(data.device)
+ elif isinstance(mu, np.ndarray):
+ mu = torch.from_numpy(mu).to(data.device)
+ mu = mu.unsqueeze(-1)
+
+ if not isinstance(std, (float, int)):
+ if isinstance(std, list):
+ std = torch.tensor(std, dtype=data.dtype, device=data.device)
+ elif isinstance(std, torch.Tensor):
+ std = std.to(data.device)
+ elif isinstance(std, np.ndarray):
+ std = torch.from_numpy(std).to(data.device)
+ std = std.unsqueeze(-1)
+
+ return (data - mu) / std
+
+
+def denormalize(data, mu, std):
+ if not isinstance(mu, float):
+ if isinstance(mu, list):
+ mu = torch.tensor(mu, dtype=data.dtype, device=data.device)
+ elif isinstance(mu, torch.Tensor):
+ mu = mu.to(data.device)
+ elif isinstance(mu, np.ndarray):
+ mu = torch.from_numpy(mu).to(data.device)
+ mu = mu.unsqueeze(-1)
+
+ if not isinstance(std, float):
+ if isinstance(std, list):
+ std = torch.tensor(std, dtype=data.dtype, device=data.device)
+ elif isinstance(std, torch.Tensor):
+ std = std.to(data.device)
+ elif isinstance(std, np.ndarray):
+ std = torch.from_numpy(std).to(data.device)
+ std = std.unsqueeze(-1)
+
+ return data * std + mu
diff --git a/matcha/utils/monotonic_align/__init__.py b/matcha/utils/monotonic_align/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eee6e0d47c2e3612ef02bc17442e6886998e5a94
--- /dev/null
+++ b/matcha/utils/monotonic_align/__init__.py
@@ -0,0 +1,22 @@
+import numpy as np
+import torch
+
+from matcha.utils.monotonic_align.core import maximum_path_c
+
+
+def maximum_path(value, mask):
+ """Cython optimised version.
+ value: [b, t_x, t_y]
+ mask: [b, t_x, t_y]
+ """
+ value = value * mask
+ device = value.device
+ dtype = value.dtype
+ value = value.data.cpu().numpy().astype(np.float32)
+ path = np.zeros_like(value).astype(np.int32)
+ mask = mask.data.cpu().numpy()
+
+ t_x_max = mask.sum(1)[:, 0].astype(np.int32)
+ t_y_max = mask.sum(2)[:, 0].astype(np.int32)
+ maximum_path_c(path, value, t_x_max, t_y_max)
+ return torch.from_numpy(path).to(device=device, dtype=dtype)
diff --git a/matcha/utils/monotonic_align/__pycache__/__init__.cpython-310.pyc b/matcha/utils/monotonic_align/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d3ebad39b786816cb0fc38dfd1bd448891bcad44
Binary files /dev/null and b/matcha/utils/monotonic_align/__pycache__/__init__.cpython-310.pyc differ
diff --git a/matcha/utils/monotonic_align/__pycache__/__init__.py b/matcha/utils/monotonic_align/__pycache__/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/matcha/utils/monotonic_align/core.c b/matcha/utils/monotonic_align/core.c
new file mode 100644
index 0000000000000000000000000000000000000000..37edd8b7aecf1377bca9c274651d4d9f28d8abd7
--- /dev/null
+++ b/matcha/utils/monotonic_align/core.c
@@ -0,0 +1,23568 @@
+/* Generated by Cython 0.29.35 */
+
+/* BEGIN: Cython Metadata
+{
+ "distutils": {
+ "depends": [],
+ "name": "matcha.utils.monotonic_align.core",
+ "sources": [
+ "matcha/utils/monotonic_align/core.pyx"
+ ]
+ },
+ "module_name": "matcha.utils.monotonic_align.core"
+}
+END: Cython Metadata */
+
+#ifndef PY_SSIZE_T_CLEAN
+#define PY_SSIZE_T_CLEAN
+#endif /* PY_SSIZE_T_CLEAN */
+#include "Python.h"
+#ifndef Py_PYTHON_H
+ #error Python headers needed to compile C extensions, please install development version of Python.
+#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000)
+ #error Cython requires Python 2.6+ or Python 3.3+.
+#else
+#define CYTHON_ABI "0_29_35"
+#define CYTHON_HEX_VERSION 0x001D23F0
+#define CYTHON_FUTURE_DIVISION 1
+#include
+#ifndef offsetof
+ #define offsetof(type, member) ( (size_t) & ((type*)0) -> member )
+#endif
+#if !defined(WIN32) && !defined(MS_WINDOWS)
+ #ifndef __stdcall
+ #define __stdcall
+ #endif
+ #ifndef __cdecl
+ #define __cdecl
+ #endif
+ #ifndef __fastcall
+ #define __fastcall
+ #endif
+#endif
+#ifndef DL_IMPORT
+ #define DL_IMPORT(t) t
+#endif
+#ifndef DL_EXPORT
+ #define DL_EXPORT(t) t
+#endif
+#define __PYX_COMMA ,
+#ifndef HAVE_LONG_LONG
+ #if PY_VERSION_HEX >= 0x02070000
+ #define HAVE_LONG_LONG
+ #endif
+#endif
+#ifndef PY_LONG_LONG
+ #define PY_LONG_LONG LONG_LONG
+#endif
+#ifndef Py_HUGE_VAL
+ #define Py_HUGE_VAL HUGE_VAL
+#endif
+#ifdef PYPY_VERSION
+ #define CYTHON_COMPILING_IN_PYPY 1
+ #define CYTHON_COMPILING_IN_PYSTON 0
+ #define CYTHON_COMPILING_IN_CPYTHON 0
+ #define CYTHON_COMPILING_IN_NOGIL 0
+ #undef CYTHON_USE_TYPE_SLOTS
+ #define CYTHON_USE_TYPE_SLOTS 0
+ #undef CYTHON_USE_PYTYPE_LOOKUP
+ #define CYTHON_USE_PYTYPE_LOOKUP 0
+ #if PY_VERSION_HEX < 0x03050000
+ #undef CYTHON_USE_ASYNC_SLOTS
+ #define CYTHON_USE_ASYNC_SLOTS 0
+ #elif !defined(CYTHON_USE_ASYNC_SLOTS)
+ #define CYTHON_USE_ASYNC_SLOTS 1
+ #endif
+ #undef CYTHON_USE_PYLIST_INTERNALS
+ #define CYTHON_USE_PYLIST_INTERNALS 0
+ #undef CYTHON_USE_UNICODE_INTERNALS
+ #define CYTHON_USE_UNICODE_INTERNALS 0
+ #undef CYTHON_USE_UNICODE_WRITER
+ #define CYTHON_USE_UNICODE_WRITER 0
+ #undef CYTHON_USE_PYLONG_INTERNALS
+ #define CYTHON_USE_PYLONG_INTERNALS 0
+ #undef CYTHON_AVOID_BORROWED_REFS
+ #define CYTHON_AVOID_BORROWED_REFS 1
+ #undef CYTHON_ASSUME_SAFE_MACROS
+ #define CYTHON_ASSUME_SAFE_MACROS 0
+ #undef CYTHON_UNPACK_METHODS
+ #define CYTHON_UNPACK_METHODS 0
+ #undef CYTHON_FAST_THREAD_STATE
+ #define CYTHON_FAST_THREAD_STATE 0
+ #undef CYTHON_FAST_PYCALL
+ #define CYTHON_FAST_PYCALL 0
+ #if PY_VERSION_HEX < 0x03090000
+ #undef CYTHON_PEP489_MULTI_PHASE_INIT
+ #define CYTHON_PEP489_MULTI_PHASE_INIT 0
+ #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT)
+ #define CYTHON_PEP489_MULTI_PHASE_INIT 1
+ #endif
+ #undef CYTHON_USE_TP_FINALIZE
+ #define CYTHON_USE_TP_FINALIZE 0
+ #undef CYTHON_USE_DICT_VERSIONS
+ #define CYTHON_USE_DICT_VERSIONS 0
+ #undef CYTHON_USE_EXC_INFO_STACK
+ #define CYTHON_USE_EXC_INFO_STACK 0
+ #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC
+ #define CYTHON_UPDATE_DESCRIPTOR_DOC 0
+ #endif
+#elif defined(PYSTON_VERSION)
+ #define CYTHON_COMPILING_IN_PYPY 0
+ #define CYTHON_COMPILING_IN_PYSTON 1
+ #define CYTHON_COMPILING_IN_CPYTHON 0
+ #define CYTHON_COMPILING_IN_NOGIL 0
+ #ifndef CYTHON_USE_TYPE_SLOTS
+ #define CYTHON_USE_TYPE_SLOTS 1
+ #endif
+ #undef CYTHON_USE_PYTYPE_LOOKUP
+ #define CYTHON_USE_PYTYPE_LOOKUP 0
+ #undef CYTHON_USE_ASYNC_SLOTS
+ #define CYTHON_USE_ASYNC_SLOTS 0
+ #undef CYTHON_USE_PYLIST_INTERNALS
+ #define CYTHON_USE_PYLIST_INTERNALS 0
+ #ifndef CYTHON_USE_UNICODE_INTERNALS
+ #define CYTHON_USE_UNICODE_INTERNALS 1
+ #endif
+ #undef CYTHON_USE_UNICODE_WRITER
+ #define CYTHON_USE_UNICODE_WRITER 0
+ #undef CYTHON_USE_PYLONG_INTERNALS
+ #define CYTHON_USE_PYLONG_INTERNALS 0
+ #ifndef CYTHON_AVOID_BORROWED_REFS
+ #define CYTHON_AVOID_BORROWED_REFS 0
+ #endif
+ #ifndef CYTHON_ASSUME_SAFE_MACROS
+ #define CYTHON_ASSUME_SAFE_MACROS 1
+ #endif
+ #ifndef CYTHON_UNPACK_METHODS
+ #define CYTHON_UNPACK_METHODS 1
+ #endif
+ #undef CYTHON_FAST_THREAD_STATE
+ #define CYTHON_FAST_THREAD_STATE 0
+ #undef CYTHON_FAST_PYCALL
+ #define CYTHON_FAST_PYCALL 0
+ #undef CYTHON_PEP489_MULTI_PHASE_INIT
+ #define CYTHON_PEP489_MULTI_PHASE_INIT 0
+ #undef CYTHON_USE_TP_FINALIZE
+ #define CYTHON_USE_TP_FINALIZE 0
+ #undef CYTHON_USE_DICT_VERSIONS
+ #define CYTHON_USE_DICT_VERSIONS 0
+ #undef CYTHON_USE_EXC_INFO_STACK
+ #define CYTHON_USE_EXC_INFO_STACK 0
+ #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC
+ #define CYTHON_UPDATE_DESCRIPTOR_DOC 0
+ #endif
+#elif defined(PY_NOGIL)
+ #define CYTHON_COMPILING_IN_PYPY 0
+ #define CYTHON_COMPILING_IN_PYSTON 0
+ #define CYTHON_COMPILING_IN_CPYTHON 0
+ #define CYTHON_COMPILING_IN_NOGIL 1
+ #ifndef CYTHON_USE_TYPE_SLOTS
+ #define CYTHON_USE_TYPE_SLOTS 1
+ #endif
+ #undef CYTHON_USE_PYTYPE_LOOKUP
+ #define CYTHON_USE_PYTYPE_LOOKUP 0
+ #ifndef CYTHON_USE_ASYNC_SLOTS
+ #define CYTHON_USE_ASYNC_SLOTS 1
+ #endif
+ #undef CYTHON_USE_PYLIST_INTERNALS
+ #define CYTHON_USE_PYLIST_INTERNALS 0
+ #ifndef CYTHON_USE_UNICODE_INTERNALS
+ #define CYTHON_USE_UNICODE_INTERNALS 1
+ #endif
+ #undef CYTHON_USE_UNICODE_WRITER
+ #define CYTHON_USE_UNICODE_WRITER 0
+ #undef CYTHON_USE_PYLONG_INTERNALS
+ #define CYTHON_USE_PYLONG_INTERNALS 0
+ #ifndef CYTHON_AVOID_BORROWED_REFS
+ #define CYTHON_AVOID_BORROWED_REFS 0
+ #endif
+ #ifndef CYTHON_ASSUME_SAFE_MACROS
+ #define CYTHON_ASSUME_SAFE_MACROS 1
+ #endif
+ #ifndef CYTHON_UNPACK_METHODS
+ #define CYTHON_UNPACK_METHODS 1
+ #endif
+ #undef CYTHON_FAST_THREAD_STATE
+ #define CYTHON_FAST_THREAD_STATE 0
+ #undef CYTHON_FAST_PYCALL
+ #define CYTHON_FAST_PYCALL 0
+ #ifndef CYTHON_PEP489_MULTI_PHASE_INIT
+ #define CYTHON_PEP489_MULTI_PHASE_INIT 1
+ #endif
+ #ifndef CYTHON_USE_TP_FINALIZE
+ #define CYTHON_USE_TP_FINALIZE 1
+ #endif
+ #undef CYTHON_USE_DICT_VERSIONS
+ #define CYTHON_USE_DICT_VERSIONS 0
+ #undef CYTHON_USE_EXC_INFO_STACK
+ #define CYTHON_USE_EXC_INFO_STACK 0
+#else
+ #define CYTHON_COMPILING_IN_PYPY 0
+ #define CYTHON_COMPILING_IN_PYSTON 0
+ #define CYTHON_COMPILING_IN_CPYTHON 1
+ #define CYTHON_COMPILING_IN_NOGIL 0
+ #ifndef CYTHON_USE_TYPE_SLOTS
+ #define CYTHON_USE_TYPE_SLOTS 1
+ #endif
+ #if PY_VERSION_HEX < 0x02070000
+ #undef CYTHON_USE_PYTYPE_LOOKUP
+ #define CYTHON_USE_PYTYPE_LOOKUP 0
+ #elif !defined(CYTHON_USE_PYTYPE_LOOKUP)
+ #define CYTHON_USE_PYTYPE_LOOKUP 1
+ #endif
+ #if PY_MAJOR_VERSION < 3
+ #undef CYTHON_USE_ASYNC_SLOTS
+ #define CYTHON_USE_ASYNC_SLOTS 0
+ #elif !defined(CYTHON_USE_ASYNC_SLOTS)
+ #define CYTHON_USE_ASYNC_SLOTS 1
+ #endif
+ #if PY_VERSION_HEX < 0x02070000
+ #undef CYTHON_USE_PYLONG_INTERNALS
+ #define CYTHON_USE_PYLONG_INTERNALS 0
+ #elif !defined(CYTHON_USE_PYLONG_INTERNALS)
+ #define CYTHON_USE_PYLONG_INTERNALS (PY_VERSION_HEX < 0x030C00A5)
+ #endif
+ #ifndef CYTHON_USE_PYLIST_INTERNALS
+ #define CYTHON_USE_PYLIST_INTERNALS 1
+ #endif
+ #ifndef CYTHON_USE_UNICODE_INTERNALS
+ #define CYTHON_USE_UNICODE_INTERNALS 1
+ #endif
+ #if PY_VERSION_HEX < 0x030300F0 || PY_VERSION_HEX >= 0x030B00A2
+ #undef CYTHON_USE_UNICODE_WRITER
+ #define CYTHON_USE_UNICODE_WRITER 0
+ #elif !defined(CYTHON_USE_UNICODE_WRITER)
+ #define CYTHON_USE_UNICODE_WRITER 1
+ #endif
+ #ifndef CYTHON_AVOID_BORROWED_REFS
+ #define CYTHON_AVOID_BORROWED_REFS 0
+ #endif
+ #ifndef CYTHON_ASSUME_SAFE_MACROS
+ #define CYTHON_ASSUME_SAFE_MACROS 1
+ #endif
+ #ifndef CYTHON_UNPACK_METHODS
+ #define CYTHON_UNPACK_METHODS 1
+ #endif
+ #if PY_VERSION_HEX >= 0x030B00A4
+ #undef CYTHON_FAST_THREAD_STATE
+ #define CYTHON_FAST_THREAD_STATE 0
+ #elif !defined(CYTHON_FAST_THREAD_STATE)
+ #define CYTHON_FAST_THREAD_STATE 1
+ #endif
+ #ifndef CYTHON_FAST_PYCALL
+ #define CYTHON_FAST_PYCALL (PY_VERSION_HEX < 0x030A0000)
+ #endif
+ #ifndef CYTHON_PEP489_MULTI_PHASE_INIT
+ #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000)
+ #endif
+ #ifndef CYTHON_USE_TP_FINALIZE
+ #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1)
+ #endif
+ #ifndef CYTHON_USE_DICT_VERSIONS
+ #define CYTHON_USE_DICT_VERSIONS ((PY_VERSION_HEX >= 0x030600B1) && (PY_VERSION_HEX < 0x030C00A5))
+ #endif
+ #if PY_VERSION_HEX >= 0x030B00A4
+ #undef CYTHON_USE_EXC_INFO_STACK
+ #define CYTHON_USE_EXC_INFO_STACK 0
+ #elif !defined(CYTHON_USE_EXC_INFO_STACK)
+ #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3)
+ #endif
+ #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC
+ #define CYTHON_UPDATE_DESCRIPTOR_DOC 1
+ #endif
+#endif
+#if !defined(CYTHON_FAST_PYCCALL)
+#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1)
+#endif
+#if CYTHON_USE_PYLONG_INTERNALS
+ #if PY_MAJOR_VERSION < 3
+ #include "longintrepr.h"
+ #endif
+ #undef SHIFT
+ #undef BASE
+ #undef MASK
+ #ifdef SIZEOF_VOID_P
+ enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) };
+ #endif
+#endif
+#ifndef __has_attribute
+ #define __has_attribute(x) 0
+#endif
+#ifndef __has_cpp_attribute
+ #define __has_cpp_attribute(x) 0
+#endif
+#ifndef CYTHON_RESTRICT
+ #if defined(__GNUC__)
+ #define CYTHON_RESTRICT __restrict__
+ #elif defined(_MSC_VER) && _MSC_VER >= 1400
+ #define CYTHON_RESTRICT __restrict
+ #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+ #define CYTHON_RESTRICT restrict
+ #else
+ #define CYTHON_RESTRICT
+ #endif
+#endif
+#ifndef CYTHON_UNUSED
+# if defined(__GNUC__)
+# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
+# define CYTHON_UNUSED __attribute__ ((__unused__))
+# else
+# define CYTHON_UNUSED
+# endif
+# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER))
+# define CYTHON_UNUSED __attribute__ ((__unused__))
+# else
+# define CYTHON_UNUSED
+# endif
+#endif
+#ifndef CYTHON_MAYBE_UNUSED_VAR
+# if defined(__cplusplus)
+ template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { }
+# else
+# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x)
+# endif
+#endif
+#ifndef CYTHON_NCP_UNUSED
+# if CYTHON_COMPILING_IN_CPYTHON
+# define CYTHON_NCP_UNUSED
+# else
+# define CYTHON_NCP_UNUSED CYTHON_UNUSED
+# endif
+#endif
+#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None)
+#ifdef _MSC_VER
+ #ifndef _MSC_STDINT_H_
+ #if _MSC_VER < 1300
+ typedef unsigned char uint8_t;
+ typedef unsigned int uint32_t;
+ #else
+ typedef unsigned __int8 uint8_t;
+ typedef unsigned __int32 uint32_t;
+ #endif
+ #endif
+#else
+ #include
+#endif
+#ifndef CYTHON_FALLTHROUGH
+ #if defined(__cplusplus) && __cplusplus >= 201103L
+ #if __has_cpp_attribute(fallthrough)
+ #define CYTHON_FALLTHROUGH [[fallthrough]]
+ #elif __has_cpp_attribute(clang::fallthrough)
+ #define CYTHON_FALLTHROUGH [[clang::fallthrough]]
+ #elif __has_cpp_attribute(gnu::fallthrough)
+ #define CYTHON_FALLTHROUGH [[gnu::fallthrough]]
+ #endif
+ #endif
+ #ifndef CYTHON_FALLTHROUGH
+ #if __has_attribute(fallthrough)
+ #define CYTHON_FALLTHROUGH __attribute__((fallthrough))
+ #else
+ #define CYTHON_FALLTHROUGH
+ #endif
+ #endif
+ #if defined(__clang__ ) && defined(__apple_build_version__)
+ #if __apple_build_version__ < 7000000
+ #undef CYTHON_FALLTHROUGH
+ #define CYTHON_FALLTHROUGH
+ #endif
+ #endif
+#endif
+
+#ifndef CYTHON_INLINE
+ #if defined(__clang__)
+ #define CYTHON_INLINE __inline__ __attribute__ ((__unused__))
+ #elif defined(__GNUC__)
+ #define CYTHON_INLINE __inline__
+ #elif defined(_MSC_VER)
+ #define CYTHON_INLINE __inline
+ #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+ #define CYTHON_INLINE inline
+ #else
+ #define CYTHON_INLINE
+ #endif
+#endif
+
+#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag)
+ #define Py_OptimizeFlag 0
+#endif
+#define __PYX_BUILD_PY_SSIZE_T "n"
+#define CYTHON_FORMAT_SSIZE_T "z"
+#if PY_MAJOR_VERSION < 3
+ #define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
+ #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
+ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
+ #define __Pyx_DefaultClassType PyClass_Type
+#else
+ #define __Pyx_BUILTIN_MODULE_NAME "builtins"
+ #define __Pyx_DefaultClassType PyType_Type
+#if PY_VERSION_HEX >= 0x030B00A1
+ static CYTHON_INLINE PyCodeObject* __Pyx_PyCode_New(int a, int k, int l, int s, int f,
+ PyObject *code, PyObject *c, PyObject* n, PyObject *v,
+ PyObject *fv, PyObject *cell, PyObject* fn,
+ PyObject *name, int fline, PyObject *lnos) {
+ PyObject *kwds=NULL, *argcount=NULL, *posonlyargcount=NULL, *kwonlyargcount=NULL;
+ PyObject *nlocals=NULL, *stacksize=NULL, *flags=NULL, *replace=NULL, *call_result=NULL, *empty=NULL;
+ const char *fn_cstr=NULL;
+ const char *name_cstr=NULL;
+ PyCodeObject* co=NULL;
+ PyObject *type, *value, *traceback;
+ PyErr_Fetch(&type, &value, &traceback);
+ if (!(kwds=PyDict_New())) goto end;
+ if (!(argcount=PyLong_FromLong(a))) goto end;
+ if (PyDict_SetItemString(kwds, "co_argcount", argcount) != 0) goto end;
+ if (!(posonlyargcount=PyLong_FromLong(0))) goto end;
+ if (PyDict_SetItemString(kwds, "co_posonlyargcount", posonlyargcount) != 0) goto end;
+ if (!(kwonlyargcount=PyLong_FromLong(k))) goto end;
+ if (PyDict_SetItemString(kwds, "co_kwonlyargcount", kwonlyargcount) != 0) goto end;
+ if (!(nlocals=PyLong_FromLong(l))) goto end;
+ if (PyDict_SetItemString(kwds, "co_nlocals", nlocals) != 0) goto end;
+ if (!(stacksize=PyLong_FromLong(s))) goto end;
+ if (PyDict_SetItemString(kwds, "co_stacksize", stacksize) != 0) goto end;
+ if (!(flags=PyLong_FromLong(f))) goto end;
+ if (PyDict_SetItemString(kwds, "co_flags", flags) != 0) goto end;
+ if (PyDict_SetItemString(kwds, "co_code", code) != 0) goto end;
+ if (PyDict_SetItemString(kwds, "co_consts", c) != 0) goto end;
+ if (PyDict_SetItemString(kwds, "co_names", n) != 0) goto end;
+ if (PyDict_SetItemString(kwds, "co_varnames", v) != 0) goto end;
+ if (PyDict_SetItemString(kwds, "co_freevars", fv) != 0) goto end;
+ if (PyDict_SetItemString(kwds, "co_cellvars", cell) != 0) goto end;
+ if (PyDict_SetItemString(kwds, "co_linetable", lnos) != 0) goto end;
+ if (!(fn_cstr=PyUnicode_AsUTF8AndSize(fn, NULL))) goto end;
+ if (!(name_cstr=PyUnicode_AsUTF8AndSize(name, NULL))) goto end;
+ if (!(co = PyCode_NewEmpty(fn_cstr, name_cstr, fline))) goto end;
+ if (!(replace = PyObject_GetAttrString((PyObject*)co, "replace"))) goto cleanup_code_too;
+ if (!(empty = PyTuple_New(0))) goto cleanup_code_too; // unfortunately __pyx_empty_tuple isn't available here
+ if (!(call_result = PyObject_Call(replace, empty, kwds))) goto cleanup_code_too;
+ Py_XDECREF((PyObject*)co);
+ co = (PyCodeObject*)call_result;
+ call_result = NULL;
+ if (0) {
+ cleanup_code_too:
+ Py_XDECREF((PyObject*)co);
+ co = NULL;
+ }
+ end:
+ Py_XDECREF(kwds);
+ Py_XDECREF(argcount);
+ Py_XDECREF(posonlyargcount);
+ Py_XDECREF(kwonlyargcount);
+ Py_XDECREF(nlocals);
+ Py_XDECREF(stacksize);
+ Py_XDECREF(replace);
+ Py_XDECREF(call_result);
+ Py_XDECREF(empty);
+ if (type) {
+ PyErr_Restore(type, value, traceback);
+ }
+ return co;
+ }
+#else
+ #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
+ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
+#endif
+ #define __Pyx_DefaultClassType PyType_Type
+#endif
+#ifndef Py_TPFLAGS_CHECKTYPES
+ #define Py_TPFLAGS_CHECKTYPES 0
+#endif
+#ifndef Py_TPFLAGS_HAVE_INDEX
+ #define Py_TPFLAGS_HAVE_INDEX 0
+#endif
+#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
+ #define Py_TPFLAGS_HAVE_NEWBUFFER 0
+#endif
+#ifndef Py_TPFLAGS_HAVE_FINALIZE
+ #define Py_TPFLAGS_HAVE_FINALIZE 0
+#endif
+#ifndef METH_STACKLESS
+ #define METH_STACKLESS 0
+#endif
+#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL)
+ #ifndef METH_FASTCALL
+ #define METH_FASTCALL 0x80
+ #endif
+ typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs);
+ typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args,
+ Py_ssize_t nargs, PyObject *kwnames);
+#else
+ #define __Pyx_PyCFunctionFast _PyCFunctionFast
+ #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords
+#endif
+#if CYTHON_FAST_PYCCALL
+#define __Pyx_PyFastCFunction_Check(func)\
+ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS)))))
+#else
+#define __Pyx_PyFastCFunction_Check(func) 0
+#endif
+#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc)
+ #define PyObject_Malloc(s) PyMem_Malloc(s)
+ #define PyObject_Free(p) PyMem_Free(p)
+ #define PyObject_Realloc(p) PyMem_Realloc(p)
+#endif
+#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1
+ #define PyMem_RawMalloc(n) PyMem_Malloc(n)
+ #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n)
+ #define PyMem_RawFree(p) PyMem_Free(p)
+#endif
+#if CYTHON_COMPILING_IN_PYSTON
+ #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co)
+ #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno)
+#else
+ #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0)
+ #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno)
+#endif
+#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000
+ #define __Pyx_PyThreadState_Current PyThreadState_GET()
+#elif PY_VERSION_HEX >= 0x03060000
+ #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet()
+#elif PY_VERSION_HEX >= 0x03000000
+ #define __Pyx_PyThreadState_Current PyThreadState_GET()
+#else
+ #define __Pyx_PyThreadState_Current _PyThreadState_Current
+#endif
+#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT)
+#include "pythread.h"
+#define Py_tss_NEEDS_INIT 0
+typedef int Py_tss_t;
+static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) {
+ *key = PyThread_create_key();
+ return 0;
+}
+static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) {
+ Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t));
+ *key = Py_tss_NEEDS_INIT;
+ return key;
+}
+static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) {
+ PyObject_Free(key);
+}
+static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) {
+ return *key != Py_tss_NEEDS_INIT;
+}
+static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) {
+ PyThread_delete_key(*key);
+ *key = Py_tss_NEEDS_INIT;
+}
+static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) {
+ return PyThread_set_key_value(*key, value);
+}
+static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) {
+ return PyThread_get_key_value(*key);
+}
+#endif
+#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized)
+#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n))
+#else
+#define __Pyx_PyDict_NewPresized(n) PyDict_New()
+#endif
+#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION
+ #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y)
+ #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y)
+#else
+ #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y)
+ #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y)
+#endif
+#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS
+#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash)
+#else
+#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name)
+#endif
+#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND)
+ #define CYTHON_PEP393_ENABLED 1
+ #if PY_VERSION_HEX >= 0x030C0000
+ #define __Pyx_PyUnicode_READY(op) (0)
+ #else
+ #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\
+ 0 : _PyUnicode_Ready((PyObject *)(op)))
+ #endif
+ #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u)
+ #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i)
+ #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u)
+ #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u)
+ #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u)
+ #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i)
+ #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch)
+ #if PY_VERSION_HEX >= 0x030C0000
+ #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u))
+ #else
+ #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000
+ #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length))
+ #else
+ #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u)))
+ #endif
+ #endif
+#else
+ #define CYTHON_PEP393_ENABLED 0
+ #define PyUnicode_1BYTE_KIND 1
+ #define PyUnicode_2BYTE_KIND 2
+ #define PyUnicode_4BYTE_KIND 4
+ #define __Pyx_PyUnicode_READY(op) (0)
+ #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u)
+ #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i]))
+ #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111)
+ #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE))
+ #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u))
+ #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i]))
+ #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch)
+ #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u))
+#endif
+#if CYTHON_COMPILING_IN_PYPY
+ #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b)
+ #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b)
+#else
+ #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b)
+ #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\
+ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b))
+#endif
+#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains)
+ #define PyUnicode_Contains(u, s) PySequence_Contains(u, s)
+#endif
+#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check)
+ #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type)
+#endif
+#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format)
+ #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt)
+#endif
+#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b))
+#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b))
+#if PY_MAJOR_VERSION >= 3
+ #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b)
+#else
+ #define __Pyx_PyString_Format(a, b) PyString_Format(a, b)
+#endif
+#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII)
+ #define PyObject_ASCII(o) PyObject_Repr(o)
+#endif
+#if PY_MAJOR_VERSION >= 3
+ #define PyBaseString_Type PyUnicode_Type
+ #define PyStringObject PyUnicodeObject
+ #define PyString_Type PyUnicode_Type
+ #define PyString_Check PyUnicode_Check
+ #define PyString_CheckExact PyUnicode_CheckExact
+#ifndef PyObject_Unicode
+ #define PyObject_Unicode PyObject_Str
+#endif
+#endif
+#if PY_MAJOR_VERSION >= 3
+ #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj)
+ #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj)
+#else
+ #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj))
+ #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj))
+#endif
+#ifndef PySet_CheckExact
+ #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type)
+#endif
+#if PY_VERSION_HEX >= 0x030900A4
+ #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt)
+ #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size)
+#else
+ #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt)
+ #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size)
+#endif
+#if CYTHON_ASSUME_SAFE_MACROS
+ #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq)
+#else
+ #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq)
+#endif
+#if PY_MAJOR_VERSION >= 3
+ #define PyIntObject PyLongObject
+ #define PyInt_Type PyLong_Type
+ #define PyInt_Check(op) PyLong_Check(op)
+ #define PyInt_CheckExact(op) PyLong_CheckExact(op)
+ #define PyInt_FromString PyLong_FromString
+ #define PyInt_FromUnicode PyLong_FromUnicode
+ #define PyInt_FromLong PyLong_FromLong
+ #define PyInt_FromSize_t PyLong_FromSize_t
+ #define PyInt_FromSsize_t PyLong_FromSsize_t
+ #define PyInt_AsLong PyLong_AsLong
+ #define PyInt_AS_LONG PyLong_AS_LONG
+ #define PyInt_AsSsize_t PyLong_AsSsize_t
+ #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
+ #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
+ #define PyNumber_Int PyNumber_Long
+#endif
+#if PY_MAJOR_VERSION >= 3
+ #define PyBoolObject PyLongObject
+#endif
+#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY
+ #ifndef PyUnicode_InternFromString
+ #define PyUnicode_InternFromString(s) PyUnicode_FromString(s)
+ #endif
+#endif
+#if PY_VERSION_HEX < 0x030200A4
+ typedef long Py_hash_t;
+ #define __Pyx_PyInt_FromHash_t PyInt_FromLong
+ #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsHash_t
+#else
+ #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t
+ #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsSsize_t
+#endif
+#if PY_MAJOR_VERSION >= 3
+ #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func))
+#else
+ #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass)
+#endif
+#if CYTHON_USE_ASYNC_SLOTS
+ #if PY_VERSION_HEX >= 0x030500B1
+ #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods
+ #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async)
+ #else
+ #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved))
+ #endif
+#else
+ #define __Pyx_PyType_AsAsync(obj) NULL
+#endif
+#ifndef __Pyx_PyAsyncMethodsStruct
+ typedef struct {
+ unaryfunc am_await;
+ unaryfunc am_aiter;
+ unaryfunc am_anext;
+ } __Pyx_PyAsyncMethodsStruct;
+#endif
+
+#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS)
+ #if !defined(_USE_MATH_DEFINES)
+ #define _USE_MATH_DEFINES
+ #endif
+#endif
+#include
+#ifdef NAN
+#define __PYX_NAN() ((float) NAN)
+#else
+static CYTHON_INLINE float __PYX_NAN() {
+ float value;
+ memset(&value, 0xFF, sizeof(value));
+ return value;
+}
+#endif
+#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL)
+#define __Pyx_truncl trunc
+#else
+#define __Pyx_truncl truncl
+#endif
+
+#define __PYX_MARK_ERR_POS(f_index, lineno) \
+ { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; }
+#define __PYX_ERR(f_index, lineno, Ln_error) \
+ { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; }
+
+#ifndef __PYX_EXTERN_C
+ #ifdef __cplusplus
+ #define __PYX_EXTERN_C extern "C"
+ #else
+ #define __PYX_EXTERN_C extern
+ #endif
+#endif
+
+#define __PYX_HAVE__matcha__utils__monotonic_align__core
+#define __PYX_HAVE_API__matcha__utils__monotonic_align__core
+/* Early includes */
+#include
+#include
+#include "numpy/arrayobject.h"
+#include "numpy/ndarrayobject.h"
+#include "numpy/ndarraytypes.h"
+#include "numpy/arrayscalars.h"
+#include "numpy/ufuncobject.h"
+
+ /* NumPy API declarations from "numpy/__init__.pxd" */
+
+#include "pythread.h"
+#include
+#include "pystate.h"
+#ifdef _OPENMP
+#include
+#endif /* _OPENMP */
+
+#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS)
+#define CYTHON_WITHOUT_ASSERTIONS
+#endif
+
+typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding;
+ const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry;
+
+#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0
+#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0
+#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8)
+#define __PYX_DEFAULT_STRING_ENCODING ""
+#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString
+#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
+#define __Pyx_uchar_cast(c) ((unsigned char)c)
+#define __Pyx_long_cast(x) ((long)x)
+#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\
+ (sizeof(type) < sizeof(Py_ssize_t)) ||\
+ (sizeof(type) > sizeof(Py_ssize_t) &&\
+ likely(v < (type)PY_SSIZE_T_MAX ||\
+ v == (type)PY_SSIZE_T_MAX) &&\
+ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\
+ v == (type)PY_SSIZE_T_MIN))) ||\
+ (sizeof(type) == sizeof(Py_ssize_t) &&\
+ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\
+ v == (type)PY_SSIZE_T_MAX))) )
+static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) {
+ return (size_t) i < (size_t) limit;
+}
+#if defined (__cplusplus) && __cplusplus >= 201103L
+ #include
+ #define __Pyx_sst_abs(value) std::abs(value)
+#elif SIZEOF_INT >= SIZEOF_SIZE_T
+ #define __Pyx_sst_abs(value) abs(value)
+#elif SIZEOF_LONG >= SIZEOF_SIZE_T
+ #define __Pyx_sst_abs(value) labs(value)
+#elif defined (_MSC_VER)
+ #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value))
+#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+ #define __Pyx_sst_abs(value) llabs(value)
+#elif defined (__GNUC__)
+ #define __Pyx_sst_abs(value) __builtin_llabs(value)
+#else
+ #define __Pyx_sst_abs(value) ((value<0) ? -value : value)
+#endif
+static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*);
+static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length);
+#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s))
+#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l)
+#define __Pyx_PyBytes_FromString PyBytes_FromString
+#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
+static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*);
+#if PY_MAJOR_VERSION < 3
+ #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString
+ #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
+#else
+ #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString
+ #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize
+#endif
+#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s))
+#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s))
+#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s))
+#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s))
+#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s))
+#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s))
+#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s))
+#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s))
+#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s))
+#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s))
+#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s))
+#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s)
+#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s)
+#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s)
+#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s)
+#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s)
+static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) {
+ const Py_UNICODE *u_end = u;
+ while (*u_end++) ;
+ return (size_t)(u_end - u - 1);
+}
+#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u))
+#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode
+#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode
+#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj)
+#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None)
+static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b);
+static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
+static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*);
+static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x);
+#define __Pyx_PySequence_Tuple(obj)\
+ (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj))
+static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
+static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
+static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*);
+#if CYTHON_ASSUME_SAFE_MACROS
+#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
+#else
+#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x)
+#endif
+#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x))
+#if PY_MAJOR_VERSION >= 3
+#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x))
+#else
+#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x))
+#endif
+#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x))
+#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
+static int __Pyx_sys_getdefaultencoding_not_ascii;
+static int __Pyx_init_sys_getdefaultencoding_params(void) {
+ PyObject* sys;
+ PyObject* default_encoding = NULL;
+ PyObject* ascii_chars_u = NULL;
+ PyObject* ascii_chars_b = NULL;
+ const char* default_encoding_c;
+ sys = PyImport_ImportModule("sys");
+ if (!sys) goto bad;
+ default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL);
+ Py_DECREF(sys);
+ if (!default_encoding) goto bad;
+ default_encoding_c = PyBytes_AsString(default_encoding);
+ if (!default_encoding_c) goto bad;
+ if (strcmp(default_encoding_c, "ascii") == 0) {
+ __Pyx_sys_getdefaultencoding_not_ascii = 0;
+ } else {
+ char ascii_chars[128];
+ int c;
+ for (c = 0; c < 128; c++) {
+ ascii_chars[c] = c;
+ }
+ __Pyx_sys_getdefaultencoding_not_ascii = 1;
+ ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL);
+ if (!ascii_chars_u) goto bad;
+ ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL);
+ if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) {
+ PyErr_Format(
+ PyExc_ValueError,
+ "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.",
+ default_encoding_c);
+ goto bad;
+ }
+ Py_DECREF(ascii_chars_u);
+ Py_DECREF(ascii_chars_b);
+ }
+ Py_DECREF(default_encoding);
+ return 0;
+bad:
+ Py_XDECREF(default_encoding);
+ Py_XDECREF(ascii_chars_u);
+ Py_XDECREF(ascii_chars_b);
+ return -1;
+}
+#endif
+#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3
+#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL)
+#else
+#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL)
+#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
+static char* __PYX_DEFAULT_STRING_ENCODING;
+static int __Pyx_init_sys_getdefaultencoding_params(void) {
+ PyObject* sys;
+ PyObject* default_encoding = NULL;
+ char* default_encoding_c;
+ sys = PyImport_ImportModule("sys");
+ if (!sys) goto bad;
+ default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL);
+ Py_DECREF(sys);
+ if (!default_encoding) goto bad;
+ default_encoding_c = PyBytes_AsString(default_encoding);
+ if (!default_encoding_c) goto bad;
+ __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1);
+ if (!__PYX_DEFAULT_STRING_ENCODING) goto bad;
+ strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c);
+ Py_DECREF(default_encoding);
+ return 0;
+bad:
+ Py_XDECREF(default_encoding);
+ return -1;
+}
+#endif
+#endif
+
+
+/* Test for GCC > 2.95 */
+#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))
+ #define likely(x) __builtin_expect(!!(x), 1)
+ #define unlikely(x) __builtin_expect(!!(x), 0)
+#else /* !__GNUC__ or GCC < 2.95 */
+ #define likely(x) (x)
+ #define unlikely(x) (x)
+#endif /* __GNUC__ */
+static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; }
+
+static PyObject *__pyx_m = NULL;
+static PyObject *__pyx_d;
+static PyObject *__pyx_b;
+static PyObject *__pyx_cython_runtime = NULL;
+static PyObject *__pyx_empty_tuple;
+static PyObject *__pyx_empty_bytes;
+static PyObject *__pyx_empty_unicode;
+static int __pyx_lineno;
+static int __pyx_clineno = 0;
+static const char * __pyx_cfilenm= __FILE__;
+static const char *__pyx_filename;
+
+/* Header.proto */
+#if !defined(CYTHON_CCOMPLEX)
+ #if defined(__cplusplus)
+ #define CYTHON_CCOMPLEX 1
+ #elif defined(_Complex_I)
+ #define CYTHON_CCOMPLEX 1
+ #else
+ #define CYTHON_CCOMPLEX 0
+ #endif
+#endif
+#if CYTHON_CCOMPLEX
+ #ifdef __cplusplus
+ #include
+ #else
+ #include
+ #endif
+#endif
+#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__)
+ #undef _Complex_I
+ #define _Complex_I 1.0fj
+#endif
+
+
+static const char *__pyx_f[] = {
+ "matcha/utils/monotonic_align/core.pyx",
+ "__init__.pxd",
+ "stringsource",
+ "type.pxd",
+};
+/* NoFastGil.proto */
+#define __Pyx_PyGILState_Ensure PyGILState_Ensure
+#define __Pyx_PyGILState_Release PyGILState_Release
+#define __Pyx_FastGIL_Remember()
+#define __Pyx_FastGIL_Forget()
+#define __Pyx_FastGilFuncInit()
+
+/* MemviewSliceStruct.proto */
+struct __pyx_memoryview_obj;
+typedef struct {
+ struct __pyx_memoryview_obj *memview;
+ char *data;
+ Py_ssize_t shape[8];
+ Py_ssize_t strides[8];
+ Py_ssize_t suboffsets[8];
+} __Pyx_memviewslice;
+#define __Pyx_MemoryView_Len(m) (m.shape[0])
+
+/* Atomics.proto */
+#include
+#ifndef CYTHON_ATOMICS
+ #define CYTHON_ATOMICS 1
+#endif
+#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS
+#define __pyx_atomic_int_type int
+#if CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\
+ (__GNUC_MINOR__ > 1 ||\
+ (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2))))
+ #define __pyx_atomic_incr_aligned(value) __sync_fetch_and_add(value, 1)
+ #define __pyx_atomic_decr_aligned(value) __sync_fetch_and_sub(value, 1)
+ #ifdef __PYX_DEBUG_ATOMICS
+ #warning "Using GNU atomics"
+ #endif
+#elif CYTHON_ATOMICS && defined(_MSC_VER) && CYTHON_COMPILING_IN_NOGIL
+ #include
+ #undef __pyx_atomic_int_type
+ #define __pyx_atomic_int_type long
+ #pragma intrinsic (_InterlockedExchangeAdd)
+ #define __pyx_atomic_incr_aligned(value) _InterlockedExchangeAdd(value, 1)
+ #define __pyx_atomic_decr_aligned(value) _InterlockedExchangeAdd(value, -1)
+ #ifdef __PYX_DEBUG_ATOMICS
+ #pragma message ("Using MSVC atomics")
+ #endif
+#else
+ #undef CYTHON_ATOMICS
+ #define CYTHON_ATOMICS 0
+ #ifdef __PYX_DEBUG_ATOMICS
+ #warning "Not using atomics"
+ #endif
+#endif
+typedef volatile __pyx_atomic_int_type __pyx_atomic_int;
+#if CYTHON_ATOMICS
+ #define __pyx_add_acquisition_count(memview)\
+ __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview))
+ #define __pyx_sub_acquisition_count(memview)\
+ __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview))
+#else
+ #define __pyx_add_acquisition_count(memview)\
+ __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock)
+ #define __pyx_sub_acquisition_count(memview)\
+ __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock)
+#endif
+
+/* ForceInitThreads.proto */
+#ifndef __PYX_FORCE_INIT_THREADS
+ #define __PYX_FORCE_INIT_THREADS 0
+#endif
+
+/* BufferFormatStructs.proto */
+#define IS_UNSIGNED(type) (((type) -1) > 0)
+struct __Pyx_StructField_;
+#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0)
+typedef struct {
+ const char* name;
+ struct __Pyx_StructField_* fields;
+ size_t size;
+ size_t arraysize[8];
+ int ndim;
+ char typegroup;
+ char is_unsigned;
+ int flags;
+} __Pyx_TypeInfo;
+typedef struct __Pyx_StructField_ {
+ __Pyx_TypeInfo* type;
+ const char* name;
+ size_t offset;
+} __Pyx_StructField;
+typedef struct {
+ __Pyx_StructField* field;
+ size_t parent_offset;
+} __Pyx_BufFmt_StackElem;
+typedef struct {
+ __Pyx_StructField root;
+ __Pyx_BufFmt_StackElem* head;
+ size_t fmt_offset;
+ size_t new_count, enc_count;
+ size_t struct_alignment;
+ int is_complex;
+ char enc_type;
+ char new_packmode;
+ char enc_packmode;
+ char is_valid_array;
+} __Pyx_BufFmt_Context;
+
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":689
+ * # in Cython to enable them only on the right systems.
+ *
+ * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<<
+ * ctypedef npy_int16 int16_t
+ * ctypedef npy_int32 int32_t
+ */
+typedef npy_int8 __pyx_t_5numpy_int8_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":690
+ *
+ * ctypedef npy_int8 int8_t
+ * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<<
+ * ctypedef npy_int32 int32_t
+ * ctypedef npy_int64 int64_t
+ */
+typedef npy_int16 __pyx_t_5numpy_int16_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":691
+ * ctypedef npy_int8 int8_t
+ * ctypedef npy_int16 int16_t
+ * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<<
+ * ctypedef npy_int64 int64_t
+ * #ctypedef npy_int96 int96_t
+ */
+typedef npy_int32 __pyx_t_5numpy_int32_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":692
+ * ctypedef npy_int16 int16_t
+ * ctypedef npy_int32 int32_t
+ * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<<
+ * #ctypedef npy_int96 int96_t
+ * #ctypedef npy_int128 int128_t
+ */
+typedef npy_int64 __pyx_t_5numpy_int64_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":696
+ * #ctypedef npy_int128 int128_t
+ *
+ * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<<
+ * ctypedef npy_uint16 uint16_t
+ * ctypedef npy_uint32 uint32_t
+ */
+typedef npy_uint8 __pyx_t_5numpy_uint8_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":697
+ *
+ * ctypedef npy_uint8 uint8_t
+ * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<<
+ * ctypedef npy_uint32 uint32_t
+ * ctypedef npy_uint64 uint64_t
+ */
+typedef npy_uint16 __pyx_t_5numpy_uint16_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":698
+ * ctypedef npy_uint8 uint8_t
+ * ctypedef npy_uint16 uint16_t
+ * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<<
+ * ctypedef npy_uint64 uint64_t
+ * #ctypedef npy_uint96 uint96_t
+ */
+typedef npy_uint32 __pyx_t_5numpy_uint32_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":699
+ * ctypedef npy_uint16 uint16_t
+ * ctypedef npy_uint32 uint32_t
+ * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<<
+ * #ctypedef npy_uint96 uint96_t
+ * #ctypedef npy_uint128 uint128_t
+ */
+typedef npy_uint64 __pyx_t_5numpy_uint64_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":703
+ * #ctypedef npy_uint128 uint128_t
+ *
+ * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<<
+ * ctypedef npy_float64 float64_t
+ * #ctypedef npy_float80 float80_t
+ */
+typedef npy_float32 __pyx_t_5numpy_float32_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":704
+ *
+ * ctypedef npy_float32 float32_t
+ * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<<
+ * #ctypedef npy_float80 float80_t
+ * #ctypedef npy_float128 float128_t
+ */
+typedef npy_float64 __pyx_t_5numpy_float64_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":713
+ * # The int types are mapped a bit surprising --
+ * # numpy.int corresponds to 'l' and numpy.long to 'q'
+ * ctypedef npy_long int_t # <<<<<<<<<<<<<<
+ * ctypedef npy_longlong long_t
+ * ctypedef npy_longlong longlong_t
+ */
+typedef npy_long __pyx_t_5numpy_int_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":714
+ * # numpy.int corresponds to 'l' and numpy.long to 'q'
+ * ctypedef npy_long int_t
+ * ctypedef npy_longlong long_t # <<<<<<<<<<<<<<
+ * ctypedef npy_longlong longlong_t
+ *
+ */
+typedef npy_longlong __pyx_t_5numpy_long_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":715
+ * ctypedef npy_long int_t
+ * ctypedef npy_longlong long_t
+ * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<<
+ *
+ * ctypedef npy_ulong uint_t
+ */
+typedef npy_longlong __pyx_t_5numpy_longlong_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":717
+ * ctypedef npy_longlong longlong_t
+ *
+ * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<<
+ * ctypedef npy_ulonglong ulong_t
+ * ctypedef npy_ulonglong ulonglong_t
+ */
+typedef npy_ulong __pyx_t_5numpy_uint_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":718
+ *
+ * ctypedef npy_ulong uint_t
+ * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<<
+ * ctypedef npy_ulonglong ulonglong_t
+ *
+ */
+typedef npy_ulonglong __pyx_t_5numpy_ulong_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":719
+ * ctypedef npy_ulong uint_t
+ * ctypedef npy_ulonglong ulong_t
+ * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<<
+ *
+ * ctypedef npy_intp intp_t
+ */
+typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":721
+ * ctypedef npy_ulonglong ulonglong_t
+ *
+ * ctypedef npy_intp intp_t # <<<<<<<<<<<<<<
+ * ctypedef npy_uintp uintp_t
+ *
+ */
+typedef npy_intp __pyx_t_5numpy_intp_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":722
+ *
+ * ctypedef npy_intp intp_t
+ * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<<
+ *
+ * ctypedef npy_double float_t
+ */
+typedef npy_uintp __pyx_t_5numpy_uintp_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":724
+ * ctypedef npy_uintp uintp_t
+ *
+ * ctypedef npy_double float_t # <<<<<<<<<<<<<<
+ * ctypedef npy_double double_t
+ * ctypedef npy_longdouble longdouble_t
+ */
+typedef npy_double __pyx_t_5numpy_float_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":725
+ *
+ * ctypedef npy_double float_t
+ * ctypedef npy_double double_t # <<<<<<<<<<<<<<
+ * ctypedef npy_longdouble longdouble_t
+ *
+ */
+typedef npy_double __pyx_t_5numpy_double_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":726
+ * ctypedef npy_double float_t
+ * ctypedef npy_double double_t
+ * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<<
+ *
+ * ctypedef npy_cfloat cfloat_t
+ */
+typedef npy_longdouble __pyx_t_5numpy_longdouble_t;
+/* Declarations.proto */
+#if CYTHON_CCOMPLEX
+ #ifdef __cplusplus
+ typedef ::std::complex< float > __pyx_t_float_complex;
+ #else
+ typedef float _Complex __pyx_t_float_complex;
+ #endif
+#else
+ typedef struct { float real, imag; } __pyx_t_float_complex;
+#endif
+static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float);
+
+/* Declarations.proto */
+#if CYTHON_CCOMPLEX
+ #ifdef __cplusplus
+ typedef ::std::complex< double > __pyx_t_double_complex;
+ #else
+ typedef double _Complex __pyx_t_double_complex;
+ #endif
+#else
+ typedef struct { double real, imag; } __pyx_t_double_complex;
+#endif
+static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double);
+
+
+/*--- Type declarations ---*/
+struct __pyx_array_obj;
+struct __pyx_MemviewEnum_obj;
+struct __pyx_memoryview_obj;
+struct __pyx_memoryviewslice_obj;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":728
+ * ctypedef npy_longdouble longdouble_t
+ *
+ * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<<
+ * ctypedef npy_cdouble cdouble_t
+ * ctypedef npy_clongdouble clongdouble_t
+ */
+typedef npy_cfloat __pyx_t_5numpy_cfloat_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":729
+ *
+ * ctypedef npy_cfloat cfloat_t
+ * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<<
+ * ctypedef npy_clongdouble clongdouble_t
+ *
+ */
+typedef npy_cdouble __pyx_t_5numpy_cdouble_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":730
+ * ctypedef npy_cfloat cfloat_t
+ * ctypedef npy_cdouble cdouble_t
+ * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<<
+ *
+ * ctypedef npy_cdouble complex_t
+ */
+typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t;
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":732
+ * ctypedef npy_clongdouble clongdouble_t
+ *
+ * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<<
+ *
+ * cdef inline object PyArray_MultiIterNew1(a):
+ */
+typedef npy_cdouble __pyx_t_5numpy_complex_t;
+struct __pyx_opt_args_6matcha_5utils_15monotonic_align_4core_maximum_path_c;
+
+/* "matcha/utils/monotonic_align/core.pyx":42
+ * @cython.boundscheck(False)
+ * @cython.wraparound(False)
+ * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<<
+ * cdef int b = values.shape[0]
+ *
+ */
+struct __pyx_opt_args_6matcha_5utils_15monotonic_align_4core_maximum_path_c {
+ int __pyx_n;
+ float max_neg_val;
+};
+
+/* "View.MemoryView":106
+ *
+ * @cname("__pyx_array")
+ * cdef class array: # <<<<<<<<<<<<<<
+ *
+ * cdef:
+ */
+struct __pyx_array_obj {
+ PyObject_HEAD
+ struct __pyx_vtabstruct_array *__pyx_vtab;
+ char *data;
+ Py_ssize_t len;
+ char *format;
+ int ndim;
+ Py_ssize_t *_shape;
+ Py_ssize_t *_strides;
+ Py_ssize_t itemsize;
+ PyObject *mode;
+ PyObject *_format;
+ void (*callback_free_data)(void *);
+ int free_data;
+ int dtype_is_object;
+};
+
+
+/* "View.MemoryView":280
+ *
+ * @cname('__pyx_MemviewEnum')
+ * cdef class Enum(object): # <<<<<<<<<<<<<<
+ * cdef object name
+ * def __init__(self, name):
+ */
+struct __pyx_MemviewEnum_obj {
+ PyObject_HEAD
+ PyObject *name;
+};
+
+
+/* "View.MemoryView":331
+ *
+ * @cname('__pyx_memoryview')
+ * cdef class memoryview(object): # <<<<<<<<<<<<<<
+ *
+ * cdef object obj
+ */
+struct __pyx_memoryview_obj {
+ PyObject_HEAD
+ struct __pyx_vtabstruct_memoryview *__pyx_vtab;
+ PyObject *obj;
+ PyObject *_size;
+ PyObject *_array_interface;
+ PyThread_type_lock lock;
+ __pyx_atomic_int acquisition_count[2];
+ __pyx_atomic_int *acquisition_count_aligned_p;
+ Py_buffer view;
+ int flags;
+ int dtype_is_object;
+ __Pyx_TypeInfo *typeinfo;
+};
+
+
+/* "View.MemoryView":967
+ *
+ * @cname('__pyx_memoryviewslice')
+ * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<<
+ * "Internal class for passing memoryview slices to Python"
+ *
+ */
+struct __pyx_memoryviewslice_obj {
+ struct __pyx_memoryview_obj __pyx_base;
+ __Pyx_memviewslice from_slice;
+ PyObject *from_object;
+ PyObject *(*to_object_func)(char *);
+ int (*to_dtype_func)(char *, PyObject *);
+};
+
+
+
+/* "View.MemoryView":106
+ *
+ * @cname("__pyx_array")
+ * cdef class array: # <<<<<<<<<<<<<<
+ *
+ * cdef:
+ */
+
+struct __pyx_vtabstruct_array {
+ PyObject *(*get_memview)(struct __pyx_array_obj *);
+};
+static struct __pyx_vtabstruct_array *__pyx_vtabptr_array;
+
+
+/* "View.MemoryView":331
+ *
+ * @cname('__pyx_memoryview')
+ * cdef class memoryview(object): # <<<<<<<<<<<<<<
+ *
+ * cdef object obj
+ */
+
+struct __pyx_vtabstruct_memoryview {
+ char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *);
+ PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *);
+ PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *);
+ PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *);
+ PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *);
+ PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *);
+ PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *);
+};
+static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview;
+
+
+/* "View.MemoryView":967
+ *
+ * @cname('__pyx_memoryviewslice')
+ * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<<
+ * "Internal class for passing memoryview slices to Python"
+ *
+ */
+
+struct __pyx_vtabstruct__memoryviewslice {
+ struct __pyx_vtabstruct_memoryview __pyx_base;
+};
+static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice;
+
+/* --- Runtime support code (head) --- */
+/* Refnanny.proto */
+#ifndef CYTHON_REFNANNY
+ #define CYTHON_REFNANNY 0
+#endif
+#if CYTHON_REFNANNY
+ typedef struct {
+ void (*INCREF)(void*, PyObject*, int);
+ void (*DECREF)(void*, PyObject*, int);
+ void (*GOTREF)(void*, PyObject*, int);
+ void (*GIVEREF)(void*, PyObject*, int);
+ void* (*SetupContext)(const char*, int, const char*);
+ void (*FinishContext)(void**);
+ } __Pyx_RefNannyAPIStruct;
+ static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL;
+ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname);
+ #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL;
+#ifdef WITH_THREAD
+ #define __Pyx_RefNannySetupContext(name, acquire_gil)\
+ if (acquire_gil) {\
+ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\
+ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
+ PyGILState_Release(__pyx_gilstate_save);\
+ } else {\
+ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\
+ }
+#else
+ #define __Pyx_RefNannySetupContext(name, acquire_gil)\
+ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
+#endif
+ #define __Pyx_RefNannyFinishContext()\
+ __Pyx_RefNanny->FinishContext(&__pyx_refnanny)
+ #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
+ #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
+ #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
+ #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
+ #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0)
+ #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0)
+ #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0)
+ #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0)
+#else
+ #define __Pyx_RefNannyDeclarations
+ #define __Pyx_RefNannySetupContext(name, acquire_gil)
+ #define __Pyx_RefNannyFinishContext()
+ #define __Pyx_INCREF(r) Py_INCREF(r)
+ #define __Pyx_DECREF(r) Py_DECREF(r)
+ #define __Pyx_GOTREF(r)
+ #define __Pyx_GIVEREF(r)
+ #define __Pyx_XINCREF(r) Py_XINCREF(r)
+ #define __Pyx_XDECREF(r) Py_XDECREF(r)
+ #define __Pyx_XGOTREF(r)
+ #define __Pyx_XGIVEREF(r)
+#endif
+#define __Pyx_XDECREF_SET(r, v) do {\
+ PyObject *tmp = (PyObject *) r;\
+ r = v; __Pyx_XDECREF(tmp);\
+ } while (0)
+#define __Pyx_DECREF_SET(r, v) do {\
+ PyObject *tmp = (PyObject *) r;\
+ r = v; __Pyx_DECREF(tmp);\
+ } while (0)
+#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0)
+#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0)
+
+/* PyObjectGetAttrStr.proto */
+#if CYTHON_USE_TYPE_SLOTS
+static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name);
+#else
+#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n)
+#endif
+
+/* GetBuiltinName.proto */
+static PyObject *__Pyx_GetBuiltinName(PyObject *name);
+
+/* MemviewSliceInit.proto */
+#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d
+#define __Pyx_MEMVIEW_DIRECT 1
+#define __Pyx_MEMVIEW_PTR 2
+#define __Pyx_MEMVIEW_FULL 4
+#define __Pyx_MEMVIEW_CONTIG 8
+#define __Pyx_MEMVIEW_STRIDED 16
+#define __Pyx_MEMVIEW_FOLLOW 32
+#define __Pyx_IS_C_CONTIG 1
+#define __Pyx_IS_F_CONTIG 2
+static int __Pyx_init_memviewslice(
+ struct __pyx_memoryview_obj *memview,
+ int ndim,
+ __Pyx_memviewslice *memviewslice,
+ int memview_is_new_reference);
+static CYTHON_INLINE int __pyx_add_acquisition_count_locked(
+ __pyx_atomic_int *acquisition_count, PyThread_type_lock lock);
+static CYTHON_INLINE int __pyx_sub_acquisition_count_locked(
+ __pyx_atomic_int *acquisition_count, PyThread_type_lock lock);
+#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p)
+#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview))
+#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__)
+#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__)
+static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int);
+static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int);
+
+/* RaiseArgTupleInvalid.proto */
+static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
+ Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found);
+
+/* RaiseDoubleKeywords.proto */
+static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name);
+
+/* ParseKeywords.proto */
+static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\
+ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\
+ const char* function_name);
+
+/* None.proto */
+static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname);
+
+/* GetTopmostException.proto */
+#if CYTHON_USE_EXC_INFO_STACK
+static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate);
+#endif
+
+/* PyThreadStateGet.proto */
+#if CYTHON_FAST_THREAD_STATE
+#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate;
+#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current;
+#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type
+#else
+#define __Pyx_PyThreadState_declare
+#define __Pyx_PyThreadState_assign
+#define __Pyx_PyErr_Occurred() PyErr_Occurred()
+#endif
+
+/* SaveResetException.proto */
+#if CYTHON_FAST_THREAD_STATE
+#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb)
+static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
+#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb)
+static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb);
+#else
+#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb)
+#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb)
+#endif
+
+/* PyErrExceptionMatches.proto */
+#if CYTHON_FAST_THREAD_STATE
+#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err)
+static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err);
+#else
+#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err)
+#endif
+
+/* GetException.proto */
+#if CYTHON_FAST_THREAD_STATE
+#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb)
+static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
+#else
+static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb);
+#endif
+
+/* PyObjectCall.proto */
+#if CYTHON_COMPILING_IN_CPYTHON
+static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw);
+#else
+#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw)
+#endif
+
+/* PyErrFetchRestore.proto */
+#if CYTHON_FAST_THREAD_STATE
+#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL)
+#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb)
+#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb)
+#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb)
+#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb)
+static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb);
+static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
+#if CYTHON_COMPILING_IN_CPYTHON
+#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL))
+#else
+#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc)
+#endif
+#else
+#define __Pyx_PyErr_Clear() PyErr_Clear()
+#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc)
+#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb)
+#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb)
+#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb)
+#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb)
+#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb)
+#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb)
+#endif
+
+/* RaiseException.proto */
+static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause);
+
+/* ArgTypeTest.proto */
+#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\
+ ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\
+ __Pyx__ArgTypeTest(obj, type, name, exact))
+static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact);
+
+/* PyCFunctionFastCall.proto */
+#if CYTHON_FAST_PYCCALL
+static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs);
+#else
+#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL)
+#endif
+
+/* PyFunctionFastCall.proto */
+#if CYTHON_FAST_PYCALL
+#define __Pyx_PyFunction_FastCall(func, args, nargs)\
+ __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL)
+#if 1 || PY_VERSION_HEX < 0x030600B1
+static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs);
+#else
+#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs)
+#endif
+#define __Pyx_BUILD_ASSERT_EXPR(cond)\
+ (sizeof(char [1 - 2*!(cond)]) - 1)
+#ifndef Py_MEMBER_SIZE
+#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member)
+#endif
+#if CYTHON_FAST_PYCALL
+ static size_t __pyx_pyframe_localsplus_offset = 0;
+ #include "frameobject.h"
+#if PY_VERSION_HEX >= 0x030b00a6
+ #ifndef Py_BUILD_CORE
+ #define Py_BUILD_CORE 1
+ #endif
+ #include "internal/pycore_frame.h"
+#endif
+ #define __Pxy_PyFrame_Initialize_Offsets()\
+ ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\
+ (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus)))
+ #define __Pyx_PyFrame_GetLocalsplus(frame)\
+ (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset))
+#endif // CYTHON_FAST_PYCALL
+#endif
+
+/* PyObjectCall2Args.proto */
+static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2);
+
+/* PyObjectCallMethO.proto */
+#if CYTHON_COMPILING_IN_CPYTHON
+static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg);
+#endif
+
+/* PyObjectCallOneArg.proto */
+static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg);
+
+/* IncludeStringH.proto */
+#include
+
+/* BytesEquals.proto */
+static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals);
+
+/* UnicodeEquals.proto */
+static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals);
+
+/* StrEquals.proto */
+#if PY_MAJOR_VERSION >= 3
+#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals
+#else
+#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals
+#endif
+
+/* DivInt[Py_ssize_t].proto */
+static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t);
+
+/* UnaryNegOverflows.proto */
+#define UNARY_NEG_WOULD_OVERFLOW(x)\
+ (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x)))
+
+static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/
+static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *); /*proto*/
+/* GetAttr.proto */
+static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *);
+
+/* GetItemInt.proto */
+#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\
+ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\
+ __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\
+ (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\
+ __Pyx_GetItemInt_Generic(o, to_py_func(i))))
+#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\
+ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\
+ __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\
+ (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL))
+static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i,
+ int wraparound, int boundscheck);
+#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\
+ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\
+ __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\
+ (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL))
+static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i,
+ int wraparound, int boundscheck);
+static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j);
+static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i,
+ int is_list, int wraparound, int boundscheck);
+
+/* ObjectGetItem.proto */
+#if CYTHON_USE_TYPE_SLOTS
+static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key);
+#else
+#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key)
+#endif
+
+/* decode_c_string_utf16.proto */
+static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) {
+ int byteorder = 0;
+ return PyUnicode_DecodeUTF16(s, size, errors, &byteorder);
+}
+static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) {
+ int byteorder = -1;
+ return PyUnicode_DecodeUTF16(s, size, errors, &byteorder);
+}
+static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) {
+ int byteorder = 1;
+ return PyUnicode_DecodeUTF16(s, size, errors, &byteorder);
+}
+
+/* decode_c_string.proto */
+static CYTHON_INLINE PyObject* __Pyx_decode_c_string(
+ const char* cstring, Py_ssize_t start, Py_ssize_t stop,
+ const char* encoding, const char* errors,
+ PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors));
+
+/* GetAttr3.proto */
+static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *);
+
+/* PyDictVersioning.proto */
+#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS
+#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1)
+#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag)
+#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\
+ (version_var) = __PYX_GET_DICT_VERSION(dict);\
+ (cache_var) = (value);
+#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\
+ static PY_UINT64_T __pyx_dict_version = 0;\
+ static PyObject *__pyx_dict_cached_value = NULL;\
+ if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\
+ (VAR) = __pyx_dict_cached_value;\
+ } else {\
+ (VAR) = __pyx_dict_cached_value = (LOOKUP);\
+ __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\
+ }\
+}
+static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj);
+static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj);
+static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version);
+#else
+#define __PYX_GET_DICT_VERSION(dict) (0)
+#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)
+#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP);
+#endif
+
+/* GetModuleGlobalName.proto */
+#if CYTHON_USE_DICT_VERSIONS
+#define __Pyx_GetModuleGlobalName(var, name) do {\
+ static PY_UINT64_T __pyx_dict_version = 0;\
+ static PyObject *__pyx_dict_cached_value = NULL;\
+ (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\
+ (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\
+ __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\
+} while(0)
+#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\
+ PY_UINT64_T __pyx_dict_version;\
+ PyObject *__pyx_dict_cached_value;\
+ (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\
+} while(0)
+static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value);
+#else
+#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name)
+#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name)
+static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name);
+#endif
+
+/* RaiseTooManyValuesToUnpack.proto */
+static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected);
+
+/* RaiseNeedMoreValuesToUnpack.proto */
+static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index);
+
+/* RaiseNoneIterError.proto */
+static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void);
+
+/* ExtTypeTest.proto */
+static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type);
+
+/* SwapException.proto */
+#if CYTHON_FAST_THREAD_STATE
+#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb)
+static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb);
+#else
+static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb);
+#endif
+
+/* Import.proto */
+static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level);
+
+/* FastTypeChecks.proto */
+#if CYTHON_COMPILING_IN_CPYTHON
+#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type)
+static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b);
+static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type);
+static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2);
+#else
+#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type)
+#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type)
+#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2))
+#endif
+#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception)
+
+static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/
+/* ListCompAppend.proto */
+#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
+static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) {
+ PyListObject* L = (PyListObject*) list;
+ Py_ssize_t len = Py_SIZE(list);
+ if (likely(L->allocated > len)) {
+ Py_INCREF(x);
+ PyList_SET_ITEM(list, len, x);
+ __Pyx_SET_SIZE(list, len + 1);
+ return 0;
+ }
+ return PyList_Append(list, x);
+}
+#else
+#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x)
+#endif
+
+/* PyIntBinop.proto */
+#if !CYTHON_COMPILING_IN_PYPY
+static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check);
+#else
+#define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\
+ (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2))
+#endif
+
+/* ListExtend.proto */
+static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) {
+#if CYTHON_COMPILING_IN_CPYTHON
+ PyObject* none = _PyList_Extend((PyListObject*)L, v);
+ if (unlikely(!none))
+ return -1;
+ Py_DECREF(none);
+ return 0;
+#else
+ return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v);
+#endif
+}
+
+/* ListAppend.proto */
+#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS
+static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) {
+ PyListObject* L = (PyListObject*) list;
+ Py_ssize_t len = Py_SIZE(list);
+ if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) {
+ Py_INCREF(x);
+ PyList_SET_ITEM(list, len, x);
+ __Pyx_SET_SIZE(list, len + 1);
+ return 0;
+ }
+ return PyList_Append(list, x);
+}
+#else
+#define __Pyx_PyList_Append(L,x) PyList_Append(L,x)
+#endif
+
+/* DivInt[long].proto */
+static CYTHON_INLINE long __Pyx_div_long(long, long);
+
+/* PySequenceContains.proto */
+static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) {
+ int result = PySequence_Contains(seq, item);
+ return unlikely(result < 0) ? result : (result == (eq == Py_EQ));
+}
+
+/* ImportFrom.proto */
+static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name);
+
+/* HasAttr.proto */
+static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *);
+
+/* PyObject_GenericGetAttrNoDict.proto */
+#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000
+static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name);
+#else
+#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr
+#endif
+
+/* PyObject_GenericGetAttr.proto */
+#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000
+static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name);
+#else
+#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr
+#endif
+
+/* SetVTable.proto */
+static int __Pyx_SetVtable(PyObject *dict, void *vtable);
+
+/* PyObjectGetAttrStrNoError.proto */
+static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name);
+
+/* SetupReduce.proto */
+static int __Pyx_setup_reduce(PyObject* type_obj);
+
+/* TypeImport.proto */
+#ifndef __PYX_HAVE_RT_ImportType_proto_0_29_35
+#define __PYX_HAVE_RT_ImportType_proto_0_29_35
+#if __STDC_VERSION__ >= 201112L
+#include
+#endif
+#if __STDC_VERSION__ >= 201112L || __cplusplus >= 201103L
+#define __PYX_GET_STRUCT_ALIGNMENT_0_29_35(s) alignof(s)
+#else
+#define __PYX_GET_STRUCT_ALIGNMENT_0_29_35(s) sizeof(void*)
+#endif
+enum __Pyx_ImportType_CheckSize_0_29_35 {
+ __Pyx_ImportType_CheckSize_Error_0_29_35 = 0,
+ __Pyx_ImportType_CheckSize_Warn_0_29_35 = 1,
+ __Pyx_ImportType_CheckSize_Ignore_0_29_35 = 2
+};
+static PyTypeObject *__Pyx_ImportType_0_29_35(PyObject* module, const char *module_name, const char *class_name, size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_0_29_35 check_size);
+#endif
+
+/* CLineInTraceback.proto */
+#ifdef CYTHON_CLINE_IN_TRACEBACK
+#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0)
+#else
+static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line);
+#endif
+
+/* CodeObjectCache.proto */
+typedef struct {
+ PyCodeObject* code_object;
+ int code_line;
+} __Pyx_CodeObjectCacheEntry;
+struct __Pyx_CodeObjectCache {
+ int count;
+ int max_count;
+ __Pyx_CodeObjectCacheEntry* entries;
+};
+static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL};
+static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line);
+static PyCodeObject *__pyx_find_code_object(int code_line);
+static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object);
+
+/* AddTraceback.proto */
+static void __Pyx_AddTraceback(const char *funcname, int c_line,
+ int py_line, const char *filename);
+
+#if PY_MAJOR_VERSION < 3
+ static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags);
+ static void __Pyx_ReleaseBuffer(Py_buffer *view);
+#else
+ #define __Pyx_GetBuffer PyObject_GetBuffer
+ #define __Pyx_ReleaseBuffer PyBuffer_Release
+#endif
+
+
+/* BufferStructDeclare.proto */
+typedef struct {
+ Py_ssize_t shape, strides, suboffsets;
+} __Pyx_Buf_DimInfo;
+typedef struct {
+ size_t refcount;
+ Py_buffer pybuffer;
+} __Pyx_Buffer;
+typedef struct {
+ __Pyx_Buffer *rcbuffer;
+ char *data;
+ __Pyx_Buf_DimInfo diminfo[8];
+} __Pyx_LocalBuf_ND;
+
+/* MemviewSliceIsContig.proto */
+static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim);
+
+/* OverlappingSlices.proto */
+static int __pyx_slices_overlap(__Pyx_memviewslice *slice1,
+ __Pyx_memviewslice *slice2,
+ int ndim, size_t itemsize);
+
+/* Capsule.proto */
+static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig);
+
+/* IsLittleEndian.proto */
+static CYTHON_INLINE int __Pyx_Is_Little_Endian(void);
+
+/* BufferFormatCheck.proto */
+static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts);
+static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx,
+ __Pyx_BufFmt_StackElem* stack,
+ __Pyx_TypeInfo* type);
+
+/* TypeInfoCompare.proto */
+static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b);
+
+/* MemviewSliceValidateAndInit.proto */
+static int __Pyx_ValidateAndInit_memviewslice(
+ int *axes_specs,
+ int c_or_f_flag,
+ int buf_flags,
+ int ndim,
+ __Pyx_TypeInfo *dtype,
+ __Pyx_BufFmt_StackElem stack[],
+ __Pyx_memviewslice *memviewslice,
+ PyObject *original_obj);
+
+/* ObjectToMemviewSlice.proto */
+static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(PyObject *, int writable_flag);
+
+/* ObjectToMemviewSlice.proto */
+static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(PyObject *, int writable_flag);
+
+/* ObjectToMemviewSlice.proto */
+static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_int(PyObject *, int writable_flag);
+
+/* GCCDiagnostics.proto */
+#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
+#define __Pyx_HAS_GCC_DIAGNOSTIC
+#endif
+
+/* RealImag.proto */
+#if CYTHON_CCOMPLEX
+ #ifdef __cplusplus
+ #define __Pyx_CREAL(z) ((z).real())
+ #define __Pyx_CIMAG(z) ((z).imag())
+ #else
+ #define __Pyx_CREAL(z) (__real__(z))
+ #define __Pyx_CIMAG(z) (__imag__(z))
+ #endif
+#else
+ #define __Pyx_CREAL(z) ((z).real)
+ #define __Pyx_CIMAG(z) ((z).imag)
+#endif
+#if defined(__cplusplus) && CYTHON_CCOMPLEX\
+ && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103)
+ #define __Pyx_SET_CREAL(z,x) ((z).real(x))
+ #define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
+#else
+ #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
+ #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
+#endif
+
+/* Arithmetic.proto */
+#if CYTHON_CCOMPLEX
+ #define __Pyx_c_eq_float(a, b) ((a)==(b))
+ #define __Pyx_c_sum_float(a, b) ((a)+(b))
+ #define __Pyx_c_diff_float(a, b) ((a)-(b))
+ #define __Pyx_c_prod_float(a, b) ((a)*(b))
+ #define __Pyx_c_quot_float(a, b) ((a)/(b))
+ #define __Pyx_c_neg_float(a) (-(a))
+ #ifdef __cplusplus
+ #define __Pyx_c_is_zero_float(z) ((z)==(float)0)
+ #define __Pyx_c_conj_float(z) (::std::conj(z))
+ #if 1
+ #define __Pyx_c_abs_float(z) (::std::abs(z))
+ #define __Pyx_c_pow_float(a, b) (::std::pow(a, b))
+ #endif
+ #else
+ #define __Pyx_c_is_zero_float(z) ((z)==0)
+ #define __Pyx_c_conj_float(z) (conjf(z))
+ #if 1
+ #define __Pyx_c_abs_float(z) (cabsf(z))
+ #define __Pyx_c_pow_float(a, b) (cpowf(a, b))
+ #endif
+ #endif
+#else
+ static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex);
+ static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex);
+ static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex);
+ static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex);
+ static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex);
+ static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex);
+ static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex);
+ static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex);
+ #if 1
+ static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex);
+ static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex);
+ #endif
+#endif
+
+/* Arithmetic.proto */
+#if CYTHON_CCOMPLEX
+ #define __Pyx_c_eq_double(a, b) ((a)==(b))
+ #define __Pyx_c_sum_double(a, b) ((a)+(b))
+ #define __Pyx_c_diff_double(a, b) ((a)-(b))
+ #define __Pyx_c_prod_double(a, b) ((a)*(b))
+ #define __Pyx_c_quot_double(a, b) ((a)/(b))
+ #define __Pyx_c_neg_double(a) (-(a))
+ #ifdef __cplusplus
+ #define __Pyx_c_is_zero_double(z) ((z)==(double)0)
+ #define __Pyx_c_conj_double(z) (::std::conj(z))
+ #if 1
+ #define __Pyx_c_abs_double(z) (::std::abs(z))
+ #define __Pyx_c_pow_double(a, b) (::std::pow(a, b))
+ #endif
+ #else
+ #define __Pyx_c_is_zero_double(z) ((z)==0)
+ #define __Pyx_c_conj_double(z) (conj(z))
+ #if 1
+ #define __Pyx_c_abs_double(z) (cabs(z))
+ #define __Pyx_c_pow_double(a, b) (cpow(a, b))
+ #endif
+ #endif
+#else
+ static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex);
+ static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex);
+ static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex);
+ static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex);
+ static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex);
+ static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex);
+ static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex);
+ static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex);
+ #if 1
+ static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex);
+ static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex);
+ #endif
+#endif
+
+/* MemviewSliceCopyTemplate.proto */
+static __Pyx_memviewslice
+__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs,
+ const char *mode, int ndim,
+ size_t sizeof_dtype, int contig_flag,
+ int dtype_is_object);
+
+/* CIntToPy.proto */
+static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value);
+
+/* CIntFromPy.proto */
+static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *);
+
+/* CIntToPy.proto */
+static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value);
+
+/* CIntFromPy.proto */
+static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *);
+
+/* CIntFromPy.proto */
+static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *);
+
+/* CheckBinaryVersion.proto */
+static int __Pyx_check_binary_version(void);
+
+/* InitStrings.proto */
+static int __Pyx_InitStrings(__Pyx_StringTabEntry *t);
+
+static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self); /* proto*/
+static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/
+static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/
+static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/
+static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/
+static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/
+static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/
+static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/
+static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/
+static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/
+
+/* Module declarations from 'cython.view' */
+
+/* Module declarations from 'cython' */
+
+/* Module declarations from 'cpython.buffer' */
+
+/* Module declarations from 'libc.string' */
+
+/* Module declarations from 'libc.stdio' */
+
+/* Module declarations from '__builtin__' */
+
+/* Module declarations from 'cpython.type' */
+static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0;
+
+/* Module declarations from 'cpython' */
+
+/* Module declarations from 'cpython.object' */
+
+/* Module declarations from 'cpython.ref' */
+
+/* Module declarations from 'cpython.mem' */
+
+/* Module declarations from 'numpy' */
+
+/* Module declarations from 'numpy' */
+static PyTypeObject *__pyx_ptype_5numpy_dtype = 0;
+static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0;
+static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0;
+static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0;
+static PyTypeObject *__pyx_ptype_5numpy_generic = 0;
+static PyTypeObject *__pyx_ptype_5numpy_number = 0;
+static PyTypeObject *__pyx_ptype_5numpy_integer = 0;
+static PyTypeObject *__pyx_ptype_5numpy_signedinteger = 0;
+static PyTypeObject *__pyx_ptype_5numpy_unsignedinteger = 0;
+static PyTypeObject *__pyx_ptype_5numpy_inexact = 0;
+static PyTypeObject *__pyx_ptype_5numpy_floating = 0;
+static PyTypeObject *__pyx_ptype_5numpy_complexfloating = 0;
+static PyTypeObject *__pyx_ptype_5numpy_flexible = 0;
+static PyTypeObject *__pyx_ptype_5numpy_character = 0;
+static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0;
+
+/* Module declarations from 'matcha.utils.monotonic_align.core' */
+static PyTypeObject *__pyx_array_type = 0;
+static PyTypeObject *__pyx_MemviewEnum_type = 0;
+static PyTypeObject *__pyx_memoryview_type = 0;
+static PyTypeObject *__pyx_memoryviewslice_type = 0;
+static PyObject *generic = 0;
+static PyObject *strided = 0;
+static PyObject *indirect = 0;
+static PyObject *contiguous = 0;
+static PyObject *indirect_contiguous = 0;
+static int __pyx_memoryview_thread_locks_used;
+static PyThread_type_lock __pyx_memoryview_thread_locks[8];
+static void __pyx_f_6matcha_5utils_15monotonic_align_4core_maximum_path_each(__Pyx_memviewslice, __Pyx_memviewslice, int, int, float); /*proto*/
+static void __pyx_f_6matcha_5utils_15monotonic_align_4core_maximum_path_c(__Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch, struct __pyx_opt_args_6matcha_5utils_15monotonic_align_4core_maximum_path_c *__pyx_optional_args); /*proto*/
+static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/
+static void *__pyx_align_pointer(void *, size_t); /*proto*/
+static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/
+static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/
+static PyObject *_unellipsify(PyObject *, int); /*proto*/
+static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/
+static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/
+static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/
+static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/
+static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/
+static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/
+static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/
+static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/
+static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/
+static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/
+static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/
+static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/
+static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/
+static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/
+static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/
+static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/
+static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/
+static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/
+static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/
+static int __pyx_memoryview_err(PyObject *, char *); /*proto*/
+static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/
+static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/
+static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/
+static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/
+static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/
+static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/
+static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/
+static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *, PyObject *); /*proto*/
+static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 };
+static __Pyx_TypeInfo __Pyx_TypeInfo_float = { "float", NULL, sizeof(float), { 0 }, 0, 'R', 0, 0 };
+#define __Pyx_MODULE_NAME "matcha.utils.monotonic_align.core"
+extern int __pyx_module_is_main_matcha__utils__monotonic_align__core;
+int __pyx_module_is_main_matcha__utils__monotonic_align__core = 0;
+
+/* Implementation of 'matcha.utils.monotonic_align.core' */
+static PyObject *__pyx_builtin_range;
+static PyObject *__pyx_builtin_ImportError;
+static PyObject *__pyx_builtin_ValueError;
+static PyObject *__pyx_builtin_MemoryError;
+static PyObject *__pyx_builtin_enumerate;
+static PyObject *__pyx_builtin_TypeError;
+static PyObject *__pyx_builtin_Ellipsis;
+static PyObject *__pyx_builtin_id;
+static PyObject *__pyx_builtin_IndexError;
+static const char __pyx_k_O[] = "O";
+static const char __pyx_k_c[] = "c";
+static const char __pyx_k_id[] = "id";
+static const char __pyx_k_np[] = "np";
+static const char __pyx_k_new[] = "__new__";
+static const char __pyx_k_obj[] = "obj";
+static const char __pyx_k_base[] = "base";
+static const char __pyx_k_dict[] = "__dict__";
+static const char __pyx_k_main[] = "__main__";
+static const char __pyx_k_mode[] = "mode";
+static const char __pyx_k_name[] = "name";
+static const char __pyx_k_ndim[] = "ndim";
+static const char __pyx_k_pack[] = "pack";
+static const char __pyx_k_size[] = "size";
+static const char __pyx_k_step[] = "step";
+static const char __pyx_k_stop[] = "stop";
+static const char __pyx_k_t_xs[] = "t_xs";
+static const char __pyx_k_t_ys[] = "t_ys";
+static const char __pyx_k_test[] = "__test__";
+static const char __pyx_k_ASCII[] = "ASCII";
+static const char __pyx_k_class[] = "__class__";
+static const char __pyx_k_error[] = "error";
+static const char __pyx_k_flags[] = "flags";
+static const char __pyx_k_numpy[] = "numpy";
+static const char __pyx_k_paths[] = "paths";
+static const char __pyx_k_range[] = "range";
+static const char __pyx_k_shape[] = "shape";
+static const char __pyx_k_start[] = "start";
+static const char __pyx_k_encode[] = "encode";
+static const char __pyx_k_format[] = "format";
+static const char __pyx_k_import[] = "__import__";
+static const char __pyx_k_name_2[] = "__name__";
+static const char __pyx_k_pickle[] = "pickle";
+static const char __pyx_k_reduce[] = "__reduce__";
+static const char __pyx_k_struct[] = "struct";
+static const char __pyx_k_unpack[] = "unpack";
+static const char __pyx_k_update[] = "update";
+static const char __pyx_k_values[] = "values";
+static const char __pyx_k_fortran[] = "fortran";
+static const char __pyx_k_memview[] = "memview";
+static const char __pyx_k_Ellipsis[] = "Ellipsis";
+static const char __pyx_k_getstate[] = "__getstate__";
+static const char __pyx_k_itemsize[] = "itemsize";
+static const char __pyx_k_pyx_type[] = "__pyx_type";
+static const char __pyx_k_setstate[] = "__setstate__";
+static const char __pyx_k_TypeError[] = "TypeError";
+static const char __pyx_k_enumerate[] = "enumerate";
+static const char __pyx_k_pyx_state[] = "__pyx_state";
+static const char __pyx_k_reduce_ex[] = "__reduce_ex__";
+static const char __pyx_k_IndexError[] = "IndexError";
+static const char __pyx_k_ValueError[] = "ValueError";
+static const char __pyx_k_pyx_result[] = "__pyx_result";
+static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__";
+static const char __pyx_k_ImportError[] = "ImportError";
+static const char __pyx_k_MemoryError[] = "MemoryError";
+static const char __pyx_k_PickleError[] = "PickleError";
+static const char __pyx_k_max_neg_val[] = "max_neg_val";
+static const char __pyx_k_pyx_checksum[] = "__pyx_checksum";
+static const char __pyx_k_stringsource[] = "stringsource";
+static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer";
+static const char __pyx_k_reduce_cython[] = "__reduce_cython__";
+static const char __pyx_k_View_MemoryView[] = "View.MemoryView";
+static const char __pyx_k_allocate_buffer[] = "allocate_buffer";
+static const char __pyx_k_dtype_is_object[] = "dtype_is_object";
+static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError";
+static const char __pyx_k_setstate_cython[] = "__setstate_cython__";
+static const char __pyx_k_pyx_unpickle_Enum[] = "__pyx_unpickle_Enum";
+static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback";
+static const char __pyx_k_strided_and_direct[] = "";
+static const char __pyx_k_strided_and_indirect[] = "";
+static const char __pyx_k_contiguous_and_direct[] = "";
+static const char __pyx_k_MemoryView_of_r_object[] = "";
+static const char __pyx_k_MemoryView_of_r_at_0x_x[] = "";
+static const char __pyx_k_contiguous_and_indirect[] = "";
+static const char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'";
+static const char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d.";
+static const char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array";
+static const char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data.";
+static const char __pyx_k_strided_and_direct_or_indirect[] = "";
+static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import";
+static const char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides";
+static const char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory.";
+static const char __pyx_k_Cannot_assign_to_read_only_memor[] = "Cannot assign to read-only memoryview";
+static const char __pyx_k_Cannot_create_writable_memory_vi[] = "Cannot create writable memory view from read-only memoryview";
+static const char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array";
+static const char __pyx_k_Incompatible_checksums_0x_x_vs_0[] = "Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))";
+static const char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported";
+static const char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s";
+static const char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)";
+static const char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object";
+static const char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)";
+static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__";
+static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import";
+static const char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides.";
+static PyObject *__pyx_n_s_ASCII;
+static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri;
+static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is;
+static PyObject *__pyx_kp_s_Cannot_assign_to_read_only_memor;
+static PyObject *__pyx_kp_s_Cannot_create_writable_memory_vi;
+static PyObject *__pyx_kp_s_Cannot_index_with_type_s;
+static PyObject *__pyx_n_s_Ellipsis;
+static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr;
+static PyObject *__pyx_n_s_ImportError;
+static PyObject *__pyx_kp_s_Incompatible_checksums_0x_x_vs_0;
+static PyObject *__pyx_n_s_IndexError;
+static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte;
+static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr;
+static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d;
+static PyObject *__pyx_n_s_MemoryError;
+static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x;
+static PyObject *__pyx_kp_s_MemoryView_of_r_object;
+static PyObject *__pyx_n_b_O;
+static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a;
+static PyObject *__pyx_n_s_PickleError;
+static PyObject *__pyx_n_s_TypeError;
+static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object;
+static PyObject *__pyx_n_s_ValueError;
+static PyObject *__pyx_n_s_View_MemoryView;
+static PyObject *__pyx_n_s_allocate_buffer;
+static PyObject *__pyx_n_s_base;
+static PyObject *__pyx_n_s_c;
+static PyObject *__pyx_n_u_c;
+static PyObject *__pyx_n_s_class;
+static PyObject *__pyx_n_s_cline_in_traceback;
+static PyObject *__pyx_kp_s_contiguous_and_direct;
+static PyObject *__pyx_kp_s_contiguous_and_indirect;
+static PyObject *__pyx_n_s_dict;
+static PyObject *__pyx_n_s_dtype_is_object;
+static PyObject *__pyx_n_s_encode;
+static PyObject *__pyx_n_s_enumerate;
+static PyObject *__pyx_n_s_error;
+static PyObject *__pyx_n_s_flags;
+static PyObject *__pyx_n_s_format;
+static PyObject *__pyx_n_s_fortran;
+static PyObject *__pyx_n_u_fortran;
+static PyObject *__pyx_n_s_getstate;
+static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi;
+static PyObject *__pyx_n_s_id;
+static PyObject *__pyx_n_s_import;
+static PyObject *__pyx_n_s_itemsize;
+static PyObject *__pyx_kp_s_itemsize_0_for_cython_array;
+static PyObject *__pyx_n_s_main;
+static PyObject *__pyx_n_s_max_neg_val;
+static PyObject *__pyx_n_s_memview;
+static PyObject *__pyx_n_s_mode;
+static PyObject *__pyx_n_s_name;
+static PyObject *__pyx_n_s_name_2;
+static PyObject *__pyx_n_s_ndim;
+static PyObject *__pyx_n_s_new;
+static PyObject *__pyx_kp_s_no_default___reduce___due_to_non;
+static PyObject *__pyx_n_s_np;
+static PyObject *__pyx_n_s_numpy;
+static PyObject *__pyx_kp_u_numpy_core_multiarray_failed_to;
+static PyObject *__pyx_kp_u_numpy_core_umath_failed_to_impor;
+static PyObject *__pyx_n_s_obj;
+static PyObject *__pyx_n_s_pack;
+static PyObject *__pyx_n_s_paths;
+static PyObject *__pyx_n_s_pickle;
+static PyObject *__pyx_n_s_pyx_PickleError;
+static PyObject *__pyx_n_s_pyx_checksum;
+static PyObject *__pyx_n_s_pyx_getbuffer;
+static PyObject *__pyx_n_s_pyx_result;
+static PyObject *__pyx_n_s_pyx_state;
+static PyObject *__pyx_n_s_pyx_type;
+static PyObject *__pyx_n_s_pyx_unpickle_Enum;
+static PyObject *__pyx_n_s_pyx_vtable;
+static PyObject *__pyx_n_s_range;
+static PyObject *__pyx_n_s_reduce;
+static PyObject *__pyx_n_s_reduce_cython;
+static PyObject *__pyx_n_s_reduce_ex;
+static PyObject *__pyx_n_s_setstate;
+static PyObject *__pyx_n_s_setstate_cython;
+static PyObject *__pyx_n_s_shape;
+static PyObject *__pyx_n_s_size;
+static PyObject *__pyx_n_s_start;
+static PyObject *__pyx_n_s_step;
+static PyObject *__pyx_n_s_stop;
+static PyObject *__pyx_kp_s_strided_and_direct;
+static PyObject *__pyx_kp_s_strided_and_direct_or_indirect;
+static PyObject *__pyx_kp_s_strided_and_indirect;
+static PyObject *__pyx_kp_s_stringsource;
+static PyObject *__pyx_n_s_struct;
+static PyObject *__pyx_n_s_t_xs;
+static PyObject *__pyx_n_s_t_ys;
+static PyObject *__pyx_n_s_test;
+static PyObject *__pyx_kp_s_unable_to_allocate_array_data;
+static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str;
+static PyObject *__pyx_n_s_unpack;
+static PyObject *__pyx_n_s_update;
+static PyObject *__pyx_n_s_values;
+static PyObject *__pyx_pf_6matcha_5utils_15monotonic_align_4core_maximum_path_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_xs, __Pyx_memviewslice __pyx_v_t_ys, float __pyx_v_max_neg_val); /* proto */
+static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */
+static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */
+static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */
+static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */
+static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */
+static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */
+static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */
+static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */
+static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */
+static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */
+static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */
+static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */
+static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */
+static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */
+static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */
+static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */
+static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/
+static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/
+static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/
+static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/
+static PyObject *__pyx_int_0;
+static PyObject *__pyx_int_1;
+static PyObject *__pyx_int_112105877;
+static PyObject *__pyx_int_136983863;
+static PyObject *__pyx_int_184977713;
+static PyObject *__pyx_int_neg_1;
+static float __pyx_k_;
+static PyObject *__pyx_tuple__2;
+static PyObject *__pyx_tuple__3;
+static PyObject *__pyx_tuple__4;
+static PyObject *__pyx_tuple__5;
+static PyObject *__pyx_tuple__6;
+static PyObject *__pyx_tuple__7;
+static PyObject *__pyx_tuple__8;
+static PyObject *__pyx_tuple__9;
+static PyObject *__pyx_slice__18;
+static PyObject *__pyx_tuple__10;
+static PyObject *__pyx_tuple__11;
+static PyObject *__pyx_tuple__12;
+static PyObject *__pyx_tuple__13;
+static PyObject *__pyx_tuple__14;
+static PyObject *__pyx_tuple__15;
+static PyObject *__pyx_tuple__16;
+static PyObject *__pyx_tuple__17;
+static PyObject *__pyx_tuple__19;
+static PyObject *__pyx_tuple__20;
+static PyObject *__pyx_tuple__21;
+static PyObject *__pyx_tuple__22;
+static PyObject *__pyx_tuple__23;
+static PyObject *__pyx_tuple__24;
+static PyObject *__pyx_tuple__25;
+static PyObject *__pyx_tuple__26;
+static PyObject *__pyx_tuple__27;
+static PyObject *__pyx_tuple__28;
+static PyObject *__pyx_codeobj__29;
+/* Late includes */
+
+/* "matcha/utils/monotonic_align/core.pyx":11
+ * @cython.boundscheck(False)
+ * @cython.wraparound(False)
+ * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_x, int t_y, float max_neg_val) nogil: # <<<<<<<<<<<<<<
+ * cdef int x
+ * cdef int y
+ */
+
+static void __pyx_f_6matcha_5utils_15monotonic_align_4core_maximum_path_each(__Pyx_memviewslice __pyx_v_path, __Pyx_memviewslice __pyx_v_value, int __pyx_v_t_x, int __pyx_v_t_y, float __pyx_v_max_neg_val) {
+ int __pyx_v_x;
+ int __pyx_v_y;
+ float __pyx_v_v_prev;
+ float __pyx_v_v_cur;
+ int __pyx_v_index;
+ int __pyx_t_1;
+ int __pyx_t_2;
+ int __pyx_t_3;
+ long __pyx_t_4;
+ int __pyx_t_5;
+ long __pyx_t_6;
+ long __pyx_t_7;
+ int __pyx_t_8;
+ Py_ssize_t __pyx_t_9;
+ Py_ssize_t __pyx_t_10;
+ float __pyx_t_11;
+ float __pyx_t_12;
+ float __pyx_t_13;
+ Py_ssize_t __pyx_t_14;
+ Py_ssize_t __pyx_t_15;
+ int __pyx_t_16;
+
+ /* "matcha/utils/monotonic_align/core.pyx":17
+ * cdef float v_cur
+ * cdef float tmp
+ * cdef int index = t_x - 1 # <<<<<<<<<<<<<<
+ *
+ * for y in range(t_y):
+ */
+ __pyx_v_index = (__pyx_v_t_x - 1);
+
+ /* "matcha/utils/monotonic_align/core.pyx":19
+ * cdef int index = t_x - 1
+ *
+ * for y in range(t_y): # <<<<<<<<<<<<<<
+ * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
+ * if x == y:
+ */
+ __pyx_t_1 = __pyx_v_t_y;
+ __pyx_t_2 = __pyx_t_1;
+ for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) {
+ __pyx_v_y = __pyx_t_3;
+
+ /* "matcha/utils/monotonic_align/core.pyx":20
+ *
+ * for y in range(t_y):
+ * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): # <<<<<<<<<<<<<<
+ * if x == y:
+ * v_cur = max_neg_val
+ */
+ __pyx_t_4 = (__pyx_v_y + 1);
+ __pyx_t_5 = __pyx_v_t_x;
+ if (((__pyx_t_4 < __pyx_t_5) != 0)) {
+ __pyx_t_6 = __pyx_t_4;
+ } else {
+ __pyx_t_6 = __pyx_t_5;
+ }
+ __pyx_t_4 = __pyx_t_6;
+ __pyx_t_5 = ((__pyx_v_t_x + __pyx_v_y) - __pyx_v_t_y);
+ __pyx_t_6 = 0;
+ if (((__pyx_t_5 > __pyx_t_6) != 0)) {
+ __pyx_t_7 = __pyx_t_5;
+ } else {
+ __pyx_t_7 = __pyx_t_6;
+ }
+ __pyx_t_6 = __pyx_t_4;
+ for (__pyx_t_5 = __pyx_t_7; __pyx_t_5 < __pyx_t_6; __pyx_t_5+=1) {
+ __pyx_v_x = __pyx_t_5;
+
+ /* "matcha/utils/monotonic_align/core.pyx":21
+ * for y in range(t_y):
+ * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
+ * if x == y: # <<<<<<<<<<<<<<
+ * v_cur = max_neg_val
+ * else:
+ */
+ __pyx_t_8 = ((__pyx_v_x == __pyx_v_y) != 0);
+ if (__pyx_t_8) {
+
+ /* "matcha/utils/monotonic_align/core.pyx":22
+ * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
+ * if x == y:
+ * v_cur = max_neg_val # <<<<<<<<<<<<<<
+ * else:
+ * v_cur = value[x, y-1]
+ */
+ __pyx_v_v_cur = __pyx_v_max_neg_val;
+
+ /* "matcha/utils/monotonic_align/core.pyx":21
+ * for y in range(t_y):
+ * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
+ * if x == y: # <<<<<<<<<<<<<<
+ * v_cur = max_neg_val
+ * else:
+ */
+ goto __pyx_L7;
+ }
+
+ /* "matcha/utils/monotonic_align/core.pyx":24
+ * v_cur = max_neg_val
+ * else:
+ * v_cur = value[x, y-1] # <<<<<<<<<<<<<<
+ * if x == 0:
+ * if y == 0:
+ */
+ /*else*/ {
+ __pyx_t_9 = __pyx_v_x;
+ __pyx_t_10 = (__pyx_v_y - 1);
+ __pyx_v_v_cur = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) )));
+ }
+ __pyx_L7:;
+
+ /* "matcha/utils/monotonic_align/core.pyx":25
+ * else:
+ * v_cur = value[x, y-1]
+ * if x == 0: # <<<<<<<<<<<<<<
+ * if y == 0:
+ * v_prev = 0.
+ */
+ __pyx_t_8 = ((__pyx_v_x == 0) != 0);
+ if (__pyx_t_8) {
+
+ /* "matcha/utils/monotonic_align/core.pyx":26
+ * v_cur = value[x, y-1]
+ * if x == 0:
+ * if y == 0: # <<<<<<<<<<<<<<
+ * v_prev = 0.
+ * else:
+ */
+ __pyx_t_8 = ((__pyx_v_y == 0) != 0);
+ if (__pyx_t_8) {
+
+ /* "matcha/utils/monotonic_align/core.pyx":27
+ * if x == 0:
+ * if y == 0:
+ * v_prev = 0. # <<<<<<<<<<<<<<
+ * else:
+ * v_prev = max_neg_val
+ */
+ __pyx_v_v_prev = 0.;
+
+ /* "matcha/utils/monotonic_align/core.pyx":26
+ * v_cur = value[x, y-1]
+ * if x == 0:
+ * if y == 0: # <<<<<<<<<<<<<<
+ * v_prev = 0.
+ * else:
+ */
+ goto __pyx_L9;
+ }
+
+ /* "matcha/utils/monotonic_align/core.pyx":29
+ * v_prev = 0.
+ * else:
+ * v_prev = max_neg_val # <<<<<<<<<<<<<<
+ * else:
+ * v_prev = value[x-1, y-1]
+ */
+ /*else*/ {
+ __pyx_v_v_prev = __pyx_v_max_neg_val;
+ }
+ __pyx_L9:;
+
+ /* "matcha/utils/monotonic_align/core.pyx":25
+ * else:
+ * v_cur = value[x, y-1]
+ * if x == 0: # <<<<<<<<<<<<<<
+ * if y == 0:
+ * v_prev = 0.
+ */
+ goto __pyx_L8;
+ }
+
+ /* "matcha/utils/monotonic_align/core.pyx":31
+ * v_prev = max_neg_val
+ * else:
+ * v_prev = value[x-1, y-1] # <<<<<<<<<<<<<<
+ * value[x, y] = max(v_cur, v_prev) + value[x, y]
+ *
+ */
+ /*else*/ {
+ __pyx_t_10 = (__pyx_v_x - 1);
+ __pyx_t_9 = (__pyx_v_y - 1);
+ __pyx_v_v_prev = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_10 * __pyx_v_value.strides[0]) )) + __pyx_t_9)) )));
+ }
+ __pyx_L8:;
+
+ /* "matcha/utils/monotonic_align/core.pyx":32
+ * else:
+ * v_prev = value[x-1, y-1]
+ * value[x, y] = max(v_cur, v_prev) + value[x, y] # <<<<<<<<<<<<<<
+ *
+ * for y in range(t_y - 1, -1, -1):
+ */
+ __pyx_t_11 = __pyx_v_v_prev;
+ __pyx_t_12 = __pyx_v_v_cur;
+ if (((__pyx_t_11 > __pyx_t_12) != 0)) {
+ __pyx_t_13 = __pyx_t_11;
+ } else {
+ __pyx_t_13 = __pyx_t_12;
+ }
+ __pyx_t_9 = __pyx_v_x;
+ __pyx_t_10 = __pyx_v_y;
+ __pyx_t_14 = __pyx_v_x;
+ __pyx_t_15 = __pyx_v_y;
+ *((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_14 * __pyx_v_value.strides[0]) )) + __pyx_t_15)) )) = (__pyx_t_13 + (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))));
+ }
+ }
+
+ /* "matcha/utils/monotonic_align/core.pyx":34
+ * value[x, y] = max(v_cur, v_prev) + value[x, y]
+ *
+ * for y in range(t_y - 1, -1, -1): # <<<<<<<<<<<<<<
+ * path[index, y] = 1
+ * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]):
+ */
+ for (__pyx_t_1 = (__pyx_v_t_y - 1); __pyx_t_1 > -1; __pyx_t_1-=1) {
+ __pyx_v_y = __pyx_t_1;
+
+ /* "matcha/utils/monotonic_align/core.pyx":35
+ *
+ * for y in range(t_y - 1, -1, -1):
+ * path[index, y] = 1 # <<<<<<<<<<<<<<
+ * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]):
+ * index = index - 1
+ */
+ __pyx_t_10 = __pyx_v_index;
+ __pyx_t_9 = __pyx_v_y;
+ *((int *) ( /* dim=1 */ ((char *) (((int *) ( /* dim=0 */ (__pyx_v_path.data + __pyx_t_10 * __pyx_v_path.strides[0]) )) + __pyx_t_9)) )) = 1;
+
+ /* "matcha/utils/monotonic_align/core.pyx":36
+ * for y in range(t_y - 1, -1, -1):
+ * path[index, y] = 1
+ * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]): # <<<<<<<<<<<<<<
+ * index = index - 1
+ *
+ */
+ __pyx_t_16 = ((__pyx_v_index != 0) != 0);
+ if (__pyx_t_16) {
+ } else {
+ __pyx_t_8 = __pyx_t_16;
+ goto __pyx_L13_bool_binop_done;
+ }
+ __pyx_t_16 = ((__pyx_v_index == __pyx_v_y) != 0);
+ if (!__pyx_t_16) {
+ } else {
+ __pyx_t_8 = __pyx_t_16;
+ goto __pyx_L13_bool_binop_done;
+ }
+ __pyx_t_9 = __pyx_v_index;
+ __pyx_t_10 = (__pyx_v_y - 1);
+ __pyx_t_15 = (__pyx_v_index - 1);
+ __pyx_t_14 = (__pyx_v_y - 1);
+ __pyx_t_16 = (((*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))) < (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_15 * __pyx_v_value.strides[0]) )) + __pyx_t_14)) )))) != 0);
+ __pyx_t_8 = __pyx_t_16;
+ __pyx_L13_bool_binop_done:;
+ if (__pyx_t_8) {
+
+ /* "matcha/utils/monotonic_align/core.pyx":37
+ * path[index, y] = 1
+ * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]):
+ * index = index - 1 # <<<<<<<<<<<<<<
+ *
+ *
+ */
+ __pyx_v_index = (__pyx_v_index - 1);
+
+ /* "matcha/utils/monotonic_align/core.pyx":36
+ * for y in range(t_y - 1, -1, -1):
+ * path[index, y] = 1
+ * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]): # <<<<<<<<<<<<<<
+ * index = index - 1
+ *
+ */
+ }
+ }
+
+ /* "matcha/utils/monotonic_align/core.pyx":11
+ * @cython.boundscheck(False)
+ * @cython.wraparound(False)
+ * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_x, int t_y, float max_neg_val) nogil: # <<<<<<<<<<<<<<
+ * cdef int x
+ * cdef int y
+ */
+
+ /* function exit code */
+}
+
+/* "matcha/utils/monotonic_align/core.pyx":42
+ * @cython.boundscheck(False)
+ * @cython.wraparound(False)
+ * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<<
+ * cdef int b = values.shape[0]
+ *
+ */
+
+static PyObject *__pyx_pw_6matcha_5utils_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
+static void __pyx_f_6matcha_5utils_15monotonic_align_4core_maximum_path_c(__Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_xs, __Pyx_memviewslice __pyx_v_t_ys, CYTHON_UNUSED int __pyx_skip_dispatch, struct __pyx_opt_args_6matcha_5utils_15monotonic_align_4core_maximum_path_c *__pyx_optional_args) {
+ float __pyx_v_max_neg_val = __pyx_k_;
+ CYTHON_UNUSED int __pyx_v_b;
+ int __pyx_v_i;
+ int __pyx_t_1;
+ int __pyx_t_2;
+ int __pyx_t_3;
+ __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } };
+ __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } };
+ Py_ssize_t __pyx_t_6;
+ Py_ssize_t __pyx_t_7;
+ if (__pyx_optional_args) {
+ if (__pyx_optional_args->__pyx_n > 0) {
+ __pyx_v_max_neg_val = __pyx_optional_args->max_neg_val;
+ }
+ }
+
+ /* "matcha/utils/monotonic_align/core.pyx":43
+ * @cython.wraparound(False)
+ * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil:
+ * cdef int b = values.shape[0] # <<<<<<<<<<<<<<
+ *
+ * cdef int i
+ */
+ __pyx_v_b = (__pyx_v_values.shape[0]);
+
+ /* "matcha/utils/monotonic_align/core.pyx":46
+ *
+ * cdef int i
+ * for i in prange(b, nogil=True): # <<<<<<<<<<<<<<
+ * maximum_path_each(paths[i], values[i], t_xs[i], t_ys[i], max_neg_val)
+ */
+ {
+ #ifdef WITH_THREAD
+ PyThreadState *_save;
+ Py_UNBLOCK_THREADS
+ __Pyx_FastGIL_Remember();
+ #endif
+ /*try:*/ {
+ __pyx_t_1 = __pyx_v_b;
+ if ((1 == 0)) abort();
+ {
+ #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))))
+ #undef likely
+ #undef unlikely
+ #define likely(x) (x)
+ #define unlikely(x) (x)
+ #endif
+ __pyx_t_3 = (__pyx_t_1 - 0 + 1 - 1/abs(1)) / 1;
+ if (__pyx_t_3 > 0)
+ {
+ #ifdef _OPENMP
+ #pragma omp parallel private(__pyx_t_6, __pyx_t_7) firstprivate(__pyx_t_4, __pyx_t_5)
+ #endif /* _OPENMP */
+ {
+ #ifdef _OPENMP
+ #pragma omp for firstprivate(__pyx_v_i) lastprivate(__pyx_v_i)
+ #endif /* _OPENMP */
+ for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_3; __pyx_t_2++){
+ {
+ __pyx_v_i = (int)(0 + 1 * __pyx_t_2);
+
+ /* "matcha/utils/monotonic_align/core.pyx":47
+ * cdef int i
+ * for i in prange(b, nogil=True):
+ * maximum_path_each(paths[i], values[i], t_xs[i], t_ys[i], max_neg_val) # <<<<<<<<<<<<<<
+ */
+ __pyx_t_4.data = __pyx_v_paths.data;
+ __pyx_t_4.memview = __pyx_v_paths.memview;
+ __PYX_INC_MEMVIEW(&__pyx_t_4, 0);
+ {
+ Py_ssize_t __pyx_tmp_idx = __pyx_v_i;
+ Py_ssize_t __pyx_tmp_stride = __pyx_v_paths.strides[0];
+ __pyx_t_4.data += __pyx_tmp_idx * __pyx_tmp_stride;
+}
+
+__pyx_t_4.shape[0] = __pyx_v_paths.shape[1];
+__pyx_t_4.strides[0] = __pyx_v_paths.strides[1];
+ __pyx_t_4.suboffsets[0] = -1;
+
+__pyx_t_4.shape[1] = __pyx_v_paths.shape[2];
+__pyx_t_4.strides[1] = __pyx_v_paths.strides[2];
+ __pyx_t_4.suboffsets[1] = -1;
+
+__pyx_t_5.data = __pyx_v_values.data;
+ __pyx_t_5.memview = __pyx_v_values.memview;
+ __PYX_INC_MEMVIEW(&__pyx_t_5, 0);
+ {
+ Py_ssize_t __pyx_tmp_idx = __pyx_v_i;
+ Py_ssize_t __pyx_tmp_stride = __pyx_v_values.strides[0];
+ __pyx_t_5.data += __pyx_tmp_idx * __pyx_tmp_stride;
+}
+
+__pyx_t_5.shape[0] = __pyx_v_values.shape[1];
+__pyx_t_5.strides[0] = __pyx_v_values.strides[1];
+ __pyx_t_5.suboffsets[0] = -1;
+
+__pyx_t_5.shape[1] = __pyx_v_values.shape[2];
+__pyx_t_5.strides[1] = __pyx_v_values.strides[2];
+ __pyx_t_5.suboffsets[1] = -1;
+
+__pyx_t_6 = __pyx_v_i;
+ __pyx_t_7 = __pyx_v_i;
+ __pyx_f_6matcha_5utils_15monotonic_align_4core_maximum_path_each(__pyx_t_4, __pyx_t_5, (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_xs.data) + __pyx_t_6)) ))), (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_ys.data) + __pyx_t_7)) ))), __pyx_v_max_neg_val);
+ __PYX_XDEC_MEMVIEW(&__pyx_t_4, 0);
+ __pyx_t_4.memview = NULL;
+ __pyx_t_4.data = NULL;
+ __PYX_XDEC_MEMVIEW(&__pyx_t_5, 0);
+ __pyx_t_5.memview = NULL;
+ __pyx_t_5.data = NULL;
+ }
+ }
+ }
+ }
+ }
+ #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))))
+ #undef likely
+ #undef unlikely
+ #define likely(x) __builtin_expect(!!(x), 1)
+ #define unlikely(x) __builtin_expect(!!(x), 0)
+ #endif
+ }
+
+ /* "matcha/utils/monotonic_align/core.pyx":46
+ *
+ * cdef int i
+ * for i in prange(b, nogil=True): # <<<<<<<<<<<<<<
+ * maximum_path_each(paths[i], values[i], t_xs[i], t_ys[i], max_neg_val)
+ */
+ /*finally:*/ {
+ /*normal exit:*/{
+ #ifdef WITH_THREAD
+ __Pyx_FastGIL_Forget();
+ Py_BLOCK_THREADS
+ #endif
+ goto __pyx_L5;
+ }
+ __pyx_L5:;
+ }
+ }
+
+ /* "matcha/utils/monotonic_align/core.pyx":42
+ * @cython.boundscheck(False)
+ * @cython.wraparound(False)
+ * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<<
+ * cdef int b = values.shape[0]
+ *
+ */
+
+ /* function exit code */
+}
+
+/* Python wrapper */
+static PyObject *__pyx_pw_6matcha_5utils_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
+static PyObject *__pyx_pw_6matcha_5utils_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
+ __Pyx_memviewslice __pyx_v_paths = { 0, 0, { 0 }, { 0 }, { 0 } };
+ __Pyx_memviewslice __pyx_v_values = { 0, 0, { 0 }, { 0 }, { 0 } };
+ __Pyx_memviewslice __pyx_v_t_xs = { 0, 0, { 0 }, { 0 }, { 0 } };
+ __Pyx_memviewslice __pyx_v_t_ys = { 0, 0, { 0 }, { 0 }, { 0 } };
+ float __pyx_v_max_neg_val;
+ int __pyx_lineno = 0;
+ const char *__pyx_filename = NULL;
+ int __pyx_clineno = 0;
+ PyObject *__pyx_r = 0;
+ __Pyx_RefNannyDeclarations
+ __Pyx_RefNannySetupContext("maximum_path_c (wrapper)", 0);
+ {
+ static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_paths,&__pyx_n_s_values,&__pyx_n_s_t_xs,&__pyx_n_s_t_ys,&__pyx_n_s_max_neg_val,0};
+ PyObject* values[5] = {0,0,0,0,0};
+ if (unlikely(__pyx_kwds)) {
+ Py_ssize_t kw_args;
+ const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
+ switch (pos_args) {
+ case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
+ CYTHON_FALLTHROUGH;
+ case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
+ CYTHON_FALLTHROUGH;
+ case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
+ CYTHON_FALLTHROUGH;
+ case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
+ CYTHON_FALLTHROUGH;
+ case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
+ CYTHON_FALLTHROUGH;
+ case 0: break;
+ default: goto __pyx_L5_argtuple_error;
+ }
+ kw_args = PyDict_Size(__pyx_kwds);
+ switch (pos_args) {
+ case 0:
+ if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_paths)) != 0)) kw_args--;
+ else goto __pyx_L5_argtuple_error;
+ CYTHON_FALLTHROUGH;
+ case 1:
+ if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_values)) != 0)) kw_args--;
+ else {
+ __Pyx_RaiseArgtupleInvalid("maximum_path_c", 0, 4, 5, 1); __PYX_ERR(0, 42, __pyx_L3_error)
+ }
+ CYTHON_FALLTHROUGH;
+ case 2:
+ if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_xs)) != 0)) kw_args--;
+ else {
+ __Pyx_RaiseArgtupleInvalid("maximum_path_c", 0, 4, 5, 2); __PYX_ERR(0, 42, __pyx_L3_error)
+ }
+ CYTHON_FALLTHROUGH;
+ case 3:
+ if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_ys)) != 0)) kw_args--;
+ else {
+ __Pyx_RaiseArgtupleInvalid("maximum_path_c", 0, 4, 5, 3); __PYX_ERR(0, 42, __pyx_L3_error)
+ }
+ CYTHON_FALLTHROUGH;
+ case 4:
+ if (kw_args > 0) {
+ PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_neg_val);
+ if (value) { values[4] = value; kw_args--; }
+ }
+ }
+ if (unlikely(kw_args > 0)) {
+ if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "maximum_path_c") < 0)) __PYX_ERR(0, 42, __pyx_L3_error)
+ }
+ } else {
+ switch (PyTuple_GET_SIZE(__pyx_args)) {
+ case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
+ CYTHON_FALLTHROUGH;
+ case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
+ values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
+ values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
+ values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
+ break;
+ default: goto __pyx_L5_argtuple_error;
+ }
+ }
+ __pyx_v_paths = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_paths.memview)) __PYX_ERR(0, 42, __pyx_L3_error)
+ __pyx_v_values = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_values.memview)) __PYX_ERR(0, 42, __pyx_L3_error)
+ __pyx_v_t_xs = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_xs.memview)) __PYX_ERR(0, 42, __pyx_L3_error)
+ __pyx_v_t_ys = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_ys.memview)) __PYX_ERR(0, 42, __pyx_L3_error)
+ if (values[4]) {
+ __pyx_v_max_neg_val = __pyx_PyFloat_AsFloat(values[4]); if (unlikely((__pyx_v_max_neg_val == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 42, __pyx_L3_error)
+ } else {
+ __pyx_v_max_neg_val = __pyx_k_;
+ }
+ }
+ goto __pyx_L4_argument_unpacking_done;
+ __pyx_L5_argtuple_error:;
+ __Pyx_RaiseArgtupleInvalid("maximum_path_c", 0, 4, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 42, __pyx_L3_error)
+ __pyx_L3_error:;
+ __Pyx_AddTraceback("matcha.utils.monotonic_align.core.maximum_path_c", __pyx_clineno, __pyx_lineno, __pyx_filename);
+ __Pyx_RefNannyFinishContext();
+ return NULL;
+ __pyx_L4_argument_unpacking_done:;
+ __pyx_r = __pyx_pf_6matcha_5utils_15monotonic_align_4core_maximum_path_c(__pyx_self, __pyx_v_paths, __pyx_v_values, __pyx_v_t_xs, __pyx_v_t_ys, __pyx_v_max_neg_val);
+
+ /* function exit code */
+ __Pyx_RefNannyFinishContext();
+ return __pyx_r;
+}
+
+static PyObject *__pyx_pf_6matcha_5utils_15monotonic_align_4core_maximum_path_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_xs, __Pyx_memviewslice __pyx_v_t_ys, float __pyx_v_max_neg_val) {
+ PyObject *__pyx_r = NULL;
+ __Pyx_RefNannyDeclarations
+ struct __pyx_opt_args_6matcha_5utils_15monotonic_align_4core_maximum_path_c __pyx_t_1;
+ PyObject *__pyx_t_2 = NULL;
+ int __pyx_lineno = 0;
+ const char *__pyx_filename = NULL;
+ int __pyx_clineno = 0;
+ __Pyx_RefNannySetupContext("maximum_path_c", 0);
+ __Pyx_XDECREF(__pyx_r);
+ if (unlikely(!__pyx_v_paths.memview)) { __Pyx_RaiseUnboundLocalError("paths"); __PYX_ERR(0, 42, __pyx_L1_error) }
+ if (unlikely(!__pyx_v_values.memview)) { __Pyx_RaiseUnboundLocalError("values"); __PYX_ERR(0, 42, __pyx_L1_error) }
+ if (unlikely(!__pyx_v_t_xs.memview)) { __Pyx_RaiseUnboundLocalError("t_xs"); __PYX_ERR(0, 42, __pyx_L1_error) }
+ if (unlikely(!__pyx_v_t_ys.memview)) { __Pyx_RaiseUnboundLocalError("t_ys"); __PYX_ERR(0, 42, __pyx_L1_error) }
+ __pyx_t_1.__pyx_n = 1;
+ __pyx_t_1.max_neg_val = __pyx_v_max_neg_val;
+ __pyx_f_6matcha_5utils_15monotonic_align_4core_maximum_path_c(__pyx_v_paths, __pyx_v_values, __pyx_v_t_xs, __pyx_v_t_ys, 0, &__pyx_t_1);
+ __pyx_t_2 = __Pyx_void_to_None(NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 42, __pyx_L1_error)
+ __Pyx_GOTREF(__pyx_t_2);
+ __pyx_r = __pyx_t_2;
+ __pyx_t_2 = 0;
+ goto __pyx_L0;
+
+ /* function exit code */
+ __pyx_L1_error:;
+ __Pyx_XDECREF(__pyx_t_2);
+ __Pyx_AddTraceback("matcha.utils.monotonic_align.core.maximum_path_c", __pyx_clineno, __pyx_lineno, __pyx_filename);
+ __pyx_r = NULL;
+ __pyx_L0:;
+ __PYX_XDEC_MEMVIEW(&__pyx_v_paths, 1);
+ __PYX_XDEC_MEMVIEW(&__pyx_v_values, 1);
+ __PYX_XDEC_MEMVIEW(&__pyx_v_t_xs, 1);
+ __PYX_XDEC_MEMVIEW(&__pyx_v_t_ys, 1);
+ __Pyx_XGIVEREF(__pyx_r);
+ __Pyx_RefNannyFinishContext();
+ return __pyx_r;
+}
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":734
+ * ctypedef npy_cdouble complex_t
+ *
+ * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(1, a)
+ *
+ */
+
+static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) {
+ PyObject *__pyx_r = NULL;
+ __Pyx_RefNannyDeclarations
+ PyObject *__pyx_t_1 = NULL;
+ int __pyx_lineno = 0;
+ const char *__pyx_filename = NULL;
+ int __pyx_clineno = 0;
+ __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":735
+ *
+ * cdef inline object PyArray_MultiIterNew1(a):
+ * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<<
+ *
+ * cdef inline object PyArray_MultiIterNew2(a, b):
+ */
+ __Pyx_XDECREF(__pyx_r);
+ __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 735, __pyx_L1_error)
+ __Pyx_GOTREF(__pyx_t_1);
+ __pyx_r = __pyx_t_1;
+ __pyx_t_1 = 0;
+ goto __pyx_L0;
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":734
+ * ctypedef npy_cdouble complex_t
+ *
+ * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(1, a)
+ *
+ */
+
+ /* function exit code */
+ __pyx_L1_error:;
+ __Pyx_XDECREF(__pyx_t_1);
+ __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename);
+ __pyx_r = 0;
+ __pyx_L0:;
+ __Pyx_XGIVEREF(__pyx_r);
+ __Pyx_RefNannyFinishContext();
+ return __pyx_r;
+}
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":737
+ * return PyArray_MultiIterNew(1, a)
+ *
+ * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(2, a, b)
+ *
+ */
+
+static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) {
+ PyObject *__pyx_r = NULL;
+ __Pyx_RefNannyDeclarations
+ PyObject *__pyx_t_1 = NULL;
+ int __pyx_lineno = 0;
+ const char *__pyx_filename = NULL;
+ int __pyx_clineno = 0;
+ __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":738
+ *
+ * cdef inline object PyArray_MultiIterNew2(a, b):
+ * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<<
+ *
+ * cdef inline object PyArray_MultiIterNew3(a, b, c):
+ */
+ __Pyx_XDECREF(__pyx_r);
+ __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 738, __pyx_L1_error)
+ __Pyx_GOTREF(__pyx_t_1);
+ __pyx_r = __pyx_t_1;
+ __pyx_t_1 = 0;
+ goto __pyx_L0;
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":737
+ * return PyArray_MultiIterNew(1, a)
+ *
+ * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(2, a, b)
+ *
+ */
+
+ /* function exit code */
+ __pyx_L1_error:;
+ __Pyx_XDECREF(__pyx_t_1);
+ __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename);
+ __pyx_r = 0;
+ __pyx_L0:;
+ __Pyx_XGIVEREF(__pyx_r);
+ __Pyx_RefNannyFinishContext();
+ return __pyx_r;
+}
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":740
+ * return PyArray_MultiIterNew(2, a, b)
+ *
+ * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(3, a, b, c)
+ *
+ */
+
+static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) {
+ PyObject *__pyx_r = NULL;
+ __Pyx_RefNannyDeclarations
+ PyObject *__pyx_t_1 = NULL;
+ int __pyx_lineno = 0;
+ const char *__pyx_filename = NULL;
+ int __pyx_clineno = 0;
+ __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":741
+ *
+ * cdef inline object PyArray_MultiIterNew3(a, b, c):
+ * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<<
+ *
+ * cdef inline object PyArray_MultiIterNew4(a, b, c, d):
+ */
+ __Pyx_XDECREF(__pyx_r);
+ __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 741, __pyx_L1_error)
+ __Pyx_GOTREF(__pyx_t_1);
+ __pyx_r = __pyx_t_1;
+ __pyx_t_1 = 0;
+ goto __pyx_L0;
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":740
+ * return PyArray_MultiIterNew(2, a, b)
+ *
+ * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(3, a, b, c)
+ *
+ */
+
+ /* function exit code */
+ __pyx_L1_error:;
+ __Pyx_XDECREF(__pyx_t_1);
+ __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename);
+ __pyx_r = 0;
+ __pyx_L0:;
+ __Pyx_XGIVEREF(__pyx_r);
+ __Pyx_RefNannyFinishContext();
+ return __pyx_r;
+}
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":743
+ * return PyArray_MultiIterNew(3, a, b, c)
+ *
+ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(4, a, b, c, d)
+ *
+ */
+
+static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) {
+ PyObject *__pyx_r = NULL;
+ __Pyx_RefNannyDeclarations
+ PyObject *__pyx_t_1 = NULL;
+ int __pyx_lineno = 0;
+ const char *__pyx_filename = NULL;
+ int __pyx_clineno = 0;
+ __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":744
+ *
+ * cdef inline object PyArray_MultiIterNew4(a, b, c, d):
+ * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<<
+ *
+ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
+ */
+ __Pyx_XDECREF(__pyx_r);
+ __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 744, __pyx_L1_error)
+ __Pyx_GOTREF(__pyx_t_1);
+ __pyx_r = __pyx_t_1;
+ __pyx_t_1 = 0;
+ goto __pyx_L0;
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":743
+ * return PyArray_MultiIterNew(3, a, b, c)
+ *
+ * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(4, a, b, c, d)
+ *
+ */
+
+ /* function exit code */
+ __pyx_L1_error:;
+ __Pyx_XDECREF(__pyx_t_1);
+ __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename);
+ __pyx_r = 0;
+ __pyx_L0:;
+ __Pyx_XGIVEREF(__pyx_r);
+ __Pyx_RefNannyFinishContext();
+ return __pyx_r;
+}
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":746
+ * return PyArray_MultiIterNew(4, a, b, c, d)
+ *
+ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(5, a, b, c, d, e)
+ *
+ */
+
+static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) {
+ PyObject *__pyx_r = NULL;
+ __Pyx_RefNannyDeclarations
+ PyObject *__pyx_t_1 = NULL;
+ int __pyx_lineno = 0;
+ const char *__pyx_filename = NULL;
+ int __pyx_clineno = 0;
+ __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":747
+ *
+ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
+ * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<<
+ *
+ * cdef inline tuple PyDataType_SHAPE(dtype d):
+ */
+ __Pyx_XDECREF(__pyx_r);
+ __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 747, __pyx_L1_error)
+ __Pyx_GOTREF(__pyx_t_1);
+ __pyx_r = __pyx_t_1;
+ __pyx_t_1 = 0;
+ goto __pyx_L0;
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":746
+ * return PyArray_MultiIterNew(4, a, b, c, d)
+ *
+ * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<<
+ * return PyArray_MultiIterNew(5, a, b, c, d, e)
+ *
+ */
+
+ /* function exit code */
+ __pyx_L1_error:;
+ __Pyx_XDECREF(__pyx_t_1);
+ __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename);
+ __pyx_r = 0;
+ __pyx_L0:;
+ __Pyx_XGIVEREF(__pyx_r);
+ __Pyx_RefNannyFinishContext();
+ return __pyx_r;
+}
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":749
+ * return PyArray_MultiIterNew(5, a, b, c, d, e)
+ *
+ * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<<
+ * if PyDataType_HASSUBARRAY(d):
+ * return d.subarray.shape
+ */
+
+static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) {
+ PyObject *__pyx_r = NULL;
+ __Pyx_RefNannyDeclarations
+ int __pyx_t_1;
+ __Pyx_RefNannySetupContext("PyDataType_SHAPE", 0);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":750
+ *
+ * cdef inline tuple PyDataType_SHAPE(dtype d):
+ * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<<
+ * return d.subarray.shape
+ * else:
+ */
+ __pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0);
+ if (__pyx_t_1) {
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":751
+ * cdef inline tuple PyDataType_SHAPE(dtype d):
+ * if PyDataType_HASSUBARRAY(d):
+ * return d.subarray.shape # <<<<<<<<<<<<<<
+ * else:
+ * return ()
+ */
+ __Pyx_XDECREF(__pyx_r);
+ __Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape));
+ __pyx_r = ((PyObject*)__pyx_v_d->subarray->shape);
+ goto __pyx_L0;
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":750
+ *
+ * cdef inline tuple PyDataType_SHAPE(dtype d):
+ * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<<
+ * return d.subarray.shape
+ * else:
+ */
+ }
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":753
+ * return d.subarray.shape
+ * else:
+ * return () # <<<<<<<<<<<<<<
+ *
+ *
+ */
+ /*else*/ {
+ __Pyx_XDECREF(__pyx_r);
+ __Pyx_INCREF(__pyx_empty_tuple);
+ __pyx_r = __pyx_empty_tuple;
+ goto __pyx_L0;
+ }
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":749
+ * return PyArray_MultiIterNew(5, a, b, c, d, e)
+ *
+ * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<<
+ * if PyDataType_HASSUBARRAY(d):
+ * return d.subarray.shape
+ */
+
+ /* function exit code */
+ __pyx_L0:;
+ __Pyx_XGIVEREF(__pyx_r);
+ __Pyx_RefNannyFinishContext();
+ return __pyx_r;
+}
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":928
+ * int _import_umath() except -1
+ *
+ * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<<
+ * Py_INCREF(base) # important to do this before stealing the reference below!
+ * PyArray_SetBaseObject(arr, base)
+ */
+
+static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) {
+ __Pyx_RefNannyDeclarations
+ __Pyx_RefNannySetupContext("set_array_base", 0);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":929
+ *
+ * cdef inline void set_array_base(ndarray arr, object base):
+ * Py_INCREF(base) # important to do this before stealing the reference below! # <<<<<<<<<<<<<<
+ * PyArray_SetBaseObject(arr, base)
+ *
+ */
+ Py_INCREF(__pyx_v_base);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":930
+ * cdef inline void set_array_base(ndarray arr, object base):
+ * Py_INCREF(base) # important to do this before stealing the reference below!
+ * PyArray_SetBaseObject(arr, base) # <<<<<<<<<<<<<<
+ *
+ * cdef inline object get_array_base(ndarray arr):
+ */
+ (void)(PyArray_SetBaseObject(__pyx_v_arr, __pyx_v_base));
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":928
+ * int _import_umath() except -1
+ *
+ * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<<
+ * Py_INCREF(base) # important to do this before stealing the reference below!
+ * PyArray_SetBaseObject(arr, base)
+ */
+
+ /* function exit code */
+ __Pyx_RefNannyFinishContext();
+}
+
+/* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":932
+ * PyArray_SetBaseObject(arr, base)
+ *
+ * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<<
+ * base = PyArray_BASE(arr)
+ * if base is NULL:
+ */
+
+static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) {
+ PyObject *__pyx_v_base;
+ PyObject *__pyx_r = NULL;
+ __Pyx_RefNannyDeclarations
+ int __pyx_t_1;
+ __Pyx_RefNannySetupContext("get_array_base", 0);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":933
+ *
+ * cdef inline object get_array_base(ndarray arr):
+ * base = PyArray_BASE(arr) # <<<<<<<<<<<<<<
+ * if base is NULL:
+ * return None
+ */
+ __pyx_v_base = PyArray_BASE(__pyx_v_arr);
+
+ /* "../../../../../../ephemeral/user/ak8224/ephemeral/pip-build-env-b7picqni/overlay/lib/python3.10/site-packages/numpy/__init__.pxd":934
+ * cdef inline object get_array_base(ndarray arr):
+ * base = PyArray_BASE(arr)
+ * if base is NULL: # <<<<<<<<<<<<<<
+ * return None
+ * return