AI Wiki中文/EN

Tacotron: aligning text with groups of acoustic frames

Tacotron

Follow original Tacotron, derive a small attention decoder and paired L1 gradients, and test grouped feedback and padding.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two frames at a time still need the right place in the sentence

Imagine a decoder reading three text units and producing seven acoustic frames. The lengths do not match, and the decoder must decide which text unit matters at each output step. Predicting two frames together shortens the number of decoding steps, but does not tell it when to advance, repeat or stop.

Original Tacotron learns a text-to-acoustic sequence mapping using an encoder, attention and an autoregressive decoder. A postprocessing network predicts a linear-frequency magnitude representation, followed by Griffin-Lim waveform reconstruction. The model therefore connects text with acoustic frames; it is not the same sample-level prediction task as a waveform autoregressor. The fixed 2017 paper is the source for this original design. Tacotron

Read attention, teacher forcing and mel spectrograms first. The worked program replaces the large encoder and recurrent modules with small inspectable components while preserving an explicit alignment, grouped feedback and two acoustic losses.

Seven targets become eight padded frames; learned attention and teacher-versus-predicted feedback reveal the grouped decoder computation.
Seven targets become eight padded frames; learned attention and teacher-versus-predicted feedback reveal the grouped decoder computation.

Follow the representation and the feedback separately

The paper’s CBHG encoder combines a convolution bank, stride-one max pooling, convolution projections, residual connections, highway layers and a bidirectional GRU. The bank offers different local receptive widths; the bidirectional recurrent part can use text on both sides. This is permitted because the input text is already supplied, and it should not be confused with access to future generated acoustic frames. Section 3.1

The original decoder uses content-based attention and recurrent states to select encoder information. To expose the same attention principle in two dimensions, our example uses fixed memory vectors mim_i, a query qsq_s and a trainable vector vv:

es,i=v⊤tanh⁡(mi+qs),as,i=ees,i∑jees,j,cs=∑ias,imi.e_{s,i}=v^\top\tanh(m_i+q_s),\quad a_{s,i}=\frac{e^{e_{s,i}}}{\sum_j e^{e_{s,j}}},\quad c_s=\sum_i a_{s,i}m_i.

The weights sum to one, so csc_s is a convex combination of memory vectors. Sharp weights do not guarantee monotonic movement through the text. Softmax normalizes scores; it does not enforce correct pronunciation, coverage or ordering.

The reduction factor rr is the number of nonoverlapping acoustic frames predicted per decoder step. Original Tacotron feeds back the last frame of the preceding group; the first step receives an all-zero GO frame. With zero-based indexing, the rule is:

f0=0,fstrain=Ysr−1∗,fsinfer=Y^sr−1(s≥1).f_0=0,\qquad f_s^{\rm train}=Y^*_{sr-1},\qquad f_s^{\rm infer}=\widehat Y_{sr-1}\quad(s\ge1).

During teacher forcing, that preceding frame comes from the reference. During inference it comes from the previous prediction. For r=2r=2, the second decoder step sees the second reference frame, not the fourth. Feeding the last frame of the current target group would leak an answer the running synthesizer does not have. The paper also uses a prenet with dropout; our substitute omits it. Section 3.3

We replace the recurrent query machinery with a fixed tanh recurrence and a trainable grouped output projection. Each memory, query, context and feedback vector has dimension 2; WW has shape 5×2r5\times2r:

qs=tanh⁡(0.3qs−1+fs),Xs=[cs⊤,fs⊤,1],Y^sr:(s+1)r−1=reshape⁡r×2(XsW).q_s=\tanh(0.3q_{s-1}+f_s),\quad X_s=[c_s^\top,f_s^\top,1],\quad\widehat Y_{sr:(s+1)r-1}=\operatorname{reshape}_{r\times2}(X_sW).

The initial query before the first step is zero. This recurrence is not a GRU and the fixed memory is not CBHG. The output represents two-dimensional synthetic acoustic features, not actual 80-band mel frames.

