Skip to content

Conversation

@dmtri35
Copy link
Contributor

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

Currently supported Glm4MoeForCausalLM with use_qk_norm: True including 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 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
@coderabbitai
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 lacks required template sections. While a brief intro mentions GLM 4.6 support and configuration, the formal 'Description' and 'Test Coverage' sections are completely empty. Fill in the 'Description' section explaining what the Glm4MoeForCausalLM implementation does and why. Provide specific test cases in 'Test Coverage' demonstrating the changes work correctly for GLM 4.5/4.6 models.
✅ 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

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.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

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.

❤️ 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.

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

@dmtri35 dmtri35 requested review from a team as code owners 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.

@jhaotingc
Copy link
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21389 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@yuxianq
Copy link
Collaborator

yuxianq commented Nov 12, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24222 [ run ] triggered by Bot. Commit: b1f0e30

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24222 [ run ] completed with state SUCCESS. Commit: b1f0e30
/LLM/main/L0_MergeRequest_PR pipeline #18268 completed with status: 'FAILURE'

@yuxianq
Copy link
Collaborator

yuxianq commented Nov 12, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24262 [ run ] triggered by Bot. Commit: b1f0e30

Copy link
Collaborator

@mikeiovine mikeiovine left a 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

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24262 [ run ] completed with state FAILURE. Commit: b1f0e30
/LLM/main/L0_MergeRequest_PR pipeline #18303 completed with status: 'FAILURE'

@yuxianq
Copy link
Collaborator

yuxianq commented Nov 13, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24358 [ run ] triggered by Bot. Commit: 6eee173

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24358 [ run ] completed with state SUCCESS. Commit: 6eee173
/LLM/main/L0_MergeRequest_PR pipeline #18383 completed with status: 'FAILURE'

@nvxuanyuc
Copy link
Collaborator

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24487 [ run ] triggered by Bot. Commit: 6eee173

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24487 [ run ] completed with state SUCCESS. Commit: 6eee173
/LLM/main/L0_MergeRequest_PR pipeline #18481 completed with status: 'FAILURE'

@nvxuanyuc
Copy link
Collaborator

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24613 [ run ] triggered by Bot. Commit: 6eee173

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24613 [ run ] completed with state SUCCESS. Commit: 6eee173
/LLM/main/L0_MergeRequest_PR pipeline #18579 completed with status: 'SUCCESS'

@yuxianq yuxianq requested a review from Superjomn November 17, 2025 01:39
@videodanchik
Copy link

Hey @dmtri35, thanks for this implementation, I was working on a GLM-4.5/4.6 myself a bit and I was wondering if this line should also be changed to elif config.model_type in ("deepseek_v3", "glm4_moe"):?

@dmtri35
Copy link
Contributor Author

dmtri35 commented Nov 17, 2025

Hey @dmtri35, thanks for this implementation, I was working on a GLM-4.5/4.6 myself a bit and I was wondering if this line should also be changed to elif config.model_type in ("deepseek_v3", "glm4_moe"):?

Does GLM do yarn? IIRC it doesn't

@videodanchik
Copy link

videodanchik commented Nov 17, 2025

Not in the transformers implementation, but here you are using it explicitly.

class Glm4Attention(QKNormRoPEAttention):
    def __init__(
        self,
        model_config: ModelConfig[PretrainedConfig],
        layer_idx: Optional[int] = None,
    ):
        config = model_config.pretrained_config
        pos_embd_params = PositionalEmbeddingParams(
            type=PositionEmbeddingType.yarn,
            rope=RopeParams.from_config(config),
        )

        super().__init__(
            hidden_size=config.hidden_size,
            num_attention_heads=config.num_attention_heads,
            num_key_value_heads=config.num_key_value_heads,
            max_position_embeddings=config.max_position_embeddings,
            bias=config.attention_bias,
            pos_embd_params=pos_embd_params,
            fuse_qk_norm_rope=False,
            layer_idx=layer_idx,
            dtype=config.torch_dtype,
            dense_bias=False,
            config=model_config,
        )

@videodanchik
Copy link

videodanchik commented Nov 17, 2025

Oh and BTW for the GLM-4.5-Air you should inherit Glm4Attention from Attention, because in the HuggingFace config it is "use_qk_norm": false,

@nvxuanyuc nvxuanyuc removed their request for review November 18, 2025 00:08
@dmtri35
Copy link
Contributor Author

dmtri35 commented Nov 18, 2025

@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

@videodanchik
Copy link

videodanchik commented Nov 18, 2025

@dmtri35, sorry, but with all respect, your current implementation is incorrect for the GLM-4.5-Air, you just got lucky that it works somehow with qk normalization. I tried and it still produces more or less meaninful, but generally broken ouput with repeated words etc. Also changing the scaling type to yarn doesn't make any trash output for me, while inferencing GLM-4.6 and I'm using your PR.

m='zai-org/GLM-4.6'
llm = LLM(model=m, max_batch_size=1)
messages = [{"role": "user", "content": "Give me a short introduction to general relativity. /nothink"}]
tokenizer = AutoTokenizer.from_pretrained(m, trust_remote_code=True)

text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
sampling_params = SamplingParams(stop_token_ids=[151329, 151336, 151338])

for output in llm.generate([text], sampling_params, use_tqdm=False):
    print(f"Prompt: {output.prompt!r}, \nGenerated text: {output.outputs[0].text}")

Anyway, I will leave it to rewievers to decide.

@dmtri35
Copy link
Contributor Author

dmtri35 commented Nov 18, 2025

your current implementation is incorrect for the GLM-4.5-Air, you just got lucky that it works somehow with qk normalization.

@videodanchik Well I said in the past when I inherited directly from Attention and not QKNormAttention. Feel free to message me over at [email protected] to discuss more.

this is the commit I was referencing: e28f220

Copy link
Collaborator

@Superjomn Superjomn left a comment

Choose a reason for hiding this comment

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

LGTM

@yuxianq
Copy link
Collaborator

yuxianq commented Nov 18, 2025

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

@yuxianq yuxianq merged commit fc088e6 into NVIDIA:main Nov 18, 2025
7 checks passed
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.