---
title: Keyword-Aware Loss Function
url: https://www.emergentmind.com/topics/keyword-aware-loss-function
type: topic
---

# Keyword-Aware Loss Function

A keyword-aware loss function is a training objective that places explicit emphasis on keyword-relevant units rather than supervising all positions uniformly. In the cited literature, the emphasized unit can be a single high-confidence frame inside a keyword segment, a smoothed temporal peak inside a broad pooling window, a positive–negative score ordering between keyword and non-keyword examples, the false-accept and false-reject count of a special `<kw>` token over an \(N\)-best list, a context-weighted subset of query words in cross-modal retrieval, or the positions and identities of biased rare-word tokens in contextual ASR. The common rationale is to align optimization with the downstream event of interest—detection, retrieval, or biasing—more directly than standard frame-wise or token-wise cross-entropy [1705.02411][2001.09246][2107.05859][2211.06478][2501.02504][2509.09197].

## 1. Problem formulation and recurring design patterns

The central design choice in a keyword-aware loss is the object that becomes keyword-conditioned. In small-footprint keyword spotting, one line of work treats the keyword as a temporal event and selects only one frame or one smoothed peak per keyword occurrence for positive supervision, while preserving ordinary background penalties elsewhere [1705.02411][2001.09246]. Another line of work treats the keyword as a ranking target and optimizes separability between true-keyword scores and competing or spurious scores by maximizing a differentiable surrogate of the area under the receiver-operating-characteristic curve [2107.05859]. Sequence-to-sequence keyword spotting adapts Minimum Bayes-Risk training so that the risk counts only false accepts and false rejects of a special `<kw>` token, thereby making the loss explicitly depend on keyword-count errors rather than general transcription mismatch [2211.06478].

Cross-modal and contextual-biasing settings instantiate the same principle differently. In video moment retrieval and highlight detection, keyword awareness is introduced by weighting text words according to their cosine similarity with clustered video-context features, and then using those weighted text representations inside clip-level and video-level contrastive objectives [2501.02504]. In contextual biasing for rare-word ASR, the loss is decomposed into a masked cross-entropy term that trains the pointer network only at biased-word positions and a binary classification term that learns when the model should bias at all [2509.09197]. Audio-text based keyword spotting adds another variant: Relational Proxy Loss focuses on structural relations within acoustic embeddings and within text embeddings, rather than only comparing acoustic and text embeddings on a point-to-point basis [2406.05314].

Taken together, these formulations indicate that “keyword-aware” is not a single canonical formula. It denotes a family of objectives in which keyword relevance modifies frame selection, window selection, score ranking, hypothesis risk, word weighting, or bias-gating behavior.

## 2. Segment-level pooling losses in keyword spotting

A foundational formulation appears in max-pooling loss training for Long Short-Term Memory networks in small-footprint keyword spotting. Let \(X=(x_1,\dots,x_T)\) be the input sequence, \(y_t\) the softmax output at frame \(t\), \(L=\{\ell_1,\dots,\ell_P\}\) the frame-index ranges for the \(P\) keyword occurrences, \(\hat{\ell}\) the background frames, and \(k_p^\dagger\) the true keyword label for segment \(\ell_p\). For each keyword segment,
\[
l_p^\dagger = \arg\max_{t\in \ell_p} y_t^{k_p^\dagger}.
\]
The max-pooling loss is
\[
L_T^{maxpool}
= - \sum_{t\in \hat{\ell}} \ln y_t^{k_t^\dagger}
  - \sum_{p=1}^{P} \ln y_{l_p^\dagger}^{k_p^\dagger}.
\]
This differs from frame-wise cross-entropy,
\[
L_T^{xent} = - \sum_{t=1}^{T} \ln y_t^{k_t^\dagger},
\]
by applying ordinary frame-wise cross-entropy to all background frames but supervising only the single “best” frame within each keyword segment. The stated motivation is that run-time keyword spotting needs one strong spike per segment, and max-pooling loss trains the model to concentrate confidence into one peak, matching the downstream detection rule based on smoothed-posterior thresholding [1705.02411].

The training and evaluation protocol reinforces that alignment. The model uses 20-dim log-Mel filterbank energies, a unidirectional LSTM with 64 memory cells and projection layer size 32, left context of 10 frames, and right context of 10 frames. At test time, the smoothed keyword posterior is
\[
s_t = \frac{1}{N_{ctx}} \sum_{i=t-N_{ctx}+1}^{t} y_i^{keyword},
\]
with \(N_{ctx}=30\), a trigger threshold \(\theta\), lockout \(N_{lck}=40\), and latency window \(N_{lat}=20\). On far-field recordings of the single keyword “Alexa,” the max-pooling loss trained LSTM initialized with a cross-entropy pre-trained network yielded \(67.6\%\) relative reduction compared to the baseline feed-forward DNN in Area Under the Curve measure; the LSTM trained with max-pooling loss from random initialization yielded \(-48.2\%\) AUC change, and the LSTM trained with cross-entropy yielded \(-34.4\%\) [1705.02411].

