Learning to Execute
Paper · 2014 · Wojciech Zaremba and Ilya Sutskever
Summary
The answer to a short program can depend on a value assigned near the beginning, a comparison made much later, and an arithmetic operation that combines the two. Learning to Execute asks how much of this behavior a neural network can learn from examples. The authors supply the characters of a program and the characters of the integer it prints. The network has to learn which symbols denote operations, how a name connects an assignment to a later use, and how the result of an inner calculation affects the expression around it. The examples use Python syntax and include arithmetic, assignments, conditionals, and bounded loops. Each program runs without external input.
The reader is a recurrent network built with Long Short-Term Memory units, or LSTMs. A recurrent network updates an internal state as it moves through a sequence. LSTM memory cells give it a way to preserve parts of that state while new characters arrive. The authors choose programs that can be evaluated in a single pass with a fixed amount of memory and computation that grows linearly with the source length. An example can still demand several kinds of work within those bounds. The network has to retain useful values until they matter, infer how operations fit together, and decide which characters to emit, including the mark that ends the answer.
The training schedule made a substantial difference. Training entirely at the target difficulty was hard, and starting with easy examples and advancing in stages could yield even worse results. The authors combined stage-by-stage progression with a stream that sampled across the full difficulty range. This combined curriculum led the program-evaluation comparisons in every reported configuration. On a separate addition task, it reached 99% character accuracy at length 9, the paper’s headline setting for adding two 9-digit numbers. A copying task supplied a different test of memory. The strongest input presentation there both reversed and repeated the digit string, while keeping the desired answer in its original order. Mixing difficulties throughout training was enough to outperform the combined curriculum in some copying settings.
The accuracy figures come from teacher forcing. At each output position, the network gets the correct answer characters that precede it, even if its own earlier guess was wrong. A high score under that protocol tells us how often it predicts a character correctly with this support. The probability of producing an exact answer independently remains unmeasured. The authors also distinguish accurate predictions from a verified execution procedure. Separate training and test examples show that the network can handle new instances from the same generator. How it computes those answers, how much it relies on memorized numerical patterns, and how it would fare on substantially different examples remain open.
Deep dive: Learning to Execute
Learning to Execute tests whether a recurrent network can predict what short Python programs print and how a mixture of easy and hard examples helps. · about 41 minutes to read
The problem and its context
From source characters to a numerical result
The paper situates a question about reasoning within code and programming languages. A program specifies a result through a sequence of operations whose meaning depends on their arrangement. An assignment can supply a value for a later expression. A comparison can determine which branch of a conditional contributes to the answer. Parentheses can indicate that a subtraction has to supply an operand for multiplication. Predicting the printed result requires the reader to use these relationships across the source.
The same characters can play different roles over the course of a program. Digits can form an ordinary value, a small multiplier, or a loop bound. A variable name can appear when its value is set and again when the value is read. Even a short stretch of text can contain a value that should be remembered and a comparison whose outcome determines whether that value will matter. The authors are interested in how much of this behavior can emerge when training supplies whole programs paired with their results.
There is little room for ambiguity about the target. The generated programs finish by printing an integer. A discrepancy between the target and a prediction can be measured directly. The ambiguity lies in how to interpret success. A network that typically predicts the correct digit might learn much of the intended operation, exploit a limited set of patterns that recur in the examples, or use a mixture of those approaches. Those possibilities make program evaluation a test of what the network can learn and a question about what counts as evidence for learning a procedure.
The character representation removes several conveniences a programmer takes for granted. A person recognizes a multi-digit numeral as a unit and reads symbols such as a plus sign in light of rules learned elsewhere. Here, each symbol is encountered as a member of an alphabet. The paper illustrates the point by scrambling the characters in an example. A consistent substitution makes the program unfamiliar to a human reader while preserving the regularities the network can learn across examples. The illustration concerns what the network is given at the start. The significance of the symbols has to come from their use in the data.
What earlier neural approaches supplied to the learner
The authors describe prior work on symbolic arithmetic and logical formulas using recursive neural networks. A tree gives such a network a way to process the parts of an expression according to their structural relationships. An inner expression can be represented at a node and combined with other information higher in the tree. That organization suits a problem in which the result of a component operation becomes an input to another operation, as in the work on recursive networks for logical semantics.
Programs offer a broader setting for that problem. The paper points out that a program can carry out the evaluation of an arithmetic or logical expression. It can also introduce assignments, conditional choices, and iteration. The experiments retain a small collection of such operations and give the network the source in linear order. The organization visible in a parse tree, which groups symbols into expressions and statements, has to be handled through the recurrent state as the characters arrive.
The related work on program text had also used parse trees. One study sought to learn a distribution over source code. Another asked a network to judge program equivalence. In the authors’ account, both approaches started from a structural representation of the program. Learning to Execute changes the target to the result of running the program and starts from a string. That combination matters to the research question. Supplying a tree would already tell the learner which characters belong to an expression and where that expression sits in a larger computation.
The character input also changes the role of a variable dependency. A structural representation can tell a reader that a group of symbols is an assignment or an expression that uses a variable. A recurrent reader encounters these clues in sequence. It must preserve information from the definition until a later occurrence makes the information relevant. That interval motivates the choice of an architecture designed to handle long dependencies.
Why sequence learning and memory belong together
The immediate methodological precedent is Sequence to Sequence Learning with Neural Networks. A sequence-to-sequence task takes an ordered input and produces an ordered answer. The sequences can have different lengths and need no simple position-by-position correspondence. Here the source characters form the input, and the characters needed to write the integer form the output. A digit near the start of the answer might depend on events scattered across the program.
The paper mentions several applications in which recurrent processing was already useful. Its examples include machine translation, where a sequence in one language is related to a sequence in another, and speech and handwriting recognition. For translation it cites Learning Phrase Representations using RNN Encoder–Decoder. The connection is the learned passage from one sequence to another through an internal representation. The program experiments use this framework with a target determined by a computation.
The LSTM is one way to carry useful information from early in a sequence to later steps. Its memory update can preserve an old value and add new information to it. This gives learning a means of storing something through intervening characters while other parts of the state change. The paper acknowledges other recurrent approaches to long dependencies, including A Clockwork RNN. Its experiments concentrate on the behavior of the chosen LSTM architecture.
An architecture that can preserve information still has to learn what to preserve. A training set full of large numbers and deeply composed expressions asks the network to discover symbol meanings, numerical relationships, and useful ways to store intermediate values at the same time. The compositional structure of programs suggests a possible training order. Individual operations can appear in easy examples before the learner is asked to deal with more demanding combinations.
Earlier curriculum learning, as described by the authors, already used a progression through manageable examples. The generator makes that proposal testable because numerical size and structural complexity can be varied separately. The resulting experimental question concerns the whole training distribution. A curriculum can determine which simple cases are prominent now, which demanding cases appear early, and when the emphasis moves. Each of those choices can affect the state learned by the time the network reaches the intended task.
The method, step by step
Generate a program and pair it with its answer
The training example begins with a short program drawn from a restricted family. The generator controls how large the numbers can be and how frequently operations may be composed. The program provides the input characters, and the integer from its final print statement provides the target sequence. The curriculum governs which settings the generator uses for drawing training examples.
From generated programs to character predictions
The steps in order.
The operation set includes addition, subtraction, multiplication, variable assignment, conditional expressions, and for loops. A loop can update a value and leave that value available for a later statement. Separate loops can appear successively, while loops inside other loops are excluded. A program has no external data to read and supplies its result through its final print statement. These restrictions give each source string a definite target and define the computational scope of the experiment.
The intended runtime bound is:
O(n)
Here, n refers to the size of the program and O describes the order of an upper bound on how the required time grows. A linear bound allows computational work proportional to the source size as the source grows. The other resource restriction is constant memory with respect to source size. The network’s state has a fixed width, and reading a longer string gives it more updates of that state. The recurrent reader therefore motivates the choice of a subclass that admits an evaluation with those resources.
That rationale explains the treatment of multiplication and iteration. General multiplication of integers raises a computational demand that the authors describe as superlinear. A single restricted factor makes the generated multiplication problems more manageable. A loop range is bounded for a related reason. The paper observes that nested loops can express multiplication and excludes them when defining the family. The source can thus contain recognizable control flow within limits chosen for a one-pass reader.
The supplementary description gives another generator property. It rules out dead code, so the family is constructed to avoid computations that have no effect on the result. The example programs still contain alternatives in their conditional expressions. Choosing the value of a conditional is part of the intended computation. The generator property addresses how the examples are assembled, while the answer still depends on the semantics of the executed statements and expressions.
Set numerical scale and structural depth
The parameter called length controls the scale of the ordinary integers in a program. Their sampling interval is written as follows:
[1, 10ˡᵉⁿᵍᵗʰ]
The square brackets delimit the interval. Its lower endpoint is 1, and its upper endpoint is 10 raised to the power given by length. The superscript spells out that parameter. The paper says that the integers are drawn uniformly from the specified interval. It describes length in terms of digits, and the interval and examples clarify that this is a setting for numerical scale. A draw can have fewer visible digits than the value of the setting.
The second parameter, nesting, controls how many times operations may be combined. Raising it permits a program with a deeper parse tree. The surface effect can be an arithmetic expression inside another arithmetic expression, a comparison whose operands require computation, or a selected branch whose value is then used in a larger expression. Some programs combine expressions with earlier statements so that a value computed on one line is needed farther along in the source.
The supplementary material makes the difference between the parameters concrete. At length 4 and nesting 1, there are examples that print a literal value, examples that subtract, and examples that perform an assignment before printing a calculation with the assigned value. The programs at length 4 and nesting 3 include a sequence of loop updates in which values are passed from one variable to another, as well as expressions that use a conditional result inside arithmetic. Examples at length 6 include literal printing at shallow nesting and, at deeper nesting, arithmetic that draws on several earlier assignments. The generator settings describe the kinds of example that can occur, so an individual program can exercise only part of the structure permitted by its setting.
A separate interval applies to a multiplication operand and to the loop range:
[1, 4 · length]
The brackets again delimit the interval. The lower endpoint is 1. At the upper endpoint, the centered dot denotes multiplication of 4 by the length parameter. The generator makes a uniform draw from this smaller range for one of the operands of a multiplication and for the range of a loop. The other multiplication operand can still involve a larger value or the result of an expression. A program can consequently require the network to combine numerical information on different scales.
Numerical and structural difficulty can interact. A long numeral adds characters and can increase the amount of information needed to retain its value. A deeper expression can require a value to remain available across more operations. A conditional that embeds arithmetic may also require carrying enough information about the alternatives and comparison to select the right result. The two settings give the experiments a way to control these aspects of difficulty even though either setting can affect both the source length and the work of retaining information.
Turn the result into a sequence
The source enters the network a character at a time. Spaces, punctuation, letters, and digits arrive as parts of a string. The network has no supplied table that says which characters form an assignment or which operations govern a group of operands. When the source includes a variable and a later reference to it, the connection has to be reflected in the state updates learned from examples.
The target uses decimal digits and, when needed, a minus sign. A dot marks termination. The mark is itself a prediction target, so the reader has to learn when the integer is complete as well as which digits it contains. Program evaluation uses an output alphabet of 12 possible characters, including 10 digits. This alphabet is also the basis for the paper’s simple guessing comparison.
Consider a supplementary example in which the program first assigns a value to a variable and later prints a subtraction involving that variable. Its answer depends on recognizing the name at both occurrences, preserving information about the assigned numeral, and handling the order of the operands. A bounded loop adds a different coupling. The state has to make use of the loop count and update expression when predicting the value printed after the loop. The architecture has a uniform update for each input character. The authors train it on the resulting integer instead of supervising the separate operations along the way.
Use addition and copying to focus the task
The paper separates addition from program evaluation because a single accuracy score for a collection of programs can be hard to interpret. A shallow subtraction, a branch, and a calculation across assignments can all contribute to an aggregate score. An addition task has a familiar, specific target and gives the authors a way to observe what happens as the operands grow.
Each addition example uses two integers drawn uniformly from the interval defined by length. The authors describe the operands as having the same length, and both draws use the same length setting. The supplementary source examples also show some numerals written with fewer digits than others from the same setting, as the stated interval allows. The design focuses on adding operands at a shared numerical scale. The authors’ motivation for the same-length setup is to simplify the alignment problem posed by addition with variable lengths.
Even with a shared scale, the answer digits depend on several relations. The input contains the operand strings in sequence, so information from the earlier operand has to remain available while the later one arrives. The operation can generate carries, which affect the result beyond the position where they arise. The network receives the source characters of the addition example, then predicts the answer characters. It is trained from the sum and receives no intermediate carry labels.
Copying focuses the study on retaining a sequence. A random digit string is read completely before reconstruction begins. An answer matches the original order of the digits. The paper illustrates the task with 123,456,789, which is both the unmodified input and the desired output. Information needed to reconstruct the answer has to survive the transition from reading to answering in the network’s state.
For reversal, the input in that illustration becomes 987,654,321 and the target remains 123,456,789. The operation changes where corresponding input and output characters occur relative to one another. The earliest answer characters correspond to digits encountered near the end of reading. Although the authors say the average distance to a corresponding character stays the same, some dependencies become shorter. Short dependencies can offer an easier starting point for learning the mapping.
For doubling, the input contains the same string twice, with a separator between the copies in the illustration. Prediction begins after the repeated input has been read, and the desired answer still contains just the original string. The difference between the usual and doubled cases can be expressed using the two conditional distributions in the paper:
p(y | x)
The symbol p denotes a probability distribution over answers. Here x is the input string, y is the target string, and the vertical bar indicates conditioning on x. The parentheses enclose the target and its conditioning information.
p(y | x, x)
The symbols p, y, and x have the same meanings. The comma separates the two presentations of x. Since both presentations carry the same sequence, the second gives the recurrent network more processing steps over the same information. The authors suggest that these steps may enable it to fill gaps or revise an imperfect state formed during the first presentation. Copying also tests the presentation that uses both reversal and doubling.
Choose the difficulty of training examples
The experiments compare four strategies. In each one, a particular target setting defines the program task of interest. The authors use a for the target value of length and b for the target value of nesting. The training strategies differ in whether every example comes from that setting, the generator moves through earlier settings in stages, or the generator draws from several settings during a stage.
In the baseline, every training example uses a and b. The validation and test examples at the target difficulty pose the same kind of problem as training. This is the natural comparison when the aim is to match training examples to the task that will be evaluated. Learning starts immediately with the full numerical and compositional demands of that configuration.
The naive curriculum begins with length and nesting both at 1. It increases length by 1 when learning stops improving on the validation set. After length reaches a, the progression advances nesting and resets length to 1. The validation criterion controls when the schedule moves, so the paper describes progression by observed learning rather than assigning a fixed duration to each possible setting. The reported experiments use this length-first order. The authors also considered advancing nesting first.
The mixed strategy chooses each example’s numerical setting from this interval:
[1, a]
The square brackets give the range of allowed length settings. The lower endpoint is 1, and a is the target length, so the draw can select a setting up to and including the intended difficulty for numerical scale.
It independently selects the structural setting from:
[1, b]
The brackets now give the range of nesting settings, from 1 through the target nesting b. Independence means that choosing one numerical setting imposes no corresponding choice of nesting. A case can therefore combine shallow structure with numbers drawn at a large scale or deep structure with numbers drawn at a small scale. The training stream exposes the network to different demands throughout training.
The combined strategy uses examples drawn through the current curriculum stage alongside examples drawn through the mixed strategy. The staged part changes as learning progresses. The mixed part keeps sampling across the target range, which brings in some demanding cases even early in training. The paper describes the two sources of examples without specifying a numerical mixing proportion. The substantive distinction from the naive curriculum is that an early focus on easier work coexists with exposure to later demands.
In the copying study, input length is the only difficulty parameter. Baseline copying trains at the chosen target length, progressive copying can begin at length 1, and mixed copying draws from the range of lengths. Combined copying retains both the progression and the broad draws. Reversal and doubling are separate choices about how a drawn string is presented. A doubled input may contain more characters to read while its original string length remains the difficulty setting used for the copying comparison.
Update the memory and hidden state
The recurrent network is a stack of LSTM layers. At a source position, the first layer gets the current input and its own state from the previous step. A higher layer receives the current activation of the layer below and its own preceding state. Every layer updates a vector of memory cells and a hidden state. The hidden state communicates information through the stack and across steps, and the memory cells give the layer an additional route for retaining information.
The layer update has the following input and output structure:
LSTM: (hₜˡ⁻¹, hₜ₋₁ˡ, cₜ₋₁ˡ) → (hₜˡ, cₜˡ)
Here t is the current timestep and t−1 is the previous timestep. The superscript l is the layer index, so l−1 names the layer immediately below it. The letter h denotes a hidden-state vector and c denotes a memory vector. The colon introduces the named mapping, parentheses group the vectors, commas separate them, and the arrow points from the three inputs to the two updated vectors. In the architecture equations, the width of each hidden or memory vector is n. This use of n refers to the number of vector components, while n in the earlier runtime bound refers to program size.
At layer index 0, hₜ⁰ is the input supplied to the stack at step t. At the top, hₜᴸ denotes the activation of layer L at the current step. The capital L is the depth of the stack. That activation is used to predict yₜ, meaning the output character associated with timestep t. The paper describes this use of the top layer and specifies the equations for the recurrent updates.
The gates and proposed memory content start with a biased linear mapping:
Tₙ,ₘ(x) = Wx + b
The symbol T names the transformation, and its subscripts n and m give the number of input and output components for that mapping. The vector x is the input to the transformation. The matrix W contains the learned weights, and Wx denotes the matrix–vector product. The vector b is the learned bias added to that product. This b is a parameter of the linear map. The curriculum’s target nesting uses the same letter in a separate context. Similarly, x stands for an input vector here and for a whole digit string in the conditional probabilities for copying.
Within the layer, a single transform produces the values for the three gates and the candidate memory content:
(i, f, o, g) = (sigm, sigm, sigm, tanh)(T₂ₙ,₄ₙ([hₜˡ⁻¹ ∥ hₜ₋₁ˡ]))
The brackets enclose two vectors joined by ∥, the notation for concatenation. They are the current input from the layer below, hₜˡ⁻¹, and the layer’s previous hidden state, hₜ₋₁ˡ. Each has width n, so the joined vector has width 2n. The transform T₂ₙ,₄ₙ maps it to a vector of width 4n, which is divided into groups of width n. The parentheses on the right indicate that a separate activation function is applied to each group in order. The function sigm is the sigmoid, which turns each of its inputs into a gate value between zero and one. The function tanh is the hyperbolic tangent, which gives the candidate both positive and negative possible values. The left side names the resulting input gate i, forget gate f, output gate o, and candidate update g.
The gates allow each component of the memory to react differently to the current character. For instance, encountering part of a numeral may call for a change in a representation of that numeral while information from an earlier assignment remains available. The network learns its gate values as functions of the current input and preceding hidden state. The equations supply ways to write, retain, and expose memory without assigning particular cells to variables or arithmetic operations.
The memory update is:
cₜˡ = f ⊙ cₜ₋₁ˡ + i ⊙ g
The new memory cₜˡ is the sum of two vectors. The symbol ⊙ denotes element-by-element multiplication. The forget gate f scales the corresponding entries of the preceding memory cₜ₋₁ˡ. The input gate i scales each entry of the proposed content g. The plus sign adds corresponding components of the retained and incoming parts. If retention is high and the incoming content is small, a cell can preserve information through multiple steps. Other cells can change more substantially during the same interval.
The visible hidden state is obtained from the updated memory:
hₜˡ = o ⊙ tanh(cₜˡ)
The symbol hₜˡ is the new hidden state for layer l and timestep t. The function tanh acts on each entry of the memory cₜˡ. The output gate o scales the transformed entries through elementwise multiplication, again indicated by ⊙. This separates what the layer maintains in memory from what it exposes through the hidden state at that step. The paper credits Speech recognition with deep recurrent neural networks for the particular LSTM equations it uses.
Fit the network and keep the data splits separate
The architecture used for the program and copying comparisons has two layers with 400 cells in each. The recurrence is unrolled for 50 steps during training. Unrolling represents successive applications of the same recurrent update over a span of characters so that those applications can be used in a training update. The network has roughly 2.5M parameters. The initial parameter values are drawn uniformly from the following interval:
[−0.08, 0.08]
The brackets delimit the range for initialization, from negative 0.08 through positive 0.08. The minus sign identifies the negative endpoint. Uniform drawing gives equal probability to equal-sized portions of that range. The hidden states start at zero.
Training processes groups called minibatches, with size 100. The final hidden states from one minibatch initialize the following minibatch. A boundary can consequently occur between reading a program and producing its answer. The 50-step unrolling setting describes the training segments. The state passed across those segments can carry information beyond an individual segment into the next one.
The gradient, which gives the direction and magnitude of changes suggested by the training examples, is normalized by the minibatch size. Its norm is capped at 5. A cap limits the size of a gradient used in an update. The learning rate, which controls the size of the parameter update, stays at 0.5 while a progressive schedule is approaching its target difficulty. The authors describe a target accuracy of 95% for beginning the rate reductions, with a reduction factor of 0.8. Later reductions follow periods without improvement on the training set. This training-set rule for reducing the learning rate serves a separate purpose from using validation progress to advance the curriculum.
Program-output training stops once the learning rate falls below 0.001. The copying experiments include a stopping condition of 20 epochs, with 0.5M samples per epoch. An epoch in this description is a specified amount of training. The paper also presents copying results at convergence, so the experiment uses both a fixed-budget view and a view of what the settings reach when allowed to finish improving.
A generated sample is assigned to training, validation, or test using its hash. A hash gives a repeatable numerical value for an example. The allocation rule uses:
hash(sample) mod 3
The function hash takes the generated example called sample and returns its numerical hash value. The operator mod gives the remainder from division by 3. That remainder determines which of the three splits receives the example. A repeat of the same sample is assigned to the same split, which gives the comparisons disjoint sets. The authors name their wojciechz/learning_to_execute repository as the implementation for reproducing most of their experiments.
Experiments and results
What an accuracy score means in these tests
In every reported accuracy comparison, output prediction uses teacher forcing. In the paper’s notation for explaining the metric, i is a position in the target, and the preceding i−1 positions are filled with their correct characters. This use of i labels a position, independently of the input gate in the LSTM equations. The predictions at those earlier positions are still scored. The correct characters are supplied to the recurrence when it goes on to the next prediction.
The resulting metric concerns choices at individual output positions. The first choice can draw on the source and the state built from it. Later choices can also use the true prefix of the answer. In an addition example, a network that missed an earlier digit when it was asked to predict it still sees the correct digit when it goes on to the following position. If the earlier prediction was already correct, teacher forcing supplies the same character that the network had selected.
Complete answers would impose a further requirement. Each successive character would be generated in the context created by the network’s own previous choices. A mistake could change that context, and even an isolated mistake makes the integer incorrect. The paper expects lower accuracy under independent generation, while the reported scores quantify the supported prediction task. Its supplementary discussion warns readers accordingly about cases with a wrong early digit and apparently correct later digits.
Program evaluation across numerical and structural difficulty
The main program experiment compares the baseline, naive, mixed, and combined strategies on generated examples at specified values of length and nesting. The baseline is an architecture-matched comparison with training concentrated at the target setting. The naive strategy changes the schedule through which the network reaches that setting. The mixed strategy samples across difficulties, and the combined strategy keeps both staged training and the broader sample stream.
The absolute-accuracy figure compares the target-only baseline with the combined curriculum. Its caption reports that the combined curriculum leads in every setting shown. The task gets harder as numbers grow and expressions become more deeply nested. A strategy that helps at a shallow setting can therefore also be evaluated against cases with larger numerical or compositional demands. The paper reports the ordering across these configurations rather than stating a numerical gain for each one in the results discussion.
A separate figure compares the curriculum strategies relative to the baseline. The authors report that the combined strategy outperforms each alternative in every program-evaluation configuration in that comparison. The naive strategy can fall below the baseline. This matters because the baseline gives the network difficult examples from the beginning, while the naive strategy builds from simpler ones. In these experiments, time spent on simpler stages could leave a network less successful on the target than direct exposure to that target.
The examples in the supplementary material show the variety behind the aggregate results. At length 4 and nesting 2, they include a conditional assignment followed by a bounded update loop, a product whose argument is a subtraction, and arithmetic that uses a previously assigned name. At length 6 and nesting 3, some examples feed the result of a series of computations into a comparison that selects the integer to print. These are illustrations of the tested family. The overall comparisons support a result about predicting answers across the generated mix. Accuracy for each separate construct would require scores grouped by the corresponding feature of the program.
The addition result at the target length
In the separate arithmetic experiment, a source expression specifies the sum of two numbers drawn at the same setting. The paper plots the accuracy achieved under different training schedules and reports 99% for the combined curriculum on the length 9 addition task. The setting is described as adding two 9-digit numbers. The score is teacher-forced character prediction accuracy on the addition evaluation. The authors characterize its improvement over the naive curriculum as large and give the combined result explicitly.
This is the most numerically specific reported accuracy for a trained network in the written results. Its significance comes in part from the focused task. A program aggregate blends several operations, sometimes within a single example. Addition holds the operation fixed, so the comparison concerns learning to predict sums as the numerical scale increases. The shared length setting and the generator’s sampling rule are part of the meaning of the result.
The supplementary addition inputs show expressions at length 6 and length 8 in the print-statement format used for the program examples. In these cases the entire answer is obtained from the two operand strings and their addition operation. The output can require carries and can extend beyond the width of the operands. A correct termination prediction contributes to the sequence task alongside the numerical predictions. The stated accuracy gives no separate breakdown for positions with carries, leading digits, or termination.
How the network performed at copying
Copying is evaluated at lengths from 5 to 65 digits. For each curriculum, the input can be supplied in its ordinary form, reversed, doubled, or both doubled and reversed. The unmodified input provides a reference for the transformations. The curriculum comparison supplies a separate reference for changes in the distribution of lengths used in training.
In the convergence results, both mixed and combined training are reported to beat the baseline and naive curriculum across the copying settings. The combined strategy’s advantage over mixed training is less consistent than it is for programs. The authors explicitly say that combined training fails to lead mixed training in some copying settings. The common feature of the stronger curricula is that difficult examples remain present in the stream even when it also contains easier examples.
The paper reports the best copying results for the presentation that uses reversal and doubling together. With this choice, the network can encounter the same information again and encounters the digits in an order that changes the distance from reading a digit to predicting it. Both input choices leave the target in its original order. A random-character reference for copying is roughly 9%, which the paper associates with 11 possible output symbols.
The main copying figure concerns performance at convergence. The supplementary experiment uses the same span of input lengths and the same presentation options with training limited to 20 epochs. A convergence comparison addresses what a setting can achieve when allowed to keep training. A fixed-budget comparison addresses what can be achieved within the stated number of epochs. The textual results give the broad comparison among strategies and presentations while leaving individual plotted accuracies out of the prose.
What simple guesses can achieve
The authors examine how much accuracy could come from choosing frequent answer characters. They examine how frequently each character appears in the output of 10,000 randomly generated programs, each with a length of 4 and a nesting depth of 1. This diagnostic concerns the evaluation and benchmarks question of how much a simple prediction rule can achieve before using any program-specific information. The sample is described as a collection for estimating frequencies, separate in purpose from the held-out prediction comparisons.
With 12 possible output symbols, the paper gives an approximate uniform guessing reference of 8.3% overall. The most frequent character in the pooled outputs is 1, with frequency 12.7%. The pooled distribution reflects the decimal digits, a minus sign of variable occurrence, and the dot that ends every answer. A reference that treats every symbol alike therefore measures something different from a reference based on the empirical frequencies.
The first answer character receives its own diagnostic because its distribution differs from that of later characters. There are 11 possibilities at this position. The paper gives 9% for random guessing and observes that 1 begins 20.3% of the sampled outputs. Always predicting that character is the best constant choice for this position in the diagnostic sample. Its expected score on those observed outputs follows directly from that character’s frequency.
First-character accuracy of guessing rules on programs at length 4 and nesting 1
The most frequent first character gives a stronger guessing rule than a uniform draw.
The numbers
| System or setting | first-character accuracy % |
|---|---|
| Uniform guess, approximate | 9 |
| Always predict the most frequent first character (this paper) | 20.3 |
The chart compares the paper’s guessing settings for the frequency diagnostic. The first-character score of a constant guess measures the effect of a positional bias. It is separate from both the overall character score and the trained network’s performance on the program test data. The authors state that their trained predictor’s accuracy is much higher than the observed initial-character frequency.
The final character is always the terminator. Just before it, the most frequent digit is 4, with a frequency of 10.3% at that position. The authors report checking larger length and nesting settings as well and confirm that the simple bias is weaker there. The diagnostic shows where answer format and digit frequency can make some decisions easier. It leaves room for richer shortcuts that use source patterns or information in a correct answer prefix. Those possibilities concern regularities a frequency count across outputs cannot reveal.
What the ablations show
Staged progression helps most when difficult examples remain in view
The curriculum experiments are controlled comparisons of training exposure. The architecture and task are shared across the curriculum conditions, while the source of generated examples changes. The target-only baseline gives the learner immediate experience with the intended task. The naive curriculum gives it stages of increasing difficulty. The mixed and combined curricula introduce hard examples early while preserving a supply of manageable examples.
The contrast between the naive and combined strategies is especially informative. Both have a current stage. Only the combined strategy supplements that stage with samples across the full range. The combined strategy’s consistent lead on programs supports a concrete statement about this setup. Incorporating a broad range of examples makes the progression more effective at the final program task than restricting training to the current stage.
The mixed curriculum tests how much can be achieved with broad exposure alone. For program evaluation, combined training leads mixed training in the reported comparison, so the staged component can contribute alongside the broad stream. For copying, the two strategies share the advantage over target-only and naive training, and their relative performance varies across conditions. This narrows the paper’s broad language about the combined strategy. Program evaluation shows a consistent winner, while copying more consistently supports the common practice of training on a continuing mixture of difficulties.
The authors also consider changing the order in which the naive curriculum advances its difficulty parameters. They report no noticeable difference between increasing length first and increasing nesting first. The later comparisons therefore use the length-first order. This observation addresses a specific explanation for the naive curriculum’s weakness. Simply changing which parameter advances first did little to alter the reported behavior. The paper gives no numerical effect size for this switch, so the evidence supports only the qualitative comparison.
Reversal makes selected dependencies shorter
Reversal changes which input digits have been seen recently when answering starts. In the normal ordering, the first target digit corresponds to the part of the input seen earliest. In the reversed ordering, that digit corresponds to the part seen last. Because the target ordering is fixed, the later output positions have a different pattern of dependencies as well.
The authors’ explanation depends on the distribution of distances, rather than their average alone. Some correspondences become short enough to offer accessible examples early in learning. The network can build useful predictions while having to preserve information for fewer steps in these cases. Other correspondences still demand storage. The average distance is unchanged in the paper’s analysis, so the benefit proposed for reversal rests on making a subset of the relationships particularly easy to learn.
The copying experiment supplies a useful setting for this comparison because the desired result is easy to describe and stable under the change in presentation. A difference in performance follows a change in the organization of the recurrent computation over an equivalent input. The experiments evaluate that effect in the digit task. The same short-dependency explanation would have to be examined anew for a program whose output depends on multiple operands, assignments, and branches.
Doubling allows further state updates over familiar input
Where reversal changes order, doubling changes the amount of processing available before output. When the first copy has been read, the recurrent state already reflects that material. The next copy begins with that state and updates it again in response to the same sequence. The authors suggest that a second pass gives the network a chance to preserve a digit it previously omitted or improve an imperfect representation.
The experiment compares doubling alone and doubling with reversal alongside the other presentations. The fact that the combined presentation leads the copying results shows that the improvements can coexist. The repeated pass can supply additional processing while the reversed order still puts useful input characters near the transition to output. This is a behavioral comparison of available presentations. The figures provide no direct record of which omissions were repaired, which cells retained which digits, or which particular correspondences accounted for the gain.
Copying also helps interpret the role of teacher forcing in these comparisons. After a position has been scored, the system is given the correct character at that position before making its next prediction. All input presentations have that help during evaluation. Their differences therefore reflect the effect of input presentation under a shared output protocol. The advantage of duplication and reversal is established for those predictions, while their effect on intact, independently generated copies remains a separate question.
The memory-allocation account remains a hypothesis
The authors propose an explanation for why progress through easy cases can give poor preparation for hard ones. An easy example requires relatively little information to be remembered. The network can potentially spread that information over much of its internal state. As long as training asks it to handle only those cases, it has little incentive to learn a representation that reserves room for harder examples.
The paper illustrates the proposal using addition and the transition from 5 digits to a 6-th digit. A system that uses a broad distributed representation for the earlier demand may need to reorganize it to hold more information. A distributed representation stores a value through a pattern across several state components, so a change in what must be remembered can involve changes throughout the pattern. The authors hypothesize that learning such a reorganization can be difficult even when the network’s overall capacity could support the target.
A mixture of difficulties changes that pressure from the beginning. Larger examples make it useful to discover how to retain more information while easy examples are still frequent. In the combined approach, the current stage can put emphasis on manageable mappings, and the broad stream can reward ways of representing them that also serve demanding cases. This gives a reason the staged part and mixed part could help together on programs.
The results measure predictive performance under different curricula. They leave the proposed organization of memory in the realm of explanation. The experiments do not quantify how much state an easy example occupies, measure a contraction when the curriculum advances, or trace a particular representation through that transition. Mixed training changes exposure to hard instances at the same time that it changes any pressure on memory organization. The comparisons establish the benefit of the exposure pattern under the reported conditions, with memory allocation as the authors’ account of how it might work.
The bias analysis tests a narrower explanation
The frequency study controls for a simpler interpretation of accurate prediction. If one answer character dominated the output, a predictor could achieve an apparently strong score simply by selecting it. Inspecting both the pooled output and particular positions shows where format and digit choice affect this comparison. Initial characters have an identifiable bias, and the terminator is deterministic at the end.
This analysis is distinct from removing a component of the network. It estimates the performance of simple reference behaviors. The strongest initial-character guess uses the observed first-position frequency and requires no source processing. The trained predictions reported by the paper exceed what the authors consider explainable by such a bias. Whether the network uses some combination of simple numerical operations and more elaborate statistical regularities remains the question raised in the paper’s critique.
Limitations
Limits the authors identify
The authors distinguish between predicting many correct characters and learning the procedure that yields every correct answer. Addition provides their example. A system could add corresponding digits and produce correct results where no carry enters the calculation. It could also memorize results for small groupings and combine those local outcomes. The paper discusses memorizing additions involving 2-digit numbers as a possible approximation. Such a strategy could cover many local predictions while failing on cases that require the relationships of the full addition procedure.
The authors do not know how heavily the network relies on memorization or how close its learned behavior is to exact execution. These alternatives are particularly relevant to a score based on individual characters. A systematic weakness on a particular pattern of carries might affect only some positions. A high average can coexist with a regular failure in the computation. The experiments give the network no labels for carries or intermediate program values, and the score provides no direct evidence about which internal procedure produced a successful prediction.
The authors also state that training and testing share distributions. The hash rule keeps examples disjoint, so the experiment can evaluate predictions on new instances from the specified settings. This controls reuse of the same examples. It leaves intact the common generator, the recurring patterns of source text, and the familiar ranges of numerical and structural difficulty. The authors suggest a substantial difference between training and testing as a way to investigate whether the behavior generalizes farther. They leave that test open.
Teacher forcing is another explicit limitation. A complete answer generated from the source alone has to survive any mistakes in its own output history. The reported protocol replaces those guesses with correct characters before the next decision. An example in which later positions are accurate after an early error shows competent predictions after the true prefix is restored. Recovery from an actual erroneous prefix would require an independent generation experiment.
The range of supported programs also follows from the resource restrictions the authors set at the beginning. They explicitly leave arbitrary programs outside the experiment and identify runtimes beyond linear as a problem for the conventional recurrent reader. A fixed-size state and a single reading pass motivate the limits on multiplication, iteration, and program inputs. The paper’s evidence for programs with restricted loops applies to the generated loops and their compositions. Supporting a program whose running time is much larger than its text would pose a computational demand outside the tested regime.
Finally, the authors leave the optimal curriculum unresolved. The combined scheme improves program prediction throughout their reported comparisons, and mixed training can do better than the combined scheme in some copying conditions. The study establishes which choices helped in its design and suggests that a more complete account would need to identify which samples benefit learning most. The hidden-state explanation gives one reason to consider early hard examples. It leaves open how many examples of each difficulty should appear or how their value changes during training.
Limits visible in the experimental design
The generator determines much of what a prediction can demonstrate. It gives the authors known targets and control over numerical scale and nesting. It also governs which surface forms recur, which operations are available, and which combinations can be tested. A held-out program may be new as a string while using a familiar pattern of assignments and expressions. The split is suited to interpolation within the task family. A stronger claim about new combinations, source conventions, or arbitrary Python syntax would need other data.
The length setting likewise needs to stay attached to the generator’s definition. It sets a sampling range, and the examples show that visible numeral width can vary within a setting. A comparison across length values therefore changes the scale from which numbers can be drawn. In program evaluation it also changes the range for loop counts and restricted factors. An observed effect of length can reflect these linked changes. The experiment does not separate their individual contributions.
Nesting defines permitted composition, and the program samples include different constructs at the same setting. A high aggregate score offers no specific guarantee about comprehension of variable assignments, faithful choice of a conditional branch, or exact arithmetic after a loop. Longer answers also provide more character positions to score, while some output positions have predictable formatting. The paper’s separate addition and copying studies help locate the task demands, but they do not turn the aggregate program score into a per-operation analysis.
The architectural choices are held fixed in the central comparisons. That is valuable for associating differences with curriculum or presentation. It also leaves open how the schedule interacts with memory width, recurrent depth, and training unroll length. For instance, the hypothesis about expanding representations depends on the relationship between memory capacity and task demand. The experiments vary the task more than the capacity. They give no capacity comparison that could show whether the advantage is largest in a particular range of state sizes.
Similarly, the two copying report conditions distinguish convergence from a budget of 20 epochs. They permit different questions about eventual quality and performance within a given amount of training. Doubling the input supplies more recurrent updates over each string, so an equal number of examples need not represent equal processing work for every presentation. The reported superiority of the combined transformation concerns accuracy under the paper’s comparisons. A comparison of computational cost would have to account for that difference in processing.
The output-frequency analysis rules out only a small set of explanations. It establishes approximate guessing references and identifies prominent symbols at some positions. A shortcut related to common source forms, local numerical patterns, or the correct answer prefix could be more effective than a constant character. The paper’s own critique gives reasons to take such alternatives seriously. Since the central measurement is predictive accuracy, it leaves substantial room for investigation of what the internal state represents and when that representation is sufficient to support exact execution.
What came after
Making room for intermediate computation
The citing work on scratchpads for intermediate computation takes up a question that is implicit in the earlier experiments. Where can information about unfinished computation go? In Learning to Execute, the source is read into a recurrent state, and a training example supplies the final numerical answer. A scratchpad makes intermediate computation part of the written sequence. The contrast gives a concrete way to relate the research questions. The earlier design asks how much can be carried from input to final answer internally. The later work puts intermediate work into the textual task.
Chain-of-Thought Prompting moves the focus to eliciting reasoning through the form of a prompt. In Learning to Execute, changing the difficulty of examples changes what the network encounters during training. A study of prompting asks how the request itself can elicit a sequence of reasoning. The connection is the use of sequences to support computation, with the earlier study emphasizing the acquisition of a source-to-result mapping and the later title identifying a way to call forth reasoning at the point of use.
The distinction between a final answer and the computation leading to it matters to both connections. Learning to Execute can measure output agreement because the generated program fixes the integer. Its experiments leave the sequence of internal computations unknown. A task that includes intermediate work in the visible sequence creates a different object of study. Intermediate steps become part of what the system is asked to express, and the relationship between those steps and the final answer becomes a possible question in its own right.
From program outputs to broader questions about code
Evaluating Large Language Models Trained on Code addresses evaluation of systems trained with source code. Learning to Execute offers a particular evaluation question in that broader area. Given program text, can a trained network predict an externally determined result? Its generator makes it possible to associate that question with specific demands such as numerical scale and composition. The title of the later study identifies the wider subject of code-trained systems. The citation places the earlier experiment in that evaluation context.
Program Synthesis with Large Language Models concerns generating programs. Synthesis and prediction of program output approach the connection between source and computation from different directions. The early task starts with source and asks what value follows. Synthesis puts source on the output side, where a produced program can be considered in relation to what it is meant to accomplish. The relation to Learning to Execute is therefore substantive even without identifying a shared dataset or schedule. Both tasks require a way to judge textual code by its computational consequences.
Inferring and Executing Programs for Visual Reasoning brings program inference and execution into visual reasoning. In Learning to Execute, the program is given, and predicting its integer is the task itself. The later work’s title places program inference before execution and uses the pair for a visual reasoning task. This extends the connection between learned processing and execution to a setting in which obtaining the program is itself part of the problem.
Examining arithmetic and compositional generalization
Analysing Mathematical Reasoning Abilities of Neural Models centers the evaluation of mathematical behavior. The addition experiment in Learning to Execute is a narrow instance of that concern. It varies numerical scale and observes the accuracy of one familiar operation under different training schedules. The authors’ critique makes the link especially clear. A score for addition leaves an open question about the generality of the learned procedure, because different methods may agree on many positions and diverge where carries are required.
Teaching Arithmetic to Small Transformers returns to arithmetic learning with a different architecture. Learning to Execute makes the presentation of training examples part of its explanation of how arithmetic becomes learnable for the recurrent network. The later title likewise places the teaching problem at the center, with small Transformers as the systems being taught. Their documented connection concerns the acquisition of arithmetic behavior. The reported 99% addition result belongs to the earlier network and its own output protocol.
Compositionality decomposed asks how neural networks generalize in connection with composition. In Learning to Execute, nesting varies how much structure the generator permits, and held-out examples test predictions within the chosen distributions. The compositional question goes further by asking in what sense a system can reuse behavior learned for the parts when the way they are assembled changes. That is a natural extension of the earlier authors’ proposal to examine more substantial differences between training and testing.
Revisiting structure and memory
Tree-Structured Long Short-Term Memory Networks studies semantic representations using tree-structured LSTMs. Its relationship to Learning to Execute lies in the choice of where composition is represented. The program experiments give a linear reader examples whose structure can be described by a tree. A tree-structured LSTM makes the tree part of the organization of recurrent computation. The two settings offer different ways for a learned state to reflect relations among constituent parts.
Neural Random-Access Machines puts memory access in the foreground. The earlier program reader updates a fixed state at every character and depends on that state to keep useful information from earlier in the source. Its limits on programs and its hypothesis about curricula both follow from this design. The later work names random access as part of its computational framing, bringing the organization and use of memory into direct view.
These citation relationships span arithmetic, code, intermediate computation, composition, and memory. The common research problem is how to tell what computation a trained system can perform from the behavior it exhibits. Learning to Execute contributes a controlled case in which the program fixes the target, the generator sets the difficulty, and the training stream strongly affects accuracy. Its teacher-forced measurements and distributional boundaries specify which part of that problem it resolved and which questions remained for later studies.
Cite
Cite as Wojciech Zaremba and Ilya Sutskever. 2014. Learning to Execute. arXiv:1410.4615.
@misc{zaremba2014learning,
title = {{Learning to Execute}},
author = {Wojciech Zaremba and Ilya Sutskever},
year = {2014},
doi = {10.48550/arxiv.1410.4615},
eprint = {1410.4615},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.1410.4615}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/zaremba-2014-learning-execute/
References
- Bengio, Yoshua, Louradour, Jérôme, Collobert, Ronan, and Weston, Jason. Curriculum learning. In Proceedings of the 26th annual international conference on machine learning, pp. 41–48. ACM, 2009. OpenAlex ↗ · Scholar ↗
- Bengio, Yoshua, Boulanger-Lewandowski, Nicolas, and Pascanu, Razvan. Advances in optimizing recurrent networks. In Acoustics, Speech and Signal Processing (ICASSP), 2013 IEEE International Conference on, pp. 8624–8628. IEEE, 2013. OpenAlex ↗ · Scholar ↗
- Bowman, Samuel R. Can recursive neural tensor networks learn logical reasoning? arXiv preprint arXiv:1312.6192, 2013. OpenAlex ↗ · Scholar ↗
- Bowman, Samuel R, Potts, Christopher, and Manning, Christopher D. Recursive neural networks for learning logical semantics. arXiv preprint arXiv:1406.1827, 2014. OpenAlex ↗ · Scholar ↗
- Cho, Kyunghyun, van Merrienboer, Bart, Gulcehre, Caglar, Bougares, Fethi, Schwenk, Holger, and Bengio, Yoshua. Learning phrase representations using rnn encoder-decoder for statistical machine translation. arXiv preprint arXiv:1406.1078, 2014. our card
- Graves, Alex, Mohamed, Abdel-rahman, and Hinton, Geoffrey. Speech recognition with deep recurrent neural networks. In Acoustics, Speech and Signal Processing (ICASSP), 2013 IEEE International Conference on, pp. 6645–6649. IEEE, 2013. our card
- Hill, Theodore P. A statistical derivation of the significant-digit law. Statistical Science, pp. 354–363, 1995. OpenAlex ↗ · Scholar ↗
- Hochreiter, Sepp and Schmidhuber, Jürgen. Long short-term memory. Neural computation, 90 (8):0 1735–1780, 1997. OpenAlex ↗ · Scholar ↗
- Jaeger, Herbert, Lukoševičius, Mantas, Popovici, Dan, and Siewert, Udo. Optimization and applications of echo state networks with leaky-integrator neurons. Neural Networks, 200 (3):0 335–352, 2007. OpenAlex ↗ · Scholar ↗
- Koutník, Jan, Greff, Klaus, Gomez, Faustino, and Schmidhuber, Jürgen. A clockwork rnn. arXiv preprint arXiv:1402.3511, 2014. OpenAlex ↗ · Scholar ↗
- Kumar, M Pawan, Packer, Benjamin, and Koller, Daphne. Self-paced learning for latent variable models. In Advances in Neural Information Processing Systems, pp. 1189–1197, 2010. OpenAlex ↗ · Scholar ↗
- Lee, Yong Jae and Grauman, Kristen. Learning the easy things first: Self-paced visual category discovery. In Computer Vision and Pattern Recognition (CVPR), 2011 IEEE Conference on, pp. 1721–1728. IEEE, 2011. OpenAlex ↗ · Scholar ↗
- Maddison, Chris J and Tarlow, Daniel. Structured generative models of natural source code. arXiv preprint arXiv:1401.0514, 2014. OpenAlex ↗ · Scholar ↗
- Martens, James. Deep learning via hessian-free optimization. In Proceedings of the 27th International Conference on Machine Learning (ICML-10), pp. 735–742, 2010. OpenAlex ↗ · Scholar ↗
- Mikolov, Tomáš. Statistical language models based on neural networks. PhD thesis, Ph. D. thesis, Brno University of Technology, 2012. OpenAlex ↗ · Scholar ↗
- Mikolov, Tomas, Karafiát, Martin, Burget, Lukas, Cernockỳ, Jan, and Khudanpur, Sanjeev. Recurrent neural network based language model. In INTERSPEECH, pp. 1045–1048, 2010. OpenAlex ↗ · Scholar ↗
- Mou, Lili, Li, Ge, Liu, Yuxuan, Peng, Hao, Jin, Zhi, Xu, Yan, and Zhang, Lu. Building program vector representations for deep learning. arXiv preprint arXiv:1409.3358, 2014. OpenAlex ↗ · Scholar ↗
- Pascanu, Razvan, Gulcehre, Caglar, Cho, Kyunghyun, and Bengio, Yoshua. How to construct deep recurrent neural networks. arXiv preprint arXiv:1312.6026, 2013. our card
- Pham, Vu, Kermorvant, Christopher, and Louradour, Jérôme. Dropout improves recurrent neural networks for handwriting recognition. arXiv preprint arXiv:1312.4569, 2013. OpenAlex ↗ · Scholar ↗
- Robinson, Tony, Hochberg, Mike, and Renals, Steve. The use of recurrent neural networks in continuous speech recognition. In Automatic speech and speaker recognition, pp. 233–258. Springer, 1996. OpenAlex ↗ · Scholar ↗
- Sutskever, Ilya. Training Recurrent Neural Networks. PhD thesis, University of Toronto, 2013. OpenAlex ↗ · Scholar ↗
- Sutskever, Ilya, Vinyals, Oriol, and Le, Quoc V. Sequence to sequence learning with neural networks. arXiv preprint arXiv:1409.3215, 2014. our card
- Zaremba, Wojciech, Kurach, Karol, and Fergus, Rob. Learning to discover efficient mathematical identities. arXiv preprint arXiv:1406.1584, 2014a. OpenAlex ↗ · Scholar ↗
- Zaremba, Wojciech, Sutskever, Ilya, and Vinyals, Oriol. Recurrent neural network regularization. arXiv preprint arXiv:1409.2329, 2014b. our card