Original Tacotron postprocesses the decoded sequence using another CBHG and predicts linear-frequency magnitudes. That stage can use the whole decoded sequence. Our miniature substitute smooths adjacent frames using a fixed matrix, then applies a trainable projection to three synthetic features:

L^=KY^P,K=0.8I+0.1I+1+0.1I−1,P∈R2×3.\widehat L=K\widehat YP,\qquad K=0.8I+0.1I_{+1}+0.1I_{-1},\qquad P\in\mathbb R^{2\times3}.

The off-diagonal matrices contain ones immediately above or below the diagonal. Edge rows sum to 0.9 because a neighbor is absent; the program does not renormalize them. This operator illustrates future-frame access in postprocessing, not a learned CBHG.

The original paper trains mel and linear outputs with equally weighted L1 losses and includes zero-padded frames. For our padded length TT, the analogous objective uses elementwise absolute-value sums:

J=12T∥Y^−Y∗∥1+13T∥KY^P−L∗∥1.J=\frac1{2T}\|\widehat Y-Y^*\|_1+\frac1{3T}\|K\widehat YP-L^*\|_1.

Keeping the two mean losses equally weighted differs from pooling all five feature dimensions into a single mean. Our seven target frames are padded to eight at r=2r=2; the padding contributes to the loss. It should not silently disappear from the denominator.

For the linear projection and mel prediction, the chain rule gives:

GL=sgn⁡(KY^P−L∗)3T,∇PJ=(KY^)⊤GL,GY=sgn⁡(Y^−Y∗)2T+K⊤GLP⊤.G_L=\frac{\operatorname{sgn}(K\widehat YP-L^*)}{3T},\quad\nabla_P J=(K\widehat Y)^\top G_L,\quad G_Y=\frac{\operatorname{sgn}(\widehat Y-Y^*)}{2T}+K^\top G_LP^\top.

The L1 derivative at exact zero is undefined; the implementation chooses subgradient 0. Reshape GYG_Y to grouped rows when differentiating WW. The context gradient then reaches attention through its softmax Jacobian:

∇WJ=X⊤reshape⁡(GY),ge=a⊙(ga−(a⊤ga)1),∇vJ=∑s∑ige,s,itanh⁡(mi+qs).\nabla_W J=X^\top\operatorname{reshape}(G_Y),\quad g_e=a\odot\left(g_a-(a^\top g_a)\mathbf1\right),\quad \nabla_vJ=\sum_s\sum_i g_{e,s,i}\tanh(m_i+q_s).

Here gag_a is the gradient with respect to the attention weights for one step. The shared-score subtraction couples all memory positions. Teacher feedback is fixed input in this training computation, so gradients do not flow into reference frames. The program differentiates every trainable attention, output and postprojection parameter; finite-difference cases avoid L1 corners, and zero residual has a separate test.

Seven targets, eight padded frames, four decoder steps

Run with Python 3.12 and NumPy 1.26.4. Three fixed memory vectors and seven two-feature target frames define a synthetic fit. Three-feature targets are derived from those same values by a declared matrix. The model trains for 200 steps of size 0.03; no text corpus, encoder training, real spectrogram extraction or speech waveform is involved.

pack determines group boundaries and teacher feedback. objective calculates both L1 terms and gradients. generate substitutes predicted feedback and uses an external fixed step limit. That limit is an honest runtime control, not a learned stopping decision.

"""Original attention/grouped-frame training example, not Tacotron replication.

Fixed two-dimensional encoder states and query recurrence replace CBHG/GRUs.
Trainable content attention, grouped acoustic projection and linear-frequency
projection use equal mean L1 losses, including padded frames. No stop gate,
dropout, real mel filterbank, speech data, waveform synthesis or listening score.
"""
import json
import numpy as np


def matrix(value,columns,max_rows=64):
    a=np.asarray(value)
    if a.dtype.kind not in 'fiu' or a.ndim!=2 or not 1<=len(a)<=max_rows or a.shape[1]!=columns or not np.isfinite(a).all() or np.any((a < -8)|(a > 8)):raise ValueError('Invalid bounded matrix')
    return a.astype(float)


