AI Wiki中文/EN

Autoregressive models: build a joint distribution without leaking the answer

自回归生成模型

Prove normalization, derive a masked network and test all gradients against a copying counterexample.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Predict a bit before seeing it

Give a network four bits and ask it to reproduce them. If it can see the bit it is predicting, copying the input can make the reconstruction loss very small. That does not make its outputs a probability distribution over four-bit strings. We will build both a valid model and a leaking counterexample, then sum their proposed probabilities over all 16 strings.

An autoregressive generative model chooses an order for the observed coordinates and predicts each from the earlier coordinates. The order can run through time, image pixels or components of a vector; it need not describe a temporal process. The neural network supplies conditional probabilities, while the probability chain rule supplies the joint distribution. Deep Learning describes this as a fully visible directed-model construction. Autoregressive representation

Our complete example uses a single hidden layer with six units and four binary outputs. It follows MADE’s masking principle, includes direct earlier-input connections, and uses dense NumPy operations so every gradient can be checked. It is an original teaching implementation, not a run of the authors’ Theano system. MADE’s construction

Actual masks, normalized joints, training curves and a copying counterexample connect probability rules with neural computation.
Actual masks, normalized joints, training curves and a copying counterexample connect probability rules with neural computation.

Normalized conditionals are the building blocks

A factorization is not an independence claim

Write x<j=(x1,…,xj−1)x_{<j}=(x_1,\ldots,x_{j-1}) for a prefix. For a fixed ordering, the chain rule gives

pθ(x)=∏j=1Dpθ(xj∣x<j).p_\theta(x)=\prod_{j=1}^D p_\theta(x_j\mid x_{<j}).

The first factor has no observed prefix. Every conditional must be a valid distribution for every prefix reached with positive probability. Conditional values on a zero-probability prefix do not change the joint, but a sampler still needs a defined policy there. Mathematically, a sigmoid at a finite logit is strictly between zero and one. Floating-point evaluation can nevertheless round a result to one; the objective below computes log probabilities from logits to avoid taking the logarithm of that rounded endpoint.

No independence assumption is required for the chain rule itself. Restricting a network’s capacity or the part of the prefix it sees can restrict which joint distributions it represents. To verify normalization, sum the last coordinate first, then repeat:

∑x1p(x1)∑x2p(x2∣x1)⋯∑xDp(xD∣x<D)=1.\sum_{x_1}p(x_1)\sum_{x_2}p(x_2\mid x_1)\cdots\sum_{x_D}p(x_D\mid x_{<D})=1.

Each inner conditional sum is one, leaving the previous factor. This argument requires the factor for coordinate jj to depend only on its prefix. An ordinary autoencoder that sees its own target does not satisfy that condition. MADE turns the restriction into a computational-path constraint. MADE, Sections 3–4

Degree labels prevent information leaks

For clarity, separate a physical coordinate index from its position in the chosen order. The code accepts permutation=(2,0,3,1) to mean that physical coordinates 2, 0, 3, 1 are generated in that order. Each physical coordinate jj receives degree djd_j, its one-based position. Hidden unit hh receives degree mhm_h.

The implementation stores row-vector weight matrices: WW is input-to-hidden, VV hidden-to-output, and AA a direct input-to-output connection. Its binary masks are

MihW=1[di≤mh],MhjV=1[mh<dj],MijA=1[di<dj].M^W_{ih}=\mathbf1[d_i\le m_h],\qquad M^V_{hj}=\mathbf1[m_h<d_j],\qquad M^A_{ij}=\mathbf1[d_i<d_j].

For an input to reach an output through a hidden unit, its degree must satisfy di≤mh<djd_i\le m_h<d_j. Therefore it must occur earlier than the output. The direct mask enforces the same strict ordering. The earliest output has no incoming input or hidden connections and depends only on its output bias.

For four coordinates, our hidden degrees are [1,2,3,1,2,3]. In the natural order, 12 entries of WW, 12 of VV and six of AA remain active. Adding six hidden biases and four output biases gives 40 effective parameters. The dense arrays store 74 numbers in total; 34 masked weights cannot affect the output.

The original Theano code uses a single non-strict comparison between layer degrees, but offsets the input degrees by one relative to the output degrees. This implements the strict final restriction rather than violating it. Match indexing conventions before comparing source code with the paper. Fixed author mask implementation

The forward pass and a stable objective

Let X∈RN×DX\in\mathbb R^{N\times D} contain NN binary rows, with D=4D=4, and let the hidden width be H=6H=6. Write Wˉ=W⊙MW\bar W=W\odot M^W, Vˉ=V⊙MV\bar V=V\odot M^V, and Aˉ=A⊙MA\bar A=A\odot M^A. Here ⊙\odot means elementwise multiplication. Biases b∈RHb\in\mathbb R^H and c∈RDc\in\mathbb R^D broadcast across rows. The activations and logits are

Ha=tanh⁡(XWˉ+b),Z=HaVˉ+XAˉ+c.H_a=\tanh(X\bar W+b),\qquad Z=H_a\bar V+X\bar A+c.

Pnj=σ(Znj)P_{nj}=\sigma(Z_{nj}) is the probability that output bit jj is one given its permitted prefix, where σ(z)=1/(1+e−z)\sigma(z)=1/(1+e^{-z}). For nonnegative row weights wnw_n summing to one, define the mean per-vector negative log-likelihood

J=∑n=1Nwn∑j=1D[softplus⁡(Znj)−XnjZnj],softplus⁡(z)=log⁡(1+ez).J=\sum_{n=1}^Nw_n\sum_{j=1}^D[\operatorname{softplus}(Z_{nj})-X_{nj}Z_{nj}],\qquad\operatorname{softplus}(z)=\log(1+e^z).

The scalar identity softplus⁡(z)−xz\operatorname{softplus}(z)-xz equals the binary negative log-likelihood for x∈{0,1}x\in\{0,1\}. Computing softplus with logaddexp(0,z) avoids taking the logarithm of a rounded zero probability. This objective sums over coordinates; it is not divided by DD. The author implementation also uses a stable softplus expression for the binary log probabilities. MADE likelihood definition

For a minibatch, one can use wn=1/Nw_n=1/N. Our experiment instead enumerates all 16 states and uses their exact target probabilities as weights. Thus it optimizes a known population objective, without claiming a held-out generalization result.

Every gradient, including masked zeros

Let Enj=wn(Pnj−Xnj)E_{nj}=w_n(P_{nj}-X_{nj}). With HaH_a denoting the hidden activation matrix in the forward equation, the output-side gradients are

∇VJ=(Ha⊤E)⊙MV,∇AJ=(X⊤E)⊙MA,∇cJ=∑nEn,:.\nabla_VJ=(H_a^\top E)\odot M^V,\qquad\nabla_AJ=(X^\top E)\odot M^A,\qquad\nabla_cJ=\sum_n E_{n,:}.

Propagating through tanh gives B=(EVˉ⊤)⊙(1−Ha2)B=(E\bar V^\top)\odot(1-H_a^2). The remaining gradients are

B=(EVˉ⊤)⊙(1−Ha2),∇WJ=(X⊤B)⊙MW,∇bJ=∑nBn,:.B=(E\bar V^\top)\odot(1-H_a^2),\qquad\nabla_WJ=(X^\top B)\odot M^W,\qquad\nabla_bJ=\sum_n B_{n,:}.

The final mask multiplications follow from differentiating W⊙MWW\odot M^W and the corresponding other matrices. They make masked-weight derivatives exactly zero. A test perturbs every stored parameter, including those zeros, and compares all 74 analytic derivatives with central differences. The tests also replace masked weights with large values and verify that the output stays unchanged. See gradient checking for the numerical method’s limitations.

Probability evaluation and generation have different schedules

