Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions tensorrt_llm/_torch/pyexecutor/config_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,48 @@ def __getitem__(self, key):
) # NOTE: HF config.json uses deepseek_v32 as model_type but with same DSV3 config class


def _relax_llama_validate_architecture() -> None:
"""Honor explicit `head_dim` in transformers 5.x LlamaConfig validation.

transformers 5.5.x LlamaConfig.validate_architecture rejects any config
where `hidden_size % num_attention_heads != 0`, ignoring an explicit
`head_dim` that decouples q/k/v projection size from `hidden_size`
(e.g. kakaocorp/kanana-1.5-2.1b: hidden_size=1792, num_attention_heads=24,
head_dim=128). The check is too strict; downstream TRT-LLM code already
honors `head_dim`. Idempotent.

The huggingface_hub @strict decorator captures validators into
``cls.__class_validators__`` at class-definition time, so we must replace
the entry in that list — overwriting ``LlamaConfig.validate_architecture``
alone is not enough.
"""
try:
from transformers.models.llama.configuration_llama import LlamaConfig
except ImportError:
return

if getattr(LlamaConfig.validate_architecture, "_trtllm_patched", False):
return

def validate_architecture(self):
head_dim = getattr(self, "head_dim", None)
if isinstance(head_dim, int) and head_dim > 0:
return
Comment on lines +559 to +561

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

It seems that LlamaConfig will set head_dim if it is None here. So it might always be int and very likely larger than 0. And this seems might disable the self.hidden_size % self.num_attention_heads != 0 check for all cases.

if self.hidden_size % self.num_attention_heads != 0:
raise ValueError(
f"The hidden size ({self.hidden_size}) is not a multiple of "
f"the number of attention heads ({self.num_attention_heads}).")

validate_architecture._trtllm_patched = True
LlamaConfig.validate_architecture = validate_architecture

validators = getattr(LlamaConfig, "__class_validators__", None) or []
for i, v in enumerate(validators):
if getattr(v, "__name__", None) == "validate_architecture":
validators[i] = validate_architecture
break


def load_pretrained_config(model_name_or_path: str,
trust_remote_code: bool = False,
checkpoint_format: Optional[str] = None,
Expand All @@ -541,6 +583,7 @@ def load_pretrained_config(model_name_or_path: str,
MistralConfigLoader
return MistralConfigLoader().load(model_name_or_path).pretrained_config

_relax_llama_validate_architecture()
config_dict, _ = transformers.PretrainedConfig.get_config_dict(
model_name_or_path, **kwargs)
model_type = config_dict.get("model_type")
Expand Down
6 changes: 6 additions & 0 deletions tensorrt_llm/tokenizer/tokenizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,12 @@ def load_hf_tokenizer(model_dir: str,
'''

_ensure_gpt2_bytes_to_unicode_compat()
# AutoTokenizer.from_pretrained internally calls AutoConfig.from_pretrained,
# which triggers transformers 5.x LlamaConfig.validate_architecture.
# Relax it so models with explicit `head_dim` (e.g. kanana-1.5-2.1b) load.
from tensorrt_llm._torch.pyexecutor.config_utils import \
_relax_llama_validate_architecture
_relax_llama_validate_architecture()
Comment on lines 677 to +683

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Move the compatibility patch inside the existing try block.

These new lines run before the try: at Line 641, so any import or patching failure now escapes instead of following load_hf_tokenizer()'s current "log and return None" behavior.

💡 Proposed fix
-    _ensure_gpt2_bytes_to_unicode_compat()
-    # AutoTokenizer.from_pretrained internally calls AutoConfig.from_pretrained,
-    # which triggers transformers 5.x LlamaConfig.validate_architecture.
-    # Relax it so models with explicit `head_dim` (e.g. kanana-1.5-2.1b) load.
-    from tensorrt_llm._torch.pyexecutor.config_utils import \
-        _relax_llama_validate_architecture
-    _relax_llama_validate_architecture()
-
     try:
+        _ensure_gpt2_bytes_to_unicode_compat()
+        # AutoTokenizer.from_pretrained internally calls AutoConfig.from_pretrained,
+        # which triggers transformers 5.x LlamaConfig.validate_architecture.
+        # Relax it so models with explicit `head_dim` (e.g. kanana-1.5-2.1b) load.
+        from tensorrt_llm._torch.pyexecutor.config_utils import \
+            _relax_llama_validate_architecture
+        _relax_llama_validate_architecture()
         tokenizer = TransformersTokenizer.from_pretrained(
             model_dir,
             legacy=False,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/tokenizer/tokenizer.py` around lines 633 - 639, The
compatibility patch calls (_ensure_gpt2_bytes_to_unicode_compat and
_relax_llama_validate_architecture) are placed outside the try block in
load_hf_tokenizer so import/patch failures escape instead of being caught; move
the two calls (and their import of _relax_llama_validate_architecture from
tensorrt_llm._torch.pyexecutor.config_utils) inside the existing try: block in
load_hf_tokenizer so any ImportError or runtime error is logged and the function
returns None as intended.


try:
tokenizer = TransformersTokenizer.from_pretrained(
Expand Down
Loading