AI Logic

Architectures

Elman Network (Simple RNN)

Updated:

Elman network architecture. Top: the overall flow with the RNN laid out at each time step (the hidden state is passed to the next time step). Bottom: the inside of one time step (the hidden layer is computed from the input and the context, and the hidden layer's values are copied to the context for the next time step)

Background and Overview

The Elman network is an RNN (recurrent neural network) that simply delays the hidden layer's values by one time step and adds them to the next time step's input. It was proposed by Elman in 1990 in "Finding Structure in Time" and is also called the "Simple Recurrent Network." Today, "RNN" usually refers to this form.

Before this, the common way for neural networks to handle sequences was to lay out time steps directly as input dimensions. The paper points out the following problems with that approach.

  • It needs a buffer for the input: The whole sequence must be received before it can be fed in at once.
  • The length is fixed: The size of the input layer sets an upper limit on the sequence length.
  • It is sensitive to shifts: [0 1 1 1 0 0 0 0 0] and [0 0 0 1 1 1 0 0 0] are the same pattern shifted in time, yet as vectors they look far apart.

Elman proposed representing time implicitly, through its effect on processing, rather than explicitly as an input dimension. The network is given a "memory," and its output depends on both the current input and the memory so far. The memory is a set of "context units" that store the hidden layer's values as they are.

This idea modifies Jordan's network (1986), which fed the output back to the next time step; the difference is that it feeds back the hidden layer instead of the output. The hidden layer holds a richer internal representation than the output, so it can carry the information the task needs into the next time step in whatever form is useful.

Because its structure is so simple, the Elman network becomes hard to train on long sequences due to vanishing gradients and exploding gradients. LSTM and GRU were developed to solve this weakness.

Architecture: Computation at One Time Step

At each time step tt, the Elman network takes the input xtx_t and the hidden state htβˆ’1h_{t-1} from the previous time step, and outputs a new hth_t and an output yty_t. The top of the figure at the beginning of the article shows the overall flow laid out over time, and the bottom shows the inside of one time step.

In the paper's terms, processing at one time step goes as follows.

  1. The input units receive the sequence element xtx_t.
  2. Both the input units and the context units (the hidden layer's values from the previous time step, htβˆ’1h_{t-1}) activate the hidden layer.
  3. The hidden layer activates the output layer, producing the output yty_t.
  4. The hidden layer's values are copied as they are into the context units. These values are used in step 2 at the next time step.

In today's common notation (the equations of PyTorch's nn.RNN), this becomes:

ht=tanh⁑(Wihxt+bih+Whhhtβˆ’1+bhh)yt=Whyht+by\begin{aligned} h_t &= \tanh(W_{ih} x_t + b_{ih} + W_{hh} h_{t-1} + b_{hh}) \\ y_t &= W_{hy} h_t + b_y \end{aligned}
SymbolMeaningLearned?
WihW_{ih}Weights from the input to the hidden layerYes
WhhW_{hh}Weights from the context (htβˆ’1h_{t-1}) to the hidden layerYes
WhyW_{hy}Weights from the hidden layer to the output layerYes
Copy from hidden layer to contextOne-to-one, weight fixed at 1.0No

The number of context units equals the number of hidden units, and each hidden unit copies its value into its own dedicated context unit. In contrast, the connections from the context to the hidden layer are fully connected: every context unit connects to every hidden unit.

The hidden state hth_t is like the notes you take while reading a book. After each sentence, you rewrite your notes by looking at both the previous notes and the new sentence. The notes have a fixed size, so what to keep is decided by learning.

The original paper and today's implementations differ as follows.

  • Activation function: The paper used a function with values in 0–1 (a sigmoid) and initialized the context units to 0.5. Today it is common to use Tanh and start h0h_0 at 0 (PyTorch's nn.RNN lets you choose 'tanh' or 'relu' via nonlinearity).
  • Bias: PyTorch splits the bias into two, bihb_{ih} on the input side and bhhb_{hh} on the hidden-state side. Since they are simply added, the functions they can represent are the same as with a single bias.

Training

The Elman network is usually trained with BPTT (Backpropagation Through Time), which applies backpropagation to the network unrolled over time.

  1. Read the sequence one time step at a time from the start, computing hth_t and yty_t at each step.
  2. Compute the loss from the output and target at each time step, and sum the losses over all time steps (cross-entropy for classification).
  3. Compute the gradient of the loss backward from the last time step to the first, and update Wih,Whh,WhyW_{ih}, W_{hh}, W_{hy}, which are shared across all time steps.

Training in the original paper was simpler. The context units were treated as "just part of the input," and at each time step the output error was backpropagated to update the weights a little at a time. The copy connections were fixed at weight 1.0 and not learned. The paper showed that even with this method, the network can learn the structure of sequences, because information from the previous time step enters through the context.

To keep gradients from growing too large in BPTT, gradient norm clipping, proposed by Pascanu et al. (2013), is commonly used. If the norm of the gradient g^\hat{g} exceeds a threshold, the gradient is shrunk to the threshold while keeping its direction.

ifΒ βˆ₯g^βˆ₯β‰₯thresholdΒ thenΒ g^←thresholdβˆ₯g^βˆ₯ g^\text{if } \lVert \hat{g} \rVert \ge \text{threshold} \text{ then } \hat{g} \leftarrow \frac{\text{threshold}}{\lVert \hat{g} \rVert}\,\hat{g}

In PyTorch, this is done with torch.nn.utils.clip_grad_norm_.

Why Long-Range Dependencies Are Hard

The Elman network struggles with long sequences because, each time the error goes back one step in time, it is multiplied by the same matrix.

In Pascanu et al.'s analysis, the rate of change from hkh_k to hk+1h_{k+1} (the Jacobian) is the product of the recurrent weights WhhW_{hh} and a diagonal matrix of activation-function derivatives. Going back from tt to kk multiplies this together tβˆ’kt-k times.

βˆ‚htβˆ‚hk=∏tβ‰₯i>kWhhβŠ€β€‰diag(Οƒβ€²(β‹…))\frac{\partial h_t}{\partial h_k} = \prod_{t \ge i > k} W_{hh}^{\top}\, \mathrm{diag}\big(\sigma'(\cdot)\big)

Just as multiplying a number by itself many times drives it toward 0 if it is less than 1 and toward infinity if it is greater than 1, the same happens with matrices.

  • Vanishing gradients: If the largest absolute eigenvalue Ξ»1\lambda_1 of WhhW_{hh} is smaller than 1/Ξ³1/\gamma (where Ξ³\gamma is an upper bound on the activation function's derivative), gradients from the distant past shrink toward 0 exponentially.
  • Exploding gradients: For gradients to explode, Ξ»1>1/Ξ³\lambda_1 > 1/\gamma is necessary.

Ξ³\gamma is 1 for tanh and 1/4 for the sigmoid, which shows that gradients vanish more easily with the sigmoid.

When gradients vanish, how inputs from the distant past affected the loss is barely reflected in the weight updates. Even if the loss goes down, the network may not have learned relationships such as "the answer is determined by an input dozens of steps earlier." For tasks that need long-range dependencies, consider LSTM or GRU from the start.

Clipping can tame exploding gradients, but it does not solve vanishing gradients. LSTM solved this problem by creating a path that updates memory by addition rather than multiplication.

Experiments in the Paper

The original paper framed every task as "predicting the next input" and examined what structure the network finds in sequences. In a prediction task, the sequence itself provides the targets, without any externally supplied answers.

TaskInputNetwork size (input, hidden, output, context)Findings
Temporal XORA 3,000-bit sequence of two bits followed by their XOR, one bit at a time1, 2, 1, 2After 600 passes of training, the error dropped only on the predictable third bit
Letter sequencesA sequence of 6-bit feature vectors in which each consonant is followed by a fixed vowel repeated a fixed number of times6, 20, 6, 20Consonants were mispredicted, but the type and number of the following vowels were predicted correctly
Word boundariesA 4,963-letter sequence of letters with no word boundaries5, 20, 5, 20The error was high at the start of each word and fell as the word progressed
Word classesA sequence of 10,000 two- or three-word sentences built from 29 words, concatenated without breaks31, 150, 31, 150Averaging the hidden-layer values per word and applying hierarchical clustering separated nouns from verbs, animate from inanimate, and so on

In temporal XOR, the sequence continues as "two bits and their XOR," for example 1 0 1 0 0 0 0 1 1. The first and second bits are random and cannot be predicted, but the third bit is determined by the previous two. The error rose and fell with this period, showing that the network remembers and uses previous inputs.

In the word-class experiment, each word was represented by a 31-bit vector orthogonal to all others, so the input carried no cues about part of speech or meaning. Even so, to predict the next word, words appearing in similar positions came to have similar hidden-layer representations, and groupings by part of speech and meaning emerged.

In the word-boundary experiment, the positions where the prediction error rose matched word boundaries well. One of the paper's conclusions is that prediction error itself can serve as a clue to "where the structure is."

Practical Considerations

Keep the following points in mind when using an Elman network (PyTorch's nn.RNN).

  • Long-range dependencies are hard to learn: Because of vanishing gradients, relationships between distant time steps often cannot be learned.
  • Guard against exploding gradients: If the loss suddenly spikes or becomes NaN during training, add gradient norm clipping.
  • No parallelism over time: Computing time step tt requires htβˆ’1h_{t-1}, so the steps must be computed in order, as many times as the sequence length.
  • nonlinearity='relu' tends to blow up values: ReLU has no upper bound, so depending on WhhW_{hh}, the hidden state can keep growing over time. With the default tanh, values stay within βˆ’1 to 1.

Setting batch_first=True in PyTorch's nn.RNN changes only the shape of the input and output. The shape of h_n stays (num_layers Γ— num_directions, batch, hidden_size). Get the last layer's hidden state with h_n[-1].

Comparison with Other Models

Comparing the main sequence models from the same perspective gives the following.

ModelHow memory is heldGatesWeight sets per time step (WhhW_{hh} and WihW_{ih})Long-range dependencies
Elman networkHidden state onlyNone1Hard to learn due to vanishing gradients
LSTMCell state and hidden stateThree: forget, input, output4Learnable via the cell-state path
GRUHidden state onlyTwo: update, reset3Learnable by regulating with gates
TransformerNone (looks at all positions directly)None (attention)β€”Directly connected by a single attention step

Guidelines for choosing:

  • Short sequences, understanding the mechanism, or running with minimal compute: An Elman network may be enough.
  • Learning relationships dozens of steps apart or more: Use LSTM or GRU.
  • Using context from both directions of the sequence: Use a bidirectional RNN, which combines forward and backward RNNs.
  • Handling long contexts with large amounts of data: The Transformer is the mainstream choice.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm

"""
Solve the paper's "temporal XOR" as a next-bit prediction task (a small example that needs no data download)
The sequence is a series of 3-bit groups "a, b, a XOR b". Only the third bit can be predicted from the previous two
"""

# Hyperparameters
num_triples = 10        # Number of 3-bit groups in one sequence (sequence length is 30)
hidden_size = 8
batch_size = 64
steps = 3000
learning_rate = 1e-2
clip_norm = 1.0         # Threshold for gradient norm clipping

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


def make_batch(n):
  a = torch.randint(0, 2, (n, num_triples))
  b = torch.randint(0, 2, (n, num_triples))
  bits = torch.stack([a, b, a ^ b], dim=2).reshape(n, -1).float()  # [n, 3 * num_triples]
  x = bits[:, :-1].unsqueeze(-1)   # Input: all bits except the last  [n, T, 1]
  y = bits[:, 1:]                  # Target: the next bit              [n, T]
  return x.to(device), y.to(device)


class ElmanPredictor(nn.Module):
  def __init__(self):
    super().__init__()
    # nn.RNN is the Elman network: h_t = tanh(W_ih x_t + b_ih + W_hh h_{t-1} + b_hh)
    self.rnn = nn.RNN(input_size=1, hidden_size=hidden_size, nonlinearity='tanh',
                      batch_first=True)
    self.head = nn.Linear(hidden_size, 1)   # Output layer W_hy

  def forward(self, x):                      # x: [B, T, 1]
    output, h_n = self.rnn(x)                # If h_0 is not given, it starts at 0
    # output: [B, T, hidden_size]  h_t at every time step
    # h_n: [num_layers, B, hidden_size]  the batch stays on the second axis even with batch_first
    return self.head(output).squeeze(-1)     # Predict the next bit at every time step [B, T]


model = ElmanPredictor().to(device)
criterion = nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training loop (BPTT: backpropagate from the loss over the whole sequence)
model.train()
for step in tqdm(range(steps)):
  x, y = make_batch(batch_size)
  optimizer.zero_grad()
  loss = criterion(model(x), y)
  loss.backward()
  torch.nn.utils.clip_grad_norm_(model.parameters(), clip_norm)  # Prevent exploding gradients
  optimizer.step()

# Evaluation: look separately at accuracy on predictable positions (the XOR bits) and unpredictable ones
model.eval()
x, y = make_batch(1000)
with torch.no_grad():
  pred = (model(x) > 0).float()
correct = (pred == y).float()
xor_pos = torch.arange(y.shape[1], device=device) % 3 == 1   # When the input is b, the next bit is a XOR b
print(f"Accuracy on XOR bits:   {correct[:, xor_pos].mean().item() * 100:.2f}%")   # Approaches 100%
print(f"Accuracy on other bits: {correct[:, ~xor_pos].mean().item() * 100:.2f}%")  # Around 50% (random)

FAQ

Q. How does the Elman network differ from Jordan's network?
A.

They differ in what is fed back to the next time step. Jordan's network (1986) feeds back the output, while the Elman network feeds back the hidden layer. The output's form is fixed by the task, but the hidden layer's representation is shaped freely by learning, so the Elman network can carry the information needed at the next time step more flexibly.

Q. Is PyTorch's `nn.RNN` an Elman network?
A.

Yes. nn.RNN is an Elman network that computes ht=tanh⁑(Wihxt+bih+Whhhtβˆ’1+bhh)h_t = \tanh(W_{ih} x_t + b_{ih} + W_{hh} h_{t-1} + b_{hh}). It does not include the output layer WhyW_{hy}, so attach an nn.Linear after it. The differences from the original paper are that the activation function is tanh (or ReLU) and that training uses BPTT.

Q. Can gradient clipping also prevent vanishing gradients?
A.

No. Clipping shrinks the gradient when its norm exceeds a threshold, so it only helps with gradients that are too large (exploding gradients). It does not enlarge gradients that have become too small. For vanishing gradients, use a model such as LSTM or GRU that has a path along which gradients do not shrink through repeated multiplication.

References

  1. Elman, J. L. (1990). Finding Structure in Time. Cognitive Science, 14(2), 179–211.
  2. Pascanu, R., Mikolov, T., & Bengio, Y. (2013). On the difficulty of training Recurrent Neural Networks. ICML 2013. arXiv:1211.5063.
  3. PyTorch. torch.nn.RNN.