Skip to content

Restructure the diffusion Train tab: right-docked settings, grayed pre-run charts, LLM-style stop - #6840

Merged
danielhanchen merged 0 commit into
image-generationfrom
diffusion-train-tab-2
Jul 7, 2026
Merged

danielhanchen merged 0 commit into
image-generationfrom
diffusion-train-tab-2

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Stacked on #6839. Frontend counterpart of the training perf/precision PRs: brings the diffusion Train tab in line with the LLM Train page.

What changed

Right-docked Advanced settings panel (same pattern as the Create tab / Chat settings rail, open by default)

Charts always visible, grayed before a run

  • The progress card and the Training Loss / Learning Rate charts are always mounted; before a run they render grayed with a "No training run yet" overlay, so the layout does not jump when training starts. DiffusionCharts no longer returns null on empty data.
  • The LR chart is now meaningful: it tracks the reported per-step LR from the scheduler wiring in Diffusion training perf core: phased loads, latent cache, real batching, LR schedule #6838 (warmup ramps and cosine decay are visible live).

LLM-style stop

  • The Stop button opens a confirm dialog: Continue training / Stop (discard) / Stop and save, posting {save} to the stop route from Diffusion training perf core: phased loads, latent cache, real batching, LR schedule #6838; the button shows a disabled "Stopping..." state until the run ends, and the pending-stop flag resets when a new run starts.
  • Stop and save now surfaces the partial adapter: a stopped run with a saved LoRA gets the same ready-to-deploy card as a completed run ("Partial adapter saved" + Deploy to Create), and the LoRA picker rescans for it.

api.ts: stopDiffusionTraining(save) with a JSON body, the /info precision fields (precision_modes / recommended_precision / supports_compile), and the new start payload fields.

Verification

  • npm run build clean (tsc no errors); backend suites on this branch: 100 passed.
  • Playwright E2E against a live secure Studio serving this branch (B200, GPU-pinned): 30 checks passed across two real z-image LoRA runs on the tuxemon example dataset:
    • idle: panel open with every knob, Base precision options exactly match /info, grayed charts + overlay, panel toggle, sdxl swaps to mixed precision;
    • run 1 (cosine + warmup): live charts, LR ramp visible (9.6e-5 at step 12), confirm dialog, Stop without save -> "Stopped (no adapter saved).", nothing in the LoRA catalog;
    • run 2: Stop and save at step 28/200 -> "Stopped (partial adapter saved).", partial adapter card, adapter present in the diffusion LoRA catalog, Deploy to Create jumps to the Create tab with the adapter attached.
  • The E2E caught and this PR fixes two real bugs: the stale pending-stop flag permanently disabling the Stop button on the next run, and stop-and-save leaving the saved adapter invisible (no deploy card).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces advanced settings and speed controls for diffusion training, including a right-docked Advanced panel, support for gradient accumulation, learning rate schedulers, gradient checkpointing, base precision modes, and transformer compilation. It also adds a confirmation dialog for stopping training with options to save or discard the partial adapter. The review feedback identifies two important issues in diffusion-train-panel.tsx: a bug where dismissed stopped runs are not cleared from the charts and progress display, and a potential issue with resetting the training completion notification state.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +416 to +420
const hasRun = Boolean(
status &&
status.status !== "idle" &&
!(status.status === "completed" && status.job_id === dismissedJobId),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

When a training run is stopped early but saved (i.e., status.status === "stopped" with a saved adapter), the user is presented with the "Partial adapter saved" card, which contains a "Train another" button. Clicking this button sets dismissedJobId to the current job's ID. However, because hasRun only checks for status.status === "completed" when determining if the run is dismissed, a dismissed "stopped" run will not be cleared from the charts and progress display (it won't get grayed out with the "No training run yet" overlay).

Changing the check to simply verify status.job_id !== dismissedJobId resolves this bug for both completed and stopped runs.

Suggested change
const hasRun = Boolean(
status &&
status.status !== "idle" &&
!(status.status === "completed" && status.job_id === dismissedJobId),
);
const hasRun = Boolean(
status &&
status.status !== "idle" &&
status.job_id !== dismissedJobId,
);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reworked panel handles this: a stopped run with a saved adapter drives the same adapter card as a completed run (Partial adapter saved wording, Deploy to Create, Train another), and the completion callback fires for stop-and-save so the adapter reaches the LoRA picker.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed at the current tip: hasRun now checks the dismissal against all terminal statuses (completed, stopped, error), so dismissing a stopped-and-saved run clears the charts and progress display the same way a completed run does.

