CMVN
Cepstral mean and variance normalization, matching kaldi's compute-cmvn-stats / apply-cmvn (see kaldi-native-fbank/csrc/feature-cmvn.h).
Stats layout (identical to kaldi's cmvn.ark):
2 rows (full stats) —
row0 = [sum_1..sum_D, count],row1 = [sumsq_1..sumsq_D, (unused)]; supports both mean and variance normalization.1 row (mean-only stats) —
row0 = [sum_1..sum_D, count]; supports mean normalization only (norm_vars=Trueis an error, same as kaldi).
Usage
import numpy as np
import kaldi_native_fbank as knf
feats = np.random.rand(100, 13).astype(np.float32) # frames x dim
stats = knf.compute_cmvn_stats(feats) # shape: (2, dim+1), float64
opts = knf.CmvnOptions()
opts.norm_vars = False
out = knf.apply_cmvn(stats, opts, feats) # normalized copy
# in-place variant
knf.apply_cmvn_(stats, opts, feats)
# reverse (undo cmvn)
rev = knf.CmvnOptions()
rev.reverse = True
restored = knf.apply_cmvn(stats, rev, out)
# incremental / speaker-level accumulation
acc = knf.CmvnAccumulator()
acc.accumulate(feats)
stats2 = acc.stats # CmvnAccumulator.stats property -> ndarray
Formulas
Let \(x_d\) be the input feature, \(w\) the frame weight (1.0 for plain accumulation), and \(N\) the frame count. The stats are:
Per-dimension mean and variance:
Mean normalization (norm_vars=False, kaldi apply-cmvn):
Variance normalization too (norm_vars=True, kaldi --norm-vars):
with \(\sigma_d^2\) floored at \(10^{-20}\) (kaldi warns and floors). The affine form \(x'_d = x_d s_d + o_d\) is what kaldi actually computes (multiply by scale, then add offset), and we follow the same order.
Reverse (reverse=True, kaldi --reverse) undoes the transform:
Equivalent in kaldi
The API mirrors kaldi's compute-cmvn-stats / apply-cmvn one-to-one. Given the same input, the outputs are value-by-value equal (see the golden tests):
# kaldi: accumulate stats
compute-cmvn-stats ark:feats.ark ark:cmvn_stats.ark
# kaldi: apply (mean normalization)
apply-cmvn --utt2spk=ark:utt2spk ark:cmvn_stats.ark ark:feats.ark ark:cmvn.ark
# kaldi: apply with variance normalization
apply-cmvn --norm-vars --utt2spk=ark:utt2spk ark:cmvn_stats.ark \
ark:feats.ark ark:cmvn_normvars.ark
# kaldi: undo cmvn
apply-cmvn --reverse --utt2spk=ark:utt2spk ark:cmvn_stats.ark \
ark:cmvn.ark ark:restored.ark
# equivalent python API
stats = knf.compute_cmvn_stats(feats) # == compute-cmvn-stats
out = knf.apply_cmvn(stats, knf.CmvnOptions(), feats) # == apply-cmvn
opts = knf.CmvnOptions(); opts.norm_vars = True # == --norm-vars
out = knf.apply_cmvn(stats, opts, feats)
opts = knf.CmvnOptions(); opts.reverse = True # == --reverse
restored = knf.apply_cmvn(stats, opts, out)
Mapping
kaldi |
python API |
|---|---|
|
|
|
|
|
|
|
|
|
|
API reference
knf.CmvnOptionsOptions object matching kaldi's
apply-cmvnflags.norm_vars: bool— variance normalization too (kaldi--norm-vars)reverse: bool— undo cmvn (kaldi--reverse)
knf.compute_cmvn_stats(feats) -> numpy.ndarrayReturns the full 2-row stats matrix (
float64, shape(2, dim+1)), same layout as kaldi'scmvn.ark.knf.apply_cmvn(stats, opts, feats) -> numpy.ndarrayReturns the normalized copy. Accepts 1-row (mean-only) or 2-row stats.
knf.apply_cmvn_(stats, opts, feats) -> NoneIn-place variant.
knf.CmvnAccumulator(dim=0)Incremental accumulator (for streaming / per-speaker stats).
accumulate(feats)— accumulate a feature matrixadd(dim, frame, weight=1.0)— accumulate one framestats(property,numpy.ndarray) — the accumulated stats matrix, layout as above; feed it toapply_cmvn
Speaker-level CMVN (kaldi's utt2spk)
kaldi's apply-cmvn --utt2spk=ark:utt2spk ... looks up per-speaker stats
for each utterance. Here the stats are passed in explicitly, so the
utt2spk grouping is done by the caller; use CmvnAccumulator to collect
per-speaker stats first:
import kaldi_native_fbank as knf
utt2feats = {"u1": feats1, "u2": feats2, "u3": feats3}
utt2spk = {"u1": "spkA", "u2": "spkA", "u3": "spkB"}
# 1) per-speaker stats (== compute-cmvn-stats on each speaker's utts)
spk2acc = {}
for utt, feats in utt2feats.items():
spk = utt2spk[utt]
acc = spk2acc.setdefault(spk, knf.CmvnAccumulator())
acc.accumulate(feats)
# 2) apply per-speaker stats (== apply-cmvn --utt2spk=...)
opts = knf.CmvnOptions()
utt2normed = {}
for utt, feats in utt2feats.items():
# CmvnAccumulator.stats is the accumulated 2x(dim+1) stats matrix
stats = spk2acc[utt2spk[utt]].stats
utt2normed[utt] = knf.apply_cmvn(stats, opts, feats)
Saving results as kaldi ark/scp (kaldi-native-io)
The stats and features are plain numpy arrays and can be written in
kaldi's ark/scp formats with kaldi-native-io, producing artifacts
that kaldi tools can read directly.
Install it first (it is a separate package):
pip install kaldi-native-io
Usage:
import kaldi_native_io as knio
# write cmvn stats (double matrix, 2 x dim+1) == cmvn.ark
with knio.DoubleMatrixWriter("ark,scp:cmvn_stats.ark,cmvn_stats.scp") as w:
for spk, acc in spk2acc.items():
w.write(spk, acc.stats) # key = speaker, like kaldi
# write normalized features == cmvn output ark
with knio.FloatMatrixWriter("ark,scp:cmvn_feats.ark,cmvn_feats.scp") as w:
for utt, feats in utt2normed.items():
w.write(utt, feats)
# read back with kaldi-native-io
with knio.SequentialDoubleMatrixReader("ark:cmvn_stats.ark") as r:
for spk, stats in r:
...
The resulting cmvn_stats.scp/cmvn_feats.scp are ordinary kaldi scp
files and can be consumed by kaldi binaries (e.g. apply-cmvn, splice-feats)
unchanged.
Full class/function documentation
- class kaldi_native_fbank.CmvnOptions(self: kaldi_native_fbank.CmvnOptions, norm_vars: bool = False, reverse: bool = False)
Options matching kaldi's apply-cmvn flags.
The flags control how
apply_cmvn()normalizes features.See also
apply_cmvn()For the normalization formulas.Construct with the given flags.
- Parameters:
norm_vars --
If
True, normalize the variances as well (kaldi apply-cmvn--norm-vars).reverse --
If
True, undo cmvn instead of applying it (kaldi apply-cmvn--reverse).
- __init__(self: kaldi_native_fbank.CmvnOptions, norm_vars: bool = False, reverse: bool = False) None
Construct with the given flags.
- Parameters:
norm_vars --
If
True, normalize the variances as well (kaldi apply-cmvn--norm-vars).reverse --
If
True, undo cmvn instead of applying it (kaldi apply-cmvn--reverse).
- property norm_vars
If
True, normalize the variances as well: after subtracting the mean, each dimension is divided by its standard deviation. Requires 2-row stats (kaldi apply-cmvn--norm-vars).
- property reverse
If
True, undo cmvn instead of applying it: the mean is added back and, ifnorm_varsisTrue, the standard deviation is multiplied back (kaldi apply-cmvn--reverse).
- class kaldi_native_fbank.CmvnAccumulator(self: kaldi_native_fbank.CmvnAccumulator, dim: SupportsInt = 0)
Incremental accumulator for speaker-level / streaming cmvn.
It always keeps the full 2-row layout (see
compute_cmvn_stats()) and adds up weighted frames one by one, so stats can be collected over many utterances of the same speaker and normalized later withapply_cmvn().See also
Construct an accumulator for features of dimension
dim.- Parameters:
dim -- Feature dimension.
0(the default) creates an empty accumulator whose stats are grown by the firstadd()oraccumulate()call.
- __init__(self: kaldi_native_fbank.CmvnAccumulator, dim: SupportsInt = 0) None
Construct an accumulator for features of dimension
dim.- Parameters:
dim -- Feature dimension.
0(the default) creates an empty accumulator whose stats are grown by the firstadd()oraccumulate()call.
- accumulate(self: kaldi_native_fbank.CmvnAccumulator, feats: Annotated[numpy.typing.ArrayLike, numpy.float32, '[m, n]']) None
Accumulate stats for a feature matrix (rows = frames).
Equivalent to calling
add()for each row with weight 1.0.- Parameters:
feats (numpy.ndarray) -- Feature matrix of shape
(num_frames, dim), float32.
- add(self: kaldi_native_fbank.CmvnAccumulator, dim: SupportsInt, frame: collections.abc.Sequence[SupportsFloat], weight: SupportsFloat = 1.0) None
Accumulate stats for one frame of dimension
dim.Applies the same updates as kaldi's AccCmvnStats; with \(w = \mathrm{weight}\) and \(x_d = \mathrm{frame}[d]\):
\[c \mathrel{+}= w, \qquad S_d \mathrel{+}= x_d\, w, \qquad Q_d \mathrel{+}= x_d^2\, w\]- Parameters:
dim -- Feature dimension; must match the dimension given to the constructor.
frame (Sequence[float]) -- One frame of shape
(dim,).weight -- Weight of this frame, e.g. 1.0.
- property stats
The accumulated 2-row stats.
Row 0 is
[sums, count], row 1 is[sumsq, (unused)]; seecompute_cmvn_stats()for the layout.- Return type:
numpy.ndarray
- kaldi_native_fbank.compute_cmvn_stats(feats: Annotated[numpy.typing.ArrayLike, numpy.float32, '[m, n]']) Annotated[numpy.typing.NDArray[numpy.float64], '[m, n]']
Compute full 2-row cmvn stats for a feature matrix.
Equivalent to initializing zero stats and accumulating every row of
featswith weight 1.0 (kaldi AccCmvnStats).The returned stats matrix matches kaldi's
cmvn.arklayout exactly:\[\begin{split}\mathrm{stats} = \left( \begin{array}{cccc|c} S_1 & S_2 & \cdots & S_D & c \\ Q_1 & Q_2 & \cdots & Q_D & - \end{array} \right)\end{split}\]Row 0, columns
0..D-1hold the sums \(S_d = \sum_t x_t(d)\); the last column \(c\) holds the frame count (sum of weights).Row 1, columns
0..D-1hold the sums of squares \(Q_d = \sum_t x_t(d)^2\); the last column is unused.
- Parameters:
feats (numpy.ndarray) -- Feature matrix of shape
(num_frames, dim), float32.- Returns:
Stats matrix of shape
(2, dim + 1), float64.- Return type:
numpy.ndarray
See also
apply_cmvn()Apply these stats to features.
CmvnAccumulatorIncremental version of this computation.
- kaldi_native_fbank.apply_cmvn(stats: Annotated[numpy.typing.ArrayLike, numpy.float64, '[m, n]'], opts: kaldi_native_fbank.CmvnOptions, feats: Annotated[numpy.typing.ArrayLike, numpy.float32, '[m, n]']) Annotated[numpy.typing.NDArray[numpy.float32], '[m, n]']
Apply cmvn to features and return the normalized copy.
This follows kaldi's ApplyCmvn / ApplyCmvnReverse semantics. Let \(c\) be the frame count, \(\mu_d = \mathrm{stats}(0, d)/c\) the mean and, when
opts.norm_varsis true, \(\sigma_d^2 = \mathrm{stats}(1, d)/c - \mu_d^2\) the variance of dimension \(d\).Forward (
opts.reverse == False), applied to every frame \(x\):\[x_d \leftarrow x_d - \mu_d\]and, if
opts.norm_vars:\[x_d \leftarrow (x_d - \mu_d) / \sigma_d\]Reverse (
opts.reverse == True) undoes the normalization:\[x_d \leftarrow x_d + \mu_d\]and, if
opts.norm_vars:\[x_d \leftarrow x_d \cdot \sigma_d + \mu_d\]1-row (mean-only) stats are accepted when
norm_varsis false; requesting variance normalization with 1-row stats raises an exception (same as kaldi).- Parameters:
stats -- 1-row or 2-row cmvn stats, e.g. from
compute_cmvn_stats().opts -- Options controlling the normalization; see
CmvnOptions.feats (numpy.ndarray) -- Feature matrix of shape
(num_frames, dim), float32.
- Returns:
A normalized copy of
feats.- Return type:
numpy.ndarray
Example
stats = knf.compute_cmvn_stats(feats) opts = knf.CmvnOptions() # norm_vars=False, reverse=False normed = knf.apply_cmvn(stats, opts, feats)
See also
- kaldi_native_fbank.apply_cmvn_(stats: Annotated[numpy.typing.ArrayLike, numpy.float64, '[m, n]'], opts: kaldi_native_fbank.CmvnOptions, feats: Annotated[numpy.typing.NDArray[numpy.float32], '[m, n]', 'flags.writeable', 'flags.c_contiguous']) None
In-place version of
apply_cmvn().featsis modified directly; no copy of the feature matrix is made.- Parameters:
stats -- 1-row or 2-row cmvn stats; see
compute_cmvn_stats().opts -- Options controlling the normalization; see
CmvnOptions.feats -- Feature matrix of shape
(num_frames, dim). Must be a writeable, C-contiguous float32numpy.ndarray; it is normalized in place.
See also
apply_cmvn()For the normalization formulas.
Golden tests
The implementation is verified value-by-value against kaldi outputs in tests/data/feat_golden (generated by kaldi binaries; see the README there for the exact commands and parameter groups). See kaldi-native-fbank/python/tests/test_feature_cmvn.py.