Design practice · Research feature

AI Generates Scientific Vector Graphics from Text Using TikZ

To address this, we propose the use of TikZ, a well-known abstract graphics language that can be compiled to vector graphics, as an intermediate representation of scientific figures.

Adapted from research by Jonas Belouadi, Anne Lauscher, Steffen Eger.

arXiv preprint revision · 2024-01-23 · Attribution & reuse
In this article
Editorial illustration of printing plates.

Authors’ overview

Generating bitmap graphics from text has gained considerable attention, yet for scientific figures, vector graphics are often preferred. Given that vector graphics are typically encoded using low-level graphics primitives, generating them directly is difficult. To address this, we propose the use of TikZ, a well-known abstract graphics language that can be compiled to vector graphics, as an intermediate representation of scientific figures. TikZ offers human-oriented, high-level commands, thereby facilitating conditional language modeling with any large language model. To this end, we introduce DaTikZ, the first large-scale TikZ dataset consisting of 120k TikZ drawings aligned with captions. We fine-tune LLaMA on DaTikZ, as well as our new model CLiMA, which augments LLaMA with multimodal CLIP embeddings. In both human and automatic evaluation, CLiMA and LLaMA outperform commercial GPT-4 and Claude 2 in terms of similarity to human-created figures, with CLiMA additionally improving text-image alignment. Our detailed analysis shows that all models generalize well and are not susceptible to memorization. GPT-4 and Claude 2, however, tend to generate more simplistic figures compared to both humans and our models. We make our framework, AutomaTikZ, along with model weights and datasets, publicly available.

Introduction

Automated vector graphics generation is a growing research area as well, but current methods have their own share of limitations. Specifically, they mainly generate low-level path elements of the Scalable Vector Graphics (SVG) format, either failing to maintain accurate geometric relations or only generating outputs of limited complexity such as single icons or font characters.

Text-to-Image & Vector Graphics Generation

Vector graphics generation has evolved as a parallel field. Building upon innovative work in sketch generation, generate single SVG font characters made up of straight lines and Bézier curves. Cited researchers extend this approach to include SVG icons. However, none of these models support text conditioning. Another branch of research focuses on vectorizing text-to-image models. Although these methods enable text conditioning, text-to-image models typically have difficulties producing flat-colored SVG-style images, and the vectorized results tend to have imprecise geometric relations and jagged paths. Addressing these challenges, and investigate auto-regressive language modeling directly on SVG representations. Even though these approaches better capture the aesthetics of vector graphics, they are limited to editing existing graphics or generating monochrome icons of limited complexity.

Scientific Figure Understanding

Despite the limited number of approaches dedicated to generating scientific figures, scientific figure understanding is a subject of extensive research. Arguably, the task that is inverse to ours is the captioning of scientific figures. Expanding on prior work in scientific visual question-answering, train a captioning model using a corpus of synthesized figure-caption pairs. Cited researchers extend this approach to real scientific figures, noting substantial challenges. To improve performance, reformulate the task, augmenting captions with OCR tokens and paragraphs referencing the figures. take a different approach and utilize reinforcement learning to consider the quality of the captions during training. In addition to such task-oriented models, recent advancements in multimodal large language modeling (MLLM; ) allow for generalized visual reasoning about scientific figures.

Code Generation

As graphics languages are a subset of programming languages, our work is closely related to code generation. At its core is the ongoing research on pre-training or fine-tuning LLMs on code, commonly with a multitask objective consisting of causal language modeling and infilling prediction. Despite the significant amount of recent progress, the primary focus of code generation remains on high-resource programming languages such as Python, Java, or JavaScript. TikZ commands, in comparison, are invoked as TeX macros, and the TeX programming language is considered low-resource and typically overlooked in model evaluations. Yet, TeX may still exist in training corpora, as evidenced by GPT-4’s ability to comprehend TeX and TikZ. As far as we know, there has been no comprehensive evaluation of this capability, which we also address in this work.

TeX Stack Exchange

We also source TikZ drawings from TeX Stack Exchange (cf. §1). We examine the quarterly data dump and extract questions tagged with TikZ and relevant answers with a minimum score of 1. To convert textual questions into image captions, we utilize WizardLM, an LLM trained to follow arbitrary instructions. Using the title and body of a question as context, we task WizardLM with creating a descriptive caption for the figure provided in the answer. More details on the caption generation procedure can be found in Appendix B.

Data Augmentation

Prior research indicates a correlation between caption length and caption quality. Notably, propose a heuristic to judge scientific captions with less than 30 tokens as being of poor quality. Given the recent advancements in MLLM, and notably in MLLM with a focus on science (cf. §2), we propose the automatic augmentation of such captions. For an in-depth analysis of implications, refer to Appendix C.

Methods

We leverage LLaMA as the base model in most experiments, using captions from DaTikZ as model input and TikZ code as ground truths. Since TeX source files from arXiv were included in LLaMA’s pre-training data, it may have prior knowledge beneficial for this task. We choose the original LLaMA release over its updated revisions, LLaMA 2 and CodeLLaMA, as their training data is not as clearly specified. This uncertainty and their more recent release would make it difficult to create a test set without training-to-test data leakage. We also experiment with GPT-4 and Claude 2, as earlier research hints at inherent potential for our task (cf. §3.1 and §2), and employ the same chain-of-thought approach outlined in §3.1. However, as they are proprietary, we can only address data leakage for LLaMA.