Smoothed Max-Pooling generalizes this idea by replacing exact frame selection with smoothed temporal peaks inside positive pooling windows. With a temporal smoothing kernel \(s(\tau)\), smoothed score \(\tilde y_i(X_t,W) \equiv (s \circledast y_i)(X_t,W)\), positive windows \([\tau_i^{start}, \tau_i^{end}]\), and complement set \(\mathcal T^c\), the loss is
\[
Loss(W)=Loss^+(W)+Loss^-(W),
\]
where
\[
Loss^+(W)=\sum_{i=1}^{n}\left[-\log \tilde y_i(X_{m(i)},W)\right],
\qquad
m(i)=\arg\max_{t\in[\tau_i^{start},\tau_i^{end}]}\log \tilde y_i(X_t,W),
\]
and
\[
Loss^-(W)=\sum_{t\in \mathcal T^c}\left[-\log y_{c_t}(X_t,W)\right].
\]
The encoder uses \(K\) consecutive windows to discover keyword parts, while the decoder uses one window that straddles the keyword end. The total loss is
\[
Total\_Loss = \alpha\cdot Loss^E + Loss^D.
\]
The paper states that this allows semi-supervised joint training of encoder and decoder without strictly depending on frame-level labeling from LVCSR; only approximate word-end information is used to position windows [2001.09246].

Empirically, the best model, “Max4 SMP\_SMP,” achieved false-reject rates of \(0.74\%\) on clean non-accented speech, \(0.82\%\) on accented speech, \(6.13\%\) on query logs, and \(2.58\%\) on noisy in-vehicle speech at \(0.1\) FA/hr, compared with the baseline “CE\_CE” rates of \(0.97\%\), \(1.48\%\), \(8.89\%\), and \(5.62\%\), respectively. The summary states that SMP\_SMP reduces false rejects by \(23\%\)–\(54\%\) relative to baseline across all conditions, while omitting smoothing in “MP\_MP” hurts, indicating that temporal smoothing is essential for stable peaks [2001.09246].

## 3. Ranking and risk minimization for keyword detection

A different strand of keyword-aware loss design starts from ranking. For binary classification, the AUC objective is
\[
\mathrm{AUC}
=
\frac{1}{N^+N^-}
\sum_{i:y_i=1}\sum_{j:y_j=0}
\mathbb{I}(s_i^+>s_j^-).
\]
Because the indicator is non-differentiable, the cited work replaces it with a squared-hinge surrogate,
\[
\ell_{\mathrm{hinge}}(s_i^+,s_j^-)
=
\max\bigl(0,\delta-(s_i^+-s_j^-)\bigr)^2,
\]
leading to
\[
\ell_{\mathrm{AUC}}
=
\frac{1}{N^+N^-}
\sum_{i:y_i=1}\sum_{j:y_j=0}
\max\bigl(0,\delta-(s_i^+-s_j^-)\bigr)^2.
\]
For multi-class keyword spotting, the network produces keyword-confidence scores \(p_{n,c}\), the positive-score set is
\[
S^+=\{p_{n,y_n}\mid y_n\in\{1,\dots,C\}\},
\]
and the negative-score set is
\[
S^- = S^-_1 \cup S^-_2,
\]
with
\[
S^-_1=\{\max_{c\neq y_n} p_{n,c}\}
\]
for keyword samples and
\[
S^-_2=\{\max_{c=1..C} p_{n,c}\}
\]
for non-keyword samples. The minibatch loss becomes
\[
\ell_{\mathrm{mAUC}}
=
\frac{1}{N^+N^-}
\sum_{s^+\in S^+}\sum_{s^-\in S^-}
\max\bigl(0,\delta-(s^+-s^-)\bigr)^2.
\]
The paper reports that \(\delta=0.3\) gave the best trade-off, and on Google Speech Commands v1 the multi-class AUC model with fixed-proportion sampling achieved total accuracy \(92.97\%\), closed accuracy \(97.22\%\), and macro-averaged \(F_1=0.9115\), compared with \(89.96\%\), \(97.14\%\), and \(0.8805\) for cross-entropy. On v2, the fixed-sampler mAUC model achieved \(94.71\%\), \(97.50\%\), and \(0.9312\), compared with \(92.74\%\), \(97.46\%\), and \(0.9068\) for cross-entropy [2107.05859].

