Foundations to Frontier
Tests
E. Deep Learning › E12 Transformer Architectures

XLNet

XLNet (Yang and colleagues, NeurIPS 2019) combines the strengths of autoregressive and masked language models with permutation language modelling. Each training sequence is factorised in a random order and every token is predicted from the tokens before it in that order. In expectation every token learns from context on both sides, without [MASK] tokens and without assuming masked tokens are independent. Two-stream self-attention lets the model know which position it predicts without seeing that token's content, and Transformer-XL's recurrence handles long text. This page covers the permutation objective, two-stream attention and partial prediction. In the exercises you implement factorisation-order masks, then train one two-stream layer on mirrored sequences. Left-to-right training and permutation training both reach the left-context ceiling (0.603 and 0.604), but only the permutation-trained model uses context from both sides (1.000 against 0.583).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Reading in a random order

A left-to-right model predicts each word from the words before it, so it never learns to use the words after. BERT uses both sides but practises on artificial [MASK] tokens. XLNet shuffles the order in which it predicts the words of each sentence: sometimes the last word is predicted first, sometimes the third word last. Over many shuffles, every word learns from words on both sides, while the training stays a genuine “predict the next one” task. The demo shows how the attention mask decides who sees whom.

Transformer lab
Computed pairs: 136 of 256 for 16 tokens. Sparse patterns grow linearly with length instead of quadratically.
Why engineers care

Ordering and masking choices decide what context a model can use. The same idea lets one model fill gaps in sequences in any order, as in infilling code or reconstructing missing sensor samples.

📝 Quick check (Level 0)
0/3 answered
  1. 1. XLNet predicts tokens in…
  2. 2. XLNet avoids…
  3. 3. Over many orders each token learns from…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Permutation LM:
    • maximise E over orders z of Σₜ log p(x(zₜ) | x(z₁), …, x(zₜ₋₁));
    • the order changes only the attention mask: positions are kept, and tokens are not physically shuffled.
  • Masks:
    • position j may see the content of k if k precedes j in the order;
    • for the order (2, 0, 1), position 0 sees 2, position 1 sees 0 and 2, and position 2 sees nothing;
    • the identity order gives the ordinary left-to-right (strictly causal) mask;
    • with L tokens there are L! orders (120 for L = 5), and a position sees on average (L − 1)/2 others.
  • Two-stream attention:
    • to predict x_j, the model must know the target position j but must not see x_j;
    • the query stream g carries position only, and the content stream h carries tokens;
    • g attends to the content of earlier tokens in the order, while h (which may see its own token) feeds later layers.
  • Partial prediction: only the last ⌈L/K⌉ tokens of each order are predicted (K about 6–7), since early tokens have too little context. For L = 512 and K = 6 that is 86 tokens.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Orders of 5 tokens:
  2. 2. The identity order gives…
  3. 3. The query stream carries…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

XLNet in code

Exercise 1.

  • Order masks matched the definition.
  • The average visible count over random orders of 10 tokens equalled (L − 1)/2 = 4.5.
  • Partial prediction kept the last ⌈L/K⌉ positions.

Practice.

  • Hugging Face XLNetLMHeadModel takes perm_mask (who may see whom) and target_mapping (which positions to predict) to express orders.
  • XLNet uses Transformer-XL’s relative positions and segment recurrence (E12-11), and a relative segment encoding for sentence pairs.
  • Cost: two streams double some computation, and permutation training converged more slowly than MLM. RoBERTa (E12-5) later matched XLNet with plain MLM and better training, so XLNet is less used today.
order = torch.randperm(L)
rank = torch.empty(L, dtype=torch.long); rank[order] = torch.arange(L)
perm_mask = (rank[None, :] >= rank[:, None]).float()           # 1 = may NOT see (XLNet's convention)
target_mapping = torch.zeros(n_pred, L); target_mapping[torch.arange(n_pred), order[-n_pred:]] = 1
out = model(input_ids, perm_mask=perm_mask[None], target_mapping=target_mapping[None])
🐍 Exercise 1: factorisation orders
Build order masks, count orders, choose predicted positions and check the expected number of visible tokens.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Hugging Face's XLNet argument for visibility:
  2. 2. XLNet's backbone:
  3. 3. A model that later matched XLNet with plain MLM:

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

What permutation LM fixes.

  • Masked LM:
    • predicts masked tokens independently given the visible ones, so it cannot model dependencies between masked tokens (for example two words of “New York” both masked);
    • uses an artificial [MASK] token absent at fine-tuning.
  • Left-to-right LM: has neither problem but sees only one side.
  • Permutation LM: is a proper autoregressive factorisation for every order, so the joint probability is modelled exactly. Averaging over orders gives each token context from all subsets of the others.

Why two streams.

  • With one stream, the representation at position j either includes x_j (making prediction trivial) or excludes it (and then cannot be used as context for later tokens).
  • Two streams resolve this: g_j predicts x_j without seeing it, and h_j, which includes x_j, serves as context.
  • Exercise 2 uses a one-layer version: queries from position embeddings, keys and values from content.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Masked LM assumes masked tokens are…
  2. 2. Permutation LM is, for every order,…
  3. 3. One stream fails because the representation would either…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Does a random order teach bidirectional context?

History.

  • Z. Yang, Z. Dai, Y. Yang, J. Carbonell, R. Salakhutdinov and Q. Le, “XLNet: generalized autoregressive pretraining for language understanding” (NeurIPS 2019).
  • XLNet outperformed BERT on 20 tasks at release.
  • Order-agnostic training was earlier explored in NADE-style models (Uria et al., 2014).

Exercise 2.

  • Data: mirrored sequences (12 tokens, vocabulary 8), where each token’s partner sits on the opposite side.
  • Model: one two-stream attention layer (gradients checked numerically), trained for 400 steps with either the left-to-right order always or a random order per sequence.
  • Evaluation: each model predicts every token with left context only, or with all other tokens visible.
training left context only all other tokens
left-to-right 0.603 0.583
permutation 0.604 1.000
  • Both reach the left-context ceiling of 0.602: second-half tokens see their partner, while first-half tokens must guess.
  • Only permutation training learned to use context on the right. Given every other token, it fills in perfectly, while the left-to-right model does no better than with left context, since it never saw right context in training.
  • This is the bidirectionality XLNet gets without [MASK] tokens. Each random order shows a token a different subset of its neighbours.
🐍 Exercise 2 (research): does a random order teach bidirectional context?
Train a two-stream attention layer with left-to-right or random factorisation orders and test with left or full context.

XLNet in AI, robotics and aerospace

  • Infilling: order-agnostic models fill gaps in sequences (missing telemetry samples, code) using context on both sides.
  • Flexible generation: choosing generation order (most confident first) can help structured outputs such as plans or schedules.
  • Model choice: today, MLM encoders or decoder LMs with infilling objectives are usually simpler. XLNet’s ideas survive in fill-in-the-middle training.

References

  1. Z. Yang et al. (2019). “XLNet: generalized autoregressive pretraining for language understanding.” Proc. NeurIPS.
  2. B. Uria, I. Murray, H. Larochelle (2014). “A deep and tractable density estimator.” Proc. ICML.