Skip to content

Conversation

dmtri35
Copy link

@dmtri35 dmtri35 commented Oct 10, 2025

Currently works with GLM 4.6 (bf16 / fp4) with MTP
Launch with trtllm-serve $FP4_CKPT --tp_size 8 --ep_size 4 --extra_llm_api_options glm.yaml

kv_cache_config:
    free_gpu_memory_fraction: 0.8
enable_chunked_prefill: true
max_batch_size: 16
moe_config:
    backend: CUTLASS
speculative_config:
    decoding_type: MTP
    num_nextn_predict_layers: 3

The architecture is basically DeepSeekV3 with QKNormAttention. I did have to disable fuse_routing_kernel (fix hanging issues) and fuse_qk_norm_rope (fix trash outputs).

@coderabbitai summary

Description

Test Coverage

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

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.

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.

@dmtri35 dmtri35 requested review from a team as code owners October 10, 2025 04:29
@dmtri35 dmtri35 requested review from 2ez4bz and mikeiovine October 10, 2025 04:29
Copy link
Contributor

coderabbitai bot commented Oct 10, 2025

📝 Walkthrough

Walkthrough

Introduces GLM4 MoE causal LM implementation with new attention, decoder, MoE, MTP, and model wrapper; exposes Glm4MoeForCausalLM publicly. Adjusts speculative MTP layer selection by model_type. Adds aux CUDA stream plumbed into QK-Norm+RoPE attention. Improves weight-loading error messages with contextual KeyError wrapping.

Changes

Cohort / File(s) Summary
GLM4 MoE model integration
tensorrt_llm/_torch/models/modeling_glm.py
Adds GLM4 components: Glm4Attention, Glm4MoE, Glm4DecoderLayer, Glm4MTP, Glm4Model, and Glm4MoeForCausalLM with MoE routing, TP sizing, quant overrides, weight load/post-load remapping, and registration.
Public export
tensorrt_llm/_torch/models/__init__.py
Exports Glm4MoeForCausalLM by importing from .modeling_glm and updating __all__.
Speculative decoding selection
tensorrt_llm/_torch/models/modeling_speculative.py
Chooses MTP layer class by model_type (glm4_moe → Glm4MTP, deepseekv3 → DeepseekV3MTP); raises error for unsupported types.
Attention aux stream plumbed
tensorrt_llm/_torch/modules/qk_norm_attention.py
Adds aux_stream parameter to QKNormRoPEAttention.__init__; uses provided stream instead of always creating a new one.
Weight-loading diagnostics
tensorrt_llm/_torch/models/modeling_utils.py
Wraps module load_weights calls in try/except to rethrow KeyError with module context in non-PP and related paths.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant M as Glm4MoeForCausalLM
  participant Core as Glm4Model
  participant L as Glm4DecoderLayer[n]
  participant Attn as Glm4Attention
  participant MoE as Glm4MoE
  participant MLP as MLP

  U->>M: forward(input_ids, ... )
  M->>Core: forward(...)
  loop for each layer
    Core->>L: forward(hidden_states, ... )
    L->>Attn: attend(qk-norm + RoPE, aux_stream)
    Attn-->>L: attn_output
    alt layer is MoE-enabled
      L->>MoE: route(attn_output)
      MoE-->>L: moe_output
      L-->>Core: residual + norm(moe_output)
    else
      L->>MLP: mlp(attn_output)
      MLP-->>L: mlp_output
      L-->>Core: residual + norm(mlp_output)
    end
  end
  Core-->>M: final_hidden_states
  M-->>U: logits
  note over MoE,L: Routing, expert exec, optional shared expert TP
Loading
sequenceDiagram
  autonumber
  participant MC as ModelConfig
  participant Spec as MTPForCausalLM
  MC-->>Spec: model_type
  alt model_type == "glm4_moe"
    Spec->>Spec: mtp_layer = Glm4MTP
  else model_type == "deepseekv3"
    Spec->>Spec: mtp_layer = DeepseekV3MTP
  else
    Spec->>Spec: raise ValueError
  end
  Spec->>Spec: self.mtp_layers = ModuleList(mtp_layer(...))
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The PR description retains the template structure but never replaces placeholder sections with actual content. It lacks the required title line, a filled “Description” section explaining the issue and solution, and a “Test Coverage” section detailing relevant tests. The only content present is a brief usage note and placeholders, so it does not fulfill the repository’s description template requirements. Please add a proper title following the repository’s template, populate the “Description” section with a concise explanation of the change and its rationale, and provide a “Test Coverage” section listing relevant tests, and ensure the PR checklist items are appropriately completed.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title “[None][feat] Support Glm4MoeForCausalLM” directly reflects the main change of adding support for the Glm4MoeForCausalLM model, making it clear and specific for reviewers and maintainers. It is a concise, single‐sentence description of the primary feature introduced by the PR. Despite the tag prefix, the core message remains focused and understandable.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • 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

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

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: 4

