Build a text-to-image generation platform from scratch
Machine LearningModel answerLast updated
Design the complete ML pipeline for producing images from text prompts: data, architecture, training, safety, evaluation, and serving at scale.
You're building a text-to-image generation platform that will serve millions of requests per day. Design the complete end-to-end system.
Your design should cover:
Core ML pipeline
- Data sourcing, curation, and preparation (including captioning strategy)
- Model architecture selection and conditioning mechanisms
- Training approach, objectives, and compute requirements
- Quality and safety evaluation frameworks
Production system
- Inference optimization techniques to meet latency and cost targets
- Safety controls at multiple layers
- Monitoring and quality assurance
- Cost management strategies
Extension task After covering the image generation system, extend your design to support multimodal generation—a system that can accept both text and images as input and produce both text and images as output. Address:
- How the data requirements change
- Architectural modifications for cross-modal understanding
- Training strategies for aligned multimodal behavior
- Product and safety considerations specific to multimodal scenarios
Be concrete about numbers, trade-offs, and failure modes. Assume you need to serve ~50 million images per day with p95 latency under 5 seconds and a target cost below $0.002 per image.
Hints
Hint 1
Start by defining scale targets clearly—peak queries per second drives your infrastructure decisions and makes distillation non-optional
Hint 2
Safety must be layered across prompt input, training data, and generated output; no single classifier catches everything
Hint 3
Precomputing and caching embeddings (text encoder outputs, VAE latents) often doubles throughput for nearly free
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Text-to-Image Generation Platform
1. Requirements and Scale Analysis
Functional scope
- Primary: text prompt → 1–4 images at 1024×1024
- Support aspect ratios, style controls, negative prompts, reproducible seeds
- All outputs watermarked and safety-filtered
Scale assumptions
- 50M images/day ≈ 580 req/s average, ~1,750 req/s at 3× peak load
- p95 latency target: 5 seconds
- Cost target: $0.002/image
- 99.9% availability
Compute reality check A standard 30-step diffusion sampler on an 8B-parameter transformer takes roughly 4 GPU-seconds per image on H100 hardware. At peak load, that would require ~7,000 GPUs—prohibitively expensive. A distilled 4-step model running in 0.5s needs only ~900 GPUs. This makes distillation the most critical cost lever in the entire system.
2. Data Pipeline
Sourcing strategy
- Licensed stock image libraries with clear terms
- Public web data respecting robots.txt and honoring opt-out requests
- User-contributed content where consent and licensing permit
- Synthetic data generation for underrepresented concepts
- Maintain per-asset provenance to support takedown requests
Curation steps
- Deduplication: Exact hash matching, then perceptual hashing (pHash), then embedding-based near-duplicate clustering using CLIP or SSCD (cosine similarity >0.95). This reduces memorization risk.
- Safety filtering: Block CSAM via hash databases at ingestion; apply NSFW/violence classifiers; remove watermarked and low-quality images.
- Quality gating: Filter by resolution, aesthetic scoring models, face detection policies.
- Captioning: Original alt-text is noisy. Re-caption all images using a vision-language model to produce both short (≤75 tokens) and dense descriptions. Train on ~95% synthetic captions and 5% original to maintain prompt-following while handling terse user input.
- Balancing: Cluster image embeddings and resample to prevent head concepts from dominating. Audit demographic distributions within concept categories (e.g., "doctor," "engineer") to identify and mitigate representational bias.
3. Model Architecture
Architecture choice: Latent diffusion with flow matching
- Latent diffusion offers the best quality per FLOP, supports parallel decoding, and has mature distillation techniques
- Autoregressive token-based models (e.g., VQGAN + transformer) unify naturally with language models but suffer from sequential bottlenecks and tokenizer quality loss
- Selected approach: Rectified-flow transformer (MM-DiT style)
Components
- VAE: 8× spatial compression, 16-channel latent space
- Patch embedding: 2×2 patches reduce 1024² images to 4,096 tokens
- Text conditioning: Dual encoders (T5-XXL for rich semantics + CLIP for pooled embeddings), fused via joint attention over text and image tokens
- Timestep & resolution conditioning: Adaptive layer normalization (adaLN) for timestep and pooled text; 2D RoPE for aspect-ratio awareness
- Multi-resolution training: Progressive training at 256² → 512² → 1024² with aspect-ratio bucketing and noise schedule adjustments at higher resolutions
4. Training
Objective
- Rectified-flow velocity matching: minimize
||v_θ(z_t, t, c) − (noise − z_0)||² - Logit-normal timestep sampling (concentrates samples near mid-diffusion)
- Classifier-free guidance (CFG): drop text conditioning 10% of the time during training
Compute estimate
- 8B parameters, ~2T tokens (latent patches, mostly at lower resolutions)
- Approximation: 6·N·D ≈ 1×10²³ FLOPs
- At 40% model FLOP utilization on H100s: ~70k GPU-hours, or 3 days on 1,024 GPUs
- Budget 3–5× for ablations, restarts, hyperparameter tuning
Post-training refinement
- Supervised fine-tuning (SFT) on ~10k curated high-aesthetic images
- Preference optimization (Diffusion-DPO) using human pairwise comparisons
Infrastructure
- FSDP with bf16 mixed precision and activation checkpointing
- Precompute VAE latents and text embeddings offline—this often yields 2× throughput improvement
- Streaming dataloader with sharded datasets; checkpoint every 30 minutes
5. Safety (Layered Defense)
No single classifier is sufficient. Apply controls at multiple stages:
- Input (prompt) layer: Policy classifier or LLM rewriter; blocklist for named individuals (especially minors); jailbreak detection heuristics
- Training data layer: Filtering described above plus concept erasure or targeted unlearning for disallowed content
- Output layer: NSFW, violence, and likeness classifiers; CSAM hash matching on generated images
- Provenance: Invisible watermarking (e.g., Stable Signature) embedded in the generation process; C2PA metadata attached to outputs
- Operational: Red-team testing before launches; per-user rate limits; abuse reporting and human review queues
6. Evaluation
Image quality
- FID or FD-DINOv2 on COCO-30k (note: FID saturates at the high end)
- Human side-by-side Elo ratings (launch gate metric)
Prompt alignment
- CLIPScore, GenEval (tests object counts, spatial relationships, attributes), VQA-based metrics (TIFA, DSG)
Diversity & memorization
- Intra-prompt LPIPS diversity; nearest-neighbor search against training set using SSCD to measure memorization rate
Bias
- Demographic distribution on neutral occupational prompts (use attribute classifiers + human audit)
- Quality parity across skin tones in portrait generation
Safety
- Red-team attack success rate; false-refusal rate on benign prompts
7. Inference Optimization
Distillation (highest impact)
- Consistency distillation or adversarial methods (LCM, ADD) to reduce from 30 steps to 1–4 steps
- Distill CFG into the model itself (eliminates the second forward pass, saving 2×)
Quantization
- FP8 for DiT weights and activations; INT8 for text encoder
- Keep quality degradation within 1 Elo point
Caching & batching
- Cache text encoder outputs (prompts repeat frequently)
- Cache popular prompt+seed pairs at the image level
- Dynamic batching by resolution bucket to maximize GPU utilization
- Serve text encoder separately from the image generator
Cost controls
- Tiered service: fast 512² preview, optional paid upscale to 1024²
- Route simple prompts to a smaller/faster model variant
- Per-user quotas; use spot/preemptible instances for batch jobs
8. Multimodal Extension (Text + Image In/Out)
Data requirements
- Image-text pairs with spatial grounding annotations
- Interleaved document datasets (e.g., web pages, PDFs with inline images)
- Instruction-following datasets: "edit this image to…", "describe what's happening…"
- Aligned datasets where text references specific image regions
Architecture modifications
- Unified tokenization: image patches and text tokens in a shared sequence
- Cross-attention or interleaved attention blocks for joint reasoning
- Separate generation heads for text (autoregressive LM head) and image (denoising diffusion head), or unified next-token prediction over a hybrid vocabulary
Training strategy
- Pretraining: Joint vision-language modeling on interleaved data
- Instruction tuning: Supervised fine-tuning on task-specific datasets (captioning, VQA, editing)
- Alignment: RLHF or RLAIF using multimodal reward models
Product considerations
- Retrieval augmentation: fetch relevant images from a knowledge base when user requests current information
- Latency: text generation can stream token-by-token; image generation is batched and slower—surface this in UX
- Safety: multimodal inputs enable new attack vectors (adversarial images that jailbreak text behavior); apply separate input classifiers for each modality
9. Monitoring
System health
- Latency (p50, p95, p99), GPU utilization, queue depth, error rates, cache hit rates
Quality
- Daily automated eval on a frozen prompt set (track FID, CLIPScore, GenEval over time)
- Sample and manually review 0.1% of outputs
Safety
- Trigger rates for each safety filter by category
- False-positive and false-negative rates from human review
- Drift detection on demographic distributions
Cost
- Cost per image by tier; GPU time vs. preemptible savings; cache effectiveness
Common Pitfalls
- Skipping distillation and trying to serve a 30-step model at scale
- Single-point safety (relying only on output filtering)
- Training on raw alt-text without re-captioning
- Ignoring memorization (not deduplicating or measuring nearest-neighbor recall)
- Not precomputing embeddings (wasting 50% of throughput)
- Underestimating the cost of multi-resolution and aspect-ratio support
Complexity: O(batch_size · sequence_length² · num_layers) per training step; O(num_steps · sequence_length²) at inference (before distillation).