Mastering Sparse CUDA Generation through Pretrained Models and Deep Reinforcement Learning
Yaoyu Wang, Hankun Dai, Zhidong Yang, Junmin Xiao, Guangming Tan
International Conference on Learning Representations 2026 · Oral
Overview
The talk "Mastering Sparse CUDA Generation through Pretrained Models and Deep Reinforcement Learning" introduces Sparse RL, a novel framework designed to bridge a critical and persistent gap between the capabilities of large language models (LLMs) in code generation and the stringent demands of hardware-aware high-performance computing (HPC). Presented by Yaoyu Wang and his colleagues, this work tackles the challenge of generating not just syntactically correct code, but code that is profoundly optimized for specific hardware architectures, particularly for sparse computing tasks. Current LLMs, while adept at producing logically sound code, often treat code as mere text, failing to grasp the intricate interplay between data structures, memory hierarchies, and execution latency that is paramount in HPC.

Key moments
- 0:00 Introduction to Sparse RL and hardware-aware code generation
- 0:25 Fundamental gap: LLMs focus on correctness, HPC needs speed
- 2:45 SpMV: The 'boss fight' for dynamic sparse code generation
- 4:00 Sparse RL's solution: matrix structure as modality, 14x speedup
- 5:20 Innovation: Sinusoidal embeddings for sparse matrix geometry
- 6:00 Innovation: Three-stage training pipeline for Sparse RL
- 7:00 Innovation: Hierarchical reward function for speed and correctness
- 8:00 Experimental setup and strong baselines for evaluation
Mastering Sparse CUDA Generation through Pretrained Models and Deep Reinforcement Learning
Speakers: Yaoyu Wang, Hankun Dai, Zhidong Yang, Junmin Xiao, Guangming Tan
Conference: ICLR 2026
YouTube: https://slideslive.com/39062205
Overview
The talk "Mastering Sparse CUDA Generation through Pretrained Models and Deep Reinforcement Learning" introduces Sparse RL, a novel framework designed to bridge a critical and persistent gap between the capabilities of large language models (LLMs) in code generation and the stringent demands of hardware-aware high-performance computing (HPC). Presented by Yaoyu Wang and his colleagues, this work tackles the challenge of generating not just syntactically correct code, but code that is profoundly optimized for specific hardware architectures, particularly for sparse computing tasks. Current LLMs, while adept at producing logically sound code, often treat code as mere text, failing to grasp the intricate interplay between data structures, memory hierarchies, and execution latency that is paramount in HPC.
Sparse RL addresses this limitation by integrating pretrained models with deep reinforcement learning (DRL), enabling an AI system to learn and adapt its code generation strategy based on real-world execution feedback. The framework’s significance lies in its ability to dynamically optimize code for irregular data patterns inherent in sparse matrices, a problem that has historically resisted general solutions and relied heavily on decades of manual, pattern-specific optimizations. By focusing on execution latency as the primary optimization target, Sparse RL pushes the boundaries of AI-driven code generation, offering a pathway to significantly enhance the efficiency and scalability of sparse computing operations vital for modern AI and scientific workloads.
The implications of this research are far-reaching. As AI models become larger and more complex, sparse computations—such as those found in sparse weight pruning, Mixture-of-Experts (MoE) architectures, and sparse attention mechanisms—are becoming indispensable for managing model size, scaling capacity, and reducing computational costs. Sparse RL's ability to automatically generate highly optimized CUDA kernels for these irregular sparse operations promises to accelerate the development and deployment of next-generation AI systems, reducing the burden on human experts and unlocking new levels of performance on specialized hardware like GPUs.
Background
▶ Watch: Introduction to Sparse RL and hardware-aware code generation (0:00)
The landscape of code generation has been dramatically reshaped by the advent of large language models such as Code Llama and GPT-4. These models have demonstrated remarkable proficiency in generating syntactically correct and logically sound code, often measured by metrics like Pass@k, which assesses the percentage of generated solutions that pass unit tests. However, as the talk elucidates, this paradigm falls critically short when confronted with the demands of High-Performance Computing (HPC). In HPC, logical correctness is merely the foundational requirement; the ultimate objective is achieving minimal execution latency and maximal throughput. This necessitates code that is acutely "hardware-aware," capable of intelligently managing thread allocation, memory hierarchies (e.g., shared memory, L1/L2 cache), and instruction-level parallelism to minimize stalls and maximize computational efficiency.
The core problem stems from the fact that standard LLMs treat code primarily as text. Their generative process involves predicting the next token in a sequence, a methodology that inherently overlooks the geometric structure of data and the underlying hardware dynamics. This textual approach leads to code that, while valid, is often suboptimal or even catastrophically slow for HPC applications. A prime example of this disconnect is seen in sparse computing, a domain critical for efficient, scalable AI models. Sparse matrices, which contain a high proportion of zero elements, are ubiquitous in areas like sparse weight pruning (reducing model size without accuracy loss), sparse Mixture-of-Experts (MoE) models (scaling capacity by activating partial experts), and sparse attention mechanisms (fixing long context costs).
Unlike dense matrix operations, which feature predictable memory access patterns and lend themselves well to static compiler optimizations, sparse matrices present an irregular pattern. Their non-zero elements are scattered unpredictably, leading to dynamic and often imbalanced memory access patterns. This irregularity makes static optimization exceedingly difficult, as the optimal code strategy can change drastically based on the specific input data structure—a diagonal matrix versus a clustered one, for instance. For decades, optimizing sparse computing has relied on highly specialized, manual efforts, resulting in hundreds of pattern-specific kernel variants with no general, adaptive solution. This labor-intensive and expert-dependent optimization process represents a significant bottleneck in advancing sparse AI and scientific computing.
The talk highlights sparse matrix-vector multiplication (SpMV) as a "boss fight" for code generation due to its inherent challenges. SpMV is a fundamental operation in many scientific simulations, graph algorithms, and machine learning models. Its performance is highly sensitive to the sparse matrix's structure. A static code solution, generated without real-time awareness of the input matrix's sparsity pattern, cannot achieve optimal performance. The critical need, therefore, is for a dynamic adaptation mechanism that can generate high-performance code on-the-fly, tailored to the specific characteristics of the input data. This long-standing gap in general-purpose sparse acceleration is the primary motivation behind the Sparse RL framework, aiming to imbue AI code generation with the hardware-awareness and dynamic adaptability required for true HPC optimization.
Key Findings
▶ Watch: SpMV: The 'boss fight' for dynamic sparse code generation (2:45)
The Sparse RL framework demonstrates groundbreaking capabilities in generating high-performance CUDA code for sparse matrix operations, significantly outperforming existing state-of-the-art methods. The central key finding is its ability to generate faster solution programs for dynamic input at runtime, a challenge that has historically plagued sparse computing optimizations.
Specifically, the experimental results show that Sparse RL:
- Outperforms NVIDIA's vendor-optimized library cuSPARSE by an impressive factor of 14x. This is a monumental achievement, as cuSPARSE is the industry standard, highly optimized, and hand-tuned library for sparse operations on NVIDIA GPUs. Beating it by such a wide margin underscores the effectiveness of Sparse RL's learning-based, hardware-aware approach.
- Beats state-of-the-art LLM-based code generation techniques, such as CodeRL, by a factor of 30x. This highlights the critical distinction between generating logically correct code (where LLMs excel) and generating high-performance code that accounts for hardware realities (where Sparse RL makes its mark). The dramatic speedup against CodeRL validates Sparse RL's strategy of treating matrix structure as a distinct modality and optimizing for execution speed directly through reinforcement learning.
- Successfully addresses the data irregularity challenges in sparse computing. By dynamically adapting its code generation strategy based on the input matrix's sparsity pattern, Sparse RL overcomes load imbalances and inefficient memory access, which are fatal for performance in conventional LLM-generated code.
- Introduces a robust and generalizable approach to sparse code optimization. Unlike previous manual, pattern-specific optimizations, Sparse RL offers a framework that learns to optimize across a wide range of sparse matrix patterns, moving towards a general solution for a long-standing HPC problem.
These findings collectively establish Sparse RL as a significant advancement in the field of AI-driven code generation, particularly for the demanding domain of high-performance sparse computing.
Technical Deep Dive
▶ Watch: Innovation: Sinusoidal embeddings for sparse matrix geometry (5:20)
Sparse RL's technical prowess stems from three core innovations that collectively enable it to generate highly optimized CUDA code for dynamic sparse inputs: a novel workflow integrating LLMs with an execution-feedback loop, the introduction of sinusoidal embeddings to represent sparse matrix structure, and a rigorous three-stage training pipeline complemented by a hierarchical reward function.
Workflow: LLM as Actor in a Reinforcement Learning Loop
At the heart of Sparse RL is a sophisticated workflow that treats a pretrained large language model (LLM) as a stochastic policy or "actor." This actor's role is to take a sparse matrix as input and generate a sequence of CUDA code tokens, representing a potential solution program. The generated code is then fed into an "environment," which comprises a compiler and an executor. This environment's critical function is to build and run the generated CUDA code on actual GPU hardware.
Upon execution, the environment provides crucial feedback to the LLM in the form of a "state" (e.g., execution logs, compilation errors) and a "reward." The reward signal is meticulously designed to reflect two primary criteria: correctness (does the code produce the right mathematical result?) and, crucially, execution time (how fast does it run on the GPU?). This creates a closed-loop feedback system where the LLM continually learns and refines its code generation strategy, directly optimizing for the hardware environment. By observing the real-world performance of its generated code, the model moves beyond mere textual correctness to embrace hardware-aware optimization.
Innovation 1: Sinusoidal Embeddings for Geometric Awareness
One of the fundamental limitations of standard LLMs is their inability to "see" or understand the geometric structure of data. They process indices as raw numbers or text tokens, losing critical information about spatial relationships. Sparse RL addresses this by treating matrix structure as a distinct modality and introducing sinusoidal embeddings to encode the row and column indices of sparse matrices. This technique, adapted from its famous application in Transformers for positional encoding, maps discrete indices into a continuous wave space.
This approach offers two significant benefits:
- Scale Invariance: Sinusoidal embeddings can gracefully handle matrices with millions of rows and columns without encountering numerical instability. Unlike simple integer embeddings, which might struggle with very large index values, the wave-like representation provides a stable and consistent encoding across different scales.
- Locality Awareness: Crucially, these embeddings capture relative positions, enabling the model to distinguish between different sparsity patterns, such as dense diagonal blocks versus scattered clusters of non-zero elements. Understanding these geometric relationships is vital because they directly dictate optimal memory access strategies (e.g., coalesced memory access for contiguous blocks, or specific cache-aware access patterns for scattered data). By providing this geometric context, the LLM can generate code that intelligently manages memory hierarchies and thread layouts, leading to significantly better performance. The model no longer predicts tokens in a vacuum but with an understanding of the underlying data's spatial arrangement.
Innovation 2: Three-Stage Training Pipeline
To achieve mastery in such a challenging domain, Sparse RL employs a rigorous three-stage training pipeline:
- Pretraining on CUDA Corpus: In the initial stage, the base language model is pretrained on a massive corpus of CUDA code. This foundational step is crucial for equipping the model with a deep understanding of valid CUDA syntax, parallel programming concepts (e.g., threads, blocks, warps), kernel structures, and common optimization patterns. This ensures the model's generated code is syntactically correct and adheres to parallel programming paradigms.
- Supervised Fine-tuning (SFT) on Sparse Matrix Mapping: Following pretraining, the model undergoes supervised fine-tuning. In this stage, it is trained to map specific sparse matrix structures (represented by the sinusoidal embeddings) to known high-performance CUDA code. This involves providing pairs of sparse matrix representations and their corresponding optimal (or near-optimal) hand-tuned CUDA kernels. The SFT phase teaches the model the initial mapping between data geometry and efficient code structures, leveraging existing human expertise.
- Reinforcement Learning (RL) with Proximal Policy Optimization (PPO): The final and most critical stage involves Reinforcement Learning using the Proximal Policy Optimization (PPO) algorithm. While SFT can teach the model what good code looks like, it cannot provide feedback on how fast that code actually runs on a GPU. This is where RL becomes indispensable. The PPO loop refines the model's policy (its code generation strategy) by directly optimizing for execution speed. The LLM generates code, the environment executes it, and the observed execution time (and correctness) informs the reward signal. PPO then uses this reward to update the model's parameters, pushing it towards generating code that achieves minimal latency. This iterative feedback loop allows the model to discover novel optimizations and adapt to subtle hardware characteristics that are difficult to encode explicitly.
Innovation 3: Hierarchical Reward Function
Stabilizing DRL training in complex environments like code generation is notoriously difficult. Sparse RL addresses this with a meticulously designed hierarchical reward function, which guides the learning process in a structured manner:
- Compilation Reward: The most basic requirement is that the generated code must compile successfully. The system assigns a significant positive reward (e.g., +15 points) for successful compilation and a penalty (e.g., -15 points) for compilation failures. This ensures the model first learns to produce syntactically valid and compilable CUDA kernels.
- Correctness Reward: Once the code compiles, the next hierarchical level focuses on mathematical correctness. The model receives a substantial positive reward if the generated kernel produces the correct output for the given sparse matrix-vector multiplication. Incorrect mathematical results incur a severe penalty, guiding the model towards functionally accurate code.
- Efficiency Reward: The pinnacle of the reward hierarchy is efficiency. Once correctness is established, the reward function primarily focuses on execution speed. The model is rewarded based on the speedup achieved against a predefined baseline (e.g., a simple baseline kernel or a cuSPARSE implementation). Higher speedups yield greater rewards, directly incentivizing the model to discover performance optimizations.
- Penalty for Resource Contention: To prevent common pitfalls in GPU programming, such as excessive resource usage, the reward function also includes penalties. Specifically, it penalizes excessive shared memory usage. Over-utilizing shared memory can lead to resource contention, reduced occupancy (the number of active warps on a Streaming Multiprocessor), and ultimately, lower overall performance. This penalty guides the model towards resource-efficient code generation, balancing speed with optimal hardware utilization.
By combining these technical innovations, Sparse RL constructs a powerful framework that not only understands the nuances of parallel programming and sparse data structures but also learns to dynamically generate highly optimized CUDA kernels tailored for specific hardware, effectively bridging the gap between general-purpose LLMs and high-performance computing.
Experimental Setup & Results
▶ Watch: Innovation: Three-stage training pipeline for Sparse RL (6:00)
The experimental validation of Sparse RL was conducted on industry-standard NVIDIA GPUs, providing a robust platform for benchmarking its performance against established baselines.
Hardware:
The experiments were performed on NVIDIA V100 and A100 GPUs. These GPUs represent high-performance computing workhorses, with the A100 being a more recent and powerful architecture, allowing for a comprehensive evaluation across different generations of NVIDIA's Tensor Core GPUs.
Datasets:
To ensure broad applicability and generalization, Sparse RL was tested using a diverse collection of sparse matrices. The dataset comprised 1100 matrices drawn from two prominent sources:
- The SuiteSparse Matrix Collection: A widely used repository of sparse matrices from various scientific and engineering domains, representing a vast array of sparsity patterns and sizes.
- The Deep Learning Matrix Collection: This collection likely includes matrices derived from sparse neural network operations, such as those found in sparse weight pruning or MoE layers, making the evaluation particularly relevant to modern AI workloads.
Baselines:
Sparse RL's performance was rigorously compared against several strong baselines, encompassing both traditional and AI-driven optimization approaches:
- State-of-the-art LLMs:
- CodeRL: A prominent LLM-based code generation framework that leverages reinforcement learning for code optimization.
- PPO-Coder: Another advanced LLM-based system that likely employs Proximal Policy Optimization for improving generated code.
- Vendor-optimized library:
- cuSPARSE: NVIDIA's highly optimized, proprietary library for sparse matrix operations. This serves as a critical baseline, representing the pinnacle of human-engineered, vendor-specific performance.
- Auto-tuners:
- TVM-S: Likely a variant or integration with Apache TVM, an open-source deep learning compiler stack that can automatically optimize computation graphs for various hardware backends. Auto-tuners like TVM-S explore different code transformations and configurations to find high-performance kernels.
Headline Results:
The results unequivocally demonstrated Sparse RL's superior performance:
- 14x speedup over NVIDIA's cuSPARSE library: This is a remarkable achievement, as cuSPARSE is the de facto standard for sparse operations on NVIDIA hardware and is the result of decades of expert optimization. Sparse RL's ability to significantly outpace it highlights the power of its adaptive, learning-based approach.
- 30x speedup over state-of-the-art LLM code generation (CodeRL): This dramatic performance gap underscores the core distinction Sparse RL makes: moving beyond merely correct code to truly hardware-aware, high-performance code. It validates the framework's unique approach of integrating geometric awareness and direct execution feedback into the code generation process.
These headline numbers, derived from a comprehensive evaluation across a large and diverse matrix collection and against formidable baselines, firmly establish Sparse RL as a leading solution for dynamic sparse CUDA code generation. While specific ablation studies were not detailed in the provided transcript, the comparative results against such strong baselines inherently demonstrate the efficacy of Sparse RL's combined innovations.
Practical Implications
▶ Watch: Experimental setup and strong baselines for evaluation (8:00)
The Sparse RL framework carries profound practical implications for a wide range of practitioners, from infrastructure teams and model builders to deployers of AI systems and researchers in scientific computing. Its ability to dynamically generate highly optimized CUDA kernels for sparse operations addresses a critical bottleneck that has long impeded performance and scalability in various domains.
For Infrastructure Teams and Deployers:
- Automated Performance Optimization: Sparse RL offers a pathway to automate the notoriously difficult task of optimizing sparse kernels. Infra teams often spend significant resources hand-tuning kernels for specific hardware and sparsity patterns. Sparse RL can potentially offload much of this burden, leading to faster development cycles and reduced operational costs.
- Dynamic Adaptation at Runtime: The framework's ability to adapt to dynamic input at runtime means that systems can maintain high performance even when sparse matrix characteristics change on the fly. This is crucial for real-world deployments where data patterns are rarely static. It could lead to more robust and consistently high-performing systems without requiring manual intervention or pre-compiled kernels for every conceivable pattern.
- Hardware Agnosticism (to an extent): While trained on NVIDIA GPUs, the underlying DRL approach suggests potential for adaptation to other hardware architectures (e.g., AMD GPUs, FPGAs, custom AI accelerators) by simply retraining the RL agent with execution feedback from the new target hardware. This could streamline multi-platform deployments.
For Model Builders and Researchers:
- Accelerated Sparse AI Models: Sparse computing is fundamental to scaling large language models (LLMs) through techniques like Sparse Mixture-of-Experts (MoE), sparse attention, and sparse weight pruning. Sparse RL can directly accelerate the inference and training of these models, making larger and more complex AI architectures feasible and cost-effective.
- Democratization of HPC Optimization: The framework lowers the barrier to entry for achieving HPC-level performance. Model builders and researchers who may not be CUDA experts can still benefit from highly optimized sparse operations, allowing them to focus on model innovation rather than low-level kernel tuning.
- New Design Space for Sparse Algorithms: With an automated, high-performance sparse kernel generator, researchers might be emboldened to explore novel sparse algorithms and data structures that were previously deemed too complex or impractical to optimize manually.
Tradeoffs and Limitations:
While revolutionary, Sparse RL, like any advanced system, comes with inherent tradeoffs and limitations:
- Training Complexity and Cost: The three-stage training pipeline, especially the RL phase with PPO, can be computationally intensive and require significant GPU resources and time. Building and refining such a model is a non-trivial undertaking.
- Generalization Beyond SpMV: The talk primarily focuses on Sparse Matrix-Vector Multiplication (SpMV). While SpMV is a fundamental "boss fight," generalizing Sparse RL to other complex sparse operations (e.g., sparse matrix-matrix multiplication, sparse convolutions) would require further research and potentially tailored training.
- Interpretability: As an AI-driven system, the generated CUDA code might not always be as human-interpretable as hand-tuned kernels. Understanding why a particular piece of code is optimal might be challenging, which could impact debugging or further manual refinement if needed.
- Dependency on Execution Environment: The DRL approach relies heavily on feedback from the execution environment. Any inaccuracies or latency in this feedback loop could impact the learning process and the quality of the generated code.
- Hardware Specificity: While adaptable, the initial training is tied to specific hardware (V100, A100). Porting to vastly different architectures might require retraining or significant fine-tuning, reflecting the deep hardware awareness it develops.
Despite these considerations, Sparse RL represents a significant leap forward in merging the power of generative AI with the rigor of HPC. Its ability to dynamically adapt and generate highly efficient sparse CUDA code has the potential to fundamentally reshape how we develop and deploy high-performance computing applications, particularly in the rapidly evolving landscape of AI.
Key Takeaways
- Bridging LLMs and HPC: Sparse RL critically addresses the gap between general-purpose LLM code generation (focused on logical correctness) and the demands of HPC (focused on hardware-aware execution latency).
- Dynamic Optimization for Sparse Data: The framework enables AI to generate highly optimized CUDA code for sparse matrix operations, dynamically adapting to irregular data patterns at runtime, a long-standing challenge in HPC.
- Geometric Awareness via Sinusoidal Embeddings: Sparse RL introduces sinusoidal embeddings to help LLMs understand the geometric structure of sparse matrices, providing scale invariance and locality awareness crucial for efficient memory access.
- Three-Stage DRL Pipeline: A robust training pipeline combines pretraining on CUDA, supervised fine-tuning with sparse matrix mappings, and reinforcement learning (PPO) using real GPU execution feedback to optimize for speed.
- Hierarchical Reward for Stable Learning: A multi-level reward function prioritizes compilation, correctness, and execution efficiency, including penalties for resource contention, to stabilize and guide the learning process.
- Record-Breaking Performance: Sparse RL achieves a 14x speedup over NVIDIA's cuSPARSE and a 30x speedup over state-of-the-art LLM code generation (CodeRL) on diverse sparse matrix benchmarks.
About the Speaker(s)
The talk "Mastering Sparse CUDA Generation through Pretrained Models and Deep Reinforcement Learning" was presented by Yaoyu Wang, alongside co-authors Hankun Dai, Zhidong Yang, Junmin Xiao, and Guangming Tan. Their affiliations are not explicitly stated in the transcript, but their collective work demonstrates expertise at the intersection of large language models, high-performance computing, and deep reinforcement learning, contributing significantly to the field of AI-driven code optimization.
Reviews
→ Top-rated talks at International Conference on Learning Representations 2026
All talks from International Conference on Learning Representations 2026