<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Milan Cugurovic on Medium]]></title>
        <description><![CDATA[Stories by Milan Cugurovic on Medium]]></description>
        <link>https://medium.com/@milancugurovic?source=rss-2875ed618c11------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H8vvGGA8maOlTRAHrEIV3Q.jpeg</url>
            <title>Stories by Milan Cugurovic on Medium</title>
            <link>https://medium.com/@milancugurovic?source=rss-2875ed618c11------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:07:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milancugurovic/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Machine Learning-Driven Static Profiling for Native Image]]></title>
            <link>https://medium.com/graalvm/machine-learning-driven-static-profiling-for-native-image-d7fc13bb04e2?source=rss-2875ed618c11------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7fc13bb04e2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graalvm-native-image]]></category>
            <category><![CDATA[graalvm]]></category>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Milan Cugurovic]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 14:04:57 GMT</pubDate>
            <atom:updated>2024-12-11T14:04:57.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Egin3Ob4tcfkRZ-ZyhFLBw.png" /></figure><p><a href="https://en.wikipedia.org/wiki/Machine_learning">Machine learning</a> (ML) enables the training of models that, based on the characteristics of a program, can accurately predict its execution. In this blog we will explain how we used ML to develop the static profiler GraalSP (a static profiler that predicts profiles in Native Image), integrated it into <a href="https://www.graalvm.org/latest/reference-manual/native-image/">Oracle GraalVM Native Image</a>, and achieved a 7.5% improvement in runtime performance!</p><p>In the first part of this blog, we describe static profilers and compare them to their dynamic counterparts, which we covered in <a href="https://medium.com/graalvm/profile-guided-optimization-for-native-image-f015f853f9a8">a previous blog</a>. In that blog we discussed program profiles and how they “guide” optimizations. Using a sorting example we will delve into the design and development of GraalSP. At the end we’ll also present the results of integrating ML into Native Image and discuss the deployment of the ML models into production.</p><h3>Dynamic and Static Profilers</h3><p>In AOT compilation, dynamic profilers work by building an instrumented image, collecting profiles, and then building an optimized image. They collect high-quality profiles but also have a few drawbacks. First, they complicate the optimization process by requiring two builds and a profile-collection run. This process is usually time and memory consuming, placing an extra burden on programmers and the machines used for optimization. Also, finding appropriate workloads for profile collection can be challenging.</p><p>Fortunately, there is a much cheaper alternative where there’s no need to go through the run-build-run compilation cycle or hunt for suitable inputs for profile collection. It’s called “static profiling” or “static profile prediction”. A static profiler is a profiler that doesn’t collect a profile during program execution — instead, it predicts a program’s profile. A state-of-the-art static profiler takes advantage of a machine learning model to predict a profile based on a set of static features that characterize a program.</p><p>Figure 1 illustrates the pipeline of a Profile-Guided Optimization (PGO) build driven by a static profiler relying on an ML model. A static profiler extracts features (we will get back to them later!) that characterize a program and then perform ML model inference to predict a profile. This predicted profile is then used just like one obtained by dynamic profiling: the compiler utilizes the information about program “execution” to create an optimized executable. This way, an ML model enables the compiler to utilize a profile without needing to run the program, reducing the usability burden and the challenge of finding suitable workloads for profile collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*ii04P0ei3Zp_jv2fTTqvxg.png" /><figcaption>Figure 1: Pipeline of a PGO build driven by an ML-based static profiler.</figcaption></figure><h3>Introducing the Graal IR</h3><p>It is important to note that a static profiler does not operate on a program’s source code but use the <a href="https://en.wikipedia.org/wiki/Intermediate_representation">compiler’s intermediate representation (IR) </a>instead. A compiler translates a program’s source code into IR, a form that is more manageable and suitable for various optimizations, such as eliminating redundant code and duplicating frequent loops.</p><p>In this context, Native Image uses <a href="https://ssw.jku.at/General/Staff/GD/APPLC-2013-paper_12.pdf">Graal Intermediate Representation (Graal IR)</a> to represent a program as a graph. Graal IR is a high-level IR that captures a program’s structure and includes additional information that enables the compiler to perform advanced analyses and optimizations, leading to better-optimized programs.</p><p>Graal IR represents a program as a graph consisting of nodes that correspond to the control flow and nodes that correspond to the data flow in the program. For example, consider the simple <em>for</em> loop. Graal IR translates the <em>for</em> loop into the IR graph shown below (Figure 2), with control flow edges colored red and data flow edges colored blue. The condition <em>i &lt; n</em> is parsed into an <em>IF</em> node that evaluates the value of the counter <em>i</em>. The loop body corresponds to the <em>true</em> branch of the <em>IF</em> control split node in the IR. Therefore, executing the loop body corresponds to executing the <em>true</em> branch of the corresponding <em>IF</em> node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*sWoqND-nr20QN_wo6yyg_Q.png" /><figcaption>Figure 2: Graal IR graph corresponding to a simple <strong><em>for</em></strong> loop.</figcaption></figure><p>You can learn more about Graal IR in <a href="https://medium.com/graalvm/under-the-hood-of-graalvm-jit-optimizations-d6e931394797">one of our previous blog posts</a> and in the paper <a href="https://ssw.jku.at/General/Staff/GD/APPLC-2013-paper_12.pdf">Graal IR: An Extensible Declarative Intermediate Representation</a>.</p><h3>GraalSP: The Static Profiler for Native Image</h3><p>Now that we are familiar with the pipeline of static profilers and Graal IR, let’s discuss the ML in Native Image. We developed <em>GraalSP</em>: a precise, highly efficient, lightweight, polyglot, and robust static profiler as a part of the Native Image tool. Let’s delve into GraalSP using an example — we’ll use the heap sort function to demonstrate how (static) profiling can help us improve performance.</p><h4>Running Example: Heap Sort</h4><p>In the code block below we show the source code of the <em>heapSort</em> function from the Java Development Kit (JDK). This sorting implementation uses the <em>pushDown</em> method to push elements down the heap.</p><pre>/**<br>* Sorts the specified range of the array using heap sort.<br>*<br>* @param a the array to be sorted<br>* @param low the index of the first element, inclusive, to be sorted<br>* @param high the index of the last element, exclusive, to be sorted<br>*/<br>private static void heapSort(int[] a, int low, int high) {<br>   for (int k = (low + high) &gt;&gt;&gt; 1; k &gt; low; ) {<br>       pushDown(a, --k, a[k], low, high);<br>   }<br>   while (--high &gt; low) {<br>       int max = a[low];<br>       pushDown(a, low, a[high], low, high);<br>       a[high] = max;<br>   }<br>}</pre><h4>Impact of the Program Profiles on Performance</h4><p><a href="https://en.wikipedia.org/wiki/Inline_expansion">Function inlining optimization</a> determines whether to inline function calls based on the probability of executing loop bodies in <em>for</em> and <em>while</em> loops. More precisely, function inlining is a very complex optimization, and decisions about inlining a <em>pushDown</em> invocation aren’t made solely based on the probabilities of loop body execution. However, these probabilities play a significant role in determining whether or not to inline calls. Therefore, optimization of the <em>heapSort</em> function highly depends on program profiles that contain information about the execution probabilities of the <em>for</em> and <em>while</em> loops.</p><p>Consider sorting an array of 10 million integer values using the <em>heapSort</em> function from the JDK. Function inlining optimization can inline calls to the <em>pushDown</em> method, reducing the overhead of function calls during the sorting process. When the <em>pushDown</em> method calls are inlined, the average sorting time is 1.80 seconds. Conversely, if these calls are not inlined, the average sorting time increases to 2.18 seconds. As inlining calls to the <em>pushDown</em> method can speed up program execution by more than 20%, the execution probabilities of the loop bodies are very important.</p><h4>Goal: Accurately Predict Program Profiles</h4><p>Our goal is to predict the execution probabilities of the bodies of the <em>for</em> and <em>while</em> loop. Let’s focus on, for example, <em>for</em> loop. Predicting the probability of executing the loop body translates to predicting the probability of executing the <em>true</em> branch of the corresponding <em>IF</em> node in the Graal IR; so our goal is to predict the execution probability of the <em>true</em> branch of the<em> IF</em> node corresponding to the <em>for</em> loop. To do so, first, we need to take a look at the Graal IR and “define” branches of the <em>IF</em> node.</p><h4>ML Features that Characterize Code</h4><p>In Figure 3, we illustrate the <em>IF</em> node in the Graal IR that corresponds to the <em>for</em> loop (named <em>“1. If”</em>), along with its <em>true</em> and <em>false</em> branches defined by the blocks of a <a href="https://en.wikipedia.org/wiki/Control-flow_graph">control flow graph</a> (CFG).</p><p>If you’re wondering about the CFG, it’s essentially composed of blocks, where each block contains nodes from the IR graph. The CFG consolidates both control flow and data flow from the Graal IR, providing a clear representation of the program’s execution order and enhancing comprehension of its flow. Therefore, we utilized the CFG to characterize the branches of <em>IF</em> statements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yb1e8qOFR_nIsYnQ3f_XxQ.png" /><figcaption>Figure 3: IF node that corresponds to the for and loop of the heapSort function.</figcaption></figure><p>We “define” branches of the <em>IF</em> node in terms of the nodes in the Graal IR and blocks of the CFG built on top of the Graal IR. The <em>true</em> branch of the <em>“1. If” </em>node consists of blocks <em>B2-B8</em>, while the <em>false</em> branch consists of blocks <em>B9-B24</em>. Once we define blocks corresponding to the branches of the <em>IF</em> node, to fully characterize the<em> IF</em> node we also extract features from the CFG block that hosts the <em>IF</em> node (block <em>B1</em> in our example) as well as blocks that point to that block in the CFG (block <em>B0</em>).</p><p>The features we extract include, for example, the estimated assembly size of a branch, the estimated number of CPU cycles the computer will perform to execute instructions from the branch, and the nesting loop depth of an <em>IF</em> node. <a href="https://www.laphamsquarterly.org/miscellany/fermats-last-margin-note">The margin of this blog is too narrow</a> to discuss all the features. For those interested in more details, our paper <a href="https://www.sciencedirect.com/science/article/abs/pii/S0164121224001031"><em>GraalSP: Polyglot, efficient, and robust machine learning-based static profiler</em></a><em> </em>provides more details. Here, it is important to note that the feature characterizing the <em>IF</em> node, for which we aim to predict the probability of executing its <em>true</em> branch, is represented by a vector of floating point numbers.</p><h4>Machine Learning for Profile Prediction</h4><p>After extracting the feature vector, we use <a href="https://en.wikipedia.org/wiki/Supervised_learning">supervised learning techniques</a> to train the ML model to predict profiles. We use <a href="https://medium.com/@iuyasik/introduction-to-ensemble-models-and-xgboost-9b13948a42a7">the XGBoost ensemble</a> of decision tree (DT) models for regression to predict profiles.</p><p>A DT model uses a tree-like structure consisting of nodes, branches, and leaves to model the data. Each node evaluates a feature and directs decisions down the tree, while leaf nodes predict profiles. On the left side of Figure 4, we illustrate a shallow DT model that predicts the branch execution probability of a <em>true</em> branch based on the loop depth of an <em>IF</em> node, as well as the assembly size and number of CPU cycles of a branch. For example, if an <em>IF</em> node is at a depth of two or more and the estimated CPU cycles for a <em>true</em> branch are less than five, the DT model predicts the execution probability of that branch to be 0.15. The main benefits of DTs are their interpretability, speed, and ease of use.</p><p>To improve prediction performance, reduce overfitting, and increase accuracy, we utilize the XGBoost ensemble, combining DTs as weak learners. On the right side of Figure 4, we illustrate an ensemble consisting of 1,500 decision trees. Each tree in the ensemble predicts the execution probability for a target branch, and the ensemble aggregates all predictions (for example, by averaging them) to determine the outcome.</p><p>Usage of the ensembles enables us to achieve <strong>precise</strong> predictions, while usage of the decision trees enables us to achieve a<strong> highly efficient </strong>static profiler. Also, by using <strong>lightweight</strong> decision trees, we end up with a small model of only ~250 kilobytes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*X6V1PrBaW8B25aOg" /><figcaption>Figure 4: DT and XGBoost ML models.</figcaption></figure><p>By defining the static profiler on top of the IR of the Graal compiler, we’ve created a <strong>polyglot</strong> static profiler capable of predicting profiles for all programs compiled to Java bytecode (for example, Java, Scala, and so on!).</p><p>Furthermore, we designed and developed two profile prediction heuristics that handle scenarios where input data deviates from the real-world Java and Scala programs. Of course, these heuristics can’t predict profiles better than ML models, but they can help prevent the model from making mistakes. For instance, one of the heuristics ensures that the probability of executing the body of a loop is not less than 0.2. This way, the ML model won’t make cardinal mistakes on frequent loops. By slightly increasing the binary size of the generated programs, these heuristics have enabled us to create a <strong>robust</strong> static profiler that effectively handles outliers.</p><p>The impact of a static profiler on program performance can vary depending on the program’s code. To evaluate the impact, we use programs from test suites <a href="https://github.com/renaissance-benchmarks/renaissance">Renaissance</a>, <a href="https://www.dacapobench.org/">DaCapo</a>, and <a href="https://dl.acm.org/doi/10.1145/2048066.2048118">DaCapo con Scala</a>. We integrated GraalSP into Native Image and achieved a <strong>7.46% speedup</strong> in execution time (geometric mean) compared to the default configuration. The default image build assumes a uniform distribution of execution probabilities over the branches of a control split. Figure 5 reports the geomean speedup of programs aggregated according to the test suite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*P2y3OCzpBesevHOL" /><figcaption>Figure 5: Runtime speedup of GraalSP across the test suites Renaissance, DaCapo, and DaCapo con Scala.</figcaption></figure><p>Runtime improvement comes at the cost of an average increase in the size of generated programs of only 3.9%. The increased size of generated binary files results from <a href="https://epub.jku.at/download/pdf/4410434.pdf">duplication-based compiler optimizations</a>. The static profiler generates profiles for the entire codebase, even though usually only a small section of the code is executed. Duplication-based optimizations duplicate code even in sections that won’t be executed, thus slightly increasing the size of the compiled programs.</p><p>It is important to emphasize that the performance of programs optimized using PGO with dynamically collected profiles is much higher than those optimized using profiles predicted by GraalSP. In our experiments, <strong>PGO with dynamically collected profiles produces programs that are 33% faster and 15% smaller</strong>. As expected, the quality of the dynamically collected profiles is superior because they lack the inherent errors found in ML models. Additionally, dynamically collected profiles include information that GraalSP currently does not predict: method call profiles, reached types in virtual calls, details about monitor locking and unlocking, and so on. Of course, as there is no such thing as a free lunch, these performance improvements comes with the hurdles of dynamic profiling.</p><h3>Model Inference: Deployment to Production</h3><p>Since the releases of GraalVM for JDK 17 and GraalVM for JDK 20 (version 23.0), GraalSP has been <strong>enabled by default in Oracle GraalVM</strong>! During the default build, you’ll find out that Native Image optimizes your program using PGO with <em>ML-inferred</em> profiles. Figure 6 illustrates the integration of GraalSP and dynamic profiling in Native Image. When users enable dynamic profiling, Native Image instruments the code and runs the instrumented executable to collect profiles. Otherwise, if users do not enable the dynamic profiler, Native Image will run the GraalSP to predict profiles and optimize programs based on the predicted values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*8fWpygwoxA_5pYY2" /><figcaption>Figure 6: Integration of the GraalSP and dynamic profiler in the Native Image.</figcaption></figure><p>GraalSP uses <a href="https://onnxruntime.ai/docs/get-started/with-java.html">the ONNX Java Runtime</a>, developed by Microsoft for cross-platform accelerated ML. This ensures compatibility with various architectures, including Windows amd64, Linux amd64 and aarch64, and Darwin amd64 and aarch64, providing flexibility and usability of GraalSP across different platforms. Also, by using the ONNX runtime, we implemented static profiling with a compilation time overhead of only 10%.</p><h3>Conclusion</h3><p>To summarize, GraalSP is enabled by default in Oracle GraalVM Native Image and offers the benefits of PGO without requiring profile collection. GraalSP characterizes programs in terms of Graal IR and uses the XGBoost ensemble to predict profiles. Native Image then uses these predicted profiles to perform PGO and create optimized programs. This represents the first successful application of ML in Oracle GraalVM. However, at Oracle Labs, we are preparing some exciting updates, improvements, and ML novelties to be announced very soon. Stay tuned!</p><p>For more details about the ML magic inside Oracle GraalVM, please refer to our paper <a href="https://www.sciencedirect.com/science/article/abs/pii/S0164121224001031"><em>GraalSP: Polyglot, efficient, and robust machine learning-based static profiler</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7fc13bb04e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/graalvm/machine-learning-driven-static-profiling-for-native-image-d7fc13bb04e2">Machine Learning-Driven Static Profiling for Native Image</a> was originally published in <a href="https://medium.com/graalvm">graalvm</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>