Skip to content

Conversation

@achartier
Copy link
Collaborator

@achartier achartier commented Aug 11, 2025

Summary by CodeRabbit

  • New Features

    • Support for providing activation scales as a directory, with automatic extraction and inclusion in packaged artifacts across all packaging paths.
  • Bug Fixes

    • Gracefully handle missing per-rank amax files with clear warnings; stop packaging when no valid amax data is available to avoid invalid outputs.
  • Chores

    • Improved messaging and flow control around activation-scale handling and packaging.
  • Notes

    • No changes to public interfaces.

Description

  • Add scales to output safetensors on all ranks
  • Fix file copy to handle directory
  • Add extra checks that amax files exist

Test Coverage

Script with no CI related

GitHub Bot Help

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

Details

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in the stage-list parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.

For guidance on mapping tests to stage names, see docs/source/reference/ci-overview.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip testing for latest commit on pull request. --comment "Reason for skipping build/test" is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

reuse-pipeline

reuse-pipeline

Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

Signed-off-by: Aurelien Chartier <2567591+achartier@users.noreply.github.com>
@achartier achartier requested a review from a team as a code owner August 11, 2025 21:18
@achartier achartier requested a review from kaiyux August 11, 2025 21:18
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 11, 2025

📝 Walkthrough

Walkthrough

The script now checks amax file existence per rank and warns/errors when missing, returns early if none loaded, extracts activation scales via get_scales_from_amax and merges them into new_safetensors, and supports act_scales provided as a directory (copytree/dir processing) across packaging paths.

Changes

Cohort / File(s) Summary
Amax loading, activation scales extraction, and directory handling
examples/quantization/quantize_mixed_precision_moe.py
- Check amax file existence per rank; warn if missing and error/early-return if none loaded
- Load amax files when present and call get_scales_from_amax(...) to obtain activation scales, merging them into new_safetensors
- Treat act_scales directories via copytree/dir processing and include extracted scales in both per-layer and non-layer packaging branches
- Add warnings/errors and flow guards to avoid proceeding with empty state

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant User
  participant Script as quantize_mixed_precision_moe.py
  participant FS as Filesystem
  participant Log as Logger

  User->>Script: Run packaging
  loop For each rank
    Script->>FS: Check amax file exists
    alt Exists
      Script->>FS: Load amax
      Script->>Script: get_scales_from_amax(amaxes)
      Script->>Script: Merge scales into new_safetensors
    else Missing
      Script->>Log: Warn: amax file missing for rank
    end
  end
  alt No amax files loaded
    Script->>Log: Error: no amax loaded
    Script-->>User: Return empty result
  else Proceed
    alt act_scales is directory
      Script->>FS: copytree/process act_scales directory
      Script->>Script: Insert extracted scales into new_safetensors
    else act_scales is file/absent
      Script->>FS: Handle file copy or skip
    end
    Script-->>User: Output packaged safetensors
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33a2744 and b0c4c70.

📒 Files selected for processing (1)
  • examples/quantization/quantize_mixed_precision_moe.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/quantization/quantize_mixed_precision_moe.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@achartier achartier requested a review from Shixiaowei02 August 11, 2025 21:22
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (5)
examples/quantization/quantize_mixed_precision_moe.py (5)

48-65: Fix potential IndexError when some amax files are missing

The current implementation will cause an IndexError if some (but not all) amax files are missing. When files are missing, state_dict_list will have fewer elements than world_size, but the loop at line 60 still iterates over the full range.

Apply this fix to handle partial file loading correctly:

 def load_and_preprocess_state_dict(modelopt_state_root, world_size=8):
-    state_dict_list = []
+    state_dict_list = {}
     # load amax from state dict
     for rank in range(world_size):
         amax_file = f"{modelopt_state_root}/amax_dict_rank{rank}-mp{world_size}.pt"
         if os.path.exists(amax_file):
-            state_dict_list.append(torch.load(amax_file, map_location="cuda:0"))
+            state_dict_list[rank] = torch.load(amax_file, map_location="cuda:0")
         else:
             print(f"WARNING: amax file not found: {amax_file}")
 
     if not state_dict_list:
         print("ERROR: No amax files loaded!")
         return {}
 
     # calculate the max across all TP ranks