def pack(frames,r=2):
    y=matrix(frames,2)
    if type(r) is not int or not 1<=r<=4:raise ValueError('Invalid reduction factor')
    padding=(-len(y))%r;padded=np.pad(y,((0,padding),(0,0)))
    blocks=padded.reshape(-1,r,2);feedback=np.vstack([np.zeros((1,2)),blocks[:-1,-1]])
    return dict(padded=padded,blocks=blocks,feedback=feedback,padding=padding)


def initialize(r=2,seed=5):
    if type(r) is not int or not 1<=r<=4 or type(seed) is not int or not 0<=seed<2**32:raise ValueError('Invalid model settings')
    rng=np.random.default_rng(seed)
    return dict(v=np.array([.6,-.4]),w=rng.normal(0,.12,(5,2*r)),p=rng.normal(0,.12,(2,3)))


def parameters(value,r):
    if not isinstance(value,dict) or set(value)!={'v','w','p'}:raise ValueError('Invalid parameter names')
    p={k:np.asarray(v) for k,v in value.items()};shapes=dict(v=(2,),w=(5,2*r),p=(2,3))
    if any(a.shape!=shapes[k] or a.dtype.kind not in 'fiu' or not np.isfinite(a).all() or np.any((a < -8)|(a > 8)) for k,a in p.items()):raise ValueError('Invalid parameter values')
    return {k:a.astype(float) for k,a in p.items()}


def attention(memory,query,v):
    features=np.tanh(memory+query);scores=features@v;weights=np.exp(scores-scores.max());weights/=weights.sum()
    return weights,weights@memory,features


def smoother(n):
    # A fixed whole-sequence context operator, not a learned CBHG postnet.
    return .8*np.eye(n)+.1*np.eye(n,k=1)+.1*np.eye(n,k=-1)


def objective(memory,mel_target,linear_target,value,r=2):
    m=matrix(memory,2,max_rows=16);packed=pack(mel_target,r);p=parameters(value,r)
    linear=matrix(linear_target,3)
    if len(linear)!=len(mel_target):raise ValueError('Acoustic target lengths disagree')
    linear=np.pad(linear,((0,packed['padding']),(0,0)));query=np.zeros(2);features=[];weights=[];energy_features=[]
    for feedback in packed['feedback']:
        query=np.tanh(.3*query+feedback)
        a,context,e=attention(m,query,p['v']);features.append(np.r_[context,feedback,1.]);weights.append(a);energy_features.append(e)
    x=np.array(features);prediction=(x@p['w']).reshape(-1,2);k=smoother(len(prediction));smooth=k@prediction;linear_prediction=smooth@p['p']
    mel_residual=prediction-packed['padded'];linear_residual=linear_prediction-linear
    loss=float(np.mean(abs(mel_residual))+np.mean(abs(linear_residual)))
    dl=np.sign(linear_residual)/linear_residual.size;dp=smooth.T@dl
    dy=np.sign(mel_residual)/mel_residual.size+k.T@dl@p['p'].T;db=dy.reshape(len(x),2*r)
    dw=x.T@db;dx=db@p['w'].T;dv=np.zeros(2)
    for i,a in enumerate(weights):
        da=m@dx[i,:2];de=a*(da-a@da);dv+=energy_features[i].T@de
    return dict(loss=loss,mel_loss=float(np.mean(abs(mel_residual))),linear_loss=float(np.mean(abs(linear_residual))),gradient=dict(v=dv,w=dw,p=dp),
        mel=prediction,linear=linear_prediction,attention=np.array(weights),feedback=packed['feedback'],padding=packed['padding'])


def fit(memory,mel,linear,steps=200,rate=.03,r=2):
    if type(steps) is not int or not 0<=steps<=500 or type(rate) not in (int,float) or not 0<rate<=.1:raise ValueError('Invalid training settings')
    p=initialize(r);history=[]
    for _ in range(steps):
        result=objective(memory,mel,linear,p,r);history.append(result['loss'])
        p={k:v-rate*result['gradient'][k] for k,v in p.items()}
    history.append(objective(memory,mel,linear,p,r)['loss'])
    return dict(parameters=p,history=history)