When a complete vector is available, the masked network computes all its conditionals in one forward pass. The mask makes seeing the full array safe because forbidden entries have no path to an output.

To generate a fresh vector, initialize an array and visit coordinates in the chosen order. Compute the next Bernoulli probability, draw that bit, store it, and continue. Unfilled values may be zeros because valid masks prevent earlier predictions from depending on them. Our code evaluates the whole network again at every step; it is deliberately easy to inspect.

For a batch of NN vectors, the dense forward computation costs roughly O(NDH+ND2)O(NDH+ND^2). The mask does not turn dense matrix multiplication into sparse computation automatically. Recomputing the full network DD times gives roughly O(ND2H+ND3)O(ND^2H+ND^3) generation work here. Calling the shared objective also calculates gradients that sampling does not need; this program is unsuitable for hardware-speed comparisons.

NADE illustrates a different reuse strategy. Its hidden preactivation can be updated incrementally after each observed bit:

a1=ch,aj+1=aj+W:,jxj,hj=σ(aj).a_1=c_h,\qquad a_{j+1}=a_j+W_{:,j}x_j,\qquad h_j=\sigma(a_j).

Here aja_j is an HH-dimensional hidden preactivation, chc_h its initial bias, and W:,jW_{:,j} the input column for bit jj. Computing one update and its conditional costs O(H)O(H), giving O(DH)O(DH) for the full vector in this particular architecture. It is not a complexity claim for every autoregressive network. NADE method and Algorithm 1

Order changes a parameterized model

We train on a four-bit Markov target: the first bit is fair and each subsequent bit copies its predecessor with probability 0.9. For all 16 states,

P∗(x)=12∏j=240.91[xj=xj−1]0.11[xj≠xj−1].P_*(x)=\frac12\prod_{j=2}^{4}0.9^{\mathbf1[x_j=x_{j-1}]}0.1^{\mathbf1[x_j\ne x_{j-1}]}.

This target is normalized and has full support. A chain-rule representation can express the same true joint in different orders if the correct conditionals are used. Reusing a fixed set of learned weights with different masks does not generally produce those correct conditionals. Our reversed-order model still normalizes, but its probabilities differ from the trained-order model. MADE’s discussion also distinguishes the models obtained from different orderings; their probability average can form an ensemble. MADE, Section 4.2

A copying network fails the sum test

Construct an intentionally invalid model whose logit sees its own bit: zj=κ(2xj−1)z_j=\kappa(2x_j-1). Both zero and one targets then receive assigned probability σ(κ)\sigma(\kappa). Its proposed joint score and total mass are

q~(x)=σ(κ)D,∑x∈{0,1}Dq~(x)=[2σ(κ)]D.\widetilde q(x)=\sigma(\kappa)^D,\qquad\sum_{x\in\{0,1\}^D}\widetilde q(x)=[2\sigma(\kappa)]^D.

With D=4D=4 and κ=4\kappa=4, the per-vector reconstruction NLL is less than 0.08, but the score sum exceeds 14. The problem is not numerical rounding: the target itself influenced the factor that was supposed to predict it.

Check all 16 strings

Save the complete program as autoregressive.py. It runs with Python 3.12 and NumPy 1.26.4, needs no downloaded data or upstream framework, and prints deterministic reference quantities plus a seeded sampling histogram.

"""Original one-hidden-layer binary MADE teaching model; dense masked NumPy."""
import itertools,json
import numpy as np
D=4;H=6

def binary(x):
    a=np.asarray(x)
    if a.dtype.kind not in 'fiu' or a.ndim!=2 or a.shape[1]!=D or not 1<=len(a)<=20000 or not np.isfinite(a).all() or np.any((a!=0)&(a!=1)):raise ValueError('Use a nonempty batch of four-bit rows')
    return a.astype(float)

def order(value):
    a=np.asarray(value)
    if a.dtype.kind not in 'iu' or a.shape!=(D,) or set(a.tolist())!=set(range(D)):raise ValueError('Use a permutation of the four physical coordinate indices')
    return a.astype(int)