Sequence-discriminative keyword spotting applies keyword awareness at the level of hypothesis risk. Classical Minimum Bayes-Risk training minimizes
\[
\mathcal{L}_{\mathrm{MBR}}^{(i)}
=
\sum_{j=1}^{J}
P(H_{ij}\mid \mathbf X_i)\,
R(H_{ij},R_i),
\]
but the keyword-specific specialization counts only `<kw>` errors. With \(K_{ij}^H\) the number of `<kw>` tokens in hypothesis \(H_{ij}\) and \(K_i^R\) the number in the reference,
\[
\mathrm{FP}_{ij}=\max(0,K_{ij}^H-K_i^R),\qquad
\mathrm{FN}_{ij}=\max(0,K_i^R-K_{ij}^H),
\]
and the risk is
\[
R(H_{ij},R_i)
=
\alpha\,\mathrm{FP}_{ij}
+
\beta\,\mathrm{FN}_{ij}\,K_i^R
+
\varepsilon.
\]
The total fine-tuning objective adds an RNN-T regularizer:
\[
\mathcal{L}
=
\sum_{i\in\mathcal B}
\left[
\sum_{j=1}^{J}
P(H_{ij}\mid \mathbf X_i)
\bigl(\alpha\,\mathrm{FP}_{ij}
+\beta\,\mathrm{FN}_{ij}\,K_i^R+\varepsilon\bigr)
-
\lambda \log P(Y_i\mid \mathbf X_i)
\right].
\]
In practice, beam size \(B=8\), top \(J=4\) hypotheses, learning rate \(10^{-5}\), \(\lambda=0.01\), \(\alpha=1.0\), \(\beta=1.0\), and \(\varepsilon=10^{-6}\) are used. At inference time, the utterance-level confidence is
\[
s(\mathbf X)=\max_t P(y_t=\langle kw\rangle \mid \mathbf X),
\]
and thresholding this score yields the detection decision. This formulation makes the loss directly sensitive to the two operational errors of keyword spotting—false accepts and false rejects—rather than to generic sequence mismatch [2211.06478].

## 4. Keyword-aware contrastive learning in cross-modal retrieval

In video moment retrieval and highlight detection, keyword-aware loss is introduced through context-dependent word weighting and two contrastive objectives. Let \(F^t\in\mathbb R^{n\times d}\) be word-level text features, \(F^{cv}\in\mathbb R^{c\times d}\) clustered video-context features, and \(\tau>0\) a temperature. The similarity matrix is
\[
M=\frac{F^t\cdot {F^{cv}}^T}{\|F^t\|\|F^{cv}\|}\in \mathbb R^{n\times c}.
\]
A column-wise softmax followed by max-pooling over clusters yields the per-word weight vector
\[
w^t = \max_k\bigl(\mathrm{softmax}(M/\tau)_{:,k}\bigr),
\]
and the keyword-weighted text features are
\[
F^{wt}=w^t\odot F^t.
\]
This assigns larger weights to words that are more discriminative under the overall video context [2501.02504].

The first contrastive term, the clip-keyword loss \(\mathcal L_{ck}\), aligns each clip feature with the aggregated keyword-weighted query representation. With clip-level video features \(F^v\in\mathbb R^{L\times d}\), aggregated weighted text embedding \(G_i^{Wt}=\mathrm{mean}_k[F_i^{wt}(k)]\), ground-truth moment indices \(R_i\subseteq\{1,\dots,L\}\), batch size \(B\), and cosine similarity \(\mathrm{Sim}(a,b)=a\cdot b/(\|a\|\|b\|)\),
\[
\mathcal L_{ck}
=
-\frac{1}{B}\sum_{i=1}^{B}
\log
\left[
\frac{\sum_{j\in R_i}\exp \mathrm{Sim}(F_i^v(j),G_i^{Wt})}
{\sum_{j=1}^{L}\exp \mathrm{Sim}(F_i^v(j),G_i^{Wt})}
\right].
\]
The second term, the video-keyword loss \(\mathcal L_{vk}\), uses a pooled positive video feature \(G_i^v=\mathrm{mean}_k[r_i^b(k)\cdot F_i^v(k)]\) and aligns it against the keyword-weighted query across the batch:
\[
\mathcal L_{vk}
=
-\frac{1}{B}\sum_{i=1}^{B}
\log
\left[
\frac{\exp \mathrm{Sim}(G_i^v,G_i^{Wt})}
{\sum_{j=1}^{B}\exp \mathrm{Sim}(G_j^v,G_i^{Wt})}
\right].
\]
The combined keyword-aware contrastive loss is
\[
\mathcal L_{kw}=\mathcal L_{ck}+\mathcal L_{vk},
\]
and the full training objective is
\[
\mathcal L_{Total}=\mathcal L_{mr}+\mathcal L_{hd}+\lambda_{kw}\mathcal L_{kw},
\]
with \(\lambda_{kw}=0.3\) [2501.02504].