🧹 Nitpick comments (3)
tensorrt_llm/_torch/models/__init__.py (1)

10-10: Public export looks good; optional: keep all ordering consistent with imports.

Importing and exporting Glm4MoeForCausalLM is correct. For readability, consider placing "Glm4MoeForCausalLM" in all to mirror the import order comment suggests.

Also applies to: 72-72

tensorrt_llm/_torch/models/modeling_utils.py (1)

886-890: Good contextual KeyError wrapping; apply same to manual-copy path for consistency.

You wrapped module.load_weights calls to surface module name on KeyError. Do the same for the manual parameter copy path to keep diagnostics uniform.

Apply this diff:

                 else:
-                    for n, p in module._parameters.items():
-                        if p is not None:
-                            p.data.copy_(module_weights[n][:])
+                    try:
+                        for n, p in module._parameters.items():
+                            if p is not None:
+                                p.data.copy_(module_weights[n][:])
+                    except KeyError as key_err:
+                        raise KeyError(f"{key_err} in module {name}") from key_err

Also applies to: 894-899

tensorrt_llm/_torch/models/modeling_glm.py (1)

871-898: Minor: avoid shadowing self.model_nextn.

The local model_nextn shadows the attribute set above. Consider assigning to self.model_nextn and then using it to avoid confusion.

-            model_nextn = model_config.spec_config.num_nextn_predict_layers
+            self.model_nextn = model_config.spec_config.num_nextn_predict_layers
@@
-                            self.num_hidden_layers + model_nextn):
-                        ckpt_mtp_idx = (model_mtp_idx - self.num_hidden_layers
-                                        ) % ckpt_nextn + self.num_hidden_layers
+                            self.num_hidden_layers + self.model_nextn):
+                        ckpt_mtp_idx = ((model_mtp_idx - self.num_hidden_layers)
+                                        % ckpt_nextn) + self.num_hidden_layers
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 76a47c7 and 7858c82.

📒 Files selected for processing (5)
  • tensorrt_llm/_torch/models/__init__.py (2 hunks)
  • tensorrt_llm/_torch/models/modeling_glm.py (1 hunks)
  • tensorrt_llm/_torch/models/modeling_speculative.py (2 hunks)
  • tensorrt_llm/_torch/models/modeling_utils.py (1 hunks)
  • tensorrt_llm/_torch/modules/qk_norm_attention.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use only spaces, no tabs; indent with 4 spaces.

Files:

  • tensorrt_llm/_torch/models/__init__.py
  • tensorrt_llm/_torch/models/modeling_speculative.py
  • tensorrt_llm/_torch/modules/qk_norm_attention.py
  • tensorrt_llm/_torch/models/modeling_utils.py
  • tensorrt_llm/_torch/models/modeling_glm.py
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.

Files:

  • tensorrt_llm/_torch/models/__init__.py
  • tensorrt_llm/_torch/models/modeling_speculative.py
  • tensorrt_llm/_torch/modules/qk_norm_attention.py
  • tensorrt_llm/_torch/models/modeling_utils.py
  • tensorrt_llm/_torch/models/modeling_glm.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).

Files:

  • tensorrt_llm/_torch/models/__init__.py
  • tensorrt_llm/_torch/models/modeling_speculative.py
  • tensorrt_llm/_torch/modules/qk_norm_attention.py
  • tensorrt_llm/_torch/models/modeling_utils.py
  • tensorrt_llm/_torch/models/modeling_glm.py
🧬 Code graph analysis (5)
tensorrt_llm/_torch/models/__init__.py (1)
tensorrt_llm/_torch/models/modeling_glm.py (1)
  • Glm4MoeForCausalLM (864-961)
tensorrt_llm/_torch/models/modeling_speculative.py (2)
tensorrt_llm/_torch/models/modeling_glm.py (1)
  • Glm4MTP (662-799)
tensorrt_llm/_torch/models/modeling_deepseekv3.py (1)
  • DeepseekV3MTP (1254-1391)
