<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.8.5">Jekyll</generator><link href="http://placebokkk.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="http://placebokkk.github.io/" rel="alternate" type="text/html" /><updated>2022-04-07T07:02:13+00:00</updated><id>http://placebokkk.github.io/feed.xml</id><title type="html">Chao Yang</title><subtitle>Notes on speech and programming</subtitle><entry><title type="html">Wenet网络设计与实现</title><link href="http://placebokkk.github.io/wenet/2021/06/04/asr-wenet-nn-1.html" rel="alternate" type="text/html" title="Wenet网络设计与实现" /><published>2021-06-04T02:00:00+00:00</published><updated>2021-06-04T02:00:00+00:00</updated><id>http://placebokkk.github.io/wenet/2021/06/04/asr-wenet-nn-1</id><content type="html" xml:base="http://placebokkk.github.io/wenet/2021/06/04/asr-wenet-nn-1.html">&lt;p&gt;&lt;strong&gt;如果觉得wenet还不错，点个star支持我们一下吧&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/wenet-e2e/wenet&quot;&gt;https://github.com/wenet-e2e/wenet&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;本文分为四部分&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;端到端语音识别基础&lt;/li&gt;
  &lt;li&gt;pytorch的实现介绍&lt;/li&gt;
  &lt;li&gt;进阶内容:mask&lt;/li&gt;
  &lt;li&gt;进阶内容:cache&lt;/li&gt;
&lt;/ul&gt;

&lt;ul class=&quot;table-of-content&quot; id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#第1节-端到端语音识别基础&quot; id=&quot;markdown-toc-第1节-端到端语音识别基础&quot;&gt;第1节: 端到端语音识别基础&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#ctc目标函数&quot; id=&quot;markdown-toc-ctc目标函数&quot;&gt;CTC目标函数&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#attention-based-encoder-decoder&quot; id=&quot;markdown-toc-attention-based-encoder-decoder&quot;&gt;Attention-based Encoder Decoder&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#联合建模&quot; id=&quot;markdown-toc-联合建模&quot;&gt;联合建模&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#神经网络类型&quot; id=&quot;markdown-toc-神经网络类型&quot;&gt;神经网络类型&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#流式语音识别&quot; id=&quot;markdown-toc-流式语音识别&quot;&gt;流式语音识别&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#第2节-wenet中的神经网络设计与实现&quot; id=&quot;markdown-toc-第2节-wenet中的神经网络设计与实现&quot;&gt;第2节: Wenet中的神经网络设计与实现&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#模型入口-asrmodel&quot; id=&quot;markdown-toc-模型入口-asrmodel&quot;&gt;模型入口 ASRModel&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#模型定义&quot; id=&quot;markdown-toc-模型定义&quot;&gt;模型定义&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#创建模型&quot; id=&quot;markdown-toc-创建模型&quot;&gt;创建模型&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#前向计算&quot; id=&quot;markdown-toc-前向计算&quot;&gt;前向计算&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#其他接口&quot; id=&quot;markdown-toc-其他接口&quot;&gt;其他接口&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#encoder网络&quot; id=&quot;markdown-toc-encoder网络&quot;&gt;Encoder网络&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#subsampling网络&quot; id=&quot;markdown-toc-subsampling网络&quot;&gt;Subsampling网络&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#encoder-block&quot; id=&quot;markdown-toc-encoder-block&quot;&gt;Encoder Block&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#attention-based-decoder网络&quot; id=&quot;markdown-toc-attention-based-decoder网络&quot;&gt;Attention based Decoder网络&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#ctc-loss&quot; id=&quot;markdown-toc-ctc-loss&quot;&gt;CTC Loss&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#attention-based-decoder-loss&quot; id=&quot;markdown-toc-attention-based-decoder-loss&quot;&gt;Attention based Decoder Loss&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#网络的完整结构&quot; id=&quot;markdown-toc-网络的完整结构&quot;&gt;网络的完整结构&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#第3节-进阶话题mask&quot; id=&quot;markdown-toc-第3节-进阶话题mask&quot;&gt;第3节: 进阶话题:Mask&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#问题1batch-padding&quot; id=&quot;markdown-toc-问题1batch-padding&quot;&gt;问题1:Batch Padding&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#处理padding对loss的影响&quot; id=&quot;markdown-toc-处理padding对loss的影响&quot;&gt;处理Padding对Loss的影响&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#处理模型输入padding&quot; id=&quot;markdown-toc-处理模型输入padding&quot;&gt;处理模型输入Padding&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#问题2-自回归&quot; id=&quot;markdown-toc-问题2-自回归&quot;&gt;问题2: 自回归&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#问题3-chunk-based-model&quot; id=&quot;markdown-toc-问题3-chunk-based-model&quot;&gt;问题3: Chunk-Based Model&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#encoder中的mask&quot; id=&quot;markdown-toc-encoder中的mask&quot;&gt;Encoder中的mask&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#subsampling中的mask&quot; id=&quot;markdown-toc-subsampling中的mask&quot;&gt;Subsampling中的mask&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#conformer-block中的conv的mask&quot; id=&quot;markdown-toc-conformer-block中的conv的mask&quot;&gt;Conformer Block中的Conv的mask&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#multiheadedattention-module的mask实现&quot; id=&quot;markdown-toc-multiheadedattention-module的mask实现&quot;&gt;MultiHeadedAttention Module的Mask实现&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#chunk-based-mask&quot; id=&quot;markdown-toc-chunk-based-mask&quot;&gt;Chunk-based mask&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#decoder中的mask&quot; id=&quot;markdown-toc-decoder中的mask&quot;&gt;Decoder中的mask&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#其他&quot; id=&quot;markdown-toc-其他&quot;&gt;其他&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#第4节-进阶话题cache&quot; id=&quot;markdown-toc-第4节-进阶话题cache&quot;&gt;第4节: 进阶话题:Cache&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#runtime流式解码&quot; id=&quot;markdown-toc-runtime流式解码&quot;&gt;Runtime流式解码&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#python流式解码&quot; id=&quot;markdown-toc-python流式解码&quot;&gt;Python流式解码&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#baseencoderforward_chunk分析&quot; id=&quot;markdown-toc-baseencoderforward_chunk分析&quot;&gt;BaseEncoder.forward_chunk()分析&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#offset&quot; id=&quot;markdown-toc-offset&quot;&gt;offset&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#subsampling内部&quot; id=&quot;markdown-toc-subsampling内部&quot;&gt;subsampling内部&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#subsampling_cache&quot; id=&quot;markdown-toc-subsampling_cache&quot;&gt;subsampling_cache&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#elayers_output_cache&quot; id=&quot;markdown-toc-elayers_output_cache&quot;&gt;elayers_output_cache&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#conformer_cnn_cache&quot; id=&quot;markdown-toc-conformer_cnn_cache&quot;&gt;conformer_cnn_cache&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;第1节-端到端语音识别基础&quot;&gt;第1节: 端到端语音识别基础&lt;/h2&gt;

&lt;p&gt;语音识别任务中，输入是语音，输出是文本，其特点在于两个序列不等长，但在时序上有同步性。传统语音识别通过HMM来建模输出和输入不等长和时序同步性，并对音素，词典，语言模型分层次建模。&lt;/p&gt;

&lt;p&gt;在传统的HMM框架里，声学模型往往在三音素的hmm状态级别建模，与语言模型分开建模训练，在训练时，任务的整体目标会被割裂成多个训练目标。
另外，传统的HMM框架框架的模型训练会涉及到很多过程，包括上下文相关音素，音素聚类，HMM-GMM训练，强制对齐等，非常繁琐。因此，传统的HMM框架在性能和易用性上都存在不足。&lt;/p&gt;

&lt;p&gt;下面是一个HMM-DNN模型的训练过程，仅用于说明训练过程的复杂，具体内容可以不看。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;1.对于每个句子扩展为单音素序列，用前向后向EM训练，得到单因素的hmm-单高斯model1。
2.用model1对句子做对齐，单高斯进行2倍分裂，更新模型，迭代这个对齐/分裂的过程n次，得到单因素的hmm-gmm模型model2.
3.用model2对句子做对齐，将音素根据上下文扩展为三音素，使用单高斯学习每个音素的决策树，，最后每个叶子结点对应一个单高斯. 得到一个三音素-hmm-单高斯模型model3
4.类似于第2步，用model3不停迭代分裂高斯，得到三音素hmm-gmm的model4
5. model4对句子做对齐，对齐数据用于帧级别NN训练.
...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;一般在传统HMM框架下，会先利用HMM-GMM模型，通过对齐的方式，得到帧级别的对应标注，再通过帧级别损失函数来优化神经网络模型，
不过这也不是必须的，HMM框架也可以不做帧对齐，比如论文End-to-end speech recognition using lattice-free MMI中直接进行训练。&lt;/p&gt;

&lt;p&gt;近几年，基于神经网络的端到端建模方式则更佳简洁&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;直接以目标单元作为建模对象，比如中文使用&lt;code class=&quot;highlighter-rouge&quot;&gt;字&lt;/code&gt;，英文使用&lt;code class=&quot;highlighter-rouge&quot;&gt;字符&lt;/code&gt;或者&lt;code class=&quot;highlighter-rouge&quot;&gt;BPE&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;通过特殊的模型（目标函数），处理输入输出对齐未知的问题。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;这类端到端模型常用的建模方式分两类: 基于CTC目标函数和基于Attention-Encoder-Decoder结构的模型。在这两种框架下，可以选用各种不同的类型神经网络。比如DNN，RNN，CNN，Self-Attention。&lt;/p&gt;

&lt;h3 id=&quot;ctc目标函数&quot;&gt;CTC目标函数&lt;/h3&gt;

&lt;p&gt;传统语音识别通过HMM来约束输出和输入的对齐方式（时间上保持单调），CTC其实也是一种特殊的HMM约束，可以处理输入输出间的不等长和时序同步约束。&lt;/p&gt;

&lt;p&gt;CTC本质上对所有合法的输出和输入对齐方式进行了穷举，所谓合法，即对齐后的输出序列能够按CTC规则规约得到的原标注序列，则为合法对齐。&lt;/p&gt;

&lt;p&gt;使用CTC目标函数会引入一个blank的输出单元，CTC规约规则为：&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;连续的相同字符进行合并&lt;/li&gt;
  &lt;li&gt;移除blank字符&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;一个例子：&lt;/p&gt;

&lt;p&gt;某段语音数据，输入帧数为7帧（此处仅用于举例），原始的标注序列为“出门问问”，是4个字，但是网络的输出和输入一一对应，因此需要输出7个单元。CTC模型中，通过对原标注内的4个单元进行重复和插入blank来扩展为7个单元，下面两种都是可能的扩展序列，其中&lt;code class=&quot;highlighter-rouge&quot;&gt;-&lt;/code&gt;为blank，如果扩展序列通过CTC规则规约可以得到原标注序列，则此扩展序列称为合法对齐序列。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;出-门问问-问  -&amp;gt; 出门问问
出-门--问问 -&amp;gt; 出门问
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;第一个对齐序列&lt;code class=&quot;highlighter-rouge&quot;&gt;出-门问问-问&lt;/code&gt;是合法对齐序列，第二个对齐序列&lt;code class=&quot;highlighter-rouge&quot;&gt;出-门--问问&lt;/code&gt;不是合法对齐序列。&lt;/p&gt;

&lt;p&gt;除了&lt;code class=&quot;highlighter-rouge&quot;&gt;出-门问问-问&lt;/code&gt;还有很多其他合法序列，比如&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;出出门问问-问
出出出门问-问
出-门-问-问
出--门问-问
...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;CTC目标函数的思想是: 既然不知道哪种对齐关系是正确的，那就最大化所有合法CTC对齐的概率之和。所以对于这个样本，目标就是最大化如下概率。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;P(出门问问|X) = P(出-门问问-问|X) + P(出出门问问-问|X)
              + P(出出出门问-问|X)+ ... + P(出--门问-问|X)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;求这个目标函数梯度的一种方式是穷举所有的有效CTC对齐，分别求梯度相加。但是这种方法复杂度太高。由于CTC本身结构特点，存在一种更高效的动态规划算法，可以极大的提升速度。具体可参考论文 &lt;a href=&quot;http://www.cs.toronto.edu/~graves/icml_2006.pdf&quot;&gt;CTC-paper&lt;/a&gt; 和文章&lt;a href=&quot;http://placebokkk.github.io/asr/2020/01/13/asr-ctc-eesen.html&quot;&gt;Eesen中的CTC实现&lt;/a&gt;。&lt;/p&gt;

&lt;p&gt;解码时，模型对每一个输入帧都给出输出，这种解码方法称为&lt;code class=&quot;highlighter-rouge&quot;&gt;Frame同步&lt;/code&gt;解码。若某些帧输出为blank或者和前一帧是重复的字符，则可以合并。&lt;/p&gt;

&lt;p&gt;由于在训练时，穷举的所有CTC扩展序列中blank占的个数最多，因此模型会倾向于学习到去输出尽量多的blank字符，也就是尽可能少的非blank字符，从而解码序列中往往每个非blank字符只输出一次，这个叫做CTC的尖峰效应。&lt;/p&gt;

&lt;p&gt;学习CTC的优秀材料：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://distill.pub/2017/ctc/&quot;&gt;Sequence Modeling With CTC&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.bilibili.com/video/BV1hZ4y1w7j1?p=4&quot;&gt;李宏毅老师-人类语言处理课程&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;attention-based-encoder-decoder&quot;&gt;Attention-based Encoder Decoder&lt;/h3&gt;

&lt;p&gt;Attention-based Encoder Decoder简称AED，也叫Seq2Seq框架，在ASR领域里，该框架也叫做LAS（Listen, Attend and Spell）。&lt;/p&gt;

&lt;p&gt;模型中的encoder对输入序列（语音）进行信息提取，decoder则是一个在目标序列（文本）上的自回归模型（输入之前的单元，预测下一个单元），同时在自回归计算时，通过attention方式去获取encoder的输出编码信息，从而能够利用到输入序列的信息。&lt;/p&gt;

&lt;p&gt;这种建模方式，可以不必显示建模输出和输入之间的对齐关系，而是利用attention机制交给网络去学习出隐含的对齐。相比如CTC，AED允许输入输出单元之间存在时序上的交换，因此特别适用于机器翻译这种任务。但是对于语音识别或者语音合成这些存在时序单调性的任务，这种无约束反而会带来一些问题。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AED的解码&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;解码时，不需要对每一个输入帧都进行输出，而是根据整个输入序列信息和已输出信息进行下一次输出，直到输出一个特殊结束字符。
这种解码方法称为&lt;code class=&quot;highlighter-rouge&quot;&gt;Label同步&lt;/code&gt;解码。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;多说一句&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;CTC没有显示构建文本之间的关系，RNN-t模型是一种显示建模了文本关系的帧同步解码的模型。&lt;/p&gt;

&lt;p&gt;标准的AED中，decoder和encoder之间cross-attention需要看到encoder的完整序列，所以无法进行流式识别。可利用GMM-attention/Mocha/MMA等单调递进的局部Attention方法进行改进。&lt;/p&gt;

&lt;h3 id=&quot;联合建模&quot;&gt;联合建模&lt;/h3&gt;

&lt;p&gt;研究者发现，联合使用CTC loss和AED可以有效的加速训练收敛，同时得到更好的识别结果。目前这个方法已经成为端到端学习的标准方案。&lt;/p&gt;

&lt;p&gt;在解码时，同时使用CTC和AED的输出，可以提高识别率，但是由于AED本身是非流式的解码，在Wenet中，则没采用联合解码的方式，而是采用了先使用CTC解码，再用AED对CTC的Nbest结果进行Rescoring，这样即结合了两种模型的效果，又可以应用于流式场景。&lt;/p&gt;

&lt;h3 id=&quot;神经网络类型&quot;&gt;神经网络类型&lt;/h3&gt;

&lt;p&gt;常用的神经网络类型包括DNN，CNN，RNN，Self-attention等，这些方法进行组合，衍生出了各种模型，Wenet中，对于encoder网络部分，支持Transformer和Conformer两种网络。decoder网络部分，支持Transformer网络。&lt;/p&gt;

&lt;p&gt;Transformer由多个Transformer Block堆叠，每个Block中会使用self-attention，res，relu，ff层。&lt;/p&gt;

&lt;p&gt;Conformer由多个Conformer Block堆叠，每个Block中会使用conv，self-attention，res，relu，ff层。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;降采样/降帧率&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;输入序列越长，即帧的个数越多，网络计算量就越大。而在语音识别中，一定时间范围内的语音信号是相似的，多个连续帧对应的是同一个发音，另外，端到端语音识别使用建模单元一般是一个时间延续较长的单元（粗粒度），比如建模单元是一个中文汉字，假如一个汉字用时0.2s，0.2s对应20帧，如果将20帧的信息进行合并，比如合并为5帧，在进行帧同步输出时不会出现丢字问题，同时还可以线性的减少后续encoder网络的前向计算、CTC loss和AED计算cross attention时的开销。&lt;/p&gt;

&lt;p&gt;可以用不同的神经网络来进行降采样，Wenet中使用的是2D-CNN。&lt;/p&gt;

&lt;h3 id=&quot;流式语音识别&quot;&gt;流式语音识别&lt;/h3&gt;

&lt;p&gt;虽然CTC解码是&lt;code class=&quot;highlighter-rouge&quot;&gt;Frame同步&lt;/code&gt;的，但若需要支持低延迟的流式识别，Encoder中的计算对右侧的依赖不能太长。标准的Fully self-attention会依赖整个序列，不能进行流式计算，因此wenet采用了基于chunk的attention，将序列划分为多个固定大小的chunk，每个chunk内部的帧不会依赖于chunk右侧的帧。&lt;/p&gt;

&lt;p&gt;另一方面，连续堆叠的convolution层会带来较大的右侧依赖，wenet则采用了因果卷积来避免convolution层的右侧依赖。&lt;/p&gt;

&lt;h2 id=&quot;第2节-wenet中的神经网络设计与实现&quot;&gt;第2节: Wenet中的神经网络设计与实现&lt;/h2&gt;

&lt;p&gt;前文介绍了端到端神经网络的基本知识，本文介绍Wenet中的设计与实现。&lt;/p&gt;

&lt;p&gt;Wenet的代码借鉴了Espnet等开源项目，由于完全专注于语音识别和工业方案，代码非常简洁，但是为了实现基于chunk的流式解码，以及处理batch内不等长序列，仍然包含的一些实现技巧，比如cache和mask，这使得一些代码在初次阅读时不易理解，可在第一步学习代码时略过相关内容。&lt;/p&gt;

&lt;p&gt;核心模型的代码位于&lt;code class=&quot;highlighter-rouge&quot;&gt;wenet/transformer/&lt;/code&gt;目录&lt;/p&gt;

&lt;h3 id=&quot;模型入口-asrmodel&quot;&gt;模型入口 ASRModel&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;wenet/transformer/asr_model.py&lt;/strong&gt;&lt;/p&gt;

