Skip to content

Language models, retrieval, prompting, and language adaptation · Long-context and retrieval-augmented language · LNG046 · Architecture

Longformer

Reduces attention cost for long documents using local windows plus selected global-attention positions. It is particularly useful for document classification and extractive question answering where a subset of tokens…

Explained here Component demo, not a trained model CodeSplash's own run

In CodeSplash

Documented in the Academy only. There's no Set up button.

Availability
Explained here
Code example
Component demo, not a trained model
Who ran it
CodeSplash's own run
CodeSplash's run
The reference's example ran in Python and R here, and they agree.
The reference's record
Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Reduces attention cost for long documents using local windows plus selected global-attention positions. It is particularly useful for document classification and extractive question answering where a subset of tokens should connect globally.

Question / objective

Can local attention plus a few global positions support long-document understanding?

Architecture / computational structure

A bidirectional encoder uses sparse local/global attention; task heads consume token or pooled states. Learned encoder/head weights are parameters; windows and global masks are task-level configuration choices.

Assumptions

Choosing global tokens is part of the model/task design.

Formula / computational definition

E={(i,j):∣i−j∣≤w}∪{(i,j):i∈G or j∈G},∣E∣=O(nw+n∣G∣).\mathcal E=\{(i,j):|i-j|\le w\}\cup\{(i,j):i\in G\ \text{or }j\in G\},\qquad |\mathcal E|=O(nw+n|G|).

Each token attends to nearby positions; designated global tokens attend to all positions and are attended by all tokens. With fixed window width w and few global tokens g, attention edges scale approximately as O(nw+ng) instead of n squared.

Parameters and notation

Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Per-layer attention window, global-token selection, maximum positions, padding alignment, and task-specific heads.

Fitting, fine-tuning, and adaptation

Fine-tune a classification or QA head, then unfreeze selected layers or use supported adapters. Choose global tokens based on the task without using hidden answer labels. Validate length-stratified quality, sparse-kernel execution, memory, and retention; nominal maximum length is not sufficient evidence.

How to use and calibrate

Compare document-length strata, relevant-span localization, memory use, runtime, and global-token ablations. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.

Example application

Extract answers from lengthy reports using globally connected question tokens.

Interpretation / pitfalls

Watch out

Sparse connectivity may miss required interactions, and theoretical sparsity does not guarantee speed if the implementation materializes dense matrices. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.

Python and R code examples

Full implementation route: Transformers supports Longformer and its attention-mask conventions; R can call the same implementation through reticulate. The native example builds its logical attention mask, intentionally dense for teaching rather than a scalable sparse kernel.

Example scope: Longformer local/global logical mask; dense teaching array, not sparse kernel execution.

Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.

Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — Longformer local/global logical mask; dense teaching array, not sparse kernel execution.

Shared setup for this chapter
import math

def softmax(xs):
    m = max(xs)
    es = [math.exp(x-m) for x in xs]
    return [e/sum(es) for e in es]

def dot(a, b):
    return sum(x*y for x, y in zip(a, b))

def matvec(matrix, vector):
    return [dot(row, vector) for row in matrix]

def meanvec(rows):
    return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]

def sigmoid(x):
    return 1/(1+math.exp(-x))

def nll(probabilities):
    return -sum(math.log(p) for p in probabilities)
n, radius, global_tokens = 6, 1, {0}
mask = [[int(abs(i-j)<=radius or i in global_tokens or j in global_tokens) for j in range(n)] for i in range(n)]
print(mask)
R

Component demo, not a trained model — Longformer local/global logical mask; dense teaching array, not sparse kernel execution.

Shared setup for this chapter
softmax <- function(x) {
  shifted <- exp(x-max(x))
  shifted/sum(shifted)
}
n <- 6L; radius <- 1L; global_tokens <- 0L
mask <- outer(0:(n-1),0:(n-1),function(i,j) as.integer(abs(i-j)<=radius | i %in% global_tokens | j %in% global_tokens))
print(mask)

Sources

From the CodeSplash reference, entry LNG046.