tensorrt_llm/_torch/modules/qk_norm_attention.py (1)
tensorrt_llm/_torch/attention_backend/interface.py (1)
  • PositionalEmbeddingParams (506-524)
tensorrt_llm/_torch/models/modeling_utils.py (6)
tensorrt_llm/_torch/models/modeling_glm.py (1)
  • load_weights (920-932)
tensorrt_llm/_torch/modules/linear.py (2)
  • load_weights (230-242)
  • load_weights (2002-2006)
tensorrt_llm/_torch/models/modeling_deepseekv3.py (3)
  • load_weights (146-394)
  • load_weights (683-690)
  • load_weights (1526-1528)
tests/unittest/_torch/modules/test_fused_moe.py (1)
  • load_weights (2235-2300)
tensorrt_llm/_torch/models/checkpoints/base_weight_mapper.py (1)
  • filter_weights (143-149)
tensorrt_llm/_torch/models/checkpoints/hf/llama4_weight_mapper.py (1)
  • filter_weights (13-22)
tensorrt_llm/_torch/models/modeling_glm.py (14)
tensorrt_llm/models/modeling_utils.py (4)
  • PretrainedConfig (366-567)
  • QuantConfig (128-268)
  • quant_algo (547-548)
  • is_module_excluded_from_quantization (234-247)
tensorrt_llm/_utils.py (1)
  • is_sm_100f (695-698)
tensorrt_llm/quantization/mode.py (2)
  • QuantAlgo (23-47)
  • is_int4_weight_only_per_group (136-137)
tensorrt_llm/quantization/utils/fp8_utils.py (2)
  • resmooth_to_fp8_e8m0 (82-92)
  • transform_sf_into_required_layout (169-217)
tensorrt_llm/_torch/attention_backend/interface.py (3)
  • AttentionMetadata (40-336)
  • PositionalEmbeddingParams (506-524)
  • RopeParams (350-502)
tensorrt_llm/_torch/distributed/ops.py (2)
  • AllReduce (442-590)
  • MoEAllReduce (593-681)
tensorrt_llm/_torch/modules/embedding.py (1)
  • Embedding (184-266)
tensorrt_llm/_torch/modules/fused_moe/interface.py (1)
  • MoEWeightLoadingMode (16-22)
tensorrt_llm/_torch/modules/fused_moe/create_moe.py (1)
  • create_moe (61-211)
tensorrt_llm/_torch/modules/gated_mlp.py (1)
  • GatedMLP (19-182)
tensorrt_llm/_torch/modules/linear.py (9)
  • Linear (1787-2009)
  • TensorParallelMode (45-57)
  • forward (1971-2000)
  • has_nvfp4 (1906-1909)
  • load_weights (230-242)
  • load_weights (2002-2006)
  • post_load_weights (244-245)
  • post_load_weights (2008-2009)
  • has_fp8_block_scales (1900-1903)
tensorrt_llm/_torch/modules/multi_stream_utils.py (1)
  • maybe_execute_in_parallel (35-74)
tensorrt_llm/_torch/utils.py (1)
  • Fp4QuantizedTensor (100-107)
tensorrt_llm/_torch/models/modeling_deepseekv3.py (3)
  • DeepseekV3Gate (635-701)
  • DeepseekV3MTPHead (397-451)
  • moe_reduce_add_shared_output (133-135)
🪛 Ruff (0.13.3)
tensorrt_llm/_torch/models/modeling_speculative.py

353-353: Avoid specifying long messages outside the exception class

(TRY003)

tensorrt_llm/_torch/modules/qk_norm_attention.py

159-159: Do not perform function call torch.cuda.Stream in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

tensorrt_llm/_torch/models/modeling_utils.py

890-890: Avoid specifying long messages outside the exception class

(TRY003)


897-898: Avoid specifying long messages outside the exception class

(TRY003)

tensorrt_llm/_torch/models/modeling_glm.py

2-2: Comment contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF003)


84-85: Avoid specifying long messages outside the exception class

(TRY003)


123-123: Do not perform function call ModelConfig in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)


150-150: Comment contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF003)


150-150: Comment contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF003)


150-150: Comment contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF003)


150-150: Comment contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF003)


446-446: Docstring contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF002)


447-447: Docstring contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF002)


838-838: Unused method argument: kwargs

(ARG002)


841-843: Avoid specifying long messages outside the exception class

(TRY003)

