Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: serialize LoRA caption vision calls across runs so concurrent runs don't fan out parallel requests at a single-GPU backend

[._.]/ Adam Eivy0bc4fc46d2ee
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3991d26964..3cfa2cd0f0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,8 @@
## Fixed
+- **Concurrent LoRA caption runs no longer fan out parallel requests at a single-GPU backend** — Within one run the captioner already processes images one at a time, but nothing stopped several runs from overlapping (captioning two datasets at once, re-captioning multiple single images, or a double-click). Each run is a detached loop, so concurrent runs fired N parallel `/chat/completions` requests at the same local Ollama/LM Studio — and on one GPU that's pure downside: every Ollama parallel slot reserves its own 32K-token KV cache, so concurrent vision requests multiply VRAM and risk an OOM or model reload, while parallel decoding gives no throughput win (it just time-slices the same compute and makes each request slower). A module-level mutex now serializes every caption vision call across all runs, holding backend load at concurrency 1 regardless of how many runs are in flight. One-shot vision calls (voice `ui_describe_visually`, the vision-test page) stay off the lock so a long batch run can't FIFO-starve an interactive describe. (`server/services/loraDatasetCaption.js`)
+
- **LoRA auto-captions no longer silently come back as just the trigger word** — When a vision model returned an empty reply (common when it refuses a realistic close-up face, or when a thinking model spends its whole token budget reasoning), the captioner prefixed that empty string with the trigger word and saved the result — so the image was bound but undescribed, yet the run still logged it as captioned. A blank model reply is now treated as a per-image failure: it's surfaced in the caption run's progress (with the model name and a hint to try a different vision model or caption manually) and never persisted, so the image stays un-captioned and a re-run re-attempts it instead of leaving a degenerate trigger-word-only caption. (`server/services/loraDatasetCaption.js`)
- **LoRA caption-model picker now sees vision-capable Ollama models whose name lacks a `vl`/`vision` token** — The picker showed "none installed" even with a vision model like the `qwen3.6:35b` MoE installed, because Ollama's `/api/tags` carries no vision flag and the id heuristic only matches names containing a `vl`/`vision`/known-family token. Ollama *does* report `capabilities: ["…","vision",…]` via `/api/show`, but PortOS only consulted that for LM Studio. `listVisionModels` now enriches each Ollama model the id heuristic doesn't already catch with its `/api/show` capabilities (cached per model, busted on delete), so capability-tagged vision models surface in the picker — and, through the same path, in the captioner's auto-pick and explicit-model validation. (`server/services/ollamaManager.js`, `server/services/localLlm.js`)
diff --git a/server/services/loraDatasetCaption.js b/server/services/loraDatasetCaption.js
index c022ace4a5..7ce04769d9 100644
--- a/server/services/loraDatasetCaption.js
+++ b/server/services/loraDatasetCaption.js
@@ -4,7 +4,11 @@
* Sequential loop (vision backends are local; concurrency 1) over the
* dataset's ready images: read file → base64 data URL →
* `describeImageDataUrl` (the same provider pathway the voice agent's
- * ui_describe_visually tool uses) → trigger-word prefix → persist.
+ * ui_describe_visually tool uses) → trigger-word prefix → persist. A
+ * module-level mutex (`withCaptionVisionLock`) extends that concurrency-1
+ * guarantee ACROSS runs, so overlapping caption runs can't fan out parallel
+ * requests at a single-GPU backend (see the lock's header for why parallel
+ * local vision is pure downside).
* Progress streams over the shared per-job SSE helpers; the client
* subscribes via `GET /api/lora-datasets/:id/caption-runs/:runId/events`
* and refetches the dataset on the terminal frame.
@@ -23,6 +27,7 @@ import { shortId } from '../lib/fileUtils.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { prefixCaption } from '../lib/loraDataset.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';
+import { createMutex } from '../lib/asyncMutex.js';
import { describeImageDataUrl } from './visionTest.js';
import { getSettings } from './settings.js';
import { listVisionModels } from './localLlm.js';
@@ -39,6 +44,23 @@ export const CAPTION_PROMPT = [
const CAPTION_MAX_TOKENS = 300;
+// Module-level mutex serializing every vision call across ALL caption runs.
+// Within one run the loop is already sequential, but nothing stops a user (or
+// the UI) from kicking off several runs at once — caption Dataset A + Dataset B,
+// re-caption multiple single images, or double-click the button. Each run is a
+// detached loop, so concurrent runs would fire N parallel `/chat/completions`
+// requests at the same local backend. On a single-GPU Ollama/LM Studio that is
+// pure downside: every Ollama parallel slot reserves its own `num_ctx` KV cache
+// (PortOS uses 32K), so concurrent vision requests multiply VRAM and risk an
+// OOM/model reload, while parallel decoding gives no throughput win on one GPU —
+// it just time-slices the same compute and makes each request slower. Funnelling
+// every image through this lock keeps backend load at concurrency 1 (predictable
+// VRAM, no slower-per-request) regardless of how many runs are in flight. Scoped
+// to caption runs only — one-shot vision calls (voice `ui_describe_visually`, the
+// vision-test page) deliberately stay off this lock so a long batch run can't
+// FIFO-starve an interactive describe.
+export const withCaptionVisionLock = createMutex();
+
// runId → { clients: [], lastPayload } — same shape the imageGen/videoGen
// SSE helpers operate on.
const captionRuns = new Map();
@@ -176,13 +198,13 @@ export async function startCaptionRun(datasetId, {
try {
const bytes = await readFile(datasetImagePath(datasetId, img.file));
const dataUrl = `data:image/png;base64,${bytes.toString('base64')}`;
- const text = await describeImageDataUrl({
+ const text = await withCaptionVisionLock(() => describeImageDataUrl({
dataUrl,
prompt: CAPTION_PROMPT,
providerId: resolvedProvider,
model: resolvedModel,
maxTokens: CAPTION_MAX_TOKENS,
- });
+ }));
caption = buildCaption(dataset.triggerWord, text, `vision model "${resolvedModel}"`);
} catch (err) {
failed += 1;
diff --git a/server/services/loraDatasetCaption.test.js b/server/services/loraDatasetCaption.test.js
index a6087b9a6c..9db56bda06 100644
--- a/server/services/loraDatasetCaption.test.js
+++ b/server/services/loraDatasetCaption.test.js
@@ -4,7 +4,7 @@ import { describe, it, expect, vi } from 'vitest';
// branches are testable without touching the network/DB. The module still
// pulls in localLlm transitively at import; that's import-only (no calls fire
// until resolveCaptionModel runs with our stub), so no mocks are needed.
-const { resolveCaptionModel, buildCaption } = await import('./loraDatasetCaption.js');
+const { resolveCaptionModel, buildCaption, withCaptionVisionLock } = await import('./loraDatasetCaption.js');
const VISION = [
{ providerId: 'lmstudio', backend: 'lmstudio', id: 'qwen2.5-vl-7b', name: 'Qwen2.5-VL 7B', vision: true },
@@ -84,3 +84,33 @@ describe('buildCaption', () => {
.toThrow(/llava:7b/);
});
});
+
+describe('withCaptionVisionLock', () => {
+ it('serializes overlapping vision calls so concurrent runs never overlap at the backend', async () => {
+ // Two caption runs firing at once must NOT produce two in-flight vision
+ // requests — on a single-GPU Ollama that doubles KV-cache VRAM. The lock
+ // forces concurrency 1: while one "vision call" is mid-await, a second
+ // call kicked off in parallel must wait for it to finish.
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const visionCall = () => withCaptionVisionLock(async () => {
+ inFlight += 1;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await new Promise((r) => setTimeout(r, 5)); // simulate a backend round-trip
+ inFlight -= 1;
+ });
+
+ await Promise.all([visionCall(), visionCall(), visionCall()]);
+
+ expect(maxInFlight).toBe(1);
+ });
+
+ it('runs calls in submission order (FIFO)', async () => {
+ const order = [];
+ await Promise.all([1, 2, 3].map((n) => withCaptionVisionLock(async () => {
+ await new Promise((r) => setTimeout(r, 1));
+ order.push(n);
+ })));
+ expect(order).toEqual([1, 2, 3]);
+ });
+});