Repository navigation
Studio: run diffusion dataset upload file work on a worker thread - #16361
Merged
Merged
Conversation
This was referenced Nov 1, 2026
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
danielhanchen
added a commit
to LeoBorcherding/unsloth
that referenced
this pull request
Nov 1, 2026
… while the file is unchanged (unslothai#16366) ## What changes `GET /api/train/diffusion/dataset/{name}/images` serves the image dataset showcase on dataset selection, the labeling grid toggle, and every refresh after an upload. On every call it opened each image with Pillow to read the header dimensions. The listing now keeps those dimensions per path in a bounded LRU (8192 entries, like the gallery recipe-chunk cache). The key is the stat the listing already takes for `size_bytes`: `(st_dev, st_ino, st_size, st_mtime_ns, st_ctime_ns)`. The header is read again as soon as any of these changes: a rewrite moves ctime even when mtime is restored, and a replace moves the inode. - Only successful reads are kept. An unreadable or non-image file is opened again on every listing, so a transient error, or a file that later becomes readable, behaves as before (0x0 until it reads). - If the stat fails, the header is read uncached, as before. - Clips still skip Pillow. Caption resolution, ordering, `size_bytes` and every other field are unchanged. - `upload_diffusion_dataset` is not touched. The commit cherry-picks cleanly onto unslothai#16353 and onto unslothai#16361, and all three merge together. ## Results (CPU, TestClient end to end, median of 15 requests, 3 runs each, warm page cache) | images in dataset | base ms (3 runs) | head ms (3 runs) | change | |---|---|---|---| | 20 | 6.9 / 6.6 / 6.7 | 5.5 / 6.7 / 5.5 | within noise | | 100 | 13.7 / 14.3 / 12.8 | 8.5 / 9.0 / 8.4 | -35% | | 200 | 21.8 / 21.6 / 21.0 | 14.1 / 13.7 / 13.9 | -35% | | 1000 | 82.0 / 87.6 / 77.4 | 50.1 / 43.3 / 45.8 | -44% | | 3000 | 229 / 228 / 229 | 136 / 121 / 137 | -42% | The first listing in a process still reads every header and takes as long as on base (20 images: 10-12 ms on both; 200: 19-24 ms on both; 3000: 240-294 ms on both). Fixture: 512x512 PNG and JPEG files, half of them with `.txt` sidecars, and one `metadata.jsonl` row per image. ## Tests - New `studio/backend/tests/test_diffusion_dataset_image_size_cache.py`: - unchanged files are not reopened; - a same-size rewrite with the old mtime restored is read again; - a file swapped in with `os.replace` is read again; - unreadable files are retried on every listing and never kept; - clips never open Pillow; - the LRU bound holds; - a failed stat reads the header uncached. - Base vs head differential over 300 seeded datasets. The fixtures cover: - PNG, JPEG, WebP, BMP and GIF, with mixed-case extensions; - truncated and garbage images, fake clips; - `.txt`, `.caption` and `.TXT` sidecars, including empty, whitespace-only and invalid UTF-8; - AppleDouble files and a directory named `dir.png`; - metadata and captions jsonl with alias keys, duplicates, null, non-string and malformed rows. Each seed ran 6 mutation steps (rewrite, rewrite with the old mtime, replace with the old mtime, delete, add, caption PUT, metadata rewrite) and compared the images listing and `/diffusion/info` after every step. All 4978 responses were byte identical, with 16527 cache hits. As a control, a cache keyed on path only, ignoring the stat key, gives 948 differing responses. - `test_diffusion_dataset_api.py`, `test_diffusion_dataset_clips.py`, `test_dataset_upload_limits.py`, `test_diffusion_train*.py` and `test_diffusion_training*.py`: 369 passed and 4 skipped. The same 3 tests fail on both base and head: - `test_diffusion_train_perf.py::test_gather_sigmas_matches_search_based_gather` - `test_diffusion_train_speed.py::test_checkpoint_modes_match_uncheckpointed_grads[plain]` - `test_diffusion_train_speed.py::test_checkpoint_modes_match_uncheckpointed_grads[partial]` - The suites that read `routes/training.py` as source give the same result on both (725 passed). - `tests/studio -k "dataset or caption or diffusion_train or labeling"`: 5 passed, 1 skipped. ## Not covered - Only measured on Linux ext4. On Windows, `st_ctime` is the creation time, so a same-size rewrite that also restores the old mtime would not be noticed there. The gallery listing cache makes the same tradeoff. The test for that case is skipped on Windows; a normal in-place save, which moves the mtime, is reread on every OS (`test_in_place_rewrite_is_reread`). - The `/diffusion/info` dataset summaries and the metadata reread on caption save are unchanged. At realistic dataset sizes both are below the bar.
danielhanchen
marked this pull request as ready for review
November 1, 2026 10:10
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.
What changes
POST /api/train/diffusion/datasetdid its filesystem work inline in the async route: the folder listing for the caption-stem check, staging every part to disk, the image header checks, the commit and the response summary (one sidecar probe and read per item). Studio uploads a picked folder in slices of 500 parts, so each slice froze the event loop for 0.1 to 0.5 s and every other request (chat streaming, progress polls) waited behind it.The route now keeps the cheap checks and the non-blocking import-lock acquire on the event loop, then runs the rest on a worker thread (
asyncio.to_thread). The code that runs there is the existing body, moved unchanged into_store_diffusion_dataset_upload, except that each chunk is read withUploadFile.file.read, which returns the same bytesUploadFile.readreturns.finallyas before. If the request is cancelled while the worker runs, the lock stays held until the worker finishes, so a second import into the folder still gets a 409. If the request is cancelled before the worker starts, the route releases the lock itself.await, so a cancel while staging still removes the staged files and the newly created folder. A cancel after staging lets the commit finish, as before (the commit never had anawait). A cancelled request also stays pending until the worker stops, so the training interlock (the dataset mutation count that/diffusion/startchecks) and the open uploads stay held for exactly as long as the folder is being changed. Without that, a cancel landing between the worker's last training re-check and the end of its commit would have let a training start reserve the slot while files were still being renamed into the folder.This does not touch the lines changed by #16353 and applies cleanly with or without it.
Results
CPU only. A real uvicorn server, Studio's upload flow (2000 images, each with a
.txtcaption, sent as 8 slices of 500 parts). A ticker GETs a trivial route every 5 ms, and a task inside the server measures event-loop lag. Medians over 3 runs, range in brackets, all with #16353 applied.Time per slice inside the route at 5000 existing pairs, before: names 103 ms, image header checks 10 ms, writes 42 ms, summary 273 ms. All of this now runs on the worker. The lag that remains is mostly multipart parsing of the 500-part body, which Starlette does on the event loop before the route runs.
Upload wall time with no concurrent traffic, 2 rounds x 3 runs: 0 existing pairs 2369 / 2619 ms before vs 2517 / 2756 ms after; 5000 existing pairs 5090 / 5291 ms before vs 5054 / 5049 ms after. Both differences are within the spread between the two "before" rounds.
On main without #16353, at 5000 existing pairs, the quadratic stem check used to hold the loop for 30 s per slice. It now runs on the worker: max loop lag 31.9 s before, 75 ms after.
Tests
studio/backend/tests/test_diffusion_dataset_upload_worker_thread.py: requests are served while a slow summary runs (fails on base); a cancelled request stays pending and keeps the lock until the worker ends; a cancel before the worker starts releases the lock and never runs the worker; a cancel while staging rolls back and removes the created folder; a refusal releases the lock and the next upload works.create_only, case-insensitive mode). Status, body and final folder listing are identical between base and head, both on main and stacked on Studio: list the dataset folder once per upload for the caption-stem check #16353 (898 x 200, 1667 x 400, 435 x 409). The only difference is the random uuid in leftover.upload-backup-*.partnames, and the same seeds leave one on both arms.test_diffusion_dataset_api.py,test_diffusion_dataset_clips.py,test_diffusion_training.py,test_mcp_tools_datasets_images.pyand the new file: 258 passed on head, no failing IDs on base.tests/studio -k "diffusion or dataset or upload or training": 188 passed, 2 skipped.test_diffusion_dataset_upload_stem_index.pyfrom Studio: list the dataset folder once per upload for the caption-stem check #16353 passes stacked with this change.Rerun on a quiet CPU host
Colab CPU High-RAM (8 vCPU, load 0.75), main without #16353, base and head interleaved (ABBA), 3 runs per arm, medians with the range in brackets. 2000 pairs (0 existing) or 1000 pairs (1000 existing), uploaded in slices of 500 parts.
With a 5 ms ticker running, the upload itself takes longer after the change (43 s to 72 s at 0 existing, 33 s to 54 s at 1000), because the ticker's requests are now served and share the GIL with the worker; before, they got no CPU at all until the slice finished. The ticker client ran in the same process as the server here, so part of that cost is the client's own.
A behavioural differential over 600 more seeded cases (random existing folders, batches with bad extensions, case variants, subfolder and backslash names, oversized images,
create_only) gave identical status, body and folder listing on base and head (65 x 200, 502 x 400, 33 x 409). The new test file passes on ubuntu-latest, macos-15 and windows-latest.Not covered