Tag: Infra

  • ML0165 Streaming Sketches: Count-Min & HLL

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • DL0257 MoE Inference Nondeterminism

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • DL0252 CUDA Timing Lies

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • DL0248 Dataloader Bottleneck Triage

    Training GPUs sit at 30% utilization. Walk me through how you localize the data-pipeline bottleneck: what do you check, and in what order?

    A three-panel question card. The first panel describes the training job: eight A100 GPUs and 64 CPU cores, ResNet-50 at batch 256 per GPU, 1.28 million JPEGs of about 110 KB each on shared NFS with a measured 2.5 GB/s ceiling, and PIL decode, random crop, flip and normalize running on the CPU. The second panel shows a GPU kernel timeline of three steps with short busy blocks and long idle gaps, nvidia-smi reporting 30 percent on all eight GPUs, and a step time of 0.32 seconds or 800 images per second per GPU. The third panel lists five suspects with their current settings: num_workers 4, pin_memory False, JPEG decode and augment on CPU, prefetch_factor at the default of 2, and NFS I/O wait not measured, plus a teammate's suggestion to just set num_workers to 64.

    The Problem: An image team trains ResNet-50 on 8 A100s at batch 256 per GPU, reading 1.28M JPEGs from shared NFS with num_workers=4 and pin_memory=False, and every GPU reports 30% utilization with 0.32 s steps. A teammate wants to set num_workers=64, and you have to say which of the five suspects to check first and in what order.

    Answer

    Low utilization is a symptom, so the first check is whether the input pipeline causes it at all. Replay one batch that already sits on the GPU in a loop: if utilization jumps to about 95%, the loader is guilty, and if it stays near 30% the cause is a host sync point, a small batch, or communication. Next compare two rates, the loader’s throughput measured alone with no model and the GPU’s demand of batch size over synthetic step time, which tells you exactly how much speedup you need. Then sweep num_workers while watching CPU state, because the resource that saturates names the bottleneck. Workers pinned at 100% user CPU mean decode or augmentation is CPU-bound, workers blocked in I/O wait mean storage, and a single busy main process means collate or host-side work. Only after that do you tune the overlap plumbing (pin_memory with non_blocking copies, prefetch_factor, persistent_workers), whose signatures are periodic stalls rather than a uniform slowdown.

    (1) Prove It Is The Loader: A synthetic-batch replay splits the hypothesis space in one run, separating data starvation from sync points, launch overhead, and collective communication.
    (2) Measure Rates, Not Utilization: nvidia-smi utilization is the sampled fraction of time any kernel runs, not SM occupancy. Log per-step data-wait time and compare loader-only throughput with the GPU’s demand.
    (3) Scale Workers To The Core Budget: Sweep num_workers and watch throughput rise linearly, then flatten. Under DDP every rank owns its own loader, so the ceiling is cores per GPU minus one, and going past it oversubscribes the CPU.
    (4) Read The CPU State: 100% user CPU points to decode or augmentation, high %iowait with workers in the D state points to storage, and one saturated main process points to collate or the pin-memory thread.
    (5) Break Down Per-Sample Cost: Time read, decode, augment, and collate inside one worker. JPEG decode usually dominates, so pre-resized storage, GPU decode, or shipping uint8 beats adding processes.
    (6) Tune Overlap Last And Re-Measure: pin_memory, prefetch depth, and persistent workers fix stalls only after capacity matches demand, and the binding constraint moves after every fix.

    Mathematical Formulation:
    R_{need} = B / t_{gpu}
    R_{cpu} = W / t_{cpu}
    R_{io} = BW_{io} / (G \cdot s)
    R_{load} = \min(R_{cpu}, R_{io})
    U \approx \min(1, R_{load} / R_{need})
    f_{wait} = t_{wait} / t_{step}

    Where:

    • R_{need} is the per-GPU sample rate the model consumes, B is the per-GPU batch size, and t_{gpu} is the step time measured with a GPU-resident synthetic batch.
    • R_{cpu} is the worker-limited rate, with W workers per GPU rank and t_{cpu} the per-sample CPU time summed over read, decode, augment, and the collate share.
    • R_{io} is the storage-limited rate, where BW_{io} is measured storage bandwidth shared by the G GPUs on the node and s is the mean bytes per sample.
    • R_{load} is the delivered loader rate and U the implied utilization, assuming prefetching fully overlaps loading with compute so only the slowest stage matters.
    • f_{wait} is the fraction of each step spent blocked waiting for the next batch, with t_{step} \approx t_{wait} + t_{gpu} when the loader is the bottleneck.

    Worked Triage Example (8 GPUs, 64 cores, NFS at 2.5 GB/s):
    R_{need} = 256 / 0.10\ \text{s} = 2560\ \text{img/s}
    R_{cpu} = 4 / 5.0\ \text{ms} = 800\ \text{img/s}
    U \approx 800 / 2560 = 0.31
    t_{cpu} = 0.4 + 3.1 + 1.2 + 0.3 = 5.0\ \text{ms}
    R_{cpu}(W{=}7) = 7 / 5.0\ \text{ms} = 1400\ \text{img/s}
    t_{cpu}' = 0.4 + 1.2 + 0.9 = 2.5\ \text{ms}
    R_{cpu}' = 7 / 2.5\ \text{ms} = 2800\ \text{img/s}
    R_{io} = 2.5\ \text{GB/s} / (8 \cdot 110\ \text{KB}) = 2841\ \text{img/s}

    The synthetic replay runs a step in 0.10 s, so each GPU needs 2,560 img/s. Iterating the loader alone gives 800 img/s, which reproduces the observed 0.32 s step exactly (256 / 800), so the loader is confirmed as the cause. htop shows the workers at 100% user CPU with almost no iowait, and a per-stage timer splits the 5.0 ms per image into 0.4 ms read, 3.1 ms decode, 1.2 ms crop and flip, and 0.3 ms normalize. Raising workers to the core budget of 7 per rank (64 cores across 8 ranks, one core kept for each training process) only reaches 1,400 img/s, about 55%. Storing pre-resized JPEGs cuts decode to 1.2 ms and cropping to 0.9 ms, and normalizing on the GPU removes the last 0.3 ms, which lifts capacity to 2,800 img/s and makes the job GPU-bound. NFS serves only 0.70 GB/s today, but at full speed full-size files would need 2.25 GB/s, 90% of the ceiling, so storage becomes the next constraint unless the smaller pre-resized files restore headroom.

    Line chart of loader throughput per GPU against num_workers per GPU rank from 1 to 16. The current pipeline at 5.0 ms per sample rises linearly by 200 images per second per worker to 1,400 at the core budget of 7 workers and then declines slowly as workers oversubscribe the CPU. The fixed pipeline at 2.5 ms per sample rises by 400 per worker to 2,800 at 7 workers, above the dashed GPU demand line at 2,560 and just below the dotted NFS ceiling at 2,841. Markers and annotations show today's point at 4 workers and 800 images per second, about 31 percent, the core-budget point at 1,400 and about 55 percent, and the fixed capacity of 2,800. A right axis shows implied GPU utilization in percent.

    Figure 1: Loader capacity per GPU as num_workers grows on the 64-core, 8-GPU node. Today’s 5.0 ms/sample pipeline scales linearly only up to the core budget of 7 workers, stalls at 1,400 img/s (about 55%), and loses throughput when oversubscribed. Only cutting per-sample cost to 2.5 ms lifts capacity above the 2,560 img/s GPU demand, and it lands just under the 2,841 img/s NFS ceiling.

    Storage deserves its own check even when the CPU picture looks clear. It is the suspect when workers sit in the D (uninterruptible I/O) state with high %iowait and low user CPU, or when epoch 2 runs much faster than epoch 1 because the page cache now holds the files. On shared filesystems the limit is often metadata operations per second rather than bytes, which is why millions of 110 KB files hurt more than their total size suggests and why sharding them into large sequential files helps. The overlap plumbing comes last because its failures look like periodic stalls. pin_memory=True stages batches in page-locked host memory so .to(device, non_blocking=True) overlaps with compute, and shipping uint8 instead of fp32 shrinks a 256-image batch from 154 MB to 38.5 MB. prefetch_factor (default 2 batches per worker) absorbs bursty sample costs, and persistent_workers=True stops the DataLoader from tearing down and respawning every worker at each epoch boundary.

    Five horizontal GPU kernel timelines over three seconds. Row a, loader too slow: short busy blocks separated by long idle gaps every step, 31 percent busy. Row b, loader keeps ahead: nearly continuous busy blocks, 95 percent busy. Row c, prefetch queue drains: continuous busy blocks with an isolated stall every seventh step. Row d, epoch boundary: continuous busy blocks with one long 0.7 second gap where workers respawn. Row e, host sync point: regular small gaps every step that remain at 71 percent busy even with synthetic data.

    Figure 2: Timeline shapes from a profiler trace name different causes. A gap every step (a) means the loader is too slow, an isolated stall every few steps (c) means the prefetch queue drains on slow samples, a long gap at each epoch start (d) means workers are respawned, and gaps that survive synthetic data (e) are host sync points rather than the loader.

    The table below maps each observable signal to its diagnosis, the measurement that confirms it, and the fix that matches it. Reading it top to bottom is the triage order, because each row is cheap to test and rules out a whole branch before the next one.

    Observed signalLikely causeConfirming checkMatching fix
    Synthetic replay still near 30%Not the loader: sync points, small batch, launch overhead, collectivesProfiler shows stream synchronizes from .item() or .cpu() between stepsRemove host syncs, larger batch, CUDA graphs, overlap communication
    Throughput scales with workers, cores idleToo few workers (num_workers=0 loads in the main process)Loader-only sweep over 2, 4, 8 workers per rankRaise to cores per GPU minus one, never beyond
    All workers at 100% user CPUDecode or augmentation is CPU-boundPer-stage timer in one worker; decode dominatesPre-resize offline, GPU decode, uint8 transfer with GPU normalize
    Workers in D state, high %iowaitStorage bandwidth or metadata rateiostat await, NFS ops per second, epoch 1 vs epoch 2 speedShard into large files, stage to local NVMe, larger reads
    Main process at 100%, workers idleHeavy collate_fn or host-side batch workpy-spy dump of the training processMove work into workers, simplify collate
    Stall every k steps or at epoch startPrefetch queue drains, or workers respawnGPU timeline shape in Nsight Systems or torch.profilerRaise prefetch_factor, set persistent_workers=True
    Pageable HtoD copy blocks each stepNo pinned memory, fp32 batches on the hostProfiler shows Memcpy HtoD (Pageable) on the critical pathpin_memory=True with non_blocking=True, ship uint8

    Login to view more content
  • DL0240 Tokenizer Throughput Pipeline

    Your BPE encode() is correct but tokenizing a 2TB corpus takes three weeks. The tech lead suggests a Rust rewrite. Why is that the second priority, not the first?

    A three-panel question card. The first panel lists today's pipeline: a 2 TB corpus in 4,000 shards, one Python process, a 64-core machine with one core busy, 1.1 MB/s throughput, and an ETA of 21 days. The second panel shows a profile of one shard as horizontal bars: 15 percent waiting on reads, 5 percent decompress and parse, 70 percent in BPE encode, and 10 percent waiting on writes. The third panel shows the tech lead's proposal to rewrite encode in Rust, estimated at 10x faster encode for about three weeks of work, and asks whether this is the first fix and what 21 days becomes.

    The Problem: A pretraining team’s byte-level BPE encode() produces the right token IDs, but one Python process on a 64-core machine pushes the 2 TB corpus through at 1.1 MB/s, an ETA of 21 days. A profile puts 70% of the time inside encode(), and the tech lead proposes a Rust rewrite estimated at 10x on that step.

    Answer

    A Rust rewrite attacks the wrong number first. Rewriting encode() only accelerates the share of runtime spent inside it. By Amdahl’s law, a 10x faster encode on a 70% share yields 2.70x end to end, and even an infinitely fast one caps at 3.33x. Meanwhile 63 of 64 cores sit idle, and tokenization is embarrassingly parallel across documents, so one process per core gives roughly 57x with no change to the encoding logic. Overlapping storage waits with compute and caching repeated pre-tokens recover most of the remaining waste. Only after the pipeline saturates every core does per-core speed decide the bill, and then the right move is usually to adopt an existing Rust tokenizer behind a byte-exact differential test.

    (1) Profile Before Choosing A Lever: A sampling profiler such as py-spy splits wall-clock time into read wait, parse, encode, and write wait. Those shares decide which speedups are even reachable.
    (2) Amdahl Caps Any Single-Stage Rewrite: Speeding up a stage that takes a fraction p of runtime can never beat 1/(1-p), which is 3.33x here no matter how good the Rust code is.
    (3) Shard First, Because Documents Are Independent: Run one worker process per core, not threads, since the GIL serializes pure-Python BPE. Pass shard paths rather than text, and the output stays byte-identical because encode() is untouched.
    (4) Overlap IO With Compute: Prefetch the next shard and write asynchronously through bounded queues, so a worker runs at the pace of its slowest stage instead of the sum of all stages.
    (5) Fix The Algorithm Before The Language: A pre-token cache skips repeated merge loops on Zipfian text, and a priority-queue merge removes the quadratic worst case on long pre-tokens.
    (6) Rust Comes Last, And Usually Off The Shelf: Once every core is busy, per-core cost equals core-hours, so a native encoder pays. Adopt Hugging Face tokenizers or tiktoken and gate it on a token-ID differential test against the Python reference.

    Mathematical Formulation:
    S_{\mathrm{enc}}(s) = \frac{1}{(1-p) + p/s}
    S_{\max} = \lim_{s \to \infty} S_{\mathrm{enc}}(s) = \frac{1}{1-p}
    S_{\mathrm{par}}(N) = \frac{1}{f + (1-f)/N}
    T_{\mathrm{seq}} = \sum_{k} t_k
    T_{\mathrm{pipe}} = \max_{k} t_k

    Where:

    • S_{\mathrm{enc}}(s) is the end-to-end speedup when only encode() becomes s times faster, and p is encode’s share of single-process runtime (0.70 in this job).
    • S_{\max} is the Amdahl ceiling reached by an infinitely fast encoder, because the other 1-p of the time is untouched.
    • S_{\mathrm{par}}(N) is the speedup from N parallel workers, and f is the serial fraction (shard listing, manifest merge) that no worker count shrinks, about 0.002 here.
    • t_k is the per-shard time of stage k \in \{\mathrm{read}, \mathrm{parse}, \mathrm{enc}, \mathrm{write}\}, so T_{\mathrm{seq}} is a blocking worker and T_{\mathrm{pipe}} a worker whose stages overlap.

    Worked Example (504 hours today, p = 0.70, f = 0.002):
    S_{\mathrm{enc}}(10) = 1/(0.30 + 0.07) = 2.70
    T_{\mathrm{rust}} = 504/2.70 = 187\ \mathrm{h}
    T_{\infty} = 504 \times 0.30 = 151\ \mathrm{h}
    S_{\mathrm{par}}(64) = 1/(0.002 + 0.998/64) = 56.8
    T_{64} = 1.0 + 503/64 = 8.9\ \mathrm{h}
    T_{64,\mathrm{rust}} = 1.0 + 7.86 \times 0.37 = 3.9\ \mathrm{h}

    The two levers are not symmetric. Every encode-only change competes for the same 70% slice, whether it is a Rust port, a C extension, or a cache, and none of them can beat 151 hours on one process. Sharding instead multiplies the whole pipeline. Each of the 4,000 shards tokenizes independently, and the only serial work is roughly an hour of listing and manifest merging. It also leaves encode() untouched, so the output is byte-identical to today’s and needs no new correctness argument. The levers compose rather than compete: once the job is sharded, a faster encoder still divides the 7.86 parallel hours by 2.70. That is why the Rust work is deferred, not cancelled.

    Two-panel chart. Left: end-to-end speedup on log-log axes against the factor applied. The orange curve for making encode faster with p equal to 0.70 flattens under a dashed ceiling at 3.33x, with a marker at 2.70x for a 10x Rust encode. The blue curve for adding workers with a 0.2 percent serial share rises almost linearly, with a marker at 56.8x for 64 workers. Right: horizontal bars of wall-clock hours on a log axis: 504 hours today, 187 hours with Rust encode in one process, 151 hours with an infinitely fast encode, 8.9 hours with 64 shard workers, and 3.9 hours with 64 workers plus Rust.

    Figure 1: Left, the two levers on the same log axes. Making encode() faster flattens at the 3.33x Amdahl ceiling however good the rewrite is, while adding shard workers keeps paying until the 0.2% serial share starts to bite. Right, the resulting wall-clock: the Rust-only plan still takes 7.8 days, 64 workers finish in 8.9 hours, and adding the Rust encoder brings that to 3.9 hours.

    Two cheaper fixes sit between sharding and a rewrite. The first is to overlap IO with compute. Today each worker idles for 15% of a shard waiting on reads and 10% waiting on writes. A background thread that prefetches the next shard into a bounded queue, plus an asynchronous writer, removes those stalls because blocking syscalls release the GIL. The second is to fix the algorithm. Byte-level BPE runs its merges inside each regex pre-token, and pre-token frequencies are Zipfian, so a pre-token cache from word to IDs skips most merge loops (GPT-2’s reference encoder already memoizes this way). A merge loop that rescans every adjacent pair on each step is quadratic in pre-token length, so a single 1 MB base64 blob can stall a shard for minutes. A priority-queue merge over a linked list brings that to O(n \log n), and a pre-token length cap guards the rest. After all of this plus Rust, 64 workers consume close to 200 MB/s of text, so the next bottleneck is often storage rather than code.

    PropertyShard workers and IO overlapPre-token cache and heap mergeRust rewrite of encode()
    What it targetsThe whole pipeline: 63 idle cores and 25% storage stallsThe 70% encode share, by skipping repeated and quadratic workThe 70% encode share, by a constant factor per core
    Engineering effortAbout a day: process pool over shard paths, prefetch thread, async writerA few days: memo dict on pre-tokens, priority-queue merge, length capWeeks to write, or hours to adopt an existing library
    Effect on the 504 h jobAbout 57x, down to 8.9 h, before counting the overlap gainDepends on hit rate, and capped at 3.33x like any encode-only fix2.70x alone (187 h); multiplies on top of sharding (3.9 h)
    Risk to token IDsNone: encode logic is unchangedLow: the cache returns the function’s own outputHigh: pre-tokenizer regex and merge tie-breaks must match byte for byte

    Login to view more content
  • DL0226 Checkpoint Formats: safetensors and Memory Mapping

    A teammate wants to load a 40GB pickle checkpoint and wonders why Hugging Face pushed safetensors instead. Separately, how does a 2TB dataset fit in 64GB of RAM?

    A three-panel question card. The first panel describes one shared checkpoint: file pytorch_model.bin, Python pickle format, 40 GB in fp16, downloaded from a stranger's repo, on a box with 64 GB of RAM, and asks whether it is safe to load and whether it will fit. The second panel shows Hugging Face moving the Hub default from a pickle .bin file to a safetensors file and asks why. The third panel shows 2 TB of token ids on NVMe next to 64 GB of RAM and asks how the corpus fits.

    The Problem: A teammate on a 64 GB training box wants to torch.load a 40 GB pickle checkpoint pulled from someone else’s repo, and asks why Hugging Face moved the Hub to safetensors. The same box must also train on a 2 TB tokenized corpus, which is about 31 times larger than its RAM.

    Answer

    A pickle checkpoint is a program, not a data file. Python’s unpickler executes opcodes that can import any callable and call it, so loading an untrusted .bin is arbitrary code execution. Safetensors replaces it with a passive layout of an 8-byte length, a JSON header that maps each tensor name to dtype, shape and byte offsets, and one contiguous byte buffer. Because nothing needs decoding, a loader can mmap the file and hand out zero-copy tensor views, so only the pages a process actually touches are read from disk. That removes the unpickling pass and the second copy of the weights, which is why CPU loading is often more than an order of magnitude faster and peak RAM halves. The 2 TB dataset fits the same way, because Hugging Face datasets keeps it as memory-mapped Apache Arrow (or streams it) and the OS page cache holds only the working set.

    (1) Pickle Is A Program: The GLOBAL opcode imports any module attribute and REDUCE calls it with arguments, so a __reduce__ returning os.system runs at load time. Sharing a pickle checkpoint means sharing whatever payload it carries.
    (2) weights_only Is A Mitigation, Not A Format: torch.load(weights_only=True) restricts the unpickler to an allowlist of types, but it still parses an executable opcode stream and has needed security patches.
    (3) Header Then Bytes: The first 8 bytes are a little-endian unsigned 64-bit length N, the next N bytes are JSON, and the rest is tensor data in C order with no gaps or overlaps, so validation is just bounds checking.
    (4) Zero-Copy mmap: Tensors are views into the mapped file, so there is no deserialization pass and no intermediate copy, and every process on the host shares the same page cache.
    (5) Lazy And Sliced Loads: safe_open with get_tensor or get_slice reads one tensor or one slice of it, which is how a tensor-parallel rank loads only its own columns.
    (6) Meta-Device Skeleton: from_pretrained builds the model with no storage on the meta device and fills it shard by shard, so the random-init copy never exists.
    (7) Datasets Never Load Into RAM: Arrow files are memory-mapped and row lookup is offset arithmetic, while streaming=True reads remote shards incrementally, so RAM holds the working set, not the corpus.

    The danger on the pickle side is concrete. torch.save writes a zip archive whose data.pkl entry is a pickle program, with tensor storages kept as separate raw entries. On load, the unpickler walks that program: GLOBAL pushes a callable named by module and attribute, and REDUCE applies it to a tuple. A crafted object whose __reduce__ returns os.system with a shell command therefore executes the moment the file is opened, before a single tensor is touched. Safetensors has no such code path. A typical header entry reads “model.embed_tokens.weight”: {“dtype”: “F16”, “shape”: [32000, 4096], “data_offsets”: [0, 262144000]}, the library rejects headers above 100 MB, duplicate names, and offsets that disagree with dtype times shape, and the worst a malicious file can do is fail validation.

    Byte layout of a safetensors file: an 8-byte length N, a JSON header of N bytes, then contiguous tensor data for embed_tokens, layers.0.q_proj, 288 more tensors, and lm_head. Below the header, a box shows a JSON entry with dtype F16, shape 32000 by 4096 and data offsets 0 to 262144000. Below the tensor region, a row of twenty 4 KiB pages mapped into the process shows only the six pages under layers.0.q_proj shaded as resident after one get_tensor call, while the rest are mapped but never read.

    Figure 1: A safetensors file is an 8-byte length, a JSON index, and one contiguous tensor buffer. After a single mmap call, asking for layers.0.q_proj faults in only the pages under its byte range (plus the partial edge pages), while every other tensor stays on disk until touched.

    Mathematical Formulation:
    \mathrm{start}(t) = 8 + N + b_t
    e_t - b_t = s(\tau_t) \prod_{j} d_{t,j}
    M_{\mathrm{pickle}} \approx 2 P s
    M_{\mathrm{safe}} \approx P s
    W_{\mathrm{step}} = B \cdot L \cdot s_{\mathrm{tok}}

    Where:

    • \mathrm{start}(t) is the absolute file byte where tensor t begins, N is the JSON header length stored in the first 8 bytes, and b_t is the begin value of its data_offsets, which is relative to the end of the header.
    • e_t is the end offset, s(\tau_t) the bytes per element of dtype \tau_t (2 for F16 and BF16, 4 for F32), and d_{t,j} the shape dimensions; a header where this product disagrees with the byte range is rejected.
    • P is the parameter count and s the bytes per parameter of the stored dtype; M_{\mathrm{pickle}} counts a random-initialized model plus the unpickled state dict held at the same time.
    • M_{\mathrm{safe}} counts a single copy when the skeleton lives on the meta device, and that copy is file-backed page cache the kernel can evict and share rather than anonymous memory.
    • W_{\mathrm{step}} is the data touched per training step, with B sequences per batch, L tokens per sequence, and s_{\mathrm{tok}} bytes per token id (2 for uint16 when the vocabulary has at most 65,536 entries).

    Worked Example (one 64 GB box, 40 GB checkpoint, 2 TB corpus):
    P s = 20 \times 10^{9} \cdot 2\ \mathrm{B} = 40\ \mathrm{GB}
    M_{\mathrm{pickle}} \approx 2 \cdot 40\ \mathrm{GB} = 80\ \mathrm{GB} > 64\ \mathrm{GB}
    M_{\mathrm{safe}} \approx 40\ \mathrm{GB}
    W_{\mathrm{step}} = 512 \cdot 2048 \cdot 2\ \mathrm{B} = 2\ \mathrm{MiB}
    2 \times 10^{12}\ \mathrm{B} / 4096\ \mathrm{B} \approx 4.9 \times 10^{8}

    The checkpoint numbers explain the teammate’s experience. A 20B-parameter fp16 model is 40 GB, and the classic pickle path needs about 80 GB of anonymous memory, so on a 64 GB box it swaps or gets OOM-killed before load_state_dict finishes. The mmap path holds one evictable copy, and the unavoidable cost is the raw read itself, roughly 13 s at 3 GB/s from NVMe. Hugging Face’s own GPT-2 benchmark reports tens of times faster CPU loading with a warm page cache and about 2x on GPU, where the host-to-device copy dominates; part of the CPU number is deferred I/O, since pages are read on first touch rather than at open. The corpus numbers are even more lopsided. A 2048-token uint16 sequence is exactly 4096 bytes, one page, so the 2 TB file holds about 490 million sequences and a 512-sequence batch is 512 random 4 KiB reads. A datacenter NVMe drive serves several hundred thousand such reads per second, which puts each step’s I/O on the order of a millisecond.

    Two schematic charts of host RAM. Left: loading a 40 GB fp16 checkpoint, the pickle path climbs to 40 GB during random initialization and then to about 80 GB while torch.load reads the state dict, crossing the 64 GB physical RAM line, while the safetensors path keeps anonymous RAM near 1 GB and its page cache rises to 40 GB. Right: reading a 2 TB corpus, loading it into RAM runs out of memory after 64 GB, while the memory-mapped path keeps process RSS near 2 GB and the page cache saturates just under the RAM ceiling.

    Figure 2: Schematic resident memory on the 64 GB box. (a) The pickle path holds a random-initialized model and the unpickled state dict at once and needs about 80 GB, while the mmap path keeps the weights in evictable page cache. (b) Reading the 2 TB corpus into RAM fails after 64 GB, whereas a memory-mapped corpus keeps process RSS near 2 GB and lets the page cache cycle at the RAM ceiling.

    Inside transformers, from_pretrained runs a fixed chain: resolve repo id and revision → fetch files into the hub cache (content-addressed blobs behind snapshot symlinks) → read config.json and pick the model class → open model.safetensors.index.json, whose weight_map assigns every tensor name to a shard → build the module tree on the meta device → per shard, safe_open, read each tensor, cast to torch_dtype and assign → tie shared weights and place layers by device_map. When only pytorch_model.bin exists, the same chain unpickles instead. That is why Hugging Face’s conversion bot opened safetensors pull requests on popular repos and why save_pretrained now writes safetensors by default.

    The dataset side uses the same operating-system trick on a different file format. load_dataset converts source files once into Apache Arrow tables in the local cache, and a Dataset object is a view over those memory-mapped files. Arrow stores a token column as one contiguous values buffer plus an offsets buffer, so row i is two offset lookups and a slice, with no Python objects created until you ask for them. Many pretraining codebases go one step simpler and write a single flat uint16 token array read with numpy.memmap, where sample i is a slice at byte 4096 i. When 2 TB exceeds local disk too, streaming=True returns an IterableDataset that pulls shards over HTTP as iteration proceeds and shuffles approximately with a shard-order shuffle plus a fixed-size sample buffer.

    PropertysafetensorsPickle .bin (torch.save)
    What the file isPassive data: 8-byte length, JSON index, raw tensor bytesA pickle program inside a zip archive, plus raw storage entries
    Opening an untrusted fileNo code path; a malformed header fails bounds checksOpcodes can import and call any function, so loading runs attacker code
    Load pathmmap, zero-copy views, pages read on first touchUnpickle, rebuild objects, copy storages into fresh memory
    Peak host RAM, 40 GB modelAbout one evictable copy with a meta-device skeletonAbout two copies: initialized model plus state dict
    Partial readsget_tensor and get_slice fetch one tensor or one sliceThe whole program is unpickled; mmap=True since PyTorch 2.1 avoids only the storage copies
    What it can storeTensors plus a flat string-to-string metadata mapAny Python object: optimizer state, schedulers, custom classes
    ReadersRust core with PyTorch, NumPy, JAX, TensorFlow and MLX bindingsPython with the exact classes importable, in practice PyTorch only

    Login to view more content
  • DL0212 LLM Serving Frameworks: vLLM, SGLang, TensorRT-LLM

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0114 Categorical Feature Encoding

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0150 Insurance-Claims Document Agent

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0145 Uplift Modeling for Promo Budgets

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.