-    merged_state_dict = state_dict_list[0]
-    for rank in range(world_size):
-        for key, amax in state_dict_list[rank].items():
+    merged_state_dict = next(iter(state_dict_list.values())).copy()
+    for rank, state_dict in state_dict_list.items():
+        for key, amax in state_dict.items():
             if key in merged_state_dict.items():
                 amax = torch.max(amax.to(0), merged_state_dict[key].to(0))
             merged_state_dict[key] = amax.to(0)

242-323: Refactor to eliminate code duplication for activation scales processing

The activation scales extraction logic is duplicated between rank-0 (lines 242-249) and non-rank-0 (lines 315-322) branches. This violates the DRY principle.

Extract the common logic before the rank check:

+    # Process activation scales for all ranks
+    if os.path.isdir(args.act_scales):
+        # Extract activation scales
+        renamed_state_dict = load_and_preprocess_state_dict(
+            modelopt_state_root=args.act_scales, world_size=8)
+        scales = get_scales_from_amax(start_layer=start_layer,
+                                      end_layer=end_layer,
+                                      renamed_state_dict=renamed_state_dict)
+        new_safetensors.update(scales)
+
     if args.rank == 0:
-        if os.path.isdir(args.act_scales):
-            # Extract activation scales
-            renamed_state_dict = load_and_preprocess_state_dict(
-                modelopt_state_root=args.act_scales, world_size=8)
-            scales = get_scales_from_amax(start_layer=start_layer,
-                                          end_layer=end_layer,
-                                          renamed_state_dict=renamed_state_dict)
-            new_safetensors.update(scales)
-        else:
+        if not os.path.isdir(args.act_scales):
             input_scales = safe_open(args.act_scales, "pt")
             for k in input_scales.keys():
                 new_safetensors.update({k: input_scales.get_tensor(k)})
                 new_json['weight_map'][k] = args.act_scales.split("/")[-1]

         # ... rest of rank-0 specific logic ...
     else:
-        if os.path.isdir(args.act_scales):
-            # Extract activation scales
-            renamed_state_dict = load_and_preprocess_state_dict(
-                modelopt_state_root=args.act_scales, world_size=8)
-            scales = get_scales_from_amax(start_layer=start_layer,
-                                          end_layer=end_layer,
-                                          renamed_state_dict=renamed_state_dict)
-            new_safetensors.update(scales)
-
         file_name = get_file_name(start_layer)

60-64: Fix incorrect dictionary key check

Line 62 incorrectly uses .items() when checking if a key exists in the dictionary.

     for rank in range(world_size):
         for key, amax in state_dict_list[rank].items():
-            if key in merged_state_dict.items():
+            if key in merged_state_dict:
                 amax = torch.max(amax.to(0), merged_state_dict[key].to(0))
             merged_state_dict[key] = amax.to(0)

66-78: Remove duplicate keys in mapping dictionary

The mapping dictionary has duplicate keys for "ffn.shared_experts" (lines 70-72), which means only the last value will be retained.

     mapping = {
         "ffn.shared_experts.w1": "mlp.shared_experts.gate_proj",
         "ffn.shared_experts.w2": "mlp.shared_experts.down_proj",
         "ffn.shared_experts.w3": "mlp.shared_experts.up_proj",
-        "ffn.shared_experts": "mlp.shared_experts",
-        "ffn.shared_experts": "mlp.shared_experts",
-        "ffn.shared_experts": "mlp.shared_experts",
         "ffn.w1": "mlp.gate_proj",
         "ffn.w2": "mlp.down_proj",
         "ffn.w3": "mlp.up_proj",
         "head": "lm_head",
         "attn": "self_attn",
     }

288-288: Use num_layer variable instead of hardcoded value

Line 288 uses a hardcoded value of 61 for the layer count, which should use the num_layer variable for consistency and maintainability.

-        for l in range(61):
+        for l in range(num_layer):
🧹 Nitpick comments (2)
examples/quantization/quantize_mixed_precision_moe.py (2)

269-272: Consider preserving the directory structure more explicitly

The current implementation copies the entire act_scales directory into output_dir. This might create an unexpected nested structure if act_scales has a complex path.

Consider copying to a specific subdirectory or just the contents:

 if os.path.isdir(args.act_scales):
-    shutil.copytree(args.act_scales, output_dir, dirs_exist_ok=True)
+    # Option 1: Copy to a specific subdirectory
+    act_scales_dest = os.path.join(output_dir, "act_scales")
+    shutil.copytree(args.act_scales, act_scales_dest, dirs_exist_ok=True)
+    # Option 2: Copy only the contents (if you want flat structure)
+    # for item in os.listdir(args.act_scales):
+    #     src = os.path.join(args.act_scales, item)
+    #     dst = os.path.join(output_dir, item)
+    #     if os.path.isdir(src):
+    #         shutil.copytree(src, dst, dirs_exist_ok=True)
+    #     else:
+    #         shutil.copy2(src, dst)
 else:
     shutil.copy(args.act_scales, output_dir)

52-56: Consider using Python's logging module instead of print statements

For better logging control and production readiness, consider using Python's logging module.

Add at the top of the file:

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

Then replace print statements:

-            print(f"WARNING: amax file not found: {amax_file}")
+            logger.warning(f"amax file not found: {amax_file}")

     if not state_dict_list:
-        print("ERROR: No amax files loaded!")
+        logger.error("No amax files loaded!")
         return {}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c9fe07e and 33a2744.

📒 Files selected for processing (1)
  • examples/quantization/quantize_mixed_precision_moe.py (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code should conform to Python 3.8+.
Indent Python code with 4 spaces. Do not use tabs.
Always maintain the namespace when importing in Python, even if only one class or function from a module is used.
Python filenames should use snake_case (e.g., some_file.py).
Python classes should use PascalCase (e.g., class SomeClass).
Python functions and methods should use snake_case (e.g., def my_awesome_function():).
Python local variables should use snake_case. Prefix k for variable names that start with a number (e.g., k_99th_percentile).
Python global variables should use upper snake_case and prefix G (e.g., G_MY_GLOBAL).
Python constants should use upper snake_case (e.g., MY_CONSTANT).
Avoid shadowing variables declared in an outer scope in Python.
Initialize all externally visible members of a Python class in the constructor.
For interfaces that may be used outside a Python file, prefer docstrings over comments.
Comments in Python should be reserved for code within a function, or interfaces that are local to a file.
Use Google style docstrings for Python classes and functions, which can be parsed by Sphinx.
Attributes and variables in Python can be documented inline; attribute docstrings will be rendered under the class docstring.
Avoid using reflection in Python when functionality can be easily achieved without it.
When using try-except blocks in Python, limit the except to the smallest set of errors possible.
When using try-except blocks to handle multiple possible variable types in Python, keep the body of the try as small as possible, using the else block to implement the logic.

Files:

  • examples/quantization/quantize_mixed_precision_moe.py
**/*.{cpp,h,hpp,cc,cxx,cu,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the current year. This includes .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.

Files:

  • examples/quantization/quantize_mixed_precision_moe.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (1)
examples/quantization/quantize_mixed_precision_moe.py (1)

246-249: LGTM! Proper extraction and inclusion of activation scales.

The code correctly extracts activation scales from the preprocessed state dict and merges them into the output safetensors.

@achartier achartier changed the title Fix script when using calibration tensors from modelopt [#6530][fix] Fix script when using calibration tensors from modelopt Aug 11, 2025
Signed-off-by: Aurelien Chartier <2567591+achartier@users.noreply.github.com>
Copy link
Collaborator

@Barry-Delaney Barry-Delaney left a comment

Choose a reason for hiding this comment

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

LGTM.

@achartier
Copy link
Collaborator Author

/bot skip --comment "Changes on script with no CI related"

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15057 [ skip ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15057 [ skip ] completed with state SUCCESS
Skipping testing for commit b0c4c70

@achartier achartier merged commit 2e0081b into NVIDIA:main Aug 13, 2025
5 checks passed
@achartier achartier deleted the fix-6530 branch August 13, 2025 03:41
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