🔇 Additional comments (1)
tensorrt_llm/_torch/models/modeling_speculative.py (1)

343-354: Remove Python-3.8 compatibility suggestion: project requires Python ≥ 3.10
setup.py’s python_requires=">=3.10" and classifiers include Python 3.10+, so match/case is supported.

Likely an incorrect or invalid review comment.

@@ -0,0 +1,961 @@
# --------------------------------------------------
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add NVIDIA Apache-2.0 header to new source file.

Prepend the standard NVIDIA SPDX header to comply with repo policy. Keep the existing third‑party MIT notice below it.

As per coding guidelines.

+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
 # --------------------------------------------------
 # Portions of this code were derived from DeepSeek‑V3:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# --------------------------------------------------
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# --------------------------------------------------
# Portions of this code were derived from DeepSeek-V3:
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/models/modeling_glm.py at lines 1 to 1, the new source
file is missing the required NVIDIA Apache-2.0 SPDX header; prepend the standard
NVIDIA Apache-2.0 header (including SPDX-License-Identifier: Apache-2.0 and the
full NVIDIA copyright/notice block used across the repo) at the top of the file
and leave the existing third-party MIT notice intact below it so both headers
appear in order.

@juney-nvidia juney-nvidia requested review from QiJune and yuxianq and removed request for 2ez4bz October 10, 2025 04:54
@juney-nvidia
Copy link
Collaborator

Hi @mikeiovine @QiJune @yuxianq

Can you help review this PR contributed by the community?

Thanks
June

@svc-trtllm-gh-bot svc-trtllm-gh-bot added the Community want to contribute PRs initiated from Community label Oct 10, 2025
self.self_attn = Glm4Attention(
model_config,
layer_idx=layer_idx_for_attention,
fuse_qk_norm_rope=False,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is this related to the fused_add_rms_norm flashinfer hang? or it's the air/4.5/4.6 no qk_norm in attention. Thanks!

Copy link
Collaborator

Choose a reason for hiding this comment

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

Also, is this the only diff between modeling_deepseek.py and modeling_glm? Thanks!

Copy link
Author

Choose a reason for hiding this comment

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

fuse_qk_norm_rope=False is for quality, putting it to default true makes it generate trash

For the hanging, disabling moe routing kernel fusion fixed it

@jhaotingc
Copy link
Collaborator

Thanks @dmtri35, I'm cloning the weights of GLM listed below for testing. What ckpts does this PR supports? And you mentioned nvfp4? Thank you!

zai-org/GLM-4.5-Air
zai-org/GLM-4.6
zai-org/GLM-4.6-FP8

@dmtri35
Copy link
Author

dmtri35 commented Oct 13, 2025

  • it support zai-org/GLM-4.6 and zai-org/GLM-4.5, and yes it does support fp4 (we quantized only the mlp and keep the attention + mlp in bf16).
  • for fp8 we would at least need to use modelopt
  • for zai-org/GLM-4.5-Air, we need to support non qknorm attention (doable just work)

@dmtri35
Copy link
Author

dmtri35 commented Oct 13, 2025

@jhaotingc When running it there are a couple gotchas if you use trtllm-serve, you need to add the stop_token_ids in the generation config to the request or it won't stop generating: https://huggingface.co/zai-org/GLM-4.6/blob/main/generation_config.json

@jhaotingc
Copy link
Collaborator

Thanks a lot, I'll test zai-org/GLM-4.6 zai-org/GLM-4.5 as well as nvfp4 ckpt through modelopt.

root and others added 11 commits October 13, 2025 19:29
Signed-off-by: root <root@tridao-dev-pod-h100-0.tridao-dev-pod-h100.baseten.svc.cluster.local>
Signed-off-by: Tri Dao <[email protected]>
Signed-off-by: Tri Dao <[email protected]>
Signed-off-by: Tri Dao <[email protected]>
Signed-off-by: Tri Dao <[email protected]>
Signed-off-by: Tri Dao <[email protected]>
Signed-off-by: Tri Dao <[email protected]>
Signed-off-by: Tri Dao <[email protected]>
@dmtri35 dmtri35 requested a review from a team as a code owner October 13, 2025 22:36
@dmtri35 dmtri35 requested a review from a team as a code owner October 13, 2025 22:36
@jhaotingc
Copy link
Collaborator

/bot run --disable-fail-fast

@jhaotingc jhaotingc self-requested a review October 14, 2025 17:08
@jhaotingc jhaotingc changed the title Support Glm4MoeForCausalLM [None][feat] Support Glm4MoeForCausalLM Oct 14, 2025
@jhaotingc jhaotingc dismissed their stale review October 14, 2025 17:30

Dismissing my change request.

Signed-off-by: Tri Dao <[email protected]>
@jhaotingc
Copy link
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21389 [ run ] triggered by Bot

Signed-off-by: Tri Dao <[email protected]>
@tensorrt-cicd
Copy link
Collaborator

PR_Github #21389 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #16154 completed with status: 'FAILURE'

@@ -0,0 +1,961 @@
# --------------------------------------------------
# Portions of this code were derived from DeepSeek‑V3:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Which DeepSeek‑V3 file do you port from? If you have rewritten the modeling code using TRT-LLM API, we can remove the license header, which indicates this file uses the default Apache license.

disable_deep_gemm: bool = False,
use_gemma_rms_norm: bool = False,
attn_output_gate: Optional[bool] = None,
aux_stream: Optional[torch.cuda.Stream] = None,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is it necessary to pass aux_stream from Glm4Model? Can we use a new aux_stream for each QKNormRoPEAttention like other models?

max_position_embeddings=config.max_position_embeddings,
bias=config.attention_bias,
pos_embd_params=pos_embd_params,
fuse_qk_norm_rope=fuse_qk_norm_rope,
Copy link
Collaborator

Choose a reason for hiding this comment

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

We can remove fuse_qk_norm_rope argument and use fuse_qk_norm_rope=False here if it can only be False in your case.

):
config = model_config.pretrained_config

