Welcome to our course on modern unified image generation architectures. This session examines how state-of-the-art models like FLUX, ERNIE-Image, and HiDream are reshaping image synthesis, exploring different combinations of latent or pixel representations and separate or integrated encoders.
Consider the motivation for unifying these architectures. Classical pipelines chain a variational autoencoder, a frozen text encoder, and a U-Net denoiser, each with mismatched inductive biases. Unification consolidates these into one transformer backbone, tightening cross-modal alignment and improving parameter efficiency.
This snippet imports PyTorch and the Hugging Face transformers stack, then instantiates a unified backbone. Note the shift: rather than orchestrating separate VAE, CLIP, and U-Net modules, we load a single pretrained transformer and run a forward pass on image latents.
Recall the legacy pipeline: a VAE compresses images into a latent grid, a text encoder produces conditioning embeddings, and a U-Net with cross-attention iteratively denoises. This is the Stable Diffusion recipe, and it is the substrate on which unified transformer models build.
From these separate components we move to unified architectures, focusing on FLUX, ERNIE-Image, and HiDream-O1. We will dissect their rectified-flow objectives, joint attention over text and image tokens, and the design tradeoffs each makes.
By the end of this course, you will understand the rationale behind these designs, their implementation nuances, from positional encoding to classifier-free guidance, and their relevance to current research and industrial deployment.
Equations, code and original cards
Course Introduction & Overview
• Motivation: unify generation into one Transformer backbone for efficiency and scalability
• Scope: FLUX, ERNIE-Image, and HiDream-O1 architectures
• Expected Outcomes: mechanistic understanding and practical implementation skill
import torch
from transformers import AutoModel
flux_model = AutoModel.from_pretrained('flux') # Unified Transformer backbone
# Forward pass over VAE latents with text conditioning
inputs = torch.randn(1, 3, 256, 256) # Dummy input image tensor
outputs = flux_model(inputs)
Moment 02 / 12
Legacy Pipeline Recap: VAE and Text Encoder
Let's revisit the legacy latent diffusion pipeline: a CLIP text encoder, a U-Net denoiser, and a VAE mapping between pixel and latent space. This is the Stable Diffusion stack, and it defined the first wave of practical text-to-image generation.
The CLIP text encoder maps the prompt into a joint image-text embedding space trained contrastively. That embedding conditions the U-Net through cross-attention, injecting semantic information at every resolution of the denoising network.
The U-Net operates entirely in latent space, predicting the noise component at each timestep so the sampler can iteratively invert the forward diffusion process. Skip connections preserve fine structure while the bottleneck captures global composition.
Finally, the VAE decoder upsamples the denoised latent back to pixel space. Because the autoencoder compresses by a factor of eight per spatial dimension, the diffusion model never touches raw pixels, which is where the computational savings come from.
The weakness is the modularity itself. Each component is trained with its own objective, so errors compound across the pipeline: a misaligned text embedding or a lossy latent bottleneck cannot be corrected downstream, and joint fine-tuning is awkward.
Here is the VAE objective, the evidence lower bound: reconstruction loss minus the KL divergence between the approximate posterior and the prior. The KL term regularizes the latent space so the diffusion model can sample it reliably.
This is the latent diffusion objective: the expected squared error between the true noise and the U-Net's prediction, averaged over timesteps sampled uniformly. The schedule of alphas controls how much signal survives at each step.
To summarize: CLIP encodes, the U-Net denoises in latent space, the VAE decodes. The mathematics is sound, but the disjoint training and the bottleneck of a frozen text encoder motivated the integrated architectures we turn to next.
Equations, code and original cards
Legacy Pipeline Recap: VAE and Text Encoder
Component Roles
• CLIP Text Encoder: Contrastive prompt embedding, conditions via cross-attention
Mathematical Foundations: Diffusion and VAE Models
We now formalize two generative paradigms: variational autoencoders as amortized latent-variable inference, and diffusion models as learned reversal of a fixed noising process.
For the autoencoder of Kingma and Welling, maximize the evidence lower bound: an expected reconstruction log likelihood under the encoder posterior, minus the KL divergence to the prior.
With a standard normal prior and diagonal Gaussian posterior, that KL term is closed form, while the reparameterization trick makes stochastic sampling differentiable for backpropagation.
Denoising diffusion probabilistic models, after Ho and collaborators, learn the reverse Markov chain by predicting injected Gaussian noise at each timestep under a variance schedule.
The simplified objective is the expectation over clean data, noise, and time of the squared error between sampled noise and the network prediction for the noisy sample at that time.
Latent embeddings form a matrix whose rows index batch instances and whose columns index features, so one linear map acts on the whole batch simultaneously.
The PyTorch line realizes an affine layer: matrix multiplication applies the weight to every row, and broadcasting adds the same bias vector to each transformed embedding.
The takeaway is that probabilistic objectives define what to optimize, while tensor algebra and automatic differentiation make those objectives trainable at scale.
Equations, code and original cards
Mathematical Foundations: VAEs and Denoising Diffusion
• VAE: amortized latent-variable model (Kingma & Welling, 2014)
We now examine the conceptual shift toward unified architectures in transformer models. This slide isolates that single design decision.
Classical pipelines route images and text through disjoint encoders. Here we collapse both modalities into one residual stream, eliminating cross-module interfaces entirely.
The code concatenates text and image tokens along the sequence dimension. Note the absence of any external VAE latent space or standalone text encoder.
Removing those components cuts optimization complexity and improves robustness, since both modalities now share one representation space and one gradient path.
That unification exposes a single objective, enabling scalable training and cleaner optimization.
In short, replacing modular pipelines with one transformer streamlines the architecture, improves scaling behavior, and enables the optimizations we develop in subsequent lectures.
Equations, code and original cards
Unified Architectures: Conceptual Shift
• Collapse disjoint modality encoders into one Transformer
• Concatenate text and image tokens into a shared sequence
• Remove the external VAE and standalone text encoder
• One representation space, one gradient path, lower complexity
• Single objective enables cleaner large-scale optimization
FLUX, released by Black Forest Labs in 2024, is a twelve-billion-parameter rectified flow transformer in the diffusion transformer lineage of Peebles and Xie, with double-stream blocks handling text and image tokens separately.
Each modality carries its own projections, layer norms, and feed-forward weights, so text tokens encoded by T5 and CLIP and image patch latents from the VAE are processed with modality-appropriate parameters before any interaction.
The streams meet inside joint attention: queries, keys, and values from both modalities are concatenated, so every token attends across the full multimodal sequence, conditioned by rotary positional embeddings following Su and colleagues.
The schnell variant applies adversarial step distillation, compressing a fifty-step teacher sampler into as few as one to four student steps while retaining near-teacher sample fidelity.
Here is the attention operation itself: softmax of Q K transpose over the square root of d-k, times V, where queries, keys, and values are projections drawn from both token streams jointly.
This is the rectified flow update: the latent moves along the learned velocity field with a simple Euler step, transporting a Gaussian prior toward the data distribution along near-straight paths.
This PyTorch snippet shows the mechanics: project both modalities to queries, keys, and values, scale by one over the square root of the head dimension, then apply softmax and aggregate the values.
To summarize: FLUX combines modality-specific double-stream weights, joint attention with rotary embeddings, rectified flow training following Lipman and colleagues, and step distillation for fast sampling. These choices define the current frontier of open multimodal generation.
Clarification: Text and image output lengths can differ; do not add these tensors directly.
Consider the ERNIE-Image architecture: a diffusion-based image synthesis system that couples a large diffusion transformer backbone with reasoning-driven prompt rewriting and a text-rendering pipeline aimed at dense technical labels.
The backbone is a single-stream diffusion transformer with eight billion parameters, in the lineage of Peebles and Xie's DiT: text tokens and latent image patches share one attention stack, giving tight cross-modal conditioning.
Upstream, a reasoning-driven prompt agent rewrites the raw user prompt into a structured specification, resolving layout, entity attributes, and textual content before conditioning, which measurably improves compositional coherence.
The turbo variant applies multistep diffusion distillation, in the spirit of Salimans and Ho's progressive distillation, plus reinforcement learning on preference rewards, cutting sampling steps while stabilizing training and preserving perceptual quality.
Evaluation on LongText-Bench, which stresses long-form and technical label rendering, shows stronger text-image alignment than prior baselines, particularly on glyph accuracy and semantic fidelity for dense captions.
Training couples the standard denoising objective, the expected squared error between predicted and target noise, with auxiliary alignment losses and optimization choices that enforce consistency between conditioning text and generated pixels.
In sum, ERNIE-Image shows that scaling a unified diffusion transformer, reasoning over prompts, and distilling the sampler are complementary levers for reliable synthesis from complex, text-heavy technical prompts.
Welcome. Today we examine HiDream-O1, a pixel-level unified transformer that maps raw pixels, text, and conditioning signals into one shared token space, dispensing with the variational autoencoder latent and the frozen text encoder that diffusion pipelines typically require.
The core innovation is this unified token space: pixels, text, and conditions are embedded jointly, so a single transformer processes all modalities end to end, rather than stitching together separately trained encoders.
We now turn to the mathematical formulation underlying the architecture, where token embeddings and stacked transformer layers encode the multimodal inputs precisely.
Here we define the pixel token embeddings, e sub t superscript p, which project raw pixels into the unified token space. This preserves pixel-level granularity inside the embedding rather than compressing through a latent bottleneck.
Next, the transformer layer recursion, h superscript l, describes the computation within each layer: self-attention and feed-forward updates that fuse pixel and text modalities through the shared residual stream.
For implementation, the PyTorch style transformer layer shows how these embeddings and layers become executable code, which matters for understanding parameter allocation and real-world model construction.
To summarize, HiDream-O1 advances pixel-level multimodal modeling with an eight billion parameter transformer, supporting text-to-image generation and instruction-based editing, all orchestrated through unified token embeddings and standard transformer layers.
Equations, code and original cards
HiDream-O1: Pixel-level Unified Transformer
• Unified token space: pixels, text, and conditions embedded jointly
• 8B-parameter transformer, no VAE latent or separate text encoder
Begin with FLUX's double-stream multimodal diffusion transformer: text and image tokens keep separate projections and feed-forwards, yet attention runs jointly over the concatenated sequence. Watch the residual streams mix.
Contrast this with ERNIE-Image's unified single stream: one shared set of weights processes the concatenated text-and-image sequence, so every self-attention head mixes modalities directly.
Now vary the depth and the head count. Depth composes mixing across blocks; head count partitions the attention into independent subspaces, each with its own query-key geometry.
Track the cross-modal token flow. Joint attention scales quadratically in sequence length, so merging both modalities raises attention FLOPs at every denoising step.
Finally, weigh the trade-off: double-stream blocks preserve modality-specific features at higher parameter cost; the unified stream is cheaper but forces shared weights to serve both distributions.
Equations, code and original cards
Moment 09 / 12
2024-2026 Research Trends & Scaling Laws
Today's session surveys the research frontier from 2024 through 2026, where scaling laws, inference-time compute, and alignment methods are converging.
First, the scaling laws: Kaplan and Chinchilla showed that loss falls as a power law in parameters, data, and compute. Chinchilla's rule, roughly twenty tokens per parameter, dictates how to allocate a fixed training budget.
Next, efficiency: FlashAttention, grouped-query attention, and speculative decoding slash inference cost, while consistency models and flow matching compress diffusion sampling from hundreds of steps to a handful.
Alignment has moved beyond RLHF toward direct preference optimization and reinforcement learning with verifiable rewards — the recipe behind the reasoning models now dominating benchmarks.
A defining trend couples reinforcement learning with distillation: frontier reasoning models produce long chains of thought, and that behavior is then distilled into smaller, cheaper student models.
Finally, open problems persist: mechanistic interpretability, hallucination, generalization beyond the training distribution, and the evaluation and governance of increasingly capable unified systems.
Together, these threads describe a field where pretraining scaling, test-time compute, alignment, and mechanistic understanding intersect. Keep these themes in view as we dissect each mechanism in the coming sections.
Equations, code and original cards
2024-2026 Research Trends & Scaling Laws
Frontier directions: compute-optimal scaling, inference efficiency, and alignment of unified models
Key Research Directions
• Scaling laws: power-law loss in N, D, C; Chinchilla-optimal ≈ 20 tokens/param; test-time compute
• RL + distillation: reasoning traces transferred from large teachers to small students
• Open problems: interpretability, hallucination, evaluation, governance
Moment 10 / 12
Implementation Details: Python/PyTorch Snippets
Start with the unified block: text and image tokens share one residual stream and one self-attention operator, with modality embeddings and positional encodings doing the separation. This is joint attention, not a separate cross-attention layer.
The loss is the usual denoising objective from DDPM-style training, mean squared error between predicted and target noise, plus a small prompt-consistency term. Keep that coefficient near one tenth; too large and guidance dominates the score estimate.
The scheduler anneals the distillation weight lambda across steps, so the student first matches the teacher on easy denoising intervals and only later inherits aggressive few-step behavior.
For throughput, use automatic mixed precision, gradient checkpointing, warmup then cosine decay, and watch gradient norm; memory saved is what buys larger batch or resolution.
Together, the snippets show the real engineering surface: a shared attention block, a weighted variational objective, a distillation schedule, and systems choices that determine whether scaling is affordable.
The takeaway is that multimodal generation is not one trick; it is architecture, objective weighting, and optimization discipline aligned so the score model learns conditionally useful structure.
Equations, code and original cards
Implementation Details: PyTorch for Multimodal Diffusion
• Gradient checkpointing: trade roughly one extra forward for memory
• Warmup then cosine decay; clip by global gradient norm
• Log loss terms separately; ablate beta and lambda schedule
Moment 11 / 12
Advanced Section: Cutting-edge Variations & Open Questions
Let's explore the advanced section: cutting-edge variations and open questions in current research. This part highlights directions that push beyond conventional discrete-token, single-task pipelines.
Here are the key topics: emerging pixel-level multitask unified transformers, exploration of non-discrete token embeddings, potential joint video, audio, and image architectures, challenges in training stability and interpretability, and finally, opportunities driven by community research.
First, pixel-level multitask unified transformers replace per-task pipelines with a single architecture that conditions on the task and regresses outputs directly at pixel resolution. This yields tighter integration and amortizes representation learning across tasks.
Second, non-discrete token embeddings abandon vector-quantized codebooks in favor of continuous latent spaces. This avoids codebook collapse, preserves differentiability end to end, and captures fine-grained variation that discrete tokens quantize away.
Another direction is unifying video, audio, and images into joint architectures with shared tokenization and attention, which could unlock stronger cross-modal representations and generation capabilities than modality-specific models.
However, these innovations bring challenges, particularly training stability and interpretability. Controlling gradient norms across heterogeneous losses and explaining what unified representations encode remain critical open problems.
Finally, community-driven research initiatives play a vital role, as collaborative open-source efforts accelerate progress and open exploration pathways beyond what any single lab pursues.
Let's now look at a practical PyTorch snippet illustrating continuous token embeddings, showing how continuous token representations can be implemented directly in code.
This example defines a module that maps continuous token vectors through a learned linear projection into the model's embedding dimension, enabling smooth interpolation across token space and fully differentiable learning dynamics.
In summary, today's advanced topics spotlight research pushing the boundaries of unified transformer architectures and token representations, while confronting the stability and interpretability challenges these innovations introduce.
Equations, code and original cards
Advanced Section: Cutting-edge Variations & Open Questions
Discuss active research directions: multitask unified architectures, continuous token spaces, and cross-modal unification beyond vision and language.
• Training stability and interpretability challenges
• Community-driven research opportunities
PyTorch Snippet: Continuous Token Embeddings
import torch
from torch import nn
class ContinuousTokenEmbed(nn.Module):
def __init__(self, dim, token_dim):
super().__init__()
self.fc = nn.Linear(token_dim, dim)
def forward(self, x):
# x: [batch, tokens, token_dim]
return self.fc(x) # linear projection into the residual stream dimension
Moment 12 / 12
Comprehensive Quiz: Concepts and Computations
We've covered the core machinery of diffusion models and transformer architectures, from the denoising objective to attention's quadratic cost. This quiz tests both conceptual understanding and computation. Work through each question independently, and reason from first principles rather than recall.
When you finish, we'll walk through the solutions together, resolve any points of confusion, and connect your answers back to the underlying theory.
Equations, code and original cards
MAKE IT YOURS
Explain the change.
References, scope & corrections
Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.