Manuscript Offprint
arXiv:2610.36907A lightweight C Code Generator for Heterogeneous TinyML Systems
Abstract
Over the past decade, the significant advancements in artificial intelligence have been closely tied to increasingly sophisticated training frameworks and steadily powerful computing hardware. However, the entire ecosystem remains fragmented. On one hand, models are represented with frameworks dependent formats, while on the other hand, new tailored hardware for accelerating novel operators has continued to emerge. To effectively diminish the transfer costs from training to inference, we propose a lightweight C code generator designed for bare-metal heterogeneous systems that incorporate domain-specific accelerators. Through a comprehensive case study on a RISC-V based radar DSP, we demonstrate that by employing an accelerator with ahead-of-time optimizations like weight tuning and bias fusion, our approach achieves a improvement in inference speed and a 20% reduction in binary size compared to the microTVM flow registered with the same accelerator, thus offering another compelling choice for resource-constrained edge devices. The code is open-sourced in Gitlab .
CCS Concepts
• Software and its engineering → Source code generation.
ACM Reference Format:
Chen Liu*, Bernhard Vogginger*, Christian Mayr*†. 2025. A lightweight C Code Generator for Heterogeneous TinyML Systems. In Workshop on Compilers, Deployment, and Tooling for AI (CODAI'25), January 20, 2025, Barcelona, Spain. ACM, New York, NY, USA, 5 pages.
1 Introduction
Numerous lightweight deep learning models have recently emerged, achieving impressive performance in classification and recognition tasks while consuming minimal resources. Deploying these models on edge devices and serving in low-power mode have become increasingly popular. Established software frameworks, such as TensorFlow [1] and PyTorch [16], along with general-purpose hardware (e.g., CPUs, GPUs, and TPUs), support model training in a mature manner. However, when it comes to deploying deep learning models on a wide variety of edge devices with highly diverse hardware resources, the deployment process becomes complex, and efficiency cannot be guaranteed—this includes both model runtime performance and human resource expenditure.
To address these challenges, major frameworks have developed expended toolkits to simplify deployment. For instance, Google introduced TensorFlow Lite (TFLite) [8] and TensorFlow Lite Micro (TFLM) [4] to enable production-level model deployment on resource-constrained devices. Similarly, Meta has announced ExecuTorch [14] to enhance its deployment pipeline for PyTorch.
Another force to overcoming deployment barriers comes from device vendors, who provide end-to-end development toolkits optimized for their own hardware. These toolkits ensure model performance on deterministic backend devices, such as STM32Cube.AI from STMicroelectronics [19], ai8x-synthesis from Analog Devices [5], and eIQ toolkit from NXP [15].
Multi-Level Intermediate Representation (MLIR) is an emerging framework for creating reusable and extensible compiler infrastructures. Its versatility has been demonstrated in diverse applications, including CPU-FPGA heterogeneous computing nodes and FPGA-based data centers . Building on MLIR's capabilities, the Tiny Intermediate Representation Execution Environment (TinyIREE) framework further generates compact workloads with optimized runtime libraries for embedded systems . Additionally, frameworks like TVM have also been employed to deploy DNN models on heterogeneous edge devices, expanding the scope of efficient model deployment in edge computing .
However, current solutions still face several limitations:
https://gitlab.com/chensterliu/dnn_codegen
- While TFLM and ExecuTorch remove OS dependencies, they continue to rely on C++ to wrap low-level library functions. An embedded market study [6] indicates that C usage still dominates embedded systems, being over twice as prevalent as C++. The binary size generated by C++ remains prohibitively large for tiny devices.
Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org.
CODAI'25, January 2025, Barcelona, Spain
- Device vendors’ commercial tools are highly fragmented, as they are optimized exclusively for their proprietary hardware. This approach limits user intervention in the deployment process and creates a strong dependency on specific backend devices.
© 2025 Copyright held by the owner/author(s). Publication rights licensed to ACM.
CODAI'25, January 2025, Barcelona, Spain
Liu et al.
-
Deployment tools offer limited support for domain-specific accelerators (DSAs), especially custom-built DSAs, restricting the flexibility required for specific applications.
-
Integrating new operators into the MLIR ecosystem involves significant overhead, including building dialects, patterns, abstraction lowering, etc.
-
Model weights are quantized to lower precision integers, but the associated overhead of floating-point based rescaling operations is often overlooked.
To address above limitations, we propose a lightweight C code generator designed to overcome existing challenges. Our tool accepts various trained model formats, applies optimization techniques like weight tuning and bias fusion, provides C function templates for customized DSAs, and generates human-readable C source code to enhance compatibility and transparency. This approach facilitates efficient model deployment across diverse edge devices while supporting both standard and specialized hardware configurations.
2 Implementation
Our C code generator, accessible via a Python interface, is designed for ease of use and follows two primary design principles.
Pure C Code Generation. The generator produces pure C code compatible with the vast majority of embedded systems, ensuring high compatibility even for non-commercial, research-oriented devices. The streamlined compiled binary size is especially suitable for memory-constrained tiny devices and custom-designed domain-specific accelerators.
Template Mechanism for backend Integration. By employing a template-based approach, the generator seamlessly maps model operators to C functions for the backend, enabling an end-to-end model parsing pipeline. The resulting code is both human-readable and editable, allowing for extensive customization in experimental deployments. A key advantage of the template method is that generation stops at source code, leaving the final compilation to be handled by the backend hardware's toolchain, thus minimizing potential compilation errors.
2.1 Overview
Our code generator employs a modular design, where each module functions similarly to the concept of a Pass in LLVM [11]. Multiple modules are sequentially stacked to form a pipeline that performs specific analyses and optimizations on each operator as the model flows through. Fig. 1 presents a structural overview of our code generator. The first two modules are dedicated to model optimization, while the DSA optimization module incorporates backend hardware specification to invoke DSA for specific operator acceleration. If no DSA is attached, this step can be skipped. The final generation module uses prepared templates to generate the main source code and saves model weights and activations in various formats.
2.2 Modules
The frontend module initially performs a forward pass on an input sample, such as an image, through the input model to cache intermediate activations for all hidden layers. Subsequently, the

Figure 1: Structure overview of the proposed code generator. Files coming from users are marked as yellow. Modules are marked as blue.
frontend module parses the input model file (currently supporting TFLite, with ONNX support under development) and extracts model information layer by layer, including weights and activations, which are converted into intermediate representations (IRs) stored in dictionary format. As the initial release, the current frontend supports key components of convolutional neural networks, e.g. conv2d, dense, flatten, and maxpool. Users are free to extend the parser to other operators. For quantized models, quantization parameters like scaling factors and zero points are also extracted. Additionally, operator attributes, such as convolutional kernel size and padding, are stored within the weight attributes for potential DSA configuration. An example of an IR extracted by the frontend module is displayed in Table 1.
Table 1: Layerwise IR extracted from the input model
| Layer Name | ||||
|---|---|---|---|---|
| Key | tensor | scale | zero_p | attribute |
| i (input) | ndarray | FP32 | FP32 | |
| w (weight) | ndarray | FP32 | FP32 | dict |
| b (bias) | ndarray | FP32 | FP32 | |
| o (output) | ndarray | FP32 | FP32 | |
We observe that quantized models require scaling factors (often represented as FP32 values) to adapt quantized values to the full precision range in order to maintain accuracy. This not only necessitates floating-point units (FPU) in the backend but also introduces additional memory write overhead for rescaling computations between two accelerated layers, leading to increased inference time. Furthermore, many AI accelerators focus primarily on optimizing low-level operations, such as General Matrix Multiplications (GEMM) and convolutions, while delegating corresponding bias addition to the CPU for execution.
To address these issues, we propose two ahead-of-time (AOT) optimizations, referred to as weight tuning and bias fusion, and integrate them into the IR optimization module. These optimizations eliminate CPU-based rescaling and bias addition, thereby improving the efficiency of quantized model inference. In principle, weight tuning can be applied to any quantized layer based on weighted sum operations, while bias fusion is applicable to layers with an enabled bias term. We detail this process targeting fully connected and 2D convolutional layers, whose single output is simply formulated as
A lightweight C Code Generator for Heterogeneous TinyML Systems
CODAI'25, January 2025, Barcelona, Spain
where w and b denote weights and bias, respectively. The relationship between pre- and post-quantization values in input or output is stated as
where indicates pre-quantized value, denotes post-quantized value, is the scaling factor, is the zero point. In case that symmetric quantization with applied, we have
then the quantized output from equation (1) can be represented by
(4)
If is the input to the following layer, a post-rescaling of the layer's quantized output by the factor is necessary, typically increasing additional CPU overhead. This overhead can be minimized by weight tuning, where the factor is reformulated to a tuned value with a right shift of N bits, as shown in
Bit-shifting is computationally cheap from hardware side. Some DSA [10] even directly supports right-shifted outputs. Meanwhile, can be merged with and , resulting in tuned weights and biases ( , ), transforming (4) into

(a) Fusion in fully-connected layer

(b) Fusion in convolutional layer
Figure 2: Illustration of bias fusion
Bias fusion further optimizes (6) by embedding bias addition into the weighted sum, as illustrated in Fig. 2. For fully connected layers, this involves filling the input matrix with additional columns of a constant and extending the weight matrix with additional rows of , where . For convolutional layers, the input feature map is padded with additional channels of , and the convolutional kernels are expanded with additional channels of . This optimization further yields
Thus, peripheral calculations such as bias addition and rescaling are merged into DSA-driven operators, requiring only constant fills for certain extended input buffers. Although weight tuning and bias fusion introduce some truncation errors during optimization, experiments show that the impact on model accuracy remains minimal.
The DSA optimization module adapts the IRs for the target DSA backend, with its operations highly dependent on the specific registered DSA. Initially, the module cross-references the IR details with backend specifications to verify compatibility, checking whether any operators exceed the hardware's support limits (e.g., feature map size constraints). Next, it conducts a dimension order check, as TFLite stores tensors in NHWC format (batch, height, width, channel), which may require conversion to NCHW format for certain DSAs. If the DSA requires a particular dimension ordering for weight storage, the weights are permuted accordingly at this stage as well. Memory alignment is subsequently verified. To maximize throughput, DSAs often fetch multiple values simultaneously, so width dimensions may require zero-padding to align with specific boundaries (e.g., 128-bit alignment). Finally, we employ a ping-pong buffer strategy to minimize allocated buffer memory, with a detailed example in section 3.1.
Once the IR preparation is complete, C source code generation begins. Users are required to prepare C function templates specific to the backend, including the main function and layer functions for various supported layer types. For instance, Fig. 3 depicts the code template of softmax layer for distinguishing the final class in a classifier. The code generator sequentially parses IRs and translates them into corresponding function calls that populate the main function. Formulated tensors, such as and in Equation (7), are archived in multiple formats within the output directory, including C headers, JSON, and binary memory formats. Users can specify the desired output formats via the output configuration settings.
void layer_{({layer_i})({IR[layer_i][i][t"tensor"].dtype})_t* d_in, int cls_num, uint8_t* cls_out){ //softmax is simplified by hardmax to select the class id as it is monotonically increasing. {{IR[layer_i][i][t"tensor"].dtype}}_t output_i = *d_in; *cls_out = 0; for(uint8_t i = 1; i < cls_num; i++) { if(d_in[i] > output_i){ *cls_out = i; output_i = d_in[i]; } } }
Figure 3: Code template for Softmax layer using jinja2 library
CODAI'25, January 2025, Barcelona, Spain
Liu et al.
3 Evaluation
To demonstrate how this code generator integrates seamlessly into a typical AI development workflow, we present a case study focused on a CNN-based radar target classification task. We detail the agile, codegen-based deployment on a custom radar DSP equipped with a machine learning accelerator capable of accelerating GEMMs and convolution operations. Our goal is to lower the barrier for future replication of this process and to encourage the development of new workflows for other backends.
3.1 Case Study
To classify objects in millimeter-wave radar images, we developed a compact CNN model named as RadarNet with only 9,704 parameters that achieves accuracy on a four-class task for car, cyclist, pedestrian, and noise. The model consists of convolutional layers, max-pooling layers, and fully connected layers, as shown in Fig. 4a. Prior to the code generation, the model is statically quantized to int8 using TFLite. To minimize memory usage for intermediate activations, we implemented a ping-pong buffer strategy, which alternates storage of each layer's output. Our code generator automatically calculates the buffer size based on the maximum tensor size collected for each buffer and reserves the corresponding memory regions in the generated code. For example, in Fig. 4b, buf_a is sized equal to act2, while buf_b fits act1 exactly.

(a) Structure overview

(b) Ping-pong buffer strategy
Figure 4: Illustration of RadarNet
The employed backend device is a custom low-power radar DSP [7] that includes 25 processing elements (PEs): a peripheral core and 24 signal processing cores. Each processing core encompasses an embedded RISC-V core, a Machine Learning Accelerator (MLA), and 128 kB of memory. The MLA integrates 64 multiply-accumulate (MAC) units, which are leveraged to accelerate integer-based GEMM and convolution operations. This MLA also supports bit-shifted outputs, allowing direct computation of in Equation (7).
In principle, once users prepare the required input files (as shown by yellow blocks in Fig. 1), they can generate the model's C source code with a single call of our code generator and then compile the code using the backend's default toolchain.

Figure 5: Overview of the adopted radar DSP as backend
3.2 Result
We compared three different code generation methods by deploying RadarNet on the aforementioned radar DSP, assessing hardware resources that do not pose bottlenecks for this model. The microTVM flow [12] was used as the baseline, as it relies solely on the RISC-V core for all computations without targeting any accelerator backend. In contrast, quantized convolutions (qnn.conv) were incorporated into the TVM flow through the Universal Modular Accelerator (UMA) interface [2]. We extended it to include quantized dense layers (qnn.dense) as the comparison object, enabling full acceleration of both the convolutional and fully connected layers within RadarNet. These two TVM-based counterparts adopt static memory planning for tensor management.
Table 2: Toolkit benchmark
| exec. time [us] | binary size [kB] | manual intervention | |
|---|---|---|---|
| microTVM [12] | 4571 | 39.3 | - |
| microTVM+UMA | 1470 | 31.2 | 278+81 |
| Our CodeGen | 630 | 25.0 | 677+211 |
The benchmarking results are presented in Table 2, showing single-inference time, compiled binary size, and the degree of manual intervention required for code generation. Compared to the baseline microTVM flow, integrating the MLA via the UMA interface reduces execution time and binary size to and of the original, respectively, while for our code generator, these figures are further reduced to and .
Comparing the last two rows, although both methods leverage the accelerator, our generator achieves more than double the speed of the microTVM+UMA approach. This performance gain is primarily due to two factors: first, while microTVM+UMA performs runtime dimension reordering (from NHWC to NCHW), our generator handles this conversion at compile time; second, whereas microTVM+UMA relies on the RISC-V core for rescaling after invoking the MLA, our generator completes this rescaling through compile-time weight tuning. Additionally, performing as many IR optimizations as possible at compile time minimizes binary size, enabling larger networks to fit on hardware with limited storage.
A lightweight C Code Generator for Heterogeneous TinyML Systems
CODAI'25, January 2025, Barcelona, Spain
In this use case, the code lines in frontend modules and backend templates represent amount of manual intervention. Since our code generator implements all required operators in RadarNet and applies additional IR optimizations, while UMA focuses solely on operators mapped to accelerators, our overall code size is more than twice as large. However, the required incremental code size to register new operators is comparable to that of the TVM approach.
3.3 Discussion
As the initial release of the code generator, we have implemented key operators commonly used in CNNs, including conv2d, dense, flatten, and maxpool, within the frontend module. To support models with additional operators, users should extend the Python API in the frontend module, enabling the recognition and extraction of new operators into IRs. For deploying models on new backends, users need to prepare a set of Jinja2 templates that define all operators used in the model and specify the unique characteristics of the new backend in the backend specification. Each individual set of templates is designed to fully exploit the specific hardware capabilities while ensuring isolation between different hardware backends. However, developing a comprehensive set of operator templates for a new backend requires a one-time effort.
From a methodological perspective, the compilation workflow of this code generator closely resembles that of TVM. Importantly, IR optimization techniques such as weight tuning and bias fusion, as employed in this work, are also applicable to the TVM compilation process. Nevertheless, the proposed code generator aims to provide a turnkey solution with minimal external dependencies and a lightweight executable runtime. In this regard, it takes an additional step beyond existing solutions.
4 Conclusion
In this work, we present a lightweight code generator that extracts IRs from a TFLite model and translates them into template-based C source code compatible with a backend chip. We demonstrate the complete workflow through a practical case study of radar target classification on a radar DSP in a real-world setting. Benchmarking against other state-of-the-art methods reveals that our generated code achieves the smallest executable size and lowest execution time. To adapt it to another backend, the only effort is to prepare a set of corresponding templates for required operators. We hope this approach can play a critical role in accelerating the deployment of machine learning models for heterogeneous backends. Moreover, as multi-core heterogeneous systems advance, we envision future research to focus on partitioning single operators into multiple tiles and mapping end-to-end workloads across multiple coupled cores and accelerators.
Acknowledgments
This work was funded by the German Federal Ministry of Education and Research (BMBF), funding reference 16ME0729K, joint project "EVENTS", and by the German Research Foundation (DFG, Deutsche Forschungsgemeinschaft) as part of Germany's Excellence Strategy – EXC 2050/1 – Project ID 390696704 – Cluster of Excellence "Centre for Tactile Internet with Human-in-the-Loop" (CeTI) of Technische Universität Dresden.
References
[1] Martín Abadi, Ashish Agarwal, Paul Barham, Eugene Brevdo, Zhifeng Chen, Craig Citro, Greg S. Corrado, Andy Davis, Jeffrey Dean, Matthieu Devin, Sanjay Ghemawat, Ian Goodfellow, Andrew Harp, Geoffrey Irving, Michael Isard, Yangqing Jia, Rafal Jozefowicz, Lukasz Kaiser, Manjunath Kudlur, Josh Levenberg, Dandelion Mané, Rajat Monga, Sherry Moore, Derek Murray, Chris Olah, Mike Schuster, Jonathon Shlens, Benoit Steiner, Ilya Sutskever, Kunal Talwar, Paul Tucker, Vincent Vanhoucke, Vijay Vasudevan, Fernanda Viégas, Oriol Vinyals, Pete Warden, Martin Wattenberg, Martin Wicke, Yuan Yu, and Xiaoqiang Zheng. 2015. TensorFlow: Large-Scale Machine Learning on Heterogeneous Systems. https://www.tensorflow.org/ Software available from tensorflow.org.
[2] Samira Ahmadifarsani, Rafael Stahl, Philipp van Kempen, Daniel Mueller-Gritschneder, and Ulf Schlichtmann. 2023. Towards Rapid Exploration of Heterogeneous TinyML Systems using Virtual Platforms and TVM's UMA. In Proceedings of the 2023 Workshop on Compilers, Deployment, and Tooling for Edge AI. 6–10.
[3] Tianqi Chen, Thierry Moreau, Ziheng Jiang, Lianmin Zheng, Eddie Yan, Haichen Shen, Meghan Cowan, Leyuan Wang, Yuwei Hu, Luis Ceze, et al. 2018. TVM: An automated End-to-End optimizing compiler for deep learning. In 13th USENIX Symposium on Operating Systems Design and Implementation (OSDI 18). 578–594.
[4] Robert David, Jared Duke, Advait Jain, Vijay Janapa Reddi, Nat Jeffries, Jian Li, Nick Kreeger, Ian Nappier, Meghna Natraj, Tiezhen Wang, et al. 2021. TensorFlow Lite Micro: Embedded Machine Learning for tinyML systems. Proceedings of Machine Learning and Systems 3 (2021), 800–811.
[5] Analog Devices. 2020. ADI MAX78000/MAX78002 Model Training and Synthesis. https://github.com/analogdevicesinc/ai8x-synthesis
[6] EETimes. 2019. Integrating IoT and Advanced Technology Designs, Application Development & Processing Environments. https://www.embedded.com/wp-content/uploads/2019/11/EETimes_Embedded_2019_Embedded_Markets_Study.pdf
[7] Hector A Gonzalez, Bernhard Vogginger, Chen Liu, Marco Stolba, Florian Kelber, Heiner Bauer, Stefan Hänzsche, Stefan Scholze, Marc Berthel, Tim Rosmeisl, et al. 2023. A 12-ADC 25-Core Smart MPSoC Using ABB in 22FDX for 77GHz MIMO Radars at 52.6 mW Average Power. In 2023 IEEE Custom Integrated Circuits Conference (CICC). IEEE, 1–2.
[8] Google. 2021. LiteRT overview. https://ai.google.dev/edge/litert
[9] Mohamed Amine Hamdi, Francesco Daghero, Giuseppe Maria Sarda, Josse Van Delm, Arne Symons, Luca Benini, Marian Verhelst, Daniele Jahier Pagliari, and Alessio Burrello. 2024. MATCH: Model-Aware TVM-based Compilation for Heterogeneous Edge Devices. arXiv preprint arXiv:2410.08855 (2024).
[10] Sebastian Höppner, Yexin Yan, Andreas Dixius, Stefan Scholze, Johannes Partzsch, Marco Stolba, Florian Kelber, Bernhard Vogginger, Felix Neumärker, Georg Ellguth, et al. 2021. The SpiNNaker 2 processing element architecture for hybrid digital neuromorphic computing. arXiv preprint arXiv:2103.08392 (2021).
[11] Chris Lattner and Vikram Adve. 2004. LLVM: A compilation framework for lifelong program analysis & transformation. In International symposium on code generation and optimization, 2004. CGO 2004. IEEE, 75–86.
[12] Chen Liu, Matthias Jobst, Liyuan Guo, Xinyue Shi, Johannes Partzsch, and Christian Mayr. 2023. Deploying machine learning models to ahead-of-time runtime on edge using microTVM. In Proceedings of the 2023 Workshop on Compilers, Deployment, and Tooling for Edge AI. 37–40.
[13] Hsin-I Cindy Liu, Marius Brehler, Mahesh Ravishankar, Nicolas Vasilache, Ben Vanik, and Stella Laurenzo. 2022. TinyIREE: An ML Execution Environment for Embedded Systems From Compilation to Deployment. IEEE Micro 42, 5 (2022), 9–16. https://doi.org/10.1109/MM.2022.3178068
[14] Meta. 2023. Github repository of ExecuTorch. https://github.com/pytorch/executorch
[15] NXP. 2022. elQ Toolkit. https://www.nxp.com/design/design-center/training/TIP-ML-AND-AI-SERIES-EIQ-TOOLKIT
[16] Adam Paszke, Sam Gross, Francisco Massa, Adam Lerer, James Bradbury, Gregory Chanan, Trevor Killeen, Zeming Lin, Natalia Gimelshein, Luca Antiga, et al. 2019. Pytorch: An imperative style, high-performance deep learning library. Advances in neural information processing systems 32 (2019).
[17] Christian Pilato, Stanislav Bohm, Fabien Brocheton, Jeronimo Castrillon, Riccardo Cevasco, Vojtech Cima, Radim Cmar, Dionysios Diamantopoulos, Fabrizio Ferrandi, Jan Martinovic, et al. 2021. EVEREST: A design environment for extreme-scale big data analytics on heterogeneous platforms. In 2021 Design, Automation & Test in Europe Conference & Exhibition (DATE). IEEE, 1320–1325.
[18] Stephanie Soldavini, Felix Suchert, Serena Curzel, Michele Fiorito, Karl Friebel, Fabrizio Ferrandi, Radim Cmar, Jeronimo Castrillon, and Christian Pilato. 2024. Etna: MLIR-Based System-Level Design and Optimization for Transparent Application Execution on CPU-FPGA Nodes. In 2024 IEEE 32nd Annual International Symposium on Field-Programmable Custom Computing Machines (FCCM). 224–224. https://doi.org/10.1109/FCCM60383.2024.00012
[19] STMicroelectronics. 2022. STM32Cube.AI (X-CUBE-AI v9.0). https://stm32ai.st.com/stm32-cube-ai/