AI Wiki中文/EN

Next-token prediction: boundaries are part of the target

下一词元预测

Build document-aware teacher forcing and check EOS, packing, token weighting and perplexity.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The last word still has a target

For a document containing tokens a b, a next-token training example can use inputs BOS a b and labels a b EOS. The last content token predicts the end of the document. BOS supplies a starting context; EOS is a predicted event. Dropping either boundary without explaining the convention changes the task.

The original GPT report trains a language model by predicting tokens from preceding context. T5 also uses autoregressive target prediction, although its target may be a transformed sequence conditioned on a separate source. “Next-token prediction” describes this ordered conditional operation; it does not say whether the tokens are words, subwords, bytes, class labels or sentinels. GPT T5

This chapter builds a document-aware data path and a small smoothed bigram baseline. A bigram model only sees the previous token, so it cannot model long context. That limitation is useful here: the probability table is small enough to check by hand, leaving boundaries, packing and evaluation visible.

Document boundaries, loss denominators and EOS each change what is counted; the displayed mask preserves independent examples.
Document boundaries, loss denominators and EOS each change what is counted; the displayed mask preserves independent examples.

Define the sequence being assigned probability

Let a document contain content tokens x1,…,xLx_1,\ldots,x_L and let xL+1x_{L+1} be EOS. A model with a BOS starting convention assigns:

pθ(x1,…,xL,EOS)=∏t=1L+1pθ(xt∣BOS,x<t). p_\theta(x_1,\ldots,x_L,EOS)=\prod_{t=1}^{L+1}p_\theta(x_t\mid BOS,x_{<t}).

A finite product gives the probability of one completed sequence. To define a normalized distribution over all finite documents, the generative process must also terminate with probability one. Locally normalized next-token probabilities alone do not guarantee that: a model that never emits EOS assigns no mass to completed sequences. Our smoothed finite-state example has a positive lower bound on EOS probability, which does ensure eventual termination.

For one observed document, teacher forcing constructs:

inputs=(BOS,x1,…,xL),labels=(x1,…,xL,EOS). \text{inputs}=(BOS,x_1,\ldots,x_L),\qquad \text{labels}=(x_1,\ldots,x_L,EOS).

The input at a prediction position is the previous token, not its own label. A causal attention mask then prevents access to later input positions that would reveal future labels. Read causal masking for why masking and shifting are separate requirements.

Several documents can share a storage row. If they are meant to remain independent training examples, add document segment IDs and allow attention only to earlier positions in the same segment:

Aij=1[j≤i] 1[doc⁡(i)=doc⁡(j)]. A_{ij}=\mathbf1[j\le i]\,\mathbf1[\operatorname{doc}(i)=\operatorname{doc}(j)].

The example supplies a separate BOS and EOS for every document. An EOS marker alone does not enforce this block structure: ordinary attention can still read tokens before that marker. Concatenating documents as one stream is another possible objective, but it is not identical to independent-document likelihood. T5 mentions packing examples for efficient batches; the explicit block mask here is our teaching convention, not a claim that we reproduced its packing implementation. T5, section 3.1.2

For a non-neural baseline, count transitions from context token aa to target token bb. Add positive smoothing α\alpha to each possible output:

p^(b∣a)=C(a,b)+α∑v∈VoutC(a,v)+α∣Vout∣. \widehat p(b\mid a)=\frac{C(a,b)+\alpha}{\sum_{v\in\mathcal V_{out}}C(a,v)+\alpha|\mathcal V_{out}|}.

Our content vocabulary contains IDs zero and one. BOS is an input-only context, while EOS is an output-only symbol. Both tables have three categories, but their third category means different things. The implementation explicitly maps the EOS ID to the last output column rather than treating it as an ordinary content token.

For evaluation documents dd with NdN_d predicted tokens, including EOS, the token-weighted mean is:

ℓ‾token=∑d∑t=1Nd−log⁡p(xdt∣xd,<t)∑dNd,ℓ‾doc=1D∑d1Nd∑t=1Nd−log⁡p(xdt∣xd,<t). \overline\ell_{\mathrm{token}}= \frac{\sum_d\sum_{t=1}^{N_d}-\log p(x_{dt}\mid x_{d,<t})}{\sum_d N_d}, \qquad \overline\ell_{\mathrm{doc}}=\frac1D\sum_d\frac1{N_d}\sum_{t=1}^{N_d}-\log p(x_{dt}\mid x_{d,<t}).

