Repository navigation
Description
Describe the bug
With tie_word_embeddings=True, lm_head.weight and model.embed_tokens.weight are the same tensor
after HF loading. tensorrt-edgellm-quantize llm --quantization int4_awq --lm_head_quantization <method>
enables the lm_head quantizers (quantization_configs.py:315-323 at 0f52705) and calibrates with the
backbone's awq_lite algorithm. AWQ then smooths the head by dividing its weight by the per-input-channel
pre_quant_scale. Because the weight is shared, the division also lands on the embedding table.
quantize_and_export (quantize.py:1083 onward) does nothing to separate the two.
So the exported checkpoint's model.embed_tokens.weight is the original embedding divided by
lm_head.pre_quant_scale, not the model's embedding. tensorrt-edgellm-export writes the runtime
embedding.safetensors from that tensor (checkpoint/checkpoint_utils.py:1139-1169), so the engine
looks up scaled embeddings. The exported config.json also still says tie_word_embeddings: true,
while lm_head is stored separately as a quantized tensor.
Measured with a tiny tied LlamaForCausalLM on CPU, using the repo's build_quant_config and ModelOpt
0.45.0 (script below):
exported embed_tokens rel mean abs diff vs original: 2.588e-02
exported embed * pre_quant_scale vs original: 1.735e-08
config tie_word_embeddings: True
The embedding is exactly the original divided by the head's smoothing scale. The size of the error
depends on the model. On Gemma 4 E2B (tied), the mean absolute difference was about 54 % in our fork
(see Additional details).
Calibration-only check (no export) of which combinations change the embedding:
--quantization |
--lm_head_quantization |
algorithm | embed_tokens changed |
|---|---|---|---|
| int4_awq | int4_awq | awq_lite | yes |
| int4_awq | fp8 | awq_lite | yes |
| fp8 | int4_awq | max | no |
| nvfp4 | int4_awq | max | no |
| nvfp4 | nvfp4 | max | no |
| fp8 | fp8 | max | no |
(int4_awq + nvfp4 head could not be calibrated on CPU and was not checked.)
Impact: should have. An INT4-AWQ checkpoint with a quantized head on any tied-embedding model (Gemma 4,
small Qwen and Llama variants with tied heads) silently changes the input embeddings. Aggregate accuracy
can hide this; see Additional details.
Steps/Code to reproduce bug
Installation method: source checkout at 0f52705 on PYTHONPATH, pinned transformers==5.14.1,
nvidia-modelopt==0.45.0, CPU only.
Export command used: the bug is in tensorrt-edgellm-quantize. A real-model reproduction is
tensorrt-edgellm-quantize llm --model_dir google/gemma-4-E2B-it --output_dir out --quantization int4_awq --lm_head_quantization int4_awq,
then compare model.embed_tokens.weight in out with the original checkpoint. The minimal version
below needs no GPU or download:
import glob, json, os, tempfile, torch
import modelopt.torch.quantization as mtq
from modelopt.torch.export import export_hf_checkpoint
from safetensors.torch import load_file
from transformers import LlamaConfig, LlamaForCausalLM
from tensorrt_edgellm.quantization.quantization_configs import build_quant_config
torch.manual_seed(0)
cfg = LlamaConfig(vocab_size=256, hidden_size=128, intermediate_size=256, num_hidden_layers=1,
num_attention_heads=4, num_key_value_heads=4, tie_word_embeddings=True,
architectures=["LlamaForCausalLM"])
model = LlamaForCausalLM(cfg).eval()
orig = model.model.embed_tokens.weight.detach().clone()
data = [torch.randint(0, 256, (4, 64)) for _ in range(4)]
mtq.quantize(model, build_quant_config("int4_awq", "int4_awq"),
forward_loop=lambda m: [m(input_ids=x) for x in data])
pqs = model.lm_head.input_quantizer.pre_quant_scale.float().flatten()
d = tempfile.mkdtemp()
with torch.inference_mode():
export_hf_checkpoint(model, export_dir=d)
sd = {}
for f in glob.glob(os.path.join(d, "*.safetensors")):
sd.update(load_file(f))
emb = sd["model.embed_tokens.weight"].float()
print("rel diff:", ((emb - orig).abs().mean() / orig.abs().mean()).item())
print("rel diff after * pre_quant_scale:", ((emb * pqs - orig).abs().mean() / orig.abs().mean()).item())
print("tie_word_embeddings:", json.load(open(os.path.join(d, "config.json")))["tie_word_embeddings"])Expected behavior
model.embed_tokens.weight in the quantized checkpoint equals the original embedding, and only
lm_head carries the smoothing (lm_head.weight, lm_head.weight_scale, lm_head.pre_quant_scale).
The config should say the head is untied, because the checkpoint now stores two different tensors.
A fix that does this: before calibration, when lm_head_quantization is set and
get_output_embeddings().weight is get_input_embeddings().weight, give the head its own
nn.Parameter copy and set tie_word_embeddings=False on the config (and text_config). With that,
the tiny model above exports the original embedding bit for bit, and its lm_head.* tensors are
bit-identical to those without the change. The change, with a unit test, is in draft PR #256.
System information (x86 Host with GPU)
- Container used (if applicable): none
- OS (e.g., Ubuntu 22.04, CentOS 7): Ubuntu 24.04.5 LTS
- CPU architecture: x86_64
- GPU name (e.g. H100, A100, RTX 4090): none (the reproduction runs on CPU)
- GPU memory size: n/a
- Number of GPUs: 0
- Library versions:
- Python: 3.12.3
- TensorRT Edge-LLM version or commit hash: 0f52705
- CUDA: n/a (torch 2.13.0+cu130 used on CPU)
- PyTorch: 2.13.0+cu130
- Transformers: 5.14.1
- ModelOpt: 0.45.0
- ONNX: not involved
- Any other details that may help: see below
Additional details
We found this in a fork that builds an INT8 token-embedding table from the quantized checkpoint's
embed_tokens, for Gemma 4 E2B with --lm_head_quantization int4_awq. There, embed * pre_quant_scale
matched the original checkpoint to 2.4e-4 relative error, while the unscaled tensor was off by 54 %
(mean absolute). On an 8 GB Jetson, with the same engine and only the token table changed, MMLU-500 was
237/500 against 238/500 with the correct table. But only 417/500 predictions matched the FP16-head
baseline, against 488/500 with the correct table. Those numbers come from the fork's pipeline, not from
stock main.
Activity