REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Isolate packed documents in causal attention

Packing several documents into one tensor improves utilization, but a causal triangle alone permits one document to read an earlier unrelated document.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Isolate packed documents in causal attention →

Your task

q,k,v have aligned nonempty [B,H,T,D] shapes. Long segments[B,T] assigns document identities or -1 padding. A query may see only earlier-or-equal positions with the same nonnegative document identity. Return differentiable attention output. Padded queries produce finite zero outputs and zero gradients. Block cross-document influence even when both documents share one row; reject invalid shapes or segment values below -1.

Starter

import torch


def packed_attention(q, k, v, segments):
    return None
Inspect the worked answer
import math
import torch


def packed_attention(q, k, v, segments):
    if q.ndim != 4 or q.shape != k.shape or k.shape != v.shape or min(q.shape) < 1:
        raise ValueError('aligned nonempty [B,H,T,D] tensors required')
    if segments.shape != (q.shape[0], q.shape[2]) or segments.dtype != torch.long or bool((segments < -1).any()):
        raise ValueError('integer document identities or -1 padding required')
    length = q.shape[2]
    same = segments[:, :, None] == segments[:, None, :]
    valid = (segments[:, :, None] >= 0) & (segments[:, None, :] >= 0)
    causal = torch.ones(length, length, dtype=torch.bool, device=q.device).tril()
    allow = (same & valid & causal)[:, None, :, :]
    active = allow.any(dim=-1, keepdim=True)
    scores = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])
    scores = scores.masked_fill(~allow, float('-inf'))
    scores = torch.where(active, scores, torch.zeros_like(scores))
    weights = torch.softmax(scores, dim=-1) * allow.to(scores.dtype)
    return weights @ v

About this algorithm

How Isolate packed documents in causal attention works

The idea

Short documents waste compute when each one is padded out to the length of a batch row, so training pipelines often pack several documents end to end in one row. A causal triangle alone is then not enough. The second document sits later in the row, so its tokens could read the first, unrelated document.

The fix is a second condition. segments gives every token a document id, or -1 for padding, and a query may attend to a key only if the key is not later, both are real tokens, and both carry the same id. Three boolean tables combined with & express exactly that. Padded queries end up with no allowed key and are handled so that they output zeros with finite zero gradients.

How it works

  1. Validate aligned nonempty [B, H, T, D] tensors and a long segments tensor of shape [B, T] with no value below -1.
  2. Compare segments with itself by broadcasting to get same, a [B, T, T] table of token pairs with equal ids.
  3. Build valid, true where both tokens have a nonnegative id, and causal, a lower-triangular matrix.
  4. Combine same & valid & causal and insert a head axis to get allow.
  5. Mask the scores with -inf, replace rows that have no allowed key with zeros, apply softmax and multiply by allow.
  6. Return weights @ v; padded queries come out as exact zeros.

What it costs

Time
O(B·H·T²·D)
Mask
O(B·T²) booleans
Benefit
fewer padded positions

Packing does not make attention cheaper per row; it fills rows with real tokens instead of padding, and the mask costs one boolean per token pair.

Where it is used

  • Graphcore's packed BERT ('Packing: Towards 2x NLP BERT Acceleration', Kosec et al., 2021) packs several sequences into one row and masks attention so they do not interact.
  • The flash-attn library's flash_attn_varlen_func takes cumulative sequence lengths so sequences concatenated in one buffer attend only within themselves.
  • PyTorch's scaled_dot_product_attention accepts a boolean attn_mask of this kind, broadcast across heads, in place of is_causal.

Watch out for

  • Relying on the causal triangle alone, which lets a later document in the row read every token of the earlier one.
  • Letting -1 match -1: padding tokens share an id, so without the valid term they would attend to each other.
  • Leaving a padded query with only -inf scores: softmax returns NaN for that row and backward() sends NaN into q, k and v.