Skip to content

fix: make MPS video generation 1.6x faster with GIL-free block reads - #190

Closed
Sabbagh Fares (Sabmit) wants to merge 3 commits into
Lightricks:mainfrom
Sabmit:mps-disk-streaming-direct-read
Closed

Sabbagh Fares (Sabmit) wants to merge 3 commits into
Lightricks:mainfrom
Sabmit:mps-disk-streaming-direct-read

Conversation

@Sabmit

@Sabmit Sabbagh Fares (Sabmit) commented Oct 31, 2026 •

Copy link
Copy Markdown

Summary

This PR makes stage 1 of video generation on Apple Silicon approximately 2.7 times faster. A 540p 5 s generation becomes 1.4 times faster: 4:56 instead of 6:50 on an M3 Max. The output file is byte-identical to stock. The PR adds no dependencies. The PR has no effect on other platforms.

This PR and #189 are independent. You can merge them in any order. With both PRs, a 540p 5 s video takes 3:35 instead of 6:50.

Problem

On macOS, the transformer weights (39 GiB) stream from the disk in each denoising step. BlockFetcher reads the next block on its I/O thread while the main thread computes the current block.

DiskBlockReader.read_into reads each tensor with safetensors get_tensor. get_tensor holds the GIL during the full read. We checked this in the safetensors Rust bindings at 0.8.0 and on main: the CPU path never releases the GIL. The main thread needs the GIL to queue each MPS operation. Thus the main thread stops while each block loads. Stage 1 queues many small operations per block (2304 video tokens and 126 audio tokens). Stage 1 loses the most time.

On an M3 Max, with a block read on the I/O thread:

Measurement on the main thread No read get_tensor read os.preadv read
Small linear (126 x 2048 x 2048) 0.39 ms 0.92 ms 0.39 ms
Queue 200 small operations 1.4 ms 7.9 ms 1.4 ms

The disk is not the bottleneck. The SSD gives 6.4 GB/s. Stage 1 needs less than 2 GB/s.

Solution

On Darwin, the patch reads each tensor directly from the file into its CPU slot with os.preadv. os.preadv releases the GIL during the read. It does not make a temporary tensor. The bytes are the same bytes that get_tensor copies.

A tensor uses the direct read only when these conditions are true:

  • No SDKeyValueOperation in the reader's sd_ops matches the key. With no match, apply_to_key_value returns the tensor unchanged.
  • The slot is a contiguous CPU tensor. Its dtype, shape, and byte size are equal to the values in the file header.

All other tensors use the original read_into. The patch calls it on a second DiskBlockReader that holds only these tensors. For the LTX-2.5 bf16 transformer, 3744 of the 4032 block tensors (93%) use the direct read. The other 288 tensors are the f32 scale_shift_table tensors. Their slots are bf16, so they keep the get_tensor path and its dtype conversion.

Results

Benchmark: 540p text-to-video

Conditions:

  • MacBook Pro M3 Max, 40-core GPU, 48 GB, AC power, macOS 27.0 (26A428)
  • Headless dev backend at 1.3.1. Each run starts a new backend process.
  • Text-to-video, 540p (1024x576), 5 s, 24 fps, seed 42, Fast decode on
  • 3 rounds. Each round runs the four configurations one after the other. Odd rounds use the opposite order.
  • The stage times come from the progress endpoint. The total is the wall time of the /api/generate request. The total includes the model load.
  • The table shows the median. The range is in parentheses.
Step Stock This PR #189 only #189 and this PR
Stage 1 (8 steps) 3:09 (3:08-3:11) 1:15 (1:11-1:18) 3:11 (3:08-3:12) 1:11 (1:11-1:15)
Stage 2 (3 steps) 1:48 (1:47-2:01) 1:42 (1:40-1:44) 1:49 (1:49-1:50) 1:40 (1:39-1:42)
VAE decode 1:36 (1:32-1:45) 1:39 (1:35-1:41) 0:24 (0:24-0:25) 0:25 (0:24-0:25)
Total 6:50 (6:49-7:12) 4:56 (4:43-4:59) 5:42 (5:39-5:44) 3:35 (3:33-3:36)

Stock and this PR gave the same file in all 6 runs (SHA-256 6d9811b9b0f7...). "#189 only" and "#189 and this PR" gave one other file in all 6 runs (SHA-256 0ffdec439447...). Stage 2 gains less time than stage 1. Its operations are 4 times larger, so the main thread waits for the GIL during a smaller part of its time.

Memory

We sampled /api/gpu-info/mps and footprint -p each second during the runs above. Stock and this PR gave these values:

Stock This PR
Peak MPS driver memory (stage 2) 11.16 GiB 11.16 GiB
Peak torch allocation (model load) 9.83 GiB 9.77 GiB
Physical footprint, during stage 1 14 GB. Malloc Large: 5751 MB 14 GB. Malloc Large: 5238 MB
Physical footprint, idle after the run 6688 MB 6699 MB

The Malloc Large category is 513 MB smaller during streaming. This is the temporary tensor for each weight that get_tensor allocates and this PR does not. The peaks and the idle footprint do not change.

All generation types: smoke suite

We ran performance_runner/sanity.py --tags smoke two times: once with this PR and once without it. Both runs had #189. Both runs gave pass=25 fail=0 skip=3. The 3 skipped tests need IC-LoRA models. We installed these models later and ran all IC-LoRA tests separately (see the next section).

Generation type Without this PR With this PR Speed
Text-to-video 270p, 2 s 204 s 86 s 2.4x
Text-to-video 270p with LoRA 214 s 96 s 2.2x
Text-to-video 540p, 2 s (two stages) 291 s 142 s 2.0x
Image-to-video 270p 218 s 89 s 2.4x
Keyframes 270p 228 s 93 s 2.5x
Keyframes 540p (two stages) 305 s 156 s 2.0x
Audio-to-video 270p, 5 s 281 s 131 s 2.1x
Image and audio to video 270p, 5 s 293 s 130 s 2.3x
Retake (4 modes) 290-292 s 133-138 s 2.1-2.2x
Extend (start or end) 298-309 s 183-191 s 1.6x
Three queued text-to-video jobs 671 s 281 s 2.4x
Text-to-image 40 s 42 s no change
All 25 tests 107 min 51 min 2.1x

The speed increase is the largest for short videos at low resolution, because stage 1 is a large part of their time. Text-to-image does not use block streaming, so it does not change.

IC-LoRA

We installed the union-control and day-to-night IC-LoRA models. Then we ran performance_runner/sanity.py --tags iclora two times: once with this PR and once without it. The conditions were the same as the benchmark. Both runs gave pass=8 fail=0 skip=0.

Test Without this PR With this PR Speed
Canny control 312 s 194 s 1.6x
Depth control 331 s 203 s 1.6x
Day to night 233 s 172 s 1.3x
Day to night, stage 2 on 323 s 239 s 1.4x
Smoke: canny control 292 s 113 s 2.6x
Smoke: depth control 295 s 113 s 2.6x
Smoke: day to night 217 s 89 s 2.4x
Cancel 30 s 26 s 1.1x
All 8 tests 33.8 min 19.2 min 1.8x

The 7 output videos are the same files with and without this PR (same SHA-256). The cancel test has no output.

Same output

  • 11 seeded scenarios and the 3 benchmark runs gave the same file with and without this PR.
  • Text-to-image and the legacy /api/extend and /api/retake requests have no seed. Each run gives a different output.
  • 4 image scenarios gave different files in one long run without this PR. We ran these scenarios again, alone, with and without this PR. In each scenario, all runs gave the same file. That file was the same as the file from the long run with this PR. Thus this PR is not the cause of the difference. We did not find the cause.

Previous work

We did not find a previous report of this problem.

How to check this PR

  1. Run pnpm backend:test -- tests/test_disk_streaming_direct_read.py.
  2. On a Mac, generate the same seeded video with and without this PR. Compare the SHA-256 of the two files. They must be the same.
  3. Look for this line in the backend log: Disk streaming reads blocks with os.preadv (GIL released).

Checks

  • pnpm typecheck: 0 errors
  • pnpm backend:test: all tests pass. The one skipped test is for Windows only.
  • backend/tests/test_disk_streaming_direct_read.py: 5 tests. Each test finds one error in the patch. We put each error into the patch, one at a time. Each time, the related test failed. These are the errors: incorrect file offsets, raw bytes for a tensor that an SDKeyValueOperation must change, a slot with a different dtype, file descriptors that stay open, and the patch installed on a platform that is not macOS.

Removal

Remove this patch when ltx-core DiskBlockReader reads without the GIL, or when safetensors get_tensor releases the GIL during CPU reads.

DiskBlockReader.read_into reads each block tensor with safetensors
get_tensor on the BlockFetcher I/O thread. get_tensor holds the GIL
while it reads. The main thread must have the GIL to queue each MPS
operation, so it stops while each block loads.

On Darwin, read each tensor directly into its CPU slot with os.preadv.
os.preadv releases the GIL. A tensor uses the original path when an
SDKeyValueOperation matches its key, or when the slot does not have
the dtype and shape from the file.
Each test finds one bug: incorrect file offsets, raw bytes for a tensor
that sd_ops must change, a slot with a different dtype, a block key map
that is not restored, file descriptors that stay open, and the patch
installed on a platform that is not macOS.
The direct-read patch handed the original read_into the fallback keys by
swapping them into the reader's block key map and restoring the map in a
finally block. A second DiskBlockReader that holds only the fallback keys
does the same job without touching the shared map, so the restore test
and its thread-safety note go away.

Claude-Session: https://claude.ai/code/session_01M8Y4f9pRwDZfXY2VAqZNvz
@bureyburey

Copy link
Copy Markdown
Member

Hi Sabbagh Fares (@Sabmit), thank you for this PR and for the detailed work. The GIL analysis, the benchmarks, and the byte-identical output check were very helpful. We also apologize that we did not review it sooner.

We are not going to merge this PR. The reason is that LTX-2 v1.6.0 changed the loader in ltx-core. The ltx_core.block_streaming package, with DiskBlockReader, is removed. Disk streaming now goes through ltx_core/loader/raw.py. It reads each tensor with os.preadv into a caller buffer, on a pool of read workers. This is the same approach as your patch. It does not use get_tensor.

Desktop v1.3.2 uses ltx-core 1.6.0. Your patch targets code that no longer exists in that version, so it has no effect there.

Thank you again. If you still see the stall on Apple Silicon with ltx-core 1.6.0 or later, please send us the measurement. We will look at it again. We are closing this PR.

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