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

keep a character's signature look out of LoRA captions so the trigger word learns it

[._.]/ Adam Eivy507e83669f09
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 915c4180a5..185cd0e5c7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,7 @@
## Local model stack
+- **[issue-1320] LoRA captioning now keeps a subject's signature look out of the captions, so the trigger word learns it — and training won't silently start when identity is still leaking.** A LoRA binds whatever the captions *don't* describe to the trigger word, so naming a character's always-present cloak/crown/armor in every caption taught the model those phrases instead of the trigger — the bare trigger then rendered a generic subject. Two changes close the loop: (1) the vision captioner is now told to describe **only what changes shot-to-shot** (pose, framing, expression, lighting, setting) and to omit fixed identity — and when the bible knows the subject's signature wardrobe/props/palette, those are passed in by name as an explicit do-not-mention list, so they're omitted even when the model would have phrased them differently each shot (the case the post-hoc shared-fragment strip misses, since it only matches exact repeated phrasing). (2) Launching a training run now **re-checks for caption identity-leak and blocks** (409 `CAPTION_IDENTITY_LEAK`, listing the offending fragments) instead of training silently — the panel offers "Strip identity & queue" or "Train anyway," and resume skips the gate. This is the dataset-quality groundwork before the #1321 base-tier fidelity bench. (`server/services/loraDatasetCaption.js`, `server/services/loraDatasetGenerate.js`, `server/services/loraTraining/dataset.js`, `client/src/components/loraTraining/TrainingPanel.jsx`)
- **[issue-1329] Pinned a validated mlx/mlx-metal trio for LoRA training so the GPU-watchdog stack can't silently drift back to the known-bad build.** The three M5 Max kernel panics during FLUX.2 LoRA training all happened on mlx/mlx-metal 0.30.6, but `setup-image-video.sh` installed `mflux>=0.17` as a *floor* and let pip resolve mlx under mflux's `mlx<0.32` cap — so a reinstall could land back on a panicking build. The setup script now pins the bisect-validated trio **mflux 0.17.5 · mlx 0.31.2 · mlx-metal 0.31.2**, proven by run `d36562a0` completing a full LoRA training to adapter extraction (flux2-klein-4b, bf16, 768px, segmentation on) on the panicking M5 Max with no panic or reboot. The runtime-fingerprint half shipped earlier (#1406). (`scripts/setup-image-video.sh`, `docs/research/2026-06-13-mflux-training-watchdog-panic.md`)
- **[issue-1329] Applied the upstream-confirmed fix for the LoRA-training GPU watchdog panic.** A search of the MLX tracker turned up the root cause: [mlx #3267](https://github.com/ml-explore/mlx/issues/3267) — the Metal GPU watchdog kills sustained LoRA training whose command buffers compete with active-display compositing (escalating to a `watchdogd` kernel panic + hard reboot on M5-class silicon). The MLX maintainer's confirmed workaround is the `AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1` env var, which PortOS now sets automatically in the trainer (it propagates to the `mflux-train` child; set it to `0` to disable). The trainer logs `STATUS:watchdog mitigation · AGX_RELAX_CDM_CTXSTORE_TIMEOUT=…` so a paniclog records whether it was active. Notably, per #3267 the kill is at the IOGPU layer *above* the process boundary — so process-teardown segmentation alone does not prevent it, and the strongest user-side mitigation is to keep the display off (SSH headless or `pmset displaysleepnow`) for heavy sustained runs. Our data points were posted to #3267 rather than filed as a duplicate. (`scripts/train_mflux_lora.py`, `docs/TROUBLESHOOTING.md`, `docs/research/2026-06-13-mflux-training-watchdog-panic.md`)
- **[issue-1329] Confirmed on the M5 Max what actually stops the watchdog panic: keeping the display off.** A clean A/B on the *same* 9B-bf16 segmentation-OFF config (the heaviest, most panic-prone) — both with `AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1` set — settled it: with the **display active** the box hard-rebooted at step 0 within minutes (first telemetry-captured panic showed Nominal thermal pressure, i.e. a GPU **driver hang** not heat, with `WindowServer` the top-CPU thread); with the **display asleep** (`pmset displaysleepnow`) the identical run reached **step 302**, clearing the documented 150–300 panic window with no panic. So the env var is necessary but not sufficient for heavy runs — for a 9B/heavy bf16 job, drive the box over SSH or sleep the display, and keep segmentation on. `caffeinate -s` does not sleep the display, and closing the lid suspends the whole machine. TROUBLESHOOTING now documents the working recipe. (`docs/TROUBLESHOOTING.md`, `docs/research/2026-06-13-mflux-training-watchdog-panic.md`)
diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsx
index 247cc51f96..74fd441df3 100644
--- a/client/src/components/loraTraining/TrainingPanel.jsx
+++ b/client/src/components/loraTraining/TrainingPanel.jsx
@@ -9,7 +9,7 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
-import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles, RotateCcw, Moon } from 'lucide-react';
+import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles, RotateCcw, Moon, AlertTriangle, Eraser } from 'lucide-react';
import toast from '../ui/Toast';
import { useSseProgress } from '../../hooks/useSseProgress';
import CheckpointPicker from './CheckpointPicker';
@@ -21,6 +21,7 @@ import {
cancelLoraTrainingRun,
resumeLoraTrainingRun,
listImageModels,
+ stripLoraDatasetSharedCaptionFragments,
} from '../../services/api';
const isActive = (run) => run && ['queued', 'running'].includes(run.status);
@@ -35,6 +36,11 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
const [starting, setStarting] = useState(false);
const [canceling, setCanceling] = useState(false);
const [resuming, setResuming] = useState(false);
+ // Server-detected caption identity-leak (409 CAPTION_IDENTITY_LEAK): the
+ // fragments that repeat + the captioned-image total they're measured against.
+ // Non-empty fragments → render the inline confirm row instead of queueing.
+ const [captionLeak, setCaptionLeak] = useState({ fragments: [], total: 0 });
+ const [strippingLeak, setStrippingLeak] = useState(false);
useEffect(() => {
getLoraTrainingStatus().then((s) => {
@@ -100,17 +106,49 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
// installed, else the torch venv. Either being ready unblocks training.
const engineReady = !!(status?.runtimes?.mflux?.ready || status?.runtimes?.flux2?.ready);
- const start = async () => {
+ // `silent: true` — this owns its own error surfacing: the expected
+ // CAPTION_IDENTITY_LEAK 409 becomes the inline confirm row (not a toast), and
+ // every other failure toasts here exactly once.
+ const start = async ({ acknowledgeCaptionLeak = false } = {}) => {
setStarting(true);
try {
- await startLoraTrainingRun({ datasetId: dataset.id, baseModelId, params });
+ await startLoraTrainingRun(
+ { datasetId: dataset.id, baseModelId, params, acknowledgeCaptionLeak },
+ { silent: true },
+ );
+ setCaptionLeak({ fragments: [], total: 0 });
toast.success('Training queued');
refreshRuns();
+ } catch (err) {
+ if (err?.code === 'CAPTION_IDENTITY_LEAK') {
+ setCaptionLeak({ fragments: err.context?.sharedFragments || [], total: err.context?.total || 0 });
+ } else {
+ toast.error(err?.message || 'Failed to queue training');
+ }
} finally {
setStarting(false);
}
};
+ // From the leak row: strip the shared identity fragments server-side, sync the
+ // parent's caption view, then re-launch (the gate now passes).
+ const stripAndQueue = async () => {
+ setStrippingLeak(true);
+ try {
+ const { removedFragments } = await stripLoraDatasetSharedCaptionFragments(dataset.id);
+ if (removedFragments?.length) {
+ toast.success(`Stripped ${removedFragments.length} shared identity fragment${removedFragments.length === 1 ? '' : 's'}`);
+ }
+ onRunFinished?.(); // parent reloads the dataset so captions + the lint banner refresh
+ setCaptionLeak({ fragments: [], total: 0 });
+ await start();
+ } catch (err) {
+ toast.error(err?.message || 'Failed to strip captions');
+ } finally {
+ setStrippingLeak(false);
+ }
+ };
+
const cancel = async () => {
if (!activeRun) return;
setCanceling(true);
@@ -369,6 +407,49 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
</div>
</div>
)}
+ {captionLeak.fragments.length > 0 && (
+ <div className="bg-port-warning/10 border border-port-warning/40 rounded-lg p-3 text-sm space-y-2">
+ <div className="flex items-start gap-2">
+ <AlertTriangle className="w-4 h-4 text-port-warning shrink-0 mt-0.5" />
+ <p className="text-gray-200 min-w-0">
+ <span className="font-medium text-port-warning">Identity is leaking into the captions.</span>{' '}
+ These fragments repeat across most images, so the{' '}
+ <span className="font-mono text-gray-300">{dataset.triggerWord || 'trigger'}</span>{' '}
+ token would learn a generic subject. Strip them so the trigger absorbs the fixed identity, or train anyway.
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ {captionLeak.fragments.map((f) => (
+ <span
+ key={f.normalized}
+ className="text-xs px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-gray-300 font-mono"
+ title={`in ${f.count} of ${captionLeak.total} captions`}
+ >
+ {f.fragment}<span className="text-gray-500"> ·{f.count}</span>
+ </span>
+ ))}
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={stripAndQueue}
+ disabled={strippingLeak || starting}
+ className="px-3 py-1.5 text-xs rounded bg-port-warning/20 text-port-warning hover:bg-port-warning/30 flex items-center gap-2 disabled:opacity-50"
+ >
+ {strippingLeak ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Eraser className="w-3.5 h-3.5" />}
+ Strip identity &amp; queue
+ </button>
+ <button
+ type="button"
+ onClick={() => start({ acknowledgeCaptionLeak: true })}
+ disabled={strippingLeak || starting}
+ className="px-3 py-1.5 text-xs rounded border border-port-border text-gray-300 hover:bg-port-bg flex items-center gap-2 disabled:opacity-50"
+ >
+ Train anyway
+ </button>
+ </div>
+ </div>
+ )}
<div className="flex items-center justify-between gap-2">
<span className={`text-xs ${!disabledReason && readiness?.quality === 'minimum' ? 'text-port-warning' : 'text-gray-500'}`}>
{disabledReason
@@ -378,8 +459,8 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
</span>
<button
type="button"
- onClick={start}
- disabled={!!disabledReason || starting}
+ onClick={() => start()}
+ disabled={!!disabledReason || starting || strippingLeak}
className="px-3 py-2 text-sm rounded bg-port-accent text-white disabled:opacity-50 flex items-center gap-2"
>
{starting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Dumbbell className="w-4 h-4" />}
diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.js
index 6a438df9eb..3bdc639896 100644
--- a/client/src/services/apiLoraTraining.js
+++ b/client/src/services/apiLoraTraining.js
@@ -90,10 +90,17 @@ export const stripLoraDatasetSharedCaptionFragments = (id) =>
export const getLoraTrainingStatus = () => request('/lora-training/status');
-export const startLoraTrainingRun = ({ datasetId, baseModelId, name, params }) =>
+export const startLoraTrainingRun = ({ datasetId, baseModelId, name, params, acknowledgeCaptionLeak }, options = {}) =>
request('/lora-training/runs', {
method: 'POST',
- body: JSON.stringify({ datasetId, baseModelId, ...(name ? { name } : {}), ...(params ? { params } : {}) }),
+ silent: options.silent,
+ body: JSON.stringify({
+ datasetId,
+ baseModelId,
+ ...(name ? { name } : {}),
+ ...(params ? { params } : {}),
+ ...(acknowledgeCaptionLeak ? { acknowledgeCaptionLeak: true } : {}),
+ }),
});
export const listLoraTrainingRuns = (filters = {}) => {
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 9e675e717c..32a868712b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -905,6 +905,9 @@ export const startTrainingRunSchema = z.object({
baseModelId: z.string().min(1).max(128),
name: z.string().trim().max(120).optional(),
params: loraTrainingParamsSchema.optional(),
+ // Override the caption identity-leak gate (see validateDatasetReady) and train
+ // anyway — the UI sends this from the explicit "Train anyway" action.
+ acknowledgeCaptionLeak: z.boolean().optional(),
});
// Query for GET /api/city/snapshots — `since` (ISO timestamp) and `limit`
diff --git a/server/services/loraDatasetCaption.js b/server/services/loraDatasetCaption.js
index bb5171239f..dd79c3ede0 100644
--- a/server/services/loraDatasetCaption.js
+++ b/server/services/loraDatasetCaption.js
@@ -33,14 +33,47 @@ import { getSettings } from './settings.js';
import { listVisionModels } from './localLlm.js';
import { isVisionModel } from '../lib/localModelHeuristics.js';
import { getDataset, updateDataset, datasetImagePath } from './loraDatasets.js';
+import { loadDatasetSubject, extractSubjectSignaturePhrases } from './loraDatasetGenerate.js';
-export const CAPTION_PROMPT = [
- 'Describe the person or character in this image for image-generation training:',
- 'pose, camera angle, expression, clothing, visible accessories, and framing',
- '(full body / bust / close-up). Reply with ONE comma-separated list of short',
- 'fragments. Do not mention art style, the character\'s name, or that this is',
- 'an illustration.',
-].join(' ');
+/**
+ * Build the vision-captioning instruction. A LoRA binds whatever the captions
+ * DON'T describe to the trigger word, so a strong character/object/place caption
+ * names only what changes shot-to-shot (pose, framing, lighting, setting) and
+ * deliberately omits the subject's permanent identity — hair, build, signature
+ * outfit, recurring props, palette. Captioning those in every shot teaches the
+ * model the phrases instead of the trigger, and the bare trigger then renders a
+ * generic subject (issue #1320). When the bible knows the subject's signature
+ * features, we name them explicitly so the model omits them even when it would
+ * have phrased them differently shot-to-shot (the case the post-hoc
+ * shared-fragment strip misses, since it matches on exact repeated phrasing).
+ *
+ * `signaturePhrases` — discrete always-present features (wardrobe, props,
+ * palette) to call out by name; empty for uploaded datasets with no bible
+ * subject, where the general guidance still applies.
+ */
+export function buildCaptionPrompt(signaturePhrases = []) {
+ const omit = (Array.isArray(signaturePhrases) ? signaturePhrases : [])
+ .map((p) => (typeof p === 'string' ? p.trim() : ''))
+ .filter(Boolean);
+ return [
+ 'Describe ONLY what changes from shot to shot in this image, for image-generation training:',
+ 'pose, body position, camera angle, expression, framing (full body / bust / close-up),',
+ 'lighting, and background or setting. If the outfit clearly differs from the subject\'s',
+ 'usual look, name it briefly; otherwise do not describe clothing.',
+ 'Do NOT describe the subject\'s fixed identity — hair, eyes, skin, body build, signature',
+ 'outfit, recurring props, or color scheme. Those are bound to the trigger word, and',
+ 'repeating them in every caption weakens it.',
+ omit.length
+ ? `In particular, do NOT mention these signature features that are always present: ${omit.join('; ')}.`
+ : '',
+ 'Reply with ONE comma-separated list of short fragments. Do not mention art style,',
+ 'the subject\'s name, or that this is an illustration.',
+ ].filter(Boolean).join(' ');
+}
+
+// Base prompt with no bible-derived deny-list — the fallback when a dataset has
+// no resolvable subject (uploads), and the shape the tests pin.
+export const CAPTION_PROMPT = buildCaptionPrompt();
// A comma-separated caption fits well under 300, but reasoning models (Qwen3,
// thinking Gemma builds) spend tokens on a hidden <think> block FIRST and only
@@ -223,6 +256,19 @@ export async function startCaptionRun(datasetId, {
providerId, model, settings,
});
+ // Build the captioning instruction once, naming the subject's bible-known
+ // signature features so the vision model omits them (they belong to the
+ // trigger word, not the per-shot caption). Best-effort: an upload-only
+ // dataset or a since-deleted subject just falls back to the general guidance.
+ let signaturePhrases = [];
+ try {
+ const { subject, entryKind } = await loadDatasetSubject(dataset);
+ signaturePhrases = extractSubjectSignaturePhrases(subject, entryKind);
+ } catch (err) {
+ console.log(`🏷️ No bible subject for dataset ${shortId(datasetId)} — captioning with general identity guidance (${err?.message || err})`);
+ }
+ const captionPrompt = buildCaptionPrompt(signaturePhrases);
+
const runId = uuidv4();
captionRuns.set(runId, { clients: [], lastPayload: null });
console.log(`🏷️ Caption run ${shortId(runId)} — dataset=${shortId(datasetId)} images=${targets.length} provider=${resolvedProvider} model=${resolvedModel}`);
@@ -240,7 +286,7 @@ export async function startCaptionRun(datasetId, {
const dataUrl = `data:image/png;base64,${bytes.toString('base64')}`;
const result = await withCaptionVisionLock(() => describeImageDataUrlDetailed({
dataUrl,
- prompt: CAPTION_PROMPT,
+ prompt: captionPrompt,
providerId: resolvedProvider,
model: resolvedModel,
maxTokens: CAPTION_MAX_TOKENS,
diff --git a/server/services/loraDatasetCaption.test.js b/server/services/loraDatasetCaption.test.js
index cf8a8e86e1..88ec710f1b 100644
--- a/server/services/loraDatasetCaption.test.js
+++ b/server/services/loraDatasetCaption.test.js
@@ -4,7 +4,34 @@ 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, withCaptionVisionLock } = await import('./loraDatasetCaption.js');
+const {
+ resolveCaptionModel, buildCaption, withCaptionVisionLock, buildCaptionPrompt, CAPTION_PROMPT,
+} = await import('./loraDatasetCaption.js');
+
+describe('buildCaptionPrompt', () => {
+ it('tells the model to describe only what varies and omit fixed identity', () => {
+ const prompt = buildCaptionPrompt();
+ expect(prompt).toMatch(/ONLY what changes from shot to shot/i);
+ expect(prompt).toMatch(/Do NOT describe the subject's fixed identity/i);
+ // No bible signature → no explicit deny-list clause.
+ expect(prompt).not.toMatch(/signature features that are always present/i);
+ });
+
+ it('CAPTION_PROMPT is the no-signature base prompt', () => {
+ expect(CAPTION_PROMPT).toBe(buildCaptionPrompt());
+ expect(CAPTION_PROMPT).toBe(buildCaptionPrompt([]));
+ });
+
+ it('appends the signature features as an explicit do-not-mention list', () => {
+ const prompt = buildCaptionPrompt(['red cloak', 'woven crown', 'light leather armor']);
+ expect(prompt).toMatch(/do NOT mention these signature features that are always present: red cloak; woven crown; light leather armor\./);
+ });
+
+ it('drops blank/non-string fragments before building the list', () => {
+ const prompt = buildCaptionPrompt(['red cloak', '', ' ', null, 42, 'crown']);
+ expect(prompt).toMatch(/always present: red cloak; crown\./);
+ });
+});
const VISION = [
{ providerId: 'lmstudio', backend: 'lmstudio', id: 'qwen2.5-vl-7b', name: 'Qwen2.5-VL 7B', vision: true },
diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.js
index da903fef00..4b42cd7458 100644
--- a/server/services/loraDatasetGenerate.js
+++ b/server/services/loraDatasetGenerate.js
@@ -78,6 +78,44 @@ const flattenValue = (value) => {
return '';
};
+/**
+ * Pull the subject's INVARIANT signature features — the wardrobe pieces, props,
+ * and palette that are present in (nearly) every reference image and therefore
+ * belong to the trigger token, not the per-shot caption. Returned as discrete
+ * short phrases so the captioner can be told to omit them by name (issue #1320:
+ * captioning "red cloak, woven crown, leather armor" in every shot binds the
+ * look to those phrases instead of the trigger). Pure; tolerant of the bible's
+ * looser object/place shape. Capped + de-duped so the deny-list stays focused.
+ */
+export function extractSubjectSignaturePhrases(subject, entryKind = 'characters') {
+ if (!subject || typeof subject !== 'object') return [];
+ const out = [];
+ const pushNames = (arr) => {
+ if (!Array.isArray(arr)) return;
+ for (const item of arr) {
+ const name = trim(item?.name);
+ if (name) out.push(name);
+ }
+ };
+ if (normalizeEntryKind(entryKind) === 'characters') {
+ pushNames(subject.wardrobes);
+ pushNames(subject.props);
+ pushNames(subject.colorPalette);
+ } else {
+ // Objects/places: the recurring details + palette names are the invariants.
+ pushNames(subject.colorPalette || subject.palette);
+ const recurring = flattenValue(subject.recurringDetails);
+ if (recurring) out.push(...recurring.split(',').map((p) => p.trim()));
+ }
+ const visualIdentity = trim(subject.visualIdentity);
+ if (visualIdentity) out.push(visualIdentity);
+ const seen = new Set();
+ return out
+ .map((s) => s.replace(/\s+/g, ' ').trim())
+ .filter((s) => s && !seen.has(s.toLowerCase()) && seen.add(s.toLowerCase()))
+ .slice(0, 12);
+}
+
/**
* Build the image-gen prompt + negative prompt for ONE dataset image.
* Leads with the universe style, then the character identity block, then
@@ -228,7 +266,9 @@ export async function getDatasetVariationAxes(datasetId) {
// Load the dataset's live canon subject (generation + slicing both need
// the current canon, not the dataset's snapshot). 409 when the subject
// was deleted from the universe after the dataset was created.
-async function loadDatasetSubject(dataset) {
+// Exported so the captioner can derive the subject's signature-feature
+// deny-list without duplicating the universe/entry lookup.
+export async function loadDatasetSubject(dataset) {
const entryKind = normalizeEntryKind(dataset.character.entryKind);
const universe = await getUniverse(dataset.character.universeId);
const entries = Array.isArray(universe[entryKind]) ? universe[entryKind] : [];
diff --git a/server/services/loraDatasetGenerate.test.js b/server/services/loraDatasetGenerate.test.js
index 1eb354def6..b741d0af0f 100644
--- a/server/services/loraDatasetGenerate.test.js
+++ b/server/services/loraDatasetGenerate.test.js
@@ -34,6 +34,7 @@ vi.mock('sharp', () => ({
import {
buildDatasetImagePrompt, deriveVariationAxes, getDatasetVariationAxes,
normalizeCropProposals, proposeCropRegions, sliceReferenceSheet,
+ extractSubjectSignaturePhrases,
} from './loraDatasetGenerate.js';
import { getDataset, updateDataset } from './loraDatasets.js';
import { getUniverse } from './universeBuilder.js';
@@ -45,6 +46,43 @@ import { getUniverse } from './universeBuilder.js';
const UNIVERSE = { artStyle: 'gritty ink-and-wash fantasy' };
+describe('extractSubjectSignaturePhrases', () => {
+ it('collects character wardrobe, prop, and palette names + visual identity', () => {
+ const phrases = extractSubjectSignaturePhrases({
+ wardrobes: [{ name: 'red cloak', description: 'crimson' }, { name: 'light leather armor' }],
+ props: [{ name: 'woven crown' }],
+ colorPalette: [{ name: 'crimson', hex: '#b00' }, { name: 'iron blue' }],
+ visualIdentity: 'tall barbarian warrior',
+ }, 'characters');
+ expect(phrases).toEqual([
+ 'red cloak', 'light leather armor', 'woven crown', 'crimson', 'iron blue', 'tall barbarian warrior',
+ ]);
+ });
+
+ it('de-dupes case-insensitively and caps the list', () => {
+ const wardrobes = Array.from({ length: 20 }, (_, i) => ({ name: `item ${i}` }));
+ const phrases = extractSubjectSignaturePhrases(
+ { wardrobes: [{ name: 'Red Cloak' }, { name: 'red cloak' }, ...wardrobes] },
+ 'characters',
+ );
+ expect(phrases).toHaveLength(12);
+ expect(phrases.filter((p) => p.toLowerCase() === 'red cloak')).toHaveLength(1);
+ });
+
+ it('uses recurring details + palette for objects/places', () => {
+ const phrases = extractSubjectSignaturePhrases({
+ colorPalette: [{ name: 'mossy green' }],
+ recurringDetails: 'cracked obelisk, glowing runes',
+ }, 'places');
+ expect(phrases).toEqual(['mossy green', 'cracked obelisk', 'glowing runes']);
+ });
+
+ it('returns [] for a null/empty subject', () => {
+ expect(extractSubjectSignaturePhrases(null)).toEqual([]);
+ expect(extractSubjectSignaturePhrases({})).toEqual([]);
+ });
+});
+
describe('buildDatasetImagePrompt', () => {
it('renders a single-figure character prompt (default kind)', () => {
const { prompt, negativePrompt } = buildDatasetImagePrompt(
diff --git a/server/services/loraTraining/dataset.js b/server/services/loraTraining/dataset.js
index 7aa203f7f8..22134e887c 100644
--- a/server/services/loraTraining/dataset.js
+++ b/server/services/loraTraining/dataset.js
@@ -6,15 +6,21 @@
import { access } from 'fs/promises';
import { ServerError } from '../../lib/errorHandler.js';
-import { captionHasTriggerWord, computeDatasetReadiness } from '../../lib/loraDataset.js';
+import {
+ analyzeCaptionInvariants, captionHasTriggerWord, computeDatasetReadiness,
+} from '../../lib/loraDataset.js';
import { getDataset, datasetImagePath, datasetImagesDir } from '../loraDatasets.js';
/**
* Load + validate the dataset, returning `{ dataset, manifest }` where
* manifest is the trainer-facing image list:
* `{ triggerWord, imagesDir, images: [{ file, path, caption }] }`.
+ *
+ * `acknowledgeCaptionLeak` skips the identity-leak gate (below) — set by the
+ * resume path (the run already cleared it once) and by an explicit
+ * "train anyway" from the UI.
*/
-export async function validateDatasetReady(datasetId) {
+export async function validateDatasetReady(datasetId, { acknowledgeCaptionLeak = false } = {}) {
const dataset = await getDataset(datasetId);
const readiness = computeDatasetReadiness(dataset);
if (!readiness.trainable) {
@@ -24,6 +30,21 @@ export async function validateDatasetReady(datasetId) {
{ status: 409, code: 'DATASET_NOT_READY' },
);
}
+ // Backstop the caption omit-list: if the same identity fragments still repeat
+ // across most captions, the look is binding to the phrases instead of the
+ // trigger word — the LoRA renders a generic subject. Block (with the offending
+ // fragments) rather than train silently, so the user strips them or opts in.
+ if (!acknowledgeCaptionLeak) {
+ const { total, sharedFragments } = analyzeCaptionInvariants(dataset.images, dataset.triggerWord);
+ if (sharedFragments.length) {
+ const preview = sharedFragments.slice(0, 6).map((f) => f.fragment).join(', ');
+ throw new ServerError(
+ `Identity is leaking into the captions — "${preview}"${sharedFragments.length > 6 ? '…' : ''} repeat across most images, `
+ + 'so the trigger word would learn a generic subject. Strip the shared identity from the captions, or train anyway to override.',
+ { status: 409, code: 'CAPTION_IDENTITY_LEAK', context: { sharedFragments, total } },
+ );
+ }
+ }
// Same token-boundary predicate as the readiness gate — share the helper so
// the manifest can never include a caption the gate counted differently.
const trainImages = dataset.images.filter(
diff --git a/server/services/loraTraining/dataset.test.js b/server/services/loraTraining/dataset.test.js
new file mode 100644
index 0000000000..3076d554cc
--- /dev/null
+++ b/server/services/loraTraining/dataset.test.js
@@ -0,0 +1,67 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// validateDatasetReady is a thin orchestration over the pure readiness/invariant
+// helpers + getDataset + an fs.access existence probe. Mock the data + fs deps so
+// the gate logic (leak detection, acknowledge override, resume skip) is testable
+// without a real dataset store or files on disk.
+vi.mock('../loraDatasets.js', () => ({
+ getDataset: vi.fn(),
+ datasetImagePath: vi.fn((id, file) => `/tmp/${id}/${file}`),
+ datasetImagesDir: vi.fn((id) => `/tmp/${id}`),
+}));
+vi.mock('fs/promises', () => ({ access: vi.fn(async () => {}) }));
+
+const { getDataset } = await import('../loraDatasets.js');
+const { validateDatasetReady } = await import('./dataset.js');
+
+// 10 ready, trigger-prefixed images = trainable. `body(i)` lets a test make the
+// per-shot descriptive tail unique (no leak) or repeat a fragment (leak).
+const dataset = (body) => ({
+ id: 'ds1',
+ triggerWord: 'freydis',
+ character: { entryId: 'c1', universeId: 'u1', entryKind: 'characters' },
+ images: Array.from({ length: 10 }, (_, i) => ({
+ id: `img${i}`, file: `${i}.png`, status: 'ready', caption: `freydis, ${body(i)}`,
+ })),
+});
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('validateDatasetReady caption-identity-leak gate', () => {
+ it('passes (returns manifest) when captions share no identity fragment', async () => {
+ getDataset.mockResolvedValue(dataset((i) => `pose ${i}, angle ${i}`));
+ const { manifest } = await validateDatasetReady('ds1');
+ expect(manifest.triggerWord).toBe('freydis');
+ expect(manifest.images).toHaveLength(10);
+ });
+
+ it('throws 409 CAPTION_IDENTITY_LEAK with the shared fragments when identity repeats', async () => {
+ getDataset.mockResolvedValue(dataset((i) => `red cloak, woven crown, pose ${i}`));
+ await expect(validateDatasetReady('ds1')).rejects.toMatchObject({
+ status: 409,
+ code: 'CAPTION_IDENTITY_LEAK',
+ context: {
+ total: 10,
+ sharedFragments: expect.arrayContaining([
+ expect.objectContaining({ fragment: 'red cloak' }),
+ expect.objectContaining({ fragment: 'woven crown' }),
+ ]),
+ },
+ });
+ });
+
+ it('trains anyway when acknowledgeCaptionLeak overrides the gate', async () => {
+ getDataset.mockResolvedValue(dataset((i) => `red cloak, woven crown, pose ${i}`));
+ const { manifest } = await validateDatasetReady('ds1', { acknowledgeCaptionLeak: true });
+ expect(manifest.images).toHaveLength(10);
+ });
+
+ it('still rejects an untrainable dataset before the leak check', async () => {
+ getDataset.mockResolvedValue({
+ id: 'ds1', triggerWord: 'freydis', character: { entryId: 'c1' }, images: [],
+ });
+ await expect(validateDatasetReady('ds1')).rejects.toMatchObject({
+ status: 409, code: 'DATASET_NOT_READY',
+ });
+ });
+});
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index ca5624527d..ce44a9b1cd 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -148,7 +148,9 @@ const stampDatasetTrainingStatus = (run, jobId) =>
* creates the run record, and enqueues the training job. Returns
* `{ runId, jobId, position }` (202-shaped).
*/
-export async function startTrainingRun({ datasetId, baseModelId, name = null, params = {} }) {
+export async function startTrainingRun({
+ datasetId, baseModelId, name = null, params = {}, acknowledgeCaptionLeak = false,
+}) {
const settings = await getSettings();
const pythonPath = settings?.imageGen?.local?.pythonPath || null;
// Engine pick: prefer mflux's MLX trainer when the user's mflux install
@@ -156,7 +158,7 @@ export async function startTrainingRun({ datasetId, baseModelId, name = null, pa
// torch/diffusers trainer in venv-flux2.
const mlxAvailable = isMfluxTrainAvailable(pythonPath);
const routing = resolveTrainingRuntime(baseModelId, getImageModels(), { mlxAvailable });
- const { dataset } = await validateDatasetReady(datasetId);
+ const { dataset } = await validateDatasetReady(datasetId, { acknowledgeCaptionLeak });
if (routing.runtime === TRAINING_RUNTIMES.FLUX2) {
const healthy = await isFlux2VenvHealthy();
@@ -260,7 +262,9 @@ export async function resumeTrainingRun(runId, { auto = false } = {}) {
// Re-validate dataset readiness + ownership exactly like a fresh launch — the
// dataset may have been edited, deleted, or reassigned since the run failed.
- const { dataset } = await validateDatasetReady(run.datasetId);
+ // Skip the caption-leak gate: this run already cleared it at first launch,
+ // and resume shouldn't re-block on captions the user already accepted.
+ const { dataset } = await validateDatasetReady(run.datasetId, { acknowledgeCaptionLeak: true });
if (!sameCharacter(dataset.character, run.character)) {
throw new ServerError('Dataset was reassigned to a different subject — start a fresh run.', {
status: 409, code: 'DATASET_REASSIGNED',