AI Wiki中文/EN

WaveNet: predicting one sample without seeing its answer

WaveNet

Derive companding, gated dilated convolution and categorical gradients; train and sample a strictly causal toy model.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A predictor must not receive the sample it is guessing

Imagine training a model to predict the next audio sample while accidentally leaving that sample in its input window. Its loss might look excellent. At generation time, however, the answer would not yet exist. The model would have learned a task that the synthesizer cannot perform.

WaveNet models a waveform through conditional predictions of individual samples. Its dilated causal convolutions make a long history available without using future waveform samples. The 2016 architecture combines gated transformations, residual paths and skip connections with an output distribution over sample values. The original announcement is dated September 8, 2016; the fixed paper version studied here is dated September 19. These identify an announcement and a particular manuscript version, not an independently reproduced performance result. Announcement Model description

Review convolution and conditional probability first. The example below trains an original scalar-channel model on a short synthetic signal. It lets us inspect every parameter and perturb the input to determine exactly which predictions depend on it.

Quantization, an actual input-perturbation matrix, training likelihood and sequential samples expose the strict-past model and its teaching limits.
Quantization, an actual input-perturbation matrix, training likelihood and sequential samples expose the strict-past model and its teaching limits.

From a waveform probability to a causal computation

The chain rule of probability expresses a joint distribution as a product. Before the first sample, the history is empty. Quantizing samples to categorical codes ctc_t gives a mean negative log-likelihood objective:

p(x0:T−1)=∏t=0T−1p(xt∣x0:t−1),L=−1T∑t=0T−1log⁡p(ct∣c0:t−1).p(x_{0:T-1})=\prod_{t=0}^{T-1}p(x_t\mid x_{0:t-1}),\qquad\mathcal L=-\frac1T\sum_{t=0}^{T-1}\log p(c_t\mid c_{0:t-1}).

This factorization is not itself a neural architecture. A model must still specify each conditional distribution. During training, the complete reference sequence is available, so a causal convolution can calculate predictions for many positions together. During generation, each new sample depends on already generated samples. That dependency survives even if training is highly parallel. WaveNet, section 2

The original model uses a 256-way categorical output after µ-law companding. Companding changes resolution before quantization: it expands small amplitudes in the compressed coordinate and compresses large ones. For normalized sample x∈[−1,1]x\in[-1,1]:

z=sgn⁡(x)log⁡(1+μ∣x∣)log⁡(1+μ),x=sgn⁡(z)μ((1+μ)∣z∣−1).z=\operatorname{sgn}(x)\frac{\log(1+\mu|x|)}{\log(1+\mu)},\qquad x=\frac{\operatorname{sgn}(z)}\mu\left((1+\mu)^{|z|}-1\right).

The original choice is μ=255\mu=255. We retain that companding parameter but reduce the teaching alphabet to Q=16Q=16. Our nearest-grid convention is:

c=⌊(z+1)(Q−1)2+12⌋,z^=2cQ−1−1,∣z−z^∣≤1Q−1.c=\left\lfloor\frac{(z+1)(Q-1)}2+\frac12\right\rfloor,\quad \widehat z=\frac{2c}{Q-1}-1,\quad |z-\widehat z|\le\frac1{Q-1}.

The error bound holds in compressed coordinates, not uniformly in waveform amplitude. With even QQ, no reconstruction grid point is exactly zero: code 8 is a small positive value. The fixed librosa implementation uses digitize and signed indices; its bin boundaries differ from this declared grid. Do not treat a shared µ-law formula as proof that two integer encodings are interchangeable. Original companding Library convention

For one scalar-channel layer, dilation dd means using the current hidden value and a hidden value dd positions earlier. A tanh branch supplies a signed transformation, and a sigmoid branch gates it:

ut=tanh⁡(f0ht+f1ht−d) σ(g0ht+g1ht−d),ht+=ht+rut.u_t=\tanh(f_0h_t+f_1h_{t-d})\,\sigma(g_0h_t+g_1h_{t-d}),\qquad h_t^+=h_t+r u_t.