&lt;h4 id=&quot;模型定义&quot;&gt;模型定义&lt;/h4&gt;
&lt;p&gt;使用pytorch Module构建神经网络时，在init中定义用到的子模块&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class ASRModel(torch.nn.Module)
def __init__():
    self.encoder = encoder 
    self.decoder = decoder
    self.ctc = ctc
    self.criterion_att = LabelSmoothingLoss(...）# AED的loss
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;ASRModel的init中定义了encoder, decoder, ctc, criterion_att几个基本模块。其整体网络拓扑如下图所示。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;encoder是Shared Encoder，其中也包括了Subsample网络。&lt;/li&gt;
  &lt;li&gt;decoder是Attention-based Decoder网络&lt;/li&gt;
  &lt;li&gt;ctc是ctc Decoder网络（该decoder结构很简单，仅仅是前向网络和softmax）和ctc loss&lt;/li&gt;
  &lt;li&gt;criterion_att是Attention-based Decoder对应的自回归似然loss，实际是一个LabelSmoothing的loss。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wenet/train-arch.png&quot; alt=&quot;train-arch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;ASRModel中的模块又有自己的子模块，可以通过print打印出完整的模型结构。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ASRModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(...)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;创建模型&quot;&gt;创建模型&lt;/h4&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def init_asr_model(config):
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;该方法根据传入的config，创建一个ASRModel实例。 config内容由训练模型时使用的yaml文件提供。这个创建仅仅是构建了一个初始模型，其参数是随机的，可以通过 &lt;code class=&quot;highlighter-rouge&quot;&gt;model.load_state_dict(checkpoint)&lt;/code&gt;从训练好的模型中加载参数。&lt;/p&gt;

&lt;h4 id=&quot;前向计算&quot;&gt;前向计算&lt;/h4&gt;
&lt;p&gt;pytorch框架下，只需定义模型的前向计算forword,。对于每个Module，可以通过阅读forward代码来学习其具体实现。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class ASRModel(torch.nn.Module):
  def forward()
    ...
    # Encoder
    encoder_out, encoder_mask = self.encoder(speech, speech_lengths)
    encoder_out_lens = encoder_mask.squeeze(1).sum(1)

    # Attention-decoder
    loss_att, acc_att = self._calc_att_loss(encoder_out, encoder_mask,
                                              text, text_lengths)
    # CTC
    loss_ctc = self.ctc(encoder_out, encoder_out_lens, text,text_lengths)
    loss = self.ctc_weight * loss_ctc + (1 -self.ctc_weight) * loss_att
    ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;其他接口&quot;&gt;其他接口&lt;/h4&gt;

&lt;p&gt;ASRModel除了定义模型结构和实现前向计算用于训练外，还有两个功能：&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;提供多种python的解码接口&lt;/li&gt;
  &lt;li&gt;提供runtime中需要使用的接口。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;python解码接口&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;recognize() # attention decoder
attention_rescoring() # CTC + attention rescoring
ctc_prefix_beam_search() # CTC prefix beamsearch
ctc_greedy_search() # CTC greedy search
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;用于Runtime的接口, 这些接口均有@torch.jit.export注解，可以在C++中调用&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;subsampling_rate()
right_context()
sos_symbol()
eos_symbol()
forward_encoder_chunk()
forward_attention_decoder()
ctc_activation()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;其中比较重要的是:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_attention_decoder()&lt;/code&gt; Attention Decoder的序列forward计算，非自回归模式。&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;ctc_activation()&lt;/code&gt; CTC Decoder forward计算&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_encoder_chunk()&lt;/code&gt; 基于chunk的Encoder forward计算&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;初学者可以先仅关注训练时使用的forward()函数。&lt;/p&gt;

&lt;h3 id=&quot;encoder网络&quot;&gt;Encoder网络&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;wenet/transformer/encoder.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Wenet的encoder支持Transformer和Conformer两种网络结构，实现时使用了模版方法的设计模式进代码复用。BaseEncoder中定义了如下统一的前向过程，由TransformerEncoder，ConformerEncoder继承BaseEncoder后分别定义各自的self.encoders的结构。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class BaseEncoder(torch.nn.Module):
  def forward(...):
      xs, pos_emb, masks = self.embed(xs, masks)
      chunk_masks = add_optional_chunk_mask(xs, ..)
      for layer in self.encoders:
          xs, chunk_masks, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
      if self.normalize_before:
          xs = self.after_norm(xs)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;可以看到Encoder分为两大部分&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;self.embed是Subsampling网络&lt;/li&gt;
  &lt;li&gt;self.encoders是一组相同结构网络（Encoder Blocks）的堆叠&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;除了forward，Encoder还实现了两个方法，此处不展开介绍。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_chunk_by_chunk&lt;/code&gt;，python解码时，模拟流式解码模式基于chunk的前向计算。&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_chunk&lt;/code&gt;, 单次基于chunk的前向计算，通过ASRModel导出为&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_encoder_chunk()&lt;/code&gt;供runtime解码使用。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;下面先介绍Subsampling部分，再介绍Encoder Block&lt;/p&gt;

&lt;h4 id=&quot;subsampling网络&quot;&gt;Subsampling网络&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;wenet/transformer/subsampling.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;前文已经介绍了降采样或者降帧率的目的。这里不再重述。&lt;/p&gt;

&lt;p&gt;语音任务里有两种使用CNN的方式，一种是2D-Conv，一种是1D-Conv：&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;2D-Conv: 输入数据看作是深度(通道数）为1，高度为F（Fbank特征维度，idim），宽度为T（帧数）的一张图.&lt;/li&gt;
  &lt;li&gt;1D-Conv: 输入数据看作是深度(通道数）为F（Fbank特征维度)，高度为1，宽度为T（帧数）的一张图.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Kaldi中著名的TDNN就是是1D-Conv，在Wenet中采用2D-Conv来实现降采样。&lt;/p&gt;

&lt;p&gt;Wenet中提供了多个降采样的网络，这里选择把帧率降低4倍的网络&lt;code class=&quot;highlighter-rouge&quot;&gt;Conv2dSubsampling4&lt;/code&gt;来说明。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class Conv2dSubsampling4(BaseSubsampling):
    def __init__(self, idim: int, odim: int, dropout_rate: float,
                 pos_enc_class: torch.nn.Module):
        &quot;&quot;&quot;Construct an Conv2dSubsampling4 object.&quot;&quot;&quot;
        super().__init__()
        self.conv = torch.nn.Sequential(
            torch.nn.Conv2d(1, odim, 3, 2),
            torch.nn.ReLU(),
            torch.nn.Conv2d(odim, odim, 3, 2),
            torch.nn.ReLU(),
        )
        self.out = torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim)
        self.pos_enc = pos_enc_class
        # The right context for every conv layer is computed by:
        # (kernel_size - 1) / 2 * stride  * frame_rate_of_this_layer
        self.subsampling_rate = 4
        # 6 = (3 - 1) / 2 * 2 * 1 + (3 - 1) / 2 * 2 * 2
        self.right_context = 6
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;我们可以把一个语音帧序列[T,D]看作宽是T，高是D，深度为1的图像。&lt;code class=&quot;highlighter-rouge&quot;&gt;Conv2dSubsampling4&lt;/code&gt;通过两个&lt;code class=&quot;highlighter-rouge&quot;&gt;stride=2&lt;/code&gt;的2d-CNN，把图像的宽和高都降为1/4. 因为图像的宽即是帧数，所以帧数变为1/4.&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;torch.nn.Conv2d(1, odim, kernel_size=3, stride=2)
torch.nn.Conv2d(odim, odim, kernel_size=3, stride=2)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;具体的实现过程&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def forward(...):
    x = x.unsqueeze(1)  # (b, c=1, t, f)
    x = self.conv(x)
    b, c, t, f = x.size()
    x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))
    x, pos_emb = self.pos_enc(x, offset)
    return x, pos_emb, x_mask[:, :, :-2:2][:, :, :-2:2]

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;x = x.unsqueeze(1)  # (b, c=1, t, f) 增加channel维，以符合2dConv需要的数据格式。&lt;/li&gt;
  &lt;li&gt;conv(x)中进行两次卷积，此时t维度约等于原来的1/4，因为没加padding，实际上是从长度T变为长度((T-1)/2-1)/2）。注意经过卷积后深度不再是1。&lt;/li&gt;
  &lt;li&gt;view(b, t, c * f) 将深度和高度合并平铺到同一维，然后通过self.out(）对每帧做Affine变换.&lt;/li&gt;
  &lt;li&gt;pos_enc(x, offset) 经过subsampling之后，帧数变少了，此时再计算Positional Eembedding。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;在纯self-attention层构建的网络里，为了保证序列的顺序不可变性而引入了PE，从而交换序列中的两帧，输出会不同。但是由于subsampling的存在，序列本身已经失去了交换不变性，所以其实PE可以省去。&lt;/p&gt;

&lt;p&gt;x_mask是原始帧率下的记录batch各序列长度的mask，在计算attention以及ctc loss时均要使用，现在帧数降低了，x_mask也要跟着变化。&lt;/p&gt;

&lt;p&gt;返回独立的pos_emb，是因为在relative position attention中，需要获取relative pos_emb的信息。在标准attention中该返回值不会被用到。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wenet/subsampling.png&quot; alt=&quot;subsampling&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;上下文依赖&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;注意Conv2dSubsampling4中的这两个变量。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;self.subsampling_rate = 4
self.right_context = 6
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;这两个变量都在asr_model中进行了导出，在runtime时被使用，他们的含义是什么？&lt;/p&gt;

&lt;p&gt;在CTC或者WFST解码时，我们是一帧一帧解码，这里的帧指的是subsample之后的帧。我们称为解码帧，而模型输入的帧序列里的帧（subsample之前的）称为原始语音帧。&lt;/p&gt;

&lt;p&gt;在图里可以看到&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;第1个解码帧，需要依赖第1到第7个原始语音帧。&lt;/li&gt;
  &lt;li&gt;第2个解码帧，需要依赖第5到第11个原始语音帧。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;subsampling_rate: 对于相邻两个解码帧，在原始帧上的间隔。&lt;/p&gt;

&lt;p&gt;right_context: 对于某个解码帧，其对应的第一个原始帧的右侧还需要额外依赖多少帧，才能获得这个解码帧的全部信息。&lt;/p&gt;

&lt;p&gt;在runtime decoder中，每次会送入一组帧进行前向计算并解码，一组（chunk）帧是定义在解码帧级别的，在处理第一个chunk时，接受输入获得当前chunk需要的所有的context，之后每次根据chunk大小和subsampling_rate获取新需要的原始帧。比如，chunk_size=1，则第一个chunk需要1-7帧，第二个chunk只要新拿到8-11帧即可。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# runtime/core/decoder/torch_asr_decoder.cc
TorchAsrDecoder::AdvanceDecoding()
    if (!start_) {                      // First chunk
      int context = right_context + 1;  // Add current frame
      num_requried_frames = (opts_.chunk_size - 1) * subsampling_rate + context;
    } else {
      num_requried_frames = opts_.chunk_size * subsampling_rate;
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;encoder-block&quot;&gt;Encoder Block&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;wenet/transformer/encoder_layer.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;对于Encoder, Wenet提供了Transformer和Conformer两种结构，Conformer在Transformer里引入了卷积层，是目前语音识别任务效果最好的模型之一。
强烈建议阅读这篇文章 &lt;a href=&quot;https://nlp.seas.harvard.edu/2018/04/03/attention.html&quot;&gt;The Annotated Transformer&lt;/a&gt;, 了解Transformer的结构和实现。&lt;/p&gt;

&lt;p&gt;Transformer的self.encoders由一组TransformerEncoderLayer组成&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;self.encoders = torch.nn.ModuleList([
    TransformerEncoderLayer(
        output_size,
        MultiHeadedAttention(attention_heads, output_size,
                              attention_dropout_rate),
        PositionwiseFeedForward(output_size, linear_units,
                                dropout_rate), dropout_rate,
        normalize_before, concat_after) for _ in range(num_blocks)
])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Conformer的self.encoders由一组ConformerEncoderLayer组成&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;self.encoders = torch.nn.ModuleList([
    ConformerEncoderLayer(
        output_size,
        RelPositionMultiHeadedAttention(*encoder_selfattn_layer_args),
        PositionwiseFeedForward(*positionwise_layer_args),
        PositionwiseFeedForward(*positionwise_layer_args)
        if macaron_style else None,
        ConvolutionModule(*convolution_layer_args)
        if use_cnn_module else None,
        dropout_rate,
        normalize_before,
        concat_after,
    ) for _ in range(num_blocks)
])

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;仅介绍ConformerEncoderLayer，其涉及的主要模块有：&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;RelPositionMultiHeadedAttention&lt;/li&gt;
  &lt;li&gt;PositionwiseFeedForward&lt;/li&gt;
  &lt;li&gt;ConvolutionModule&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;conformer论文中conformer block的结构如图&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wenet/conformer.png&quot; alt=&quot;conformer&quot; /&gt;&lt;/p&gt;

&lt;p&gt;如果不考虑cache，使用normalize_before=True，feed_forward_macaron=True，则wenet中的ConformerEncoderLayer的forward可以简化为&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class ConformerEncoderLayer(nn.Module):
    def forward(...):
        residual = x
        x = self.norm_ff_macaron(x)
        x = self.feed_forward_macaron(x)
        x = residual + 0.5 * self.dropout(x)

        residual = x
        x = self.norm_mha(x)
        x_att = self.self_attn(x, x, x, pos_emb, mask)
        x = residual + self.dropout(x_att)

        residual = x
        x = self.norm_conv(x)
        x, new_cnn_cache = self.conv_module(x, mask_pad, cnn_cache)
        x = residual + self.dropout(x)

        residual = x
        x = self.norm_ff(x)
        x = self.feed_forward(x)
        x = residual + 0.5 * self.dropout(x)

        x = self.norm_final(x)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;可以看到，对于RelPositionMultiHeadedAttention，ConvolutionModule，PositionwiseFeedForward，都是前有Layernorm，后有Dropout，再搭配Residual。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conformer Block - RelPositionMultiHeadedAttention&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;wenet/transformer/attention.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;attention.py中提供了两种attention的实现，&lt;code class=&quot;highlighter-rouge&quot;&gt;MultiHeadedAttention&lt;/code&gt;和&lt;code class=&quot;highlighter-rouge&quot;&gt;RelPositionMultiHeadedAttention&lt;/code&gt;。&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;MultiHeadedAttention&lt;/code&gt;用于Transformer。&lt;code class=&quot;highlighter-rouge&quot;&gt;RelPositionMultiHeadedAttention&lt;/code&gt;用于Conformer。&lt;/p&gt;

&lt;p&gt;原始的Conformer论文中提到的self-attention是Relative Position Multi Headed Attention，这是transformer-xl中提出的一种改进attention，和标准attention的区别在于，其中显示利用了相对位置信息，具体原理和实现可参考文章。 &lt;a href=&quot;https://zhuanlan.zhihu.com/p/344604604&quot;&gt;Conformer ASR中的Relative Positional Embedding&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;注意，wenet中实现的Relative Position Multi Headed Attention是存在问题的, 但是由于采用正确的实现并没有什么提升，就没有更新成transformer-xl中实现。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conformer Block - PositionwiseFeedForward&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;wenet/transformer/positionwise_feed_forward.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;PositionwiseFeedForward，对各个帧时刻输入均使用同一个矩阵权重去做前向Affine计算，即通过一个[H1, H2]的的前向矩阵，把[B, T, H1]变为[B，T，H2]。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conformer Block - ConvolutionModule&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;wenet/transformer/convolution.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ConvolutionModule结构如下&lt;/p&gt;

&lt;p&gt;Wenet中使用了因果卷积(Causal Convolution)，即不看右侧上下文，这样无论模型含有多少卷积层，对右侧的上下文都无依赖。&lt;/p&gt;

&lt;p&gt;原始的对称卷积，如果不进行左右padding，则做完卷积后长度会减小。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wenet/casual-conv.png&quot; alt=&quot;casual-conv&quot; /&gt;&lt;/p&gt;

&lt;p&gt;因此标准的卷积，为了保证卷积后序列长度一致，需要在左右各pad长度为(kernel_size - 1) // 2的 0.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  if causal: # 使用因果卷积
    padding = 0 # Conv1D函数设置的padding长度
    self.lorder = kernel_size - 1 # 因果卷积左侧手动padding的长度
  else: # 使用标准卷积
    # kernel_size should be an odd number for none causal convolution
    assert (kernel_size - 1) % 2 == 0
    padding = (kernel_size - 1) // 2 # Conv1D函数设置的padding长度
    self.lorder = 0
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;因果卷积的实现其实很简单，只在左侧pad长度为kernel_size - 1的0，即可实现。如图所示。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;if self.lorder &amp;gt; 0:
  if cache is None:
    x = nn.functional.pad(x, (self.lorder, 0), 'constant', 0.0)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;attention-based-decoder网络&quot;&gt;Attention based Decoder网络&lt;/h3&gt;

&lt;p&gt;对于Attention based Decoder, Wenet提供了自回归Transformer和双向自回归Transformer结构。 所谓自回归，既上一时刻的网络输出要作为网络当前时刻的输入，产生当前时刻的输出。&lt;/p&gt;

&lt;p&gt;在ASR整个任务中，Attention based Decoder的输入是当前已经产生的文本，输出接下来要产生的文本，因此这个模型建模了语言模型的信息。&lt;/p&gt;

&lt;p&gt;这种网络在解码时，只能依次产生输出，而不能一次产生整个输出序列。&lt;/p&gt;

&lt;p&gt;和Encoder中的attention层区别在于，Decoder网络里每层DecoderLayer，除了进行self attention操作(self.self_attn)，也和encoder的输出进行cross attention操作(self.src_attn)&lt;/p&gt;

&lt;p&gt;另外在实现上，由于自回归和cross attention，mask的使用也和encoder有所区别。&lt;/p&gt;

&lt;h3 id=&quot;ctc-loss&quot;&gt;CTC Loss&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;wenet/transformer/ctc.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;CTC Loss包含了CTC decoder和CTC loss两部分，CTC decoder仅仅对Encoder做了一次前向线性计算，然后计算softmax.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    # hs_pad: (B, L, NProj) -&amp;gt; ys_hat: (B, L, Nvocab)
    ys_hat = self.ctc_lo(F.dropout(hs_pad, p=self.dropout_rate))
    # ys_hat: (B, L, D) -&amp;gt; (L, B, D)
    ys_hat = ys_hat.transpose(0, 1)
    ys_hat = ys_hat.log_softmax(2)
    loss = self.ctc_loss(ys_hat, ys_pad, hlens, ys_lens)
    # Batch-size average
    loss = loss / ys_hat.size(1)
    return loss
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;CTC loss的部分则直接使用的torch提供的函数 &lt;code class=&quot;highlighter-rouge&quot;&gt;torch.nn.CTCLoss&lt;/code&gt;.&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    self.ctc_loss = torch.nn.CTCLoss(reduction=reduction_type)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;attention-based-decoder-loss&quot;&gt;Attention based Decoder Loss&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;wenet/transformer/label_smoothing_loss.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Attention-based Decoder的Loss是在最大化自回归的概率，在每个位置计算模型输出概率和样本标注概率的Cross Entropy。这个过程采用teacher forcing的方式，而不采用scheduled sampling。&lt;/p&gt;

&lt;p&gt;每个位置上，样本标注概率是一个one-hot的表示，既真实的标注概率为1，其他概率为0. Smoothing Loss中，对于样本标注概率，将真实的标注概率设置为1-e，其他概率设为e/(V-1)。&lt;/p&gt;

&lt;h3 id=&quot;网络的完整结构&quot;&gt;网络的完整结构&lt;/h3&gt;
&lt;p&gt;通过&lt;code class=&quot;highlighter-rouge&quot;&gt;print()&lt;/code&gt;打印出的&lt;code class=&quot;highlighter-rouge&quot;&gt;ASRModel&lt;/code&gt;的网络结构。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;ASRModel(
  (encoder): ConformerEncoder(
    (global_cmvn): GlobalCMVN()
    (embed): Conv2dSubsampling4(
      (conv): Sequential(
        (0): Conv2d(1, 256, kernel_size=(3, 3), stride=(2, 2))
        (1): ReLU()
        (2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2))
        (3): ReLU()
      )
      (out): Sequential(
        (0): Linear(in_features=4864, out_features=256, bias=True)
      )
      (pos_enc): RelPositionalEncoding(
        (dropout): Dropout(p=0.1, inplace=False)
      )
    )
    (after_norm): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
    (encoders): ModuleList(
      (0): ConformerEncoderLayer(
        (self_attn): RelPositionMultiHeadedAttention(
          (linear_q): Linear(in_features=256, out_features=256, bias=True)
          (linear_k): Linear(in_features=256, out_features=256, bias=True)
          (linear_v): Linear(in_features=256, out_features=256, bias=True)
          (linear_out): Linear(in_features=256, out_features=256, bias=True)
          (dropout): Dropout(p=0.0, inplace=False)
          (linear_pos): Linear(in_features=256, out_features=256, bias=False)
        )
        (feed_forward): PositionwiseFeedForward(
          (w_1): Linear(in_features=256, out_features=2048, bias=True)
          (activation): Swish()
          (dropout): Dropout(p=0.1, inplace=False)
          (w_2): Linear(in_features=2048, out_features=256, bias=True)
        )
        (feed_forward_macaron): PositionwiseFeedForward(
          (w_1): Linear(in_features=256, out_features=2048, bias=True)
          (activation): Swish()
          (dropout): Dropout(p=0.1, inplace=False)
          (w_2): Linear(in_features=2048, out_features=256, bias=True)
        )
        (conv_module): ConvolutionModule(
          (pointwise_conv1): Conv1d(256, 512, kernel_size=(1,), stride=(1,))
          (depthwise_conv): Conv1d(256, 256, kernel_size=(15,), stride=(1,), groups=256)
          (norm): LayerNorm((256,), eps=1e-05, elementwise_affine=True)
          (pointwise_conv2): Conv1d(256, 256, kernel_size=(1,), stride=(1,))
          (activation): Swish()
        )
        (norm_ff): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
        (norm_mha): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
        (norm_ff_macaron): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
        (norm_conv): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
        (norm_final): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
        (dropout): Dropout(p=0.1, inplace=False)
        (concat_linear): Linear(in_features=512, out_features=256, bias=True)
      )
      ...
    )
  )
 (decoder): TransformerDecoder(
    (embed): Sequential(
      (0): Embedding(4233, 256)
      (1): PositionalEncoding(
        (dropout): Dropout(p=0.1, inplace=False)
      )
    )
    (after_norm): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
    (output_layer): Linear(in_features=256, out_features=4233, bias=True)
    (decoders): ModuleList(
      (0): DecoderLayer(
        (self_attn): MultiHeadedAttention(
          (linear_q): Linear(in_features=256, out_features=256, bias=True)
          (linear_k): Linear(in_features=256, out_features=256, bias=True)
          (linear_v): Linear(in_features=256, out_features=256, bias=True)
          (linear_out): Linear(in_features=256, out_features=256, bias=True)
          (dropout): Dropout(p=0.0, inplace=False)
        )
        (src_attn): MultiHeadedAttention(
          (linear_q): Linear(in_features=256, out_features=256, bias=True)
          (linear_k): Linear(in_features=256, out_features=256, bias=True)
          (linear_v): Linear(in_features=256, out_features=256, bias=True)
          (linear_out): Linear(in_features=256, out_features=256, bias=True)
          (dropout): Dropout(p=0.0, inplace=False)
        )
        (feed_forward): PositionwiseFeedForward(
          (w_1): Linear(in_features=256, out_features=2048, bias=True)
          (activation): ReLU()
          (dropout): Dropout(p=0.1, inplace=False)
          (w_2): Linear(in_features=2048, out_features=256, bias=True)
        )
        (norm1): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
        (norm2): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
        (norm3): LayerNorm((256,), eps=1e-12, elementwise_affine=True)
        (dropout): Dropout(p=0.1, inplace=False)
        (concat_linear1): Linear(in_features=512, out_features=256, bias=True)
        (concat_linear2): Linear(in_features=512, out_features=256, bias=True)
      )
      ...
    )
  )
  (ctc): CTC(
    (ctc_lo): Linear(in_features=256, out_features=4233, bias=True)
    (ctc_loss): CTCLoss()
  )
  (criterion_att): LabelSmoothingLoss(
    (criterion): KLDivLoss()
  )
)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;第3节-进阶话题mask&quot;&gt;第3节: 进阶话题:Mask&lt;/h2&gt;

&lt;p&gt;在Wenet的模型实现时，涉及到一些论文中没有描述细节，比如:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;一个batch内的输入帧数不等长，进行padding的部分如何处理。&lt;/li&gt;
  &lt;li&gt;一个batch内标注文本不等长，进行padding的部分如何处理。&lt;/li&gt;
  &lt;li&gt;decoder的自回归依赖关系如何表达。&lt;/li&gt;
  &lt;li&gt;chunk-based的encoder如何实现。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;这些细节会对convolution和attention网络以及loss的计算带来影响。
因此在实现时，需要引入各种mask来进行处理。本节通过系统的介绍Wenet代码中涉及的mask，帮助初学者更好的理解wenet的实现。&lt;/p&gt;

&lt;p&gt;可以参考&lt;code class=&quot;highlighter-rouge&quot;&gt;wenet/utils/mask.py&lt;/code&gt;中的注释也提供了说明和示例。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;三类问题&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;问题1batch-padding&quot;&gt;问题1:Batch Padding&lt;/h3&gt;

&lt;p&gt;一个batch内部各个样本长度不同，但是pytorch这类框架，处理的基本数据格式形式规整tensor，比如一个矩阵，因此输入和标注都需要padding，补上一些数据变成相等长度的序列再进行处理。&lt;/p&gt;

&lt;p&gt;Wenet中, 输入的padding叫做frame batch padding，标注的padding叫label batch padding。&lt;/p&gt;

&lt;h4 id=&quot;处理padding对loss的影响&quot;&gt;处理Padding对Loss的影响&lt;/h4&gt;

&lt;p&gt;在计算Loss时，需要避免label batch padding带来的影响。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Attention Loss&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;标注的padding的部分，使用一个特殊整数padding_idx来进行填补。在计算Attention loss时，如果标注值为padding_idx，则不参与loss的计算。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    ignore = target == self.padding_idx  # (B,)
    total = len(target) - ignore.sum().item()
    target = target.masked_fill(ignore, 0)  # avoid -1 index
    true_dist.scatter_(1, target.unsqueeze(1), self.confidence)
    kl = self.criterion(torch.log_softmax(x, dim=1), true_dist)
    denom = total if self.normalize_length else batch_size
    return kl.masked_fill(ignore.unsqueeze(1), 0).sum() / denom
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;CTC loss&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;torch.nn.CTCLoss接口支持指定Batch内各个输出序列的长度&lt;code class=&quot;highlighter-rouge&quot;&gt;hlens&lt;/code&gt;和各个标注序列的长度&lt;code class=&quot;highlighter-rouge&quot;&gt;ys_lens&lt;/code&gt;&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;self.ctc_loss = torch.nn.CTCLoss(reduction=reduction_type)
loss = self.ctc_loss(ys_hat, ys_pad, hlens, ys_lens)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;hlens是encoder输出的Batch中各序列真实长度（除去padding部分的长度）。可以通过encoder_mask得到，encoder_mask会在后面介绍。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/transformer/asr_model.py
encoder_out_lens = encoder_mask.squeeze(1).sum(1)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;ys_lens是batch中各标注序列的真实长度，由dataloader返回的target_lengths得到。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/utils/executor.py
for batch_idx, batch in enumerate(data_loader):
    key, feats, target, feats_lengths, target_lengths = batch
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;处理模型输入padding&quot;&gt;处理模型输入Padding&lt;/h4&gt;

&lt;p&gt;模型的输入分为两个部分:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Encoder的输入:
    &lt;ul&gt;
      &lt;li&gt;声音特征序列: frame batch padding&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Decoder的输入:
    &lt;ul&gt;
      &lt;li&gt;Encoder的输出: 降采样后的frame batch padding&lt;/li&gt;
      &lt;li&gt;标注文本序列: label batch padding&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;实现时通过mask技巧对这些padding进行处理。mask是一个0，1值组成的掩码张量，wenet里mask的语义为：mask中值为1的部分是要考虑的，0的部分不考虑。&lt;/p&gt;

&lt;p&gt;Wenet的mask大致可分为两类:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;序列mask,（Batch, Length）， 每个 (Length,) 中值为1的位置代表了本序列要考虑的部分。&lt;/li&gt;
  &lt;li&gt;Attention mask,（Batch, L1, L2），每个（L1，L2) 用于约束L1中的哪些位置只能对于L2中的哪些位置进行attention操作。&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;问题2-自回归&quot;&gt;问题2: 自回归&lt;/h3&gt;

&lt;p&gt;Attention Decoder的结构是自回归的，即每个word只能看到自己以及左侧的words。所以其中的attention操作实现时，每个位置只能和当前位置以及左侧的位置进行操作。为了实现这个操作，需要引入一个mask。&lt;/p&gt;

&lt;h3 id=&quot;问题3-chunk-based-model&quot;&gt;问题3: Chunk-Based Model&lt;/h3&gt;

&lt;p&gt;因为full attention每一帧都要依赖右侧所有帧，所以无法应用于流式解码中，Wenet采用chunk-based attention，将帧分为等大小的chunk，每个chunk内的帧只在chunk内部进行attention操作。
另外，也允许和左侧的一定长度的帧进行attention。这种固定chunk大小的训练模式，要求解码时必须采用同样大小的帧。Wenet引入了一种dynamic chunk training算法，在训练时可以动态为每个batch生成不同大小的
chunk，这样，在解码时，chunk大小可以任意指定，大的chunk可以获得高识别率，小的chunk可以获得低延时，从而用户仅需训练单一模型，根据具体场景在解码时选择合适的chunk大小，而无需重新训练模型。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;网络各部分的实现&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;encoder中的mask&quot;&gt;Encoder中的mask&lt;/h3&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;wenet/transformer/encoder.py
def forward()
    ...
    masks = ~make_pad_mask(xs_lens).unsqueeze(1)  # (B, 1, L)
    xs, pos_emb, masks = self.embed(xs, masks)
    mask_pad = masks
    chunk_masks = add_optional_chunk_mask(xs, masks,
                                              self.use_dynamic_chunk,
                                              self.use_dynamic_left_chunk,
                                              decoding_chunk_size,
                                              self.static_chunk_size,
                                              num_decoding_left_chunks)
    for layer in self.encoders:
        xs, chunk_masks, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;self.embed会对frame padding mask进行降采样得到subsample frame padding mask。&lt;/li&gt;
  &lt;li&gt;mask_pad在Conformer Block中的卷积网络中使用。&lt;/li&gt;
  &lt;li&gt;add_optional_chunk_mask会在subsample frame padding mask基础上增加chunk mask，在Conformer Block中的self attention网络使用。&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;subsampling中的mask&quot;&gt;Subsampling中的mask&lt;/h4&gt;

&lt;p&gt;subsampling网络中的卷积运算时本身不使用frame padding mask，但是会对frame padding mask降采样得到subsample frame padding mask，后续在进行encoder相关计算时会使用这个subsample frame padding mask.&lt;/p&gt;

&lt;p&gt;比如在4倍降采样的网络里，使用了两个stride=2的卷积，对shape=(B, 1, L)
的mask进行了mask[:, :, :-2:2][:, :, :-2:2]的操作，新的mask的shape为(B, 1, L/4)。&lt;/p&gt;

&lt;p&gt;但是目前的实现存在小问题，最后几个解码帧（降采样帧）如果其卷积野中有padding的帧，则该降采样帧输入无效帧，不该参与后续计算，但是按照目前mask的实现仍会被使用。&lt;/p&gt;

&lt;p&gt;举个例子，训练时，某个样本的倒数4个原始帧都是padding的，最后一个解码帧依赖于这些padding帧，因此不应该使用，其mask计算过程如下：&lt;/p&gt;

&lt;p&gt;原始mask（单个样本)&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;1 1 1 1 1 1 1 0 0 0 0
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;经过subsample后的mask&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;1   1   1   1   0
1       1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;注意，此时根据计算出对subsample padding mask，仍然会使用最后一个解码帧。&lt;/p&gt;

&lt;p&gt;类似的，如果倒数5个原始帧都是padding的，那么此时倒数两个解码帧信息都不全，都不应该使用，但是subsample padding mask仍然会使用两个解码帧。可以自行验证下。&lt;/p&gt;

&lt;p&gt;不过这个‘不完美’的实现问题对训练影响不大，只会影响最后1到2帧，相当于给模型增加了一些干扰。&lt;/p&gt;

&lt;h4 id=&quot;conformer-block中的conv的mask&quot;&gt;Conformer Block中的Conv的mask&lt;/h4&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wenet/mask-conv.png&quot; alt=&quot;train-arch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;考虑图中多层卷积的情况，假设kernel大小为3。 由于batch paddings的存在，在训练时，绿色单元依赖于红色单元，而红色单元不是0值。
然而在解码时，因为没有batch padding存在，绿色单元依赖的红色单元位置的值是由conv paddings产生的，这个值是0值，所以如果不进行任何处理，存在训练和解码不一致的问题。&lt;/p&gt;

&lt;p&gt;因此，代码里利用subsample frame padding，将每一层的batch padding部分的值变为0.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/transformer/convolution.py
# def forward():
    x.masked_fill_(~mask_pad, 0.0)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;不过如果使用casual conv中，由于其结构的特点，每个点不依赖于自己右侧的点，则不需要这个mask。&lt;/p&gt;

&lt;h4 id=&quot;multiheadedattention-module的mask实现&quot;&gt;MultiHeadedAttention Module的Mask实现&lt;/h4&gt;

&lt;p&gt;MultiHeadedAttention可以用于三种不同的attention。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Encoder中的self-attention&lt;/li&gt;
  &lt;li&gt;Decoder中的self-attention&lt;/li&gt;
  &lt;li&gt;Decoder中的cross-attention&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;不同的情况下，attention的mask会有所区别。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;用于self-attention时，每个样本的mask是一个长和高一样大小的方阵。&lt;/li&gt;
  &lt;li&gt;用于cross-attention时，mask的纵轴从上到下为文本序列，横轴从左到右为帧序列。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;MultiHeadedAttention的forward函数注释里说明了在不同情况下传入的mask的shape不同。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/transformer/attention.py
