Hybrid Architecture for Text-to-Image Generation: Precise Chinese Text Rendering and Arbitrary Aspect Ratios
This article explores the practical application of hybrid architectures in text-to-image generation models to address common challenges in text rendering and fixed resolutions. It details the methodology of combining autoregressive models for semantic understanding with diffusion decoders for pixel generation. Topics covered include glyph condition encoding, an OCR-based verification loop for Chinese text rendering, achieving arbitrary aspect ratios through position encoding adaptation, and best practices for large-scale distributed training and evaluation.
I. Background: Two Challenges in Text-to-Image Deployment
Text-to-image models often demonstrate stunning results in demos, but developers typically encounter two major issues when applying them to production scenarios.
The first issue is text rendering. Titles, slogans, prices, and descriptive texts in images often suffer from missing strokes, connected glyphs, garbled characters, and typos. Because the English alphabet has a small character set, issues are relatively rare. In contrast, Chinese characters are numerous, structurally complex, and densely packed with strokes, demanding higher modeling capabilities from the model. Consequently, Chinese text rendering is significantly more difficult than English.
The second issue is resolution. Many models only support preset aspect ratios, such as 1:1, 4:3, or 16:9. Scenarios like posters, social media covers, and banner ads often require specific dimensions. Directly using preset ratios necessitates cropping or leaving whitespace, which wastes canvas space and risks cutting off key elements.
To address these issues, a recent trend in the industry is to introduce the reasoning capabilities of language models into the image generation pipeline. This allows the model to first understand requirements, plan the composition, and then perform pixel-level rendering. The following content discusses this architecture, key technologies, and engineering implementation methods based on this approach.
II. Hybrid Architecture: Understand First, Draw Later
2.1 Basic Concept
Pure diffusion models excel at generating high-frequency details and natural textures but have relatively weak control over long-sentence semantics, spatial relationships between multiple objects, and text content accuracy. Autoregressive models generate sequences token by token, making them naturally suited for semantic and structured information, but outputting high-resolution pixels directly is costly.
The hybrid architecture combines the strengths of both into two stages:
- Understanding and Planning Stage: An autoregressive module reads the text prompt and outputs a set of semantic representations. This set contains information about objects, positions, styles, and text content, functioning similarly to a composition sketch.
- Drawing Stage: A diffusion decoder uses this representation as a condition to progressively denoise and generate the details of the final image.
This process can be likened to a designer’s workflow: first understanding the requirements, determining the layout and copy, and then moving into detailed drawing.
2.2 Module Responsibilities
| Module | Primary Responsibility | Strengths | Limitations |
|---|---|---|---|
| Autoregressive Understanding Module | Semantic parsing, global composition, text content planning | Long-text understanding, logical relations, instruction following | High cost for direct pixel output |
| Diffusion Decoder | Pixel detail generation, textures and lighting | Image quality, detail restoration | Weak control over semantics and text content |
| Text Encoding Condition | Provides glyph and position constraints | Improves text rendering accuracy | Requires additional data and training design |
The key to this division of labor lies in interface design. The representations output by the understanding module must contain sufficient structural information; otherwise, the decoder cannot faithfully restore the composition. In practice, a common approach is to have the understanding module output a sequence of conditions, which the decoder reads via cross-attention.
2.3 Architecture Trade-offs
When choosing a hybrid architecture, the following dimensions should be compared:
- Semantic Accuracy: A larger understanding module usually improves adherence to complex prompts, but inference latency and VRAM usage also increase.
- Image Quality Ceiling: The capacity of the diffusion decoder determines detail quality. A decoder that is too small will result in blurry textures.
- Controllability: The more structured the intermediate representation, the easier it is to perform local editing and layout adjustments later.
- Training Cost: The two modules require staged or joint training, making debugging more complex than a single model.
In engineering, teams should first clarify the metrics most valued by the business. If the primary scenario is posters and copy-heavy images, text accuracy and composition stability take priority, warranting greater investment in the understanding module.
III. Text Rendering Focus: From Glyph Conditions to Verification Loops
3.1 Why Chinese Text is Difficult to Render
There are over three thousand commonly used Chinese characters, far exceeding the Latin alphabet. Each character consists of multiple strokes and components, where the spacing and proportions between components are critical. During the denoising process of a diffusion model, a local feature offset of just one pixel can cause a noticeable error in the character glyph. Therefore, relying solely on general image data for training makes it difficult to achieve stable Chinese character forms.
3.2 Glyph Condition Encoding
A common practice is to introduce a dedicated text encoder. It takes the text content to be rendered, font style, and bounding box, and outputs glyph features, which are then injected into the diffusion decoder’s conditional input. This way, when generating the corresponding region, the decoder receives clear glyph constraints.
Pseudocode illustration:
def build_text_condition(text_items):"""text_items: List, each item contains text content, bounding box (x0, y0, x1, y1), font style tagReturns: Glyph condition features for the diffusion decoder"""glyph_features = []for item in text_items:glyph = render_reference_glyph(item["text"], item["style"]) # Render reference glyphfeat = text_encoder(glyph) # Encode into featuresglyph_features.append({"feat": feat, "box": item["box"]})return glyph_features
This code only expresses the process. render_reference_glyph and text_encoder need to be replaced based on the specific implementation.
3.3 Training Data Construction
Text rendering capabilities rely heavily on data. Common data construction methods include:
- Synthetic Data: Using a typography engine to render specified text onto background images, generating image-text pairs with precise annotations.
- Real Data Filtering: Extracting text-containing images from materials like posters and book covers, and supplementing text content through manual or automatic annotation.
- Hard Example Augmentation: Increasing the sampling ratio for difficult samples, such as visually similar characters, multi-line layouts, and mixed languages.
Data quality is more important than quantity. Incorrect text annotations will lead the model to learn erroneous glyphs, which are very difficult to correct later.
3.4 Verification Loop
After generation, Optical Character Recognition (OCR) can be used to read back the text in the image and compare it with the target text in the prompt. The character accuracy calculation method is as follows:
import difflibdef char_accuracy(target: str, recognized: str) -> float:"""Calculate character accuracy based on edit similarity, result range [0, 1]."""if not target:return 1.0 if not recognized else 0.0matcher = difflib.SequenceMatcher(None, target, recognized)matched = sum(block.size for block in matcher.get_matching_blocks())return matched / max(len(target), len(recognized))
This metric can serve as an automated testing gate. When the character accuracy falls below a threshold, the system automatically regenerates the image or routes the sample to a manual review queue.
IV. Arbitrary Resolution Generation: From Preset Ratios to Custom Dimensions
4.1 Source of Resolution Constraints
Diffusion models typically work in a latent space. The image is first compressed by an encoder at a fixed downsampling factor, such as 8x. The latent space features are then divided into patches and fed into a Transformer or U-Net. Therefore, the width and height of the image must be multiples of the product of the downsampling factor and the patch size; otherwise, correct splitting is impossible.
Early models solved this by presetting a set of resolution buckets, using only these sizes for both training and inference. The key to supporting arbitrary aspect ratios lies in allowing the model’s position encoding to adapt to different grid shapes and dynamically calculating the grid based on the target size during inference.
4.2 Position Encoding Adaptation
Position encoding determines how the model perceives the relative positions of pixels or patches. Common solutions include interpolation of absolute position encoding and dynamic extrapolation of Rotary Position Embedding (RoPE). The former adapts to new grid sizes by interpolating the pretrained position table; the latter uses the definition of rotation angles to give the attention mechanism an inherent relative position perception. Regardless of the solution, training should cover multiple aspect ratios; otherwise, the model is prone to subject repetition or composition fragmentation under extreme ratios.
4.3 Engineering Implementation of Size Calculation
In production systems, users typically provide an aspect ratio or target size. The system needs to convert these into a resolution that satisfies the alignment constraints. The following function provides a general approach: using the longest side as the constraint, calculating the other side proportionally, and aligning it to a specified multiple.
def fit_resolution(ratio_w: int, ratio_h: int,max_side: int = 2048,min_side: int = 512,multiple: int = 16) -> tuple[int, int]:"""Calculate usable resolution based on aspect ratio.max_side: Upper limit for the longest side, constrained by VRAM and inference timemultiple: The multiple to which the size must be aligned, determined by downsampling factor and patch size"""ratio = ratio_w / ratio_hif ratio >= 1:w, h = max_side, max_side / ratioelse:w, h = max_side * ratio, max_sidew = max(min_side, round(w / multiple) * multiple)h = max(min_side, round(h / multiple) * multiple)return w, hprint(fit_resolution(3, 4)) # (1536, 2048)print(fit_resolution(16, 9)) # (2048, 1152)
The actual ratio after alignment may have a slight deviation from the target ratio. The acceptable error margin for business purposes should be determined during the requirements phase and verified in testing.
4.4 Practical Considerations
- Extreme ratios (e.g., ultra-wide banners) increase the extrapolation difficulty of position encoding; it is recommended to retain such samples in the training data.
- As the longest side increases, VRAM usage and inference time grow rapidly; limits should be set based on hardware conditions.
- For printed materials requiring exact dimensions, cropping or scaling is still necessary after generation to ensure the delivered size meets specifications.
V. Training Engineering: Data, Parallelism, and Operators for Large Models
5.1 Data Preprocessing
The first step in the training pipeline is data preprocessing, including deduplication, filtering low-quality images, unifying encoding formats, and generating text descriptions and text annotations. For multimodal models, image-text consistency must also be checked to eliminate mislabeled samples. Preprocessing is often underestimated, but it directly determines the upper limit of subsequent training.
5.2 Distributed Training
When the model scale is large, a single GPU cannot accommodate all parameters and optimizer states, necessitating a combination of parallel strategies:
- Data Parallelism: Each GPU holds a complete model replica, processes different batches of data, and updates parameters through gradient synchronization.
- Tensor Parallelism: Splits the weights of a single operator across multiple GPUs, reducing single-GPU VRAM usage.
- Pipeline Parallelism: Splits the model by layers into multiple stages, which execute in a pipeline across different devices.
In actual projects, the three are usually combined, accompanied by mixed-precision training and gradient accumulation to balance VRAM, communication, and computational efficiency.
5.3 Optimizers and Operator Fusion
During training, common optimizers include AdamW, which improves regularization through decoupled weight decay. Exponential Moving Average (EMA) is used to smooth parameter updates, and EMA weights are often used during inference for more stable output. Regarding normalization layers, RMSNorm removes the mean-centering step, reducing computation, and is widely used in large models.
Operator fusion is a common method to improve training efficiency. Merging multiple consecutive small operators into a single kernel reduces the number of memory read/writes for intermediate results, thereby increasing throughput. Fusion strategies need to be adjusted based on hardware characteristics, as optimal fusion methods may vary across different accelerator chips.
5.4 Training Stability
In large-scale training, sudden loss divergence, gradient explosions, and numerical overflow are common. General countermeasures include gradient clipping, learning rate warmup, periodic checkpoint saving, and monitoring activation statistics across layers. When anomalies occur, the system should be able to roll back to the latest stable checkpoint and check whether the data batch contains anomalous samples.
VI. Evaluation Methods: Establishing a Reproducible Metric System
Evaluating image generation is more complex than classification tasks, and a single metric rarely reflects overall quality. It is recommended to build an evaluation set from the following dimensions:
- Text Accuracy: Use the character accuracy metric mentioned earlier to track performance across different character counts, fonts, and layouts.
- Semantic Adherence: Check whether the generated image contains the objects, quantities, and attributes specified in the prompt. Visual Question Answering (VQA) models can be used for automated judgment, supplemented by manual spot-checks.
- Composition and Layout: Check whether element positioning, whitespace, and hierarchical relationships are reasonable.
- Resolution Adaptability: Evaluate image completeness under various aspect ratios, observing for subject truncation or repetition.
- Aesthetic Quality: Primarily use manual scoring, supplemented by automated aesthetic scores.
The evaluation set should cover real business scenarios and maintain version control. After each model update, the same evaluation set should be used for retesting, and differences recorded to facilitate locating regression issues.
VII. Deployment Practice: Production Pipeline for Posters and Social Covers
Taking marketing poster generation as an example, a deployable pipeline is as follows:
- Requirement Structuring: Break down the operator’s natural language requirements into fields such as theme, copy, dimensions, style, and prohibited elements.
- Size Calculation: Determine the target aspect ratio based on the placement channel, and use the previously mentioned size function to obtain the generation resolution.
- Prompt Assembly: Convert structured fields into model inputs, listing text content separately to avoid mixing it with descriptive sentences.
- Generation and Verification: After generating the image, perform OCR readback and character accuracy checks; if it fails to meet standards, automatically retry.
- Manual Review: Check brand compliance, legal compliance, and sensitive content, and deliver upon confirmation.
- Archiving and Feedback: Save prompts, parameters, and results, and record manual modification suggestions for subsequent optimization.
During deployment, it is important to note operational constraints and compliance requirements specific to the production environment.
