All posts

2026-11-30 · 8 min read

Building a Personalized AI Portrait Pipeline — LoRA, ComfyUI, and a Likeness QA Gate

generative-aifluxloracomfyuicomputer-visionmlops

Given 15–30 photos of a person, this pipeline trains a single-subject FLUX.1-dev LoRA via Dreambooth, serves inference through two backends, and — the part most tutorials skip — automatically scores whether each output still looks like the person. It's all open tooling: SimpleTuner, ComfyUI, and a handful of open models on RunPod Serverless.

Infographic of the five-stage pipeline: input photos of the subject, auto-captioning and preprocessing, FLUX.1-dev DreamBooth LoRA training into a .safetensors file, portrait generation with diffusers or ComfyUI, and a likeness QA gate that scores identity similarity before outputs are accepted.
The pipeline end to end: source photos → captioned dataset → subject LoRA → two inference backends → likeness QA gate.

Architecture

Training and inference each run as a RunPod Serverless worker: a Docker image that hands every incoming job to a handler function. RunPod cold-starts a GPU pod per job and tears it down afterwards, so there's no idle GPU to pay for.

Architecture infographic: source photos feed a RunPod training worker running SimpleTuner with FLUX.1-dev DreamBooth LoRA; the resulting subject LoRA is served by Inference A (diffusers FluxPipeline, stacked LoRAs, Real-ESRGAN) or Inference B (ComfyUI workflow API, UltimateSDUpscale, custom nodes); both pass through an InsightFace likeness QA gate before accepted portraits are delivered.
Training, inference, and QA — each stage runs as its own RunPod Serverless worker.

Part 1 — Training a FLUX.1-dev LoRA with SimpleTuner

SimpleTuner has first-class FLUX support and a proper multi-aspect-bucket dataloader, which beats hand-rolling a training loop. The LoRA trains at SimpleTuner's default rank of 16.

Hardware. At rank 16, unquantized bf16 training needs 32 GB+ of VRAM, so it doesn't fit on a 24 GB card without gradient checkpointing, an 8-bit optimizer and int8/fp8-quantized base weights. A 48 GB card such as the A6000 is the comfortable option.

Licensing and consent. FLUX.1 [dev] is gated and non-commercial, so a commercial deployment needs a licence from Black Forest Labs (or the Apache-2.0 FLUX.1 [schnell]). Training photos come from the subject or with their written consent, confirmed before a job is queued.

Captions. Each photo gets a short caption such as "ohwx man wearing navy suit blazer in office background": a rare placeholder word that stands for the subject, a class noun, then a GPT-4o-mini description of only clothing and background. Leaving out face, hair and expression stops the LoRA from tying the subject's identity to one photo's smile or hairstyle.

Training settings. The learning rate is 0.00025 on a polynomial schedule, with the first 10% of steps as warm-up. Training is step-based: 500 steps by default, adjusted per job to the size of the dataset. Each step uses one image at 1024 px, in bf16 precision with a bf16 AdamW optimizer and gradient checkpointing to save memory. xformers stays off because it isn't reliably compatible with FLUX's attention blocks, and 10% of captions are dropped at random to help the LoRA generalise. Validation previews use a guidance of 3.5 with true classifier-free guidance switched off, which also means the negative prompt has no effect.

Two choices that are easy to get wrong:

  • No min-SNR weighting. Min-SNR was designed for noise-prediction models like SD/SDXL. FLUX is a rectified-flow model, so SimpleTuner's logit-normal timestep sampling does that job instead.
  • Turn off InfiniBand and peer-to-peer in NCCL for multi-GPU training. Most rented pods lack InfiniBand or reliable peer-to-peer, and NCCL hangs without those settings.

The worker handler downloads the photos, captions them, runs the training script, and uploads the finished LoRA weights back to storage.

System diagram of the production request flow: the user uploads and validates images into a temporary S3 bucket that deletes uploads after 24 hours; the backend starts a headshot session, copies images into a per-user S3 bucket organised by user, model and session, and starts a session on the RunPod training and inference endpoint, which downloads the dataset, captions it, fine-tunes and saves the LoRA, generates and saves images, and calls back so the backend can save image URLs in MongoDB and show them to the user.
Where the workers sit in the product: uploads are validated into a 24-hour temp bucket, the backend copies them into a per-user S3 layout and starts a session, and the RunPod endpoint captions, trains, generates and reports back via webhook. Click to open full size.