def forward(self, query: torch.Tensor, key: torch.Tensor,
            value: torch.Tensor,
            mask: Optional[torch.Tensor]) -&amp;gt; torch.Tensor:
    &quot;&quot;&quot;Compute scaled dot product attention.

    Args:
        query (torch.Tensor): Query tensor (#batch, time1, size).
        key (torch.Tensor): Key tensor (#batch, time2, size).
        value (torch.Tensor): Value tensor (#batch, time2, size).
        mask (torch.Tensor): Mask tensor (#batch, 1, time2) or
            (#batch, time1, time2).
            1.When applying cross attention between decoder and encoder,
            the batch padding mask for input is in (#batch, 1, T) shape.
            2.When applying self attention of encoder,
            the mask is in (#batch, T, T)  shape.
            3.When applying self attention of decoder,
            the mask is in (#batch, L, L)  shape.
            4.If the different position in decoder see different block
            of the encoder, such as Mocha, the passed in mash could be
            in (#batch, L, T) shape. But there is no such case in current
            Wenet.
    &quot;&quot;&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;具体实现&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;计算attention的权重时使用mask：先将不需要计算的位置的score设为负无穷而不是0，然后计算softmax得到位置权重，再把不需要参与attention计算的位置的权重系数设为0.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/transformer/attention.py
def forward_attention ():
    ...
    mask = mask.unsqueeze(1).eq(0)  # (batch, 1, *, time2)
    scores = scores.masked_fill(mask, -float('inf'))
    attn = torch.softmax(scores, dim=-1).masked_fill(mask, 0.0)  # (batch, head, time1, time2)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;mask.unsqueeze(1)是为了增加一个head维度。此时:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;当用于decoder cross-attention时， mask的shape为(batch, 1, 1, Tmax), scores的shape为(batch, head, Lmax, Tmax),第1，第2维会进行broadcast&lt;/li&gt;
  &lt;li&gt;当用于decoder self-attention时， mask的shape为(batch, 1, Lmax, Lmax), scores的shape为(batch, head, Lmax, Lmax)，第1维会进行broadcast&lt;/li&gt;
  &lt;li&gt;当用于encoder self-attention时， mask的shape为(batch, 1, Tmax, Tmax), scores的shape为(batch, head, Tmax, Tmax)，第1维会进行broadcast&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;chunk-based-mask&quot;&gt;Chunk-based mask&lt;/h4&gt;

&lt;p&gt;为了实现流式解码，encoder中使用了基于chunk的attention，并允许各个batch使用不同的chunk大小。&lt;/p&gt;

&lt;p&gt;基于chunk的attention，本质上是去限制attention的作用范围，可以通过attention mask来实现。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wenet/mask-encoder-attention.png&quot; alt=&quot;mask-encoder-attention&quot; /&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;subsequent_chunk_mask方法用于创建一个固定大小chunk的mask。&lt;/li&gt;
  &lt;li&gt;add_optional_chunk_mask方法则用于创建动态大小的chunk的mask。&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def add_optional_chunk_mask(xs: torch.Tensor, masks: torch.Tensor,
                            use_dynamic_chunk: bool,
                            use_dynamic_left_chunk: bool,
                            decoding_chunk_size: int, static_chunk_size: int,
                            num_decoding_left_chunks: int):
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;use_dynamic_chunk=Ture, 各的batch使用随机的chunk mask。
    &lt;ul&gt;
      &lt;li&gt;如果 use_dynamic_left_chunk=True， 各的batch使用随机的的left chunk长度依赖&lt;/li&gt;
      &lt;li&gt;如果 use_dynamic_left_chunk=False， 各的batch使用均依赖开头到当前chunk&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;use_dynamic_chunk = false, static_chunk_size &amp;lt;= 0. 使用full-attention.&lt;/li&gt;
  &lt;li&gt;use_dynamic_chunk = false, static_chunk_size &amp;gt; 0. 使用固定的chunk mask.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;decoder中的mask&quot;&gt;Decoder中的mask&lt;/h3&gt;

&lt;p&gt;Decoder涉及到两种Attention。
self.self_attn是decoder上的self attention。
self.src_attn是decoder和encoder的cross attention。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/transformer/decoder_layer.py
def forward():
    ...
    self.self_attn(tgt_q, tgt, tgt, tgt_q_mask)
    self.src_attn(x, memory, memory, memory_mask)
    ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Self attention&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;self attention中要考虑自回归和label batch padding带来的影响。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;wenet/transformer/decoder.py
        tgt = ys_in_pad
        # tgt_mask: (B, 1, L)
        tgt_mask = (~make_pad_mask(ys_in_lens).unsqueeze(1)).to(tgt.device)
        # m: (1, L, L)
        m = subsequent_mask(tgt_mask.size(-1),
                            device=tgt_mask.device).unsqueeze(0)
        # tgt_mask: (B, L, L)
        tgt_mask = tgt_mask &amp;amp; m
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;ul&gt;
  &lt;li&gt;~make_pad_mask产生的tgt_mask是label padding mask，每个words不允许对padding部分进行attention操作。&lt;/li&gt;
  &lt;li&gt;subsequent_mask产生的m是decoder的自回归mask，每个words只对自己以及左侧的words进行attention操作。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;如图中所示，自回归mask和label padding mask被同时使用。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wenet/mask-decoder-self.png&quot; alt=&quot;mask-self&quot; /&gt;&lt;/p&gt;

&lt;p&gt;不过，由于decoder本身是自回归的，自回归掩码保证了对于非padding的位置，均不会去计算自己右侧的位置，而对于padding位置，在loss中会处理，不参与最后的loss计算。
因此，其实并不需要label padding mask(代码中的tgt_mask).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cross attention&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;进行Cross attention， 由于encoder的一些输出是padding产生的，需要利用subsample frame padding mask.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wenet/mask-decoder-cross.png&quot; alt=&quot;mask-decoder-cross&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;整体结构&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Decoder中每一层中，均需要计算如上两个attention，从网络视角来看，如下图所示。
&lt;img src=&quot;/assets/images/wenet/mask-decoder-attention.png&quot; alt=&quot;mask-decoder-attention&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;其他&quot;&gt;其他&lt;/h3&gt;

&lt;p&gt;在进行Batch解码时，还用到了&lt;code class=&quot;highlighter-rouge&quot;&gt;mask_finished_scores&lt;/code&gt;和&lt;code class=&quot;highlighter-rouge&quot;&gt;mask_finished_preds&lt;/code&gt;，本文不进行介绍&lt;/p&gt;

&lt;h2 id=&quot;第4节-进阶话题cache&quot;&gt;第4节: 进阶话题:Cache&lt;/h2&gt;

&lt;p&gt;标准的forward是整个序列进行计算，但是在流式推断时，需要chunk级别的forward，因此需要引入cache的概念，即当前chunk的进行前向计算时，需要拿到上次前向的一些结果作为输入。&lt;/p&gt;

&lt;p&gt;什么是cache？&lt;/p&gt;

&lt;p&gt;对于流式推断，输入是一个个chunk的到来，对第i个chunk，当计算第k层网络的输出时，由于网络结构存在对左侧上下文的依赖，需要依赖第k-1层网络里在i之前的一些chunks的输出。
如果对于当前到来chunk，将其和依赖的chunk序列（比如10层self-attention层，每层依赖左侧4个chunk，则累积起来需要依赖左侧40个chunk）拼起来作为网络输入进行前向，其计算量会比较大。
对于那些已经计算过的chunk，可以将那些在计算下一个chunk的输出时需要的中间量保存下来，从而减少重复计算。这种方式就叫cache。&lt;/p&gt;

&lt;p&gt;另外，wenet的网络在设计时，对于因果卷积和self-attention的左侧上下文都使用有限长度，因此无论序列多长，每次cache的大小是不变的（不增长）。&lt;/p&gt;

&lt;p&gt;仅仅encoder部分涉及chunk计算时的cache。&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;对于CTC decoder，由于是线性层，不需要cache。&lt;/li&gt;
  &lt;li&gt;对于AED decoder，是在计算完整个序列的encoder输出后进行rescoring，不涉及chunk。&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;runtime流式解码&quot;&gt;Runtime流式解码&lt;/h3&gt;

&lt;p&gt;asr_model.py中的&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_encoder_chunk()&lt;/code&gt;通过jit导出，用于C++ runtime，其内部使用了&lt;code class=&quot;highlighter-rouge&quot;&gt;encoder.py&lt;/code&gt;中的&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_chunk()&lt;/code&gt;函数。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/transformer/asr_model.py

@torch.jit.export
    def forward_encoder_chunk()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;python流式解码&quot;&gt;Python流式解码&lt;/h3&gt;

&lt;p&gt;如果设置simulate_streaming为True，则会模拟runtime流时解码的过程，将数据分成chunk，依次进行前向计算。
该方法的结果，和送入整个序列通过mask进行流式模拟的结果应该是一致的。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;recognize() -&amp;gt; _forward_encoder() -&amp;gt; BaseEncoder.forward_chunk_by_chunk()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_chunk_by_chunk()&lt;/code&gt;的内部也是使用的&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_chunk()&lt;/code&gt;函数。&lt;/p&gt;

&lt;h3 id=&quot;baseencoderforward_chunk分析&quot;&gt;BaseEncoder.forward_chunk()分析&lt;/h3&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;forward_chunk()&lt;/code&gt;是对单个chunk进行前向计算的核心函数。下面从该函数的内容来了解cache的实现。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/transformer/encoder.py
def forward_chunk(
        self,
        xs: torch.Tensor,
        offset: int,
        required_cache_size: int,
        subsampling_cache: Optional[torch.Tensor] = None,
        elayers_output_cache: Optional[List[torch.Tensor]] = None,
        conformer_cnn_cache: Optional[List[torch.Tensor]] = None,
    ) -&amp;gt; Tuple[torch.Tensor, torch.Tensor, List[torch.Tensor],
               List[torch.Tensor]]:
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;xs是当前的chunk输入，由于对于单个chunk的前向计算，需要之前的chunk的计算得到的信息，因此这里需要传入相关的三个cache信息。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;subsampling_cache:torch.Tensor&lt;/strong&gt;  subsampling的输出的cache。即第一个conformer block的输入。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;elayers_output_cache:List[torch.Tensor]&lt;/strong&gt; 第1个到最后1个conformer block的输出的cache。也就是第2个conformer block的输入和CTC层的输入。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;conformer_cnn_cache:List[torch.Tensor]&lt;/strong&gt; conformer block里的conv层的左侧依赖的输入cache。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;cache的大小&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;subsampling_cache和elayers_output_cache的大小
由self-attention是对左侧的依赖长度required_cache_size决定。
decoding_chunk_size是解码帧级别的chunk大小, num_decoding_left_chunks是self-attention依赖的左侧chunk数。
    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;required_cache_size = decoding_chunk_size * num_decoding_left_chunks
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;conformer_cnn_cache的大小和required_cache_size无关，由casual网络的左侧上下文lorder决定。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;函数返回了四个值，包括当前chunk输入对应的输出，更新后的三个cache。&lt;/p&gt;

&lt;p&gt;该函数的整个计算过程请参考下图&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/wenet/cache-all.png&quot; alt=&quot;cache-all&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;offset&quot;&gt;offset&lt;/h4&gt;

&lt;p&gt;当按chunk进行输入时，不能直接得到chunk在序列中的位置，需要传入offset给出该chunk在整个序列里的偏移，用于计算positional encoding。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;xs, pos_emb, _ = self.embed(xs, tmp_masks, offset)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;subsampling内部&quot;&gt;subsampling内部&lt;/h4&gt;

&lt;p&gt;subsampling内部的计算虽然存在冗余，但是不进行cache。一个是其实现比较复杂，另一个原因是subsampling的计算量占比不大。&lt;/p&gt;

&lt;h4 id=&quot;subsampling_cache&quot;&gt;subsampling_cache&lt;/h4&gt;

&lt;p&gt;subsampling的输出的cache。即第一个conformer block的输入。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;if subsampling_cache is not None:
    cache_size = subsampling_cache.size(1)
    # xs是第一个conformer block的输入
    xs = torch.cat((subsampling_cache, xs), dim=1)
else:
    cache_size = 0
pos_emb = self.embed.position_encoding(offset - cache_size, xs.size(1))
if required_cache_size &amp;lt; 0:
    next_cache_start = 0
elif required_cache_size == 0:
    next_cache_start = xs.size(1)
else:
    next_cache_start = max(xs.size(1) - required_cache_size, 0)
# 更新subsampling_cache
r_subsampling_cache = xs[:, next_cache_start:, :]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;elayers_output_cache&quot;&gt;elayers_output_cache&lt;/h4&gt;

&lt;p&gt;第1个到最后1个conformer block的输出的cache。也就是第2个conformer block的输入和CTC层的输入。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;for i, layer in enumerate(self.encoders):
    attn_cache = elayers_output_cache[i]
    cnn_cache = conformer_cnn_cache[i]
    xs, _, new_cnn_cache = layer(xs,
        masks,
        pos_emb,
        output_cache=attn_cache,
        cnn_cache=cnn_cache)
    # 更新elayers_output_cache
    r_elayers_output_cache.append(xs[:, next_cache_start:, :])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;注意，此处的xs不是当前的chunk，而是当前chunk+cache输入，所以其长度不是chunk_size, 而是chunk_size + required_cache_size。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
# wenet/transformer/encoder.py BaseEncoder.forward_chunk()
# 第一个conformer block输入的xs
xs = torch.cat((subsampling_cache, xs), dim=1)


# wenet/transformer/encoder_layer.py ConformerEncoderLayer.forward()
# 之后的conformer block输入的xs
if output_cache is not None:
    x = torch.cat([output_cache, x], dim=1)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;layer()对应着wenet/transformer/encoder_layer.py中的ConformerEncoderLayer.forward()。下面是其具体过程。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# 计算feedforwad/res/norm(包含当前chunk和左侧num_decoding_left_chunks个chunk)

# 使用cache时，只要计算当前chunk x_q的self-attentionattention和residual

chunk = x.size(1) - output_cache.size(1)
x_q = x[:, -chunk:, :]

# 只选择当前chunk对应的部分做residual计算
residual = residual[:, -chunk:, :]

# 选取当前chunk对应的mask，
mask = mask[:, -chunk:, :]

# 使用当前chunk的x_q去和其依赖的x做attention
x = residual + self.dropout(self.self_attn(x_q, x, x, mask))

# 仅计算计算当前chunk的conv
x, new_cnn_cache = self.conv_module(x, mask_pad, cnn_cache)

# 仅计算当前chunk的feedforwad/res/norm
x = self.norm2(x)
x = residual + self.dropout(self.feed_forward(x))

# 可以看到通过cache节省了x[:, :-chunk, :]部分的attention/conv以及之后的feedforwad/res/norm计算

# chunk的输出和cache拼在一起，作为网络的最终输出。
x = torch.cat([output_cache, x], dim=1)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;注意，self-attention之前的一些前向计算其实仍然存在冗余，如果对attention层的输入进行cache，而不是对conformer block层的输入cache，可以进一步降低计算量。&lt;/p&gt;

&lt;h4 id=&quot;conformer_cnn_cache&quot;&gt;conformer_cnn_cache&lt;/h4&gt;

&lt;p&gt;conformer block里的conv层的左侧依赖的输入cache。&lt;/p&gt;

&lt;p&gt;conformer_cnn_cache大小为lorder，即因果卷积左侧依赖，。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/transformer/encoder_layer.py ConformerEncoderLayer.forward()
# conformer_cnn_cache通过ConvolutionModule.forward()返回的新cache来更新
x, new_cnn_cache = self.conv_module(x, mask_pad, cnn_cache)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# wenet/transformer/convolution.py ConvolutionModule.forward()
if self.lorder &amp;gt; 0:
    if cache is None:
        x = nn.functional.pad(x, (self.lorder, 0), 'constant', 0.0)
    else:
        x = torch.cat((cache, x), dim=2)
    # 更新 conformer_cnn_cache
    new_cache = x[:, :, -self.lorder:]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;感谢阅读，欢迎使用wenet！&lt;/strong&gt;&lt;/p&gt;</content><author><name></name></author><summary type="html">如果觉得wenet还不错，点个star支持我们一下吧</summary></entry><entry><title type="html">Relative Positional Embedding</title><link href="http://placebokkk.github.io/asr/2021/01/14/asr-rpe.html" rel="alternate" type="text/html" title="Relative Positional Embedding" /><published>2021-01-14T02:00:00+00:00</published><updated>2021-01-14T02:00:00+00:00</updated><id>http://placebokkk.github.io/asr/2021/01/14/asr-rpe</id><content type="html" xml:base="http://placebokkk.github.io/asr/2021/01/14/asr-rpe.html">&lt;ul class=&quot;table-of-content&quot; id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#relative-positional-embedding&quot; id=&quot;markdown-toc-relative-positional-embedding&quot;&gt;Relative Positional Embedding&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#原始的带positional-embedding的-attention-score计算方法&quot; id=&quot;markdown-toc-原始的带positional-embedding的-attention-score计算方法&quot;&gt;原始的带positional embedding的 attention score计算方法&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#relative-positional-embedding-1&quot; id=&quot;markdown-toc-relative-positional-embedding-1&quot;&gt;Relative Positional Embedding&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#代码实现&quot; id=&quot;markdown-toc-代码实现&quot;&gt;代码实现&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#产生relative-positional-embedding&quot; id=&quot;markdown-toc-产生relative-positional-embedding&quot;&gt;产生Relative Positional Embedding&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#attention计算&quot; id=&quot;markdown-toc-attention计算&quot;&gt;Attention计算&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#attention-score矩阵左移操作&quot; id=&quot;markdown-toc-attention-score矩阵左移操作&quot;&gt;Attention Score矩阵左移操作&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;本文讲解基于transformer/conformer的语音识别Wenet中的Relative Positional Embed的实现&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/mobvoi/wenet/tree/main/wenet&quot;&gt;Wenet代码&lt;/a&gt;&lt;/p&gt;

&lt;h1 id=&quot;relative-positional-embedding&quot;&gt;Relative Positional Embedding&lt;/h1&gt;

&lt;p&gt;Transformer XL中提出了Relative Positional Embedding方法，在ASR conformer论文中，也提到&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;We employ multi-headed self-attention (MHSA) while integrating an important  technique from Transformer-XL [20],the relative sinusoidal positional encoding scheme. The relative po- sitional encoding allows the self-attention module to generalize better on different input length and the resulting encoder is more robust to the variance of the utterance length.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;原始的带positional-embedding的-attention-score计算方法&quot;&gt;原始的带positional embedding的 attention score计算方法&lt;/h2&gt;
&lt;p&gt;i位置的encoding embedding为&lt;script type=&quot;math/tex&quot;&gt;\mathbf{E}_{x_{i}}&lt;/script&gt;,positional embedding信息&lt;script type=&quot;math/tex&quot;&gt;\mathbf{U}_{k}&lt;/script&gt;, i和j位置的attention score计算如下:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\begin{equation}
\left(\mathbf{E}_{x_{i}}^{\top}+\mathbf{U}_{i}^{\top}\right) \mathbf{W}_{q}^{\top} \mathbf{W}_{k}\left(\mathbf{E}_{x_{j}}+\mathbf{U}_{j}\right)
\end{equation}&lt;/script&gt;

&lt;p&gt;展开得到&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{equation}
\begin{aligned}
\mathbf{A}_{i, j}^{\mathrm{abs}} &amp;=\underbrace{\mathbf{E}_{x_{i}}^{\top} \mathbf{W}_{q}^{\top} \mathbf{W}_{k} \mathbf{E}_{x_{j}}}_{(a)}+\underbrace{\mathbf{E}_{x_{i}}^{\top} \mathbf{W}_{q}^{\top} \mathbf{W}_{k} \mathbf{U}_{j}}_{(b)} \\
&amp;+\underbrace{\mathbf{U}_{i}^{\top} \mathbf{W}_{q}^{\top} \mathbf{W}_{k} \mathbf{E}_{x_{j}}}_{(c)}+\underbrace{\mathbf{U}_{i}^{\top} \mathbf{W}_{q}^{\top} \mathbf{W}_{k} \mathbf{U}_{j}}_{(d)}
\end{aligned}
\end{equation} %]]&gt;&lt;/script&gt;

&lt;p&gt;去除&lt;script type=&quot;math/tex&quot;&gt;\mathbf{W}_{q}&lt;/script&gt;和&lt;script type=&quot;math/tex&quot;&gt;\mathbf{W}_{k}&lt;/script&gt;简化形式:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\begin{equation}
\mathbf{A}_{i, j}^{\mathrm{abs}}=\underbrace{\mathbf{E}_{x_{i}}^{\top} \mathbf{E}_{x_{j}}}_{(a)}+\underbrace{\mathbf{E}_{x_{i}}^{\top} \mathbf{U}_{j}}_{(b)}+\underbrace{\mathbf{U}_{i}^{\top} \mathbf{E}_{x_{j}}}_{(c)}+\underbrace{\mathbf{U}_{i}^{\top} \mathbf{U}_{j}}_{(d)}
\end{equation}&lt;/script&gt;

&lt;h2 id=&quot;relative-positional-embedding-1&quot;&gt;Relative Positional Embedding&lt;/h2&gt;
&lt;p&gt;相对位置这个概念，只有做attention时才存在，
使用&lt;script type=&quot;math/tex&quot;&gt;R_{i-j}&lt;/script&gt;表示第i个位置的query和第j个位置的key做attention时用的相对距离信息:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;第3个位置的query和第2个位置的key做attention，使用R1.&lt;/li&gt;
  &lt;li&gt;第4个位置的query和第3个位置的key做attention，使用R1.&lt;/li&gt;
  &lt;li&gt;第4个位置的query和第2个位置的key做attention，使用R2.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;在引入两个跟位置无关的可学习的向量参数u和v，将上述的带位置信息的attention score计算改写为:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\begin{equation}
\mathbf{A}_{i, j}^{\mathrm{rel}}=\underbrace{\mathbf{E}_{x_{i}}^{\top} \mathbf{E}_{x_{j}}}_{(a)}+\underbrace{\mathbf{E}_{x_{i}}^{\top} \mathbf{R}_{i-j}}_{(b)}+\underbrace{\mathbf{u}^{\top} \mathbf{E}_{x_{j}}}_{(c)}+\underbrace{\mathbf{v}^{\top} \mathbf{R}_{i-j}}_{(d)}
\end{equation}&lt;/script&gt;

&lt;p&gt;合并ac项，bd项:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\begin{equation}
\mathbf{A}_{i, j}^{\mathrm{rel}}=\underbrace{\left(\mathbf{E}_{x_{i}}^{\top}+\mathbf{u}^{\top}\right) \mathbf{E}_{x_{j}}}_{(a c)}+\underbrace{\left(\mathbf{E}_{x_{i}}^{\top}+\mathbf{v}^{\top}\right) \mathbf{R}_{i-j}}_{(b d)}
\end{equation}&lt;/script&gt;

&lt;p&gt;这个score matrix可以写成下面两项之和&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\begin{equation}
\mathbf{A}^{\mathrm{rel}}=\mathbf{A}_{a c}+\mathbf{A}_{b d}
\end{equation}&lt;/script&gt;

&lt;p&gt;ac项容易计算，这里只关注bd项, 为了表示方便，用&lt;script type=&quot;math/tex&quot;&gt;R_{j-i}&lt;/script&gt;代替&lt;script type=&quot;math/tex&quot;&gt;R_{i-j}&lt;/script&gt;, 同时令 &lt;script type=&quot;math/tex&quot;&gt;\mathbf{q}_{i} = \mathbf{E}_{x_{i}} + \mathbf{v}&lt;/script&gt;&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{equation}
\mathbf{A}_{b d}=\left[\begin{array}{cccc}
q_{0}^{\top} \mathbf{R}_{0} &amp; q_{0}^{\top} \mathbf{R}_{1} &amp; \cdots &amp; q_{0}^{\top} \mathbf{R}_{L-1} \\
q_{1}^{\top} \mathbf{R}_{-1} &amp; q_{1}^{\top} \mathbf{R}_{0} &amp; \cdots &amp; q_{1}^{\top} \mathbf{R}_{L-2} \\
\vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
q_{L-1}^{\top} \mathbf{R}_{-(L-1)} &amp; q_{L-1}^{\top} \mathbf{R}_{-(L-2)} &amp; \cdots &amp; q_{L-1}^{\top} \mathbf{R}_{0}
\end{array}\right]
\end{equation} %]]&gt;&lt;/script&gt;

&lt;p&gt;一种计算&lt;script type=&quot;math/tex&quot;&gt;\mathbf{A}_{bd}&lt;/script&gt; 的方法是对于矩阵中的每一项分别计算。但是无法利用到GPU对大矩阵相乘加速的优点。有没有办法把矩阵&lt;script type=&quot;math/tex&quot;&gt;\mathbf{A}_{bd}&lt;/script&gt; 的计算变为矩阵乘法呢？可以使用下面方法&lt;/p&gt;

&lt;p&gt;令&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{equation}
\mathbf{R}=\left[\begin{array}{llllll}
\mathbf{R}_{-(L-1)} &amp; \mathbf{R}_{-(L-2)} &amp; \mathbf{R}_{0} &amp; \cdots &amp; \mathbf{R}_{L-2} &amp; \mathbf{R}_{L-1}
\end{array}\right]
\end{equation} %]]&gt;&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\begin{equation}
\mathbf{q}=\left[\begin{array}{c}
\mathbf{q}_{0}^{\top} \\
\mathbf{q}_{1}^{\top} \\
\vdots \\
\mathbf{q}_{L-1}^{\top} \\
\mathbf{q}_{L}^{\top}
\end{array}\right]
\end{equation}&lt;/script&gt;

&lt;p&gt;两个矩阵相乘,得&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{equation}
\mathbf{q} \mathbf{R}=\left[\begin{array}{ccccccc}
q_{0}^{\top} \mathbf{R}_{-(L-1)} &amp; q_{0}^{\top} \mathbf{R}_{-(L-2)} &amp; \cdots &amp; q_{0}^{\top} \mathbf{R}_{0} &amp; \cdots &amp; q_{0}^{\top} \mathbf{R}_{L-2} &amp; q_{0}^{\top} \mathbf{R}_{L-1} \\
q_{1}^{\top} \mathbf{R}_{-(L-1)} &amp; q_{1}^{\top} \mathbf{R}_{-(L-2)} &amp; \cdots &amp; q_{1}^{\top} \mathbf{R}_{0} &amp; \cdots &amp; q_{1}^{\top} \mathbf{R}_{L-2} &amp; q_{1}^{\top} \mathbf{R}_{L-1} \\
\vdots &amp; \vdots &amp; \ddots &amp; \vdots &amp; \ddots &amp; \vdots &amp; \vdots \\
q_{L-1}^{\top} \mathbf{R}_{-(L-1)} &amp; q_{L-1}^{\top} \mathbf{R}_{-(L-2)} &amp; \cdots &amp; q_{L-1}^{\top} \mathbf{R}_{0} &amp; \cdots &amp; q_{L-1}^{\top} \mathbf{R}_{L-2} &amp; q_{L-1}^{\top} \mathbf{R}_{L-1}
\end{array}\right]
\end{equation} %]]&gt;&lt;/script&gt;

&lt;p&gt;对该矩阵，将第i行左移L-i个位置，并且取前L列即得到&lt;script type=&quot;math/tex&quot;&gt;\mathbf{A}_{bd}&lt;/script&gt;&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{equation}
\mathbf{A}_{b d}=\left[\begin{array}{cccc}
q_{0}^{\top} \mathbf{R}_{0} &amp; q_{0}^{\top} \mathbf{R}_{1} &amp; \cdots &amp; q_{0}^{\top} \mathbf{R}_{L-1} \\
q_{1}^{\top} \mathbf{R}_{-1} &amp; q_{1}^{\top} \mathbf{R}_{0} &amp; \cdots &amp; q_{1}^{\top} \mathbf{R}_{L-2} \\
\vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
q_{L-1}^{\top} \mathbf{R}_{-(L-1)} &amp; q_{L-1}^{\top} \mathbf{R}_{-(L-2)} &amp; \cdots &amp; q_{L-1}^{\top} \mathbf{R}_{0}
\end{array}\right]
\end{equation} %]]&gt;&lt;/script&gt;

&lt;p&gt;以上是一个长为L的序列中进行fully-attention的计算方式，对于的非流式E2E ASR系统，encoder部分使用上述fully-attention方法即可，对于流式的系统，一般可采用chunk-based，即当前chunk内的帧要和前面的帧以及本chunk内的帧做attention。在transformer-XL中，也是类似的方法: 当前长度为&lt;script type=&quot;math/tex&quot;&gt;L&lt;/script&gt;的segment和他前面长度为&lt;script type=&quot;math/tex&quot;&gt;M&lt;/script&gt;的memory以及自己segment内部的各个点做attention。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/rpe/ChunkRPE.png&quot; alt=&quot;ChunkRPE&quot; /&gt;&lt;/p&gt;

&lt;p&gt;下面是chunk based attention下的计算方法，fully-attention只是chunk based attention的一个特例，即chunk size=整个序列长度的情况。&lt;/p&gt;

&lt;p&gt;假设当前chunk的大小为&lt;script type=&quot;math/tex&quot;&gt;C&lt;/script&gt;，之前帧数为&lt;script type=&quot;math/tex&quot;&gt;M&lt;/script&gt;，则对于每个chunk，query的个数为&lt;script type=&quot;math/tex&quot;&gt;C&lt;/script&gt;个，key/value的个数为&lt;script type=&quot;math/tex&quot;&gt;M+C&lt;/script&gt;个。&lt;/p&gt;

&lt;p&gt;只需将&lt;script type=&quot;math/tex&quot;&gt;\mathbf{q} \mathbf{R}&lt;/script&gt;第&lt;script type=&quot;math/tex&quot;&gt;i&lt;/script&gt;行左移&lt;script type=&quot;math/tex&quot;&gt;C-i&lt;/script&gt;个位置即可得到对应的score matrix
令 &lt;script type=&quot;math/tex&quot;&gt;L=M+C&lt;/script&gt; ，则当前chunk的score matrix计算方式如下:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{equation}
\mathbf{A}_{b d}=\left[\begin{array}{cccc}
q_{0}^{\top} \mathbf{R}_{-(L-C)} &amp; q_{0}^{\top} \mathbf{R}_{L-C+1} &amp; \cdots &amp; q_{0}^{\top} \mathbf{R}_{C-1} \\
q_{1}^{\top} \mathbf{R}_{-(L-C+1)} &amp; q_{1}^{\top} \mathbf{R}_{L-C} &amp; \cdots &amp; q_{1}^{\top} \mathbf{R}_{C-2} \\
\vdots &amp; \vdots &amp; \ddots &amp; \vdots \\
q_{C-1}^{\top} \mathbf{R}_{-(L-1)} &amp; q_{C-1}^{\top} \mathbf{R}_{-(L-2)} &amp; \cdots &amp; q_{C-1}^{\top} \mathbf{R}_{0}
\end{array}\right]
\end{equation} %]]&gt;&lt;/script&gt;

&lt;h2 id=&quot;代码实现&quot;&gt;代码实现&lt;/h2&gt;

&lt;h3 id=&quot;产生relative-positional-embedding&quot;&gt;产生Relative Positional Embedding&lt;/h3&gt;

&lt;p&gt;生成一个[-L,L]的Relative Positional Embedding的方法:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class RelPositionalEncoding():
    def __init__(self,
                    d_model: int,
                    dropout_rate: float,
                    max_len: int = 5000):
            super().__init__()
            self.d_model = d_model
            self.max_len = max_len

            self.pe = torch.zeros(self.max_len, self.d_model)
            position = torch.arange(0, self.max_len,
                                    dtype=torch.float32).unsqueeze(1)
            div_term = torch.exp(
                torch.arange(0, self.d_model, 2, dtype=torch.float32) *
                -(math.log(10000.0) / self.d_model))
            self.pe[:, 0::2] = torch.sin(position * div_term)
            self.pe[:, 1::2] = torch.cos(position * div_term)

    def position_encoding(self, size: int) -&amp;gt; torch.Tensor:
        assert size &amp;lt; int(self.max_len/2)
        mid_pos = int(self.max_len / 2)
        pos_emb = self.pe[mid_pos - size + 1:mid_pos + size]
        return pos_emb
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h3 id=&quot;attention计算&quot;&gt;Attention计算&lt;/h3&gt;
&lt;p&gt;利用上面生成的 &lt;script type=&quot;math/tex&quot;&gt;2*L-1&lt;/script&gt; 长度的Relative Positional Embedding和Query Embeddings做矩阵乘法，
计算方式和Multi-Head Attention类似&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;def forward(self, query: torch.Tensor, key: torch.Tensor,
                value: torch.Tensor, pos_emb: torch.Tensor,
                mask: Optional[torch.Tensor]):
        &quot;&quot;&quot;Compute 'Scaled Dot Product Attention' with rel. positional encoding.
        Args:
            query (torch.Tensor): Query tensor (#batch, time1, size).
            key (torch.Tensor): Key tensor (#batch, time2, size).
            value (torch.Tensor): Value tensor (#batch, time2, size).
            pos_emb (torch.Tensor): Positional embedding tensor
                (2*time2-1, size).
            mask (torch.Tensor): Mask tensor (#batch, time1, time2).
        Returns:
            torch.Tensor: Output tensor (#batch, time1, d_model).
        &quot;&quot;&quot;
        q, k, v = self.forward_qkv(query, key, value)
        q = q.transpose(1, 2)  # (batch, time1, head, d_k)

        p = self.linear_pos(pos_emb).view(-1, self.h, self.d_k)  # (2*time2-1, head, d_k)
        p = p.transpose(0, 1)  # (head, 2*time2-1, d_k)

        # (batch, head, time1, d_k)
        q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2)
        # (batch, head, time1, d_k)
        q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2)

        # compute attention score
        # first compute matrix a and matrix c
        # as described in https://arxiv.org/abs/1901.02860 Section 3.3
        # (batch, head, time1, time2)
        matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))

        # compute matrix b and matrix d
        # (batch, head, time1, 2*time2 -1)
        matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
        # Remove rel_shift since it is useless in speech recognition,
        # and it requires special attention for streaming.
        matrix_bd = self.rel_shift(matrix_bd)
        matrix_bd = matrix_bd[:, :, :, :matrix_ac.size(3)]
        scores = (matrix_ac + matrix_bd) / math.sqrt(
            self.d_k)  # (batch, head, time1, time2)

        return self.forward_attention(v, scores, mask)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;其中matrix_bd的计算:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;p = self.linear_pos(pos_emb).view(-1, self.h, self.d_k)  # (2*time2-1, head, d_k)
p = p.transpose(0, 1)  # (head, 2*time2-1, d_k)
matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
matrix_bd = self.rel_shift(matrix_bd)
matrix_bd = matrix_bd[:, :, :, :matrix_ac.size(3)]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;attention-score矩阵左移操作&quot;&gt;Attention Score矩阵左移操作&lt;/h3&gt;

&lt;p&gt;rel_shift会对一个矩阵进行左移操作。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    def rel_shift(self, x):
        &quot;&quot;&quot;Compute relative positinal encoding.
        Args:
            x (torch.Tensor): Input tensor (batch, head, time1, time2)
            (batch, time, size).
            zero_triu (bool): If true, return the lower triangular part of
                the matrix.
        Returns:
            torch.Tensor: Output tensor.
        &quot;&quot;&quot;
        zero_pad = torch.zeros((x.size(0), x.size(1), x.size(2), 1),
                               device=x.device,
                               dtype=x.dtype)
        x_padded = torch.cat([zero_pad, x], dim=-1)

        x_padded = x_padded.view(x.size(0),
                                 x.size(1),
                                 x.size(3) + 1, x.size(2))
        x = x_padded[:, :, 1:].view_as(x)
        return x
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;下面以C=3,L=4举例，&lt;/p&gt;

&lt;p&gt;对于一个C x (2L-1)的矩阵，总共用C*(2L-1)个元素，&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;tensor([[[[ 1.,  2.,  3.,  4.,  5.,  6.,  7.],
          [ 8.,  9., 10., 11., 12., 13., 14.],
          [ 15., 16., 17., 18., 19., 20., 21.]]]])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;每一行开头增加一个0，&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;tensor([[[[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],
          [ 0.,  8.,  9., 10., 11., 12., 13., 14.],
          [ 0., 15., 16., 17., 18., 19., 20., 21.]]]])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;变为C*(2L-1)+C个元素，然后将行列展开成一行，&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;tensor([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  0.,  8.,  9., 10., 11., 12.,
        13., 14.,  0., 15., 16., 17., 18., 19., 20., 21.])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;去除开头的C个元素，&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;tensor([ 3.,  4.,  5.,  6.,  7.,  0.,  8.,  9., 10., 11., 12., 13., 14.,  0.,
        15., 16., 17., 18., 19., 20., 21.])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;再排列成C x (2L-1)的矩阵。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;tensor([[[[ 3.,  4.,  5.,  6.,  7.,  0.,  8.],
          [ 9., 10., 11., 12., 13., 14.,  0.],
          [15., 16., 17., 18., 19., 20., 21.]]]])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;取前L列&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;tensor([[[[ 3.,  4.,  5.],
          [ 9., 10., 11.],
          [15., 16., 17.]]]])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name></name></author><summary type="html"></summary></entry><entry><title type="html">Kaldi中的ivector-原理和实现</title><link href="http://placebokkk.github.io/kaldi/2020/05/08/asr-kaldi-ivector.html" rel="alternate" type="text/html" title="Kaldi中的ivector-原理和实现" /><published>2020-05-08T03:11:59+00:00</published><updated>2020-05-08T03:11:59+00:00</updated><id>http://placebokkk.github.io/kaldi/2020/05/08/asr-kaldi-ivector</id><content type="html" xml:base="http://placebokkk.github.io/kaldi/2020/05/08/asr-kaldi-ivector.html">&lt;ul class=&quot;table-of-content&quot; id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#本文目的&quot; id=&quot;markdown-toc-本文目的&quot;&gt;本文目的&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#gmm-ubm模型-gmm-universal-background-model&quot; id=&quot;markdown-toc-gmm-ubm模型-gmm-universal-background-model&quot;&gt;GMM-UBM模型( GMM Universal Background Model)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#fa因子分析模型&quot; id=&quot;markdown-toc-fa因子分析模型&quot;&gt;FA（因子分析）模型&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#fa-参数估计&quot; id=&quot;markdown-toc-fa-参数估计&quot;&gt;FA 参数估计&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#fa-推断&quot; id=&quot;markdown-toc-fa-推断&quot;&gt;FA 推断&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#ivector模型&quot; id=&quot;markdown-toc-ivector模型&quot;&gt;Ivector模型&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#kaldi的实现&quot; id=&quot;markdown-toc-kaldi的实现&quot;&gt;Kaldi的实现&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#high-level脚本&quot; id=&quot;markdown-toc-high-level脚本&quot;&gt;high-level脚本&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#kaldi的计算ivector脚本&quot; id=&quot;markdown-toc-kaldi的计算ivector脚本&quot;&gt;Kaldi的计算Ivector脚本&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#kaldi中ivector的c实现&quot; id=&quot;markdown-toc-kaldi中ivector的c实现&quot;&gt;Kaldi中Ivector的C++实现&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#附录&quot; id=&quot;markdown-toc-附录&quot;&gt;附录&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#kaldi中计算gmm成分后验&quot; id=&quot;markdown-toc-kaldi中计算gmm成分后验&quot;&gt;Kaldi中计算GMM成分后验&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#kaldi训练pca的脚本&quot; id=&quot;markdown-toc-kaldi训练pca的脚本&quot;&gt;Kaldi训练PCA的脚本&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#kaldi训练gmm-ubm的脚本&quot; id=&quot;markdown-toc-kaldi训练gmm-ubm的脚本&quot;&gt;Kaldi训练GMM-UBM的脚本&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#c实现&quot; id=&quot;markdown-toc-c实现&quot;&gt;C++实现&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#参考文献&quot; id=&quot;markdown-toc-参考文献&quot;&gt;参考文献&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;本文目的&quot;&gt;本文目的&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;学习GMM-UBM/FA/Ivector的基本原理。&lt;/li&gt;
  &lt;li&gt;学习Kaldi的实现和Ivector论文中公式的对应关系。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;gmm-ubm模型-gmm-universal-background-model&quot;&gt;GMM-UBM模型( GMM Universal Background Model)&lt;/h2&gt;
&lt;p&gt;用GMM来建模语音特征，即假设每一帧语音独立同分布于一个GMM分布。&lt;/p&gt;

&lt;p&gt;i是第i个utterance（一个utterance对应一个不同speaker），t表示是第t时刻的帧，c是GMM的成分索引。则
&lt;script type=&quot;math/tex&quot;&gt;p\left(\mathbf{o}_{i t}\right)=\sum_{c=1}^{C} \lambda_{c} \mathcal{N}\left(\mathbf{o}_{i t} | \boldsymbol{\mu}_{c}, \mathbf{\Sigma}_{c}\right), \quad t=1, \ldots, T_{i}&lt;/script&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;UBM(Universal Backgound GMM) - 所有训练数据用最大似然估计(EM)训练出的GMM， 得到UBM参数 &lt;script type=&quot;math/tex&quot;&gt;\lambda_{c}^{(b)}&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\mu}_{c}^{(b)}&lt;/script&gt; &lt;script type=&quot;math/tex&quot;&gt;\mathbf{\Sigma}_{c}^{(b)}&lt;/script&gt;&lt;/li&gt;
  &lt;li&gt;Target GMM - 特定目标（比如某个说话人）的语音的训练出的GMM。每个uttrance估计出自己的GMM参数，第i个uttrance的GMM参数是 &lt;script type=&quot;math/tex&quot;&gt;\lambda_{ic}&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\mu}_{ic}&lt;/script&gt; &lt;script type=&quot;math/tex&quot;&gt;\mathbf{\Sigma}_{ic}&lt;/script&gt;