Here f0,f1,g0,g1f_0,f_1,g_0,g_1 are filter coefficients, rr is a residual gain, and missing left-context values are zero. The identity term in h+h^+ supplies another gradient path. Separately, every layer contributes to a skip sum used by the output. The final layer needs a skip contribution but no unused residual gain if no later layer consumes that residual output. The teaching model therefore contains two residual gains for three layers.

For sequential layers with kernel width kk, the receptive-field length grows by (k−1)d(k-1)d per layer. Our dilations are 1, 2, 4. Crucially, hidden-layer causality still permits the current hidden input; we must shift the original sample sequence:

R=1+(k−1)∑ℓdℓ=1+1+2+4=8,ht(0)=z^t−1,z^−1=0.R=1+(k-1)\sum_\ell d_\ell=1+1+2+4=8,\qquad h_t^{(0)}=\widehat z_{t-1},\quad \widehat z_{-1}=0.

The input uses the reconstructed quantization grid z^\widehat z, not the unrounded compressed value zz. Prediction tt can then depend on original samples t−8t-8 through t−1t-1, excluding xtx_t. The paper’s example width-two dilation cycle 1, 2, 4, …, 512 spans 1024 hidden-input positions by the same calculation. Stacking cycles enlarges the field further; the receptive field is not simply the largest dilation. Dilated convolutions

Let each layer’s scalar skip gain be sℓs_\ell. The output uses QQ weights oqo_q and biases bqb_q:

st=∑ℓsℓut(ℓ),ℓt,q=stoq+bq,pt,q=eℓt,q−mt∑jeℓt,j−mt,mt=max⁡jℓt,j.s_t=\sum_\ell s_\ell u_t^{(\ell)},\quad \ell_{t,q}=s_t o_q+b_q,\quad p_{t,q}=\frac{e^{\ell_{t,q}-m_t}}{\sum_j e^{\ell_{t,j}-m_t}},\quad m_t=\max_j\ell_{t,j}.

Subtracting the maximum logit avoids overflow without changing probabilities. With natural logarithms, the training loss is measured in nats per sample. Differentiating log-softmax gives:

∂L∂ℓt,q=pt,q−1[q=ct]T,∂L∂oq=∑tst∂L∂ℓt,q,∂L∂bq=∑t∂L∂ℓt,q.\frac{\partial\mathcal L}{\partial\ell_{t,q}}=\frac{p_{t,q}-\mathbf1[q=c_t]}T,\quad \frac{\partial\mathcal L}{\partial o_q}=\sum_t s_t\frac{\partial\mathcal L}{\partial\ell_{t,q}},\quad\frac{\partial\mathcal L}{\partial b_q}=\sum_t\frac{\partial\mathcal L}{\partial\ell_{t,q}}.

The skip gradient flows into each gate. If aa and bb are the two preactivations, their local derivatives are:

∂u∂a=σ(b)(1−tanh⁡2a),∂u∂b=tanh⁡(a)σ(b)(1−σ(b)),u=tanh⁡(a)σ(b).\frac{\partial u}{\partial a}=\sigma(b)(1-\tanh^2a),\qquad\frac{\partial u}{\partial b}=\tanh(a)\sigma(b)(1-\sigma(b)),\quad u=\tanh(a)\sigma(b).

For a delayed term, its input gradient goes to the earlier position, not the current one. Residual and skip contributions must both be added before applying the local derivatives. The program carries out these operations explicitly and checks all 49 scalar parameter derivatives using central finite differences.

Train, sample and perturb the history

Use Python 3.12 and NumPy 1.26.4. objective performs a full forward and backward pass. fit updates parameters on 96 samples of a synthetic sine wave with period 8 and peak amplitude 0.7. It uses 250 updates of size 0.08. No audio files, text conditioning or upstream implementation are involved.

sample repeatedly appends a placeholder target, computes the final logit distribution and draws a code. Because the input is shifted, that placeholder cannot leak into its own prediction. Temperature rescales logits; it changes the sampling distribution rather than retraining the model.