def masks(permutation=(0,1,2,3)):
    sequence=order(permutation);degree=np.empty(D,int);degree[sequence]=np.arange(1,D+1);hidden=np.tile(np.arange(1,D),2)
    return {'w':degree[:,None]<=hidden,'v':hidden[:,None]<degree,'a':degree[:,None]<degree},degree,hidden

def initialize(seed=11):
    if type(seed) is not int or not 0<=seed<2**32:raise ValueError('Invalid seed')
    rng=np.random.default_rng(seed)
    return dict(w=rng.normal(0,.2,(D,H)),v=rng.normal(0,.2,(H,D)),a=np.zeros((D,D)),b=np.zeros(H),c=np.zeros(D))

def parameters(p):
    shapes=dict(w=(D,H),v=(H,D),a=(D,D),b=(H,),c=(D,));result={}
    if not isinstance(p,dict) or set(p)!=set(shapes):raise ValueError('Invalid parameter keys')
    for k,shape in shapes.items():
        a=np.asarray(p[k])
        if a.dtype.kind not in 'fiu' or a.shape!=shape or not np.isfinite(a).all() or np.any((a< -20)|(a>20)):raise ValueError('Invalid bounded parameter array')
        result[k]=a.astype(float)
    return result

def objective(x,p,weights=None,permutation=(0,1,2,3)):
    x=binary(x);p=parameters(p);mask,degree,hidden=masks(permutation)
    if weights is None:weights=np.full(len(x),1/len(x))
    weights=np.asarray(weights)
    if weights.dtype.kind not in 'fiu' or weights.shape!=(len(x),) or not np.isfinite(weights).all() or np.any(weights<0) or not np.isclose(weights.sum(),1,rtol=0,atol=1e-12):raise ValueError('Invalid normalized row weights')
    w=p['w']*mask['w'];v=p['v']*mask['v'];a=p['a']*mask['a'];h=np.tanh(x@w+p['b']);z=h@v+x@a+p['c']
    prob=np.exp(-np.logaddexp(0,-z));losses=np.sum(np.logaddexp(0,z)-x*z,axis=1);dz=(prob-x)*weights[:,None]
    dh=(dz@v.T)*(1-h*h)
    grad=dict(w=(x.T@dh)*mask['w'],v=(h.T@dz)*mask['v'],a=(x.T@dz)*mask['a'],b=dh.sum(axis=0),c=dz.sum(axis=0))
    return dict(loss=float(weights@losses),log_joint=-losses,probabilities=prob,gradient=grad)

def all_states():return np.array(list(itertools.product([0,1],repeat=D)),float)

def target():
    x=all_states();return .5*np.prod(np.where(x[:,1:]==x[:,:-1],.9,.1),axis=1)

def fit(steps=500,rate=.25,permutation=(0,1,2,3)):
    if type(steps) is not int or not 0<=steps<=1000 or type(rate) not in (int,float) or not 0<rate<=.5:raise ValueError('Invalid training settings')
    p=initialize();x=all_states();weight=target();history=[]
    for i in range(steps+1):
        r=objective(x,p,weight,permutation);history.append(r['loss'])
        if i<steps:p={k:v-rate*r['gradient'][k] for k,v in p.items()}
    return dict(parameters=p,history=history)

def sample(p,count=4000,seed=7,permutation=(0,1,2,3)):
    sequence=order(permutation);parameters(p)
    if type(count) is not int or not 1<=count<=20000 or type(seed) is not int or not 0<=seed<2**32:raise ValueError('Invalid sampling bounds')
    x=np.zeros((count,D));rng=np.random.default_rng(seed)
    for j in sequence:
        prob=objective(x,p,permutation=sequence)['probabilities'][:,j]
        x[:,j]=rng.random(count)<prob
    return x