若直接Target数据做EM估计GMM，一方面数据少，训练不充分，另一方面其混合成分和UBM的混合成分的对应关系未知。 所以一般使用target训练数据在UBM上做adaptation训练，从而高斯混合成分和UBM是对应的。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;基于GMM-UBM说话人验证任务过程&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;训练全局GMM&lt;/li&gt;
  &lt;li&gt;说话人说几句话注册(Enroll), 从而得到该说话人的语音。&lt;/li&gt;
  &lt;li&gt;用该说话人的语音学习Target-GMM&lt;/li&gt;
  &lt;li&gt;说话人验证(Verification), 对于一段语音，如果该语音在Target-GMM上的似然 减去 其在UBM-GMM上的似然 大于阈值，则认为是该Target的声音。&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Supervector的概念&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;除了计算似然，还可以从另一个角度去使用GMM-UBM框架做说话人识别。&lt;/p&gt;

&lt;p&gt;将GMM的每个高斯成分的均值拼接成一个长向量（supervector）。这个向量表征了说话人的信息。对于一个语音，在UBM-GMM上用MAP去更新参数（每个高斯成分均值，高斯成分的权重），将得到的新的高斯成分均值拼起来，作为这个语音的说话人信息向量。
用该向量和Target-GMM的均值组成的超向量去计算相似度（比如cosine距离），如果相似度大于阈值，则认为是该Target发出的声音。&lt;/p&gt;

&lt;h2 id=&quot;fa因子分析模型&quot;&gt;FA（因子分析）模型&lt;/h2&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;x = m + z*V + \epsilon&lt;/script&gt;
什么是因子分析模型？&lt;/p&gt;

&lt;p&gt;考虑一个问题：全世界人任何两个人长得都不一样。但是我们描述一个人的长相时并不是从像素点去描述，而是会说他是亚洲脸，这个人的嘴巴很小。
这里亚洲脸，嘴巴大小这些就叫因子。&lt;/p&gt;

&lt;p&gt;脸 = 平均人脸 + 本质特征 * 特征展现矩阵（本质的特征 -&amp;gt; 脸上的展现） + 随机扰动&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;x：每个人的脸的像素点。&lt;/li&gt;
  &lt;li&gt;m：平均的脸的像素点。&lt;/li&gt;
  &lt;li&gt;z：本质特征，但是你本质特征不是脸上的像素点，是一个更抽象的描述，可能是一个维度更低的量，比如
[肤色，性别，年龄，名族]甚至 [嘴型，脸型，鼻型，眼型，眉形，胡须型，肤质，耳形…]。&lt;/li&gt;
  &lt;li&gt;V：本质特征（特征空间）反映到脸上（观察空间）的一个变换。&lt;/li&gt;
  &lt;li&gt;epsilon： 一些随机变化。比如双胞胎，因为他们[肤色，年龄，民族]肯定一样，而他们的[嘴型，脸型，鼻型，眼型，眉形，胡须型，肤质，耳形。。。]因为遗传也非常相似，
但是epson还是会引入一些随机变化，所以两者的脸在像素级别看肯定还是有不同的，但是这种微小的差别可能妈妈都分不出来。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;我们看看脸怎么来的，概率图模型或者生成模型。&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;有一个很不错平均脸。&lt;/li&gt;
  &lt;li&gt;上帝、父母和你自己一起选择了一些特征。&lt;/li&gt;
  &lt;li&gt;这些特征会根据共同的规则V作用在平均脸上。比如”肤色=白”这个描述，会让你脸上所有的像素点的颜色变浅。&lt;/li&gt;
  &lt;li&gt;再加点随机扰动&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;两个，根据这个模型，如果我们知道了V，则对于一个x可以得到其更本质的表示，这个表示。
当然，这个V可以是人类的先验知识，也可以是通过&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;参数估计（训练）：给定很多x，学习V&lt;/li&gt;
  &lt;li&gt;推断：给定一个x，已知V，得到x对应的z。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;训练
&lt;script type=&quot;math/tex&quot;&gt;x = m + z*V + \epsilon&lt;/script&gt;
其中&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;z服从高斯分布 &lt;script type=&quot;math/tex&quot;&gt;N(z\|0,I)&lt;/script&gt;&lt;/li&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;\epsilon&lt;/script&gt; 服从高斯分布 &lt;script type=&quot;math/tex&quot;&gt;N(\epsilon\|0,\Sigma)&lt;/script&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;fa-参数估计&quot;&gt;FA 参数估计&lt;/h3&gt;
&lt;p&gt;通过EM算法去求最大化似然&lt;script type=&quot;math/tex&quot;&gt;log_{p(X)}&lt;/script&gt;，即不停迭代最大化&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;E_{p(Z|X)}{[p(X,Z)]}&lt;/script&gt;

&lt;p&gt;这里直接给出结果，关于FA的推导，可以参考PRML第10章和FA-Ivector的FA部分。理解这个推导需要用到的基础知识&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;EM算法 - 通过迭代最大化联合分布在隐变量条件分布下的期望，a求含有隐变量的模型的最大似然解。&lt;/li&gt;
  &lt;li&gt;理解高斯分布的配方 - 高斯分布的乘法和积分运算仍是高斯，计算后的均值和方差可以通过配方法找出。&lt;/li&gt;
  &lt;li&gt;矩阵向量的基本运算 - 某些形式的求导公式。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;E-步，计算隐变量的统计量&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\left\langle\mathbf{z}_{i} | \mathbf{x}_{i}\right\rangle=\mathbf{L}^{-1} \mathbf{V}^{\top} \mathbf{\Sigma}^{-1}\left(\mathbf{x}_{i}-\mathbf{m}\right)&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\left\langle\mathbf{z}_{i} \mathbf{z}_{i}^{\top} | \mathbf{x}_{i}\right\rangle=\mathbf{L}^{-1}+\left\langle\mathbf{z}_{i} | \mathbf{x}_{i}\right\rangle\left\langle\mathbf{z}_{i} | \mathbf{x}_{i}\right\rangle^{\top}&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\mathbf{L}=\mathbf{I}+\mathbf{V}^{\top} \mathbf{\Sigma}^{-1} \mathbf{V}&lt;/script&gt;

&lt;p&gt;M-步,更新参数。&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\mathbf{V}^{\prime}=\left[\sum_{i}\left(\mathbf{x}_{i}-\mathbf{m}^{\prime}\right)\left\langle\mathbf{z}_{i} | \mathbf{x}_{i}\right\rangle^{\top}\right]\left[\sum_{i}\left\langle\mathbf{z}_{i} \mathbf{z}_{i}^{\top} | \mathbf{x}_{i}\right\rangle\right]^{-1}&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\mathbf{m}^{\prime}=\frac{1}{N} \sum_{i} \mathbf{x}_{i}&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\boldsymbol{\Sigma}^{\prime}=\frac{1}{N}\left\{\sum_{i=1}^{N}\left[\left(\mathbf{x}_{i}-\mathbf{m}^{\prime}\right)\left(\mathbf{x}_{i}-\mathbf{m}^{\prime}\right)^{\top}-\mathbf{V}^{\prime}\left\langle\mathbf{z}_{i} | \mathbf{x}_{i}\right\rangle\left(\mathbf{x}_{i}-\mathbf{m}^{\prime}\right)^{\top}\right]\right\}&lt;/script&gt;

&lt;h3 id=&quot;fa-推断&quot;&gt;FA 推断&lt;/h3&gt;
&lt;p&gt;已知模型参数，给定一个x，求其对应的z的期望值，&lt;script type=&quot;math/tex&quot;&gt;E_{p(z|x)}[z]&lt;/script&gt;.也就是参数估计里E步中的&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\left\langle\mathbf{z}_{i} | \mathbf{x}_{i}\right\rangle=\mathbf{L}^{-1} \mathbf{V}^{\top} \mathbf{\Sigma}^{-1}\left(\mathbf{x}_{i}-\mathbf{m}\right)&lt;/script&gt;

&lt;h2 id=&quot;ivector模型&quot;&gt;Ivector模型&lt;/h2&gt;

&lt;p&gt;在GMM-UBM模型部分介绍了supervector，第i个uttrance的supervector  &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\mu}_{i}&lt;/script&gt;是对第i句话的一种表示，这种表示可以把不同长度的uttrance用等长度的向量表示出来，从而大家在同一个向量空间中，可以进行相似度计算。更进一步，&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\mu}_{i}&lt;/script&gt; 本身也可以用FA模型来建模，从而得到更本质的表示。&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\boldsymbol{\mu}_{i}=\boldsymbol{m}+\mathbf{T} \mathbf{w}_{i}&lt;/script&gt;

&lt;p&gt;supervector是各个GMM的成分均值拼起来的，如果按各成分拆开则有：（注意这里是&lt;script type=&quot;math/tex&quot;&gt;\mathbf{w}_{i}&lt;/script&gt; 而不是&lt;script type=&quot;math/tex&quot;&gt;\mathbf{w}_{ic}&lt;/script&gt;，这里是对拼接的supervector做因子分析，并不是各个成分的&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\mu}_{i c}&lt;/script&gt;有自己的因子模型）&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\boldsymbol{\mu}_{i c}=\boldsymbol{m}_{c}+\mathbf{T}_{c} \mathbf{w}_{i}, \quad c=1, \ldots, C&lt;/script&gt;

&lt;p&gt;其中&lt;script type=&quot;math/tex&quot;&gt;\mathbf{T} = [\mathbf{T}_1^t,...,\mathbf{T}_C^t]^t&lt;/script&gt;;&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{m}= [\boldsymbol{m}_1^t,...,\boldsymbol{m}_C^t]^t&lt;/script&gt;;&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\mu}_{i} = [\boldsymbol{\mu}_{i1}^t,...,\boldsymbol{\mu}_{iC}^t]^t&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;每个uttrance都有自己的GMM，比如第i个uttrance的各个时刻t的特征服从如下GMM模型：&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;p\left(\mathbf{o}_{i t}\right)=\sum_{c=1}^{C} \lambda_{ic} \mathcal{N}\left(\mathbf{o}_{i t} | \boldsymbol{\mu}_{ic}, \mathbf{\Sigma}_{ic}\right), \quad t=1, \ldots, T_{i}&lt;/script&gt;

&lt;p&gt;用UBM中计算得到的的&lt;script type=&quot;math/tex&quot;&gt;\lambda_{c}^{(b)}&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\mu}_{c}^{(b)}&lt;/script&gt; &lt;script type=&quot;math/tex&quot;&gt;\mathbf{\Sigma}_{c}^{(b)}&lt;/script&gt;代替&lt;script type=&quot;math/tex&quot;&gt;\lambda_{ic}&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{m}_c&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;\mathbf{\Sigma}_{ic}&lt;/script&gt;，得到&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;p\left(\mathbf{o}_{i t}\right)=\sum_{c=1}^{C} \lambda_{c}^{(b)} \mathcal{N}\left(\mathbf{o}_{i t} | \boldsymbol{\mu}_{ic}, \mathbf{\Sigma}_{c}^{(b)}\right), \quad t=1, \ldots, T_{i}&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\boldsymbol{\mu}_{i c}=\boldsymbol{\mu}_{c}^{(b)}+\mathbf{T}_{c} \mathbf{w}_{i}, \quad c=1, \ldots, C&lt;/script&gt;

&lt;p&gt;其中&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;\lambda_{c}^{(b)}&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\mu}_{c}^{(b)}&lt;/script&gt; &lt;script type=&quot;math/tex&quot;&gt;\mathbf{\Sigma}_{c}^{(b)}&lt;/script&gt; 是已知的参数。&lt;/li&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;\mathbf{T}_{c}&lt;/script&gt;是未知的参数。&lt;/li&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\mu}_{ic}&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;\mathbf{w}_{i}&lt;/script&gt;是隐随机变量&lt;/li&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;\mathbf{o}_{i t}&lt;/script&gt; 是已知的随机变量&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;如上的模型就是Ivector模型，其本质是：&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;对GMM成分均值拼接成的超向量随机变量用FA建模，并直接使用UBM的参数作为高斯混合权重，成分方差和FA的均值参数值。&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;我把它简称为UBM-constrainted-FA-GMM模型。&lt;/p&gt;

&lt;p&gt;GMM-UBM/FA/Ivector各自的概率图模型表示如下：&lt;/p&gt;

&lt;table&gt;
    &lt;tr&gt;
        &lt;td&gt;&lt;center&gt;&lt;img src=&quot;/assets/images/ivector/gmm.png&quot; /&gt;GMM &lt;/center&gt;&lt;/td&gt;
        &lt;td&gt;&lt;center&gt;&lt;img src=&quot;/assets/images/ivector/fa.png&quot; /&gt;FA&lt;/center&gt;&lt;/td&gt;
        &lt;td&gt;&lt;center&gt;&lt;img src=&quot;/assets/images/ivector/ivector.png&quot; /&gt;Ivector&lt;/center&gt;&lt;/td&gt;
    &lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;两篇文献和Kaldi实现的符号对比说明&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;FA-ivector的下标i表示第i个uttrance样本&lt;/li&gt;
  &lt;li&gt;Simple-Ivector省略下标i&lt;/li&gt;
  &lt;li&gt;kaldi里的下标i对应公式中的c&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;说明&lt;/th&gt;
      &lt;th&gt;FA-ivector&lt;/th&gt;
      &lt;th&gt;Simple-Ivector&lt;/th&gt;
      &lt;th&gt;Kaldi&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;GMM成分索引&lt;/td&gt;
      &lt;td&gt;c&lt;/td&gt;
      &lt;td&gt;c&lt;/td&gt;
      &lt;td&gt;i&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;高斯成分的权重&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;\omega&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;-&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ubm得到第c个成分的均值&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;\gamma_{c}(o_{it})&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;\gamma_{t,c}&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;weight(i)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;对齐到第c个成分的统计量&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;N_{ic}&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;\eta_{c}&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;gamma(i)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ubm得到的均值&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;\mu_{c}^{(b)}&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;\mu_{c}&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;Means_(i)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ivector隐变量的条件期望&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
&lt;w_i|\mathcal{O}_i&gt; %]]&gt;&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;w&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;ivec_mean&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ivector隐变量平方的条件期望&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
&lt;w_i w_i|\mathcal{O}_i&gt; %]]&gt;&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;w&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;ivec_mean&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;f&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
&lt;w_i|\mathcal{O}_i&gt; %]]&gt;&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;w&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;R&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;第c个成分的变换矩阵&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;T_c&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;T^{(c)}&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;M(i)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;计算T的第一项&lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td&gt;C&lt;/td&gt;
      &lt;td&gt;Y&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;计算T的第二项&lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td&gt;A&lt;/td&gt;
      &lt;td&gt;R&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td&gt;&lt;script type=&quot;math/tex&quot;&gt;T^{(c)'} \Sigma^{-1} T^{(c)}&lt;/script&gt;&lt;/td&gt;
      &lt;td&gt;U(i)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;纠正&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;公式(4)需要除上分母p(x)&lt;/li&gt;
  &lt;li&gt;公式(10)不带求逆&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;from SJTU 王帅 phd: Ivector如何去除文本相关信息，只保留ivector 本质上是对帧级别的统计量求了平均，ivector 本质上是对帧级别的统计量求了平均。&lt;/p&gt;

&lt;h2 id=&quot;kaldi的实现&quot;&gt;Kaldi的实现&lt;/h2&gt;

&lt;h3 id=&quot;high-level脚本&quot;&gt;high-level脚本&lt;/h3&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# computing a PCA transform from the fbank data.&quot;
steps/online/nnet2/get_pca_transform.sh
# training the diagonal UBM.&quot;
steps/online/nnet2/train_diag_ubm.sh 
# training the iVector extractor&quot;
steps/online/nnet2/train_ivector_extractor.sh
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;其中&lt;a href=&quot;#kaldi训练pca的脚本&quot;&gt;计算PCA&lt;/a&gt;和&lt;a href=&quot;#kaldi训练gmm-ubm的脚本&quot;&gt;计算UBM&lt;/a&gt;放在全文最后，这里直接介绍第三步，计算Ivecotr。&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;kaldi的计算ivector脚本&quot;&gt;Kaldi的计算Ivector脚本&lt;/h3&gt;
&lt;p&gt;计算GMM-UBM后验用的feat和更新ivector统计量用的feat不一样。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;gmm_feats=&quot;ark,s,cs:apply-cmvn-online --config=$dir/online_cmvn.conf --spk2utt=ark:$sdata/JOB/spk2utt $dir/global_cmvn.stats scp:$sdata/JOB/feats.scp ark:- | splice-feats $splice_opts ark:- ark:- | transform-feats $dir/final.mat ark:- ark:- | subsample-feats --n=$subsample ark:- ark:- |&quot;

feats=&quot;ark,s,cs:splice-feats $splice_opts scp:$sdata/JOB/feats.scp ark:- | transform-feats $dir/final.mat ark:- ark:- | subsample-feats --n=$subsample ark:- ark:- |&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;模型训练流程&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;ivector-extractor-init --ivector-dim=$ivector_dim --use-weights=false \
     &quot;gmm-global-to-fgmm $dir/final.dubm -|&quot; $dir/0.ie

gmm-global-get-post --n=$num_gselect --min-post=$min_post $dir/final.dubm &quot;$gmm_feats&quot; ark:- \| \
    scale-post ark:- $modified_posterior_scale &quot;ark:|gzip -c &amp;gt;$dir/post.JOB.gz&quot; || exit 1;

Args=() # bash array of training commands for 1:nj, that put accs to stdout.
for j in $(seq $nj_full); do
  Args[$j]=`echo &quot;ivector-extractor-acc-stats --num-threads=$num_threads $dir/$x.ie '$feats' 'ark,s,cs:gunzip -c $dir/post.JOB.gz|' -|&quot; | sed s/JOB/$j/g`
done

for g in $(seq $nj); do
  start=$[$num_processes*($g-1)+1]
  ivector-extractor-sum-accs --parallel=true &quot;${Args[@]:$start:$num_processes}&quot; $dir/acc.$x.$g 
done

for j in $(seq $nj); do
      accs+=&quot;$dir/acc.$x.$j &quot;
done

ivector-extractor-sum-accs $accs $dir/acc.$x 
ivector-extractor-est --num-threads=$nt $dir/$x.ie $dir/acc.$x $dir/$[$x+1].ie 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;kaldi中ivector的c实现&quot;&gt;Kaldi中Ivector的C++实现&lt;/h3&gt;
&lt;p&gt;Kaldi在实现Ivector时，基于SGMM框架，和Ivecotr标准公式有些不制止，idiap在kaldi的基础上做了一些调整，实现了一个和公式完全一致的版本。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;代码: https://github.com/idiap/kaldi-ivector&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;ivector-extractor-acc-stats 
{
  utt_stats.AccStats(feats, post); //利用r计算0阶/1阶。
  CommitStatsForUtterance(extractor, utt_stats);//计算C/A，mean,Var
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;更新？？？&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;void IvectorExtractorConv::GetStats(
    const MatrixBase&amp;lt;BaseFloat&amp;gt; &amp;amp;feats,
    const MatrixBase&amp;lt;BaseFloat&amp;gt; &amp;amp;post,
    IvectorExtractorConvUtteranceStats *stats) const {
  typedef std::vector&amp;lt;std::pair&amp;lt;int32, BaseFloat&amp;gt; &amp;gt; VecType;

  int32 num_frames = feats.NumRows(), num_gauss = NumGauss(),
      feat_dim = FeatDim();
  KALDI_ASSERT(feats.NumCols() == feat_dim);
  KALDI_ASSERT(stats-&amp;gt;gamma.Dim() == num_gauss &amp;amp;&amp;amp;
               stats-&amp;gt;X.NumCols() == feat_dim);
  bool update_variance = (!stats-&amp;gt;S.empty());
  
  for (int32 t = 0; t &amp;lt; num_frames; t++) {
    SubVector&amp;lt;BaseFloat&amp;gt; frame(feats, t);
    SpMatrix&amp;lt;double&amp;gt; outer_prod;
    if (update_variance) {
      outer_prod.Resize(feat_dim);
      outer_prod.AddVec2(1.0, frame);
    }
    for (int32 i = 0; i &amp;lt; num_gauss; i++) {
      double weight = post(t,i);
      stats-&amp;gt;gamma(i) += weight;
      stats-&amp;gt;X.Row(i).AddVec(weight, frame);
      if (update_variance)
        stats-&amp;gt;S[i].AddSp(weight, outer_prod);
    }
  }

  for (int32 i = 0; i &amp;lt; num_gauss; i++) {
      stats-&amp;gt;X.Row(i).AddVec(-stats-&amp;gt;gamma(i), Means_.Row(i));
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;计算？？&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;CommitStatsForUtterance
{
 extractor.GetIvectorDistribution(utt_stats,
                                   &amp;amp;ivec_mean,
                                   &amp;amp;ivec_var);//mean,var
  CommitStatsForM(extractor, utt_stats, ivec_mean, ivec_var);//计算C/A，
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;计算？？&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;GetIvectorDistribution
{
  GetIvectorDistMean(utt_stats, &amp;amp;linear, &amp;amp;quadratic);
    GetIvectorDistPrior(utt_stats, &amp;amp;linear, &amp;amp;quadratic);
    if (var != NULL) {
      var-&amp;gt;CopyFromSp(quadratic);
      var-&amp;gt;Invert(); // now it's a variance.

      // mean of distribution = quadratic^{-1} * linear...
      mean-&amp;gt;AddSpVec(1.0, *var, linear, 0.0);
    } else {
      quadratic.Invert();
      mean-&amp;gt;AddSpVec(1.0, quadratic, linear, 0.0);
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;计算？？&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;void IvectorExtractor::GetIvectorDistMean(
    const IvectorExtractorUtteranceStats &amp;amp;utt_stats,
    VectorBase&amp;lt;double&amp;gt; *linear,
    SpMatrix&amp;lt;double&amp;gt; *quadratic) const {
  int32 I = NumGauss();
  for (int32 i = 0; i &amp;lt; I; i++) {
    double gamma = utt_stats.gamma_(i);
    if (gamma != 0.0) {
      SubVector&amp;lt;double&amp;gt; x(utt_stats.X_, i); // == \gamma(i) \m_i
      // next line: a += \gamma_i \M_i^T \Sigma_i^{-1} \m_i
      linear-&amp;gt;AddMatVec(1.0, Sigma_inv_M_[i], kTrans, x, 1.0);
    }
  }
  SubVector&amp;lt;double&amp;gt; q_vec(quadratic-&amp;gt;Data(), IvectorDim()*(IvectorDim()+1)/2);
  q_vec.AddMatVec(1.0, U_, kTrans, utt_stats.gamma_, 1.0);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;ivector-extractor-sum-accs 
ivector-extractor-est
根据0阶/1阶统计量，和ubm参数，T等，进行EM。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;double IvectorExtractorStats::Update(
    const IvectorExtractorEstimationOptions &amp;amp;opts,
    IvectorExtractor *extractor) const {
  CheckDims(*extractor);
  if (tot_auxf_ != 0.0) {
    KALDI_LOG &amp;lt;&amp;lt; &quot;Overall auxf/frame on training data was &quot;
              &amp;lt;&amp;lt; (tot_auxf_/gamma_.Sum()) &amp;lt;&amp;lt; &quot; per frame over &quot;
              &amp;lt;&amp;lt; gamma_.Sum() &amp;lt;&amp;lt; &quot; frames.&quot;;
  }

  double ans = 0.0;
  ans += UpdateProjections(opts, extractor);
  if (extractor-&amp;gt;IvectorDependentWeights())
    ans += UpdateWeights(opts, extractor);
  if (!S_.empty())
    ans += UpdateVariances(opts, extractor);
  ans += UpdatePrior(opts, extractor); // This will also transform the ivector
                                       // space.  Note: this must be done as the
                                       // last stage, because it will make the
                                       // stats invalid for that model.
  KALDI_LOG &amp;lt;&amp;lt; &quot;Overall objective-function improvement per frame was &quot; &amp;lt;&amp;lt; ans;
  extractor-&amp;gt;ComputeDerivedVars();
  return ans;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// Note, throughout this file we use SGMM-type notation because
// that's what I'm comfortable with.
// Dimensions:
//  D is the feature dim (e.g. D = 60)
//  I is the number of Gaussians (e.g. I = 2048)
//  S is the ivector dim (e.g. S = 400)

  /// R_i, quadratic term for ivector subspace (M matrix)estimation.  This is a
  /// kind of scatter of ivectors of training speakers, weighted by count for
  /// each Gaussian.  Conceptually vector&amp;lt;SpMatrix&amp;lt;double&amp;gt; &amp;gt;, but we store each
  /// SpMatrix as a row of R_.  Conceptually, the dim is [I][S][S]; the actual
  /// dim is [I][S*(S+1)/2].
  Matrix&amp;lt;double&amp;gt; R_;

  /// Weight projection vectors, if used.  Dimension is [I][S]
  Matrix&amp;lt;double&amp;gt; w_;

  /// If we are not using weight-projection vectors, stores the Gaussian mixture
  /// weights from the UBM.  This does not affect the iVector; it is only useful
  /// as a way of making sure the log-probs are comparable between systems with
  /// and without weight projection matrices.
  Vector&amp;lt;double&amp;gt; w_vec_;

  /// Ivector-subspace projection matrices, dimension is [I][D][S].
  /// The I'th matrix projects from ivector-space to Gaussian mean.
  /// There is no mean offset to add-- we deal with it by having
  /// a prior with a nonzero mean.
  std::vector&amp;lt;Matrix&amp;lt;double&amp;gt; &amp;gt; M_;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;void IvectorExtractorConv::GetIvectorDistribution(
    const IvectorExtractorConvUtteranceStats &amp;amp;utt_stats,
    VectorBase&amp;lt;double&amp;gt; *mean,
    SpMatrix&amp;lt;double&amp;gt; *var) const {
    Vector&amp;lt;double&amp;gt; linear(IvectorDim());
    SpMatrix&amp;lt;double&amp;gt; quadratic(IvectorDim());
    GetIvectorDistMean(utt_stats, &amp;amp;linear, &amp;amp;quadratic);
    if (var != NULL) {
      var-&amp;gt;CopyFromSp(quadratic);
      var-&amp;gt;Invert(); // now it's a variance.

      // mean of distribution = quadratic^{-1} * linear...
      mean-&amp;gt;AddSpVec(1.0, *var, linear, 0.0);
    } else {
      quadratic.Invert();
      mean-&amp;gt;AddSpVec(1.0, quadratic, linear, 0.0);
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;更新Y和R，即更新C和A&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;void IvectorConvStats::CommitStatsForM(
    const IvectorExtractorConv &amp;amp;extractor,
    const IvectorExtractorConvUtteranceStats &amp;amp;utt_stats,
    const VectorBase&amp;lt;double&amp;gt; &amp;amp;ivec_mean,
    const SpMatrix&amp;lt;double&amp;gt; &amp;amp;ivec_var) {
  subspace_stats_lock_.lock();

  // We do the occupation stats here also.
  gamma_.AddVec(1.0, utt_stats.gamma);
  
  // Stats for the linear term in M:
  for  (int32 i = 0; i &amp;lt; extractor.NumGauss(); i++) {
    Y_[i].AddVecVec(1.0, utt_stats.X.Row(i),
                    Vector&amp;lt;double&amp;gt;(ivec_mean));
  }

  int32 ivector_dim = extractor.IvectorDim();
  // Stats for the quadratic term in M:
  SpMatrix&amp;lt;double&amp;gt; ivec_scatter(ivec_var);
  ivec_scatter.AddVec2(1.0, ivec_mean);
  SubVector&amp;lt;double&amp;gt; ivec_scatter_vec(ivec_scatter.Data(),
                                     ivector_dim * (ivector_dim + 1) / 2);
  R_.AddVecVec(1.0, utt_stats.gamma, ivec_scatter_vec);

  subspace_stats_lock_.unlock();
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;ivec_mean -&amp;gt; w
M-&amp;gt;T
Y-&amp;gt;C
R-&amp;gt;A
U-&amp;gt;T^T Sigma T
  /// U_i = M_i^T \Sigma_i^{-1} M_i
X_  -&amp;gt; f
i -&amp;gt; c
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;其中的i对应GMM成分c索引.&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;double impr = SolveQuadraticMatrixProblem(R, Y_[i], SigmaInv, solver_opts, &amp;amp;M),
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;计算&lt;script type=&quot;math/tex&quot;&gt;T = C_{c}A_{c}^{-1}&lt;/script&gt;, 代码表示是&lt;script type=&quot;math/tex&quot;&gt;M = Y_{i}R_{i}^{-1}&lt;/script&gt;,&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;double IvectorConvStats::UpdateProjection(
    const IvectorExtractorConvEstimationOptions &amp;amp;opts,
    int32 i,
    IvectorExtractorConv *extractor) const {
  int32 I = extractor-&amp;gt;NumGauss(), S = extractor-&amp;gt;IvectorDim();
  KALDI_ASSERT(i &amp;gt;= 0 &amp;amp;&amp;amp; i &amp;lt; I);
  /*
    For Gaussian index i, maximize the auxiliary function
       Q_i(x) = tr(M_i^T Sigma_i^{-1} Y_i)  - 0.5 tr(Sigma_i^{-1} M_i R_i M_i^T)
   */
  if (gamma_(i) &amp;lt; opts.gaussian_min_count) {
    KALDI_WARN &amp;lt;&amp;lt; &quot;Skipping Gaussian index &quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; &quot; because count &quot;
               &amp;lt;&amp;lt; gamma_(i) &amp;lt;&amp;lt; &quot; is below min-count.&quot;;
    return 0.0;
  }
  SpMatrix&amp;lt;double&amp;gt; R(S, kUndefined), SigmaInv(extractor-&amp;gt;Sigma_inv_[i]);
  SubVector&amp;lt;double&amp;gt; R_vec(R_, i); // i'th row of R; vectorized form of SpMatrix.
  SubVector&amp;lt;double&amp;gt; R_sp(R.Data(), S * (S+1) / 2);
  R_sp.CopyFromVec(R_vec); // copy to SpMatrix's memory.

  Matrix&amp;lt;double&amp;gt; M(extractor-&amp;gt;M_[i]);
  SolverOptions solver_opts;
  solver_opts.name = &quot;M&quot;;
  solver_opts.diagonal_precondition = true;
  // TODO: check if inversion is sufficient?
  double impr = SolveQuadraticMatrixProblem(R, Y_[i], SigmaInv, solver_opts, &amp;amp;M),
      gamma = gamma_(i);
  if (i &amp;lt; 4) {
    KALDI_VLOG(1) &amp;lt;&amp;lt; &quot;Objf impr for M for Gaussian index &quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; &quot; is &quot;
                  &amp;lt;&amp;lt; (impr / gamma) &amp;lt;&amp;lt; &quot; per frame over &quot; &amp;lt;&amp;lt; gamma &amp;lt;&amp;lt; &quot; frames.&quot;;
  }
  extractor-&amp;gt;M_[i].CopyFromMat(M);
  return impr;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;https://danielpovey.com/files/csl10_sgmm_preprint.pdf A.2&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;计算后验&lt;script type=&quot;math/tex&quot;&gt;\gamma&lt;/script&gt;, kaldi代码中的weight&lt;/li&gt;
  &lt;li&gt;更新&lt;script type=&quot;math/tex&quot;&gt;\eta&lt;/script&gt;, kaldi代码中的gamma&lt;/li&gt;
  &lt;li&gt;计算&lt;script type=&quot;math/tex&quot;&gt;f&lt;/script&gt;,代码中的X
    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;for (int32 t = 0; t &amp;lt; num_frames; t++) {
  for (int32 i = 0; i &amp;lt; num_gauss; i++) {
    double weight = post(t,i); // （4）
    stats-&amp;gt;gamma(i) += weight; // 
    stats-&amp;gt;X.Row(i).AddVec(weight, frame);
    if (update_variance)
      stats-&amp;gt;S[i].AddSp(weight, outer_prod);
  }
}

for (int32 i = 0; i &amp;lt; num_gauss; i++) {
    stats-&amp;gt;X.Row(i).AddVec(-stats-&amp;gt;gamma(i), Means_.Row(i));
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;相关文件
$dir/post.JOB.gz
$dir/acc.$x
$dir/$[$x+1].ie&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\omega&lt;/script&gt; 和&lt;script type=&quot;math/tex&quot;&gt;w&lt;/script&gt;区别&lt;/p&gt;

&lt;h2 id=&quot;附录&quot;&gt;附录&lt;/h2&gt;

&lt;h3 id=&quot;kaldi中计算gmm成分后验&quot;&gt;Kaldi中计算GMM成分后验&lt;/h3&gt;
&lt;p&gt;p(Mixture=c|x)
后验计算公式。
&lt;script type=&quot;math/tex&quot;&gt;\frac{\lambda_{c}^{(b)}\mathcal{N}(\mathbf{x}|\mathbf{\mu}_{c}^{(b)},\mathbf{\Sigma}_{c}^{(b)})}{\sum_{j=1}^{C}{\lambda_{j}^{(b)}\mathcal{N}(\mathbf{x}|\mathbf{\mu}_{j}^{(b)},\mathbf{\Sigma}_{j}^{(b)})}}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Kaldi里的求后验实现(src/gmmbin/gmm-global-get-post.cc)&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;求每个成分的log-likehood实现里，代码 DiagGmm::LogLikelihoods()(src/gmm/diag-gmm.cc)&lt;/li&gt;
  &lt;li&gt;求softmax. GMM的成分可能很多（比如2048个)，Kaldi里只选择似然最高的N个成分（num_post默认值50）做softmax。 代码 VectorToPosteriorEntry() (src/hmm/posterior.h)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;计算每个成分的log-likehood时:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;ln(\lambda_{c}\mathcal{N}(\mathbf{x}|\mathbf{\mu}_{c},\mathbf{\Sigma}_{c})) = \frac{1}{2}x^T\Sigma^{-1}x + \mu\Sigma^{-1}x + const&lt;/script&gt;

&lt;p&gt;其中的const部分和x无关，可以提前计算好。kaldi中的变量叫gconsts_。&lt;/p&gt;

&lt;h3 id=&quot;kaldi训练pca的脚本&quot;&gt;Kaldi训练PCA的脚本&lt;/h3&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;local/chain/train_ivector.sh: computing a PCA transform from the fbank data.
feat-to-dim scp:exp/chain/diag_ubm_fbank/train_subset/feats.scp -
steps/online/nnet2/get_pca_transform.sh --cmd queue.pl --splice-opts --left-context=3 --right-context=3 --max-utts 10000 --subsample 2 --dim 23 exp/chain/diag_ubm_fbank/train_subset exp/chain/pca_transform_fbank
Done estimating PCA transform in exp/chain/pca_transform_fbank

// bin/est-pca.cc
est-pca --dim=$dim --normalize-variance=$normalize_variance \
    --normalize-mean=$normalize_mean &quot;$feats&quot; $dir/final.mat || exit 1;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;final.mat是得到的pca&lt;/p&gt;

&lt;p&gt;查看pca matrix的dim的方法&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;kaldi/src/bin/matrix-dim exp/chain/pca_transform_fbank/final.mat
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;7帧特征拼接加上normalize_mean维一共 7 *23 +1 = 162 维。&lt;/li&gt;
  &lt;li&gt;pca矩阵 162 -&amp;gt; 23
    &lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  if (normalize_mean) {
    offset.AddMatVec(-1.0, transform, kNoTrans, sum, 0.0);
    transform.Resize(full_dim, full_dim + 1, kCopyData); // Add column to transform.
    transform.CopyColFromVec(offset, full_dim);
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;查看matrix内容&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;/export/maryland/chaoyang/kaldi/src/bin/copy-matrix --binary=false exp/chain/pca_transform_fbank/final.mat -
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;kaldi训练gmm-ubm的脚本&quot;&gt;Kaldi训练GMM-UBM的脚本&lt;/h3&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;steps/online/nnet2/train_diag_ubm.sh --cmd queue.pl --nj 15 --num-frames 700000 --num-threads 8 exp/chain/diag_ubm_fbank/train_subset 512 exp/chain/pca_transform_fbank exp/chain/diag_ubm_fbank
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;–num-frames 700000, 最多使用700000帧数据训练&lt;/li&gt;
  &lt;li&gt;512个成分的GMM&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;其训练过程就是正常的GMM模型的EM估计&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;gmm-global-init-from-feats --num-threads=$num_threads --num-frames=$num_frames --min-gaussian-weight=$min_gaussian_weight \
    --num-gauss=$num_gauss --num-gauss-init=$num_gauss_init --num-iters=$num_iters_init \
    &quot;$all_feats&quot; $dir/0.dubm 

gmm-gselect --n=$num_gselect $dir/0.dubm &quot;$feats&quot; &quot;ark:|gzip -c &amp;gt;$dir/gselect.JOB.gz&quot;;

for x in `seq 0 $[$num_iters-1]`; do
      gmm-global-acc-stats &quot;--gselect=ark,s,cs:gunzip -c $dir/gselect.JOB.gz|&quot; $dir/$x.dubm &quot;$feats&quot; $dir/$x.JOB.acc
      gmm-global-est $opt --min-gaussian-weight=$min_gaussian_weight $dir/$x.dubm &quot;gmm-global-sum-accs - $dir/$x.*.acc|&quot; $dir/$[$x+1].dubm
done
mv $dir/$num_iters.dubm $dir/final.dubm;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;kaldi/gmmbin中，gmm-global-*的相关代码是ubm相关的, dubm是对角ubm的意思&lt;/p&gt;

&lt;p&gt;比如查看gmm-ubm模型信息
/export/maryland/chaoyang/kaldi/src/gmmbin/gmm-global-info exp/chain/diag_ubm_fbank/final.dubm
number of gaussians 512
feature dimension 23&lt;/p&gt;

&lt;p&gt;比如复制gmm-ubm模型（可以用转换为文本）
/export/maryland/chaoyang/kaldi/src/gmmbin/gmm-global-copy –binary=false exp/chain/diag_ubm_fbank/final.dubm -&lt;/p&gt;

&lt;p&gt;转换为文本格式后可以查看模型的具体内容，512个成分，每个是23维的对角高斯。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;DiagGMM&amp;gt;
&amp;lt;GCONSTS&amp;gt;[512]
&amp;lt;WEIGHTS&amp;gt;[512]
&amp;lt;MEANS_INVVARS&amp;gt;  [512 * 23]
&amp;lt;INV_VARS&amp;gt;[512 * 23]
&amp;lt;/DiagGMM&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;c实现&quot;&gt;C++实现&lt;/h4&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  /// Equals log(weight) - 0.5 * (log det(var) + mean*mean*inv(var))
  Vector&amp;lt;BaseFloat&amp;gt; gconsts_;
  bool valid_gconsts_;   ///&amp;lt; Recompute gconsts_ if false
  Vector&amp;lt;BaseFloat&amp;gt; weights_;        ///&amp;lt; weights (not log).
  Matrix&amp;lt;BaseFloat&amp;gt; inv_vars_;       ///&amp;lt; Inverted (diagonal) variances
  Matrix&amp;lt;BaseFloat&amp;gt; means_invvars_;  ///&amp;lt; Means times inverted variance
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;计算单个高斯成分(component)的似然&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;BaseFloat DiagGmm::ComponentLogLikelihood(const VectorBase&amp;lt;BaseFloat&amp;gt; &amp;amp;data,
                                          int32 comp_id) const {
  BaseFloat loglike;
  Vector&amp;lt;BaseFloat&amp;gt; data_sq(data);
  data_sq.ApplyPow(2.0);

  // loglike =  means * inv(vars) * data.
  loglike = VecVec(means_invvars_.Row(comp_id), data);
  // loglike += -0.5 * inv(vars) * data_sq.
  loglike -= 0.5 * VecVec(inv_vars_.Row(comp_id), data_sq);
  return loglike + gconsts_(comp_id);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;参考文献&quot;&gt;参考文献&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;SIMPLIFICATION AND OPTIMIZATION OF I-VECTOR EXTRACTION&lt;/li&gt;
  &lt;li&gt;Lecture Notes on Factor Analysis and I-Vectors&lt;/li&gt;
  &lt;li&gt;The subspace Gaussian mixture model – a structured model for speech recognition&lt;/li&gt;
  &lt;li&gt;Implementation of the Standard I-vector System for the Kaldi Speech Recognition Toolkit&lt;/li&gt;
&lt;/ol&gt;</content><author><name></name></author><summary type="html"></summary></entry><entry><title type="html">Kaldi-nnet3-上下文和egs</title><link href="http://placebokkk.github.io/kaldi-nnet3/2020/03/15/asr-kaldi-nnet3-context.html" rel="alternate" type="text/html" title="Kaldi-nnet3-上下文和egs" /><published>2020-03-15T03:11:59+00:00</published><updated>2020-03-15T03:11:59+00:00</updated><id>http://placebokkk.github.io/kaldi-nnet3/2020/03/15/asr-kaldi-nnet3-context</id><content type="html" xml:base="http://placebokkk.github.io/kaldi-nnet3/2020/03/15/asr-kaldi-nnet3-context.html">&lt;ul class=&quot;table-of-content&quot; id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#上下文&quot; id=&quot;markdown-toc-上下文&quot;&gt;上下文&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#model-context&quot; id=&quot;markdown-toc-model-context&quot;&gt;model-context&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#extra-context&quot; id=&quot;markdown-toc-extra-context&quot;&gt;extra-context&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#网络上下文的计算&quot; id=&quot;markdown-toc-网络上下文的计算&quot;&gt;网络上下文的计算&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#egs&quot; id=&quot;markdown-toc-egs&quot;&gt;EGS&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;上下文&quot;&gt;上下文&lt;/h1&gt;

&lt;h2 id=&quot;model-context&quot;&gt;model-context&lt;/h2&gt;

&lt;p&gt;t时刻的输出label依赖的输入特征的上下文宽度叫做model-context，包括左右的model-context&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;model-left-context(也叫net-left-context， 有时在也称为left-context，需要根据语境判断)&lt;/li&gt;
  &lt;li&gt;model-right-context(也叫net-right-context，有时在也称为right-context，需要根据语境判断)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;extra-context&quot;&gt;extra-context&lt;/h2&gt;

&lt;p&gt;kaldi中还有一个概念是extra-left-context和extra-right-context，这个是用于recurrent网络的recurrent计算，
需要多少context计算得到recurrent的输入。 对于Bi-RNN，还有右侧的recurrent输入，所以需要右侧的上下文。&lt;/p&gt;

&lt;h2 id=&quot;网络上下文的计算&quot;&gt;网络上下文的计算&lt;/h2&gt;

&lt;p&gt;定义网络&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;## tdnn.network.xconfig
  input dim=40 name=input
  relu-batchnorm-layer name=tdnn dim=64 input=Append(-2,0,2)
  fast-lstm-layer name=lstm cell-dim=32 decay-time=20 delay=-3
  output-layer name=output input=lstm dim=10 max-change=1.5

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;查看其左右上下文大小&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;## steps/nnet3/xconfig_to_configs.py --xconfig-file tdnn.network.xconfig --config-dir ./
## nnet3-info ref.raw
left-context: 2
right-context: 2
num-parameters: 20586
modulus: 1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;各层参数，其中+1是affine层的bias项。相加等于20586&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;tdnn affine (40 * 3 +1)* 64 
lstm affine ((64+32)+1) * 32 * 4 
lstm nonlin 32* 3
softmax affine (32+1)*10 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;看一个更复杂的网络的上下文结果，比如我们使用wsj的chain中的tdnn模型。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    input dim=100 name=ivector
    input dim=40 name=input

    idct-layer name=idct input=input dim=40 cepstral-lifter=22 affine-transform-file=$dir/configs/idct.mat
    delta-layer name=delta input=idct
    no-op-component name=input2 input=Append(delta, Scale(1.0, ReplaceIndex(ivector, t, 0)))

    # the first splicing is moved before the lda layer, so no splicing here
    relu-batchnorm-layer name=tdnn1 $tdnn_opts dim=1024 input=input2
    tdnnf-layer name=tdnnf2 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=1
    tdnnf-layer name=tdnnf3 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=1
    tdnnf-layer name=tdnnf4 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=1
    tdnnf-layer name=tdnnf5 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=0
    tdnnf-layer name=tdnnf6 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=3
    tdnnf-layer name=tdnnf7 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=3
    tdnnf-layer name=tdnnf8 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=3
    tdnnf-layer name=tdnnf9 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=3
    tdnnf-layer name=tdnnf10 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=3
    tdnnf-layer name=tdnnf11 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=3
    tdnnf-layer name=tdnnf12 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=3
    tdnnf-layer name=tdnnf13 $tdnnf_opts dim=1024 bottleneck-dim=128 time-stride=3
    linear-component name=prefinal-l dim=192 $linear_opts

    prefinal-layer name=prefinal-chain input=prefinal-l $prefinal_opts big-dim=1024 small-dim=192
    output-layer name=output include-log-softmax=false dim=$num_targets $output_opts

    prefinal-layer name=prefinal-xent input=prefinal-l $prefinal_opts big-dim=1024 small-dim=192
    output-layer name=output-xent dim=$num_targets learning-rate-factor=$learning_rate_factor $output_opts
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;查看其左右上下文大小&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;## steps/nnet3/xconfig_to_configs.py --xconfig-file tdnn-lstm.xconfig --config-dir ./
## nnet3-info wsj/configs/ref.raw
left-context: 29
right-context: 29
num-parameters: 8642592
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;其中tdnnf的time-stride表示左右上下文，累加起来1*3 + 3*8 = 27.那为何网络左右上下文是29呢，因为delta层也会引入左右上下文依赖。delta-delta时左右上下文都为2.
因此left-context=29，right-context=29.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;delta(t) = f(t+1) - f(t-1) 
delta-delta(t)  = f(t-2) - 2f(t) + f(t+2)  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;egs&quot;&gt;EGS&lt;/h1&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;/steps/nnet3/chain/get_egs.sh
/steps/nnet3/get_egs.sh
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;nnet3需要提前生成好训练样本，生成的训练样本叫做egs(examples),会根据模型的上下文生成对应egs，一旦模型上下文变了，
egs也需要重新生成。&lt;/p&gt;

&lt;p&gt;每个example是一个长度固定chunk，即一组连续的label和其根据上下文需要的输入特征。&lt;/p&gt;

&lt;p&gt;下面的是一个模型上下文为左侧16，右侧12对应的egs,01.wav这个音频被切分成了很多chunk，-87表示第87个chunk.&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;01.wav-87 
&amp;lt;Nnet3Eg&amp;gt; 
&amp;lt;NumIo&amp;gt; 2 
    &amp;lt;NnetIo&amp;gt; input 
        &amp;lt;I1V&amp;gt; 36 
        &amp;lt;I1&amp;gt; 0 -16 0 &amp;lt;I1&amp;gt; 0 -15 0 &amp;lt;I1&amp;gt; 0 -14 0 &amp;lt;I1&amp;gt; 0 -13 0 &amp;lt;I1&amp;gt; 0 -12 0 &amp;lt;I1&amp;gt; 0 -11 0 &amp;lt;I1&amp;gt; 0 -10 0 &amp;lt;I1&amp;gt; 0 -9 0 &amp;lt;I1&amp;gt; 0 -8 0 &amp;lt;I1&amp;gt; 0 -7 0 &amp;lt;I1&amp;gt; 0 -6 0 &amp;lt;I1&amp;gt; 0 -5 0 &amp;lt;I1&amp;gt; 0 -4 0 &amp;lt;I1&amp;gt; 0 -3 0 &amp;lt;I1&amp;gt; 0 -2 0 &amp;lt;I1&amp;gt; 0 -1 0 &amp;lt;I1&amp;gt; 0 0 0 &amp;lt;I1&amp;gt; 0 1 0 &amp;lt;I1&amp;gt; 0 2 0 &amp;lt;I1&amp;gt; 0 3 0 &amp;lt;I1&amp;gt; 0 4 0 &amp;lt;I1&amp;gt; 0 5 0 &amp;lt;I1&amp;gt; 0 6 0 &amp;lt;I1&amp;gt; 0 7 0 &amp;lt;I1&amp;gt; 0 8 0 &amp;lt;I1&amp;gt; 0 9 0 &amp;lt;I1&amp;gt; 0 10 0 &amp;lt;I1&amp;gt; 0 11 0 &amp;lt;I1&amp;gt; 0 12 0 &amp;lt;I1&amp;gt; 0 13 0 &amp;lt;I1&amp;gt; 0 14 0 &amp;lt;I1&amp;gt; 0 15 0 &amp;lt;I1&amp;gt; 0 16 0 &amp;lt;I1&amp;gt; 0 17 0 &amp;lt;I1&amp;gt; 0 18 0 &amp;lt;I1&amp;gt; 0 19 0
        [
        97.30364 -3.910992 -30.80304 -3.48616 -66.96941 -29.00227 -88.99083 21.78121 -62.15462 -4.151295 -35.50327 -4.110187 -18.79502 70.5752 -1.083632 38.90316 -15.14383 -4.67984 3.844811 0.7083166 -2.214117 2.550018 1.870166 1.769193 -1.508338 0.2067747 -6.741038 5.639647 -10.63978 10.62695 -7.235626 16.03898 -12.22836 3.21749 -4.498186 1.417891 2.665665 -1.110982 -5.823317 1.687254
        99.10075 2.414833 -38.25296 -1.217627 -71.97943 -41.72618 -68.26828 18.00008 -59.13413 -6.729376 -18.06305 -11.4845 -19.0238 69.58968 4.329955 42.28728 2.413088 -11.88971 -5.693924 5.658363 -0.2441978 4.228565 0.1156468 2.205399 -3.323665 -0.6477451 1.101045 5.354781 -3.874245 4.511787 -4.556805 9.047355 -13.33412 7.345819 -1.971818 -0.5560644 -3.297477 -3.503572 -4.566537 2.10817
        99.55003 9.926746 -53.82625 11.6374 -71.47052 -26.45749 -52.59174 5.153442 -57.12048 -26.77036 0.3643494 -47.99191 -0.248088 63.67664 -3.669809 49.73235 1.612537 -23.90616 -8.469775 -3.113039 -0.4495978 5.011887 0.7205315 1.575324 -1.529328 -0.7170305 3.179681 3.93045 6.694186 -0.7881775 -9.213675 13.28471 -13.14982 5.640185 8.76902 -1.971353 1.758175 -1.027197 -6.577384 2.859537
        ...
        ]
    &amp;lt;/NnetIo&amp;gt;
    &amp;lt;NnetIo&amp;gt; output 
        &amp;lt;I1V&amp;gt; 8 
        &amp;lt;I1&amp;gt; 0 0 0 &amp;lt;I1&amp;gt; 0 1 0 &amp;lt;I1&amp;gt; 0 2 0 &amp;lt;I1&amp;gt; 0 3 0 &amp;lt;I1&amp;gt; 0 4 0 &amp;lt;I1&amp;gt; 0 5 0 &amp;lt;I1&amp;gt; 0 6 0 &amp;lt;I1&amp;gt; 0 7 0 
        rows=8 dim=2040 [ 228 1 ] dim=2040 [ 264 1 ] dim=2040 [ 264 1 ] dim=2040 [ 264 1 ] dim=2040 [ 1631 1 ] dim=2040 [ 1631 1 ] dim=2040 [ 1631 1 ] dim=2040 [ 1631 1 ]
    &amp;lt;/NnetIo&amp;gt; 
&amp;lt;/Nnet3Eg&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;其中各标签含义如下&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;NumIo&gt; 后表示&lt;NnetIo&gt;的个数，egs里有input和ouput两个&lt;NnetIo&gt;，所以是2
&lt;/NnetIo&gt;&lt;/NnetIo&gt;&lt;/NumIo&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;NnetIo&gt; 后是该NnetIo的类型，代码里根据改值对后面进行不同的格式解析。
&lt;/NnetIo&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;I1V&gt;后面跟着帧数，输入是36帧，label是8帧。 8帧，t到t+7，所以需要的输入上下文是t-16到t+19
&lt;/I1V&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;I1&gt; 后是每帧的Index (minibatch_index, time_index, conv_index)
&lt;/I1&gt;
  &lt;/li&gt;
  &lt;li&gt;input中给出所有输入帧的特征组成的矩阵&lt;/li&gt;
  &lt;li&gt;output中给出是8帧label的具体值[228,264,264,2641631,1631,1631,1631]. 1表示概率为1(也可以用小于1的比如0.5？？label smoothing??). 2040是output pdf总数？？？？&lt;/li&gt;
&lt;/ul&gt;</content><author><name></name></author><summary type="html"></summary></entry><entry><title type="html">Kaldi-nnet3-基础知识</title><link href="http://placebokkk.github.io/kaldi-nnet3/2020/03/14/asr-kaldi-nnet3-basic.html" rel="alternate" type="text/html" title="Kaldi-nnet3-基础知识" /><published>2020-03-14T03:11:59+00:00</published><updated>2020-03-14T03:11:59+00:00</updated><id>http://placebokkk.github.io/kaldi-nnet3/2020/03/14/asr-kaldi-nnet3-basic</id><content type="html" xml:base="http://placebokkk.github.io/kaldi-nnet3/2020/03/14/asr-kaldi-nnet3-basic.html">&lt;ul class=&quot;table-of-content&quot; id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#kaldi-nnet3文档的描述&quot; id=&quot;markdown-toc-kaldi-nnet3文档的描述&quot;&gt;Kaldi Nnet3文档的描述&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#kaldi的nnet3网络结构&quot; id=&quot;markdown-toc-kaldi的nnet3网络结构&quot;&gt;Kaldi的Nnet3网络结构。&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#xconfig定义网络&quot; id=&quot;markdown-toc-xconfig定义网络&quot;&gt;xconfig定义网络&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#config网络定义&quot; id=&quot;markdown-toc-config网络定义&quot;&gt;config网络定义&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#nnet3网络定义&quot; id=&quot;markdown-toc-nnet3网络定义&quot;&gt;nnet3网络定义&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#component-node&quot; id=&quot;markdown-toc-component-node&quot;&gt;component-node&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#descriptor-node&quot; id=&quot;markdown-toc-descriptor-node&quot;&gt;descriptor-node&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#dim-range-node&quot; id=&quot;markdown-toc-dim-range-node&quot;&gt;dim-range-node&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#c&quot; id=&quot;markdown-toc-c&quot;&gt;C++&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#xconfig支持的组件类型&quot; id=&quot;markdown-toc-xconfig支持的组件类型&quot;&gt;xconfig支持的组件类型&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#config支持的component-node&quot; id=&quot;markdown-toc-config支持的component-node&quot;&gt;config支持的component-node&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;kaldi-nnet3文档的描述&quot;&gt;Kaldi Nnet3文档的描述&lt;/h1&gt;

&lt;p&gt;nnet1 和 nnet2 都是的基于Component(组件)对象设计，从而神经网络可以看作是Component的堆叠。每个Component有支持minibatch的Propagate和Backprop函数，以及其他函数。&lt;/p&gt;

&lt;p&gt;nnet1和nnet2除了支持按顺序堆叠非线性变换外，通过额外的设计，也支持一些其他功能.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;在nnet1里，可以用components中嵌套components实现更复杂的网络topo，比如ParallelComponent，该Component中可以包含多组Component序列。另外，LSTM是在C++层定义一个专用的Componet来实现的。&lt;/li&gt;
  &lt;li&gt;在nnet2里，网络设计中加入了时间index的概念，从而支持把不同时间帧的数据（包括中间层的输出）拼起来一起使用，可以支持TDNN这种模型。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nnet3的目标是在支持Nnet1和Nnet2已支持的topo基础上在支持更多的网络类型，同时提供基于配置文件的方式去构建网络，从而用户不需要做代码开发就可以实现新的网络结构的ideas。在Nnet3中，可以用最基本的组件直接构建LSTM。&lt;/p&gt;

&lt;h1 id=&quot;kaldi的nnet3网络结构&quot;&gt;Kaldi的Nnet3网络结构。&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;xconfig: 类似于keras，简洁的网络定义，xconfig覆盖了大部分常用的神经网络layer&lt;/li&gt;
  &lt;li&gt;config: kaldi实际使用的config， 基于node定义网络结构，如果xconfig无法满足需求，可在config层实现。&lt;/li&gt;
  &lt;li&gt;C++: 如果某些网络无法用config构建，或者想提高效率，则可以在C++层实现。(Kaldi本身的LSTM可以通过config实现，但是Kaldi也在C++层实现了一个更高效的LSTM)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;xconfig定义网络&quot;&gt;xconfig定义网络&lt;/h2&gt;

&lt;p&gt;假如要定义如下网络&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;特征40维，
1层tdnn,输出64维，t时刻的上下文依赖(t-2,t,t+2) 
1层lstm，cell/输出 32维, t时刻依赖t-3时刻的recurrent输入(一般t时刻依赖t-1时刻，但是kaldi里经常做3帧的跳帧)
10维softmax输出。
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;对应的xconfig文件为&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;#tdnn-lstm.xconfig
  input dim=40 name=input
  relu-batchnorm-layer name=tdnn dim=64 input=Append(-2,0,2)
  fast-lstm-layer name=lstm cell-dim=32 decay-time=20 delay=-3
  output-layer name=output input=lstm dim=10 max-change=1.5
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;其网络的拓扑如下图
&lt;img src=&quot;/assets/images/nnet3/nnet3-tdnn-lstm.png&quot; alt=&quot;nnet3-tdnn-lstm&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;config网络定义&quot;&gt;config网络定义&lt;/h1&gt;

&lt;p&gt;使用下面脚本，可以将xconifg转换为Kaldi Nnet3实际使用的config文件。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;steps/nnet3/xconfig_to_configs.py --xconfig-file tdnn-lstm.xconfig --config-dir ./
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;tdnn-lstm.xconfig转换后的网络如下，可以看到基于config的定义比较长。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;input-node name=input dim=40
component name=tdnn.affine type=NaturalGradientAffineComponent input-dim=120 output-dim=64  max-change=0.75
component-node name=tdnn.affine component=tdnn.affine input=Append(Offset(input, -2), input,  Offset(input, 2))
component name=tdnn.relu type=RectifiedLinearComponent dim=64 self-repair-scale=1e-05
component-node name=tdnn.relu component=tdnn.relu input=tdnn.affine
component name=tdnn.batchnorm type=BatchNormComponent dim=64 target-rms=1.0
component-node name=tdnn.batchnorm component=tdnn.batchnorm input=tdnn.relu

### Begin LTSM layer 'lstm'
# Gate control: contains W_i, W_f, W_c and W_o matrices as blocks.
component name=lstm.W_all type=NaturalGradientAffineComponent input-dim=96 output-dim=128  max-change=1.5
# The core LSTM nonlinearity, implemented as a single component.
# Input = (i_part, f_part, c_part, o_part, c_{t-1}), output = (c_t, m_t)
# See cu-math.h:ComputeLstmNonlinearity() for details.
component name=lstm.lstm_nonlin type=LstmNonlinearityComponent cell-dim=32  max-change=0.75
# Component for backprop truncation, to avoid gradient blowup in long training examples.
component name=lstm.cm_trunc type=BackpropTruncationComponent dim=64 clipping-threshold=30.0 zeroing-threshold=15.0 zeroing-interval=20 recurrence-interval=3 scale=1.0
###  Nodes for the components above.
component-node name=lstm.W_all component=lstm.W_all input=Append(tdnn.batchnorm, IfDefined(Offset(lstm.m_trunc, -3)))
component-node name=lstm.lstm_nonlin component=lstm.lstm_nonlin input=Append(lstm.W_all, IfDefined(Offset(lstm.c_trunc, -3)))
dim-range-node name=lstm.m input-node=lstm.lstm_nonlin dim-offset=32 dim=32
component-node name=lstm.cm_trunc component=lstm.cm_trunc input=lstm.lstm_nonlin
dim-range-node name=lstm.c_trunc input-node=lstm.cm_trunc dim-offset=0 dim=32
dim-range-node name=lstm.m_trunc input-node=lstm.cm_trunc dim-offset=32 dim=32
### End LTSM layer 'lstm'

component name=output.affine type=NaturalGradientAffineComponent input-dim=32 output-dim=10  max-change=1.5 param-stddev=0.0 bias-stddev=0.0
component-node name=output.affine component=output.affine input=lstm.m
component name=output.log-softmax type=LogSoftmaxComponent dim=10
component-node name=output.log-softmax component=output.log-softmax input=output.affine
output-node name=output input=output.log-softmax objective=linear
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;其中的依赖关系如下图。
&lt;img src=&quot;/assets/images/nnet3/nnet3.png&quot; alt=&quot;nnet3&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;nnet3网络定义&quot;&gt;nnet3网络定义&lt;/h2&gt;

&lt;p&gt;nnet3网络是由node组成的有向无环拓扑图。node有batch和时间维度的概念，语法中支持如下的node&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;component-node Kaldi提供的基础组件&lt;/li&gt;
  &lt;li&gt;dim-range-node 从上一层输出的矩阵中选取特定范围维度。&lt;/li&gt;
  &lt;li&gt;descriptor-node 起到胶水作用，提供一些方法将node组合连接起来&lt;/li&gt;
  &lt;li&gt;output-node/input-node&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;component-node&quot;&gt;component-node&lt;/h3&gt;
&lt;p&gt;component-node是对component的实例化。一般先定义一个component，再定义该component的component-node&lt;/p&gt;

&lt;p&gt;定义component时需要设置的属性&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;name 该component的名字&lt;/li&gt;
  &lt;li&gt;type 该component的Component类型&lt;/li&gt;
  &lt;li&gt;type的属性 不同的Component类型支持的属性&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;component-node时需要设置的属性&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;name  该component-node的名字，可以被其他node的input属性引用&lt;/li&gt;
  &lt;li&gt;component 该component-node的component类型&lt;/li&gt;
  &lt;li&gt;input 该component-node的输入node&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;如下先定义了输入120维，输出64维的NaturalGradientAffineComponent类型的component，叫做tdnn.affine。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;input-node name=input dim=40
component name=tdnn.affine type=NaturalGradientAffineComponent input-dim=120 output-dim=64  max-change=0.75
component-node name=tdnn.affine component=tdnn.affine input=Append(Offset(input, -2), input,  Offset(input, 2))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;再定义一个name为tdnn.affine的component-node(这里component-node和component的名字一样都叫tdnn.affine，但是这不是必要的)，
其input属性中引用了name为input的input-node。 注意区分input属性和name为input的节点。&lt;/p&gt;

&lt;p&gt;也可以按如下定义，和上面是等价的。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;input-node name=mfcc_input dim=40
component name=tdnn.affine type=NaturalGradientAffineComponent input-dim=120 output-dim=64  max-change=0.75
component-node name=tdnn.affine.node component=tdnn.affine input=Append(Offset(mfcc_input, -2), mfcc_input,  Offset(mfcc_input, 2))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;descriptor-node&quot;&gt;descriptor-node&lt;/h3&gt;
&lt;p&gt;descriptor-node提供一些常用操作，连接其他node。 descriptor-node的语法和其他node不同，其并不单独定义一行，一般出现在input中，上面配置里Append/IfDefined/Offset均为descriptor-node。&lt;/p&gt;

&lt;p&gt;比如下例中，Append(Offset(input, -2), input,  Offset(input, 2))，表示将input节点在t-2，t，t+2位置的值作为拼接起来，作为tdnn.affine的输入.&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;component name=tdnn.affine type=NaturalGradientAffineComponent input-dim=120 output-dim=64  max-change=0.75
component-node name=tdnn.affine component=tdnn.affine input=Append(Offset(input, -2), input,  Offset(input, 2))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;可见Kaldi nnet3 config层并不提供TDNN的component，而是在对Affine层的输入利用Append+Offset实现了1维Dilated卷积，也就是TDNN. 但是kaldi在xconfig层面提供TDNN。&lt;/p&gt;

&lt;p&gt;下面例子例子，中的IfDefined也是一个descriptor-node，表示如果改值存在则使用，否则使用一个零值量。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;component name=lstm.W_all type=NaturalGradientAffineComponent input-dim=96 output-dim=128  max-change=1.5
component-node name=lstm.W_all component=lstm.W_all input=Append(tdnn.batchnorm, IfDefined(Offset(lstm.m_trunc, -3)))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;dim-range-node&quot;&gt;dim-range-node&lt;/h3&gt;

&lt;p&gt;lstm.lstm_nonlin节点（关于该节点，可参考下一节C++的LSTM实现中的介绍）的输出，是单个矩阵(batch_size * dim)，其中包含了cell和output，分别占据0-31维和32-63维,所以用两个dim-range-node分别取出。
其中的lstm.cm_trunc是为了做Recurrent方向上的BPTT用的，因为太长的梯度会有可能梯度爆炸。&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;component-node name=lstm.lstm_nonlin component=lstm.lstm_nonlin input=Append(lstm.W_all, IfDefined(Offset(lstm.c_trunc, -3)))
dim-range-node name=lstm.m input-node=lstm.lstm_nonlin dim-offset=32 dim=32
component-node name=lstm.cm_trunc component=lstm.cm_trunc input=lstm.lstm_nonlin
dim-range-node name=lstm.c_trunc input-node=lstm.cm_trunc dim-offset=0 dim=32
dim-range-node name=lstm.m_trunc input-node=lstm.cm_trunc dim-offset=32 dim=32
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;c&quot;&gt;C++&lt;/h1&gt;

&lt;p&gt;在Kaldi中，实现LSTM，可以基于最基本的组件，比如用sigmond/tanh/affine编写config实现。&lt;/p&gt;

&lt;p&gt;xconfig中的lstm-layer即使用该方法，但是生成的config非常繁琐，而且也不高效。xconfig提供了一个fast-lstm-layer，其中在C++层面实现了LstmNonlinearityComponent，该Component封装了LSTM的
计算，从而config的定义更简洁。&lt;/p&gt;

&lt;p&gt;这里以LstmNonlinearityComponent为例看一下C++层。其他的层也可按类似方法分析。&lt;/p&gt;

&lt;p&gt;Kaldi的注释非常详细，LstmNonlinearityComponent的注释如下：&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;/*
  LstmNonlinearityComponent is a component that implements part of an LSTM, by
  combining together the sigmoids and tanh's, plus some diagonal terms, into
  a single block.
  We will refer to the LSTM formulation used in

  Long Short-Term Memory Recurrent Neural Network Architectures for Large Scale Acoustic Modeling&quot;
  by H. Sak et al,
  http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43905.pdf.

  Suppose the cell dimension is C.  Then outside this component, we compute
  the 4 * C-dimensional quantity consisting of 4 blocks as follows, by a single
  matrix multiplication:

  i_part = W_{ix} x_t + W_{im} m_{t-1} + b_i
  f_part = W_{fx} x_t + W_{fm} m_{t-1} + b_f
  c_part = W_{cx} x_t + W_{cm} m_{t-1} + b_c
  o_part = W_{ox} x_t + W_{om} m_{t-1} + b_o

  The part of the computation that takes place in this component is as follows.
  Its input is of dimension 5C [however, search for 'dropout' below],
  consisting of 5 blocks: (i_part, f_part, c_part, o_part, and c_{t-1}).  Its
  output is of dimension 2C, consisting of 2 blocks: c_t and m_t.

  To recap: the input is (i_part, f_part, c_part, o_part, c_{t-1}); the output is (c_t, m_t).

  This component has parameters, 3C of them in total: the diagonal matrices w_i, w_f
  and w_o.


  In the forward pass (Propagate), this component computes the following:

     i_t = Sigmoid(i_part + w_{ic}*c_{t-1})   (1)
     f_t = Sigmoid(f_part + w_{fc}*c_{t-1})   (2)
     c_t = f_t*c_{t-1} + i_t * Tanh(c_part)   (3)
     o_t = Sigmoid(o_part + w_{oc}*c_t)       (4)
     m_t = o_t * Tanh(c_t)                    (5)
    # note: the outputs are just c_t and m_t.

  [Note regarding dropout: optionally the input-dimension may be 5C + 3 instead
  of 5C in this case, the last three input dimensions will be interpreted as
  per-frame dropout masks on i_t, f_t and o_t respectively, so that on the RHS of
  (3), i_t is replaced by i_t * i_t_scale, and likewise for f_t and o_t.]

  The backprop is as you would think, but for the &quot;self-repair&quot; we need to pass
  in additional vectors (of the same dim as the parameters of the layer) that
  dictate whether or not we add an additional term to the backpropagated
  derivatives.  (This term helps force the input to the nonlinearities into the
  range where the derivatives are not too small).

  This component stores stats of the same form as are normally stored by the
  StoreStats() functions for the sigmoid and tanh units, i.e. averages of the
  activations and derivatives, but this is done inside the Backprop() functions.
  [the StoreStats() functions don't take the input data as an argument, so
  storing this data that way is impossible, and anyway it's more efficient to
  do it as part of backprop.]

  Configuration values accepted:
         cell-dim          e.g. cell-dim=1024  Cell dimension.  The input
                          dimension of this component is cell-dim * 5, and the
                          output dimension is cell-dim * 2.  Note: this
                          component implements only part of the LSTM layer,
                          see comments above.
         param-stddev     Standard deviation for random initialization of
                          the diagonal matrices (AKA peephole connections).
                          default=1.0, which is probably too high but
                          we couldn't see any reliable gain from decreasing it.
         tanh-self-repair-threshold   Equivalent to the self-repair-lower-threshold
                          in a TanhComponent; applies to both the tanh nonlinearities.
                          default=0.2, you probably won't want to change this.
         sigmoid-self-repair-threshold   Equivalent to self-repair-lower-threshold
                          in a SigmoidComponent; applies to all three of the sigmoid
                          nonlinearities.  default=0.05, you probably won't want to
                          change this.
         self-repair-scale Equivalent to the self-repair-scale in a SigmoidComponent
                          or TanhComponent; applies to both the sigmoid and tanh
                          nonlinearities.  default=1.0e-05, which you probably won't
                          want to change unless dealing with an objective function
                          that has smaller or larger dynamic range than normal, in
                          which case you might want to make it smaller or larger.
*/
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;从注释中可以看到，该Component&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;输入为 (i_part, f_part, c_part, o_part, c_{t-1})&lt;/li&gt;
  &lt;li&gt;输出为 (c_t, m_t)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;其中i_part, f_part, c_part, o_part的计算Gate和新Cell中跟x和m相关(即LSTM外部输入)的部分。&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  i_part = W_{ix} x_t + W_{im} m_{t-1} + b_i
  f_part = W_{fx} x_t + W_{fm} m_{t-1} + b_f
  c_part = W_{cx} x_t + W_{cm} m_{t-1} + b_c
  o_part = W_{ox} x_t + W_{om} m_{t-1} + b_o
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;i_part, f_part, c_part, o_part&lt;/code&gt;的计算由lstm.W_all层的输出提供。注意这里使用t-3的recurrent连接，所以是m_{t-3}.&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;component name=lstm.W_all type=NaturalGradientAffineComponent input-dim=96 output-dim=128  max-change=1.5
component-node name=lstm.W_all component=lstm.W_all input=Append(tdnn.batchnorm, IfDefined(Offset(lstm.m_trunc, -3)))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;用一个全联接层就可以完成上面四组计算&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\left( \begin{array}{c} i_{part} \\
           f_{part} \\
           c_{part} \\
           o_{part} 
           \end{array} \right)
=
\left( \begin{array}{cc} W_{ix} &amp; W_{im} \\
           W_{fx} &amp; W_{fm} \\
           W_{cx} &amp; W_{cm} \\
           W_{ox} &amp; W_{om} 
           \end{array} \right)
\left( \begin{array}{c} x_t \\
           m_{t-3} 
           \end{array} \right)
+
\left( \begin{array}{c} b_i \\
           b_f \\
           b_c \\
           b_o 
           \end{array} \right) %]]&gt;&lt;/script&gt;

&lt;p&gt;lstm_nonlin的输入为&lt;code class=&quot;highlighter-rouge&quot;&gt;input=Append(lstm.W_all, IfDefined(Offset(lstm.c_trunc, -3))&lt;/code&gt;， 即将lstm.W_all的t时刻输出和lstm.c_trunc的t-3时刻(IfDefined表示若改值不存在，则使用0)输出拼起来。
lstm.c_trunc是从lstm.lstm_nonlin提取出c部分。&lt;/p&gt;

&lt;p&gt;注意这里使用t-3的recurrent连接，所以需要的是c_{t-3}.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;component name=lstm.lstm_nonlin type=LstmNonlinearityComponent cell-dim=32  max-change=0.75
component-node name=lstm.lstm_nonlin component=lstm.lstm_nonlin input=Append(lstm.W_all, IfDefined(Offset(lstm.c_trunc, -3)))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;该网络前向计算完成下面计算:&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;     i_t = Sigmoid(i_part + w_{ic}*c_{t-1})   (1)
     f_t = Sigmoid(f_part + w_{fc}*c_{t-1})   (2)
     c_t = f_t*c_{t-1} + i_t * Tanh(c_part)   (3)
     o_t = Sigmoid(o_part + w_{oc}*c_t)       (4)
     m_t = o_t * Tanh(c_t)                    (5)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;LstmNonlinearityComponent类的Propagate和Backprop对应其前向计算和反向求导的计算。&lt;/p&gt;

&lt;p&gt;其中前向计算在 cu::ComputeLstmNonlinearity，分为CPU和GPU实现，其中CPU实现代码如下&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;CpuComputeLstmNonlinearity(const MatrixBase&amp;lt;Real&amp;gt; &amp;amp;input_mat,
                                const MatrixBase&amp;lt;Real&amp;gt; &amp;amp;params_mat,
                                MatrixBase&amp;lt;Real&amp;gt; *output) {
  int32 num_rows = input_mat.NumRows(),
      input_cols = input_mat.NumCols(),
        cell_dim = input_cols / 5;
  KALDI_ASSERT(input_cols == (cell_dim * 5) || input_cols == (cell_dim * 5) + 3);
  KALDI_ASSERT(output-&amp;gt;NumRows() == num_rows);
  KALDI_ASSERT(params_mat.NumRows() == 3);
  KALDI_ASSERT(params_mat.NumCols() == cell_dim);
  KALDI_ASSERT(output-&amp;gt;NumCols() == 2 * cell_dim);

  MatrixBase&amp;lt;Real&amp;gt; &amp;amp;output_mat = *output;
  const Real *params_data = params_mat.Data();
  int32 params_stride = params_mat.Stride();
  for (int32 r = 0; r &amp;lt; num_rows; r++) {
    const Real *input_row = input_mat.RowData(r);
    // i_scale and f_scale relate to dropout, they will normally be 1.0.
    Real i_scale = (input_cols == cell_dim*5 ? 1.0:input_row[cell_dim*5]),
         f_scale = (input_cols == cell_dim*5 ? 1.0:input_row[cell_dim*5 + 1]),
         o_scale = (input_cols == cell_dim*5 ? 1.0:input_row[cell_dim*5 + 2]);

    Real *output_row = output_mat.RowData(r);
    for (int32 c = 0; c &amp;lt; cell_dim; c++) {
      Real i_part = input_row[c];
      Real f_part = input_row[c + cell_dim];
      Real c_part = input_row[c + 2 * cell_dim];
      Real o_part = input_row[c + 3 * cell_dim];
      Real c_prev = input_row[c + 4 * cell_dim];
      Real w_ic = params_data[c];
      Real w_fc = params_data[c + params_stride];
      Real w_oc = params_data[c + params_stride * 2];
      Real i_t = ScalarSigmoid(i_part + w_ic * c_prev);
      Real f_t = ScalarSigmoid(f_part + w_fc * c_prev);
      Real c_t = f_t * f_scale * c_prev + i_t * i_scale * ScalarTanh(c_part);
      Real o_t = ScalarSigmoid(o_part + w_oc * c_t);
      Real m_t = o_t * o_scale * ScalarTanh(c_t);
      output_row[c] = c_t;
      output_row[c + cell_dim] = m_t;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;后向的CPU版本在CpuBackpropLstmNonlinearity中，过程更繁琐些。&lt;/p&gt;

&lt;h2 id=&quot;xconfig支持的组件类型&quot;&gt;xconfig支持的组件类型&lt;/h2&gt;

&lt;p&gt;xconfig支持的layer&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;#steps/libs/nnet3/xconfig/parser.py
# We have to modify this dictionary when adding new layers
config_to_layer = {
        'input' : xlayers.XconfigInputLayer,
        'output' : xlayers.XconfigTrivialOutputLayer,
        'output-layer' : xlayers.XconfigOutputLayer,
        'relu-layer' : xlayers.XconfigBasicLayer,
        'relu-renorm-layer' : xlayers.XconfigBasicLayer,
        'relu-batchnorm-dropout-layer' : xlayers.XconfigBasicLayer,
        'relu-dropout-layer': xlayers.XconfigBasicLayer,
        'relu-batchnorm-layer' : xlayers.XconfigBasicLayer,
        'relu-batchnorm-so-layer' : xlayers.XconfigBasicLayer,
        'batchnorm-so-relu-layer' : xlayers.XconfigBasicLayer,
        'batchnorm-layer' : xlayers.XconfigBasicLayer,
        'sigmoid-layer' : xlayers.XconfigBasicLayer,
        'tanh-layer' : xlayers.XconfigBasicLayer,
        'fixed-affine-layer' : xlayers.XconfigFixedAffineLayer,
        'idct-layer' : xlayers.XconfigIdctLayer,
        'affine-layer' : xlayers.XconfigAffineLayer,
        'lstm-layer' : xlayers.XconfigLstmLayer,
        'lstmp-layer' : xlayers.XconfigLstmpLayer,
        'lstmp-batchnorm-layer' : xlayers.XconfigLstmpLayer,
        'fast-lstm-layer' : xlayers.XconfigFastLstmLayer,
        'fast-lstm-batchnorm-layer' : xlayers.XconfigFastLstmLayer,
        'fast-lstmp-layer' : xlayers.XconfigFastLstmpLayer,
        'fast-lstmp-batchnorm-layer' : xlayers.XconfigFastLstmpLayer,
        'lstmb-layer' : xlayers.XconfigLstmbLayer,
        'stats-layer': xlayers.XconfigStatsLayer,
        'relu-conv-layer': xlayers.XconfigConvLayer,
        'conv-layer': xlayers.XconfigConvLayer,
        'conv-relu-layer': xlayers.XconfigConvLayer,
        'conv-renorm-layer': xlayers.XconfigConvLayer,
        'relu-conv-renorm-layer': xlayers.XconfigConvLayer,
        'batchnorm-conv-layer': xlayers.XconfigConvLayer,
        'conv-relu-renorm-layer': xlayers.XconfigConvLayer,
        'batchnorm-conv-relu-layer': xlayers.XconfigConvLayer,
        'relu-batchnorm-conv-layer': xlayers.XconfigConvLayer,
        'relu-batchnorm-noconv-layer': xlayers.XconfigConvLayer,
        'relu-noconv-layer': xlayers.XconfigConvLayer,
        'conv-relu-batchnorm-layer': xlayers.XconfigConvLayer,
        'conv-relu-batchnorm-so-layer': xlayers.XconfigConvLayer,
        'conv-relu-batchnorm-dropout-layer': xlayers.XconfigConvLayer,
        'conv-relu-dropout-layer': xlayers.XconfigConvLayer,
        'res-block': xlayers.XconfigResBlock,
        'res2-block': xlayers.XconfigRes2Block,
        'channel-average-layer': xlayers.ChannelAverageLayer,
        'attention-renorm-layer': xlayers.XconfigAttentionLayer,
        'attention-relu-renorm-layer': xlayers.XconfigAttentionLayer,
        'attention-relu-batchnorm-layer': xlayers.XconfigAttentionLayer,
        'relu-renorm-attention-layer': xlayers.XconfigAttentionLayer,
        'gru-layer' : xlayers.XconfigGruLayer,
        'pgru-layer' : xlayers.XconfigPgruLayer,
        'opgru-layer' : xlayers.XconfigOpgruLayer,
        'norm-pgru-layer' : xlayers.XconfigNormPgruLayer,
        'norm-opgru-layer' : xlayers.XconfigNormOpgruLayer,
        'fast-gru-layer' : xlayers.XconfigFastGruLayer,
        'fast-pgru-layer' : xlayers.XconfigFastPgruLayer,
        'fast-norm-pgru-layer' : xlayers.XconfigFastNormPgruLayer,
        'fast-opgru-layer' : xlayers.XconfigFastOpgruLayer,
        'fast-norm-opgru-layer' : xlayers.XconfigFastNormOpgruLayer,
        'tdnnf-layer': xlayers.XconfigTdnnfLayer,
        'prefinal-layer': xlayers.XconfigPrefinalLayer,
        'spec-augment-layer': xlayers.XconfigSpecAugmentLayer,
        'renorm-component': xlayers.XconfigRenormComponent,
        'batchnorm-component': xlayers.XconfigBatchnormComponent,
        'no-op-component': xlayers.XconfigNoOpComponent,
        'linear-component': xlayers.XconfigLinearComponent,
        'affine-component': xlayers.XconfigAffineComponent,
        'scale-component':  xlayers.XconfigPerElementScaleComponent,
        'dim-range-component': xlayers.XconfigDimRangeComponent,
        'offset-component':  xlayers.XconfigPerElementOffsetComponent,
        'combine-feature-maps-layer': xlayers.XconfigCombineFeatureMapsLayer,
        'delta-layer': xlayers.XconfigDeltaLayer
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;config支持的component-node&quot;&gt;config支持的component-node&lt;/h2&gt;

&lt;p&gt;其对应的C++ Componet如下，可以查看相应NN C++类的实现，可作为学习用，或自己添加新的Componet时参考。&lt;/p&gt;

&lt;p&gt;src/nnet3/nnet-simple-component.cc&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class PnormComponent
class DropoutComponent
class ElementwiseProductComponent
class SigmoidComponent
class TanhComponent
class RectifiedLinearComponent
class AffineComponent
class BlockAffineComponent
class RepeatedAffineComponent
class NaturalGradientRepeatedAffineComponent
class SoftmaxComponent
class LogSoftmaxComponent
class NaturalGradientAffineComponent
class LinearComponent
class FixedAffineComponent
class SumGroupComponent
class FixedScaleComponent
class FixedBiasComponent
class NoOpComponent
class SumBlockComponent
class ClipGradientComponent
class PermuteComponent
class PerElementScaleComponent
class PerElementOffsetComponent
class ConstantFunctionComponent
class NaturalGradientPerElementScaleComponent
class ScaleAndOffsetComponent
class CompositeComponent
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;src/nnet3/nnet-convolutional-component.h&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class TimeHeightConvolutionComponent
class TdnnComponent
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;src/nnet3/nnet-combined-component.cc&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class ConvolutionComponent
class LstmNonlinearityComponent
class MaxpoolingComponent
class GruNonlinearityComponent
class OutputGruNonlinearityComponent
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;src/nnet3/nnet-attention-component.cc&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class RestrictedAttentionComponent
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;src/nnet3/nnet-general-component.cc&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class DistributeComponent
class StatisticsExtractionComponent
class StatisticsPoolingComponent
class BackpropTruncationComponent
class ConstantComponent
class DropoutMaskComponent
class GeneralDropoutComponent
class SpecAugmentTimeMaskComponent
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;src/nnet3/nnet-normalize-component.cc&lt;/p&gt;
&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;class NormalizeComponent
class BatchNormComponent
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name></name></author><summary type="html"></summary></entry><entry><title type="html">CTC的Decode算法-Prefix Beam Search</title><link href="http://placebokkk.github.io/asr/2020/02/01/asr-ctc-decoder.html" rel="alternate" type="text/html" title="CTC的Decode算法-Prefix Beam Search" /><published>2020-02-01T02:00:00+00:00</published><updated>2020-02-01T02:00:00+00:00</updated><id>http://placebokkk.github.io/asr/2020/02/01/asr-ctc-decoder</id><content type="html" xml:base="http://placebokkk.github.io/asr/2020/02/01/asr-ctc-decoder.html">&lt;ul class=&quot;table-of-content&quot; id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#ctc几种常见的解码方式&quot; id=&quot;markdown-toc-ctc几种常见的解码方式&quot;&gt;CTC几种常见的解码方式&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#prefix-beam-search的笔记&quot; id=&quot;markdown-toc-prefix-beam-search的笔记&quot;&gt;prefix beam search的笔记&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#说明&quot; id=&quot;markdown-toc-说明&quot;&gt;说明&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;ctc几种常见的解码方式&quot;&gt;CTC几种常见的解码方式&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;greedy decode，每帧输出最大值，然后规整。&lt;/li&gt;
  &lt;li&gt;在ctc字符串上做beam search，输出的n个结果规整，并合并相同序列，然后再应用语言模型。(secondpass LM)&lt;/li&gt;
  &lt;li&gt;在规整字符串上做beam search, 可额外在应用语言模型。该算法叫Prefix Beam Search，可以在解码过程中直接应用LM。(firstpass LM)&lt;/li&gt;
  &lt;li&gt;使用fst静态解码。可引入语言模型和字典模型。&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;prefix-beam-search的笔记&quot;&gt;prefix beam search的笔记&lt;/h2&gt;
&lt;p&gt;本文为prefix beam search的笔记。&lt;/p&gt;

&lt;p&gt;Grave最早提出的prefix search不好理解，现在也没有人用。可直接参考Awni Hannun提出的prefix beam search。&lt;/p&gt;

&lt;p&gt;定义两个概念&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;ctc字符串:模型在每个时间点输出的字符组成的字符串。&lt;/li&gt;
  &lt;li&gt;规整字符串:即ctc字符串去除连续重复和blank后的字符串。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;prefix beam search基本思想:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;在每个时刻t，计算所有当前可能输出的规整字符串（即去除连续重复和blank的字符串）的概率。&lt;/li&gt;
  &lt;li&gt;因为t时刻的规整字符串长度最长为t，最短为0(全都是blank，所以规整完是0)，所有t时刻所有可能的候选规整字符串个数是&lt;script type=&quot;math/tex&quot;&gt;\sum_{0}^{t}{C^t}&lt;/script&gt;，其中C是字符词典大小。 该值随着t的增大而增大，穷举搜索空间太大。&lt;/li&gt;
  &lt;li&gt;用beam search的方法，在每个时刻选取最好的N个路径，从而将每个时间点t上的搜索空间变为常数。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;下图&lt;em&gt;a表示一个规整字符串,&lt;/em&gt;表示其前缀，a表示其最后一个字符是a，箭头表示t+1时刻的字符串可能由哪些t时刻的字符串产生。&lt;/p&gt;

&lt;p&gt;比如t+1时刻的*ab来自于两种情况：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;t时刻输出规整字符串*a，t+1时刻输出字符b&lt;/li&gt;
  &lt;li&gt;t时刻输出规整字符串*ab，t+1时刻输出字符b&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/CTC/prefix_beam1.png&quot; alt=&quot;prefix_beam1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;一个直接的想法是，对t时刻处在beam中的每个规整字符串，更新其对应的t+1时刻规整字符串的概率值。&lt;/p&gt;

&lt;p&gt;但是这里并不能直接使用t时刻规整字符串的概率乘上t+1时刻输出字符概率得到t+1时刻规整字符串的概率。&lt;/p&gt;

&lt;p&gt;我们看一个具体例子，假设第3时刻输出规整字符串a，第4时刻输出字符b。该规整字符串a的概率为-a-,-aa,aa-,aaa等不同的ctc字符串的概率和。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;如果是在aa-这个ctc字符串基础上，在t+1时刻再输出a,得到的ctc字符串为aa-a，其规整字符串为aa.&lt;/li&gt;
  &lt;li&gt;如果是在aaa这个ctc字符串基础上，在t+1时刻再输出a,得到的ctc字符串为aaaa，其规整字符串为a.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;可以看到两者使用同样的t+1的输出字符，却产生了不同的规整字符串。因此，需要区分对待blank和非blank结尾的ctc字符的规整概率:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;p_b(L)&lt;/script&gt; 表示所有以blank结尾且规整后是L的各ctc字符串的概率之和&lt;/li&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;p_nb(L)&lt;/script&gt; 表示所有以非blank结尾且规整后是L的各ctc字符串的概率之和&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;比如，假设T=3，则
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
\begin{aligned}
&amp; p_b(a) = p(aa-) + p(-a-) + p(a--) \\
&amp; p_{nb}(a) = p(aaa)+p(-aa) + p(--a) \\
\end{aligned} %]]&gt;&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;这里只随便看其中一个，比如&lt;script type=&quot;math/tex&quot;&gt;*a&lt;/script&gt;, 其t+1时刻可以产生规整字符串有四种情况。&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;当t+1输出是blank时，产生规整字符串*a&lt;/li&gt;
  &lt;li&gt;当t+1输出是a时，可以产生规整字符串*a&lt;/li&gt;
  &lt;li&gt;当t+1输出是a时，也可产生规整字符串*aa&lt;/li&gt;
  &lt;li&gt;当t+1输出是b时(或其他不等于a和blank的字符)，产生规整字符串*ab&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/CTC/prefix_beam2.png&quot; alt=&quot;prefix_beam2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;四种情况对应的需要更新的统计量的公式如下&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{aligned}
&amp; p_{b}^{t+1}(*a)\! &amp; \Leftarrow &amp; \;[ p_{b}^{t}(*a) + p_{nb}^{t}(*a) ] p_{ctc}^{t+1}(-) \\
&amp; p_{nb}^{t+1}(*a)\! &amp; \Leftarrow &amp; \;p_{nb}^{t}(*a)p_{ctc}^{t+1}(a) \\
&amp; p_{nb}^{t+1}(*aa)\! &amp; \Leftarrow &amp; \;p_{b}^{t}(*a)p_{ctc}^{t+1}(a) \\
&amp; p_{nb}^{t+1}(*ab)\! &amp; \Leftarrow &amp; \;[p_{b}^{t}(*a) + p_{nb}^{t}(*a)]p_{ctc}^{t+1}(b) \\
\end{aligned} %]]&gt;&lt;/script&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;\Leftarrow&lt;/script&gt; 不是赋值，而是C语言中的&lt;code class=&quot;highlighter-rouge&quot;&gt;+=&lt;/code&gt;操作。&lt;/li&gt;
  &lt;li&gt;注意， &lt;script type=&quot;math/tex&quot;&gt;p_{nb}^{t+1}(*ab)&lt;/script&gt;的值不仅来源于&lt;code class=&quot;highlighter-rouge&quot;&gt;t时刻beam里的*a路径&lt;/code&gt;，
在&lt;code class=&quot;highlighter-rouge&quot;&gt;对t时刻beam里的*b路径&lt;/code&gt;进行更新t+1的路径时，也会贡献概率。&lt;/li&gt;
&lt;/ul&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{aligned}
&amp; p_{nb}^{t+1}(*b)\! &amp; \Leftarrow &amp; \;p_{nb}^{t}(*b)p_{ctc}^{t+1}(b) \\
\end{aligned} %]]&gt;&lt;/script&gt;

&lt;h3 id=&quot;说明&quot;&gt;说明&lt;/h3&gt;
&lt;p&gt;ctc字符串上的beam search和规整字符串上的beam search的区别:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;同样的beam size下ctc字符串上的beam search，其丢掉的ctc路径比在规整字符串上做beam search的更多，所以最终的结果就更差一些。&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;参考Awni在Distill上的文章中的图片&lt;/p&gt;

&lt;p&gt;直接做beam search，可以看到beam size=3时，每个时刻只有三个路径v
&lt;img src=&quot;/assets/images/CTC/ctc_beamsearch.jpg&quot; alt=&quot;ctc_beamsearch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;在规整字符串上做beam search，可以看到beam size=3时，每个时刻可以保留更多路径
&lt;img src=&quot;/assets/images/CTC/prefix_beamsearch.jpg&quot; alt=&quot;prefix_beamsearch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Prefix beam search仍然会丢失一些ctc序列的概率，比如上例中，字符串ba里没有包含blank blank blank blank b a这条CTC序列。&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;在规整字符串上做beam search允许在fisrt pass引入LM得分，因为解码过程中就知道规整后的形式和space的位置，在ctc字符串上做beam search则不行。&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Hannun论文《First-Pass Large Vocabulary Continuous Speech Recognition using Bi-Directional Recurrent DNNs 》中给出的算法。
&lt;img src=&quot;/assets/images/CTC/prefix_beam_algo.png&quot; alt=&quot;prefix_beam_algo&quot; /&gt;
注意两点:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;可以在first pass里引入word LM的得分，只要在输出space的时候加入语言模型的得分。&lt;/li&gt;
  &lt;li&gt;if $l^{+}$ not in $A_{prev}$ 的作用.当t时刻的beam里只有&lt;em&gt;a而没有&lt;/em&gt;ab时，在t+1时刻计算&lt;em&gt;ab，只使用了t时刻&lt;/em&gt;a的扩展，会丢失来自t时刻*ab的得分。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hannun给出的一个python实现。&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-python&quot; data-lang=&quot;python&quot;&gt;&lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;
Author: Awni Hannun

This is an example CTC decoder written in Python. The code is
intended to be a simple example and is not designed to be
especially efficient.

The algorithm is a prefix beam search for a model trained
with the CTC loss function.

For more details checkout either of these references:
  https://distill.pub/2017/ctc/#inference
  https://arxiv.org/abs/1408.2873

&quot;&quot;&quot;&lt;/span&gt;

&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;math&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;collections&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;NEG_INF&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;inf&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beam_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blank&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;
    Performs inference for the given output probabilities.

    Arguments:
      probs: The output probabilities (e.g. log post-softmax) for each
        time step. Should be an array of shape (time x output dim).
      beam_size (int): Size of the beam to use during inference.
      blank (int): Index of the CTC blank label.

    Returns the output label sequence and the corresponding negative
    log-likelihood estimated by the decoder.
    &quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;S&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;probs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# Elements in the beam are (prefix, (p_blank, p_no_blank))
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Initialize the beam with the empty sequence, a probability of
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# 1 for ending in blank and zero for ending in non-blank
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# (in log space).
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;beam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;tuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;NEG_INF&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# Loop over time
&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# A default dictionary to store the next step candidates.
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;next_beam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;make_new_beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;S&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# Loop over vocab
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

            &lt;span class=&quot;c1&quot;&gt;# The variables p_b and p_nb are respectively the
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# probabilities for the prefix given that it ends in a
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# blank and does not end in a blank at this time step.
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prefix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_nb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# Loop over beam
&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;# If we propose a blank the prefix doesn't change.
&lt;/span&gt;                &lt;span class=&quot;c1&quot;&gt;# Only the probability of ending in blank gets updated.
&lt;/span&gt;                &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blank&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;n_p_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prefix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;n_p_b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_p_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_nb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;next_beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prefix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_p_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;continue&lt;/span&gt;

                &lt;span class=&quot;c1&quot;&gt;# Extend the prefix by the new character s and add it to
&lt;/span&gt;                &lt;span class=&quot;c1&quot;&gt;# the beam. Only the probability of not ending in blank
&lt;/span&gt;                &lt;span class=&quot;c1&quot;&gt;# gets updated.
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;end_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prefix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prefix&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;n_prefix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prefix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;n_p_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_prefix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;end_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_nb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                  &lt;span class=&quot;c1&quot;&gt;# We don't include the previous probability of not ending
&lt;/span&gt;                  &lt;span class=&quot;c1&quot;&gt;# in blank (p_nb) if s is repeated at the end. The CTC
&lt;/span&gt;                  &lt;span class=&quot;c1&quot;&gt;# algorithm merges characters not separated by a blank.
&lt;/span&gt;                  &lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

                &lt;span class=&quot;c1&quot;&gt;# *NB* this would be a good place to include an LM score.
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;next_beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_prefix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_p_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

                &lt;span class=&quot;c1&quot;&gt;# If s is repeated at the end we also update the unchanged
&lt;/span&gt;                &lt;span class=&quot;c1&quot;&gt;# prefix. This is the merging case.
&lt;/span&gt;                &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;end_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;n_p_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prefix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_nb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;next_beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prefix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_p_b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_p_nb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;# Sort and trim the beam before moving on to the
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# next time-step.
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;beam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_beam&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;reverse&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;beam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beam_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;best&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;参考资料：&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;https://distill.pub/2017/ctc/&lt;/li&gt;
  &lt;li&gt;https://arxiv.org/abs/1408.2873&lt;/li&gt;
  &lt;li&gt;https://towardsdatascience.com/beam-search-decoding-in-ctc-trained-neural-networks-5a889a3d85a7&lt;/li&gt;
&lt;/ol&gt;</content><author><name></name></author><summary type="html"></summary></entry><entry><title type="html">Eesen中的CTC实现</title><link href="http://placebokkk.github.io/asr/2020/01/13/asr-ctc-eesen.html" rel="alternate" type="text/html" title="Eesen中的CTC实现" /><published>2020-01-13T02:00:00+00:00</published><updated>2020-01-13T02:00:00+00:00</updated><id>http://placebokkk.github.io/asr/2020/01/13/asr-ctc-eesen</id><content type="html" xml:base="http://placebokkk.github.io/asr/2020/01/13/asr-ctc-eesen.html">&lt;ul class=&quot;table-of-content&quot; id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#eesen的ctc框架&quot; id=&quot;markdown-toc-eesen的ctc框架&quot;&gt;Eesen的CTC框架&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#eesen中ctc的训练&quot; id=&quot;markdown-toc-eesen中ctc的训练&quot;&gt;Eesen中CTC的训练&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#ctc的前向后向计算&quot; id=&quot;markdown-toc-ctc的前向后向计算&quot;&gt;CTC的前向后向计算&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#计算前向alpha和后向beta值&quot; id=&quot;markdown-toc-计算前向alpha和后向beta值&quot;&gt;计算前向alpha和后向beta值&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#计算条件似然函数&quot; id=&quot;markdown-toc-计算条件似然函数&quot;&gt;计算条件似然函数&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#ctc的反向传播导数&quot; id=&quot;markdown-toc-ctc的反向传播导数&quot;&gt;CTC的反向传播导数&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#softmax后y值的导数&quot; id=&quot;markdown-toc-softmax后y值的导数&quot;&gt;softmax后y值的导数&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#softmax前a值的导数&quot; id=&quot;markdown-toc-softmax前a值的导数&quot;&gt;softmax前a值的导数&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#关于cuda计算的介绍&quot; id=&quot;markdown-toc-关于cuda计算的介绍&quot;&gt;关于Cuda计算的介绍&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#eesen中的ctc的解码待更新&quot; id=&quot;markdown-toc-eesen中的ctc的解码待更新&quot;&gt;Eesen中的CTC的解码[待更新]&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#解码图构建&quot; id=&quot;markdown-toc-解码图构建&quot;&gt;解码图构建&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#t的构建&quot; id=&quot;markdown-toc-t的构建&quot;&gt;T的构建&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#l的构建&quot; id=&quot;markdown-toc-l的构建&quot;&gt;L的构建&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#解码优化&quot; id=&quot;markdown-toc-解码优化&quot;&gt;解码优化&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;eesen的ctc框架&quot;&gt;Eesen的CTC框架&lt;/h2&gt;
&lt;ol&gt;
  &lt;li&gt;准备输入feature:利用kaldi的工具提取&lt;/li&gt;
  &lt;li&gt;准备输出label数据
    &lt;ul&gt;
      &lt;li&gt;phone text根据字典变为phone序列&lt;/li&gt;
      &lt;li&gt;charactor/grapheme 单词拆分成，增加space&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;利用kaldi nnet1框架，实现CTC损失函数，直接训练神经网络的声学模型&lt;/li&gt;
  &lt;li&gt;extract_net_output得到feature通过网络的输出&lt;/li&gt;
  &lt;li&gt;构建 TLG解码图，T可以是phone或者char&lt;/li&gt;
  &lt;li&gt;利用lattice decoder解码输出，kaldi中HCLG fst的input是transition-id，eesen中是token-id.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;其中第3步和第4步也可以使用其他框架实现， 我实现了一个&lt;a href=&quot;https://github.com/placebokkk/ctc-asr&quot;&gt;pytorch版本&lt;/a&gt;，可以复现eesen中的wsj数据集上的结果。&lt;/p&gt;

&lt;h2 id=&quot;eesen中ctc的训练&quot;&gt;Eesen中CTC的训练&lt;/h2&gt;

&lt;p&gt;Eesen中CTC的实现和原始论文的推导很接近，没做什么优化，很适合用来学习理解CTC。
但是Eesen的CTC实现在梯度的计算上，没有直接使用论文中最后得到softmax前的a值的导数公式，而是先求出softmax后的y值的导数，再求出a值的导数，因此和原论文的公式并不相同。
本文主要对此进行解释。&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;src/net/ctc-loss.cc&lt;/code&gt;文件中Ctc::Eval和Ctc::EvalParallel都是计算CTC损失对softmax前的a值的导数，区别是前者计算单个样本，后者计算一组(Batch)样本。
下面仅对Ctc::Eval进行说明&lt;/p&gt;

&lt;h3 id=&quot;ctc的前向后向计算&quot;&gt;CTC的前向后向计算&lt;/h3&gt;

&lt;p&gt;在首尾和字符间插入blank，(&lt;code class=&quot;highlighter-rouge&quot;&gt;l&lt;/code&gt;变为&lt;code class=&quot;highlighter-rouge&quot;&gt;l'&lt;/code&gt;),如&lt;strong&gt;abbc&lt;/strong&gt;变为&lt;strong&gt;-a-b-b-c-&lt;/strong&gt;，长度&lt;code class=&quot;highlighter-rouge&quot;&gt;n&lt;/code&gt;变为&lt;code class=&quot;highlighter-rouge&quot;&gt;L=2n+1&lt;/code&gt;&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;  &lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Resize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;NumRows&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;NumCols&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;NumRows&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;NumCols&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;// label expansion by inserting blank (indexed by 0) at the beginning and end, &lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;// and between every pair of labels&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;len_labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_len_labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;len_labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

  &lt;span class=&quot;n&quot;&gt;label_expand_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;resize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;label_expand_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;resize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp_len_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;len_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;label_expand_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;];&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;前后向算法是在log域上进行计算的,对NN的softmax输出值取log&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;  &lt;span class=&quot;c1&quot;&gt;// compute in log scale&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;CuMatrix&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BaseFloat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_nnet_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;log_nnet_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;ApplyLog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h3 id=&quot;计算前向alpha和后向beta值&quot;&gt;计算前向alpha和后向beta值&lt;/h3&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;  &lt;span class=&quot;n&quot;&gt;alpha_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;Resize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_len_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSetZero&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;beta_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;Resize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_len_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSetZero&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;ComputeCtcAlpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_nnet_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label_expand_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;--)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;ComputeCtcBeta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_nnet_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label_expand_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;ComputeCtcAlpha和ComputeCtcBeta分别计算前向和后向值，算法类似，本文只讨论前者。ComputeCtcAlpha会调用_compute_ctc_alpha_one_sequence(位于&lt;code class=&quot;highlighter-rouge&quot;&gt;/src/gpucompute/cuda-kernels.cu&lt;/code&gt;)完成实际计算。&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;n&quot;&gt;template&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;__global__&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_compute_ctc_alpha_one_sequence&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;NumericLimits&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_zero_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LogAPlusB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]));&lt;/span&gt;
      &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LogAPlusB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LogAPlusB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
      &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LogAPlusB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]));&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;参考论文公式&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\alpha_{t}(s)=\left\{\begin{array}{ll}
{\bar{\alpha}_{t}(s) y_{1_{s}^{\prime}}^{t}} &amp; {\text { if } \mathrm{l}_{s}^{\prime}=b \text { or } \mathrm{l}_{s-2}^{\prime}=\mathrm{l}_{s}^{\prime}} \\
{\left(\bar{\alpha}_{t}(s)+\alpha_{t-1}(s-2)\right) y_{1_{s}^{\prime}}^{t}} &amp; {\text { otherwise }}
\end{array}\right. %]]&gt;&lt;/script&gt;

&lt;p&gt;其中&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\bar{\alpha}_{t}(s) \stackrel{\text { def }}{=} \alpha_{t-1}(s)+\alpha_{t-1}(s-1)&lt;/script&gt;

&lt;p&gt;很容易理解上述代码逻辑。
这里涉及CTC里针对CTC前向计算的cuda kernel的设计，但是和CTC的算法本身无关，这里先跳过，本文后面章节会介绍&lt;a href=&quot;#关于cuda计算的介绍&quot;&gt;cuda相关的知识&lt;/a&gt;&lt;/p&gt;

&lt;h3 id=&quot;计算条件似然函数&quot;&gt;计算条件似然函数&lt;/h3&gt;

&lt;p&gt;接着根据公式
&lt;script type=&quot;math/tex&quot;&gt;Z=p(\mathbf{l} | \mathbf{x})=\alpha(T,L)+\alpha(T，L-1)&lt;/script&gt;
计算当前模型下条件似然的值&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;  &lt;span class=&quot;c1&quot;&gt;// compute the log-likelihood of the label sequence given the inputs logP(z|x)&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;BaseFloat&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_len_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt; 
  &lt;span class=&quot;n&quot;&gt;BaseFloat&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_len_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;BaseFloat&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pzx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ExpA&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;这里alpha和beta都是log域的量.已知&lt;script type=&quot;math/tex&quot;&gt;\log{(a)}&lt;/script&gt;和&lt;script type=&quot;math/tex&quot;&gt;\log{(b)}&lt;/script&gt;,求&lt;script type=&quot;math/tex&quot;&gt;\log{(a+b)}&lt;/script&gt;
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
\begin{aligned}
log(a + b) &amp;= log(a) + log(1 + \exp(\log(b)-\log(a))), &amp;\mbox{if}\ &amp;b &lt; a \\
           &amp;= log(b) + log(1 + \exp(\log(a)-\log(b))), &amp;\mbox{if}\ &amp;a &lt; b
\end{aligned} %]]&gt;&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;所以&lt;code class=&quot;highlighter-rouge&quot;&gt;pzx = tmp1 + log(1 + ExpA(tmp2 - tmp1))&lt;/code&gt;  等价于&lt;code class=&quot;highlighter-rouge&quot;&gt;log(exp(tmp1)+exp(tmp2))&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;ctc的反向传播导数&quot;&gt;CTC的反向传播导数&lt;/h3&gt;

&lt;p&gt;t时刻的输出softmax函数为&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;p(y_k^t) = \frac{\exp(a_k^t)}{\sum_{k'}^K{\exp{a_{k'}^t}}}&lt;/script&gt;

&lt;p&gt;原始论文中公式(16)直接有a值的导数公式:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\frac{\partial -\ln p(\mathbf{l}|\mathbf{x})}{\partial a_{k}^{t}} =y_{k}^{t}-\frac{1}{y_{k}^{t} p(\mathbf{l} | \mathbf{x})} \sum_{s \in l a b(\mathbf{z}, k)} \hat{\alpha}_{t}(s) \hat{\beta}_{t}(s)&lt;/script&gt;

&lt;p&gt;但是eesen中没有使用该公式，而是先计算y值（softmax之后）的导数，再计算a值（softmax之前）的导数.&lt;/p&gt;

&lt;h4 id=&quot;softmax后y值的导数&quot;&gt;softmax后y值的导数&lt;/h4&gt;

&lt;p&gt;梯度法求的是极小值，因此最大化似然等价于最小化似然的负数，从而目标是求&lt;code class=&quot;highlighter-rouge&quot;&gt;-p(l|x)&lt;/code&gt;对a的导数。整体代码如下：&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;  &lt;span class=&quot;c1&quot;&gt;// gradients from CTC&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;ctc_err_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;Resize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSetZero&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;ctc_err_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;ComputeCtcErrorMSeq&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label_expand_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;frame_num_utt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pzx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// here should use the original ??&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;// back-propagate the errors through the softmax layer&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;ctc_err_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;MulElements&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;CuVector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BaseFloat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;row_sum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSetZero&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;row_sum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;AddColSumMat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctc_err_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

  &lt;span class=&quot;n&quot;&gt;CuMatrix&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BaseFloat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;net_out_tmp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;net_out_tmp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;MulRowsVec&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row_sum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CopyFromMat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctc_err_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

  &lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AddMat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;net_out_tmp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;一步步看,先看&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;n&quot;&gt;ctc_err_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;ComputeCtcError&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label_expand_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pzx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;首先计算softmax后y值的导数，保存在ctc_err_中。ctc_err_是一个T行K列的矩阵, T是序列长度，K是output个数， 则ctc_err_矩阵中第t行k列的值为&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{aligned}
E_{k}^{t} &amp; =\frac{\partial -\ln (p(\mathbf{l} | \mathbf{x}))}{\partial y_{k}^{t}} \\
&amp; =-\frac{1}{p(\mathbf{l} | \mathbf{x})} \frac{\partial p(\mathbf{l} | \mathbf{x})}{\partial y_{k}^{t}} \\
\end{aligned} %]]&gt;&lt;/script&gt;

&lt;p&gt;已知论文中的公式&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\frac{\partial p(\mathbf{l} | \mathbf{x})}{\partial y_{k}^{t}}=\frac{1}{(y_{k}^{t})^2} \sum_{s \in lab(1, k)} \alpha_{t}(s) \beta_{t}(s)&lt;/script&gt;

&lt;p&gt;所以&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{aligned}
E_{k}^{t} 
&amp; =- \frac{1}{p(\mathbf{l} | \mathbf{x})} \frac{1}{(y_{k}^{t})^2} \sum_{s \in lab(1, k)} \alpha_{t}(s) \beta_{t}(s) \\
&amp; =- \exp{\left\{\log\left\{\sum_{s \in lab(1, k)} \alpha_{t}(s) \beta_{t}(s))\right\}-\log{p(\mathbf{l} | \mathbf{x})} -2\log{y_{k}^{t}} \right\}} \\
\end{aligned} %]]&gt;&lt;/script&gt;