def generate(memory,value,steps=4,r=2):
    m=matrix(memory,2,16)
    if type(r) is not int or not 1<=r<=4 or type(steps) is not int or not 1<=steps<=16:raise ValueError('Use a bounded external decoding limit')
    p=parameters(value,r);query=np.zeros(2);feedback=np.zeros(2);frames=[];weights=[];inputs=[]
    for _ in range(steps):
        inputs.append(feedback.copy());query=np.tanh(.3*query+feedback)
        a,context,_=attention(m,query,p['v']);block=(np.r_[context,feedback,1.]@p['w']).reshape(r,2)
        frames.extend(block);weights.append(a);feedback=block[-1]
    mel=np.array(frames)
    return dict(mel=mel,linear=smoother(len(mel))@mel@p['p'],attention=np.array(weights),feedback=np.array(inputs),stopping='external fixed step limit')


def demo():
    memory=np.array([[1.,0.],[0.,1.],[-1.,.5]])
    mel=np.array([[.2,.1],[.3,.2],[.5,.4],[.6,.5],[.7,.4],[.4,.2],[.1,.1]])
    linear=mel@np.array([[1.,.5,.2],[.3,.8,1.1]])
    learned=fit(memory,mel,linear);teacher=objective(memory,mel,linear,learned['parameters']);inference=generate(memory,learned['parameters'])
    return dict(reduction_factor=2,steps=200,original_frames=7,padded_frames=8,padding=teacher['padding'],training_first=learned['history'][0],training_last=learned['history'][-1],training_history=learned['history'][::10],
        mel_target=mel.tolist(),linear_target=linear.tolist(),teacher={k:teacher[k].tolist() for k in ('mel','linear','attention','feedback')},
        inference={k:(v.tolist() if isinstance(v,np.ndarray) else v) for k,v in inference.items()},
        parameters={k:v.tolist() for k,v in learned['parameters'].items()})


if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

Loss decreases from about 0.753724 to 0.361774, and attention, output and postprojection parameters all change. A constant learning rate with L1 does not guarantee monotonic loss at every step. Teacher-forced and generated outputs agree for the first group because their initial inputs agree; later groups generally diverge as their feedback differs.

Inspect the final padded frame and both feedback arrays. Training receives true frames 2, 4, 6 after GO. Inference receives its own predicted frames 2, 4, 6. These indices are one-based descriptions of the zero-based rule above. A plot of the training attention alone cannot establish that inference reads the sequence correctly.

With SS decoder steps and MM memory vectors, the attention work is O(SM)O(SM) at this fixed feature dimension. The program explicitly stores a T×TT\times T smoothing matrix for clarity. A sparse three-diagonal application could use linear work and storage, but this implementation does not claim that optimization. Inputs are bounded to 64 target frames and 16 memory vectors; inference allows at most 16 groups with reduction factor 1–4.

Original Tacotron is not a synonym for every later implementation

The original setup includes 24 kHz audio,50 ms windows,12.5 ms hops,2048-point FFT and reduction factor 2. Its postprocessing output is reconstructed with Griffin-Lim, using the paper’s particular magnitude shaping and iteration choices. These are configuration details, not universal convergence guarantees. Griffin-Lim itself fits magnitudes; it does not verify text alignment or guarantee the original phase. Original setup Phase reconstruction

The fixed NVIDIA Tacotron2 implementation uses location-sensitive attention and a gate threshold with a maximum-step guard. Its separate loss file uses two mel MSE terms plus gate binary cross-entropy. These differ from the original Tacotron content-attention/L1/zero-padding account. A code example labeled Tacotron2 cannot silently serve as evidence that Tacotron1 used the same stopping or loss design. Tacotron2 attention and inference Tacotron2 loss

