Skip to content

feat: add native fused logp RL kernel variants - #33

Merged
Flink-ddd merged 2 commits into
RL-Align:mainfrom
inaniloquentee:issue-5-native-fused-logp
May 29, 2026
Merged

Flink-ddd merged 2 commits into
RL-Align:mainfrom
inaniloquentee:issue-5-native-fused-logp

Conversation

@inaniloquentee

Copy link
Copy Markdown
Collaborator

Summary

This PR adds native fused-logp variants for RL selected-logprob workloads.

The main RL-facing optimization is valid-row indexed output. It lets RL infra compute selected logprobs only for valid completion rows instead of every padded/inactive row.

The later iterations then improve the per-row vocab scan on top of that indexed path.

Fixes #5

Iteration Progression

Iteration 1: Baseline Dense Two-Pass

The starting point is the original dense fused-logp path.

It computes selected-token log probability for every row with a two-pass log-sum-exp kernel:

  1. pass over vocab to compute row max
  2. pass over vocab to compute exp-sum

Role: baseline correctness and performance reference.

Decision: keep as the default/simple dense path.

Iteration 2: Preallocated And FP32 Output

This iteration adds RL infra-friendly output APIs.

Added:

  • preallocated output path
  • fp32 output path

Why:

  • RL training loops often reuse buffers.
  • Avoiding per-call output allocation is useful before deeper kernel tuning.
  • fp32 output is useful for loss-side numerical stability.

Decision: promoted.

Iteration 3: Valid-Row Indexed Output

This is the main RL workload-shape optimization.

It adds indexed-row variants so the kernel can compute only valid completion rows, using row indices derived from the RL completion mask.

Why:

  • RL batches often contain padding or inactive completion tokens.
  • Dense computation wastes work on invalid rows.
  • Indexed output aligns the operator with RL mask semantics.

Decision: conditionally promoted.

Use indexed paths when valid-token density is meaningfully below full density. Keep dense paths for full-density batches.

Iteration 4: Online Log-Sum-Exp

This iteration optimizes the per-row vocab scan.

Instead of two streaming passes over vocab, it computes log-sum-exp online in one pass.

Why:

  • Large vocab rows are memory-streaming heavy.
  • Removing the second full-vocab read can improve large-vocab selected-logprob latency.

Initial online log-sum-exp was not always faster, so it was re-evaluated with block-size-controlled benchmarks and NCU. The final policy keeps:

  • 128 threads/block for default online paths
  • 256 threads/block for large-row sparse indexed online paths

Decision: promoted conditionally with a small launch policy.

Iteration 5: Static Online Launch Variants

This iteration keeps the launch policy from Iteration 4 but improves code generation.

Instead of one online kernel using runtime blockDim.x, it compiles static online variants by BlockSize.

Why:

  • The hot vocab loop and online reduction benefit from compile-time block size.
  • NCU showed fewer executed instructions and better scheduler readiness.
  • This makes the online path more stable and faster.

Decision: promoted.

Performance Summary

The main RL-facing gain is from Iteration 3: exposing valid-row indexing so RL infra can skip inactive completion tokens.

Iterations 4 and 5 then improve the per-valid-row vocab scan.

Small-Vocab RL Shape

vocab=4096, num_prompts=8, samples_per_prompt=8, completion_len=128

Mask density Dense two-pass out ms Iteration 3 indexed ms Iteration 5 online indexed ms
1.00 0.5494 0.5632 0.4280
0.50 0.5466 0.2867 0.2188
0.25 0.5468 0.1485 0.1126

Speedup vs dense two-pass:

Mask density Iteration 3 speedup Iteration 5 speedup
1.00 0.98x 1.28x
0.50 1.91x 2.50x
0.25 3.68x 4.86x

Interpretation:

  • Iteration 3 is not useful at full density because indexed dispatch adds overhead without skipping rows.
  • Iteration 3 becomes the key RL optimization once valid-token density drops.
  • Iteration 5 improves the indexed path further, but Iteration 3 is the change that exposes RL sparsity.

Large-Vocab RL Shape

num_prompts=4, samples_per_prompt=4, completion_len=64

Vocab Mask density Iteration 3 indexed ms Iteration 5 online indexed ms Iteration 5 vs 3
32768 1.00 0.9359 0.4280 2.19x
32768 0.50 0.4639 0.2179 2.13x
32768 0.25 0.2673 0.1143 2.34x
65536 1.00 1.8396 0.8465 2.17x
65536 0.50 0.9178 0.4280 2.14x
65536 0.25 0.5282 0.2222 2.38x

Interpretation:

  • For large vocab, per-row vocab streaming becomes dominant.
  • Iterations 4 and 5 matter more here because online log-sum-exp avoids the second full-vocab pass.
  • Iteration 3 remains the RL-facing dispatch mechanism: dense for full valid-token batches, indexed for sparse valid-token batches.

NCU Evidence For Iteration 5

Profiled shape: vocab=32768, mask_density=0.5, indexed path.

Variant Duration DRAM throughput Eligible warps/scheduler Achieved occupancy Executed instructions
Iteration 4 online indexed, 256 threads 357.44 us 58.94% 0.90 92.37% 14,262,272
Iteration 5 online indexed, 256 threads 232.19 us 90.65% 1.12 94.06% 10,235,904

Iteration 5 improves codegen after Iteration 4 chooses the right online launch policy. It should be viewed as the final per-row implementation improvement, while Iteration 3 is the main RL workload-shape improvement.

Final Implementation

This PR adds:

  • fused_logp_out
  • fused_logp_fp32
  • fused_logp_indexed_out
  • fused_logp_indexed_fp32
  • fused_logp_online_out
  • fused_logp_online_fp32
  • fused_logp_online_indexed_out
  • fused_logp_online_indexed_fp32

Python wrapper methods:

  • FusedLogp.out
  • FusedLogp.apply_fp32
  • FusedLogp.indexed_out
  • FusedLogp.indexed_fp32
  • FusedLogp.online_out
  • FusedLogp.online_fp32
  • FusedLogp.online_indexed_out
  • FusedLogp.online_indexed_fp32

Build-time CUDA knobs:

  • FUSED_LOGP_TWOPASS_BLOCK_SIZE
  • FUSED_LOGP_ONLINE_BLOCK_SIZE
  • FUSED_LOGP_ONLINE_SPARSE_LARGE_VOCAB_BLOCK_SIZE
  • FUSED_LOGP_ONLINE_LARGE_ROW_BYTES_THRESHOLD
  • FUSED_LOGP_ONLINE_SPARSE_DENSITY_NUMERATOR
  • FUSED_LOGP_ONLINE_SPARSE_DENSITY_DENOMINATOR
  • FUSED_LOGP_ONLINE_MIN_BLOCKS_PER_SM
  • KERNEL_ALIGN_NCU_LINEINFO=1

Validation

Ran:

pre-commit run --files csrc/fused_logp_kernel.cu csrc/ops.cpp rl_engine/kernels/fused_ops.py setup.py tests/test_op_accuracy.py
py -3.13 -m compileall benchmarks tests rl_engine
py -3.13 -m pytest tests -q

@Flink-ddd

Copy link
Copy Markdown
Collaborator

Thank you for your contribution this massive and import PR, I will make some review, Thanks.

@Flink-ddd Flink-ddd left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Amazing work on expanding the kernel variants! The progression from Dense to Online-Indexed is exactly what we need to minimize VRAM overhead for RL workloads like GRPO.

However, since this PR didn't modify our dispatcher, these new kernels are currently disconnected from our infra. To merge this smoothly, we need to wire these variants into our new dynamic dispatch system (KernelRegistry).

Action Required: Register Variants in rl_engine/kernels/registry.py

Since registry.py wasn't modified in this PR, please pull the latest main and edit it. We need to register your new workloads (e.g., "logp_indexed", "logp_online") so the RL rollout engine can fetch them dynamically based on mask density, rather than hardcoding static methods.

Please add your new variants to the _priority_map under the CUDA backend (sharing the generic fallback for now, as I will handle the broader Hardware Abstraction Layer folder restructuring later).

Example of what to add:

# rl_engine/kernels/registry.py
class KernelRegistry:
    def __init__(self):
        # ...
        self._priority_map = {
            "cuda": {
                "logp": [OpBackend.CUDA_FUSED_LOGP_GENERIC, OpBackend.PYTORCH_NATIVE],
                # Please register the new RL workload variants here:
                "logp_indexed": [OpBackend.CUDA_FUSED_LOGP_GENERIC, OpBackend.PYTORCH_NATIVE],
                "logp_online": [OpBackend.CUDA_FUSED_LOGP_GENERIC, OpBackend.PYTORCH_NATIVE],
                "logp_online_indexed": [OpBackend.CUDA_FUSED_LOGP_GENERIC, OpBackend.PYTORCH_NATIVE],
                "attn": [OpBackend.FLASH_ATTN, OpBackend.TRITON_GENERIC, OpBackend.PYTORCH_NATIVE],
            },
            # ...
        }

Once you integrate these into the registry and resolve the inline comments on setup.py, ops.cpp, and the Python wrappers, I will gladly approve this. Incredible optimization!

Comment thread rl_engine/kernels/fused_ops.py Resolved
Comment thread csrc/ops.cpp Resolved
Comment thread setup.py Resolved
@Flink-ddd

Copy link
Copy Markdown
Collaborator

LGTM now. Thank you for update code, but please resolve these conflicts before merge

@inaniloquentee
inaniloquentee force-pushed the issue-5-native-fused-logp branch from f705111 to 409a32e Compare May 29, 2026 11:19
@inaniloquentee

Copy link
Copy Markdown
Collaborator Author

LGTM now. Thank you for update code, but please resolve these conflicts before merge

Thanks for the review and LGTM!

I have rebased this PR onto the latest upstream/main and resolved the merge conflicts in csrc/ops.cpp, setup.py, rl_engine/_C.pyi, rl_engine/kernels/ops/cuda.py, rl_engine/kernels/registry.py, and tests/test_op_accuracy.py.

I also re-ran the checks after resolving the conflicts:

  • pre-commit run --files ... passed
  • py -3.13 -m pytest tests -q passed (8 passed)

The PR branch has been force-updated with the resolved rebase.

@Flink-ddd
Flink-ddd merged commit d22d22e into RL-Align:main May 29, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEAT][csrc]: optimize native fused logp CUDA kernel for GRPO training

2 participants