CLiMA

A potential drawback of vanilla LLaMA is that it may not understand visual concepts, given that it was not designed to process image data. However, this ability could significantly enhance the creation of scientific figures. Therefore, we modify LLaMA by combining it with a CLIP ViT-H/14 model. CLIP is frequently employed to establish a bridge between vision and natural language, thereby facilitating the creation of MLLMs.

Error Handling & Correction

A general issue with our language modeling approach to TikZ generation is that outputs may violate the syntactic and semantic rules of TeX, potentially leading to errors and uncompilable documents. While there are constrained decoding algorithms that can force models to form valid programs, they depend on parse trees and are only useful for languages with a context-free grammar. TeX, however, has a flat, unstructured syntax that is generally impossible to parse, rendering these methods unsuitable for our approach.

Experiments

Before fine-tuning our models on DaTikZ, we extract a sample of 1k human-created items to serve as our test set. As LLaMA’s training started in December 2022, we only sample items introduced after this date to avoid data leakage. We conduct both automatic (§5.1) and human evaluations (§5.2). Additional results and instances of generated TikZ drawings are available in Appendices C and E.

Model Sizes

In terms of model size, we fine-tune LLaMA7b and CLiMA7b, each with 7 billion parameters (7b), as well as LLaMA13b and CLiMA13b with 13 billion parameters (13b), respectively. During inference, we additionally evaluate CLiMA13b with CLIP receiving compiled human-created TikZ drawings as input instead of captions, which we refer to as CLiMAimg for clarity (cf. §4.1).

Results

Within model sizes, CLiMA7b outperforms LLaMA7b on CrystalBLEU, EED, CLIPScore, and CLIPScoreimg by up to 0.4pp, suggesting that, even when only text inputs are involved, integrating CLIP into the model has a predominantly positive effect. CLiMA13b continues this trend, showing a 0.1pp higher CLIPScore than LLaMA13b. However, we also see that this does not necessarily have to increase the similarity with a reference image as well, as LLaMA13b has a 0.1pp higher CLIPScoreimg. On CrystalBLEU and EED, CLiMA13b again fares better, although, with 0.1pp, the gap is not as pronounced as for the 7b models, possibly due to diminishing returns.

The right radar chart compares our best text-only model, CLiMA13b, with CLiMAimg, GPT-4, and Claude 2. As before, all models perform roughly the same on CSR, except for Claude 2, which needs noticeably more samples. As expected, CLiMAimg, having access to reference images, improves upon CLiMA13b in CLIPScoreimg by 1.2pp. However, this does not lead to an improvement in CLIPScore, echoing our earlier observation that image and caption-image similarity do not always correlate. It also does not improve KID, demonstrating that the overall quality of the images remains constant. Nevertheless, the string-based metrics are 0.1–0.4pp higher, indicating that conditioning on reference images positively impacts code similarity.

Results

In summary, our human evaluation aligns well with our automatic metrics, with the added benefit of lower susceptibility to typographic attacks. CLiMA13b outperforms LLaMA13b on CS, while CLiMAimg surpasses LLaMA13b on RS. GPT-4 shows peculiar distributions, with the mode (and also the expected value for RS) lagging behind, highlighting the effectiveness of our models.

Analysis

The issue of language models memorizing and copying training data is a prevalent concern. Similarly, we discovered in §5.1 that GPT-4 and Claude 2 tend to perform typographic attacks by memorizing and copying input captions. In this section, we analyze the extent of these issues on our test set using the concept of n-gram novelty. Specifically, to measure code novelty, we determine the proportion of n-grams in the model-generated TikZ code that are not found in the training data. To measure caption copying, we calculate the proportion of n-grams from the caption that were copied verbatim into the output code. For comparison, we also calculate both metrics for human references.

Conclusion & Future Work

In this work, we present AutomaTikZ, a project for automatically generating TikZ drawings based on natural language descriptions. As part of AutomaTikZ, we release DaTikZ, a pioneering dataset of aligned TikZ drawings and captions, and CLiMA, a novel model architecture which integrates multimodal CLIP embeddings into LLaMA. By fine-tuning CLiMA on DaTikZ, we demonstrate that it outperforms LLaMA on several metrics and also surpasses proprietary GPT-4 and Claude 2. In addition, CLiMA can also process images, potentially extending its application to vectorization and conditioning on sketches. Important finds are that (i) integrating CLIP can lead to improvements, even when only text inputs are involved, provided the task relates to visual concepts, and that (ii) attention should be paid to typographic attacks when evaluating models that generate text-rich images.

In future research, we aim to incorporate insights from the caption generation community and enrich our input texts with other figure-mentioning sections of the source documents (cf. §2). We also plan to enhance our extraction pipeline, especially since we had to exclude over 120k TikZ images from arXiv that failed to compile. We hope that these modifications will bring us a step closer to bridging the gap to human performance.

