Skip to content

perf(vits): cut per-batch preprocessing from seconds to a fraction - #16

Merged
danellecline merged 4 commits into
fix/embedding-ws-timeoutsfrom
perf/batch-preprocessing
Oct 6, 2026
Merged

danellecline merged 4 commits into
fix/embedding-ws-timeoutsfrom
perf/batch-preprocessing

Conversation

@danellecline

Copy link
Copy Markdown
Member

What

Preprocessing 128 images took 10–13s per batch, entirely on the CPU with the GPU idle.
Three independent causes:

  1. The image processor was the slow variant. AutoImageProcessor.from_pretrained() with
    use_fast unset resolves to the slow processor unless the checkpoint was saved with a
    fast one — in transformers 4.57 only Qwen2VLImageProcessor is force-upgraded
    (FORCE_FAST_IMAGE_PROCESSOR). The slow path resizes, rescales and normalizes one image
    at a time in Python/NumPy.
  2. Images were decoded serially, one Image.open/load/convert at a time.
  3. Every upload was round-tripped through a temp file so PIL could read it straight back
    off disk, despite the bytes already being in memory from the HTTP request.

Changes

  • Request the torchvision-backed fast processor; log which class actually loaded so it's
    visible at startup. VSS_FAST_PROCESSOR=0 restores the old behaviour.
  • Decode the batch on a thread pool (VSS_DECODE_WORKERS, default min(8, cpu_count)).
    PIL releases the GIL inside load(), so this scales with cores.
  • Pass in-memory buffers instead of temp files; removes the cleanup path entirely.
  • preprocess_images() now accepts paths or buffers, plus optional labels used for
    logging and the failed-image report.

Measured

128 × 1024px crops, 2 cores — decode only, excluding the processor change:

time
temp-file + serial decode 5.33s
in-memory + threaded decode 1.88s (2.8×)

More cores will do better. The use_fast change is on top of this and should be the larger
win.

danellecline and others added 4 commits August 24, 2026 18:05
…ime (#15)

Clients embedding a dataset through /embed + /ws/predict/job saw bursts of
inter-frame timeouts as soon as more than a couple of batches were in flight.
Two defects on this side contributed.

1. Blocking Redis calls ran inline on the event loop.
   Job.exists, Job.fetch and job.return_value() are synchronous redis-py calls,
   and ws_job_result is an async endpoint sharing one event loop with every
   other connection this process serves. Under N concurrent job sockets each
   polling at 1/WS_POLL_INTERVAL, plus concurrent multipart uploads, the loop
   spent its time inside Redis round-trips and unpickling embedding payloads --
   delaying the very heartbeat frames clients use to distinguish a slow job
   from a dead connection, and so causing the timeouts it was meant to prevent.
   All three now go through asyncio.to_thread; redis-py clients are thread-safe
   (they hold a connection pool), as is unpickling a result.

2. WS_MAX_WAIT counted loop iterations, not elapsed time.
   `elapsed += WS_POLL_INTERVAL` measured only the sleeps and ignored how long
   each Redis round-trip took, so the effective limit drifted arbitrarily far
   past WS_MAX_WAIT under load -- exactly when a real bound matters. It is now
   a time.monotonic() deadline, and the timeout frame reports how long it
   actually waited.

WS_MAX_WAIT and WS_POLL_INTERVAL are now environment-configurable, and the
default wait is raised from 300s to 1800s: jobs are processed by a single
serial RQ worker per project, so a job submitted while several others are
queued ahead of it legitimately waits for all of them, and 300s cut clients off
mid-job. A failed job now names itself in the message instead of sending a bare
{"status": "failed"}.

Note this does not raise throughput -- one worker per project still processes
jobs serially, so client-side concurrency only queues them faster. Scaling the
rq-worker service is the lever for that.


Claude-Session: https://claude.ai/code/session_019s65VkcHwERBZrXXpaivVy

Co-authored-by: Claude <noreply@anthropic.com>
Automatically generated by python-semantic-release
"Preprocessing 128 images" took 10-13s per batch, all of it on the CPU with the
GPU idle. Three causes, all addressed here.

1. The image processor was the slow one. AutoImageProcessor.from_pretrained()
   with `use_fast` unset resolves to the slow processor unless the checkpoint was
   saved with a fast one -- in transformers 4.57 only Qwen2VL is force-upgraded
   (FORCE_FAST_IMAGE_PROCESSOR). The slow path resizes, rescales and normalizes
   one image at a time in Python/NumPy. Request the torchvision-backed fast
   processor instead, and log which class was actually loaded so this is visible
   at startup. Fast output differs very slightly (torchvision resize vs PIL), so
   VSS_FAST_PROCESSOR=0 restores the old behaviour for a Redis index built with
   the slow processor.

2. Images were decoded one at a time. PIL releases the GIL inside load(), so the
   batch now decodes on a thread pool (VSS_DECODE_WORKERS, default min(8, cpu)).
   Measured 2.8x on a 2-core box for 128 1024px crops; more with more cores.

3. Every uploaded image was written to a temp file so PIL could read it straight
   back off disk, despite the bytes already being in memory from the HTTP
   upload. Pass in-memory buffers instead, which also removes the temp-file
   cleanup path entirely.

preprocess_images() now takes paths or in-memory buffers, plus optional labels
used for logging and the failed-image report. Passing a list of paths behaves
exactly as before, so predict_from_list.py and tests/load.py are unaffected.
pool.map preserves order, which matters because embeddings are matched back to
their inputs positionally.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019s65VkcHwERBZrXXpaivVy
Use the MBARI mldevops account (uid 12078, gid 20) instead of a generic
appuser, fix ownership of app/venv/cache paths, and expose GIT_VERSION as
org.opencontainers.image.version for release tagging. Keeps
huggingface_hub==0.36.2 so transformers 4.57.6/DINOv3 loads cleanly.

Fixes #12

Co-authored-by: Cursor <cursoragent@cursor.com>
@danellecline
danellecline merged commit d74a6fb into fix/embedding-ws-timeouts Oct 6, 2026
1 check passed
@danellecline
danellecline deleted the perf/batch-preprocessing branch October 30, 2026 04:09
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