RNN-T: separate the time and output axes
RNN Transducer
Compute the transducer lattice, terminal blank, alignment posteriors and joiner gradients on a finite example.
rnntCan one acoustic position emit two labels?
CTC selects a symbol per frame, then merges repetitions and blanks. An RNN Transducer (RNN-T) uses another timing rule: emitting a text label stays at the current acoustic position; emitting blank advances time. One acoustic position can therefore produce multiple labels, and repeated labels are not automatically merged. The two-axis transducer
This adds an output axis. The model considers both acoustic position and what has already been emitted. Training still sums hidden alignments instead of assuming frame-aligned transcripts. We take acoustic-encoder and label-predictor outputs as supplied vectors, implement the complete small-lattice loss, posteriors and gradients, then identify the networks and decoding components not implemented.
Time and output advance separately
Suppose acoustic representations have positions, the target has nonblank labels, and vocabulary size including blank is . State means acoustic positions consumed and target labels emitted. For , the joiner supplies next-symbol distribution . The original 2012 paper adds acoustic vector and prefix-prediction vector , then normalizes:
Vector should depend on the available label prefix, excluding future target labels. The original acoustic network is bidirectional; later systems may use different encoders or nonlinear joiners. The name RNN-T does not erase those distinctions. Predictor, encoder and output distribution
Blank moves to ; the next target label moves it to . No label may be emitted after . Acceptance is at , so the final step must be blank. Every accepted path has exactly blanks and label transitions:
Here removes only blank, without merging repetitions. With two equiprobable classes, one acoustic position and target aaa, path aaa blank is legal, probability 1/16. CTC cannot represent that target in one frame. Allowing longer outputs does not guarantee enough information from any particular encoder.
Forward mass starts with and accumulates legal predecessors:
Blank is index 0 and out-of-range terms are not evaluated. Apply this recurrence outside the origin. Disabling its second term at enforces the final blank; otherwise labels emitted after all acoustic input is consumed would enter the sum. The original paper starts time at 1 and multiplies the final blank separately, equivalent to our zero-based convention. Terminal equation 17
Backward value is the probability of completing the remaining target. Set and other positions at to zero. For :
Then . Agreement between directions checks indexing and termination. Combining forward and backward values yields posterior probabilities of the two outgoing edges conditioned on the target:
At , the label-edge posterior is zero. State visit probability sums to over the lattice, not one. Blank-edge posteriors sum to and label-edge posteriors to , because every accepted path traverses exactly those counts.
For independent joiner logit , the derivative is visit-weighted softmax probability minus the relevant edge posterior:
Other labels do not contribute matching target edges, but still affect loss through softmax normalization. With an additive joiner, sum gradients over for and over for . Training actual networks requires further backpropagation through the encoder and predictor. Lattice gradients
Enumerate how labels are allocated to frames
The complete Python/NumPy program accepts finite logits shaped , with blank 0. Bounds are , and . torchaudio 2.6 additionally has a batch axis, defaults blank to −1 and can fuse log-softmax. We use one sequence with explicit stable log-softmax, so the configurations differ. RNN-T loss interface
"""Finite RNN-T lattice loss and gradients with the terminal blank explicit.
Supplied joiner logits, zero-based time, blank0. Labels advance the output axis;
blank advances time. Repeated labels are not merged. No trained speech encoder.
"""
import itertools,json,math
import numpy as np
def inputs(logits,target):
x=np.asarray(logits)
if np.iscomplexobj(x):raise ValueError('Real logits required')
x=np.asarray(x,float)
if not isinstance(target,(list,tuple)) or len(target)>5:raise ValueError('Bounded target required')
if x.ndim!=3 or not 1<=x.shape[0]<=6 or x.shape[1]!=len(target)+1 or not 2<=x.shape[2]<=4 or not np.isfinite(x).all() or (abs(x)>50).any():raise ValueError('Use T by U+1 by V logits, T1–6, V2–4, within±50')
if any(type(t) is not int or not 1<=t<x.shape[2] for t in target):raise ValueError('Targets must be nonblank integer labels')
z=x-x.max(axis=2,keepdims=True);lp=z-np.log(np.exp(z).sum(axis=2,keepdims=True));return lp,list(target)
def infer(logits,target):
lp,target=inputs(logits,target);T,cols,V=lp.shape;U=len(target);a=np.full((T+1,U+1),-np.inf);a[0,0]=0
for t in range(T):
for u in range(U+1):
a[t+1,u]=np.logaddexp(a[t+1,u],a[t,u]+lp[t,u,0])
if u<U:a[t,u+1]=np.logaddexp(a[t,u+1],a[t,u]+lp[t,u,target[u]])
z=a[T,U];b=np.full_like(a,-np.inf);b[T,U]=0
for t in range(T-1,-1,-1):
for u in range(U,-1,-1):
b[t,u]=lp[t,u,0]+b[t+1,u]
if u<U:b[t,u]=np.logaddexp(b[t,u],lp[t,u,target[u]]+b[t,u+1])
blank=np.exp(a[:T]+lp[:,:,0]+b[1:]-z);label=np.zeros((T,U+1))
for u in range(U):label[:,u]=np.exp(a[:T,u]+lp[:,u,target[u]]+b[:T,u+1]-z)
visits=blank+label;grad=visits[:,:,None]*np.exp(lp);grad[:,:,0]-=blank
for u in range(U):grad[:,u,target[u]]-=label[:,u]
return dict(log_probability=float(z),loss=float(-z),probability=float(np.exp(z)),gradient=grad.tolist(),blank_posterior=blank.tolist(),label_posterior=label.tolist(),state_visits=visits.tolist(),backward_start=float(b[0,0]))
def enumerate_alignments(logits,target):
lp,target=inputs(logits,target);T,_,_=lp.shape;U=len(target);rows=[]
# Allocate U ordered labels to T frames; every frame ends with blank.
for separators in itertools.combinations(range(U+T-1),T-1):
counts=np.diff([-1,*separators,U+T-1])-1;u=0;weight=0.;path=[]
for t,count in enumerate(counts):
for _ in range(count):
token=target[u];weight+=lp[t,u,token];path.append([t,u,token]);u+=1
weight+=lp[t,u,0];path.append([t,u,0])
rows.append(dict(steps=path,log_probability=float(weight),probability=float(np.exp(weight))))
logs=np.array([r['log_probability'] for r in rows]);v=logs.max()+np.log(np.exp(logs-logs.max()).sum())
return dict(alignments=rows,count=len(rows),log_probability=float(v),probability=float(np.exp(v)))
def additive_joiner(acoustic,prediction):
if np.iscomplexobj(acoustic) or np.iscomplexobj(prediction):raise ValueError('Real encoder and predictor vectors required')
a=np.asarray(acoustic,float);g=np.asarray(prediction,float)
if a.ndim!=2 or g.ndim!=2 or a.shape[1]!=g.shape[1] or not 1<=len(a)<=6 or not 1<=len(g)<=6 or not 2<=a.shape[1]<=4 or not np.isfinite(a).all() or not np.isfinite(g).all() or (abs(a)>25).any() or (abs(g)>25).any():raise ValueError('Bounded compatible T by V and U+1 by V arrays required')
return a[:,None,:]+g[None,:,:]
def demo():
acoustic=np.array([[.3,.1,-.2],[-.1,.2,.4]]);prediction=np.array([[.1,.2,0],[.2,-.1,.3],[.4,.1,-.2]]);target=[1,1];x=additive_joiner(acoustic,prediction);r=infer(x,target);training=[r['loss']]
for _ in range(5):
gradient=np.array(infer(additive_joiner(acoustic,prediction),target)['gradient']);acoustic-=.15*gradient.sum(axis=1);prediction-=.15*gradient.sum(axis=0);training.append(infer(additive_joiner(acoustic,prediction),target)['loss'])
uniform=np.zeros((2,3,3));one=np.zeros((1,4,2));empty=np.zeros((2,1,2))
return dict(logits=x.tolist(),target=target,inference=r,enumeration=enumerate_alignments(x,target),uniform=dict(inference=infer(uniform,target),enumeration=enumerate_alignments(uniform,target)),longer_than_input=dict(inference=infer(one,[1,1,1]),enumeration=enumerate_alignments(one,[1,1,1])),empty=infer(empty,[]),training_losses=training)
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
Enumeration distributes ordered labels across acoustic positions, each ending with blank: weak compositions. With three equiprobable classes, and target aa, there are three paths of length 4. Total probability is 3/81, or 1/27. Using incorrectly includes paths without a final blank.
Our nonuniform target-aa example has total probability approximately 0.0457723522, agreed by three-path enumeration, forward inference and backward inference. Central differences check both logit and additive-joiner gradients. Five updates of the supplied vectors reduce loss from approximately 3.084075 to 1.499087. That is neither training a recurrent predictor nor a speech-recognition result.
The lattice DP itself is ; complete softmax and gradient tensors take time and storage. Enumeration additionally scales by path count and each path’s length. Finite logits give mathematically positive target probability, but the ordinary floating-point probability field may underflow to zero. Compare tiny masses through log_probability or loss.
Transduction does not guarantee real-time recognition
Streaming latency depends on future context in the acoustic encoder, temporal downsampling, decoding and output-stability policies. The original bidirectional encoder already demonstrates that this loss alone does not guarantee low latency. Predictor and joiner implementations can also differ; the paper’s addition formula is not the only structure of every modern system.
Training knows the target and can sum on a fixed lattice. Testing does not know the target, requiring search over prefixes, control of consecutive label emissions, predictor-state maintenance and termination handling. We do not implement unknown-target beam decoding, a lexicon, external language model or model weights. Supplied prefix vectors are explicit numerical inputs, not patterns learned from real text.
Identify which axis moves first
-
Understanding. What advances on a label versus blank? Does a a merge into a?
Answer: A label advances output; blank advances time. Two a labels remain aa. RNN-T removes blank without CTC-style repetition merging.
-
Calculation. Why do two acoustic positions, two target labels and three equiprobable classes give probability 1/27?
Answer: Three allocations place both labels at the first position, one at each, or both at the second. Every path has two labels and two blanks, probability . Their sum is 3/81.
-
Boundary. Can one acoustic position output aaa, and why retain the final blank?
Answer: Yes: emit aaa, then blank to consume the position. With two equiprobable classes, mass is 1/16. Without blank the accepting endpoint has not been reached; omitting it changes length and probability.
-
Transfer. Does replacing CTC loss with RNN-T justify a real-time streaming claim without changing a bidirectional encoder?
Answer: No. The encoder may still need future audio, and buffering, search and output policies affect latency. Define and measure the timing conditions of the complete system.
Separate the original architecture from current interfaces
Graves’ 2012 arXiv v1 supplies the bidirectional encoder, predictor, additive joiner, lattice, final-blank and gradient equations. We use equivalent zero-based boundaries. torchaudio 2.6 documentation checks tensor shape, blank and log-softmax options without executing the library. The program verifies only synthetic lattices, alignments and supplied-vector gradients, not TIMIT results or a modern transducer implementation.
Make a prediction, then check
Which transition advances acoustic time in this RNN-T lattice?
Learning objectives
- Identify label and blank transitions on separate axes.
- Keep the final blank in likelihood and alignment counts.
- Derive edge posteriors and occupancy-weighted gradients.
- Separate a transducer loss from streaming-system guarantees.
Prerequisites & connections
Explore related knowledge →References
- Sequence Transduction with Recurrent Neural Networks, arXiv v1
Alex Graves · 2012 - torchaudio 2.6.0: functional.rnnt_loss
torchaudio contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked the original2012 additive joiner and bidirectional acoustic encoder, separate time/output axes, final blank, stars-and-bars alignment count, log-space lattice, edge posteriors and occupancy-weighted gradients against the v1 paper and torchaudio2.6 interface. Six paired equations and four explained exercises. Supplied vectors only, not a trained recurrent predictor or streaming guarantee; DP complexity includes empty targets.
- Checked terminal blank, repeated labels on one frame, uniform1/27 and1/16 probabilities, path enumeration, T/U edge-count identities and logit/joiner derivatives.
- Four computed SVGs bind exact bilingual MDX. The five-topic group passed eleven numeric/encoding checks and 30 isolated language/width cases with four fallback fonts; ten actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
- After rendered review, inserted missing spaces before English reference citations. Verified an exact whitespace-only transformation, unchanged formulas/program and preserved frozen article/test payloads; see editorial/corrections/011h-citation-spacing.
Source locations checked:
- Sequence Transduction with Recurrent Neural Networks, arXiv v1 · Read section2 prediction/bidirectional transcription networks, additive joiner and forward recurrence; visually inspected page4 lattice, terminal blank and equations17–22. Synthetic supplied-vector gradients only, not LSTM or TIMIT replication.
- torchaudio 2.6.0: functional.rnnt_loss · Read batch/T/(U+1)/class shape, targets, default blank−1, fused log-softmax and reduction. Our single-sequence blank0 configuration differs. No torchaudio execution or compatibility benchmark.
Related topics