if getattr(config, "rope_scaling", None) is not None:
Copy link
Collaborator

Choose a reason for hiding this comment

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

GLM-4.6 uses "rope_scaling": null, is it necessary to support the not-none case here?

# DS-R1 W4A8 is only supported through custom quantization script from
# examples/quantization/quantize_mixed_precision_moe.py
weight_loading_mode=(
MoEWeightLoadingMode.W4A8_CUSTOM
Copy link
Collaborator

Choose a reason for hiding this comment

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

If GLM4 does not support W4A8 checkpoint, we can directly use MoEWeightLoadingMode.VANILLA

def _compute_mlp_tp_size(self, intermediate_size: int,
block_size: int) -> int:
"""
For DeepSeek‑R1, MLP TP size is limited by intermediate_size // block_size
Copy link
Collaborator

Choose a reason for hiding this comment

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

replace "DeepSeek‑R1" with "GLM4"

self, intermediate_size: int,
block_size: int) -> tuple[int, float | None]:
"""
In the case of Deepseek-R1, the TP size of MLP is capped by intermediate_size // block_size.
Copy link
Collaborator

Choose a reason for hiding this comment

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

replace "DeepSeek‑R1" with "GLM4"

override_quant_config=override_quant_config,
aux_stream_dict=aux_stream_dict,
layer_idx=layer_idx,
# DS-R1 W4A8 is only supported through custom quantization script from
Copy link
Collaborator

Choose a reason for hiding this comment

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

Replace all DeepSeek R1 related comments


self.fusion_config = EagerFusionConfig()
self.enable_fusion = os.environ.get(
"TRTLLM_DEEPSEEK_EAGER_FUSION_DISABLED", "0") == "0"
Copy link
Collaborator

Choose a reason for hiding this comment

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

Use TRTLLM_GLM_EAGER_FUSION_DISABLED instead of TRTLLM_DEEPSEEK_EAGER_FUSION_DISABLED

Args:
intermediate_size (int): MLP intermediate size.
block_size (int): The quantization block scale size. In the case of Deepseek FP8 recipe,
it's 128. For NVFP4, it's 16.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is it true for GLM4? Does GLM4 use block-scale fp8 like DeepSeek?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Can you add at least one e2e test for GLM-4.6 fp4 with MTP into test_llm_api_pytorch.py like DeepSeek R1 (see

def test_nvfp4_multi_gpus(self, tp_size, pp_size, ep_size, mtp_nextn, fp8kv,
)? Then you can run this test like pytest -s -o log_cli=true "accuracy/test_llm_api_pytorch.py::TestGLM4_6::test_nvfp4_multi_gpus[throughput]". Please also add this test to QA list tests/integration/test_lists/qa/llm_function_core.txt, so that we can cover it in the QA cycle.

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

Labels

Community want to contribute PRs initiated from Community

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants