Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

2.4 CNNs for NLP

A reviewer writes “This movie was not good at all.” A sentence classifier could count the words not and good, but those counts would stay the same if we swapped them. A TextCNN filter gives each position in a short phrase its own weights. In the worked example, swapping those words changes the pooled feature from 2 to 1. A classifier can use that difference when it predicts a label.

Motivation: The Need for Speed

A conventional RNN needs the previous hidden state to compute the next one. Within a convolutional layer, each position reads its own window from the same input. All the windows can be evaluated in parallel. Actual speed also depends on the number of layers, tensor sizes, kernels and hardware.

The Metaphor: The Reading Glass

Imagine moving a three-word reading glass one word at a time. Each stop gives the filter one local score. Max-over-time pooling keeps the strongest response for that filter, so the number reaching the classifier no longer tells it where the response occurred.

How 1D Convolutions Work on Text

A sentence of nn tokens with dd embedding coordinates per token forms a matrix X∈Rn×dX\in\mathbb{R}^{n\times d}. A width-kk filter has weights W∈Rk×dW\in\mathbb{R}^{k\times d} and a scalar bias bb. It reads all dd coordinates at each of kk successive token positions. It moves only along the token axis.

The Mechanism

For zero-based start ii, the score before activation is zi=b+∑j=0k−1Wj⋅Xi+jz_i=b+\sum_{j=0}^{k-1}W_j\cdot X_{i+j}. Each dot product pairs an embedding with the filter row at the same offset. PyTorch calls this operation Conv1d and computes cross-correlation, keeping the filter rows in their given order [5]. Mathematical convolution reverses the filter [2].

With stride one and no padding, there are n−k+1n-k+1 complete windows when n≥kn\geq k. Apply ReLU to every score to obtain the feature map ai=max⁡(0,zi)a_i=\max(0,z_i). The pooled feature for this filter is max⁡iai\max_i a_i.

Example: Sliding Window Convolution

Give not the embedding (1,0)(1,0), good the embedding (0,1)(0,1), and every other word (0,0)(0,0). These two coordinates are hand-set cues for negation and praise. Our three filter rows in order are (2,0)(2,0), (0,1)(0,1) and (−1,2)(-1,2), with bias −1-1. At start 3, not good at contributes 2+1+0−1=22+1+0-1=2. At start 2, was not good contributes 0+0+2−1=10+0+2-1=1. Both windows contain the same two cues, but the cues occupy different offsets.

Reading word order with one width-3 filter
Thismoviewasnotgoodatall
Coordinates are the negation and praise features, in that order.
WordEmbeddingFilter rowDot product
not(1, 0)(2, 0)2
good(0, 1)(0, 1)1
at(0, 0)(-1, 2)0

Sum of dot products plus bias 2 + 1 + 0 − 1 = 2

ReLU for this window 2

ReLU at all five windows [0, 0, 1, 2, 0]

Pooled maximum 2 · Winning starts 3

Before swapping the words, the five raw scores are [−1,−2,1,2,−1][-1,-2,1,2,-1]. ReLU gives [0,0,1,2,0][0,0,1,2,0], so 2 survives pooling. Swap the two words and the strongest response falls to 1 at starts 1 and 4. Pooling passes one number even when two windows tie. This filter was chosen to make the arithmetic visible. A class probability would require a trained classifier and an output transformation.

Breakthrough Architectures

Kim’s 2014 sentence classifier used 100 filters at each of widths 3, 4 and 5. One maximum per filter gives 3×100=3003\times100=300 features for the classifier. Kim compared randomly initialized, pretrained frozen, and fine-tuned word vectors, among other variants, on sentence classification benchmarks. The learned filters need not correspond to named linguistic rules [1].

PyTorch TextCNN

The first CPU example reproduces the figure with a single filter. The shape of its weight tensor is [1, 2, 3] for one output channel, two embedding coordinates and three token offsets. The input is transposed to match PyTorch’s [batch, channels, positions] convention [5].

import torch
import torch.nn.functional as F

def feature_map(sentence):
    embeddings = [[word == "not", word == "good"] for word in sentence.split()]
    inputs = torch.tensor(embeddings, dtype=torch.float32).T.unsqueeze(0)
    # Conv1d weights are [output channel, input channel, window offset].
    kernel = torch.tensor([[[2., 0., -1.], [0., 1., 2.]]])
    raw = F.conv1d(inputs, kernel, bias=torch.tensor([-1.])).flatten()
    return raw, raw.relu()

raw, features = feature_map("This movie was not good at all")
assert raw.tolist() == [-1, -2, 1, 2, -1]
assert features.tolist() == [0, 0, 1, 2, 0]
_, swapped = feature_map("This movie was good not at all")
assert swapped.tolist() == [0, 1, 0, 0, 1]

Pooling a padded batch. Suppose every real token has scalar embedding 1, the pad embedding is 0, and a width-3 filter has weights [−1,−1,−1][-1,-1,-1] and bias 2. Every full window of three real tokens scores −1-1 and becomes zero after ReLU. Append two pads to five real tokens, however, and the final window [1,0,0][1,0,0] scores 1. A maximum over all allocated positions would reward padding.

The CPU classifier below accepts sequences padded on the right. Pass one true length per row. Without lengths, it treats every supplied position as real. A filter of width kk may pool only windows whose exclusive end i+ki+k is at most the true length. We choose a zero feature for any width that has no complete window. Padding slots must contain valid vocabulary IDs because the embedding lookup runs before masking. The example keeps the three filter banks and linear classifier, and omits pretrained vectors, dropout and training.

import torch
from torch import nn
import torch.nn.functional as F

class TextCNN(nn.Module):
    def __init__(self, vocab_size, embed_dim, num_classes):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, embed_dim)
        self.conv1 = nn.Conv1d(embed_dim, 100, kernel_size=3)
        self.conv2 = nn.Conv1d(embed_dim, 100, kernel_size=4)
        self.conv3 = nn.Conv1d(embed_dim, 100, kernel_size=5)
        self.fc = nn.Linear(300, num_classes)

    def forward(self, x, lengths=None):
        if x.ndim != 2 or x.size(0) == 0:
            raise ValueError("expected token IDs shaped [batch, positions]")
        batch, slots = x.shape
        if lengths is None:
            lengths = torch.full((batch,), slots, device=x.device)
        else:
            lengths = torch.as_tensor(lengths, device=x.device)
        if lengths.shape != (batch,) or lengths.dtype not in (torch.int32, torch.int64):
            raise ValueError("supply one integer length per example")
        if ((lengths < 0) | (lengths > slots)).any():
            raise ValueError("length outside the supplied sequence")

        embedded = self.embedding(x).transpose(1, 2)  # [batch, channels, slots]
        # Conv1d needs at least the filter width even when no real window fits.
        embedded = F.pad(embedded, (0, max(0, 5 - slots)))
        pooled = []
        for conv in (self.conv1, self.conv2, self.conv3):
            features = conv(embedded).relu()
            width = conv.kernel_size[0]
            starts = torch.arange(features.size(-1), device=x.device)
            complete = starts + width <= lengths[:, None]
            peak = features.masked_fill(~complete[:, None, :], -torch.inf).amax(dim=-1)
            pooled.append(torch.where(lengths[:, None] >= width, peak, 0.0))
        return self.fc(torch.cat(pooled, dim=1))

torch.manual_seed(7)
model = TextCNN(vocab_size=8, embed_dim=2, num_classes=2).eval()
ids = torch.tensor([[1, 2, 3, 4, 5]])
batch = torch.tensor([[1, 2, 3, 4, 5, 0, 0], [5, 4, 3, 2, 1, 6, 7]])
with torch.no_grad():
    torch.testing.assert_close(model(ids)[0], model(batch, lengths=[5, 7])[0])
    # Encode "on" as 1 and "off" as 2.
    logs = torch.tensor([[1, 2, 1, 2, 1, 2], [2, 1, 2, 1, 2, 1]])
    logits = model(logs)
    torch.testing.assert_close(logits[0], logits[1])

From local receptive fields to global attention

Could this classifier tell whether a switch ended on or off? Compare the six-token logs on off on off on off and off on off on off on. Each log has the same two width-5 windows, one starting with on and one with off. At widths 3 and 4 both starting patterns occur as well. Every filter in the classifier above therefore sees the same set of windows and returns the same maximum for both logs, whatever weights it learns. The final switch states differ. For this task, reading the last valid token would settle the question.

Stacking LL convolution layers of width kk and stride one, without dilation, gives each output a receptive field spanning 1+L(k−1)1+L(k-1) input positions. Dilation spaces filter taps farther apart. ByteNet used dilated convolutions for character-level translation [3]. WaveNet used causal dilated convolutions for autoregressive audio generation [4]. A one-layer TextCNN classifier instead aggregates local detections with global pooling. That lets a detection anywhere affect the label while losing its position.

Next steps

The next chapter studies self-attention, where each query can form a direct, content-dependent connection to any key its mask allows. Dense attention trades that reach for a quadratic number of pairwise scores.

Quizzes

Quiz 1: Why can one convolution layer evaluate its windows in parallel? Each window reads the same input tensor independently. A conventional RNN needs the previous hidden state before processing the next token. Parallelism does not determine measured latency on its own.

Quiz 2: Why do the windows “was not good” and “not good at” return different scores? The two cue words occupy different offsets. The first window scores 1 and the second scores 2 because each offset has its own weight row.

Quiz 3: Which positions can interact in one convolution layer and in one self-attention layer? A convolution combines positions within its filter’s receptive field. A self-attention query can read every key allowed by its mask.

Quiz 4: What information is lost when two windows tie for the maximum? The classifier receives the maximum once. Without separate position information it cannot tell whether one or several windows had that value, or where they occurred.

Quiz 5: Why can zero padding change logits after max-over-time pooling? A partial window can get a higher score from the remaining real embeddings and the bias. Mask windows that extend past the true length before taking the maximum.

Quiz 6: How does the receptive field change with depth and stride? Without dilation, start with R0=1R_0=1. Layer ll adds (kl−1)∏i=1l−1si(k_l-1)\prod_{i=1}^{l-1}s_i input positions to the span, where klk_l is its width and sis_i are the earlier strides. With constant width kk and unit strides this gives Rl=1+l(k−1)R_l=1+l(k-1).

References

  1. Kim, Y. (2014). Convolutional neural networks for sentence classification. EMNLP paper, §2–3.
  2. 3Blue1Brown. But what is a convolution?.
  3. Kalchbrenner, N., et al. (2016). Neural Machine Translation in Linear Time. Paper.
  4. van den Oord, A., et al. (2016). WaveNet: A Generative Model for Raw Audio. Paper.
  5. PyTorch. Conv1d operator and input shapes.