&lt;p&gt;ComputeCtcError会调用_compute_ctc_error_one_sequence(位于&lt;code class=&quot;highlighter-rouge&quot;&gt;/src/gpucompute/cuda-kernels.cu&lt;/code&gt;)，其计算过程和上式最后一行完全一致。&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;c1&quot;&gt;// mat_prob are in probability scale.&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;template&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;__global__&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_compute_ctc_error_one_sequence&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pzx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blockIdx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blockDim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threadIdx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// row index&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blockIdx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blockDim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threadIdx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// column index&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;rows&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;cols&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;NumericLimits&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_zero_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index_error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;cols&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;//&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;err&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LogAPlusB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;err&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]));&lt;/span&gt;
      &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ExpA&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SubAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;err&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pzx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;NumericLimits&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_zero_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]))));&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mat_error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_error&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h4 id=&quot;softmax前a值的导数&quot;&gt;softmax前a值的导数&lt;/h4&gt;

&lt;p&gt;接着计算softmax之前a值的导数。我们先推导出计算公式：&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\frac{\partial -\ln p(\mathbf{l}|\mathbf{x})}{\partial a_{k}^{t}}
= \sum_{k^{\prime}}^{K}{\frac{\partial -\ln p(\mathbf{l}|\mathbf{x})}{\partial y_{k^{\prime}}^{t}} \frac{\partial y_{k^{\prime}}^{t}}{\partial a_{k}^{t}}}
=\sum_{k^{\prime}}^{K} {E_{k^{\prime}}^{t} \cdot \frac{\partial y_{k^{\prime}}^{t}}{\partial a_{k}^{t}}}&lt;/script&gt;