"""Original scalar-channel gated causal model, trained on synthetic samples.

Manual gradients cover all parameters. Left-shifted inputs enforce strict past.
Three width-two dilations, residual/skip paths, categorical loss and sampling;
no conditioning stacks, real speech or replication of the full WaveNet model.
"""
import json
import numpy as np


def mu_transform(values,mu=255,inverse=False):
    x=np.asarray(values)
    if x.dtype.kind not in 'fiu' or not 1<=x.size<=2048 or not np.isfinite(x).all() or np.any((x < -1)|(x > 1)) or type(mu) not in (int,float) or not 1<=mu<=255 or type(inverse) is not bool:raise ValueError('Invalid companding values')
    x=x.astype(float)
    return np.sign(x)*(np.expm1(abs(x)*np.log1p(mu))/mu if inverse else np.log1p(mu*abs(x))/np.log1p(mu))


def quantize(values,q=16,mu=255):
    if type(q) is not int or not 2<=q<=256:raise ValueError('Invalid alphabet size')
    z=mu_transform(values,mu)
    return np.floor((z+1)*(q-1)/2+.5).astype(int)


def decode(codes,q=16,mu=255):
    a=np.asarray(codes)
    if type(q) is not int or not 2<=q<=256 or a.dtype.kind not in 'iu' or not 1<=a.size<=2048 or np.any((a<0)|(a>=q)):raise ValueError('Invalid sample codes')
    return mu_transform(2*a.astype(float)/(q-1)-1,mu,inverse=True)


def initialize(q=16,seed=4):
    if type(q) is not int or not 2<=q<=256 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(f=rng.normal(0,.4,(3,2)),g=rng.normal(0,.2,(3,2)),r=np.full(2,.3),s=np.ones(3),o=rng.normal(0,.2,q),b=np.zeros(q))


def validate(codes,parameters):
    if not isinstance(parameters,dict) or set(parameters)!={'f','g','r','s','o','b'}:raise ValueError('Invalid parameter names')
    p={k:np.asarray(v) for k,v in parameters.items()};q=p['o'].size
    shapes=dict(f=(3,2),g=(3,2),r=(2,),s=(3,),o=(q,),b=(q,))
    if not 2<=q<=256 or any(v.shape!=shapes[k] or v.dtype.kind not in 'fiu' or not np.isfinite(v).all() or np.any((v < -16)|(v > 16)) for k,v in p.items()):raise ValueError('Invalid parameter arrays')
    c=np.asarray(codes)
    if c.dtype.kind not in 'iu' or c.ndim!=1 or not 1<=len(c)<=512 or np.any((c<0)|(c>=q)):raise ValueError('Invalid code sequence')
    return c,{k:v.astype(float) for k,v in p.items()}


def delayed(x,d):
    out=np.zeros_like(x)
    if d<len(x):out[d:]=x[:-d]
    return out


def objective(codes,parameters):
    c,p=validate(codes,parameters);n=len(c);q=len(p['o'])
    # Zero at the beginning is a start value in companded space, not code zero.
    h=np.r_[0.,2*c[:-1].astype(float)/(q-1)-1];skip=np.zeros(n);cache=[]
    for layer,d in enumerate((1,2,4)):
        old=h;past=delayed(old,d);f=np.tanh(p['f'][layer,0]*old+p['f'][layer,1]*past)
        logit=p['g'][layer,0]*old+p['g'][layer,1]*past
        gate=np.exp(-np.logaddexp(0,-logit));z=f*gate
        if layer<2:h=old+p['r'][layer]*z
        skip+=p['s'][layer]*z
        cache.append((old,past,f,gate,z))
    logits=skip[:,None]*p['o']+p['b'];shift=logits-logits.max(axis=1,keepdims=True)
    logp=shift-np.log(np.exp(shift).sum(axis=1,keepdims=True));prob=np.exp(logp)
    loss=-float(logp[np.arange(n),c].mean());dl=prob.copy();dl[np.arange(n),c]-=1;dl/=n
    gradient={k:np.zeros_like(v) for k,v in p.items()};gradient['o']=skip@dl;gradient['b']=dl.sum(axis=0)
    ds=dl@p['o'];dh=np.zeros(n)
    for layer in range(2,-1,-1):
        old,past,f,gate,z=cache[layer];d=(1,2,4)[layer]
        if layer<2:gradient['r'][layer]=dh@z
        gradient['s'][layer]=ds@z
        dz=(dh*p['r'][layer] if layer<2 else 0)+ds*p['s'][layer];df=dz*gate*(1-f*f);dg=dz*f*gate*(1-gate)
        gradient['f'][layer]=[df@old,df@past];gradient['g'][layer]=[dg@old,dg@past]
        direct=dh+df*p['f'][layer,0]+dg*p['g'][layer,0]
        lag=df*p['f'][layer,1]+dg*p['g'][layer,1]
        if d<n:direct[:-d]+=lag[d:]
        dh=direct
    return dict(loss=loss,gradient=gradient,probabilities=prob,logits=logits,skip=skip,receptive_field=8)


def fit(codes,steps=250,rate=.08):
    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();history=[]
    for _ in range(steps):
        result=objective(codes,p);history.append(result['loss'])
        p={k:v-rate*result['gradient'][k] for k,v in p.items()}
    history.append(objective(codes,p)['loss'])
    return dict(parameters=p,history=history)


def sample(parameters,count=48,seed=9,temperature=1.):
    if type(count) is not int or not 1<=count<=128 or type(seed) is not int or not 0<=seed<2**32 or type(temperature) not in (int,float) or not .1<=temperature<=4:raise ValueError('Invalid sampling settings')
    rng=np.random.default_rng(seed);codes=[]
    for _ in range(count):
        # The last placeholder is the target; strict shifting prevents leakage.
        logits=objective(codes+[0],parameters)['logits'][-1]/temperature
        weights=np.exp(logits-logits.max());weights/=weights.sum()
        codes.append(int(rng.choice(len(weights),p=weights)))
    return np.array(codes)


def demo():
    x=.7*np.sin(2*np.pi*np.arange(96)/8);codes=quantize(x);learned=fit(codes)
    generated=sample(learned['parameters']);probe=objective(codes,learned['parameters'])
    altered=codes.copy();altered[50]=(altered[50]+3)%16;other=objective(altered,learned['parameters'])
    return dict(q=16,mu=255,steps=250,receptive_field=8,training_history=learned['history'][::10],training_first=learned['history'][0],training_last=learned['history'][-1],
        original=x.tolist(),codes=codes.tolist(),decoded=decode(codes).tolist(),sampled_codes=generated.tolist(),sampled_wave=decode(generated).tolist(),
        causal=dict(changed_input=50,maximum_change_at_or_before=float(np.max(abs(probe['logits'][:51]-other['logits'][:51]))),changed_output_positions=np.flatnonzero(np.max(abs(probe['logits']-other['logits']),axis=1)>1e-12).tolist()),
        parameters={k:v.tolist() for k,v in learned['parameters'].items()})


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

The mean training NLL decreases from about 2.763944 to 1.095498. A uniform 16-class distribution would have NLL log⁡16≈2.772589\log16\approx2.772589, which gives an interpretable baseline. These are training values on one short repeated pattern, not a held-out speech benchmark or a listening-quality score.

The causal probe changes input code 50. Predictions at or before 50 remain identical, while positions 51–58 change. This tests both the left shift and the full eight-position receptive field. Merely checking tensor shapes or observing a falling loss would not catch target leakage.

A forward/backward pass costs O(T(3+Q))O(T(3+Q)) for this scalar model. The simple sampler recomputes the entire prefix at every step, costing O(T2(3+Q))O(T^2(3+Q)) overall; it does not cache convolution states. Training sequences are limited to 512 codes, sampling to 128 outputs, and parameters to finite values within ±16. Those are teaching limits, not WaveNet design constraints.

Sample prediction is not the entire speech task

This small model has no text, speaker or acoustic-feature conditioning. A sample stream from it is therefore not a reading of a sentence. The original paper describes global conditioning vectors and upsampled local conditioning features. Those are information supplied to the generator; waveform causality must be distinguished from whether a conditioning description is already known for the whole utterance. Conditioning, section 2.5

The scalar channels, three layers and linear categorical head simplify the published network. They preserve gates, residual/skip routes and the strict-past prediction task, but do not reproduce its complete architecture or reported quality. Coarse quantization adds distortion, and a low one-step training loss does not by itself ensure stable long generated sequences.

To extend the experiment, first hold out different synthetic patterns and report their likelihood. Then measure generation cost with a stated sample count and hardware. If introducing conditional speech data, separately test pronunciation, conditioning alignment and listening quality. None of those results follows from the 49-parameter fit.

Try to catch a model cheating

  1. A shifted receptive field. With width-two dilations 1, 2, 4 and a one-sample input shift, which original samples can influence prediction 20?

Answer: Samples 12 through 19. The hidden field has length 8, and the shift moves its latest permitted original sample to 19. Including sample 20 would leak the target.

  1. Quantizing silence. For Q=16Q=16 and exact compressed value 0, which code does the stated rule return? Does decoding it return exactly zero?

Answer: It returns 8 because the unrounded coordinate is 7.5 and halves round upward. Its reconstructed compressed value is 1/15, so the expanded waveform value is positive, not exactly zero. This is a consequence of an even-sized endpoint grid.

  1. An unconvincing causal test. A developer changes code 50 and checks only prediction 40. Why is that insufficient?

Answer: A network that improperly sees the current target could still leave prediction 40 unchanged. Check prediction 50 itself and every earlier position, then verify that the intended later neighborhood 51–58 can respond. The test must distinguish the correct dependency from plausible but wrong ones.

  1. Fast training, slow generation. All reference samples are processed together during training. Why can the sampler not generate every new sample in the same way?

Answer: Training already has the reference history. Generation must create that history, and the selected sample changes subsequent conditional inputs. Parallel evaluation of known targets does not remove the serial dependence of ancestral sampling. State caching can reduce repeated computation without erasing this dependence.

Keep the architectural claim separate from the benchmark

The fixed 2016 paper supplies the factorization, dilation, companding, gates and conditioning account. The announcement supplies its dated public introduction. The fixed librosa source illustrates why an encoding convention must be inspected at the actual implementation. We have not reproduced the paper’s listening study or adopted the announcement’s performance-gap claim as independent evidence.

The next useful comparison is a model that predicts acoustic frames rather than waveform samples. Check its sequence length, alignment mechanism and feedback unit before comparing generation speed; “autoregressive” alone does not specify those costs.

Make a prediction, then check

With shifted inputs and width-two dilations1,2,4, which original inputs can affect prediction t?

Choose one answer

Learning objectives

  • Derive the sample likelihood and distinguish training from serial sampling.
  • Compute a shifted dilated network receptive field without target leakage.
  • Differentiate gates, residual paths, skip sums and categorical outputs.
  • Explain quantization conventions and synthetic-training limits.

Prerequisites & connections

Explore related knowledge →

References

  1. WaveNet: A Generative Model for Raw Audio (arXiv v2)
    Aäron van den Oord; Sander Dieleman; Heiga Zen; Karen Simonyan; Oriol Vinyals; Alex Graves; Nal Kalchbrenner; Andrew Senior; Koray Kavukcuoglu · 2016
  2. WaveNet: A generative model for raw audio
    Aäron van den Oord; Sander Dieleman · 2016
  3. librosa mu-law companding atf808bac
    librosa contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked the fixed 2016 architecture, companding versus explicit 16-grid encoding, actual quantized hidden input, strict shift, dilations, gates/residual/skip gradients and serial sampling cost. Eight paired equations, four explained exercises, all49 scalar gradients and actual synthetic training; not full conditioned WaveNet.

  • All49 parameter finite differences, uniform log16 baseline, exact-zero code8 and compressed grid1/15 tested. Input50 changes only logits51–58;250-step NLL2.763944 to1.095498 and seeded ancestral samples computed. Removed unused last residual gain without changing outputs.
  • 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.