Skip to content

Instantly share code, notes, and snippets.

@a-elrawy
Last active October 8, 2026 16:58
Show Gist options
  • Select an option

  • Save a-elrawy/91706938192dbf45b4afcff5ef83a66b to your computer and use it in GitHub Desktop.

Select an option

Save a-elrawy/91706938192dbf45b4afcff5ef83a66b to your computer and use it in GitHub Desktop.

Google Summer of Code 2025 - Final Work Report

Supporting Thrust API in Clad for GPU-Accelerated Automatic Differentiation

Contributor: Abdelrhman Elrawy (@a-elrawy)
Organization: Compiler Research
Mentors: Vassil Vassilev, Alexander Penev
Project Repository: vgvassilev/clad
Project Proposal: HSF GSoC 2025 Proposal


Project Goals

The primary objective of this Google Summer of Code 2025 project was to extend Clad, a source-transformation automatic differentiation (AD) tool built as a Clang plugin, to support NVIDIA's Thrust parallel algorithms library.

Before this project: Clad could not differentiate through GPU-parallel primitives from Thrust, limiting its applicability in scientific computing and machine learning applications that leverage GPU acceleration.

After this project: Researchers and engineers can now automatically compute gradients for CUDA-accelerated code using Thrust primitives with minimal code changes, enabling:

  • GPU-accelerated gradient computations for high-energy physics simulations
  • Efficient training pipelines for machine learning models
  • Automatic differentiation in computational science applications requiring GPU performance

What Was Accomplished

I successfully merged 16 pull requests that comprehensively extend Clad's capabilities to support Thrust API automatic differentiation. The work spans core algorithms, advanced operations, infrastructure improvements, and practical demonstration applications.

Core Algorithm Support (8 PRs)

The foundation of this project was implementing differentiation support for Thrust's fundamental parallel primitives:

1. thrust::reduce - Parallel Reductions (base)

Pull Request: #1472 - Add custom derivative for thrust::reduce

  • Implemented forward-mode and reverse-mode automatic differentiation for parallel reductions
  • Support for multiple binary operators: thrust::plus, thrust::multiplies, thrust::maximum, thrust::minimum
  • Special handling for mathematical edge cases, particularly multiplication chains involving zeros

2. thrust::reduce - Overloads

Pull Request: #1492 - Add custom derivatives for reduce overloads

  • Added derivatives for common overloads:
    • thrust::reduce(first, last, init)
    • thrust::reduce(first, last)

3. thrust::reduce - Reverse-Forward Derivative

