Code · architecture · study mode
Before the OS can map the weight file into memory, the program needs to know exactly how many bytes to map — this is just measuring the file size without reading a single weight.
Full explanation below the code →
mmap (which we'll see in the next block) requires one critical piece of information before it can work: the exact size of the file in bytes. There's no way to ask "map this file" without saying "map this many bytes of this file." So the program measures first.
The sequence is straightforward — open the file in read-only mode, jump to the very end, ask "where am I?" (that position is the file size), then close it. No data is read, no memory is allocated. For Qwen3-0.6B, this returns roughly 2.4 GB — that number becomes the length argument for mmap.
The fseek/ftell sequence:
1. fopen(checkpoint, "rb") — open in binary read-only mode
2. fseek(file, 0, SEEK_END) — jump to the last byte
3. ftell(file) — return the current offset, which equals the total file size
4. fclose(file) — close it; mmap needs its own separate file descriptor
The file is closed after measuring because mmap needs its own separate file descriptor. We're just getting the dimensions before reserving the space.
mmap requires an exact byte length; ftell gives it without reading a single weight.
What information does fseek + ftell give us, and why do we need it before calling mmap?