Skip to content

save_safetensors: write files the mmap loader can actually map - #5

Merged
jjang-ai merged 1 commit into
osaurus-ai:mainfrom
rcfa:safetensors-write-aligned
Nov 22, 2026
Merged

jjang-ai merged 1 commit into
osaurus-ai:mainfrom
rcfa:safetensors-write-aligned

Conversation

@rcfa

@rcfa rcfa commented Aug 31, 2026 •

Copy link
Copy Markdown

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
does 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 — and
tensors 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 landed
misaligned. In a CPU-only Linux build the mmap loader gives up (make_buffer fails) and falls back to
the reader.

The base is main (MLX 0.32.3). This replaces the original change, which padded each tensor to
8 bytes: that left gaps between tensors, which the format forbids (see below).

What it costs

On main, on macOS with Metal, save_safetensors wrote eight tensors of 3, 10, 1, 6, 12, 8, 6 and 8
bytes with the data section at byte 508 (4 mod 8). Four of the eight were misaligned, and loading the
file with MLX_SAFETENSORS_MMAP=1 copied them:

[mlx.safetensors.mmap] realigned 4 unaligned tensor(s) (38 bytes) without shard fallback file=…

(the file's path is elided). A file with one tensor of every dtype save_safetensors writes had 6 of
13 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 by
dtype, 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

The byte buffer needs to be entirely indexed, and cannot contain holes.

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 same
README says

The header data MAY be trailing padded with whitespace (0x20).

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 to save_safetensors stay as they are: it evaluates its inputs before it
opens 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.cpp gains "test save_safetensors aligns tensors without holes". It saves odd-sized
tensors 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 main it fails the first two (arm64, Clang 21, Release):

tests/load_tests.cpp:75: ERROR: CHECK_EQ( data_start % 8, 0 ) is NOT correct!
  values: CHECK_EQ( 4, 0 )
tests/load_tests.cpp:87: ERROR: CHECK_EQ( (data_start + begin) % arr.itemsize(), 0 ) is NOT correct!
  values: CHECK_EQ( 4, 0 )
  logged: key := complex64
[doctest] test cases:  262 |  261 passed | 1 failed | 16 skipped

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 main and read back with the mmap loader and with the default
reader: the eight tensors above; the same plus an empty tensor; and one tensor of every dtype
save_safetensors writes (bool, uint8, int8, uint16, int16, float16, bfloat16, uint32, int32,
float32, uint64, int64, complex64), each of an odd element count.

  • macOS, Metal: every data section starts at a multiple of 8 (bytes 512, 576 and 832), 0
    tensors misaligned and 0 gaps
    in all three files, and the mmap loader copies nothing (no
    realigned line). Every tensor reads back unchanged, with both readers. On main the same run gives
    realigned 4, realigned 2 and realigned 6.
  • Linux arm64, CPU-only (Clang 21, Release): the same files, byte for byte, and every tensor reads
    back unchanged with the reader.
  • The reference reader, Hugging Face's safetensors 0.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.
    [doctest] test cases:  262 |  262 passed | 0 failed | 16 skipped
    [doctest] assertions: 3961 | 3961 passed | 0 failed |
    
    The same on x86-64, under Rosetta (Clang 21, Release):
    [doctest] test cases:  262 |  262 passed | 0 failed | 16 skipped
    [doctest] assertions: 3961 | 3961 passed | 0 failed |
    
    The 16 skipped cases are the CPU-JIT cases, which fail in a Clang build of the base and which these
    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

  • The Python tests and mx.save_safetensors from Python (paths and file objects); only the C++
    tests/tests ran, on Linux.
  • tests/tests on macOS.
  • A real model bundle written and loaded at this commit; the 95 GB numbers are the earlier measurement.
  • Readers other than MLX at this commit and safetensors 0.8.0.
  • CUDA and Windows builds.

🤖 Generated with Claude Code

`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
rcfa changed the base branch from codex/gemma4-safetensors-alignment-20260720 to main October 13, 2026 15:40
@rcfa
rcfa force-pushed the safetensors-write-aligned branch from 0c80380 to c3b922b Compare October 13, 2026 15:40
@jjang-ai
jjang-ai merged commit d2998ef into osaurus-ai:main Nov 22, 2026
@rcfa
rcfa deleted the safetensors-write-aligned branch November 23, 2026 00:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants