Skip to content

Studio: list the dataset folder once per upload for the caption-stem check - #16353

Merged
danielhanchen merged 2 commits into
mainfrom
perf/r19-image-upload
Nov 1, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
perf/r19-image-upload

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What changes

POST /api/train/diffusion/dataset checks every incoming image or clip against the files already in the dataset for a name that would share its <stem>.txt caption. Before this change, each incoming media file re-listed the dataset folder and stat'ed every entry, so one request cost (incoming media) x (existing entries) stats. All of it ran synchronously inside the async handler, so the server stopped answering other requests until it finished.

The UI sends a folder in slices of 500 parts (DATASET_UPLOAD_CHUNK), which is 250 image and caption pairs per request. Each slice also lands in the folder before the next one is checked, so a large upload gets slower with every slice even when the folder starts out empty.

The route now lists the folder once per request, at the first media file, and groups the existing media names by casefolded stem in listing order. Each incoming file checks only its own group, using the same _shares_sidecar predicate and the same is_file() test on each candidate. Because the group keeps listing order, the first clash found is the same file as before. The error text, the case rules (casefold, the exemption for casefold-equal names) and the order of the other checks do not change. Batches with only caption files still never list the folder.

Results (base vs head)

The full UI flow through TestClient: each item is a 64x64 PNG plus a .txt caption, sent in slices of 500 parts into a folder that already holds existing pairs. Median of 3 runs with [min-max]; the base run for 5000 existing / 2000 images was done once.

existing pairs images uploaded requests base ms head ms
0 200 1 56.0 [52.8-82.7] 68.2 [55.2-88.5] (noise)
0 2000 8 33973.6 [33462.0-34765.6] 1027.6 [913.4-1052.8]
500 200 1 2033.0 [1966.5-2257.8] 90.8 [90.4-138.1]
500 2000 8 51942.1 [51481.5-52638.2] 1220.2 [1163.3-1316.3]
5000 200 1 19030.0 [18871.0-19465.2] 356.1 [331.0-379.3]
5000 2000 8 222345.5 (1 run) 3097.1 [2991.4-3186.4]

Validation phase only: one slice of 250 pairs, rejected by a clash on its last file so nothing is written. With 500 existing pairs it drops from 2667.5 to 34.5 ms. With 5000 existing pairs it drops from 25934.5 to 102.6 ms.

Tests

  • New studio/backend/tests/test_diffusion_dataset_upload_stem_index.py (7 tests). These cover: the folder is listed once for a 31-file batch (this test fails on base and passes on head), a captions-only batch adds no listing, the exact clash message, the exemption for casefold-equal names, a Unicode casefold clash (straße vs STRASSE), a directory or AppleDouble entry that does not clash, and a clash inside the batch after the index exists.
  • Differential over 3000 seeded fixtures, base vs head. Fixtures include random existing folders (files, directories named like media, live and dangling symlinks, case variants, ß/SS, dotted-I, composed and decomposed é, ._ and dot files) and random batches (backslash and slash prefixes, unsupported extensions, create_only), with the case-insensitive probe forced both ways. Status, response body and final folder listing are byte-identical once the random uuid in leftover backup names is normalized. Of the 3000 cases, 1037 hit a stem clash, 36 a case clash inside the batch, and 551 an unsupported file.
  • Neighbours: test_diffusion_dataset_api.py, test_diffusion_dataset_clips.py, test_diffusion_training.py, test_mcp_tools_datasets_images.py: 253 passed on both base and head. Training route suites that read routes/training.py: 1214 passed. python -m pytest -q tests/studio -k "dataset or upload or diffusion": 110 passed, 2 skipped.

Not covered

  • Run only on Linux ext4 with Python 3.13. The change only compares strings and does not depend on the filesystem: case folding is done by str.casefold() exactly as before, and the probe for case-insensitive filesystems is untouched. No Windows or macOS run was done.
  • Base called is_file() on every entry in the folder. Head calls it only on entries whose casefolded stem matches. An entry whose stat raises an error that is not ignored (for example EIO) would make base fail but not head.
  • The listing is a snapshot taken when the request starts checking names. Base re-listed for each file, but the name loop has no await, so the only thing that could change the folder in between is a thread-pool route writing at that moment.
  • The handler still does synchronous work on the event loop: file writes, the image header check, and the response summary. The summary costs about 180 ms at 5250 pairs. This change does not touch that.

…check

Each incoming image or clip re-listed the dataset folder and stat'ed every
entry to find a name sharing its caption sidecar, so one 250-image slice into
a folder of 5000 captioned images took about 26 s on the event loop. Index the
existing media names by casefolded stem once, in listing order, and check only
that bucket; the predicate, first reported clash and messages are unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

The (Python 3.13, a-f) red here is unrelated to this PR. test_diffusion_bg_compile_idle.py::test_a_compile_elsewhere_thaws_a_frozen_compile_instead_of_deadlocking asserted exactly one thaw of the background compile and read 2. A second thaw is legitimate when a refreeze lands between the lock release and the waiter's next poll. #16364 relaxes the count to >= 1 and keeps the deadlock check. A rerun should pass.

danielhanchen added a commit that referenced this pull request Nov 1, 2026
…e for one waiting compile (#16364)

## Problem


`studio/backend/tests/test_diffusion_bg_compile_idle.py::test_a_compile_elsewhere_thaws_a_frozen_compile_instead_of_deadlocking`,
added in #16312, failed in `(Python 3.13, a-f)` on #16353, which only
changes a training route:

```
tests/test_diffusion_bg_compile_idle.py:270
    assert job.thaws == 1
E   assert 2 == 1
```

The deadlock check right above it passed: the render's compile finished,
and the output was correct. Only the exact thaw count was off.

A second thaw is legitimate. `_thaw_for_lock` lets the frozen compile
run to the end of the frame that holds dynamo's `compile_lock`, where it
releases the lock. `_maybe_freeze` declines to refreeze only while the
lock is owned and a thread is waiting on it. So if the background
compile reaches its next safe call after that release, but before the
waiting thread's next 50 ms `acquire(True, 0.05)` poll, it freezes again
without holding the lock. The waiter's poll then thaws it once more and
takes the lock. No deadlock and no lost progress, but `thaws` reads 2.
That depends only on scheduling, which is why it shows up on a loaded
runner.

## Change

`assert job.thaws == 1` becomes `assert job.thaws >= 1`, with a comment
saying why. The guard this test exists for, `assert not
worker.is_alive()`, which catches a render compile waiting forever on
the frozen trace, is unchanged. So is the later `freezes >= 2` check.

## Verification

- Reproduced on main: 1 of 96 runs failed with `assert 2 == 1` under `-n
12 --count 96` pinned to 2 CPUs.
- This branch: 192/192 pass under `-n 12 --count 192` on 2 CPUs. The
whole file passes 16/16.
- Sabotage: with `_thaw_for_lock` turned into a no-op, so a frozen
compile is never thawed for a waiter, the test does not pass. The
waiting compile deadlocks and the run hung until it was killed. The
assertion still guards what it was written for.
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 marked this pull request as ready for review November 1, 2026 09:17
@danielhanchen
danielhanchen merged commit 3860c60 into main Nov 1, 2026
@danielhanchen
danielhanchen deleted the perf/r19-image-upload branch November 1, 2026 09:17
@danielhanchen danielhanchen self-assigned this Nov 1, 2026
@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-01T09:17:26.833971Z
We couldn’t complete this review. Comment @codex review to try again.
290b0c3 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. You're on a roll.

Reviewed commit: 290b0c3386

ℹ️ 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 NilayYadav/unsloth that referenced this pull request Nov 1, 2026
…slothai#16361)

## 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 unslothai#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 unslothai#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 unslothai#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 unslothai#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 unslothai#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 unslothai#16353 passes
stacked with this change.

### Rerun on a quiet CPU host

Colab CPU High-RAM (8 vCPU, load 0.75), main without unslothai#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.
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