AI Wiki中文/EN

T5: turn tasks and missing spans into text

T5

Implement sentinel span corruption, reconstruct the original, and count encoder and decoder tokens.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The answer need not look like the input

Suppose a toy training sentence is “a small robot carries two blue boxes home.” Hide “small robot” and “blue boxes.” One possible task asks the model to reproduce the entire sentence. Another asks it to write only the missing pieces, with markers telling us where each piece belongs. T5 uses the second arrangement for its span-corruption objective. This changes the training sequence, not just the name of the loss.

T5 means Text-to-Text Transfer Transformer. Its study places tasks within a shared text-input, text-output interface: a translation returns text, and a classification can return a label written as text. A shared interface does not make the tasks identical. The input formatting, permissible labels, training mixture and evaluation still matter. The original paper investigates architecture, objectives, data and transfer procedures rather than attributing the final results to one isolated change. T5

The relevant architecture is an encoder–decoder model: an encoder reads the available source, and an autoregressive decoder predicts a target sequence using that source and its earlier target tokens. This differs from predicting a masked token directly at an encoder position. BART also uses denoising with an encoder and decoder, but its reconstruction target is the original document. That distinction determines how many decoder tokens must be predicted. BART

The missing spans move into an ordered sentinel target; both source and target lengths can be checked from the actual tokens.
The missing spans move into an ordered sentinel target; both source and target lengths can be checked from the actual tokens.

Construct the example before writing the loss

Let an original sequence have length nn. Select mm tokens arranged into ss nonempty, nonadjacent spans. Adjacent spans should merge; otherwise two markers would represent a single uninterrupted gap. Replace each span with a distinct sentinel token. The target lists each sentinel followed by its missing span, then ends with one additional sentinel. Sentinels are vocabulary entries, not characters inserted after tokenization. T5, section 3.1.4

For our eight-token example, use sentinels S0,S1,S2S_0,S_1,S_2:

x=(a,small,robot,carries,two,blue,boxes,home),x~=(a,S0,carries,two,S1,home),y=(S0,small,robot,S1,blue,boxes,S2).\begin{aligned} x&=(a,small,robot,carries,two,blue,boxes,home),\\ \widetilde x&=(a,S_0,carries,two,S_1,home),\\ y&=(S_0,small,robot,S_1,blue,boxes,S_2). \end{aligned}

The sentinel convention makes reconstruction possible without guessing the missing span lengths. S0S_0 associates the first target segment with the first source gap, and S1S_1 does the same for the second. The final S2S_2 closes the list. An end-of-sequence token, when added by the training pipeline, is a separate item; the counts below exclude EOS and padding.

∣x~∣=n−m+s,∣y∣=m+s+1. |\widetilde x|=n-m+s,\qquad |y|=m+s+1.

The combined count therefore depends on the number of gaps as well as the original length:

∣x~∣+∣y∣=n+2s+1. |\widetilde x|+|y|=n+2s+1.

With n=8,m=4,s=2n=8,m=4,s=2, the encoder receives six tokens and the decoder predicts seven. This deliberately large corruption fraction makes the example legible; it is not the paper’s 15% recipe. In the paper’s illustrative budget, 75 of 500 tokens are corrupted across 25 spans. Our count gives 450 source tokens and 101 target tokens, before EOS. A shorter target can save work, but counting total tokens alone does not estimate a Transformer’s total cost: encoder self-attention, decoder self-attention and cross-attention have different sequence-length terms.

The decoder defines a conditional distribution over the target:

pθ(y∣x~)=∏t=1∣y∣pθ(yt∣y<t,x~). p_\theta(y\mid\widetilde x)=\prod_{t=1}^{|y|}p_\theta(y_t\mid y_{<t},\widetilde x).

Training commonly supplies the correct target prefix, called teacher forcing. The model must not read the current target token through an unshifted input. Whether the training loss is summed or averaged should be explicit:

L(x,M)=−1∣y∣∑t=1∣y∣log⁡pθ(yt∣y<t,x~). \mathcal L(x,M)=-\frac{1}{|y|}\sum_{t=1}^{|y|}\log p_\theta(y_t\mid y_{<t},\widetilde x).

Here MM describes the sampled corruption and yy is determined by x,Mx,M. The expectation over examples and corruptions defines the training objective. A fixed example verifies formatting; it does not reproduce training over that expectation.

A further distinction matters when reading the paper. Its baseline drops independently selected tokens and merges consecutive dropped positions. Its later span-corruption configuration deliberately controls span lengths. Section 3.7 adopts 15% corruption with mean span length three; do not describe every earlier baseline as already using that final configuration. T5, sections 3.1.4, 3.3.4 and 3.7

corruption fraction=mn,mean missing-span length=ms(s>0). \text{corruption fraction}=\frac{m}{n},\qquad \text{mean missing-span length}=\frac{m}{s}\quad(s>0).

A transform with an inverse

The following original program accepts prescribed spans, writes source and target lists, and reconstructs the original. It uses only Python’s standard library. It does not implement T5’s random-span sampler, tokenizer or neural network. Sentinel-looking input tokens are rejected so the inverse cannot confuse ordinary text with control markers.

"""Original sentinel transform and inverse; supplied spans, no T5 training."""
import json


def sentinel(i):
    return f'<extra_id_{i}>'


def encode(tokens, spans):
    tokens=list(tokens);spans=list(spans)
    if not tokens or any(not isinstance(t,str) or t.startswith('<extra_id_') for t in tokens):
        raise ValueError('Nonempty ordinary token sequence required')
    end=0
    for j,(a,b) in enumerate(spans):
        if not isinstance(a,int) or not isinstance(b,int) or not 0<=a<b<=len(tokens) or (j and a<=end):
            raise ValueError('Sorted disjoint nonadjacent spans required; merge adjacent spans')
        end=b
    source=[];target=[];previous=0
    for i,(a,b) in enumerate(spans):
        source.extend(tokens[previous:a]);source.append(sentinel(i))
        target.append(sentinel(i));target.extend(tokens[a:b]);previous=b
    source.extend(tokens[previous:]);target.append(sentinel(len(spans)))
    return source,target


def decode(source,target):
    source=list(source);target=list(target)
    markers=[t for t in source if t.startswith('<extra_id_')]
    if markers!=[sentinel(i) for i in range(len(markers))]:
        raise ValueError('Source sentinel order must be contiguous')
    k=len(markers)
    if not target or target[-1]!=sentinel(k):raise ValueError('Final target sentinel missing')
    parts={};cursor=0
    for i in range(k):
        if cursor>=len(target) or target[cursor]!=sentinel(i):raise ValueError('Target order mismatch')
        cursor+=1;start=cursor
        while cursor<len(target) and not target[cursor].startswith('<extra_id_'):cursor+=1
        if cursor==start:raise ValueError('Empty corrupted span')
        parts[sentinel(i)]=target[start:cursor]
    if cursor!=len(target)-1:raise ValueError('Unexpected target content')
    return [v for t in source for v in parts.get(t,[t])]


def length_budget(n,missing,spans):
    if not all(isinstance(x,int) for x in (n,missing,spans)) or not 0<=missing<=n or not 0<=spans<=missing:
        raise ValueError('Invalid lengths')
    if (missing==0)!=(spans==0) or n-missing<max(0,spans-1):raise ValueError('Impossible nonadjacent spans')
    return dict(source=n-missing+spans,target=missing+spans+1,total=n+2*spans+1)


def demo():
    original='a small robot carries two blue boxes home'.split()
    spans=[(1,3),(5,7)]
    source,target=encode(original,spans)
    return dict(original=original,source=source,target=target,recovered=decode(source,target),
                selected_positions=[1,2,5,6],lengths=length_budget(8,4,2),
                paper_example_lengths=length_budget(500,75,25),
                scope='Prescribed spans and final sentinel; lengths exclude EOS and padding; not the T5 random-span sampler')


if __name__=='__main__':
    print(json.dumps(demo(),indent=2))

The result contains source length 6 and target length 7. For the 500-token budget, it returns 450 and 101. The reconstruction must recover the exact original list, including repeated words: the algorithm matches sentinels, not word contents.

For nn input tokens and ss spans, construction and reconstruction take O(n+s)O(n+s) time and output-sized memory. Bounds, sorted order and nonadjacent spans are checked before construction. The inverse rejects missing final markers, reordered markers, empty spans and trailing target material. These are format checks, not evidence that a generated span is semantically correct.

The accompanying tests enumerate all 32 subsets of a five-token sequence, merge each into spans, reconstruct every case and verify the length formula. No selected tokens produces the original source and a final sentinel alone under this toy convention; selecting everything produces one gap. Real data pipelines may exclude these extremes.

A text interface still needs a task definition

Writing a class name as output text does not remove choices about label spelling, aliases or invalid responses. A classifier evaluated by exact label matching needs those rules fixed before evaluation. For an open-ended task, exact string matching can miss equivalent answers. The interface unifies how the model receives and emits data; it does not supply one universal metric.

Likewise, a reversible corruption transform is a data-processing baseline. It proves that the target identifies the removed material, not that a model can infer it. If a source provides no clues, multiple completions remain plausible. A useful model should assign probabilities accordingly; a reconstruction benchmark with one reference does not exhaust all acceptable text.

BART’s text infilling replaces each selected span with one mask and reconstructs the original document. Its paper describes Poisson-distributed span lengths, including zero-length spans that insert masks. Our T5-style transform requires nonempty spans and distinct sentinels. Substituting one procedure for the other changes both the input and the target. BART, section 2.2

Predict the sequence before running it

  1. For tokens a b c d e f, hide positions 1–2 and position 4, using zero-based indices. Write both sequences.

Answer: The source is a S0 d S1 f. The target is S0 b c S1 e S2. Their lengths are 5 and 6; reinserting the two spans recovers all six tokens.

  1. Corrupt 75 of 500 tokens in 25 spans. What changes if the same 75 tokens occupy only 15 valid spans?

Answer: Source/target lengths change from 450/101 to 440/91. The combined length falls from 551 to 531 because ten fewer gaps remove ten source sentinels and ten target sentinels. This does not by itself quantify training speed.

  1. Does predicting only the missing tokens mean that the decoder cannot use an earlier missing token?

Answer: No. The target is autoregressive. During teacher forcing, later missing tokens can condition on earlier correct target tokens, including earlier tokens within the same span. This differs from independent predictions at simultaneously masked encoder positions.

  1. Why does the implementation reject adjacent spans (1,3) and (3,5)?

Answer: They represent one continuous missing interval. Merging them into (1,5) gives one sentinel and preserves the intended span-count convention. Keeping two would change the target length and its markers despite hiding the same tokens.

Read the configuration alongside the result

T5’s study separates a baseline, controlled variants and a final combined configuration. Its span-length comparison does not establish that length three is best for every tokenizer, language or compute budget. A useful replication fixes the corruption unit, actual token budget, EOS handling and evaluation before changing span lengths. T5

For a small follow-up project, compare the sentinel target with full-document reconstruction on the same synthetic distribution. Keep the source corruption fixed, report target lengths and conditional losses separately, and use a held-out set of combinations. Such a test can expose the computational and information differences without claiming to reproduce T5 or BART quality. BART

Make a prediction, then check

What does the T5 span-corruption target contain?

Choose one answer

Learning objectives

  • Implement sentinel span corruption, reconstruct the original, and count encoder and decoder tokens.
  • Distinguish the baseline independent-token corruption from the final span-corruption recipe.
  • Compare sentinel targets with full-document reconstruction and state the EOS counting convention.

Prerequisites & connections

Explore related knowledge →

References

  1. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer
    Colin Raffel; Noam Shazeer; Adam Roberts; Katherine Lee; Sharan Narang; Michael Matena; Yanqi Zhou; Wei Li; Peter J. Liu · 2020
  2. BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension
    Mike Lewis; Yinhan Liu; Naman Goyal; Marjan Ghazvininejad; Abdelrahman Mohamed; Omer Levy; Ves Stoyanov; Luke Zettlemoyer · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author additionally read T5 text interface2.4, training3.1.2, objective3.1.4, span3.3.4 and final recipe3.7; BART2.2 provides a different reconstruction target. Six paired equations and four explained exercises; exact sentinel transform/inverse, all32 five-token mask subsets and token budgets excluding EOS. Supplied spans, not T5 random sampling or neural training.

  • Single AI author additionally read T5 text interface2.4, training3.1.2, objective3.1.4, span3.3.4 and final recipe3.7; BART2.2 provides a different reconstruction target. Six paired equations and four explained exercises; exact sentinel transform/inverse, all32 five-token mask subsets and token budgets excluding EOS. Supplied spans, not T5 random sampling or neural training.
  • Four computed SVG variants per topic. Fifteen numeric/geometry tests and42 responsive cases passed; fourteen final Chinese-mobile/English-desktop screenshots actually inspected. Initial English mobile-heading clipping and corrections preserved. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.