E2A2 — speech on the mapped MCLT power#
E2A2 speech MCLT v2 (hub name speech_mclt_v2) is an E2A2 codec for 16 kHz mono speech that does not code the waveform. Its signal is the power of the modulated complex lapped transform (MCLT) of the waveform, passed through a fixed per-band map onto [−1, 1]:
the waveform is made zero mean and peak 1;
MDCT (cosine) and MDST (sine) coefficients with the sine window: 160 bands of 50 Hz, 320-sample frames at a 160-sample hop (10 ms), 160 zeros padded in front; power p = c² + s² per band and frame, i.e. 160 channels at 100 frames/s;
per band b, u = 2 G_b(min(√p, limit_b)) / G_b(limit_b) − 1, with G_b the CDF of |x| under a generalized Gaussian (480 constants: β, scale and limit per band).
The E2A2 autoencoder codes u with the GGDLPC entropy coder. The encoder is one linear projection per channel group followed by the SC6 quantizer: 8 channels per 80 ms patch, then 7 per 20 ms, 14 per 10 ms frame and 39 per 10 ms frame, each group on the residual of the previous ones. The four operating points are the cumulative channel counts 8, 15, 29 and 68, each a channel prefix of one encode with its own decoder; their rates are a factor of about √10 apart (0.44, 1.39, 4.50 and 14.04 kbps on LibriSpeech test-clean). Every 80 ms macroregion is a byte stream decodable alone; the stream delay is 90 ms (the 80 ms macroregion and the 10 ms transform overlap). No phase is coded: the decoder output is mapped back to power, and the waveform is recovered by 32 iterations of MCLT phase retrieval (alternating projections between the decoded magnitudes and the set of consistent MDCT/MDST pairs, Gaussian initial pairs, seed 0).
The weights are not released. The codec is loaded from a private Hugging Face repository; this page shows the workflow and its outputs. Running the notebook needs read access to that repository.
import json, glob
import numpy as np, torch, torchaudio, matplotlib.pyplot as plt
from IPython.display import Audio, display
from torchvision.transforms import ToPILImage
from compressors import speech_eval
from compressors.e2a2_mclt import MCLTSpeechCodec, mclt_power, mapped_psnr, hub_rd_curve
from compressors.audio_eval import psnr_db
Load the codec#
One merged decoder per operating point; the encoders of the lower points are channel prefixes of the top one.
device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
codec = MCLTSpeechCodec('speech_mclt_v2', device=device)
cfg, ops = codec.config, codec.ops
print(f"input = {cfg.input_channels} mapped MCLT bands at {cfg.sample_rate} frames/s")
print(f"channel groups = {list(cfg.group_sizes)} channels, patch = {list(cfg.ps)} frames")
print(f"operating points = {ops} (cumulative channels)")
for n, d in zip(ops, cfg.decoder_configs):
print(f" op {n:>2}: decoder ps={d['decoder_ps']} width={d['decoder_dim']} depth={d['decoder_depth']}")
print(f"entropy coder = GGDLPC, {cfg.stream_mode}, macroregion {cfg.macroregion} frames = {cfg.macroregion * 10} ms")
input = 160 mapped MCLT bands at 100 frames/s
channel groups = [8, 7, 14, 39] channels, patch = [8, 2, 1, 1] frames
operating points = [8, 15, 29, 68] (cumulative channels)
op 8: decoder ps=4 width=1024 depth=4
op 15: decoder ps=4 width=1024 depth=4
op 29: decoder ps=4 width=1024 depth=4
op 68: decoder ps=4 width=1024 depth=4
entropy coder = GGDLPC, all_detail, macroregion 8 frames = 80 ms
Example clip#
The first utterance of the LibriTTS test-clean subset used for the speech comparison (compressors.speech_eval: first 10 s, 16 kHz mono), zero mean and peak 1.
fs = speech_eval.SPEECH_SAMPLE_RATE
clips = speech_eval.load_libritts_clips(1, verbose=False)
print(clips.provenance['clip_selection']['records'][0])
w = codec.level(clips[0][0].numpy())
n_samples = len(w)
print(f"{n_samples} samples = {n_samples / fs:.2f} s")
mel = torchaudio.transforms.MelSpectrogram(sample_rate=fs, n_fft=1024, hop_length=256, n_mels=80)
def make_spectrogram(w):
S = (mel(torch.as_tensor(w, dtype=torch.float32)) + 1e-8).log()
S = ((S - S.mean()) / (3 * S.std()) + 0.5).clamp(0, 1)
return ToPILImage()(S.flip(0)).resize((600, 160))
display(make_spectrogram(w))
Audio(w, rate=fs)
test-clean/1089/134686/1089_134686_000002_000003.wav
160000 samples = 10.00 s
Analysis: MCLT power and the per-band map#
Left: log MCLT power, 160 bands of 50 Hz by 10 ms frames. Right: the mapped array u in [−1, 1], the signal the autoencoder codes. Below: the map for a few bands, u as a function of the magnitude √p.
p = mclt_power(w) # (frames, 160)
u = codec.analyze(w) # (160, frames)
T = u.shape[1]
print(f"power {p.shape[::-1]} (bands x frames), mapped array {u.shape}, range [{u.min():.2f}, {u.max():.2f}]")
extent = [0, T / 100, 0, 8]
fig, axes = plt.subplots(1, 2, figsize=(11, 3), dpi=110, constrained_layout=True)
im = axes[0].imshow(10 * np.log10(p.T + 1e-12), origin='lower', aspect='auto', extent=extent, cmap='magma', vmin=-80)
axes[0].set_title('MCLT power (dB)'); fig.colorbar(im, ax=axes[0])
im = axes[1].imshow(u, origin='lower', aspect='auto', extent=extent, cmap='viridis', vmin=-1, vmax=1)
axes[1].set_title('mapped array u'); fig.colorbar(im, ax=axes[1])
for ax in axes:
ax.set_xlabel('time (s)'); ax.set_ylabel('frequency (kHz)')
plt.show()
fig, ax = plt.subplots(figsize=(5, 3), dpi=110)
for b in (2, 20, 60, 120):
t = np.logspace(-7, np.log10(codec.map.limit[b]), 400)
pp = np.zeros((len(t), 160)); pp[:, b] = t ** 2
ax.semilogx(t, codec.map.fwd(pp)[:, b], label=f'band {b} ({b * 50}–{b * 50 + 50} Hz)')
ax.set_xlabel('magnitude √p'); ax.set_ylabel('u'); ax.grid(True, which='both', alpha=0.3); ax.legend(fontsize=7)
plt.tight_layout(); plt.show()
power (160, 1001) (bands x frames), mapped array (160, 1001), range [-1.00, 0.60]
Encode to bytes#
One encode at the top operating point. The mapped array is padded with −1 to a multiple of 8 frames; each 80 ms macroregion becomes one byte-padded stream, and the stream of operating point n is the bit prefix covering channels ≤ n. encode decodes every operating point back from its truncated bytes and compares the latents with the encoder’s. CR is against 16-bit PCM.
enc = codec.encode(u)
print(f"{len(enc.streams)} macroregion streams; latents decoded from the bytes at ops {ops}: identical to the encoder's")
print(f"\n{'op':>4} {'bits':>8} {'kbps':>7} {'CR':>8} {'bits/frame':>11}")
for n in ops:
bits = codec.bits(enc, n)
print(f"{n:>4} {bits:>8,} {bits / (n_samples / fs) / 1000:>7.3f} {16 * n_samples / bits:>7.0f}x {bits / T:>11.2f}")
126 macroregion streams; latents decoded from the bytes at ops [8, 15, 29, 68]: identical to the encoder's
op bits kbps CR bits/frame
8 4,216 0.422 607x 4.21
15 13,960 1.396 183x 13.95
29 43,880 4.388 58x 43.84
68 130,648 13.065 20x 130.52
Per-macroregion rate#
Bits of each 80 ms stream at each operating point.
mr = cfg.macroregion
t_edges = np.arange(len(enc.streams) + 1) * mr / 100
fig, axes = plt.subplots(2, 1, figsize=(8, 4), dpi=110, sharex=True, gridspec_kw={'height_ratios': [1, 1.6]})
axes[0].plot(np.arange(n_samples) / fs, w, lw=0.3, color='0.4'); axes[0].set_ylabel('amplitude')
for n in ops:
rb = 8 * ((enc.prefix[:, n - 1] + 7) // 8)
axes[1].stairs(rb / (mr / 100) / 1000, t_edges, label=f'{n} ch')
axes[1].set_yscale('log'); axes[1].set_xlabel('time (s)'); axes[1].set_ylabel('kbps')
axes[1].legend(fontsize=7); axes[1].grid(True, which='both', alpha=0.3)
plt.tight_layout(); plt.show()
Decode and phase retrieval#
For each operating point: the decoded mapped array (decoded from the byte prefix), its PSNR against u (10 log₁₀(4 / MSE), the measure the codec is trained on), and the waveform recovered by the inverse map and phase retrieval. The waveform PSNR and ViSQOL are printed as the speech harness defines them; the recovered waveform carries no coded phase, so it is not sample-aligned with the reference and those two numbers read low by construction. The first row is the uncoded mapped array through the same phase retrieval, the ceiling of the representation.
def report(label, u_hat, bits=None):
w_hat = codec.synthesize(u_hat, n_samples)
x, x_hat = torch.from_numpy(w)[None] / 2, torch.from_numpy(w_hat)[None] / 2
rate = f"{bits / (n_samples / fs) / 1000:.3f} kbps, " if bits is not None else ""
pm = f"PSNR on u {mapped_psnr(u, u_hat):.2f} dB, " if bits is not None else ""
print(f"{label}: {rate}{pm}waveform PSNR {psnr_db(x, x_hat):.2f} dB, ViSQOL {speech_eval.visqol_speech(x, x_hat):.3f}")
fig, ax = plt.subplots(figsize=(6, 1.8), dpi=100)
ax.imshow(u_hat, origin='lower', aspect='auto', extent=extent, cmap='viridis', vmin=-1, vmax=1)
ax.set_ylabel('kHz'); ax.set_xlabel('time (s)'); ax.set_title('decoded u' if bits is not None else 'u', fontsize=8)
plt.tight_layout(); plt.show()
display(make_spectrogram(w_hat))
display(Audio(w_hat, rate=fs))
report('uncoded u through phase retrieval', u)
for n in ops:
report(f'op {n}', codec.decode(enc, n), codec.bits(enc, n))
[tflite_quality_mapper.cc : 32] RAW: Loading TF Lattice TFLite model at /home/dan/g/lib/python3.14/site-packages/speequal/visqol/model/lattice_tcditugenmeetpackhref_ls2_nl60_lr12_bs2048_learn.005_ep2400_train1_7_raw.tflite
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
uncoded u through phase retrieval: waveform PSNR 22.79 dB, ViSQOL 4.389
op 8: 0.422 kbps, PSNR on u 27.81 dB, waveform PSNR 23.45 dB, ViSQOL 1.563
[tflite_quality_mapper.cc : 32] RAW: Loading TF Lattice TFLite model at /home/dan/g/lib/python3.14/site-packages/speequal/visqol/model/lattice_tcditugenmeetpackhref_ls2_nl60_lr12_bs2048_learn.005_ep2400_train1_7_raw.tflite
[tflite_quality_mapper.cc : 32] RAW: Loading TF Lattice TFLite model at /home/dan/g/lib/python3.14/site-packages/speequal/visqol/model/lattice_tcditugenmeetpackhref_ls2_nl60_lr12_bs2048_learn.005_ep2400_train1_7_raw.tflite
op 15: 1.396 kbps, PSNR on u 29.74 dB, waveform PSNR 23.16 dB, ViSQOL 2.163
[tflite_quality_mapper.cc : 32] RAW: Loading TF Lattice TFLite model at /home/dan/g/lib/python3.14/site-packages/speequal/visqol/model/lattice_tcditugenmeetpackhref_ls2_nl60_lr12_bs2048_learn.005_ep2400_train1_7_raw.tflite
op 29: 4.388 kbps, PSNR on u 31.29 dB, waveform PSNR 23.10 dB, ViSQOL 3.499
[tflite_quality_mapper.cc : 32] RAW: Loading TF Lattice TFLite model at /home/dan/g/lib/python3.14/site-packages/speequal/visqol/model/lattice_tcditugenmeetpackhref_ls2_nl60_lr12_bs2048_learn.005_ep2400_train1_7_raw.tflite
op 68: 13.065 kbps, PSNR on u 33.73 dB, waveform PSNR 22.89 dB, ViSQOL 3.887
Rate and quality over the evaluation sets#
Two sets. LibriTTS test-clean, 200 utterances (compressors.speech_eval), measured with this package’s speech harness (python -m compressors.e2a2_mclt.evaluate_rate_distortion): rate, PSNR on the mapped array (MSE pooled over every value of the set, and the per-utterance mean), and the harness’s waveform PSNR and ViSQOL on the phase-retrieved waveform. LibriSpeech test-clean, all 2,620 utterances, from the codec’s own record (rd.json in the private hub directory): rate, pooled PSNR on the mapped array, and the word error rate of two speech recognizers (openai/whisper-base and facebook/wav2vec2-base-960h, Whisper’s English text normalizer) on the phase-retrieved waveform. The speech harness of this package has no word-error-rate metric.
rd_path = sorted(glob.glob('results/speech_e2a2_mclt_v2/rate_distortion_*.json'))[-1]
rd = json.load(open(rd_path))
print(f"{rd_path}: {rd['dataset']} [{rd['split']}], {rd['n_samples']} utterances")
print(f"{'op':>4} {'kbps':>7} {'PSNR u pooled':>14} {'PSNR u mean':>12} {'wave PSNR':>10} {'ViSQOL':>7}")
lt = []
for n in rd['quality_values']:
r = rd['results'][str(n)]
m = r['mean']
lt.append((m['kbps'], r['pooled']['PSNR_MCLT_dB']))
print(f"{n:>4} {m['kbps']:>7.3f} {r['pooled']['PSNR_MCLT_dB']:>14.2f} {m['PSNR_MCLT_dB']:>12.2f} {m['PSNR_dB']:>10.2f} {m['ViSQOL']:>7.3f}")
hub = hub_rd_curve('speech_mclt_v2')
print(f"\n{hub['val_set']} (codec record):")
print(f"{'op':>4} {'kbps':>7} {'PSNR u pooled':>14} {'WER whisper-base':>17} {'WER wav2vec2-base':>18}")
ls = []
for q in hub['rd_curve']:
ls.append((q['kbps'], q['psnr']))
print(f"{q['n_ch']:>4} {q['kbps']:>7.3f} {q['psnr']:>14.2f} {100 * q['wer_whisper_base']:>16.2f}% {100 * q['wer_wav2vec2_base_960h']:>17.2f}%")
print("unprocessed audio: 5.07% / 3.27%")
plt.figure(figsize=(5.5, 3.8), dpi=120)
plt.semilogx(*zip(*lt), 'o-', label=f"LibriTTS test-clean, {rd['n_samples']} utterances")
plt.semilogx(*zip(*ls), 's--', label='LibriSpeech test-clean, 2,620 utterances')
for (k, v), n in zip(lt, rd['quality_values']):
plt.annotate(f'{n} ch', (k, v), fontsize=7, xytext=(4, -10), textcoords='offset points')
plt.xlabel('rate (kbps)'); plt.ylabel('PSNR on the mapped MCLT power (dB)')
plt.grid(True, which='both', alpha=0.3); plt.legend(fontsize=7); plt.tight_layout(); plt.show()
results/speech_e2a2_mclt_v2/rate_distortion_1795739626.json: danjacobellis/libritts [validation], 200 utterances
op kbps PSNR u pooled PSNR u mean wave PSNR ViSQOL
8 0.440 25.58 25.74 22.98 1.403
15 1.434 27.45 27.63 22.40 2.564
29 4.658 29.33 29.53 22.13 3.397
68 14.508 32.22 32.44 21.96 3.813
LibriSpeech test-clean, all 2,620 utterances (5.4 h) (codec record):
op kbps PSNR u pooled WER whisper-base WER wav2vec2-base
8 0.438 25.75 44.09% 35.38%
15 1.393 27.60 10.24% 7.87%
29 4.495 29.49 6.23% 4.73%
68 14.042 32.43 5.42% 3.91%
unprocessed audio: 5.07% / 3.27%