The report says that DeepSeek-V4 packs "documents from different sources into appropriate sequences to minimize sample truncation", following the best-fit packing of Ding et al. (2024), and applies sample-level attention masking so documents in one sequence do not attend to each other. Implement the packer and the naive concatenation it replaces.
Documents are given as docs, a list of (source, length) tuples; document i is identified by its index. Every sequence has capacity seq_len. A piece is a tuple (source, doc_index, piece_len).
naive_concat_pack(docs, seq_len)
seq_len tokens; a document that crosses a cut continues in the next sequence. The last sequence may be partially filled.best_fit_pack(docs, seq_len)
length // seq_len pieces of exactly seq_len tokens plus one piece for the remainder (if non-zero); documents no longer than seq_len stay whole.Both functions return a dict with
"sequences": list of sequences, each a list of pieces in placement order,"num_sequences": its length,"truncation_fraction": the fraction of documents that appear in more than one sequence, rounded to 4 decimals,"padding_fraction": unused tokens divided by num_sequences * seq_len, rounded to 4 decimals.divmod(length, seq_len) gives the number of full pieces and the remainder.sort is stable, so sorting by -piece_len keeps the input order for ties.