def leaky_identity(k=4.):
    if type(k) not in (int,float) or not 0<=k<=20:raise ValueError('Invalid identity strength')
    x=all_states();z=k*(2*x-1);score=np.exp(-np.sum(np.logaddexp(0,z)-x*z,axis=1))
    return dict(scores=score,total=float(score.sum()),per_row_reconstruction_nll=float(-np.log(score[0])))

def clean(x):
    if isinstance(x,dict):return {k:clean(v) for k,v in x.items()}
    if isinstance(x,(list,tuple)):return [clean(v) for v in x]
    if isinstance(x,np.ndarray):return x.tolist()
    if isinstance(x,np.generic):return x.item()
    return x

def demo():
    trained=fit();p=trained['parameters'];x=all_states();r=objective(x,p);q=np.exp(r['log_joint']);samples=sample(p);ids=(samples@np.array([8,4,2,1])).astype(int);mask,degree,hidden=masks()
    changed=x.copy();changed[:,2:]=1-changed[:,2:];other=objective(changed,p)
    reversed_order=(3,2,1,0);reversed_q=np.exp(objective(x,p,permutation=reversed_order)['log_joint'])
    return clean(dict(states=x,target=target(),distribution=q,total=q.sum(),training=dict(first=trained['history'][0],last=trained['history'][-1],history=trained['history'][::10]),parameters=p,parameter_count=sum(v.size for v in p.values()),active_weights={k:int(v.sum()) for k,v in mask.items()},masks=mask,degrees=degree,hidden_degrees=hidden,probabilities=r['probabilities'],causal_error=float(abs(r['probabilities'][:,:3]-other['probabilities'][:,:3]).max()),sampled=np.bincount(ids,minlength=16)/len(ids),samples_first=samples[:8],reversed_distribution=reversed_q,reversed_total=reversed_q.sum(),leaky=leaky_identity(),scope='Exact four-bit Markov target; same-distribution training, dense masked tanh MADE with direct connections. Reversed order reuses weights without retraining; no image or language benchmark.'))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

The default 500-step fit, with step size 0.25, reduces the exact target-weighted NLL from approximately 2.7721573 to 1.6702761. The trained distribution sums to one. Flipping input coordinate 2 and later coordinates leaves predictions through coordinate 2 unchanged; the target value at coordinate 2 is not visible to its own predictor.

The program samples 4,000 vectors using seed seven. The histogram fluctuates around the exact 16-state joint and should be compared with it, not substituted for it. Changing the ordering preserves normalization but changes the distribution when weights are reused without retraining. There is no image, speech or language benchmark in this experiment.

All 74 stored parameters are constrained to finite values between −20 and 20. The input validator requires binary rows with four entries and an actual permutation. These bounds support stable, inspectable tests; they do not define the complete family of MADE architectures.

What the factorization leaves unresolved

The chain rule solves normalization through conditional factors. It does not select a useful ordering, guarantee enough model capacity, make sequential sampling cheap, or establish that training data cover the intended task. An unconditional four-bit model says nothing about how a prompted language system should be evaluated.

The earliest variable is modeled with a bias-only marginal in this network. Adding capacity to later predictors cannot repair a mistaken data representation or a mismatched target. For larger problems, compare a simple marginal or low-order conditional baseline, then inspect the benefit of richer context and the cost of generating it.

The original NADE PDF contains a cautionary example for implementation from papers. Algorithm 1 on printed page 32 initializes the joint accumulator to zero and prints an addition between the two Bernoulli power terms. These printed steps conflict with the probability product definition and the NLL equation on that page. We verified the page image and use a unit-initialized product of Bernoulli factors. This is a local consistency finding, not a claim that the NADE method is invalid or that the authors published an erratum. Printed algorithm and objective

For uniform four-bit conditionals, the correct total joint mass is one. Starting a product at zero gives zero. Changing only that initialization while keeping the printed addition gives total mass 34=813^4=81. This independent small check makes the discrepancy concrete before it reaches a larger implementation.