The quantitative evidence is an ablation on the QVHighlights validation split. The baseline without \(\mathcal L_{ck}\) and \(\mathcal L_{vk}\) obtains \(R1@[0.5,0.7]=[66.90,49.94]\), \(\bar{mAP}=45.02\), HD-mAP \(=40.53\), and HIT@1 \(=65.48\). Adding only \(\mathcal L_{ck}\) gives \([67.74,51.16]\), \(46.37\), \(41.32\), and \(66.45\); adding only \(\mathcal L_{vk}\) gives \([67.16,51.42]\), \(46.76\), \(40.84\), and \(65.10\); adding both gives \([68.97,53.35]\), \(47.69\), \(41.67\), and \(67.03\). The summary states that adding either contrastive term yields a solid gain over the baseline and that combining both yields the largest improvement [2501.02504].

## 5. Contextual biasing and rare-word decoding

Keyword-aware loss also appears in contextual biasing, where the objective is not generic token prediction but targeted improvement on biased rare words. In the cited TCPGen-based formulation, \(U\) is the target sequence length, \(V\) the vocabulary size, and \(K\subseteq\{1,\dots,U\}\) the set of time-step indices at which a biased token occurs. At decoding step \(i\), the system has the original ASR model probability \(P^{mdl}(y_i=c)\), the pointer-network probability \(P^{ptr}(y_i=c)\) over a candidate set \(M_i\), and the interpolation probability \(P_i^{gen}\in(0,1)\) [2509.09197].

The first keyword-aware term is a masked cross-entropy on the pointer output:
\[
\ell_{ptr}
=
-\sum_{i=1}^{U}\mathbb 1(i\in K)
\sum_{c=1}^{V}\mathbb 1(y_i=c)\log P^{ptr}(y_i=c).
\]
The mask ensures that the pointer network is trained only at positions where a biased word actually occurs. The second term is a binary classification loss on the generation probability:
\[
\ell_{gen}
=
-\sum_{i=1}^{U}
\Bigl[
\alpha\cdot \mathbb 1(i\in K)\cdot \log P_i^{gen}
+
(1-\alpha)\cdot (1-\mathbb 1(i\in K))\cdot \log(1-P_i^{gen})
\Bigr].
\]
The combined loss is
\[
\ell_{total}=\ell_{ptr}+\ell_{gen}.
\]
No additional weighting between \(\ell_{ptr}\) and \(\ell_{gen}\) is used, and the only hyperparameter introduced is \(\alpha\), with \(\alpha=0.7\) reported to work well. The probability masking strategy further sets
\[
P(y_i=c)=P^{mdl}(y_i=c)
\]
for \(c\notin M_i\), removing the scaling factor \((1-P_i^{gen})\) outside the pointer set in order to avoid over-suppression of non-biased tokens [2509.09197].

The training pipeline freezes the encoder weights of the base ASR model and trains only TCPGen with \(\ell_{total}\), explicitly not using a standard ASR loss for TCPGen. On NSC-Part-2 with Whisper-small, the unadapted model has WER \(29.71\), B-WER \(54.03\), and U-WER \(17.21\). Fine-tuning on \(10\) hours of synthetic data yields WER \(15.00\), adding AGEM gives \(14.16\), standard TCPGen with ASR loss remains at \(14.16\), and TCPGen-2L with \(\ell_{ptr}+\ell_{gen}\) and \(\alpha=0.7\) achieves WER \(11.81\), B-WER \(20.74\), and U-WER \(7.22\). The abstract reports that adapting Whisper to \(10\) hours of synthetic data reduced the word error rate on the NSC Part 2 test set from \(29.71\%\) to \(11.81\%\) [2509.09197].

The \(\alpha\) ablation clarifies the operating trade-off. On the NSC development set, increasing \(\alpha\) from \(0.1\) to \(0.7\) raises FAR from \(0.08\) to \(9.59\) and TAR from \(16.9\) to \(67.9\), while reducing B-WER from \(60.0\) to \(37.9\). The summary states that as \(\alpha\) increases, the model fires more often, reducing B-WER but slightly increasing U-WER from over-biasing. This makes the loss interpretable in terms of “what to bias” and “when to bias,” rather than only end-task WER [2509.09197].

## 6. Relational formulations, misconceptions, and open boundaries of

Source: https://www.emergentmind.com/topics/keyword-aware-loss-function