Autoregressive models: build a joint distribution without leaking the answer
自回归生成模型
Prove normalization, derive a masked network and test all gradients against a copying counterexample.
autoregressive-modelsPredict 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
Normalized conditionals are the building blocks
A factorization is not an independence claim
Write for a prefix. For a fixed ordering, the chain rule gives
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:
Each inner conditional sum is one, leaving the previous factor. This argument requires the factor for coordinate 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 receives degree , its one-based position. Hidden unit receives degree .
The implementation stores row-vector weight matrices: is input-to-hidden, hidden-to-output, and a direct input-to-output connection. Its binary masks are
For an input to reach an output through a hidden unit, its degree must satisfy . 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 , 12 of and six of 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 contain binary rows, with , and let the hidden width be . Write , , and . Here means elementwise multiplication. Biases and broadcast across rows. The activations and logits are
is the probability that output bit is one given its permitted prefix, where . For nonnegative row weights summing to one, define the mean per-vector negative log-likelihood
The scalar identity equals the binary negative log-likelihood for . 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 . The author implementation also uses a stable softplus expression for the binary log probabilities. MADE likelihood definition
For a minibatch, one can use . 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 . With denoting the hidden activation matrix in the forward equation, the output-side gradients are
Propagating through tanh gives . The remaining gradients are
The final mask multiplications follow from differentiating 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 vectors, the dense forward computation costs roughly . The mask does not turn dense matrix multiplication into sparse computation automatically. Recomputing the full network times gives roughly 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:
Here is an -dimensional hidden preactivation, its initial bias, and the input column for bit . Computing one update and its conditional costs , giving 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,
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: . Both zero and one targets then receive assigned probability . Its proposed joint score and total mass are
With and , 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 . This independent small check makes the discrepancy concrete before it reaches a larger implementation.
Find the forbidden path
- 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 . Output degree 2 is forbidden because the final condition is strict: is false. Output degree 3 is allowed because . Using a non-strict final comparison would allow a path from a variable to its own prediction unless degrees were offset consistently.
- 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.
- A suspiciously low reconstruction loss. Derive the score sum for the copying counterexample with four bits and . Why is a small loss insufficient?
Answer: Every target bit receives , so each string has score . There are 16 strings, giving . The low reconstruction loss rewards access to the target; it does not validate a normalized joint model.
- 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?
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
- Deep Learning, Chapter 20: distribution representations and autoregressive networks
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - MADE: Masked Autoencoder for Distribution Estimation
Mathieu Germain; Karol Gregor; Iain Murray; Hugo Larochelle · 2015 - The Neural Autoregressive Distribution Estimator
Hugo Larochelle; Iain Murray · 2011 - 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:
- Deep Learning, Chapter 20: distribution representations and autoregressive networks · Read chapter opening, Section20.10 introduction and20.10.7; current HTML is not a historical cutoff snapshot. Not the full chapter or its figures.
- MADE: Masked Autoencoder for Distribution Estimation · Read Section3 factorization/loss, Section4 masks/direct connections/path proof, early4.1 and4.2 order distinctions; inspected PDF page3. No full architecture experiments or speed replication.
- The Neural Autoregressive Distribution Estimator · Read method Equations9–11, shared updates, complexity and separate output weights on PDF pages3–4; inspected page4/printed32. Algorithm1 zero initialization and additive Bernoulli terms conflict with the product definition; no author erratum claimed.
- MADE author implementation: degree offsets and masks at514849e · Read input/output degree initialization/reset and mask comparison, particularly lines19–32 and87–97. Commit2020-07-20; fixed tree lacks a license file. No source copying or upstream execution.
Related topics