Cheat sheets

Pre-Training Data Pipelines

Clean, dedup, download, tokenize, shard and window a pretraining corpus. Python from the lessons.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Tasks#

TaskCode
Run a lesson demopython3 code/main.py
Run the testspython3 -m unittest discover code/tests -v
Drop near duplicatesdeduplicate(filtered_docs, threshold=0.8)
Pack ids into sequencespack_sequences(token_ids, seq_length, pad_id=0)
Download one shardprocess_shard(plan, downloader, dedup, manifest)
Write HDF5 shardspipeline.write_corpus(shards)
Check shard hashesvalidate_corpus(entries)
Read a token rangestore.get_slice(start, stop)

From 10.03 code/main.py, 19.31 code/main.py, 19.42 code, 19.43 code

Corpus to batch#

GETbytesdocsverdictsJSONL shardsshards.jsonget_sliceclientShard URLsShardPlannerprocessStreamingDownloaderRange resumeprocessZstdDocIteratorone doc per lineprocessDedupMinHasher +LSHIndexstoremanifest.jsonshard sha256storeHDF5ShardWriterone .h5 pershardstoreMmapTokenStoreswmr readsgpuSlidingWindowDataloaderinput, targetGETbytesdocsverdictsJSONL shardsshards.jsonget_sliceclientShard URLsShardPlannerprocessStreamingDownloaderRange resumeprocessZstdDocIteratorone doc per lineprocessDedupMinHasher + LSHIndexstoremanifest.jsonshard sha256storeHDF5ShardWriterone .h5 per shardstoreMmapTokenStoreswmr readsgpuSlidingWindowDataloaderinput, target

From Lesson 19.42, Lesson 19.43

Clean and filter#

def clean_text(text):
text = re.sub(r"<[^>]+>", "", text)strip HTML tags
text = re.sub(r"http\S+", "", text)drop URLs
text = re.sub(r"[^\x20-\x7E\n]", "", text)printable ASCII only
text = re.sub(r"\n{3,}", "\n\n", text)collapse blank lines
text = re.sub(r" {2,}", " ", text)collapse spaces
return text.strip()
def quality_filter(text, min_words=50, max_ratio_caps=0.3, max_ratio_special=0.1):
...False for stubs, ALL CAPS spam, symbol noise

From 10.03 code/main.py, Lesson 10.03

Cleaning stages#

1HTML stripkeep only the visible text.2Language detectionfastText lid.176.bin. Below 0.8 confidence isnot clean English.3Quality filterhigh perplexity against a Wikipedia model meansspam.4DeduplicationMinHash plus LSH. Remove one copy above 0.8Jaccard.5PII removalregex for structured PII, NER models for names.6Tokenize and packappend tokenizer.eos_id after each document.

From Lesson 10.03

Sliding window dataset#

ds = SlidingWindowDataset(ids, context_length=16, stride=8)stride None means context_length
SlidingWindowDataset.count_windows(num_ids, context_length, stride)1 + usable // stride
x, y = ds[0]window[:-1], window[1:]
loader = make_dataloader(ds, batch_size=4, base_seed=7, epoch=0)
generator.manual_seed(base_seed + epoch)same seed, same order

From 19.31 code/main.py

Dedup and filter defaults#

SettingDefaultNote
min_words50Stub pages fail
max_ratio_caps0.3ALL CAPS spam fails
max_ratio_special0.1Symbol noise fails
threshold0.8Jaccard to drop a copy
num_hashes128Signature length
bands16Lesson 03. Lesson 42 uses DEFAULT_BANDS = 32
DEFAULT_SHINGLE_WIDTH5Demo uses shingle_width=3
CHUNK_BYTES1 << 16Download read size

From 10.03 code/main.py, 19.42 code/main.py

Resume a download#

1StreamingDownloaderreads <shard_id>.partial.json next to<shard_id>.zst.2_verify_partialfile size must equal verified_bytes. The sha256must equal sha256_prefix_hex.3Mismatchdelete the shard and checkpoint. Restart frombyte zero.4Matchsend Range as bytes={resume_from}- and open theshard in ab mode.5Response checkstatus must be 206 with a matchingContent-Range. Else do a full GET.6Each chunk_write_checkpoint with os.replace, thenout.write(buf).

From 19.42 code/main.py, Lesson 19.42

Storage defaults#

SettingDefaultNote
DEFAULT_CHUNK_SIZE8192Demo uses chunk_size=512
DEFAULT_WINDOW_SIZE64Reads window_size + 1 tokens
BOUNDARY_TOKEN_ID0Separator between documents
TOKEN_DTYPEnp.uint16Byte ids offset by one
maxshape(None,)Resizable dataset
libver"latest"Required on the writer for SWMR

From 19.43 code/main.py, Lesson 19.43

Numbers and formulas#

Window count
max(0, 1 + (N - (T + 1)) // S) for N ids, context T, stride S.
Stride
T // 2 doubles the dataset. 1 grows it by a factor of T.
LSH collision
1 - (1 - s^r)^b with k = b * r.
LSH threshold
near (1/b)^(1/r). For b=32, r=4 it is near s = 0.42.
Compression
English is about 3-4 characters per token.
Sequence utilization
below 90% means packing wastes compute.
Dedup yield
the Llama team removed approximately 38% of web data.
Chinchilla
scale parameters and tokens roughly equally.

From Lesson 10.03, Lesson 19.31, Lesson 19.42, 19.42 code/main.py

Troubleshooting#

SymptomCauseFix
Resumed shard holds garbageOffset and file differCheck the sha256 prefix first
Server ignores RangeStatus is not 206Close it and do a full GET
Duplicated suffix after power lossBytes written before checkpointCheckpoint first, then write
Model learns to predict zeroReader reads zero paddingTruncate at token_count
"file is locked"No libver="latest" or late SWMRCreate datasets, then set swmr_mode
Throughput halvesChunk does not match windowChunk a multiple of window_size
Runs diverge for no reasonNo shuffle seedPass base_seed per epoch
ValueError from LSHIndexbands does not divide num_hashesPick bands that divide 128

From Lesson 19.42, 19.42 code/main.py, Lesson 19.43, Lesson 19.31, Lesson 10.03

Q&A#

Why pack instead of pad?
Padding wastes compute on tokens that teach nothing.
Why a block-diagonal mask?
Doc A tokens must not attend to Doc B tokens.
What does the slicer do with a short tail?
It drops the last window.
Why dedup before tokenization?
Tokenization is expensive. Do not pay it twice.
Why tombstone duplicates?
The manifest keeps the link to the keeper.
Why one HDF5 per source shard?
A crash loses at most one shard.

From Lesson 10.03, Lesson 19.31, Lesson 19.42, Lesson 19.43

Tips#

  • Trainers read shards.json, not the directory listing.
  • Verify the manifest sha256 in manifest.lock before you trust shard rows.
  • Call dataset.flush() after each resize in SWMR mode.
  • Buffer tokens to chunk size, then resize. Never write one document at a time.
  • Most runs use a stride equal to the context length.

From Lesson 19.42, Lesson 19.43, Lesson 19.31