&lt;p&gt;其中softmax的输入y对输出a的导数&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\frac{\partial y_{k^{\prime}}^{t}}{\partial a_{k}^{t}} = y_{k^{\prime}}^{t} \frac{ \partial \ln y_{k^{\prime}}^{t}}{\partial a_{k}^{t}} = y_{k^{\prime}}^{t}  (\delta_{k k^{\prime}} - y_{k}^{t} )&lt;/script&gt;

&lt;p&gt;从而&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{aligned}
\frac{\partial -\ln p(\mathbf{l}|\mathbf{x})}{\partial a_{k}^{t}} 
&amp; =  \sum_{k^{\prime}}^{K} {E_{k^{\prime}}^{t} y_{k^{\prime}}^{t} \cdot (\delta_{k k^{\prime}} - y_{k}^{t} )} \\
&amp; =\sum_{k^{\prime}}^{K} {E_{k^{\prime}}^{t} y_{k^{\prime}}^{t}  \delta_{k k^{\prime}}} - \sum_{k^{\prime}}^{K} {E_{k^{\prime}}^{t} y_{k^{\prime}}^{t}  y_{k}^{t} }  \\
&amp; = E_{k}^{t} y_{k}^{t}  - \sum_{k^{\prime}}^{K} {E_{k^{\prime}}^{t} y_{k^{\prime}}^{t}  y_{k}^{t} } \\
&amp; = E_{k}^{t} y_{k}^{t}  - (\sum_{k^{\prime}}^{K} {E_{k^{\prime}}^{t} y_{k^{\prime}}^{t} ) y_{k}^{t} }
\end{aligned} %]]&gt;&lt;/script&gt;

&lt;p&gt;回到代码&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;c1&quot;&gt;// back-propagate the errors through the softmax layer&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ctc_err_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;MulElements&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;CuVector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BaseFloat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;  &lt;span class=&quot;nf&quot;&gt;row_sum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSetZero&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;row_sum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;AddColSumMat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctc_err_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;ctc_err_.MulElements(net_out);&lt;/code&gt;对两个相同大小的矩阵做elementwise乘法，得到一个矩阵，其第t行第k列的值是 &lt;script type=&quot;math/tex&quot;&gt;E_{k}^{t} y_{k}^{t}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;row_sum.AddColSumMat(1.0, ctc_err_, 0.0);&lt;/code&gt;将上述的矩阵的列相加，得到一个T*1	的矩阵（后者叫T维列向量），其第t行的值是 &lt;script type=&quot;math/tex&quot;&gt;\sum_{k^{\prime}}^{K} {E_{k^{\prime}}^{t} y_{k^{\prime}}^{t} }&lt;/script&gt;&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;n&quot;&gt;CuMatrix&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BaseFloat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;  &lt;span class=&quot;nf&quot;&gt;net_out_tmp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;net_out_tmp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;MulRowsVec&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row_sum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;MulRowsVec对&lt;code class=&quot;highlighter-rouge&quot;&gt;net_out_tmp&lt;/code&gt; 中的第n行里的每个值，都乘上row_sum的第n维值。从而net_out_tmp计算后得到了一个矩阵，其第t行k列的值是 &lt;script type=&quot;math/tex&quot;&gt;(\sum_{k^{\prime}}^{K} {E_{k^{\prime}}^{t} y_{k^{\prime}}^{t} ) y_{k}^{t} }&lt;/script&gt;&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CopyFromMat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ctc_err_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AddMat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;net_out_tmp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;diff是一个T*K的矩阵，其第t行k列的值为，即&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;E_{k}^{t} y_{k}^{t}  - (\sum_{k^{\prime}}^{K} {E_{k^{\prime}}^{t} y_{k^{\prime}}^{t} ) y_{k}^{t} }&lt;/script&gt;

&lt;h3 id=&quot;关于cuda计算的介绍&quot;&gt;关于Cuda计算的介绍&lt;/h3&gt;

&lt;p&gt;Cuda的计算架构里有Grid/Block/Thread概念。&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;一个Grid里有多个Block。&lt;/li&gt;
  &lt;li&gt;一个Block里有多个Thread。&lt;/li&gt;
  &lt;li&gt;每个Cuda Kernel在一个Thread上计算。Thread之间是并行的。&lt;/li&gt;
  &lt;li&gt;Grid和Block的布局可以是1，2，3维的。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;设计一个算法的cuda版本，需要考虑如何把算法分配到Thread上并行计算。&lt;/p&gt;

&lt;p&gt;Eesen里的CTC里的Alpha&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;c1&quot;&gt;//eesen/src/net/ctc-loss.cc&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nl&quot;&gt;Ctc:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Eval&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(...&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;）&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;alpha_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;Resize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_len_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kSetZero&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_frames&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;ComputeCtcAlpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_nnet_out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label_expand_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;其中&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;exp_len_labels是在标注序列的首尾及各字符之间插入blank扩展后的序列。原序列长度&lt;code class=&quot;highlighter-rouge&quot;&gt;n&lt;/code&gt;，则新序列长度为&lt;code class=&quot;highlighter-rouge&quot;&gt;L=2n+1&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;alpha_是一个num_frames行，exp_len_labels列的矩阵。每一行对应一个时间帧t。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;ComputeCtcAlpha里的cuda&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;c1&quot;&gt;//eesen/src/gpucompute/cuda-matrix.cc&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;template&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;CuMatrixBase&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ComputeCtcAlpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;CuMatrixBase&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt;
                                         &lt;span class=&quot;n&quot;&gt;int32&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row_idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt;
                                         &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;nl&quot;&gt;std:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MatrixIndexT&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt;
                                         &lt;span class=&quot;n&quot;&gt;bool&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rescale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;MatrixIndexT&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prob_cols&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;NumCols&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;CuArray&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MatrixIndexT&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;cuda_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dimBlock&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CU1DBLOCK&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dimGrid&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_blocks&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_cols_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CU1DBLOCK&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cuda_compute_ctc_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dimGrid&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dimBlock&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row_idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;data_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;Dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cuda_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;Data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;inline&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;cuda_compute_ctc_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim3&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Gr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim3&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Bl&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row_idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;cudaF_compute_ctc_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Bl&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row_idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;cudaF_compute_ctc_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim3&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Gr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim3&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Bl&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row_idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;_compute_ctc_alpha_one_sequence&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Bl&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&amp;gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row_idx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;其中CU1DBLOCK定义为256&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;n&quot;&gt;eesen&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;src&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gpucompute&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrixdim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;h&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// The size of a CUDA 1-d block, e.g. for vector operations..&lt;/span&gt;
