-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[None][feat] Support Glm4MoeForCausalLM #8256
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
📝 WalkthroughWalkthroughIntroduces 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
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
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(...))
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Tip 📝 Customizable high-level summaries are now available in beta!You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.
Example instruction:
Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later. 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. Comment |
There was a problem hiding this 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_errAlso applies to: 894-899
tensorrt_llm/_torch/models/modeling_glm.py (1)
871-898: Minor: avoid shadowingself.model_nextn.The local
model_nextnshadows the attribute set above. Consider assigning toself.model_nextnand 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
📒 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__.pytensorrt_llm/_torch/models/modeling_speculative.pytensorrt_llm/_torch/modules/qk_norm_attention.pytensorrt_llm/_torch/models/modeling_utils.pytensorrt_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__.pytensorrt_llm/_torch/models/modeling_speculative.pytensorrt_llm/_torch/modules/qk_norm_attention.pytensorrt_llm/_torch/models/modeling_utils.pytensorrt_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__.pytensorrt_llm/_torch/models/modeling_speculative.pytensorrt_llm/_torch/modules/qk_norm_attention.pytensorrt_llm/_torch/models/modeling_utils.pytensorrt_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’spython_requires=">=3.10"and classifiers include Python 3.10+, somatch/caseis supported.Likely an incorrect or invalid review comment.
|
Hi @mikeiovine @QiJune @yuxianq Can you help review this PR contributed by the community? Thanks |
|
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 |
|
|
@jhaotingc When running it there are a couple gotchas if you use |
|
Thanks a lot, I'll test |
|
/bot run --disable-fail-fast |
|
/bot run --disable-fail-fast |
|
PR_Github #21389 [ run ] triggered by Bot |
|
PR_Github #21389 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #24222 [ run ] triggered by Bot. Commit: |
|
PR_Github #24222 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #24262 [ run ] triggered by Bot. Commit: |
mikeiovine
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Signing off on spec dec changes
|
PR_Github #24262 [ run ] completed with state |
Signed-off-by: Tri Dao <[email protected]>
|
/bot run --disable-fail-fast |
|
PR_Github #24358 [ run ] triggered by Bot. Commit: |
|
PR_Github #24358 [ run ] completed with state |
|
/bot run |
|
PR_Github #24487 [ run ] triggered by Bot. Commit: |
|
PR_Github #24487 [ run ] completed with state |
|
/bot run |
|
PR_Github #24613 [ run ] triggered by Bot. Commit: |
|
PR_Github #24613 [ run ] completed with state |
|
Not in the |
|
Oh and BTW for the |
|
@videodanchik I just checked, seems like the rope type there doesn't do anything. Adding yarn would make it output trash. Regarding the GLM air support, I have actually made it worked before (look at my git commits) but let's do that in a later PR, this is getting quite big already |
|
@dmtri35, sorry, but with all respect, your current implementation is incorrect for the Anyway, I will leave it to rewievers to decide. |
@videodanchik Well I said in the past when I inherited directly from this is the commit I was referencing: e28f220 |
Superjomn
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
|
@videodanchik @dmtri35 Let's add support for GLM-4.5-Air in a follow-up PR. If fixing it in this PR, we need to add tests for GLM-4.5-Air to validate the implementation, which will make this PR more long-standing (additional 1~2 weeks). |
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.yamlThe architecture is basically DeepSeekV3 with QKNormAttention. I did have to disable
fuse_routing_kernel(fix hanging issues) andfuse_qk_norm_rope(fix trash outputs).Currently supported Glm4MoeForCausalLM with
use_qk_norm: Trueincluding GLM 4.5 and GLM 4.6@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 thestage-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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.