Comment on lines 424 to +435
const notifiedComplete = useRef(false);
useEffect(() => {
if (status?.status === "completed" && !notifiedComplete.current) {
const producedAdapter =
status?.status === "completed" ||
(status?.status === "stopped" && Boolean(status?.lora_path));
if (producedAdapter && !notifiedComplete.current) {
notifiedComplete.current = true;
onTrainingComplete?.();
} else if (status?.status === "running" && notifiedComplete.current) {
notifiedComplete.current = false;
}
}, [status?.status, onTrainingComplete]);
}, [status?.status, status?.lora_path, onTrainingComplete]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The else if condition only resets notifiedComplete.current to false when status?.status === "running". If a run fails immediately or goes directly to "error" or "idle" (or if the frontend misses the "running" state due to polling timing), notifiedComplete.current will remain true. This can prevent the next successful run from triggering onTrainingComplete because notifiedComplete.current is still true.

Resetting notifiedComplete.current to false whenever producedAdapter is false is more robust and simpler.

Suggested change
const notifiedComplete = useRef(false);
useEffect(() => {
if (status?.status === "completed" && !notifiedComplete.current) {
const producedAdapter =
status?.status === "completed" ||
(status?.status === "stopped" && Boolean(status?.lora_path));
if (producedAdapter && !notifiedComplete.current) {
notifiedComplete.current = true;
onTrainingComplete?.();
} else if (status?.status === "running" && notifiedComplete.current) {
notifiedComplete.current = false;
}
}, [status?.status, onTrainingComplete]);
}, [status?.status, status?.lora_path, onTrainingComplete]);
const notifiedComplete = useRef(false);
useEffect(() => {
const producedAdapter =
status?.status === "completed" ||
(status?.status === "stopped" && Boolean(status?.lora_path));
if (producedAdapter) {
if (!notifiedComplete.current) {
notifiedComplete.current = true;
onTrainingComplete?.();
}
} else {
notifiedComplete.current = false;
}
}, [status?.status, status?.lora_path, onTrainingComplete]);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 23c6457: the notification flag is also re-armed in onStart, so a second run notifies even when its running phase is never observed by the poll, and the prior run's lingering terminal status cannot re-fire the callback.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handled at the current tip: the flag is re-armed both when a run is observed as running and unconditionally in onStart the moment a new start is requested, so a second run notifies even if polling never catches the intermediate running state. Resetting whenever producedAdapter is false would instead re-fire onTrainingComplete if the poll briefly observed a non-terminal state after a completed run.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 923c1c0d80

ℹ️ 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".

<Label className="text-xs">Precision</Label>
<select
value={precision}
onChange={(e) => setPrecision(e.target.value as "bf16" | "fp16" | "no")}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reset mixed precision when leaving SDXL

When a user first selects SDXL and changes this Precision select to fp16/no, then switches to a DiT family, this shared precision state is hidden but onStart still posts it as mixed_precision. The DiT backend does not ignore that field: Z-Image/Qwen reject fp16 in run_dit_lora_training, and dense base precisions require bf16 compute, so a DiT start can fail even though the visible DiT settings look valid. Reset precision to bf16 on DiT family changes or only send it for SDXL.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 23c6457: the panel resets mixed precision to bf16 whenever the family is a DiT, so an fp16/no value left over from SDXL no longer rides along in the DiT start payload (which the backend would reject for the dense modes).

Comment on lines +722 to +726
{precisionModes.map((m) => (
<option key={m} value={m}>
{precisionLabel(m)}
</option>
))}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Gate dense precision by the selected base

When the default Qwen/Z-Image prequantized *-bnb-4bit base is selected, these dense precision choices (bf16/int8/fp8) are still offered because the list is only gated by machine support. The backend rejects explicit dense base_precision for prequantized repos, so choosing one of the advertised speed modes on the default base makes Start fail until the user manually changes the base model; disable those options for prequant bases or switch to the dense repo automatically.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 23c6457: when the selected base looks prequantized (bnb-4bit and friends, mirroring repo_is_prequantized), the dense precision options are disabled with a hint and an already-selected dense mode auto-flips back to auto, so the run cannot fail at the validator for this reason.