&lt;span class=&quot;err&quot;&gt;#&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;define&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;CU1DBLOCK&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;n_blocks用于确定一个Grid里Block的个数&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;c1&quot;&gt;//eesen/src/gpucompute/cuda-common.h&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;inline&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;int32&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;n_blocks&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;int32&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;int32&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt; 
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)?&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt; 
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;假设exp_len_labels的长度为L，则n_blocks=L/256.
所以cuda_compute_ctc_alpha的一个Grid里有&lt;code class=&quot;highlighter-rouge&quot;&gt;L/256&lt;/code&gt;个Block, 一个Block里有256个Thread&lt;/p&gt;

&lt;p&gt;现在再看最终调用的_compute_ctc_alpha_one_sequence«&amp;lt;Gr, Bl»&amp;gt;()的完整代码。&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;n&quot;&gt;template&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;__global__&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_compute_ctc_alpha_one_sequence&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MatrixDim&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blockIdx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blockDim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threadIdx&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;cols&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;

  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;class_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;];&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;class_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index_alpha_rm1_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;int32_cuda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;NumericLimits&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_zero_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LogAPlusB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]));&lt;/span&gt;
      &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Real&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LogAPlusB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LogAPlusB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tmp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;
      &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LogAPlusB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_im1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]));&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AddAB&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mat_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index_alpha_rm1_i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
 &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Cuda里计算t时刻CTC Alpha的划分如下图,代码中的i对应图中纵坐标（从上往下），row(即t)对应横坐标。每个block对应图中的一个框，其中有256个thread。每个thread计算一个圆圈上的统计量。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/CTC/alpha_chart_cuda.png&quot; alt=&quot;alpha_chart_cuda&quot; /&gt;&lt;/p&gt;

&lt;p&gt;结合图看代码：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;index_alpha_*记录前向统计量矩阵中的index，比如index_alpha_rm1_im1表示,r是row的意思，也就是时间帧t，其中m是minus的意思，即(t-1,i-1)对应的alpha矩阵中的index&lt;/li&gt;
  &lt;li&gt;index_prob记录当前thread(t时刻，expand-label第i个位置)的label在网络输出的prob矩阵中的index&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;if (i &amp;lt; dim)&lt;/code&gt; : 这里dim即label的长度L，因为L不一定是Blocksize(256)的整数倍，所以最后一个block里的i可能会大于L，因此&lt;code class=&quot;highlighter-rouge&quot;&gt;if (i &amp;lt; dim)&lt;/code&gt;是必要的。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;另外，因为CTC本身的性质，t时刻只能计算到t*2位置的label的alpha值，所以这里&lt;code class=&quot;highlighter-rouge&quot;&gt;if (i &amp;lt; dim)&lt;/code&gt;可以改为 &lt;code class=&quot;highlighter-rouge&quot;&gt;if (i &amp;lt; 2*row + 1 &amp;amp;&amp;amp; i &amp;lt; dim)&lt;/code&gt;,减小一些的计算量。不过因为一般T都远大于L，所以减少的计算量也不多。&lt;/p&gt;

&lt;h2 id=&quot;eesen中的ctc的解码待更新&quot;&gt;Eesen中的CTC的解码[待更新]&lt;/h2&gt;

&lt;h3 id=&quot;解码图构建&quot;&gt;解码图构建&lt;/h3&gt;

&lt;h4 id=&quot;t的构建&quot;&gt;T的构建&lt;/h4&gt;

&lt;h4 id=&quot;l的构建&quot;&gt;L的构建&lt;/h4&gt;

&lt;h3 id=&quot;解码优化&quot;&gt;解码优化&lt;/h3&gt;</content><author><name></name></author><summary type="html"></summary></entry><entry><title type="html">[论文]Sequence-discriminative training of DNNs笔记</title><link href="http://placebokkk.github.io/asr/2019/12/24/asr-paper-se-mmi-note.html" rel="alternate" type="text/html" title="[论文]Sequence-discriminative training of DNNs笔记" /><published>2019-12-24T03:11:59+00:00</published><updated>2019-12-24T03:11:59+00:00</updated><id>http://placebokkk.github.io/asr/2019/12/24/asr-paper-se-mmi-note</id><content type="html" xml:base="http://placebokkk.github.io/asr/2019/12/24/asr-paper-se-mmi-note.html">&lt;p&gt;公式比较多，直接在overleaf写latex了&lt;/p&gt;
&lt;h1 id=&quot;手机端点击打开pdf查看&quot;&gt;&lt;strong&gt;手机端点击&lt;a href=&quot;http://placebokkk.github.io/assets/pdf/Note_on_MMI.pdf&quot;&gt;打开pdf&lt;/a&gt;查看&lt;/strong&gt;&lt;/h1&gt;
&lt;style&gt;.pdf-embed-container { position: relative; padding-bottom: 98.25%; height: 0; overflow: hidden; max-width: 100%; margin-bottom: 20px; } .pdf-embed-container iframe, .pdf-embed-container object, .pdf-embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }&lt;/style&gt;
&lt;div class=&quot;pdf-embed-container&quot;&gt;&lt;iframe title=&quot;PDF file&quot; width=&quot;640&quot; height=&quot;390&quot; src=&quot;/assets/pdf/Note_on_MMI.pdf&quot; frameborder=&quot;0&quot; allowfullscreen=&quot;&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;</content><author><name></name></author><summary type="html">公式比较多，直接在overleaf写latex了 手机端点击打开pdf查看</summary></entry><entry><title type="html">[翻译]Dan Povey离开JHU的一封公开信</title><link href="http://placebokkk.github.io/asr/2019/08/09/eng-dan-leaving.html" rel="alternate" type="text/html" title="[翻译]Dan Povey离开JHU的一封公开信" /><published>2019-08-09T02:00:00+00:00</published><updated>2019-08-09T02:00:00+00:00</updated><id>http://placebokkk.github.io/asr/2019/08/09/eng-dan-leaving</id><content type="html" xml:base="http://placebokkk.github.io/asr/2019/08/09/eng-dan-leaving.html">&lt;p&gt;Leaving Hopkins&lt;/p&gt;

&lt;p&gt;离开霍普金斯&lt;/p&gt;

&lt;p&gt;Everyone,
I am leaving to take a private-sector job in Seattle, starting August 19th. I will still be working with my students and collaborators here remotely. As you’ll see from this letter, I have been fired from Hopkins effective the 31st of August. I had arranged a backup plan beforehand, so will be leaving a bit earlier. Please don’t blame the Whiting School or Andrew Douglas for this; this comes from higher up. You’ll see from the letter that I am not supposed to communicate with (almost) anyone at Hopkins… technically I am just putting this on the web; and if you find it, you find it.&lt;/p&gt;

&lt;p&gt;从8月19号开始，我就要离开JHU去西雅图的一家公司工作了。之后我会用远程的方式指导我的学生以及和合作者协作。在这封信里可以看到，我被JHU开除了，且必须在8月31之前离开。因为在被开除前已经有了准备，所以我可以更早些离开。请你们不要责怪Whiting学院或者Andrew Douglas，这是更高层的决定。在通知信里可以看到，我几乎不被允许和JHU的任何人交流，不过从技术角度讲，我可以把我想说的放到网上，如果你不小心看到了，那就和我无关啦。&lt;/p&gt;

&lt;p&gt;I don’t expect all this will come as a surprise to most of you, given that three months ago organized a counter-protest against the student occupation of Garland hall, and a number of people were extremely triggered about that; but I thought you might like a little background.&lt;/p&gt;

&lt;p&gt;我想对于你们不少人而言，听到这个消息时应该有心里准备，毕竟，很多人对于三个月前我组织的“反占X”（反对示威学生占领Garland行政中心)活动一直都很关心，不过我估计你们可能会想了解更多的相关背景信息。&lt;/p&gt;

&lt;p&gt;What was never in dispute is that, being frustrated as the prospect of a long siege at Garland where our computer servers live, I organized a group of what I called “counter-protesters” to try to regain control of the building from the students. This was on the evening of May 8th; there was a scuffle and I was carried out of the building by the protesters. They then made allegations to the Office of Institutional Equity (OIE), saying that I had attacked them. The OIE seems not to have been able to substantiate the allegations that I attacked the protesters, but university leadership still decided that I still needed to be fired. (The attached letter claims that they are still investigating… I think most likely the true story is either they found the protesters were lying or realize that they’ll never know what happened).&lt;/p&gt;

&lt;p&gt;我先描述下这件事的基本背景，这个是整件事里最无争议的。一些示威学生长期占领着Garland行政中心，由于我们的服务器集群恰好处于Garland行政大厅下面，而他们的行为严重影响了服务器的正常使用，所以我组织了一群“反示威者”试图从这些学生手中夺回Garland行政大厅的控制权。在5月8号，我在此和这些示威学生发生了争执，最后被他们赶了出来。之后他们向OIE声称我攻击了他们。尽管OIE找不到任何证据证明我攻击过学生，但是学校的领导仍然决定对我进行开除。（通知信中说他们仍在调查，不过估计他们实际上也知道是示威者在撒谎。）&lt;/p&gt;

&lt;p&gt;What the administration seems to be saying is that I put the students in danger by bringing outsiders into what could have been a dangerous situation. You’ll see that the letter states that I believed the group I brought with me “could become violent”… the actual conversation with their lawyer went like this: after I stated that everyone was under strict instructions to not retaliate if attacked, I was asked whether I was confident that they would be able to follow those instructions no matter what happened, and I shrugged.&lt;/p&gt;

&lt;p&gt;管理层大概的意思是，我带的一些学校外部人员使得学生处在了可能的危险之中。在辞退信中提到，我明知我带来的反示威者“可能会采用暴力”… 实际上，我和律师的对话是这样的：我要求每一个人要严格遵守指令，即使被学生攻击也不要有任何报复行为，在陈述完此段之后，律师问我是否有自信他们可以在任何情况下遵守这些指令，我只能耸了耸肩。&lt;/p&gt;

&lt;p&gt;So essentially I am being fired for what might have happened, while the students are getting off scot free for things that actually did happen. They actually made false allegations against me, both in public (on Twitter) and to the university authorities. They actually attacked me and hurt me; many of you saw the big scratches on my back. They also threw a lot of punches at the people with me, who showed admirable restraint, although I understand one punch was thrown by a person in my group. They actually shut down Garland and inconvenienced thousands of people, requiring the fire department to cut open the doors to get them out. But they suffer no consequences. Am I sensing just a liiiitle bit of a double standard? I mean, obviously faculty will be held to higher standards than students, but that’s nowhere near enough to account for the difference in treatment.&lt;/p&gt;

&lt;p&gt;所以实际上我是因为“可能发生的事情”而被开除了，与此同时示威的学生却没有因“确实已经发生的事情”而受到任何惩罚。想想他们确实对我做了虚假的指控，包括在twitter上公开的以及向学校官方的。他们确实攻击了我，并且伤害了我，你们中很多人也看到了我背部多个明显的抓痕。他们还确实挥拳打了和我一起的好几个人，而这些人都非常克制没有还手，仅仅只有一个人还了一拳而已。这些示威者确实占领关闭了Garland大厅，影响到了上千人，以至于需要消防部门来把门切开赶他们出去。但他们却不用承担任何后果。难道这里面就没有一点点点点的双标吗？我的意思是，作为学校职工的确应该比学生要遵守更高的行为标准，但是学校的这个处理对待双方的差别显然太大了。&lt;/p&gt;

&lt;p&gt;Where could this double standard come from? Well, obviously there’s the fact that they were protesting for a left-wing cause, and I was opposing them. I’m not convinced that that’s enough to explain it, though. My feeling is that this mostly has to do with underrepresented minorities, specificially black people (and trans people). There seems to be nothing that Americans, or American institutions, fear more than being accused of racism (or similar ism’s), which leads to ridiculous spectacles like what we’re seeing here, where such a huge organization can be paralyzed by a handful of deluded kids.&lt;/p&gt;

&lt;p&gt;这种双重标准的根源在哪？当然，这些人的示威抗议是因为一些左翼原因，而我是反对左翼的，但是我觉得这不是根本原因。 我认为主要原因跟少数族裔有关，尤其是涉及到了黑人和跨性别者。对于美国人或者美国的机构而言，没有什么比被指控为种族主义更可怕的事情了，所以这就导致了我们看到的荒谬情况：一个巨大的组织被一小撮被蛊惑的孩子搞得瘫痪了。&lt;/p&gt;

&lt;p&gt;Now if I had known in advance that everyone inside the building was black (that was what I saw; although from media coverage it seems that there may have been a white trans person in the core group)– I wouldn’t have gone ahead with the counterprotest. I’m not an idiot; I know that as a person who demographically ticks all the ‘oppressor boxes’, I would have to be severely punished for opposing such a group. I miscalculated by trusting the coverage in JHNewsletter, which seems to have given a false impression of the demographics of the protest; their photos showed mostly white people. Now many of the people sitting outside the building were white, but that seems to have been window-dressing; they were just bystanders and didn’t do anything except take a bunch of cellphone video. All the people that I saw fighting and screaming were black. If it were simply a matter of difference of opinion I expected that Hopkins would at least pretend to be even-handed; but once race and transgender status enter the picture I don’t think that’s possible any more.&lt;/p&gt;

&lt;p&gt;如果我提前知道那个大厅里所有的示威者都是黑人（我看到的是这样，不过从媒体报道上看，核心成员里似乎还有一个白色跨性别者），我就不会组织反示威了。我又不是个傻子，我知道自己的族裔性别肤色无论哪一项在美国都只能属于被压迫的那一类，我也知道如果反抗这样一个群体只有被严厉惩处的下场。可惜我相信了JHNewsletter网站的消息，导致了错误的判断。JHNewsletter在报道里给出的照片中大多都是白人，这使我对示威者人口分布的产生了错误估计。现在仍然有很多白人坐在大厅外面，不过他们似乎都是些看热闹的，只不过是路过拍拍视频。我看到的所有争斗和嚎叫的都是黑人。如果这件事仅仅是冲突双方存在观点上的分歧，我估计JHU至少还会假装公平处理，但是一旦涉及到种族和同性的话题，我知道他们连假装一下都不可能了。&lt;/p&gt;

&lt;p&gt;I’m aware that it’s a huge violation of social norms for me to say publicly that I think whites, or males, are being discriminated against. As far as I can tell there are three specific circumstances in which it’s acceptable for a white male in left-of-center America to allude publicy to these types of double standards:&lt;/p&gt;

&lt;p&gt;To justify them&lt;/p&gt;

&lt;p&gt;To advocate for their adoption&lt;/p&gt;

&lt;p&gt;To deny that they exist at all&lt;/p&gt;

&lt;p&gt;我明白，公开说出我的想法，即认为白人或着说是白人男性受到歧视，这极大违反了美国的社会规范。据我所知，只有三种情况下可以稍微提及白人男性被双标对待这件事，而不会惹怒美国偏左翼的白人男性。这三个情况是：&lt;/p&gt;

&lt;p&gt;为这些人辩护&lt;/p&gt;

&lt;p&gt;倡导他们的采纳&lt;/p&gt;

&lt;p&gt;否认他们存在&lt;/p&gt;

&lt;p&gt;Clearly what I am doing here doesn’t fall into any of those three categories. But the truth is, I left the bounds of left-wing respectability quite some time ago.
White males in this environment seem to be expected to constantly atone for their existence by telegraphing their exclusive concern for every demographic group but their own, like a neutered puppy-dog or some Justin Trudeau man-child. It’s pathetic, in my opinion; and I don’t accept it at all. I am not prepared to apologize for being who I am. I don’t think that empathy should preclude critical thinking or basic self-respect. I don’t accept that a person should have carte blanche to disrupt everyone’s lives just because of their minority status; and I don’t feel it’s right that I should be fired just for opposing a group whose victimhood makes them politically unassailable. This might sound very controversial to some people here, but to me it seems like common sense.&lt;/p&gt;

&lt;p&gt;很明显我现在的行为不属于这三个范畴的任何一个。事实是，很久以前，我就和左翼划清了界限。当前环境下的白人男性，似乎要不停的向所有族裔的人类（除了他们自己所在的种群即白人男性）表达关怀才得以减轻他们的罪孽，而他们自己只能像一只绝育的小狗或贾斯汀特鲁多似的男孩一样活着。我觉的这真的很可悲。而我自己不接受这一切，我就是我，我不想为我的存在而道歉，我不认为人的理性思维或基本自尊要为同情别人而让路。我无法接受一个人因为自己是少数族裔就可以肆无忌惮的享受打扰其他人生活的权利。我不认为我因为反对一个政治上更优越的团体而被解雇是个合理的事情。尽管对有些人而言我的话听上去有些争议，但对我而言这些都是常识。&lt;/p&gt;

&lt;p&gt;After writing the words above, I can hear in my head a chorus of marginalized voices crying: “But.. but.. but.. we’re triggered!” “Hate!” “White supremacy!” “Transphobia!” and demanding special protection. I expect that some people will characterize my plea for equal treatment as an incitement to genocide. Let them. Unlike some people here, I have the mental strength to not be manipulated by these kinds of histrionics. I don’t need the approval of victim groups to bolster my self-esteem; and I’m capable of weathering a little outrage. (The fact that I have career options helps, obviously). There’s a difference between tolerance and cowardice; there’s a difference between broad-mindedness and self-hatred; and no-one should claim they are bravely defending `oppressed classes’ when in reality they are just too timid, self-conscious or mentally feeble to stop themselves from being manipulated by them. Males educated here in America seem to be uniquely supine in this regard. Is it something they put in the cafeteria food?&lt;/p&gt;

&lt;p&gt;写完上面的文字后，我听到耳边有股声音在叫喊着，要求被特殊保护：“但是..但是..但是..我们被激怒了！” “这言论令人讨厌！” “你这个白人至上主义者！” “你这个跨性别恐惧症！”。我知道有些人会将我对平等待遇的诉求看成煽动种族灭绝的行为。随他们怎么想吧。和这里的某些人不同，我有种精神力量可以让自己不被现世这种装模作样的风气操纵。我不需要加入受害者团体来增强自尊心;而且我有能力经受住一些对我的不公平侮辱和暴行。 （显然，这多亏了我还有其他的职业道路可选）。请不要把宽容与怯懦混为一谈;宽宏大量并不代表要自我仇恨;如果一个人太怯懦，没有强大的精神力摆脱被风气操控，他就不要宣称自己能够勇敢的捍卫‘被压迫阶级’的权益。然而受过美国教育的男性却似乎尤善此道。难道是他们的食堂里的食物被加了什么特殊东西吗？&lt;/p&gt;

&lt;p&gt;Perceptive readers may see the above as an appeal to masculinity. Yes, that’s essentially what it is. The obvious response, for a progressive, would be to put the adjective “toxic” in front of that word “masculinity” and throw it back at me. OK. I’m aware that in the progressive world male is bad and female is good, just as in Orwell’s “Animal Farm” it was “four legs good, two legs bad”. To round it out you can add: “non-white good, white bad”; “diversity good, uniformity bad”; “majority bad, minority good”; “powerful bad, powerless good”, and so on; and you have a nice little moral system, one that may be perfectly self-consistent. Now, I view moral systems as arbitrary and subjective: it’s just a particular assignment of people, actions, thoughts, events, artifacts and so on, to the categories “good” and “bad”– typically reinforced by myths or cherry-picked facts, and held together by some more general principles or concepts. So from a certain abstract point of view, the progressive moral system as on the same footing as any other.&lt;/p&gt;

&lt;p&gt;敏锐的读者可能会把上述言论当成我对男性气概的诉求。是的，我基本上就是想表达这个意思。我知道，一些“思想进步”的人会在“男性气概”这个词的前面加上一个形容词：“有毒的”，然后扔回我面前。是的，我知道在“思想进步”的世界中，男性是坏的，女性是好的，就像在奥威尔的“动物农场”中那样，“四条腿好，两条腿坏”。你可以再加一些规矩来进一步完善这个体系，比如：“非白即好，有白即坏”、 “多样即好，单一即坏”、“少数即好，多数即坏”、“无权即好，有权即坏”等等。然后你就拥有了一个非常好的完全自洽的小型道德体系。我认为道德体系是任意和主观的：它只是将人、行为、思想、事件、人造物等在“好”和“坏”的类别进行一种划分而已 – 通常会利用神话或刻意挑选的事实来增强对这种划分的认同，并利用更一般的原则或概念来描述。因此，从某种抽象的角度来看，进步的道德体系与其他任何的道德体系的基础是一样的。&lt;/p&gt;

&lt;p&gt;What I do find very odd, though, is that any straight white male would buy into it. It’s the same as if a gay Jew were to join the Nazi party and begin endlessly apologizing for his ancestors having lent money to Aryans at too-high rates of interest; and agreeing that he needs to recognize his “problematic Jewishness” and “toxic homosexuality”, stop talking, and make space for Aryan voices to be heard. He might even take pride in having acknowledged the uniquely cancerous and exploitative nature of the Jewish people, despite being one himself. So is this person virtuous, or is he just too-easily manipulated? You decide. I know we’re approaching cerebral-haemorrhage territory here, for left-of-center readers, but it’s true: there are many things said by American progressives where if you replace “white patriarchy” and “women of color” with “Jewish capital” and “Aryan youth”, and add a picture of a blond boy and a swastika or two, you’d have a very serviceable Nazi propaganda poster. Think about it.&lt;/p&gt;

&lt;p&gt;然而我发现很奇怪的一点是，任何白直男（男性异性恋白种人）都在赞同这个道德体系。这就像一个同性恋犹太人加入了纳粹后，不停地为他的祖先以过高的利率借给雅利安人钱而道歉一样。然后他坦诚自省了自身的“错误的犹太性”和“有害的同性恋倾向”，并停止说话，敬候雅利安人的声音。他甚至可能为意识到了犹太人的不可救药的劣根性和剥削他人的天性而感到自豪，尽管他自己就是犹太人。所以到底是这个人太善良，还是他太容易被操纵呢？你可以想想。我知道我现在说的话可能会刺激到偏左翼的读者，但事实确实如此：想想美国的“思想进步“人士说的话，如果你把其中的“白人父权”和“有色女人”用“犹太资本”和”雅利安青年“替换下，并加上一个金发男孩和一两个纳粹标志，你会得到一个可以直接使用的纳粹宣传海报。想一想是不是这样。&lt;/p&gt;

&lt;p&gt;You might counter that my analogy is inappropriate because women of color actually are good and white men bad, and history and science prove it. But that’s a subjective judgement, because facts alone can never tell you what’s good or bad unless interptreted within a moral framework. And if you use a moral framework that was constructed with the specific goal of proving that women and non-whites are good and white men are bad (because it originated in women’s-studies and black-studies departments at universities), then that’s the conclusion you will reach.&lt;/p&gt;

&lt;p&gt;你可能会反驳说我的比喻是不恰当的，因为历史和科学证明了女性有色人种确实是善良的，而白人男性确实是坏的。但这其实是一种主观判断，因为事实本身并不能告诉你什么是好的或是坏的，好坏都是在道德框架内判定的。如果你使用的道德框架其构建目的就是为了证明女性和非白种人是好的，而白人是坏的（因为它起源于大学中的女性研究和的黑人研究部门），那么你当然会得到这个结论。&lt;/p&gt;

&lt;p&gt;I want to be clear: I’m not in favor of any political or cultural movements that are animated by resentment. The choice isn’t, and shouldn’t be, between demonizing one demographic group or demonizing the other. But to join a movement that’s specifically against one’s own group? That’s retarded. Man up, America! You’re better than that. Leave that garbage to the man-haters and racial agitators that generated it, stop apologizing, and start living your lives!&lt;/p&gt;

&lt;p&gt;我想声明一点：我不赞成任何因为怨恨而看起来充满生气的政治或文化运动。我们能做的选择不是，也不应该是非得妖魔化一个群体或另一个群体。但是去加入一场反对自己所在群体的运动实在太愚蠢了。站起来吧男人，美国男人！你们远不该如此卑贱，请把那些愤世嫉俗者和种族主义鼓动者生产的垃圾还给他们，不必再向谁道歉，开始自己的人生！&lt;/p&gt;

&lt;p&gt;Anywho: as for me, I may not have my job, but at least I still have my dignity and my independence of thought. I’ll leave you with some words of Bob Dylan:&lt;/p&gt;

&lt;p&gt;至于我，虽然可能没有了工作，但至少我还有着尊严和独立思想，这里送给大家一段Bob Dylan的话:&lt;/p&gt;

&lt;p&gt;I ain’t sorry for nothing I’ve done&lt;/p&gt;

&lt;p&gt;I’m glad I fought, I only wish we’d won&lt;/p&gt;

&lt;p&gt;对做过之事 我从未后悔&lt;/p&gt;

&lt;p&gt;我为之奋斗 一直骄傲如此&lt;/p&gt;

&lt;p&gt;我只是希望 假如我们赢了&lt;/p&gt;

&lt;p&gt;Please send my regards to the OIE, and say that, thanks to them, my career prospects have greatly improved.&lt;/p&gt;

&lt;p&gt;请替我向OIE表示祝福，感谢他们，让我从此前程似锦。&lt;/p&gt;

&lt;p&gt;Sayonara!&lt;/p&gt;

&lt;p&gt;再见(原文为日文“再见”的英文写法Sayonara)&lt;/p&gt;</content><author><name></name></author><summary type="html">Leaving Hopkins</summary></entry><entry><title type="html">Kaldi中的特征提取(二）- 特征变换</title><link href="http://placebokkk.github.io/kaldi/2019/08/05/asr-kaldi-feat2.html" rel="alternate" type="text/html" title="Kaldi中的特征提取(二）- 特征变换" /><published>2019-08-05T03:12:59+00:00</published><updated>2019-08-05T03:12:59+00:00</updated><id>http://placebokkk.github.io/kaldi/2019/08/05/asr-kaldi-feat2</id><content type="html" xml:base="http://placebokkk.github.io/kaldi/2019/08/05/asr-kaldi-feat2.html">&lt;h1 id=&quot;特征变换&quot;&gt;特征变换&lt;/h1&gt;

&lt;p&gt;kaldi的特征变换实现位于src/transform/&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;CMVN&lt;/em&gt; 对特征进行归一化，均值M做减法的归一化，方差V做归一化&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;差分模型（deltas)&lt;/em&gt; 是识别中经常使用的方法，即将不同帧的特征之间（比如当前帧特征减去前一帧特征，以及更高阶的差分）差值也作为特征.
kaldi存储的特征文件保留原始特征，而不包含CMVN变换和差分的特征，在每次需要（训练，识别或者对其）时再提取这些特征。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;脚本steps/train_mono.sh（使用deltas特征训练mono-phone）和steps/train_deltas.sh（使用deltas特征训练tri-phone）中的特征变换&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;&lt;span class=&quot;nv&quot;&gt;feats&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;ark,s,cs:apply-cmvn &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$cmvn_opts&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt; --utt2spk=ark:&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$sdata&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/JOB/utt2spk scp:&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$sdata&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/JOB/cmvn.scp scp:&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$sdata&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/JOB/feats.scp ark:- | add-deltas &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$delta_opts&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt; ark:- ark:- |&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;其中apply-cmvn做CMVN变换，add-deltas增加差分维度。&lt;/p&gt;

&lt;p&gt;除CMVN+deltas外，CMVN+LDA变换也是常用的变换&lt;/p&gt;

&lt;p&gt;steps/align_si.sh，steps/decode.sh等脚本支持使用不同的特征变换&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;-f&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;$srcdir&lt;/span&gt;/final.mat &lt;span class=&quot;o&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;then &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;feat_type&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;lda&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;feat_type&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;delta&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;fi
case&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;$feat_type&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in
  &lt;/span&gt;delta&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;feats&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;ark,s,cs:apply-cmvn &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$cmvn_opts&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt; --utt2spk=ark:&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$sdata&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/JOB/utt2spk scp:&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$sdata&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/JOB/cmvn.scp scp:&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$sdata&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/JOB/feats.scp ark:- | add-deltas &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$delta_opts&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt; ark:- ark:- |&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;;&lt;/span&gt;
  lda&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;feats&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;ark,s,cs:apply-cmvn &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$cmvn_opts&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt; --utt2spk=ark:&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$sdata&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/JOB/utt2spk scp:&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$sdata&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/JOB/cmvn.scp scp:&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$sdata&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/JOB/feats.scp ark:- | splice-feats &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$splice_opts&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt; ark:- ark:- | transform-feats &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$srcdir&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;/final.mat ark:- ark:- |&quot;&lt;/span&gt;
    &lt;span class=&quot;nb&quot;&gt;cp&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;$srcdir&lt;/span&gt;/final.mat &lt;span class=&quot;nv&quot;&gt;$srcdir&lt;/span&gt;/full.mat &lt;span class=&quot;nv&quot;&gt;$dir&lt;/span&gt;
   &lt;span class=&quot;p&quot;&gt;;;&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;echo&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$0&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;: invalid feature type &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$feat_type&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;exit &lt;/span&gt;1&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;esac&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h3 id=&quot;cmvn&quot;&gt;CMVN&lt;/h3&gt;
&lt;p&gt;CMVN对特征每一维做均值/方差归一化，每一维特征之间是独立的。&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;F_k^{cmvn} = (F_k - \mu_k) / \delta_k&lt;/script&gt;

&lt;p&gt;&lt;strong&gt;CMVN的模型存储结构&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;对于K维特征，kaldi存储 2* K+1的矩阵，其中存储的是统计量而不是计算好的均值和方差。&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;第一行存储K个均值统计量M和数据个数N。使用时，用M[k]/N作为归一化均值，&lt;/li&gt;
  &lt;li&gt;第二行存储K个方差统计量V和一个0（用不到）。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;通过cmvn可以了解kaldi的项目整体设计&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;顶层脚本
    &lt;ul&gt;
      &lt;li&gt;训练语料计算cmvn统计量 steps/compute_cmvn_stats.sh&lt;/li&gt;
      &lt;li&gt;需要应用特征变换的脚本 steps/align_si.sh，steps/decode.sh&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;C++实现的工具
    &lt;ul&gt;
      &lt;li&gt;训练语料计算cmvn统计量 /src/featbin/compute-cmvn-stats.cc&lt;/li&gt;
      &lt;li&gt;应用特征变换  /src/featbin/apply-cmvn.cc&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;C++核心实现 /src/transform/cmvn.cc&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;lda&quot;&gt;LDA&lt;/h3&gt;

&lt;p&gt;### 
[kaldi-lattice-url]: http://kaldi-asr.org/doc/lattices.html
[povey-lattice-paper]: https://www.danielpovey.com/files/2012_icassp_lattices.pdf&lt;/p&gt;</content><author><name></name></author><summary type="html">特征变换</summary></entry></feed>