Skip to content

Studio: run diffusion dataset upload file work on a worker thread - #16361

Merged
danielhanchen merged 4 commits into
mainfrom
perf/r19-upload-summary
Nov 1, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
perf/r19-upload-summary

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

What changes

POST /api/train/diffusion/dataset did 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 with UploadFile.file.read, which returns the same bytes UploadFile.read returns.

  • Import lock: the worker releases it in the same finally as 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.
  • Cancellation: a cancelled request sets a flag. The worker checks it at each chunk read, the same place the old code had an 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 an await). A cancelled request also stays pending until the worker stops, so the training interlock (the dataset mutation count that /diffusion/start checks) 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.
  • Training interlock, the re-check before commit, rollback, error details and response fields are unchanged.

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 .txt caption, 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.

existing pairs metric before after
0 event-loop max lag 141.6 ms [127-158] 79.7 ms [65-174]
0 ticker request max 125.6 ms [122-154] 19.3 ms [11-46]
0 ticker request p99 89.3 ms [88-97] 7.6 ms [6.9-10.6]
5000 event-loop max lag 554.9 ms [500-572] 76.3 ms [74-87]
5000 ticker request max 498.6 ms [485-575] 92.0 ms [54-117]
5000 ticker request p99 428.7 ms [418-436] 39.0 ms [38-48]
5000 total loop time lost to stalls over 20 ms 3558 ms 379 ms

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

  • New 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.
  • Differential: 3000 seeded fixtures (random existing folders including directories, live and broken symlinks, case and Unicode variants; random batches including backslash and subfolder names, 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-*.part names, 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.py and 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.
  • Combines cleanly with Studio: list the dataset folder once per upload for the caption-stem check #16353 (its stem index hunk lands inside the moved body); the combined tree passes the same suites.
  • test_diffusion_dataset_upload_stem_index.py from 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.

existing pairs metric before after
0 upload wall, no other traffic 41.9 s [41.4-42.0] 41.6 s [41.1-41.6]
1000 upload wall, no other traffic 32.4 s [32.1-32.8] 31.4 s [31.4-31.5]
0 ticker request max 9.9 s 143 ms
1000 ticker request max 9.9 s 50 ms
1000 ticker request p99 7.1 s 39 ms

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

  • Windows and macOS ran only the new test file (staging CI), not the timing benchmark.
  • Python 3.9 was only checked by parsing the files. The tests ran on 3.13.
  • Not tested: a real client disconnect through Studio's full middleware stack. Cancellation is covered by the unit tests above.
  • The summary still reads every caption file on each slice (about 275 ms at 7000 pairs; one listing plus the reads would be about 88 ms). That is left for a follow-up because it has to reproduce the filesystem's case folding exactly.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-01T10:10:49.520274Z
We couldn’t complete this review. Comment @codex review to try again.
ada25d6 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 4502af39d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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 danielhanchen self-assigned this Nov 1, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review November 1, 2026 10:10
@danielhanchen
danielhanchen merged commit d148c97 into main Nov 1, 2026
@danielhanchen
danielhanchen deleted the perf/r19-upload-summary branch November 1, 2026 10:10
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.

1 participant