The second statistic gives every document equal weight, regardless of length. The first gives every predicted token equal weight. They answer different questions. With natural-log loss, token perplexity is:

PPL⁡=exp⁡(ℓ‾token). \operatorname{PPL}=\exp(\overline\ell_{\mathrm{token}}).

A perplexity value has meaning only with its tokenizer, evaluation corpus, context restriction and boundary convention. A lower value on a different tokenization is not automatically better compression of the same text or better downstream performance.

A small baseline exposes the bookkeeping

The original NumPy program fits add-one bigram probabilities to four artificial documents, then evaluates two held-out sequences. It constructs the block-causal mask even though the bigram baseline itself only uses the previous-token input. This keeps the packing rule inspectable before substituting an attention model.

"""Document-aware teacher forcing, smoothing baseline and loss aggregation."""
import itertools
import json
import numpy as np

BOS=2
EOS=3


def pack(documents):
    inputs=[];labels=[];segments=[]
    if not documents:raise ValueError('At least one document required')
    for j,doc in enumerate(documents):
        doc=list(doc)
        if not doc or any(t not in (0,1) for t in doc):raise ValueError('Nonempty binary documents required')
        inputs.extend([BOS]+doc);labels.extend(doc+[EOS]);segments.extend([j]*(len(doc)+1))
    segments=np.array(segments);n=len(inputs)
    allowed=(segments[:,None]==segments[None,:]) & (np.arange(n)[None,:]<=np.arange(n)[:,None])
    return np.array(inputs),np.array(labels),segments,allowed


def fit_bigram(documents,alpha=1.):
    if not np.isfinite(alpha) or alpha<=0:raise ValueError('Positive finite smoothing required')
    counts=np.full((3,3),alpha) # input0/1/BOS, output0/1/EOS
    x,y,_,_=pack(documents)
    for a,b in zip(x,y):counts[a,2 if b==EOS else b]+=1
    return counts/counts.sum(axis=1,keepdims=True)


def evaluate(probabilities,documents):
    p=np.asarray(probabilities,float)
    if p.shape!=(3,3) or not np.isfinite(p).all() or (p<=0).any() or not np.allclose(p.sum(axis=1),1):
        raise ValueError('Strictly positive normalized bigram rows required')
    x,y,segments,_=pack(documents)
    losses=-np.log(p[x,np.where(y==EOS,2,y)])
    means=[float(losses[segments==j].mean()) for j in range(len(documents))]
    token_mean=float(losses.mean())
    return dict(token_mean=token_mean,document_mean=float(np.mean(means)),per_document=means,
                tokens=len(y),perplexity=float(np.exp(token_mean)))


def completed_mass(p,max_tokens):
    # Include immediate EOS (empty generated document), despite nonempty training docs.
    if max_tokens<0:raise ValueError('Nonnegative truncation required')
    total=0.
    for n in range(max_tokens+1):
        for sequence in itertools.product([0,1],repeat=n):
            prob=1.;previous=BOS
            for token in sequence:prob*=p[previous,token];previous=token
            total+=prob*p[previous,2]
    return float(total)


def demo():
    train=[[0,1],[0,1],[1,0,1],[1]];test=[[0],[1,1,0]]
    p=fit_bigram(train)
    x,y,segments,allowed=pack(test)
    naive=np.tril(np.ones_like(allowed,dtype=bool))
    return dict(probabilities=p.tolist(),inputs=x.tolist(),targets=y.tolist(),segments=segments.tolist(),
                document_mask=allowed.astype(int).tolist(),cross_document_edges=int((naive & ~allowed).sum()),
                evaluation=evaluate(p,test),completed_mass=[completed_mass(p,n) for n in range(7)],
                scope='Add-one bigram baseline; counts include EOS; independent packed documents use separate BOS, segments and masks')


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

The held-out documents have one and three content tokens, so their prediction counts are two and four after EOS is included. The program returns token-average loss about 1.457308, document-average loss about 1.422863 and token perplexity about 4.294385. The values differ because the two document lengths and losses differ.

The packed row has eight cross-document edges that a plain lower triangle would allow. Its document-aware mask removes them. That is a visibility count, not eight observed model errors: the bigram predictor does not use those extra attention edges.