Training Challenges

During the training phase, we limit the context size of our models to 1200 tokens due to constraints of our existing GPU resources, and filter out all examples that exceed this limit. Although most examples were within these limits, they were generally very close to the maximum allowable length. This prevented us from training our models to perform functions such as multi-turn conversations like chatbots, which could have allowed compiler logs to be fed back into the model to obtain improved outputs. Although we did consider this approach in preliminary experiments with vanilla LLaMA and its instruction-tuned derivatives in a zero-shot setting, the baseline performance of these models was too poor to produce usable TikZ output. Instead, by drawing parallels to text-to-image generation models that condition the output solely on the input caption and using our iterative resampling technique to improve the outputs, we provide more resource-efficient alternatives with good performance.

In-depth Evaluation Metric Scores

The table also contains the Code Error Rate (CER), which indicates the average number of compile time errors of our models. As evidenced, it largely reflects the trends of CSR. Most models generate less than one error on average, with Claude 2 being the only exception. Overall, GPT-4 achieves the best score, possibly because it has fewer opportunities to make mistakes by generating shorter and less complex code than other models (cf. §A). Since CLIPScore, at a fundamental level, evaluates similar aspects to CS from our human evaluation in §5.2 (caption-image similarity), and CLIPScoreimg is the intuitive counterpart to RS (image similarity), we also calculate their respective Spearman correlations. At the segment-level, the correlation coefficients are 0.23 for CLIPScore and CS, and 0.25 for CLIPScoreimg and RS (the degrees of correlation aligning with values commonly found for machine translation metrics; ). The system-level correlations are 0.5 and 0.8, respectively. The higher correlations witnessed for image over caption-image similarity lends credibility to our hypothesis regarding CLIPScore’s biases favoring images of text.

Impact of Data Augmentation

Although eliminating caption augmentation reveals subtle improvements for CSR and KID, the model noticeably underperforms for all other metrics, particularly CLIPScore (1.1pp lower) and CLIPScoreimg (2.4pp lower). Interestingly, the metrics that show an improvement do not compare model outputs with individual references but either do not use references at all (CSR) or use them only to evaluate general characteristics (KID). On the other hand, metrics with worse results are mostly reference-based. We attribute this observation to the reduced amount of information carried by non-augmented captions, most likely leading to a decline in CLiMA’s ability to capture the connection between captions and images and, therefore, delivering lower performance in reference-based metrics. Conversely, with less information that might otherwise constrain the output space, the model is likely to gain more flexibility in producing figures. We conjecture that this allows the model to concentrate more on aspects that contribute positively to metrics without direct references, such as CSR and KID. This hypothesis provides a plausible explanation for our observed results.

Upon examining the impacts of not sampling images during the training process, we find that most metrics exhibit worse performance, with only CSR yielding comparable results. These findings support our choice of training strategy and show that integrating images throughout the training process can bolster performance even when only textual inputs are considered at the evaluation stage.

Importance of each Data Source

The greatest performance decline occurs with the removal of arXiv, a consistent outcome across all metrics. As the primary contributor of scientific figures totaling 86k, its absence instigates a decline of 4.5pp for EED, 5.5pp for CLIPScoreimg, 1.4pp for CLIPScore, and 1.9pp for CrystalBLEU. Similarly, CER inflates nearly fourfold, and CSR experiences a noticeable increase, as well. Strikingly, however, results diverge for DaTikZ’s second largest source, the TeX Stack Exchange, which provides 29k examples. Contrary to expectations, the general downward trend is comparatively small, with EED and CLIPScoreimg only suffering a 0.2pp decrease and CLIPScore and CrystalBLEU even improving by 0.2pp and 0.1pp, respectively. We attribute this outcome to TeX Stack Exchange’s unique focus on providing problem-specific minimum working examples rather than scientific figures like the rest of DaTikZ. Although this could still provide valuable training signals, we did not design our test set (only ~100 of its 1k random samples originate from this source) to evaluate the ability of our models to follow technical advice given in the figure captions. Consequently, we plan to improve our testing framework in future work. Next, although we exclude artificial examples from our test set due to their non-human origin and their removal from the training data improves CER and CSR, their absence still has a negative impact on all other metrics. Without artificial examples, EED drops by 0.5pp, CLIPScoreimg by 0.8pp, CLIPScore by 0.1pp and CrystalBLEU by 0.3pp, showing that distillation of GPT-4 is a useful component in the training process. Lastly, even though curated examples constitute the smallest data source (less than 1k examples), their omission from the training data induces greater negative performance impacts than the removal of TeX Stack Exchange (0.2pp for EED, 0.3pp for CLIPScoreimg and 0.1pp for CrystalBLEU). We attribute this disproportionate value per size to the likely higher quality of code and captions inherent to curated examples.

Overall, if the results are examined independently, we observe that each source has primarily positive effects. However, when evaluated in the context of the source sizes, we find that curated examples create a particularly noticeably positive impact, whereas TeX Stack Exchange exhibits smaller effects. These insights will guide us to focus more on collecting such curated examples in future work.