Skip to content

Reorg the sparse/quant/common kernel dir - #1303

Merged
jingyu-ml merged 12 commits into
mainfrom
jingyux/implicit-gemm-2.1-3
Apr 22, 2026
Merged

Reorg the sparse/quant/common kernel dir#1303
jingyu-ml merged 12 commits into
mainfrom
jingyux/implicit-gemm-2.1-3

Conversation

@jingyu-ml

@jingyu-ml jingyu-ml commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: re-org code

Usage

# Add a code snippet demonstrating how to use this

Testing

Before your PR is "Ready for review"

Make sure you read and follow Contributor guidelines and your commits are signed (git commit -s -S).

Make sure you read and follow the Security Best Practices (e.g. avoiding hardcoded trust_remote_code=True, torch.load(..., weights_only=False), pickle, etc.).

  • Is this change backward compatible?: ❌ We changed the import path
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: ✅
  • Did you write any new necessary tests?: ❌
  • Did you update Changelog?:✅

Additional Information

Summary by CodeRabbit

  • New Features

    • Calibration support for skip-softmax multi-threshold measurement in sparse attention.
    • N:M sparse softmax masking and helpers for sparsity-aware attention.
  • Chores

    • Reorganized and consolidated kernel/backends for quantization and sparsity to a unified kernels layout, updating tests and examples to match.

Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
@coderabbitai

coderabbitai Bot commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR reorganizes kernel code into a unified modelopt/torch/kernels/ package, moves quantization and convolution GEMM kernels, extracts and lazy-loads shared attention/sparsity helpers, adds a calibration path for skip-softmax measurement, and updates import paths and tests accordingly.

Changes