The program also enumerates completed sequences with at most zero through six content tokens. Their cumulative probability rises from about 0.142857 to 0.973560. The first value is immediate EOS from BOS, representing an empty generated document. Although training documents are nonempty, smoothing gives this event positive probability. The unenumerated mass belongs to longer outputs; it is not a normalization failure.

Count fitting is linear in the number of observed transitions plus the probability-table size. Building the dense mask costs quadratic time and memory in packed-row length. Enumeration is exponential in the maximum generated length, so it is used only for a tiny binary vocabulary. The tests also compare against a geometric termination distribution, avoiding reliance only on enumerating the program’s own table.

A convenient batch is not a neutral transformation

If the goal is independent documents, allowing one document to read another changes the conditioning information. Merely ignoring one boundary label may remove a loss term without removing that information path. Decide whether the intended objective is an independent-document model or a continuous stream, then align labels, visibility and evaluation with that choice.

Teacher forcing evaluates correct prefixes. Free-running generation conditions on the model’s own sampled tokens, so mistakes can move it into different contexts. This does not make the likelihood objective invalid, but it explains why held-out token loss alone does not describe an entire generated conversation.

The bigram baseline cannot exploit long-range syntax or source evidence. It is also trained on a deliberately tiny artificial corpus. Its scores are bookkeeping examples, not useful language-model benchmarks. A neural model should first be compared against a correctly evaluated baseline, then investigated for gains on a fixed task and dataset.

Count targets, not just content tokens

  1. Write the input and label sequences for content tokens 0 1, with a separate start context and a predicted ending.

Answer: Inputs are BOS 0 1; labels are 0 1 EOS. There are three predictions. BOS is not an output target in this convention.

  1. Fit add-one counts using only document 0 1. What probability does the resulting model assign to that completed document?

Answer: The probabilities of zero after BOS, one after zero and EOS after one are each one-half. Their product is one-eighth. The mean negative log loss over three predictions is log⁡2\log2, so perplexity is two.

  1. A model emits EOS with probability one-half in every context, otherwise choosing a binary content token. What mass lies in sequences with at most two content tokens?

Answer: The probability of surviving three successive opportunities to stop is (1/2)3(1/2)^3. Completed mass is therefore 1−(1/2)3=7/81-(1/2)^3=7/8, including the empty document.

  1. Does inserting EOS between two packed documents automatically stop a Transformer from reading the first while predicting the second?

Answer: No. EOS is a token, not an attention barrier. Independent examples require the corresponding visibility restriction and correctly aligned boundary targets. A stream objective may intentionally allow that context, but it should be named as such.

Make the evaluation unit reproducible

The original GPT objective supplies the causal likelihood framework. T5 illustrates how a different data transformation can feed an autoregressive target objective and how packing affects the training setup. Neither reference makes tokenizer choice or data boundaries disappear. GPT T5

A useful extension replaces the bigram table with a small recurrent or attention model while retaining the exact input/label generator and held-out documents. Report token counts, EOS policy, masks, sum of negative log probabilities and the averaging rule. Then a loss change can be traced to model behavior rather than an unnoticed denominator or boundary change.

Make a prediction, then check

How should independent documents packed in one row be separated?

Choose one answer

Learning objectives

  • Build document-aware teacher forcing and check EOS, packing, token weighting and perplexity.
  • Distinguish independent-document packing from a continuous-stream objective.
  • Explain why local normalization also needs termination to define probabilities over finite documents.

Prerequisites & connections

Explore related knowledge →

References

  1. Improving Language Understanding by Generative Pre-Training
    Alec Radford; Karthik Narasimhan; Tim Salimans; Ilya Sutskever · 2018
  2. 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

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked original GPT causal objective and T5 teacher forcing/packing description. Six paired equations and four explained exercises; BOS/EOS labels, independent-document mask, add-one bigram counts, token/document averaging and finite-sequence probability mass with termination. Not T5 packing code or a language benchmark; removed edges are not observed prediction errors.

  • Single AI author checked original GPT causal objective and T5 teacher forcing/packing description. Six paired equations and four explained exercises; BOS/EOS labels, independent-document mask, add-one bigram counts, token/document averaging and finite-sequence probability mass with termination. Not T5 packing code or a language benchmark; removed edges are not observed prediction errors.
  • 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.