@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up UX round from live testing, in 906f541..0fbdd74:

  • The Create | Train page-mode tabs moved to the left side of the top bar, next to the model selector.
  • The right-docked Advanced panel is gone: training settings are configured once up front, so they now render as the main run-area card while idle. The moment a run starts they hand the area over to live progress + charts, and they come back after Train another. Less clutter, no third column.
  • The completed state is unmistakable now: the run header celebrates with a party emoji instead of a lowercase status word.
  • The Learning Rate chart (a deterministic curve the user just picked) is replaced by a Gradient Norm chart: both trainers now report the total pre-clip grad norm from clip_grad_norm_ per optimizer step, threaded through the service history (sparse-aligned with steps), the status model, and the existing GradNormChartCard.

Verified live with Playwright on a B200 Studio serving this branch: 18/18 layout+flow checks (tabs left, settings-first, swap on start, settings back after Train another) and 7/7 grad-norm checks (grad_norm streams in metric_history, Gradient Norm card replaces Learning Rate, celebration header on completion) across two real z-image runs. Backend suites: 100 passed; tsc/build clean.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bc0d10f759

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

const hasRun = Boolean(
status &&
status.status !== "idle" &&
!(status.status === "completed" && status.job_id === dismissedJobId),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore settings after stopped runs

When a run ends with status stopped (the new “Stop” discard path has no adapter card, and the “Stop and save” card can be dismissed), this condition still keeps hasRun true because it only excludes dismissed completed jobs. Since the training settings now render only under !hasRun, users who stop a run cannot get the settings panel back to adjust steps/rank/precision before starting another run.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reworked panel restores the settings view from every terminal status: completed and stopped-with-adapter show Train another, error and no-save stops show Back to settings, and dismissing a terminal run returns the settings plus the Previous runs list.

loss = ev.get("loss", s["loss"]),
avg_loss = ev.get("avg_loss", s["avg_loss"]),
learning_rate = ev.get("learning_rate", s["learning_rate"]),
grad_norm = ev.get("grad_norm", s["grad_norm"]),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Drop non-finite grad norms before status

When gradient clipping returns inf/NaN during an unstable run, this new field preserves that non-finite value in the status snapshot. The status endpoint serializes this snapshot as JSON, so polling can start failing exactly when gradients blow up even if the loss is still finite; sanitize grad_norm with math.isfinite (or convert it to None) before storing/emitting it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 84e7608: the service nulls non-finite floats (loss, avg_loss, learning_rate, grad_norm) at its single ingestion point, and the metric history skips non-finite loss points while nulling non-finite lr/grad_norm, so status snapshots and persisted run records stay strict-JSON serializable. Covered by a unit test that feeds NaN/Inf progress and round-trips json.dumps with allow_nan=False.

@danielhanchen

Copy link
Copy Markdown
Member Author

Round 3 from screenshot feedback, in 32c5855..4215035:

  • Stop training now lives inside the run card, directly under the stats row (Loss / Avg loss / Speed / Peak VRAM); the left rail keeps a single Start button that reads Training in progress while a run is active.
  • The saved-adapter card (Adapter ready / Partial adapter saved) moved ABOVE the Training Loss / Gradient Norm charts and only appears once a run is stopped or finished.
  • Previous training runs are now persisted like the LLM trainer's history: every terminal run writes a JSON record (summary + start config scrubbed of tokens + the full step/loss/grad-norm logs) under the studio runs directory, served by GET /api/train/diffusion/runs (+ /runs/{job_id}). The idle view lists them with an adapter-saved badge; selecting one re-plots its charts read-only with stats and a Deploy button for saved adapters.
  • The stop dialog's destructive action reads Stop without saving (the bare Stop rendered as a stubby pill between two wide ones and looked misaligned), and the footer rows are centered.
  • Fixed along the way: dismissing a terminal run only worked for completed runs, so Train another after a stop (and any error state) trapped the run view; stopped and error runs are now dismissible, with a Back to settings action when there is no adapter card.

Verified live with Playwright (15 checks across a real z-image run + the persisted-history flow): Stop under the stats, dialog label, adapter card above the charts by bounding box, the run record on disk, the history list with the saved badge, re-plotted charts, and deploy from history. Backend suites: 33 diffusion-training tests including the new persistence + endpoint coverage.

@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 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f1dbb74308

ℹ️ 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".

continue
rec.pop("metric_history", None)
rec.pop("config", None)
out.append(rec)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Drop malformed run records before returning them

This only catches JSON parse failures; a valid JSON file with the wrong shape (for example an older or hand-edited record missing status/job_id, or with a non-numeric avg_loss) is appended here and then DiffusionTrainingRunSummary(**r) in the /diffusion/runs route raises, taking down the whole Previous runs panel. Since these records live on disk and the comment says corrupt records should not break listing, validate the summary fields here (or catch ValidationError in the route) and skip bad records instead of returning them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 51de9da: list_diffusion_runs skips records that are not dicts or lack a string job_id/status, and the runs route additionally catches per-record ValidationError, so one bad file can no longer break the whole panel.

# The generic payload's num_epochs already matches the diffusion field name, but list it
# so the epochs override is threaded through the shared-payload path as explicitly as
# max_steps -> train_steps is.
"num_epochs": "num_epochs",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve epoch-mode shared payloads

Adding the generic num_epochs alias still leaves shared epoch-mode payloads broken when they include max_steps: 0 (the generic UI's sentinel for “use epochs”): the existing max_steps -> train_steps alias copies that 0, and DiffusionLoraConfig.normalized() rejects train_steps < 1 before resolve_train_steps() can use num_epochs. Any caller using the shared payload path in epochs mode will still get a validation error; ignore the max_steps sentinel when num_epochs > 0 or defer the train-step validation until after epoch resolution.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 51de9da: _config_from_dict drops a falsy train_steps when num_epochs > 0, so the max_steps: 0 epoch-mode sentinel no longer trips normalized() before resolve_train_steps applies the epochs. An explicit non-zero max_steps in epochs mode is still honored.

{numberField("Resolution", resolution, setResolution, 512, { min: 64, step: 64 })}
{numberField("Batch", batchSize, setBatchSize, 1)}
{numberField("Grad accumulation", gradAccum, setGradAccum, 1)}
{numberField("Seed", seed, setSeed, 42, { min: 0 })}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 Badge Allow zero as a valid seed

This adds a seed field with min: 0, but it reuses numberField, whose change handler falls back on falsy values (Number(e.target.value) || fallback). When a user enters seed 0, the state is immediately reset to 42, so runs cannot be reproduced with seed 0 even though the UI and backend both allow it. Use a null/empty check instead of truthiness for numeric fields that permit zero.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 51de9da: numberField only falls back when the input parses to NaN, so an explicit 0 is kept for the zero-legal fields (Seed, LR warmup steps).

if (!active) return;
if (status?.status === "running") return;
let cancelled = false;
listDiffusionTrainingRuns()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Refresh history after the run record is durable

When a run finishes, the service exposes the terminal status before the pump has necessarily finished writing the new JSON record, but this effect does a one-shot history fetch as soon as status.status changes away from running. If that request wins the race, prevRuns misses the just-finished run and it will still be absent after the user clicks “Train another” because the dependency remains completed/stopped; retry/delay this terminal refresh or trigger it from a persisted-record signal so the newest run reliably appears.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 51de9da: after a terminal status the previous-runs list refetches once more about 1.5 s later (timeout cleared on unmount), so the just-finished run appears even when the record write races the first fetch.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces epoch-based training and run history persistence for diffusion training, including backend resolution of training steps, tracking of pre-clip gradient norms, and new API endpoints and frontend UI components to list, view, and chart previous runs. The reviewer's feedback highlights several key improvements: coercing num_epochs to an integer during validation to prevent downstream type errors, explicitly specifying UTF-8 encoding when reading and writing run records for cross-platform compatibility, and correcting the usage of AlertDialogAction in the frontend stop dialog to avoid console warnings and styling issues.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +350 to +351
if not 0 <= int(self.num_epochs) <= 1000:
raise ValueError("num_epochs must be between 0 and 1000 (0 uses train_steps)")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Coerce self.num_epochs to an integer permanently in normalized(). Currently, int(self.num_epochs) is only used for the validation check, leaving self.num_epochs as a string or float if it was initialized that way. This can cause a TypeError downstream when comparing cfg.num_epochs > 0 in resolve_train_steps.

Suggested change
if not 0 <= int(self.num_epochs) <= 1000:
raise ValueError("num_epochs must be between 0 and 1000 (0 uses train_steps)")
self.num_epochs = int(self.num_epochs)
if not 0 <= self.num_epochs <= 1000:
raise ValueError("num_epochs must be between 0 and 1000 (0 uses train_steps)")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2c5955b: normalized() now coerces num_epochs to int in the replace(...) alongside the other field normalisations, so downstream consumers always see an int.

out: list[dict] = []
for p in files[: max(0, int(limit))]:
try:
rec = json.loads(p.read_text())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Always specify encoding="utf-8" when reading text files (such as JSON run records) to ensure cross-platform compatibility, especially on Windows where the default system encoding may not be UTF-8.

Suggested change
rec = json.loads(p.read_text())
rec = json.loads(p.read_text(encoding = "utf-8"))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2c5955b: this read_text now passes encoding = "utf-8".

return None
p = _runs_dir() / f"{job_id}.json"
try:
return json.loads(p.read_text())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Always specify encoding="utf-8" when reading text files to prevent decoding errors on platforms like Windows when non-ASCII characters are present in the run record.

Suggested change
return json.loads(p.read_text())
return json.loads(p.read_text(encoding = "utf-8"))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2c5955b: this read_text now passes encoding = "utf-8".

},
}
path = _runs_dir() / f"{s['job_id']}.json"
path.write_text(json.dumps(record))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Always specify encoding="utf-8" when writing text files to ensure that non-ASCII characters (e.g., in the instance prompt or messages) are correctly encoded as UTF-8 across all platforms.

