Skip to main content
Back

CoCo Makes AI Draw Accurate Charts and Text by Writing Code First

CoCo replaces fuzzy natural-language planning with executable code as an intermediate reasoning step, unlocking precise layout control for structured image generation

Pro

  • CoCo uses executable code (not natural language) as the Chain-of-Thought reasoning step before generating images, enabling precise spatial layout control.
  • The pipeline has three stages: generate code from the prompt, execute it in a sandbox to get a structural draft, then refine the draft into a high-fidelity image.
  • On StructT2IBench, CoCo scores 73.52% overall, beating GPT-Image (49.58%) and all open-source models by a wide margin.
  • The team built CoCo-10K, a dataset of Text-Code-Draft-Final triplets, after finding that base BAGEL only produces executable code 9% of the time; CoCo achieves 100%.
  • Gains over direct generation: +68.83% on structured visuals, +54.8% on multilingual text rendering, +41.23% on long-text generation.
  • Code and dataset are open-source on GitHub; the paper is on arXiv.

Ask any image generation model to draw a 2D plot of y = x², render a restaurant menu with accurate prices, or produce a travel poster with legible multilingual text, and you will almost certainly get something wrong -- misplaced labels, garbled text, or a layout that bears little resemblance to the prompt. The root cause is not a lack of visual quality; it is a lack of structured reasoning. A new framework called CoCo (Code-as-CoT) from researchers at South China University of Technology and StepFun proposes a fix: replace vague natural-language planning with executable code as the reasoning step before image synthesis.

Why "think before you draw" is not enough

The dominant approach to improving text-to-image generation right now is Chain-of-Thought (CoT) reasoning -- the same technique that made LLMs dramatically better at math by forcing them to reason step-by-step before answering. Applied to image generation, CoT means the model writes a plan in plain English ("place a bar chart on the left, title at the top...") before generating pixels. Several recent systems, including BAGEL-Thinking, T2I-R1, and IRG, follow this paradigm.

Existing CoT-based T2I methods largely rely on abstract natural-language planning, which lacks the precision required for complex spatial layouts, structured visual elements, and dense textual content. A sentence like "put the legend in the upper right" is ambiguous -- it does not encode exact pixel coordinates, font sizes, or data values. The model is left to guess, and it often guesses wrong on anything structurally demanding.

Comparison of five image generation reasoning paradigms including CoCo

Code as a blueprint

CoCo's core insight is that code is a far more precise reasoning medium than prose. Code can deterministically encode pixel coordinates, canvas dimensions, font sizes, data series, and object relationships -- and crucially, it can be executed to verify the plan before any diffusion or autoregressive image generation happens.

The framework operates in three stages:

  1. Code generation: Given a text prompt, the model generates executable code (Python/matplotlib-style scripts) that explicitly specifies the structural layout -- object placement, text content, canvas size, and spatial relationships.
  2. Draft rendering: The code runs inside a sandboxed environment to produce a deterministic draft image. This draft is a simple, programmatic rendering -- think a clean matplotlib figure or a wireframe poster -- that captures the semantic structure but lacks visual polish.
  3. Draft-guided refinement: The draft image is fed back into the unified multimodal model alongside the original prompt. The model uses both a ViT encoder (for high-level semantic understanding) and a VAE encoder (for low-level pixel details) to refine the draft into a high-fidelity final image while preserving the structural layout.

Rather than only relying on abstract natural-language descriptions, CoCo requires the model to express its planning process as code that encodes spatial layouts, structural constraints, and object relationships in a deterministic manner. The generated code is executed within a sandboxed environment to produce a draft image that faithfully reflects the intended structure.

CoCo three-stage pipeline: code generation, sandbox execution, and draft-guided image refinement

Building the training data from scratch

One of the less obvious but critical contributions is the CoCo-10K dataset. When the team ran zero-shot experiments on BAGEL (the base unified multimodal model they build on), they found two hard failures: the model produced non-executable code most of the time, and even when given a valid draft image, it tended to ignore it and generate something entirely new.

Only 9.06% of BAGEL's generated programs compile successfully (29/320) on LongText-Bench, indicating that the model struggles to produce reliable code for downstream rendering. In contrast, after fine-tuning with CoCo's training pipeline, CoCo achieves a 100% compilation success rate.

CoCo-10K was built to fix both problems. It contains two complementary components:

  • Editing Dataset: Sourced from StructVisuals, a collection of structured chart images. Each sample pairs an original chart (A-Image) with a corrected version (B-Image), teaching the model to make precise edits without destroying the underlying structure.
  • Synthesis Dataset: Gemini 3 Pro generates code from diverse prompts covering scientific diagrams, infographics, and text-heavy posters. That code is executed to produce a draft (A-Image), then Nano Banana refines it into a polished final image (B-Image). This creates the Text-Code-Draft-Final triplets that CoCo needs for end-to-end training.

Training uses supervised fine-tuning on top of BAGEL, with two loss functions: cross-entropy on the generated code tokens, and MSE on the VAE tokens for the final image. An important finding from the ablation: only 5% of training data needs to be Text-Code pairs. The dominant signal comes from draft-to-final refinement data, which teaches the model to use the structural scaffold rather than ignore it.

The numbers are hard to argue with

The team evaluated CoCo on three benchmarks specifically designed to stress-test structured and text-intensive generation:

  • StructT2IBench: 1,714 samples covering charts, math figures, tables, puzzles, and scientific diagrams, evaluated via multi-round QA.
  • OneIG-Bench: Multilingual text rendering (English and Chinese), evaluated with a composite metric combining edit distance, completion rate, and word accuracy.
  • LongText-Bench: 160 prompts targeting accurate rendering of long-form Chinese and English text inside images.

CoCo achieves improvements of +68.83%, +54.8%, and +41.23% over direct generation on StructT2IBench, OneIG-Bench, and LongText-Bench respectively, while also outperforming other generation methods empowered by CoT.

On StructT2IBench, CoCo achieves an overall accuracy of 73.52%, significantly surpassing the best baseline (GPT-Image, 49.58%). It leads on charts (79.44%), graphs (62.58%), math (69.12%), and tables (79.15%). On text rendering, CoCo reaches 0.895 (English) and 0.811 (Chinese) with an overall score of 0.853 on OneIG-Bench, outperforming all compared generation-only and unified MLLM methods.

Side-by-side comparison of BAGEL, BAGEL Thinking, DraCo, and CoCo outputs on restaurant menu, travel ad, and math plot prompts

An unexpected bonus: adaptive aspect ratios

One emergent behavior the team did not explicitly train for: CoCo adapts canvas dimensions to match the prompt semantics. Poster-like prompts produce wide 16:9 outputs; charts and diagrams default to square or near-square canvases. This behavior suggests that the model does not simply memorize a fixed rendering configuration. Instead, it learns to treat canvas size and layout parameters as part of the reasoning process encoded in the generated code. All training was done at a fixed 1024-resolution, making this generalization genuinely surprising.

Where it falls short

CoCo is purpose-built for structured, layout-heavy, and text-intensive generation. It is not a general-purpose photorealism upgrade. On puzzle tasks in StructT2IBench, it scores 49.10% -- below GPT-Image (59.42%) and Nano Banana (63.87%) -- suggesting that purely spatial reasoning without a clear programmatic structure is harder to encode in code. The approach also inherits a dependency on the quality of the code generation step: if the model writes code that produces a structurally wrong draft, the refinement stage has to work harder to correct it.

What this unlocks

The practical use-cases are clearest in domains where layout precision is non-negotiable:

  • Scientific figure generation (plots, annotated diagrams, equation-heavy slides)
  • Data visualization from natural-language descriptions
  • Multilingual poster and infographic design
  • UI mockups and structured document generation
  • Any pipeline where a human needs to verify the layout before committing to a full render

The draft-preview step is particularly valuable: because the draft is generated from deterministic code, it is cheap to produce and easy to inspect or edit before the expensive refinement pass runs. This turns image generation into a two-stage workflow that practitioners can actually intervene in.

The real breakthrough here is not just the performance numbers -- it is the demonstration that code is a valid and verifiable reasoning modality for visual generation. The code and dataset are publicly available, and the approach is model-agnostic enough that it could be adapted to any unified multimodal model that supports interleaved text and image generation. Given that structured visual generation is one of the clearest remaining gaps between open-source and frontier closed models, CoCo's approach points toward a concrete path forward.