Delivered remotely for a business based in Amsterdam, Netherlands. Names withheld by agreement.
Project Overview
Commercial design teams quickly outgrow general-purpose image generators once real campaign requirements arrive: product packaging must preserve exact silhouettes, editorial campaigns require recurring visual styles, and creative directors need reproducible control over composition. Running local node-graph GUIs across designer laptops creates hardware bottlenecks, inconsistent model versions, and zero governance over proprietary brand weights.
We built a centralized web and API image generation platform powered by Python, PyTorch, and React. Designers work inside an interactive browser canvas supporting brush-based inpainting, ControlNet spatial guidance, and private LoRA style presets, while an orchestrated GPU cluster handles multi-tenant inference, safety screening, and full parameter lineage.
Creative & Scaling Challenges
Deploying diffusion architectures for concurrent studio workflows introduces distinct systems constraints compared to standard web APIs:
- VRAM thrashing under multi-tenancy: Loading multi-gigabyte diffusion checkpoints per request destroys throughput, yet keeping every customer's custom LoRA permanently mounted exhausts GPU memory.
- Precision masking friction: Uploading masks created in external tools breaks creative momentum; designers need smooth brush strokes, feathering, and zoomable layers directly in React.
- Non-deterministic drift: Ad-hoc parameter tweaks across team members make it nearly impossible to recreate an approved visual when legal or regional markets request minor edits.
- Unpredictable tail latency: Mixing heavy high-step ControlNet upscaling jobs with rapid ideation previews in a single FIFO queue leaves interactive users staring at spinners.
Architectural Strategy
Our architecture separates stateless creative orchestration from VRAM-resident model execution. React serializes every canvas action—prompt weights, ControlNet preprocessors, binary masks, and seed locks—into an explicit workflow graph submitted to FastAPI. Rather than dispatching blindly to arbitrary workers, Redis Streams partition incoming jobs by base model family and SLA tier (interactive canvas previews versus asynchronous batch variations).
On the compute plane, PyTorch workers maintain warm base models in BF16/FP16 precision, pairing TensorRT-accelerated UNet/transformer backbones with an in-memory adapter cache that mounts and unmounts LoRA weights on demand without reloading the underlying foundation model.
Core Capabilities
- Browser Canvas & Inpainting Studio: React workspace featuring pan-and-zoom canvas layers, soft-edge mask brushes, reference overlays, and non-destructive variation history.
- Multi-Adapter Style Mixing: Combine locked corporate LoRA checkpoints with adjustable strength weights and negative-prompt guardrails per workspace.
- Spatial Conditioning Pipelines: Integrated ControlNet edge, depth, and pose preprocessors enabling designers to anchor compositions to product renders or rough sketches.
- Reproducible Seed & Graph Provenance: One-click parameter restoration from any historical output, guaranteeing exact visual lineage across campaign revisions.
- Programmatic Batch API: Authenticated REST endpoints allowing merchandising and localization tools to generate variant imagery across aspect ratios at scale.
Technical Architecture
When a user triggers generation from the React canvas, FastAPI validates tenant entitlements, persists the normalized workflow specification in PostgreSQL, and publishes a signed job descriptor onto model-affinity queues in Redis. GPU workers pull compatible batches, hydrate any missing LoRA safetensors from pinned host memory or local NVMe cache, execute denoising alongside TensorRT-optimized submodules, pass decoded tensors through a lightweight safety head, and emit preview URLs back over WebSockets.
Flow: React Canvas Studio → FastAPI Gateway (PostgreSQL Workflow Graph) → Model-Affinity Redis Streams → PyTorch + TensorRT GPU Workers (LoRA/ControlNet Cache) → Inline Safety Classifier → Object Storage & CDN → WebSocket Gallery Update
Separating preprocessor execution (such as Canny edge extraction or depth estimation) from the main denoising loop allows lightweight CPU or small-GPU pods to cache intermediate conditioning maps, preventing heavy inference nodes from repeating preprocessing work during rapid prompt tweaks.
Technology Stack
| Category | Technology detail |
|---|---|
| Canvas Studio UI | React with HTML5 Canvas masking, layer stacks, and real-time job streams |
| API & Auth Layer | Python and FastAPI managing tenant quotas, presets, and signed URLs |
| Inference Engine | PyTorch diffusion pipelines accelerated with TensorRT and torch.compile |
| Adapter Management | Pinned host-memory LRU cache for rapid LoRA and ControlNet weight swapping |
| Queue & Broker | Redis Streams routing requests by base checkpoint and priority tier |
| Lineage Database | PostgreSQL storing seeds, sampler graphs, LoRA versions, and permissions |
| Safety & Moderation | Lightweight PyTorch vision classifiers gating inputs and generated outputs |
| Asset Storage | Object storage holding LoRA safetensors, reference masks, and lossless PNGs |
Engineering Trade-offs & Solutions
| Engineering Challenge | Solution & Trade-off |
|---|---|
| Swapping customer LoRAs rapidly without reloading base weights | Used dynamic weight patching backed by a pinned-RAM LRU cache and worker-affinity routing; introduces slight routing complexity while keeping VRAM overhead bounded. |
| Balancing TensorRT compilation speed against dynamic aspect ratios | Compiled engines for curated resolution buckets and fell back to torch.compile for arbitrary canvas crops; requires maintaining bucket profiles in exchange for steady throughput. |
| Preventing heavy upscaling jobs from starving live canvas previews | Split Redis Streams into fast preview and background high-res queues with weighted worker consumption; adds queue tuning overhead while keeping interactive drafting snappy. |
| Avoiding huge client payloads when sending high-res masks repeatedly | Uploaded binary mask blobs once via presigned URLs and referenced immutable hashes inside workflow JSON; adds an extra client pre-upload step while keeping API payloads tiny. |
Security & Reliability
Proprietary brand LoRA weights and unreleased product silhouettes require strict multi-tenant boundaries. Customer adapters are encrypted at rest in object storage, decrypted only inside authorized worker enclaves, and scrubbed from host caches according to workspace isolation policies. PostgreSQL row-level scoping ensures users only query galleries, seeds, and custom presets belonging to their organization.
To guard against GPU memory exhaustion or denial-of-service inputs, FastAPI clamps maximum pixel budgets, step counts, and batch sizes before enqueuing jobs. PyTorch inference runs inside deterministic torch.inference_mode() blocks with explicit memory cleanup on unhandled exceptions, preventing fragmented CUDA allocations from degrading subsequent tenant requests.
Performance & Scale
Latency in generative imaging hinges heavily on avoiding unnecessary weight transfers and host-to-device synchronization. Workers map .safetensors files directly into memory and warm TensorRT execution contexts during container readiness probes, ensuring pods never advertise availability to Redis until ready to denoise immediately.
On the client side, React offloads mask rasterization to offscreen canvas buffers and streams progressively encoded WebP thumbnails for instant gallery previews while lossless PNG masters finish uploading asynchronously. Redis tracks active tenant concurrency with sliding-window rate limits, keeping bursty API integrations from saturating shared creative studio capacity.
Operational Outcomes
Consolidating generative imaging onto a disciplined PyTorch, Python, and React platform gave creative teams control without sacrificing iteration speed:
- Consistent brand fidelity: Art directors lock approved LoRA adapters and ControlNet templates so distributed contributors produce cohesive campaign visuals.
- Traceable creative workflows: Every exported asset links cleanly to its exact seed, mask inputs, and model weights in PostgreSQL for effortless follow-up revisions.
- Elastic GPU utilization: Affinity routing and dynamic micro-batching maximize throughput across shared accelerator pools without dedicating idle hardware per tenant.
- Seamless API integration: Automated merchandising pipelines consume the exact same tested inference graphs perfected inside the visual React studio.