Pull Request: #1585 - Add custom reverse_forw for thrust::reduce

  • Added reduce_reverse_forw implementation
  • Fixes regression: Unsupported declaration errors in Thrust headers when differentiating functions (issue #1582)

4. thrust::inner_product - Dot Products

Pull Request: #1480 - Added support for thrust::inner_product

  • Implemented both 4-argument and 6-argument variants

  • Critical for linear algebra operations on GPU

  • Enables efficient gradient computation for vector operations in neural networks and physics simulations

  • Proper handling of custom binary operators for both multiplication and addition phases

    • 6-argument supported operator combinations:
      • op1 = thrust::plus, op2 = thrust::multiplies
      • op1 = thrust::plus, op2 = thrust::plus
      • op1 = thrust::plus, op2 = thrust::minus

5. thrust::transform - Element-wise Transformations

Pull Request: #1520 - Add support for thrust::transform

  • Maintains efficient GPU parallelization in derivative code

  • Foundation for many higher-level operations

  • Supports both unary and binary transform operations

    • Supported functors:
      • Unary: thrust::negate, thrust::identity
      • Binary: thrust::plus, thrust::minus, thrust::multiplies, thrust::divides
    • Supports user-defined functors via operator_call_pullback

6. thrust::transform_reduce - Fused Transformation and Reduction

Pull Request: #1532 - Add support for thrust::transform_reduce

  • Combines transform and reduce to minimize memory traffic

  • Essential for ML operations like computing norms and loss functions

  • Efficient gradient backpropagation through fused operations

    • Initial operation support:
      • Transform functors: thrust::negate, thrust::identity
      • Reduction ops: thrust::plus, thrust::maximum, thrust::minimum

7. thrust::copy - Memory Operations with Gradient Tracking

Pull Request: #1511 - Add custom derivative for thrust::copy

  • Ensures proper gradient flow during data movement
  • Handles device-to-device and host-device transfers
  • Critical for maintaining gradient consistency across memory spaces

8. thrust::adjacent_difference - Computing Differences Between Adjacent Elements

Pull Request: #1597 - add custom derivatives for thrust::adjacent_difference

  • Useful for finite difference schemes and time-series analysis

  • Proper derivative handling for sequential dependencies

  • Support for custom binary operators

    • Supported operators: thrust::minus, thrust::plus

Advanced Operations (4 PRs)

Building on the core algorithms, I implemented support for more sophisticated parallel primitives:

9. Scan Operations - Prefix Sums

Pull Request: #1589 - Add custom derivatives for Thrust prefix sum operations

  • Inclusive and exclusive prefix sum variants: thrust::inclusive_scan, thrust::exclusive_scan
  • Fundamental building blocks for many parallel algorithms
  • Applications in cumulative distributions, parallel scheduling, and dynamic programming
  • Technical challenge: Output at position i depends on all inputs up to i, requiring careful gradient backpropagation
  • Efficient parallel backward pass for gradient accumulation

10. thrust::sort_by_key - Sorting with Gradient Preservation

Pull Request: #1611 - Add custom derivatives for thrust::sort_by_key

  • Forward pass records index permutation
  • Backward pass applies inverse permutation to gradients
  • Critical for algorithms requiring sorted data structures
  • Maintains gradient correspondence across sorting operations

Key insight: Sorting doesn't change gradient magnitudes, only their positions.

11. thrust::reduce_by_key - Segmented Reductions

Pull Request: #1617 - Add custom derivatives for thrust::reduce_by_key

  • SQL-like GROUP BY operations on GPU
  • Essential for batch processing in neural networks
  • Complex gradient routing through irregular partition boundaries
  • Proper handling of variable-length segments

Use case: Computing per-batch gradients in mini-batch training.

12. Segmented Scans - Partitioned Prefix Sums

Pull Request: #1620 - Add custom derivatives for Thrust segmented scans

  • Prefix sums within each segment defined by keys

  • Handles complex gradient flow through segmented data structures

  • Applications in graph algorithms and dynamic programming on GPUs

    • Supported operations:
      • thrust::inclusive_scan_by_key
      • thrust::exclusive_scan_by_key

Infrastructure Improvements (2 PRs)

13. thrust::device_vector Support

Pull Request: #1608 - Add initial thrust::device_vector support and update Thrust demos

  • Differentiate against the constructors and operations of Thrust container classes
  • Interoperability with existing Thrust code
    • Introduced ThrustBuiltins.h providing:
      • zero_init(thrust::device_vector<T>) via thrust::fill
      • constructor_pullback(size) and constructor_pullback(size, value)
    • Updated demos:
      • VectorAddition: allocate local z
      • ParticleSimulation: allocate tmp, x_buffer, y_buffer internally

14. Generic Functor Support for Transform Operations

Pull Request: #1599 - Added Generic functor support for transform

  • Users can define custom functors to use with thrust::transform
  • Greatly extends the flexibility of thrust::transform and related operations
  • Support for function objects
    • Implemented via operator_call_pullback for unary and binary functors
    • Preserves builtin op support (negate, identity, plus, minus, multiplies, divides)
    • Adds complex tests using custom operations

Demonstration Applications (2 PRs)

To showcase the practical utility of this work, I developed several real-world demonstrations:

15. Multiple Thrust-based Demo Applications

Pull Request: #1554 - Add Thrust-based demos

  • Linear Regression: GPU-accelerated gradient descent using thrust::transform_reduce for loss computation
  • Particle Simulation: N-body simulation with automatic derivative tracking for parameter optimization
  • Demonstrates end-to-end workflows from problem setup to gradient computation

16. Bag-of-Words Logistic Regression

Pull Request: #1630 - Add BoW logistic regression Thrust demo

  • Machine learning pipeline using Thrust and Clad
  • GPU-accelerated logistic regression with gradient descent
  • Cross-entropy loss function with automatic differentiation
  • Showcases how multiple Thrust operations (reduce, transform, inner_product) combine for ML workflows
  • All computations remain on GPU device memory for maximum performance
    • Features:
      • Single-example logistic loss and L2-regularized 2-document batch loss
      • Runs SGD over a 4-document mini-batch; prints loss, gradient header, iteration losses, and final accuracy

What's Left to Do

While the core objectives were successfully completed, several exciting directions remain for future development:

Additional Thrust Primitives

  • thrust::gather and thrust::scatter: Indirect memory access patterns with gradient tracking
  • thrust::partition: Partitioning operations with gradient preservation
  • thrust::unique: Handling duplicate elimination in derivative code
  • Additional sorting operations: thrust::stable_sort, thrust::is_sorted variants
  • thrust::merge and thrust::set_operations: Set-based operations with gradients

Real-World Applications

  • Neural network training: Full GPU-native neural network training framework using Clad
  • Physics simulations: Large-scale physics simulations with gradient-based parameter optimization (e.g., detector geometry optimization in high-energy physics)

Challenges and Key Learnings

  • Addressed GPU memory debugging, mathematical edge cases, correctness validation, and complex data dependencies with targeted tooling, testing, and algorithmic analysis.

Impact and Applications

This work significantly expands Clad's applicability in several domains:

High-Energy Physics

  • Gradient-based optimization for detector simulations: Automatically compute gradients for detector geometry parameters
  • Parameter estimation in complex physical models: Fit model parameters to experimental data using gradient descent
  • Enables GPU acceleration of gradient computations for large-scale simulations: Orders of magnitude speedup for optimization tasks

Machine Learning

  • GPU-accelerated training for custom models: Build custom neural architectures with automatic gradient computation
  • Efficient gradient computation for loss functions: Implement custom loss functions without manual derivative implementation

Pull Requests List

Below is the complete list of merged pull requests, organized by category:

Core Algorithm Support

PR # Title Status Description
#1472 Add thrust::reduce support ✅ Merged Parallel reductions with multiple binary operators
#1492 Add thrust::reduce overload derivatives ✅ Merged Support for reduce(first,last,init) and reduce(first,last)
#1585 Add reverse_forw for thrust::reduce ✅ Merged Adds reduce_reverse_forw; fixes regression (#1582)
#1480 Add thrust::inner_product support ✅ Merged Dot products and inner products (4 and 6 argument variants)
#1520 Add thrust::transform support ✅ Merged Element-wise transformations with generic functors
#1532 Add thrust::transform_reduce support ✅ Merged Fused transformation and reduction
#1511 Add thrust::copy support ✅ Merged Memory operations with gradient tracking
#1597 Add thrust::adjacent_difference support ✅ Merged Computing differences between adjacent elements

Advanced Operations

PR # Title Status Description
#1589 Add scan operations support ✅ Merged Inclusive and exclusive prefix sums
#1611 Add thrust::sort_by_key support ✅ Merged Sorting key-value pairs with gradient preservation
#1617 Add thrust::reduce_by_key support ✅ Merged Segmented reductions for grouped data
#1620 Add segmented scan operations ✅ Merged Partitioned prefix sum operations

Infrastructure

PR # Title Status Description
#1608 Add thrust::device_vector support ✅ Merged Container support and memory management
#1599 Generic functor support for transform ✅ Merged User-defined functor differentiation

Demonstrations

PR # Title Status Description
#1554 Add Thrust demo applications ✅ Merged Vector addition, particle simulation, linear regression demos
#1630 Add bag-of-words logistic regression demo ✅ Merged ML pipeline with GPU-accelerated training

Conclusion

This Google Summer of Code 2025 project successfully brought GPU-accelerated automatic differentiation to Clad through comprehensive Thrust API support. The 16 merged pull requests cover core algorithms, advanced operations, infrastructure improvements, and practical demonstrations, representing a significant contribution to the scientific computing community.

The project opens new possibilities for researchers and engineers who need efficient gradient computations in GPU-accelerated applications across high-energy physics, machine learning, and computational science domains. By bridging the gap between GPU parallel programming and automatic differentiation, this work enables faster development cycles and more efficient computation for gradient-based optimization and parameter estimation tasks.

Related Links


@azad2003-ai

azad2003-ai commented Jan 6, 2026 •

Copy link
Copy Markdown

Hello @vassil Vassilev, Alexander Penev
sir and mentors,

My name is Azad Kumar, And I recently pursuing Bachelor's Degree in Computer Scince from Madhya Pradesh
MERN Stack
Java
Python
SQL
Blockchain
System Design (LLD & HLD)
Linux OS
Gen al
Backend development
Data structures & alogrithms

I am interested in contributing to the a highly scalable project is one that GSoC 2026
I have reviewed the project description and would like to begin contributing and understanding the expected the expected

deliverables.
Could you please guide me on:
where is the development repo/codebase for this project maintained?

Beginner-friendly tasks or areas I should explore first?
Are there any specific tools, datasets, or technologies I should set up before I start?

Looking forward to contributing meaningfully.

Thank you!
Azad kumar

@Mohima6

Mohima6 commented Jan 8, 2026

Copy link
Copy Markdown

Thanks for sharing the insightful report. I am interested in contributing to GSoC 2026 projects. Looking forward to contributing meaningfully and would love to hear any guidance, feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment