Repository navigation
save_safetensors: write files the mmap loader can actually map - #5
Merged
Merged
Conversation
`tensor_from_mmap` shares the mapping only when a tensor's absolute byte
offset is a multiple of its dtype width, and copies into a freshly
allocated aligned buffer otherwise. `save_safetensors` did nothing to
avoid the copy: it wrote the header unpadded, so the data section began
at 8 + strlen(json), and then packed the tensors back to back in the
order of the map. On macOS, eight small tensors written that way started
their data section at byte 508, and loading the file with
MLX_SAFETENSORS_MMAP=1 copied four of them ("realigned 4 unaligned
tensor(s) (38 bytes)"). An earlier measurement on a 95 GB bundle found
1,775 of 2,999 tensors on the copy path: 59.3 GB of extra anonymous
memory on top of the mapping.
Pad the header with spaces to a multiple of 8, and write the tensors
widest dtype first, ties by name; the reference safetensors writer also
writes the widest dtypes first. A tensor's size is a multiple of its
dtype width, and the widths are powers of two up to 8, so each tensor
then starts at a multiple of its own width: the order aligns every
tensor without padding between them. Padding between tensors would not
do: the format forbids holes ("The byte buffer needs to be entirely
indexed, and cannot contain holes"), and the reference reader rejects a
file with a gap ("invalid offset for tensor"). The header may be padded
with spaces; that costs at most 7 bytes a file.
The tensors' order in the data section changes. The header still maps
each name to its offsets; MLX's readers and the reference reader find
tensors by name. The old order was the hash map's, which differed
between macOS and Linux.
tests/load_tests.cpp gains a case that saves odd-sized tensors of every
width, an empty one among them, and checks from the file's header that
the data section starts at a multiple of 8, that every tensor's offset
is a multiple of its width, and that the spans tile the data with no
hole up to the end of the file. On main it fails the first two checks.
With this change, files with every dtype save_safetensors writes start
their data section at a multiple of 8, with no tensor misaligned and no
gap. MLX reads every tensor back unchanged on macOS, with the mmap
loader (which copies nothing) and without it, and on Linux; the
reference reader, Hugging Face's safetensors 0.8.0, reads every file
with the same values. The layout no longer depends on the map's
iteration order: macOS and Linux write the same bytes.
rcfa
changed the base branch from
codex/gemma4-safetensors-alignment-20260720
to
main
October 13, 2026 15:40
rcfa
force-pushed
the
safetensors-write-aligned
branch
from
October 13, 2026 15:40
0c80380 to
c3b922b
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
tensor_from_mmapshares the mapping only when a tensor's absolute byte offset is a multiple of itsdtype width, and copies into a freshly allocated aligned buffer otherwise.
save_safetensorsdoes nothing to avoid the copy: the header is written unpadded, so the data section begins at
8 + strlen(json)— an arbitrary byte, landing on a multiple of 8 about one time in eight — andtensors are then packed back to back in the order of the map.
So when this fork maps a file it wrote (
MLX_SAFETENSORS_MMAP=1), it copies every tensor that landedmisaligned. In a CPU-only Linux build the mmap loader gives up (
make_bufferfails) and falls back tothe reader.
The base is
main(MLX 0.32.3). This replaces the original change, which padded each tensor to8 bytes: that left gaps between tensors, which the format forbids (see below).
What it costs
On
main, on macOS with Metal,save_safetensorswrote eight tensors of 3, 10, 1, 6, 12, 8, 6 and 8bytes with the data section at byte 508 (4 mod 8). Four of the eight were misaligned, and loading the
file with
MLX_SAFETENSORS_MMAP=1copied them:(the file's path is elided). A file with one tensor of every dtype
save_safetensorswrites had 6 of13 misaligned, and the loader copied those six. The values are unaffected: the same bytes are copied,
and every tensor read back unchanged. That is why this can sit undetected: it is invisible in any
test that reads the tensors, and shows up only as memory.
An earlier measurement, not repeated for this update, shows what that costs at scale: on a 95 GB
bundle on a 128 GB M4 Max, 1,224 of 2,999 tensors stayed on the zero-copy path as written and all
2,999 after the same shards were aligned. Loading took 59.3 GB of extra anonymous memory as written and
none aligned, the memory compressor held 60.1 GB against 0.8 GB, and generation fell to about 3 tokens
a minute. A scan of 128 locally held MLX bundles found 49 affected.
The change
Pad the header to a multiple of 8, and write the tensors widest dtype first, ties by name. A tensor's
size is a multiple of its dtype width, and the widths are powers of two up to 8. So once the data
section starts at a multiple of 8, every 8-byte tensor ends on a multiple of 8, every 4-byte tensor
after them starts and ends on a multiple of 4, and so on down to 1: each tensor starts at a multiple
of its own width, with no padding between tensors. The reference writer, Hugging Face's
safetensors, also pads its header to a multiple of 8 and writes wider dtypes first (it sorts bydtype, then by name), which is what aligns its tensors.
The order matters because padding between tensors is not an option. The format forbids holes; its
README says
and the reference reader rejects a file with a gap before a tensor
(
invalid offset for tensor). Header padding, on the other hand, is sanctioned by the format; the sameREADME says
and the reference writer pads its own headers with spaces to a multiple of 8. The cost is at most 7
bytes of header padding per file.
The tensors' order in the data section changes. The header still maps each name to its offsets.
MLX's readers and the reference reader find tensors by name; the reference reader sorts them by offset
itself. The old order was the hash map's, which differed between macOS and Linux, so nothing could rely
on it. Now macOS and Linux write the same bytes.
main's two recent changes tosave_safetensorsstay as they are: it evaluates its inputs before itopens the file (ml-explore#4434), and it accepts empty arrays (ml-explore#4080), which take
no bytes.
Relationship to a828cb4
This complements "Fix mmap loading for unaligned safetensors tensors",
which made unaligned files load correctly. This stops producing them, so the fast path becomes
reachable rather than merely survivable.
The test
tests/load_tests.cppgains "test save_safetensors aligns tensors without holes". It saves odd-sizedtensors of every width (bool, int8, float16, bfloat16, float32, int64, complex64) and an empty one, and
checks three things from the file's header: the data section starts at a multiple of 8, every tensor's
offset is a multiple of its dtype width, and the tensors' spans tile the data section with no hole, up
to the end of the file.
On
mainit fails the first two (arm64, Clang 21, Release):Against the earlier version of this change, which padded each tensor to 8 bytes, it fails the third:
four
CHECK_EQ( begin, offset )failures, one for each hole.Verification
Three files, each written by this PR on
mainand read back with the mmap loader and with the defaultreader: the eight tensors above; the same plus an empty tensor; and one tensor of every dtype
save_safetensorswrites (bool, uint8, int8, uint16, int16, float16, bfloat16, uint32, int32,float32, uint64, int64, complex64), each of an odd element count.
tensors misaligned and 0 gaps in all three files, and the mmap loader copies nothing (no
realignedline). Every tensor reads back unchanged, with both readers. Onmainthe same run givesrealigned 4,realigned 2andrealigned 6.back unchanged with the reader.
safetensors0.8.0, reads every file from both platforms,with the values that were written.
tests/tests, the same Linux build, with the new case passing:main's 261 cases plus this one.runs leave out.
The layouts were read from each file's header by a separate reader, which also handed each file to
the reference implementation.
Context
Filed upstream as ml-explore/mlx#4439 (it proposed
padding between tensors; this PR does not), closed on 2026-09-01. Upstream (v0.32.3) does not memory-map safetensors, so alignment costs it nothing there.
Here the reader and writer are in the same file and disagree, which is why the fix belongs on this
branch.
Detection needs only each shard's header: the layouts above come from the headers alone.
Not verified
mx.save_safetensorsfrom Python (paths and file objects); only the C++tests/testsran, on Linux.tests/testson macOS.safetensors0.8.0.🤖 Generated with Claude Code