Autoregressive Span Infilling Pretraining: Principles, Implementation, and Cloud Deployment Guide

    This article explains autoregressive span infilling pretraining, a unified objective that combines context understanding with sequential generation by masking contiguous spans and reconstructing them token by token. It covers how the objective differs from unidirectional autoregression and bidirectional masked language modeling, the core mechanisms (loss formulation, two-dimensional positional encoding, and hybrid attention masks), and a runnable minimal implementation with data construction, forward pass, loss computation, and a smoke test. It also provides engineering configuration guidance, memory and throughput estimation, a cloud deployment checklist covering resources, monitoring, cost, and security, and pre-/post-training checklists for evaluation and troubleshooting.

    1. Boundaries and Positioning: Why Autoregressive Infilling

    In large-scale pretraining, common objectives fall into three categories: unidirectional autoregression, bidirectional masked language modeling, and hybrid reconstruction objectives. Unidirectional autoregression predicts token by token from left to right. It has strong generation ability, but during training it makes limited use of the right-side context. Bidirectional masked models understand context more fully, but their predictions at each masked position are relatively independent and are generally not directly suitable for high-quality free-form generation.

    The core motivation of autoregressive infilling pretraining is to obtain both understanding and generation ability within a single unified objective: randomly mask several contiguous spans in the text, then have the model reconstruct the masked content span by span in token order. This way, the query at a masked position can simultaneously see the visible context on both the left and right sides, forming infilling-style bidirectional understanding; and while generating the masked content, it still follows a left-to-right autoregressive process, thereby preserving generation ability.

    A boundary must be emphasized here: the “bidirectional understanding” referred to in this article means that the query at a masked position can access the visible context on both sides. It does not mean that the context region itself also uses bidirectional self-attention. If the context region still follows causal visibility, the overall model remains a hybrid structure of “unidirectional generation plus infilling-style context access.” If an implementation instead makes the context region bidirectionally visible as well, this should be stated separately, and information leakage and training stability should be re-evaluated.

    Autoregressive infilling is suitable for general-purpose language model scenarios that require both understanding and generation, such as text completion, summarization, rewriting, classification assistance, and dialogue generation. It does not promise to unconditionally outperform all pretraining objectives; its value lies in introducing contiguous-span generation ability at relatively low cost, so that the model encounters both understanding-type and generation-type tasks during the pretraining stage.

    For span length and masking ratio, the following decision rules are recommended:

    • Span length: the minimum length should be no less than 2, with a common range of 1 to 16 and a mean that can be set to 6 to 10. Too short makes the task too easy, while too long degenerates into ordinary generation.
    • Masking ratio: recommended to be kept between 15% and 25%. Too low provides insufficient information gain; too high leaves insufficient conditioning context.
    • Context retention ratio: retain at least 75% to ensure the model has enough context for conditioning.
    • Number of spans: the minimal implementation suggests 1 to 4. Too many spans compress the context, increasing difficulty and reducing parallelism.
    • Long-document scenarios: the number of spans and the sequence length can be increased appropriately, but span-level loss, context utilization, and memory usage should be monitored in tandem.

    2. Comparing the Three Pretraining Objectives and Positioning Relative to Adjacent Methods

    Objective type Generation ability Context usage Training parallelism Suitable scenarios
    Unidirectional autoregression Strong Mainly uses left-side context Probabilities can be computed in parallel during training Dialogue, continuation, free generation
    Bidirectional masked language modeling Weaker Can use both left and right context simultaneously Masked positions are relatively independent Classification, retrieval, understanding tasks
    Autoregressive infilling Fairly strong Masked positions can access both left and right context Autoregressive within each span; multiple spans processed in parallel or sequentially General-purpose models that balance understanding and generation

    Compared with adjacent methods, SpanBERT emphasizes span-level masking and span prediction and is often used for sentence-pair or span understanding; UL2 improves generality through mixed denoising objectives; T5 adopts span corruption and a seq2seq structure that separates input from output. The differentiated positioning of autoregressive infilling is that it preserves autoregressive generation ability within contiguous spans while allowing span queries to access the visible context on both sides, and it uses two-dimensional positional encoding to distinguish the original sequence position from the within-span generation progress.

    3. Breaking Down the Core Mechanisms

    3.1 Objective, Input Masking, and Loss Function

    Given a token sequence of length seq_len, randomly select several non-overlapping contiguous intervals as the masked spans. The unmasked tokens serve as the visible context. For the j-th masked span, let its target tokens be:

    y_j = (x_a, x_{a+1}, ..., x_{b-1})

    The training objective is to maximize the likelihood of the tokens within each span:

    L = - Σ_j Σ_t log P(y_{j,t} | C, y_{j,<t})

    where C denotes the visible context and y_{j,<t} denotes the tokens in the current span that precede t.

    The input replacement and masking rules for masked spans must be made explicit here. The recommended approach is:

    1. During the offline data construction stage, replace all masked span positions with a unified mask token, for example MASK_ID. At the same time, store the true labels and the span loss mask loss_mask.
    2. During the teacher-forcing training stage, the interior of the span cannot remain fully masked, or the model would be unable to use the true prefix to predict the next token. The teacher-forcing prefix inside the span must be restored: if the span length is m, then the first m-1 input positions of the span are filled in order with the true prefix y_0, ..., y_{m-2}, while the last span position may keep MASK_ID.
    3. During inference or free generation, all span positions keep MASK_ID, and the model generates token by token in an autoregressive manner.

    The key to this approach is avoiding two extremes: first, you must not feed the true span tokens to the model without any masking, or the context or the span itself may see the target, causing leakage; second, you must not keep only the fully masked input, or the within-span prefix would be missing and teacher forcing would not hold.

    In teacher-forcing training, the model uses the true preceding tokens as input to predict the next token. Therefore, the logits and labels must be shifted: the output at position i-1 predicts the label at position i. If a span starts at position a, then the prediction of the first span token depends on the context at position a-1; if a=0, you need to introduce BOS or ensure the span has at least one context token before it.

    To simplify the boundary condition, it is recommended to uniformly add BOS during data construction. After adding BOS, an original sequence span (a, b) becomes (a+1, b+1) in model coordinates. This way, even if the original span starts at 0, the first span token can still be predicted from the logits at the BOS position.

    3.2 Two-Dimensional Positional Encoding

    A standard language model usually uses only one-dimensional positional encoding, representing the order of tokens in the original sequence. Autoregressive infilling needs to distinguish “the original sequence position” from “the within-span generation progress,” so two-dimensional positional encoding is often introduced.

    • First dimension pos1: identifies the token’s true position in the original sequence, used to maintain the global order of the context.
    • Second dimension pos2: identifies the token’s relative position within the current masked span, used to guide within-span autoregressive generation.

    The specific rules are:

    • For visible context tokens, pos2 is uniformly set to zero.
    • For tokens within a masked span, pos2 increments starting from 0.
    • In multi-span scenarios, pos2 for each span resets independently to avoid interference between within-span positions of different spans.
    • If BOS is added, you can set pos1=0, pos2=0 for BOS separately, or keep a special positional embedding.
    • If you need to distinguish which span a token comes from, you can additionally add span-type or span-index embeddings, but this is not a required item for the minimal implementation.

    Two-dimensional positional encoding is usually integrated in one of two ways:

    1. Addition: token_embedding + pos1_embedding + pos2_embedding. This is simple to implement and suits most Transformer encoders.
    2. Concatenation: encode pos1 and pos2 separately, then concatenate them and map them back to the hidden dimension through a linear layer. This has stronger expressive power but adds a small amount of parameters and computation.

    In either case, the key is to ensure that pos1 still anchors the original sequence position while pos2 only serves as a supplementary signal for within-span progress. For the visible context, pos2=0, avoiding meaningless within-span progress.

    3.3 Hybrid Attention Mask: Single-Span and Multi-Span

    The key to implementing “a span can see the left and right context, while generation within the span proceeds in order” is the attention mask. The default recommended rules are:

    • Within the context region, visibility is causal: each context token can only attend to itself and the context tokens that already appeared to its left.
    • Context tokens cannot attend to any masked span, to prevent target leakage.
    • Tokens within a masked span can attend to all visible context, including both the left context and the right context.
    • Within a masked span, visibility is autoregressive: the current token can only attend to tokens to its left within the same span, and it must include itself, i.e., k <= q.
    • Multiple spans are independent by default: the current span cannot attend to other masked spans.

    It must be emphasized here that the visible range of the span region cannot be written only as for k in range(a, q); it should be written as k <= q or equivalent logic. The reason is that the Transformer’s self-attention query needs to see the token representation at the current position. If self-exclusion is applied, the input embedding of the current span token cannot fully enter the representation at the current position, which breaks the behavior of “predicting the next token based on the current prefix” under teacher forcing and may cause abnormal training or results that deviate from expectations.

    The visibility in the single-span case is illustrated below:

    Query region Left context Right context Current span
    Left context Only sees its own left context Not visible Not visible
    Right context Visible Only sees its own left context Not visible
    Current span Visible Visible Only itself and its left

    The following is a more intuitive example of the mask matrix. Assume the model coordinates are 0 to 6, where 0 is BOS, 1 and 2 are the left context, 3 and 4 are the masked span, and 5 and 6 are the right context. The span is (3, 5).

    query can see key 0 1 2 3 4 5 6
    0 1 0 0 0 0 0 0
    1 1 1 0 0 0 0 0
    2 1 1 1 0 0 0 0
    3 1 1 1 1 0 1 1
    4 1 1 1 1 1 1 1
    5 1 1 1 0 0 1 0
    6 1 1 1 0 0 1 1

    Here 1 means visible. You can see that:

    • Context queries cannot see the span positions 3 and 4.
    • Span queries can see all visible context, including the right context at 5 and 6.
    • Within the span, self-visibility is included: position 3 can see itself, and position 4 can see 3 and itself.
    • The right context still accesses the visible context causally and cannot access the span.

    In multi-span scenarios, you additionally need a column for “other masked spans.” In the default implementation, other spans are invisible to all queries. This ensures each span is trained independently, improving parallelism and avoiding answer leakage between spans. If the business wants to generate multiple contiguous gaps within a long text and have a later span reference an earlier one, the mask can be changed to sequential generation: span j can attend to the generated content of spans <j but not to the content of spans >j. This sequential generation reduces inter-span parallelism and requires more complex teacher-forcing input construction.

    4. Key Implementation Points: Runnable Pseudocode and Smoke Test

    The following is a conservative minimal implementation. The example is suitable for first verifying correctness and then gradually scaling up. The recommended runtime is Python 3.10 or higher and PyTorch 2.1 or higher. The example does not depend on external frameworks and only relies on random, torch, and torch.nn.functional.

    1. import random
    2. import torch
    3. import torch.nn.functional as F
    4. random.seed(0)
    5. # Example vocabulary: replace with the real tokenizer's vocab size during actual training
    6. VOCAB_SIZE = 1002
    7. MASK_ID = 1000
    8. BOS_ID = 1001
    9. def sample_span_len(min_span_len, max_span_len):
    10. # Can be replaced with log-normal, uniform, or another distribution
    11. return random.randint(min_span_len, max_span_len)

    4.1 Data Construction

    Data construction must ensure: spans do not overlap; the total masking ratio does not exceed the threshold; at least 75% of the visible context is retained; span length is neither too short nor too long; and enough context is kept between spans.

    1. def build_infilling_sample(
    2. token_ids,
    3. seq_len=64,
    4. p_start=0.1,
    5. max_spans=3,
    6. min_span_len=2,
    7. max_span_len=6,
    8. max_mask_ratio=0.25
    9. ):
    10. assert len(token_ids) >= seq_len
    11. assert 0 < max_mask_ratio < 0.5
    12. tokens = list(token_ids[:seq_len])
    13. # 1. Sample non-overlapping spans in the original coordinates
    14. spans = []
    15. span_mask = [0] * seq_len
    16. masked_count = 0
    17. i = 0
    18. while i < seq_len and len(spans) < max_spans:
    19. if span_mask[i] == 0 and random.random() < p_start:
    20. length = sample_span_len(min_span_len, max_span_len)
    21. length = min(length, seq_len - i)
    22. if length > 0 and masked_count + length <= int(max_mask_ratio * seq_len):
    23. a, b = i, i + length
    24. spans.append((a, b))
    25. span_mask[a:b] = [1] * length
    26. masked_count += length
    27. i = b
    28. continue
    29. i += 1
    30. # 2. Smoke-test fallback: force one valid span if none was sampled
    31. if not spans:
    32. length = max(1, min(max_span_len, int(max_mask_ratio * seq_len)))
    33. spans = [(0, length)]
    34. # 3. Add BOS and convert to model coordinates
    35. model_len = seq_len + 1
    36. masked_input = [MASK_ID] * model_len
    37. masked_input[0] = BOS_ID
    38. for idx, tok in enumerate(tokens, start=1):
    39. masked_input[idx] = tok
    40. labels = [-100] * model_len
    41. loss_mask = [0] * model_len
    42. model_spans = []
    43. for a, b in spans:
    44. ma, mb = a + 1, b + 1
    45. model_spans.append((ma, mb))
    46. for p in range(ma, mb):
    47. labels[p] = tokens[p - 1]
    48. loss_mask[p] = 1
    49. masked_input[p] = MASK_ID
    50. # 4. Teacher-forcing input:
    51. # Restore the real prefix for the first m-1 positions in each span,
    52. # and keep the last span position as MASK_ID.
    53. teacher_input = masked_input.copy()
    54. for ma, mb in model_spans:
    55. m = mb - ma
    56. for t in range(m - 1):
    57. teacher_input[ma + t] = labels[ma + t]
    58. return teacher_input, labels, loss_mask, model_spans

    The core boundaries of this step are:

    • In the offline samples, all span positions should be replaced with MASK_ID.
    • During teacher forcing, the within-span prefix must be restored, otherwise the within-span autoregressive conditional probability cannot be modeled.
    • If a span starts at position 0, you must rely on BOS or assert a > 0.
    • If a span length is 1, that span can keep its mask in the teacher-forcing input, and its target is predicted from the preceding context position or BOS.

    4.2 Building the Mask and Two-Dimensional Positions

    1. def build_positions_and_mask(model_len, spans):
    2. in_span = [False] * model_len
    3. pos2 = [0] * model_len
    4. for a, b in spans:
    5. for q in range(a, b):
    6. in_span[q] = True
    7. pos2[q] = q - a
    8. visible = [i for i in range(model_len) if not in_span[i]]
    9. # attn[q][k] = True means query q can attend to key k
    10. attn = [[False] * model_len for _ in range(model_len)]
    11. # Context region: causal visibility, cannot see any span
    12. for q in visible:
    13. for k in visible:
    14. if k <= q:
    15. attn[q][k] = True
    16. # Span region: can see all context; within the span, itself and left tokens are visible
    17. for a, b in spans:
    18. for q in range(a, b):
    19. for k in visible:
    20. attn[q][k] = True
    21. for k in range(a, b):
    22. if k <= q:
    23. attn[q][k] = True
    24. return pos2, attn

    If multi-span sequential generation is used, you can add a “visible preceding spans” rule for each span in the above logic. The default version does not recommend this, because it sacrifices inter-span parallelism.

    4.3 Forward Pass

    1. def forward(model, input_ids, model_len, pos2, attn):
    2. input_ids = torch.tensor(input_ids, dtype=torch.long).unsqueeze(0)
    3. # In the minimal implementation, continuous positions are fine;
    4. # in production, build pos1 from the original sequence coordinates
    5. pos1 = torch.arange(model_len, dtype=torch.long).unsqueeze(0)
    6. pos2 = torch.tensor(pos2, dtype=torch.long).unsqueeze(0)
    7. # Adjust dimensions per the specific model; the common form requires [B, 1, L, L]
    8. attn_mask = torch.tensor(attn, dtype=torch.bool).unsqueeze(0).unsqueeze(0)
    9. logits = model(
    10. input_ids=input_ids,
    11. pos1=pos1,
    12. pos2=pos2,
    13. attn_mask=attn_mask
    14. )
    15. return logits

    In engineering practice, you should ensure that attn matches the mask semantics of the model implementation. Common errors include: inverting the boolean mask, swapping the row and column directions, wrongly masking context outside spans, wrongly allowing full visibility inside spans, and span tokens not including self-visibility.

    4.4 Loss Computation

    1. def compute_loss(logits, labels, loss_mask):
    2. shift_logits = logits[..., :-1, :]
    3. shift_labels = torch.tensor(labels[1:], dtype=torch.long)
    4. shift_mask = torch.tensor(loss_mask[1:], dtype=torch.float)
    5. loss = F.cross_entropy(
    6. shift_logits.reshape(-1, VOCAB_SIZE),
    7. shift_labels.reshape(-1),
    8. ignore_index=-100,
    9. reduction="sum"
    10. )
    11. denom = shift_mask.sum()
    12. assert denom > 0, "No valid span target token in the current batch"
    13. return loss / denom

    The keys here are:

    • labels keeps the true token only at masked span positions and is -100 elsewhere.
    • loss_mask is 1 only at masked span positions, used for normalization.
    • Under teacher forcing, the logits and labels must be shifted.
    • If a span starts at position 0, you need BOS or special handling, otherwise the first span token lacks left context.
    • The meaning of shift_mask is: if loss_mask[p] = 1 means that the true token at model position p is a span target, then after shifting shift_mask[p-1] = 1, meaning that the logits at position p-1 are responsible for predicting that target.
    • If BOS is used and the original span starts at 0, the model coordinate becomes 1, and the first span target is predicted from the BOS logits at position 0, completing the boundary.
    • If BOS is not used, you should add an assertion that all span start positions satisfy a > 0, otherwise discard the sample or handle it separately.

    4.5 Smoke Test

    1. def smoke_test():
    2. tokens = [random.randrange(0, MASK_ID) for _ in range(32)]
    3. input_ids, labels, loss_mask, spans = build_infilling_sample(
    4. token_ids=tokens,
    5. seq_len=32,
    6. p_start=0.2,
    7. max_spans=2,
    8. min_span_len=2,
    9. max_span_len=5,
    10. max_mask_ratio=0.25
    11. )
    12. pos2, attn = build_positions_and_mask(len(input_ids), spans)
    13. assert len(input_ids) == len(labels) == len(loss_mask)
    14. assert len(pos2) == len(attn) == len(input_ids)
    15. assert any(x != -100 for x in labels)
    16. assert any(mask == 1 for mask in loss_mask)
    17. # Every query should at least see itself, ensuring complete within-span autoregressive representations
    18. for q in range(len(attn)):
    19. assert attn[q][q], "The attention mask must include self-visibility"
    20. print("spans:", spans)
    21. print("labels_count:", sum(1 for x in labels if x != -100))
    22. print("smoke test passed")

    5. A Minimal Viable Engineering Configuration

    For teams that want to validate quickly, they can start with small-scale, conservative parameters, confirm the mask, loss, and training stability, and then scale up.

    Config item Minimal recommendation Notes
    Sequence length 1024 or 2048 Validate long-context stability first, then decide whether to extend to 4096 and above
    Span length 1-16, mean about 8 Too short lacks challenge; too long approaches ordinary generation
    Span start probability p_start=0.02 Adjust by corpus length and target masking ratio
    Max spans 1-4 Too many spans compress the context and increase difficulty
    Masking ratio 15%-25% Too high makes the task too hard; too low gives insufficient information gain
    Context retention ratio At least 75% Ensures the model has enough context for conditioning
    Gradient checkpointing Recommended on Reduces activation memory, suitable for large-model training
    Global batch Start small, then grow Expand gradually on the premise of stable memory and throughput

    5.1 Memory and Throughput Estimation

    Memory usage comes mainly from model weights, optimizer states, gradients, and activations. After enabling mixed precision and gradient checkpointing, activation memory can drop significantly, but at the cost of some recomputation overhead. For an actual configuration, it is recommended to first run a smoke test with a small-scale model and observe whether OOM occurs, whether the loss fails to decrease, or whether gradient explosion or NaN appears.

    Throughput can be estimated with a simplified formula:

    tokens_per_second = global_batch_size × seq_len / median_step_time

    Training time can be estimated further:

    training_hours ≈ total_tokens / tokens_per_second / 3600

    To keep the metrics verifiable, it is recommended to record the following measurement conditions:

    • Number of model parameters.
    • GPU model and count.
    • Parallelism strategy: data parallelism, tensor parallelism, pipeline parallelism, or expert parallelism.
    • Per-GPU batch size, gradient accumulation steps, and global batch size.
    • Sequence length seq_len.
    • Whether mixed precision, gradient checkpointing, FlashAttention, or similar efficient attention is enabled.
    • Whether checkpoint, validation, and log-writing time is excluded.
    • The median step_time after warmup, rather than a single fastest or slowest value.

    It is recommended to record the following metrics in the early stage of training:

    • Loss every 100 steps.
    • The difference between span loss and overall loss.
    • Gradient norm.
    • Whether learning rate warmup is normal.
    • Whether all ranks are synchronized and whether any straggler GPUs exist.
    • GPU utilization, peak memory, data-loading wait time, and I/O throughput.

    6. Cloud Deployment Guide: Resources, Monitoring, Cost, and Permissions

    If you want to deploy autoregressive infilling pretraining on the cloud, you cannot focus only on the training script; you also need to complete resource planning, monitoring and alerting, cost measurement, and permission auditing.

    6.1 Cloud Resource Planning

    The minimal cloud resources can include:

    • Object storage: for storing the raw corpus, tokenized data, configuration files, and checkpoints.
    • Container or batch processing platform: for running data preprocessing, training, evaluation, and export tasks.
    • GPU training instances: it is recommended to prioritize instances that support high-speed interconnect and stable network bandwidth.
    • Logging and monitoring systems: for collecting training loss, gradient norm, GPU metrics, and task status.
    • Key management and access auditing: for managing object storage credentials, database passwords, and service account keys.
    • Message queue or task scheduler: for splitting data preprocessing, training shards, and evaluation tasks.

    It is recommended to design training tasks to be resumable, shardable, and re-runnable:

    • Write data shards to object storage and record the data version and hash.
    • Save checkpoints periodically in training tasks.
    • Keep the configuration file, random seed, code image version, and dependency versions for each task.
    • Use the same data version for preprocessing and training to avoid mismatches between training and evaluation samples.

    6.2 Monitoring and Alerting

    It is recommended to monitor the following metrics:

    • Training loss and span loss.
    • Whether the gradient norm explodes or anomalously drops to zero.
    • Whether learning rate warmup and decay match expectations.
    • Whether per-step time and throughput drop sharply.
    • GPU memory peak, temperature, power consumption, and ECC errors.
    • Data-loading latency and object storage request error rate.
    • Whether any rank becomes a straggler.
    • Whether OOM, NaN, Inf, or a long period of no loss decrease occurs.

    Alerting can be graded as follows:

    • Level 1: task failure, OOM, NaN, continuously rising loss, multiple straggler ranks.
    • Level 2: throughput drop, memory approaching the limit, rising data-read latency.
    • Level 3: abnormal span-length distribution, abnormal masking ratio, suspected original spans appearing in the logs.

    6.3 Cost Measurement

    Cloud costs should at least include:

    • GPU instance fees.
    • CPU preprocessing fees.
    • Object storage and data-read fees.
    • Network egress and cross-region transfer fees.
    • Log, monitoring, and audit storage fees.
    • Manual debugging and failed-task re-run costs.

    It is recommended to estimate with a unified measure:

    single_experiment_cost ≈ GPU unit price × number of GPUs × training hours + storage and network fees + logging and monitoring fees

    For pre-launch capacity assessment, you can further compute:

    training cost per unit token = total training cost / total number of training tokens

    This makes it easy to compare the economics of different model sizes, sequence lengths, and parallelism strategies.

    6.4 Permission Auditing and Data Security

    The cloud scenario should at least meet the following minimal security checklist:

    • Use least-privilege IAM roles, distinguishing permissions for data reading, training writes, log access, and key management.
    • Enable versioning, access logging, and encryption on object storage buckets.
    • Encrypt sensitive data with KMS or the cloud provider’s key management service.
    • Put keys and credentials into a key management system, and prohibit writing them into code repositories or images.
    • Avoid logging raw spans, user privacy, or evaluation samples directly in training logs.
    • Isolate the evaluation set from the training set to prevent evaluation distortion.
    • Retain audit logs for data access, downloads, deletions, and permission changes.
    • Perform copyright and authorization checks on corpora such as books, news, and web page text.
    • Filter and de-identify personal information, sensitive words, and violating content.
    • Periodically review service account permissions and clean up unused credentials and expired data.

    7. Evaluation, Troubleshooting, and Common Checklists

    Since the autoregressive infilling model involves both understanding and generation, evaluation cannot look at perplexity alone. It is recommended to cover at least the following dimensions:

    Check item Description
    Language modeling perplexity Observe the model’s ability to model natural text
    Span infilling accuracy Evaluate token-level or span-level recovery ability within spans
    Downstream classification tasks Verify whether bidirectional understanding transfers to classification, retrieval, and similar tasks
    Generation task quality Evaluate fluency and relevance in summarization, rewriting, dialogue, and other generation scenarios
    Latency and cost Evaluate the per-call cost of the inference service at target traffic
    Failure cases Collect cases of too-short spans, insufficient context, repetitive generation, and semantic breaks

    Pre-training checklist:

    • Are labels valid only at span positions?
    • Is loss_mask aligned with labels?
    • Is the logits shift under teacher forcing completed?
    • Are the masked spans already replaced with MASK_ID in the offline data?
    • Does teacher forcing restore the within-span prefix?
    • Does the context wrongly see the spans?
    • Are multiple spans invisible to each other by default?
    • Does the span attention include self-visibility, i.e., k <= q?
    • Is the span-length distribution reasonable?
    • Is the masking ratio too high?
    • Does the two-dimensional positional encoding conflict with the original sequence position?
    • If a span start position may be 0, is BOS added or an assertion in place?

    Post-training checklist:

    • Does the model only copy the context without generating spans?
    • Does accuracy drop too quickly as spans get longer?
    • Is there answer leakage between spans?
    • Is there overfitting to short spans?
    • Is there over-reliance on the left context in downstream generation tasks?
    • Is there a benefit from bidirectional understanding in classification and retrieval tasks?
    • Is there a decline in context utilization in long-document scenarios?
    • Is span generation stable during inference, without repetition or breaks?

    8. Summary

    The core value of autoregressive infilling pretraining lies in connecting context understanding and sequential generation with a single unified objective: at masked positions, the model can simultaneously access the left and right context while reconstructing the span token by token in an autoregressive manner. To make this approach truly work in practice, it is not enough to remember the concepts; the details must be implemented correctly.

    First, the single-span and multi-span masks must be clear, distinguishing causal visibility of the context from bidirectional access within a span. Second, the two-dimensional positional encoding must be handled correctly, so that pos1 anchors the original sequence while pos2 represents the within-span progress. Third, on the data side, span length, masking ratio, and context retention ratio must be controlled, and on the training side, the replacement rules for masked spans and the prefix-restoration rules for teacher forcing must be made explicit. Finally, on the loss side, the loss should be computed only on span targets, with the BOS, first token, and shift boundaries handled correctly.

    For cloud deployment, resource planning, monitoring and alerting, cost measurement, permission auditing, and a data security checklist must also be completed. Autoregressive infilling is not unconditionally superior to all pretraining objectives; its effectiveness depends on data quality, mask design, span sampling strategy, model size, and evaluation tuning. Only under clear applicability boundaries, by combining it with high-quality corpora, a stable training pipeline, verifiable monitoring, and a complete security process, can you build a general-purpose language model with both understanding and generation ability.