Part 2 — Two inference backends

A: diffusers, with stacked LoRAs

The simplest path is a diffusers FLUX pipeline with two LoRA adapters loaded side by side and blended at inference time, without merging either into the base model. The personal identity adapter runs at full strength. A community "realism" LoRA runs at half strength, enough to nudge output away from base FLUX's slightly waxy look without fighting the identity adapter for control of facial structure.

Output is then upscaled 4× with Real-ESRGAN, blending two versions of the same model through Deep Network Interpolation: 10% of the strong-denoise model and 90% of the weak-denoise one. Light denoising keeps natural skin texture instead of smoothing it away. One dependency landmine: a library Real-ESRGAN relies on imports a part of torchvision that newer releases removed, so the Docker image ships a patched copy of the affected file.

B: ComfyUI as a headless workflow server

For anything beyond a fixed script, headless ComfyUI driven through its API gives node-level control without rewriting Python. The active workflow loads an fp8 version of FLUX, applies the identity LoRA at full strength and the realism LoRA at half strength, and samples for 28 steps. It then decodes the image, applies a highlight-and-shadow tone curve, and finishes with a tiled 2× upscale that adds fine detail.

The handler treats the workflow file as a template and swaps in the LoRA, random seeds, prompt and output filename for each job. To know when a job is done, it waits for ComfyUI's completion message for that specific prompt, then looks up the output file in ComfyUI's history for that prompt. An earlier version waited for an event from one hard-coded node, which broke across ComfyUI versions, and a global "queue is empty" signal describes the whole queue rather than one prompt.

Worker hygiene. The handler waits up to 10 minutes for ComfyUI to come up, since cold starts plus multi-gigabyte model files take time. Because RunPod reuses warm workers, every job starts and ends by wiping the outputs, the dataset and the previous identity LoRA, so one user's data never leaks into the next job.

Part 3 — The likeness QA gate

Neither backend knows whether its output resembles the subject. LoRA training can drift and seeds can land badly, so every image is scored before it's allowed out the door.

Infographic of the likeness QA gate: two to three reference photos of the subject, three generated candidates in different outfits and scenes, a face-embedding similarity score for each candidate against the reference set, and a decision step that regenerates low scores with a new seed and delivers the candidate that clears the threshold.
How weak generations get filtered out. The scores and threshold in this graphic are illustrative; the production gate thresholds on the per-subject calibrated percentage described below.

Each face is turned into a numeric "fingerprint" with InsightFace's recognition model, and two faces are compared by how closely their fingerprints point in the same direction (cosine similarity). InsightFace's pretrained weights are non-commercial, so a commercial deployment uses a licensed model in the same slot.

Raw similarity isn't a percentage anyone can reason about, and its useful range shifts per subject: some people's photos are naturally more alike than others'. So a one-time calibration pass compares every pair of the subject's own training photos. The top of the scale is set to the highest pairwise similarity minus one and a half standard deviations (capped at 0.9), and the bottom is zero. Pulling the top down matters because the single best pair is often an outlier, such as two photos taken seconds apart, and calibrating against it would make every legitimate match look low. The same pass picks the two or three most representative photos as references.

Each new image's similarity is then mapped onto a 10–100% scale. The floor of 10 is deliberate: a low score is more actionable than a flat 0%.

The generation loop uses that score:

  • Quality-driven retries. If an image scores below 50%, it's discarded and regenerated with a new random seed, up to 3 attempts, stopping as soon as one passes.
  • Fail soft. When the attempts run out, the last image ships with its real score instead of the whole job failing.
  • Mind the hand-off to the API. The scores come out as NumPy numbers, which Python's standard JSON encoder can't handle, so they're converted to plain numbers before the result is sent back. The boundary between ML code and API code is where a disproportionate share of real bugs live.

Closing thoughts

None of these pieces is novel on its own. What made it a real system was the boring reliability work: calibrating likeness per subject, detecting completion per prompt, and never letting a reused worker leak one user's data into the next job. The diffusion model will do its job; the reliability layer around it is what actually ships.

A condensed version. The full write-up, with every config and code listing, was originally published on LinkedIn.