Suggested change
path.write_text(json.dumps(record))
path.write_text(json.dumps(record), encoding = "utf-8")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2c5955b: this write_text now passes encoding = "utf-8".

Comment on lines +1424 to +1426
<AlertDialogAction variant="destructive" onClick={() => void onStop(false)}>
Stop without saving
</AlertDialogAction>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In standard shadcn/ui, AlertDialogAction does not support the variant prop directly and will trigger a React console warning while failing to render the destructive styling. Use asChild and wrap a standard Button with variant="destructive" to ensure correct styling and avoid warnings.

            <AlertDialogAction asChild>
              <Button variant="destructive" onClick={() => void onStop(false)}>
                Stop without saving
              </Button>
            </AlertDialogAction>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This repo's AlertDialogAction is not the stock shadcn one: it accepts Pick<React.ComponentProps<typeof Button>, "variant" | "size"> and renders <Button variant={variant} size={size} asChild>, so the destructive variant renders correctly with no console warning. Leaving as is.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1978b2a844

ℹ️ 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".

Comment on lines +429 to +430
steps_per_epoch = max(1, math.ceil(n_images / per_step))
return min(100000, cfg.num_epochs * steps_per_epoch)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make epoch mode iterate over the dataset

When a user selects num_epochs, this only converts epochs into a number of random optimizer steps; the actual SDXL loop still samples each batch independently via _next_batch in diffusion_lora_trainer.py, and the DiT loop uses rng.randrange, so images are sampled with replacement rather than making a full pass. For example, num_epochs=1, batch=1, and 100 images runs 100 random draws, which leaves roughly a third of the dataset unseen while repeating others, so epoch-based runs do not match the advertised full-pass semantics and can skew training results.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in da3a794: both trainers now draw batches from a reshuffled permutation sampler (PermutationBatchSampler in diffusion_train_common), so every image is visited once per cycle before any repeats. Determinism via the run rng and step/batch shapes are unchanged.

Comment on lines +1342 to +1343
try:
return DiffusionTrainingRunDetail(**rec)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle non-object run detail records

If a persisted run file is valid JSON but not an object (for example a truncated/manual [] file named with a valid job id), get_diffusion_run() returns that value and this **rec raises a TypeError, bypassing the intended 404 handling and returning a 500 from the detail endpoint. The list path already skips non-dict records, so the detail route should apply the same shape check before unpacking.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in da3a794: the run detail route now guards for non-object records and returns 404 instead of raising TypeError on valid-JSON non-dict files.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 303d38cf98

ℹ️ 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".

Comment on lines +134 to 139
<GradNormChartCard
data={gradData}
domain={gradDomain}
visibleStepDomain={stepDomain}
xAxisTicks={xAxisTicks}
scale="linear"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep the LR chart wired to scheduler history

When users pick constant_with_warmup, cosine, or linear, the backend still returns metric_history.lr and the settings copy says the LR is shown live, but this component now renders only loss plus grad norm and no longer consumes the LR series at all. In those non-constant schedules the warmup/decay curve disappears, so users cannot verify the scheduler behavior during a run.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a1114bf. The two-card layout (Training Loss + Grad Norm) is deliberate: DiffusionCharts drops the LR card because the LR curve is the deterministic schedule the user just picked (see the component comment). The genuine issue was the stale copy still promising a live LR chart, so I reworded the settings copy and the two comments to match. Kept the intentional 2-card design rather than re-adding a chart the author removed on purpose.

Comment on lines +1237 to +1239
) : !hasRun ? (
<>
<div className="bg-card corner-squircle flex flex-col gap-4 rounded-3xl p-5 ring-1 ring-foreground/10">

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 Badge Render the idle chart placeholders before a run

In the idle !hasRun branch the right pane renders only the settings/history cards; DiffusionCharts is mounted only in the history/live branches. A first visit therefore has no grayed-out charts or “No training run yet” overlay, and the chart area appears only after starting a run, reintroducing the layout jump this change was meant to prevent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idle !hasRun branch is not empty: it renders the full Training settings card in the same area, with a note that live progress and the Loss/Grad-Norm charts take over that space once training starts. This settings-to-charts swap is the intended design (the settings pane is useful while idle, unlike grayed-out empty charts), so the area is populated on first visit and there is no empty-to-content jump.

Comment on lines +428 to +429
per_step = max(1, cfg.train_batch_size * cfg.gradient_accumulation_steps)
steps_per_epoch = max(1, math.ceil(n_images / per_step))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid under-counting epochs for oversized batches

When train_batch_size * gradient_accumulation_steps is at least the dataset size, this resolves one epoch to a single optimizer step, but the new permutation sampler still fills each microbatch by wrapping into additional cycles. For example, with 10 images and batch 64, num_epochs=1 becomes one step while DiT consumes 64 samples in that step, so small subject datasets can be trained for many more passes than the requested epoch count.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 1-step floor is correct: you cannot run fewer than one optimizer step, and steps_per_epoch = ceil(N / effective_batch) is the standard epoch->step conversion. When effective_batch >= N the PermutationBatchSampler's within-batch wrapping is the deliberate, documented coverage design (its docstring separates the num_epochs step budget from the per-batch index draw). An effective batch larger than the dataset inherently samples each item multiple times per step; capping it silently would change the gradient statistics the user selected. The default (batch 1) is unaffected.

cancelled = true;
if (delayed !== undefined) clearTimeout(delayed);
};
}, [active, status?.status]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 Badge Refresh run history when the job id changes

This effect only depends on status.status, so if a short second run goes from the previous terminal status back to the same terminal status between 1.5s polls (for example completed → completed without observing running), the effect never refetches and the new JSON record is missing from Previous runs until some unrelated status/activation change. Include the job id or another per-run field in the dependency so each terminal run refreshes the history.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This requires a second training run to start AND reach a terminal status within a single 1.5s poll window without the poller ever sampling 'running'. Diffusion runs take minutes (model load alone is seconds), so status.status always transitions through 'running' (or to a different terminal like 'error'), which the effect observes and refetches on. The completed->completed-in-under-1.5s path is not reachable for real training, and the delayed 1.5s refetch already covers the just-finished run.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: a1114bfdc3

ℹ️ 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
danielhanchen changed the base branch from diffusion-train-precision to image-generation July 7, 2026 00:54
@danielhanchen
danielhanchen merged commit b52e7a5 into image-generation Jul 7, 2026
41 of 44 checks passed
@danielhanchen
danielhanchen deleted the diffusion-train-tab-2 branch July 7, 2026 01:33
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