Find the forbidden path

  1. Boundary of the output mask. Input degree is 2 and hidden degree is 2. Can that hidden unit predict output degree 2? Can it predict output degree 3?

Answer: The input-to-hidden connection is allowed because 2≤22\le2. Output degree 2 is forbidden because the final condition is strict: 2<22<2 is false. Output degree 3 is allowed because 2<32<3. Using a non-strict final comparison would allow a path from a variable to its own prediction unless degrees were offset consistently.

  1. How many parameters learn? The model stores 24 input-hidden weights, 24 hidden-output weights, 16 direct weights and ten biases. Why do all 74 gradient checks not imply 74 effective parameters?

Answer: Only 12, 12 and six weights survive their masks, plus all ten biases: 40 effective parameters. The other 34 checks verify zero derivatives. Changing a masked array entry cannot change the computed distribution.

  1. A suspiciously low reconstruction loss. Derive the score sum for the copying counterexample with four bits and κ=4\kappa=4. Why is a small loss insufficient?

Answer: Every target bit receives σ(4)\sigma(4), so each string has score σ(4)4\sigma(4)^4. There are 16 strings, giving [2σ(4)]4>14[2\sigma(4)]^4>14. The low reconstruction loss rewards access to the target; it does not validate a normalized joint model.

  1. Change the order. If the same weights are evaluated with the order [3,2,1,0], must the total mass remain one? Must every string retain its previous probability?

Answer: The total remains one because the rebuilt masks enforce valid conditionals in the new order. Individual probabilities need not match: the weights were trained under another set of prefixes. Equality would require the appropriate conditionals for the same joint, not merely a new permutation of masks.

Follow normalization through implementations

NADE emphasizes sharing computations across conditional predictors. MADE packages the no-future-information rule into masks, making all conditionals available together for a known vector. Both connect the probability chain rule to a trainable neural architecture, while choosing different computational structures. Their publication years are 2011 and 2015 respectively; precise conference dates and website metadata timestamps should not be conflated.

The fixed MADE source uses Theano and provides normalization and input-flip checks. We read those portions to compare conventions, implemented the example independently, and ran no upstream scripts. No license file was found in the inspected fixed repository tree, so public readability was not treated as permission to copy its code. The source references support the described mechanisms; the complete derivation, counterexamples and NumPy program here are original teaching work.

Make a prediction, then check

Can a copying network have low reconstruction loss but fail to define a joint probability?

Choose one answer

Learning objectives

  • Prove normalization by summing conditional factors in reverse order.
  • Map variable ordering to strict output masks and forbidden paths.
  • Derive masked-network gradients, including zero derivatives.
  • Compare parallel likelihood evaluation with sequential sampling and order changes.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning, Chapter 20: distribution representations and autoregressive networks
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. MADE: Masked Autoencoder for Distribution Estimation
    Mathieu Germain; Karol Gregor; Iain Murray; Hugo Larochelle · 2015
  3. The Neural Autoregressive Distribution Estimator
    Hugo Larochelle; Iain Murray · 2011
  4. MADE author implementation: degree offsets and masks at514849e
    Mathieu Germain and contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked scoped NADE2011, MADE2015 and fixed author masks. Ten paired equations, four explained exercises; normalization proof, strict degree masks, stable objective and all74 stored derivatives (40 effective parameters). Exact four-bit target, order changes and leakage tests; no media-model benchmark or independent human review.

  • Verified all74 stored gradients including34 masked zeros,24 order normalizations, all-coordinate causal flips, sequential product oracle,500-step exact-target training, copying mass above14 and finite logit loss despite sigmoid rounding.
  • Four computed SVGs bind exact bilingual MDX. The two-topic group passed11 numeric/encoding checks and12 isolated language/width cases with four fallback fonts; four representative final screenshots inspected by the AI author. English mobile title overflow corrected with original figures and failed browser evidence preserved. 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.