Cohort / File(s) Summary
Top-level kernel package
modelopt/torch/kernels/__init__.py, modelopt/torch/kernels/common/__init__.py, modelopt/torch/kernels/quantization/__init__.py, modelopt/torch/kernels/sparsity/__init__.py
Added package initializers and removed prior top-level Triton plugin-load/export logic from kernels.__init__.
Common attention package
modelopt/torch/kernels/common/attention/__init__.py, modelopt/torch/kernels/common/attention/hf_triton_attention.py, modelopt/torch/kernels/common/attention/triton_fa.py
New common.attention exposes IS_AVAILABLE, attention, register_triton_attention, and integrates lazy loading of sparsity helpers; triton_fa.py refactored to call _load_sparsity_helpers() and had attention_calibrate removed from its exports.
Sparsity attention modules
modelopt/torch/kernels/sparsity/attention/__init__.py, .../diffusers_triton_attention.py, .../ltx_triton_attention.py, .../calibrate.py, .../skip_softmax_helpers.py
Moved sparsity/triton backends into kernels.sparsity.attention; changed to call-site/lazy imports to avoid circulars; added calibrate.py with _attn_fwd_calibrate and attention_calibrate; added skip_softmax_helpers.py with N:M masks, skip decision, and dense-region predicate.
Quantization GEMM & conv kernels
modelopt/torch/kernels/quantization/gemm/*, modelopt/torch/kernels/quantization/conv/*, modelopt/torch/quantization/extensions.py, modelopt/torch/quantization/tensor_quant.py, modelopt/torch/quantization/nn/modules/quant_conv.py, modelopt/torch/quantization/qtensor/nvfp4_tensor.py, modelopt/torch/quantization/plugins/huggingface.py, modelopt/torch/quantization/utils/calib_utils.py
Switched imports and extension source paths to the centralized kernels.quantization.gemm and kernels.quantization.conv locations (FP4/FP8/GEMM kernels); callers unchanged aside from import paths.
Examples & benchmarks
examples/deepseek/ptq.py, examples/deepseek/quantize_to_nvfp4.py, modelopt/torch/kernels/quantization/conv/README.md, modelopt/torch/kernels/quantization/conv/bench_implicit_gemm.py
Updated example and benchmark import paths to use modelopt.torch.kernels.quantization.*.
Sparsity integration points
modelopt/torch/sparsity/attention_sparsity/conversion.py, .../methods/flash_skip_softmax.py, .../methods/triton_skip_softmax.py
Repointed registration and skip-softmax context imports to modelopt.torch.kernels.sparsity.attention (absolute paths) and updated backend config/import handling.
Lint config
pyproject.toml
Updated Ruff per-file-ignores to target new kernel paths under modelopt/torch/kernels/....
Tests — import/path updates
many test files under tests/gpu/... and tests/unit/... (see diff)
All affected tests updated to import kernel availability flags, attention, calibrate, and helper symbols from modelopt.torch.kernels.common.attention and modelopt.torch.kernels.sparsity.attention; mocks/patch targets adjusted accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Common Attention<br/>(common/attention)
    participant Sparsity as Sparsity Helpers<br/>(skip_softmax_helpers.py)
    participant Calibrate as Calibrate Module<br/>(calibrate.py)
    participant GPU as GPU Counters<br/>(device buffers)

    Client->>Client: _load_sparsity_helpers() on first call
    Client->>Sparsity: load _apply_sparse_nm, _skip_softmax_decision, _is_dense_region

    alt Normal forward
        Client->>Client: attention() compute qk scores
        Client->>Sparsity: _apply_sparse_nm_to_qk_tile() if N:M enabled
        Client->>Sparsity: _skip_softmax_decision() if skip-softmax enabled
        Client->>Client: return attention output
    else Calibration flow
        Client->>Calibrate: attention_calibrate(thresholds)
        Calibrate->>Calibrate: launch _attn_fwd_calibrate kernel
        Calibrate->>GPU: write per-program totals/skipped counters
        Calibrate->>Calibrate: reduce counters and return (output, sparsity_counters)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes


Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error, 1 warning)

Check name Status Explanation Resolution
Security Anti-Patterns ❌ Error torch.load() on user-supplied file paths in examples/deepseek/quantize_to_nvfp4.py line 101 lacks weights_only=True or security comment. Add weights_only=True to torch.load() call or add inline security comment explaining the file is internally-generated with codeowner review.
Docstring Coverage ⚠️ Warning Docstring coverage is 78.13% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'Reorg the sparse/quant/common kernel dir' accurately reflects the main objective: reorganizing kernel directories across sparse/quantization/common modules.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jingyux/implicit-gemm-2.1-3

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Apr 20, 2026

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-04-22 23:35 UTC

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@modelopt/torch/kernels/__init__.py`:
- Line 16: Restore a temporary compatibility bridge in modelopt.torch.kernels by
re-exporting the legacy Triton-level symbols that were removed (reintroduce the
module-level names that downstream code imports) and emit a DeprecationWarning
when those legacy names are accessed; update the package __init__ (module
modelopt.torch.kernels) to import and re-export the new implementations (or
alias them) under the old names and add a short deprecation shim that warns
users and points to the new import path so existing runtime imports continue to
work during the migration window.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 0e39d97c-3957-4253-97cf-b9ad751b3c59

📥 Commits

Reviewing files that changed from the base of the PR and between 2fef374 and 7e00248.

📒 Files selected for processing (49)
  • examples/deepseek/ptq.py
  • examples/deepseek/quantize_to_nvfp4.py
  • modelopt/torch/kernels/__init__.py
  • modelopt/torch/kernels/common/__init__.py
  • modelopt/torch/kernels/common/hf_triton_attention.py
  • modelopt/torch/kernels/common/triton_fa.py
  • modelopt/torch/kernels/quantization/__init__.py
  • modelopt/torch/kernels/quantization/conv/README.md
  • modelopt/torch/kernels/quantization/conv/__init__.py
  • modelopt/torch/kernels/quantization/conv/bench_implicit_gemm.py
  • modelopt/torch/kernels/quantization/conv/implicit_gemm_binding.cpp
  • modelopt/torch/kernels/quantization/conv/implicit_gemm_cuda.py
  • modelopt/torch/kernels/quantization/conv/implicit_gemm_kernel.cu
  • modelopt/torch/kernels/quantization/gemm/__init__.py
  • modelopt/torch/kernels/quantization/gemm/fp4_kernel.py
  • modelopt/torch/kernels/quantization/gemm/fp4_kernel_hopper.py
  • modelopt/torch/kernels/quantization/gemm/fp8_kernel.py
  • modelopt/torch/kernels/quantization/gemm/tensor_quant.cpp
  • modelopt/torch/kernels/quantization/gemm/tensor_quant.h
  • modelopt/torch/kernels/quantization/gemm/tensor_quant_gpu.cu
  • modelopt/torch/kernels/quantization/gemm/tensor_quant_gpu_fp8.cu
  • modelopt/torch/kernels/quantization/gemm/tensor_quant_mx.cu
  • modelopt/torch/kernels/quantization/gemm/tensor_quant_mx.h
  • modelopt/torch/kernels/sparsity/__init__.py
  • modelopt/torch/kernels/sparsity/attention/__init__.py
  • modelopt/torch/kernels/sparsity/attention/diffusers_triton_attention.py
  • modelopt/torch/kernels/sparsity/attention/ltx_triton_attention.py
  • modelopt/torch/kernels/sparsity/gemm/__init__.py
  • modelopt/torch/quantization/extensions.py
  • modelopt/torch/quantization/nn/modules/quant_conv.py
  • modelopt/torch/quantization/plugins/huggingface.py
  • modelopt/torch/quantization/qtensor/nvfp4_tensor.py
  • modelopt/torch/quantization/tensor_quant.py
  • modelopt/torch/sparsity/attention_sparsity/conversion.py
  • modelopt/torch/sparsity/attention_sparsity/methods/flash_skip_softmax.py
  • modelopt/torch/sparsity/attention_sparsity/methods/triton_skip_softmax.py
  • pyproject.toml
  • tests/gpu/torch/quantization/kernels/test_implicit_gemm.py
  • tests/gpu/torch/quantization/test_tensor_quant_cuda.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_diffusers_triton_attention.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa_calibrate.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa_skip_softmax.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa_sparse_nm.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_wan22_skip_softmax.py
  • tests/unit/torch/kernels/test_triton_fa.py
  • tests/unit/torch/sparsity/attention_sparsity/test_kernel_backends.py
  • tests/unit/torch/sparsity/attention_sparsity/test_ltx_triton_attention.py
  • tests/unit/torch/sparsity/attention_sparsity/test_sparse_attention_conversion.py

Comment thread modelopt/torch/kernels/__init__.py
@codecov

codecov Bot commented Apr 20, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 44.63519% with 129 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.68%. Comparing base (0678136) to head (8b0a02b).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...kernels/sparsity/attention/skip_softmax_helpers.py 12.82% 68 Missing ⚠️
...lopt/torch/kernels/sparsity/attention/calibrate.py 40.00% 57 Missing ⚠️
...delopt/torch/kernels/common/attention/triton_fa.py 82.35% 3 Missing ⚠️
...h/kernels/quantization/conv/bench_implicit_gemm.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1303      +/-   ##
==========================================
+ Coverage   74.46%   75.68%   +1.21%     
==========================================
  Files         464      467       +3     
  Lines       50089    50176      +87     
==========================================
+ Hits        37300    37975     +675     
+ Misses      12789    12201     -588     
Flag Coverage Δ
examples 41.47% <28.75%> (+5.42%) ⬆️
gpu 58.53% <43.77%> (-0.56%) ⬇️
regression 14.83% <2.14%> (+0.03%) ⬆️
unit 52.35% <14.16%> (-0.09%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@shengliangxu shengliangxu 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.

LGTM

Comment thread tests/gpu/torch/kernels/quantization/conv/test_implicit_gemm.py
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@modelopt/torch/kernels/sparsity/attention/calibrate.py`:
- Around line 157-172: The kernel computes num_q_tiles using tl.load(b_seq_len +
0) (batch 0 length) which can under-estimate and cause prog_idx to exceed
allocated buffers (affecting Per_program_totals and Per_program_skipped); change
the kernel signature to accept max_input_len and use tl.cdiv(max_input_len,
BLOCK_M) when computing num_q_tiles/prog_idx, update the prog_idx/base
calculation sites (prog_idx, base) accordingly, and update the Python wrapper
that launches the kernel to pass the same max_input_len used to size the
Per_program_* buffers so the kernel and host agree on bounds.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b59a3685-d843-4abe-8b17-41f6c2e12a9a

📥 Commits

Reviewing files that changed from the base of the PR and between 7e00248 and bab5022.

📒 Files selected for processing (17)
  • modelopt/torch/kernels/common/__init__.py
  • modelopt/torch/kernels/common/attention/__init__.py
  • modelopt/torch/kernels/common/attention/hf_triton_attention.py
  • modelopt/torch/kernels/common/attention/triton_fa.py
  • modelopt/torch/kernels/quantization/attention/__init__.py
  • modelopt/torch/kernels/sparsity/attention/__init__.py
  • modelopt/torch/kernels/sparsity/attention/calibrate.py
  • modelopt/torch/kernels/sparsity/attention/diffusers_triton_attention.py
  • modelopt/torch/kernels/sparsity/attention/ltx_triton_attention.py
  • modelopt/torch/kernels/sparsity/attention/skip_softmax_helpers.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_diffusers_triton_attention.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa_calibrate.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa_skip_softmax.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa_sparse_nm.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_wan22_skip_softmax.py
  • tests/unit/torch/kernels/test_triton_fa.py
✅ Files skipped from review due to trivial changes (6)
  • modelopt/torch/kernels/quantization/attention/init.py
  • modelopt/torch/kernels/common/attention/hf_triton_attention.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa.py
  • modelopt/torch/kernels/sparsity/attention/init.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_diffusers_triton_attention.py
  • modelopt/torch/kernels/common/init.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • tests/gpu/torch/sparsity/attention_sparsity/test_triton_fa_calibrate.py
  • modelopt/torch/kernels/sparsity/attention/diffusers_triton_attention.py
  • tests/unit/torch/kernels/test_triton_fa.py
  • modelopt/torch/kernels/sparsity/attention/ltx_triton_attention.py
  • tests/gpu/torch/sparsity/attention_sparsity/test_wan22_skip_softmax.py

Comment thread modelopt/torch/kernels/sparsity/attention/calibrate.py
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
@jingyu-ml jingyu-ml self-assigned this Apr 22, 2026

@cjluo-nv cjluo-nv 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.

This is a well-executed code reorganization moving kernels from scattered locations into a clean modelopt/torch/kernels/{common,quantization,sparsity} hierarchy. All internal import sites have been updated, tests are moved and adjusted, and the lazy-import pattern in triton_fa.py properly handles the circular dependency between common.attention and sparsity.attention.

Two items worth the owner's attention:

  1. Backward compatibility claim is misleading: The PR checks "backward compatible ✅" but removes public symbols from modelopt.torch.kernels (previously exported IS_AVAILABLE, attention, attention_calibrate, register_triton_attention) and eliminates the modelopt.torch.quantization.triton and modelopt.torch.sparsity.attention_sparsity.kernels import paths. External consumers using these paths will break. Consider adding deprecation re-exports in the old __init__.py locations, or at minimum update the backward-compatibility checkbox to ❌ with an explanation.

  2. Copyright year on new files: calibrate.py and skip_softmax_helpers.py (new files in this PR) have Copyright (c) 2024 — these should likely be 2024-2025 or 2025 since they're being created now (even though the code is moved from an existing file).

@jingyu-ml
jingyu-ml requested a review from cjluo-nv April 22, 2026 20:28
@jingyu-ml

Copy link
Copy Markdown
Contributor Author

This is a well-executed code reorganization moving kernels from scattered locations into a clean modelopt/torch/kernels/{common,quantization,sparsity} hierarchy. All internal import sites have been updated, tests are moved and adjusted, and the lazy-import pattern in triton_fa.py properly handles the circular dependency between common.attention and sparsity.attention.

Two items worth the owner's attention:

  1. Backward compatibility claim is misleading: The PR checks "backward compatible ✅" but removes public symbols from modelopt.torch.kernels (previously exported IS_AVAILABLE, attention, attention_calibrate, register_triton_attention) and eliminates the modelopt.torch.quantization.triton and modelopt.torch.sparsity.attention_sparsity.kernels import paths. External consumers using these paths will break. Consider adding deprecation re-exports in the old __init__.py locations, or at minimum update the backward-compatibility checkbox to ❌ with an explanation.
  2. Copyright year on new files: calibrate.py and skip_softmax_helpers.py (new files in this PR) have Copyright (c) 2024 — these should likely be 2024-2025 or 2025 since they're being created now (even though the code is moved from an existing file).

Thank you Chenjie, change the Backward compatibility to false since we changed the import path

Copyright year is correct, all the file under this repo followed this pattern.

@cjluo-nv cjluo-nv 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.

This is a well-organized directory restructuring, but two critical issues from previous reviews remain unaddressed:

  1. Backward compatibility (critical, unresolved): The PR removes modelopt.torch.quantization.triton, modelopt.torch.kernels.{IS_AVAILABLE, attention, ...}, and modelopt.torch.sparsity.attention_sparsity.kernels import paths entirely with no deprecation shims. Any downstream code using these paths will break at import time. The author correctly marked backward compat as ❌, but no migration path is provided. At minimum, add __getattr__ deprecation shims in the old __init__.py locations.

  2. Buffer overrun bug in calibrate.py (critical, unresolved): Line 157 uses tl.load(b_seq_len + 0) (batch 0's sequence length) to compute num_q_tiles for the flat program index, but the Python wrapper (line ~243) sizes Per_program_* buffers using max_input_len. When batch 0 has a shorter sequence than other batches, the kernel computes a smaller num_q_tiles, causing prog_idx for later batches to potentially exceed buffer bounds, leading to out-of-bounds writes. This was flagged in the previous review and is still present. Pass max_input_len as a kernel parameter to fix the mismatch.

Comment thread modelopt/torch/kernels/__init__.py
acc = tl.dot(p.to(v.dtype), v, acc)
row_max = m_new

# --- Write per-program counters (no atomics, just stores) ---

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.

Bug (unresolved from previous review): tl.load(b_seq_len + 0) loads batch 0's sequence length to compute num_q_tiles, but the Python wrapper sizes Per_program_totals/Per_program_skipped using max_input_len. If batch 0's seq_len < max_input_len (i.e., another batch is longer), the kernel computes a smaller num_q_tiles, causing prog_idx for later batches to exceed the allocated buffer — out-of-bounds write.

Fix: pass max_input_len as a kernel argument and use it here:

num_q_tiles = tl.cdiv(max_input_len, BLOCK_M)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, but it's not OOB, the buffer is sized by max_input_len, so the stride mismatch causes prog_idx collisions (silent wrong counts), not out-of-bounds. Hasn't fired because every current caller uses uniform-length batches.

Fixed: swap tl.load(b_seq_len + 0) -> tl.num_programs(2), plus a wrapper guard that raises on non-uniform b_seq_len until varlen is validated.

@cjluo-nv cjluo-nv 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.

Two critical issues flagged in previous reviews remain unresolved in this revision:

  1. Buffer overrun bug in calibrate.py (UNRESOLVED): Line 157 still uses tl.load(b_seq_len + 0) (batch 0's sequence length) to compute num_q_tiles for the flat program index. The Python wrapper sizes Per_program_* buffers using max_input_len. The author acknowledged the bug and stated they'd fix it ("swap tl.load(b_seq_len + 0) -> tl.num_programs(2), plus a wrapper guard"), but the code is unchanged.

  2. No backward-compatibility deprecation shims (UNRESOLVED): modelopt/torch/kernels/__init__.py had its public symbols (IS_AVAILABLE, attention, attention_calibrate, register_triton_attention) removed with no __getattr__ deprecation bridge. The old modelopt.torch.quantization.triton package is also gone entirely. The PR correctly marks backward compat as ❌ but provides no migration path for downstream consumers.

Comment thread modelopt/torch/kernels/sparsity/attention/calibrate.py
"attention_calibrate",
"register_triton_attention",
]
"""ModelOpt kernel library: common, quantization (conv, gemm), sparsity (attention, gemm)."""

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.

Critical (unresolved from two prior reviews): The old public symbols (IS_AVAILABLE, attention, attention_calibrate, register_triton_attention) were removed with no deprecation bridge. Any downstream code doing from modelopt.torch.kernels import attention will break.

Please add a __getattr__ shim that re-exports these names from modelopt.torch.kernels.common.attention with a DeprecationWarning, or at minimum document the breaking change with migration guidance in the CHANGELOG.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Mentioned it in the changelog

Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
@jingyu-ml
jingyu-ml requested a review from a team as a code owner April 22, 2026 20:53
@jingyu-ml
jingyu-ml requested a review from Edwardf0t1 April 22, 2026 20:53
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
@jingyu-ml
jingyu-ml requested a review from cjluo-nv April 22, 2026 20:58

@cjluo-nv cjluo-nv 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.

Re-review of the kernel directory reorganization PR. Of the two critical issues from previous reviews:

  1. Buffer overrun in calibrate.py — RESOLVED ✅: tl.load(b_seq_len + 0) has been replaced with tl.num_programs(2), and the Python wrapper now has guards that reject non-uniform-length batches with NotImplementedError. Good fix.

  2. Backward compatibility deprecation shims — STILL UNRESOLVED ❌: The CHANGELOG (line 8) claims "these four names continue to work at the old location via a __getattr__ shim that emits a DeprecationWarning" but no such shim exists in the code. modelopt/torch/kernels/__init__.py is just a docstring with no __getattr__. The old modelopt.torch.quantization.triton package is entirely deleted with no redirect. This is actually worse than before — the documentation now actively lies about backward compatibility that doesn't exist.

"attention_calibrate",
"register_triton_attention",
]
"""ModelOpt kernel library: common, quantization (conv, gemm), sparsity (attention, gemm)."""

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.

Critical (unresolved from three prior reviews): The CHANGELOG claims "these four names continue to work at the old location via a __getattr__ shim that emits a DeprecationWarning" — but this file contains no such shim. from modelopt.torch.kernels import attention will raise ImportError at runtime.

Please either:

  1. Add the __getattr__ shim as described in the CHANGELOG (see the suggested code from previous reviews), or
  2. Remove the claim from the CHANGELOG that a shim exists.

The modelopt.torch.quantization.triton package is also entirely gone with no redirect — any downstream code using that path will break silently.

Comment thread CHANGELOG.rst
Signed-off-by: Jingyu Xin <jingyux@nvidia.com>

@cjluo-nv cjluo-nv 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.

Both critical issues from previous reviews are now resolved:

  1. Buffer overrun in calibrate.py ✅: tl.load(b_seq_len + 0) replaced with tl.num_programs(2), and the Python wrapper guards against non-uniform-length batches with NotImplementedError.

  2. Backward compatibility documentation ✅: The CHANGELOG no longer falsely claims a __getattr__ shim exists. It now honestly states "there is no backwards-compatibility shim" and provides a clear migration table mapping old import paths to new ones.

The reorganization into modelopt/torch/kernels/{common,quantization,sparsity} is clean, all internal import sites are updated, the lazy import pattern in triton_fa.py properly handles the circular dependency, and tests are moved/updated to match.

@jingyu-ml
jingyu-ml enabled auto-merge (squash) April 22, 2026 22:32
@jingyu-ml
jingyu-ml merged commit c796611 into main Apr 22, 2026
47 checks passed
@jingyu-ml
jingyu-ml deleted the jingyux/implicit-gemm-2.1-3 branch April 22, 2026 23:34
grzegorz-k-karch pushed a commit that referenced this pull request Apr 28, 2026
### What does this PR do?

Type of change: re-org code <!-- Use one of the following: Bug fix, new
feature, new example, new tests, documentation. -->

<!-- Details about the change. -->

### Usage

```python
# Add a code snippet demonstrating how to use this
```

### Testing
<!-- Mention how have you tested your change if applicable. -->

### Before your PR is "*Ready for review*"

Make sure you read and follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)
and your commits are signed (`git commit -s -S`).

Make sure you read and follow the [Security Best
Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors)
(e.g. avoiding hardcoded `trust_remote_code=True`, `torch.load(...,
weights_only=False)`, `pickle`, etc.).

- Is this change backward compatible?: ❌ We changed the import path
<!--- If ❌, explain why. -->
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: ✅ <!---
Mandatory -->
- Did you write any new necessary tests?: ❌ <!--- Mandatory for new
features or examples. -->
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:✅
<!--- Only for new features, API changes, critical bug fixes or backward
incompatible changes. -->

### Additional Information
<!-- E.g. related issue. -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Calibration support for skip-softmax multi-threshold measurement in
sparse attention.
  * N:M sparse softmax masking and helpers for sparsity-aware attention.

* **Chores**
* Reorganized and consolidated kernel/backends for quantization and
sparsity to a unified kernels layout, updating tests and examples to
match.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Jingyu Xin <jingyux@nvidia.com>
Signed-off-by: Grzegorz Karch <gkarch@nvidia.com>
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.

4 participants