Our example has no CBHG, GRU, prenet dropout, actual mel filterbank or waveform stage. Training loss cannot establish naturalness, intelligibility or monotonic alignment. For an expanded experiment, test output on held-out text lengths, inspect skipped/repeated content and report the stopping rule. Keep acoustic error and a declared listening evaluation separate. No MOS score or full model reproduction is claimed here.

Trace the last frame of the preceding group

  1. Choose the teacher input. With r=2r=2, which reference frame is fed to the third decoder step?

Answer: The fourth reference frame, which ends the second group. The first step gets GO; subsequent steps receive the last frame of the preceding group. The sixth reference frame would end the current third group and would leak its answer.

  1. Count padding. Seven frames are grouped with r=2r=2. How many groups and padded frames are there, and does the loss use the padding?

Answer: There are four groups and eight total frames, including one appended zero frame. Both acoustic mean losses include that frame under the stated policy. Masking it out would change the training objective and normalization.

  1. Future access in the right place. The postprocessor uses frame 3 to refine frame 2. Is this necessarily a violation of decoder causality?

Answer: No. The postprocessor can run after the acoustic sequence has been decoded. That differs from feeding the future target frame into the current autoregressive decoder step. State the processing schedule before diagnosing leakage or claiming streaming latency.

  1. A repository comparison. Someone says original Tacotron used a learned stop gate because the inspected Tacotron2 code does. What evidence is missing?

Answer: Evidence about the original model’s actual stopping design. The 2017 paper’s zero-padding training description and the later code’s gate/max-step behavior belong to different implementations. Likewise, later MSE-plus-BCE losses cannot replace the original paired L1 objective in an account of Tacotron1.

Compare a paper and a codebase without merging their versions

The fixed Tacotron paper supports the encoder, grouped decoder, postprocessing and acoustic-loss account. Griffin and Lim explain the reconstruction stage. The two fixed Tacotron2 source files support a concrete later-version comparison. We read the relevant mechanisms, not the complete listening experiments or all implementation dependencies, and did not execute upstream models.

When extending this example, replace one simplified component at a time and keep its input/output contract explicit. A better attention map, a lower acoustic loss and a more understandable utterance are three observations that need not improve together.

Make a prediction, then check

With reduction factor2, what feeds the second decoder step during teacher forcing?

Choose one answer

Learning objectives

  • Distinguish original Tacotron from later Tacotron2 implementations.
  • Track the last frame of each group through training and inference.
  • Derive attention and paired acoustic L1 gradients.
  • Explain padding, stopping and learned alignment limitations.

Prerequisites & connections

Explore related knowledge →

References

  1. Tacotron: Towards End-to-End Speech Synthesis (arXiv v2)
    Yuxuan Wang; RJ Skerry-Ryan; Daisy Stanton; Yonghui Wu; Ron J. Weiss; Navdeep Jaitly; Zongheng Yang; Ying Xiao; Zhifeng Chen; Samy Bengio; Quoc Le; Yannis Agiomyrgiannakis; Rob Clark; Rif A. Saurous · 2017
  2. Signal Estimation from Modified Short-Time Fourier Transform
    Daniel W. Griffin; Jae S. Lim · 1984
  3. Tacotron2 attention and inference at185cd24
    NVIDIA Tacotron2 contributors
  4. Tacotron2 acoustic and gate losses at185cd24
    NVIDIA Tacotron2 contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked original Tacotron grouped last-frame feedback, paired L1 and zero padding against fixed Tacotron2 attention/gate/MSE differences. Seven paired equations, four explained exercises, full toy attention/output/postprojection gradients. Fixed memory/query are not CBHG/GRUs; no speech corpus or listening claim.

  • Actual attention/W/P gradients, L1 zero subgradient, seven-to-eight padding, teacher frames2/4/6 versus predicted group ends and whole-sequence postprocessing tested.200-step loss0.753724 to0.361774; external step limit is not a learned gate.
  • Four computed SVGs bind exact bilingual MDX. The four-topic group passed14 numeric/encoding checks and24 isolated language/width cases with four fallback fonts; eight representative actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.