@@ -368,11 +368,21 @@ def tie_word_embeddings(
368368 embed_key : str = "model.embed_tokens.weight" ,
369369 head_key : str = "lm_head.weight" ,
370370) -> None :
371- """Ensure both embedding and LM head weights are present (tied).
372-
373- If one of the two keys is missing, copies the other. This handles
374- the common HuggingFace ``tie_word_embeddings=True`` pattern where
375- only one of the two weights is stored in the checkpoint.
371+ """Ensure both embedding and LM head weights are present and tied.
372+
373+ When HuggingFace saves a model with ``tie_word_embeddings=True``, only
374+ one of the two weights (embedding or LM head) is stored in the
375+ checkpoint. This function fills in the missing key by assigning it
376+ to **the same Python tensor object** as the existing key.
377+
378+ This identity relationship is what enables true ONNX weight sharing
379+ downstream: :func:`~mobius._weight_loading.apply_weights` detects
380+ that two state-dict entries share the same underlying storage (via
381+ ``data_ptr()``), creates a **single** ONNX initializer for the first
382+ occurrence, and redirects all graph uses of the second initializer to
383+ point at the first one. The result is one copy of the embedding
384+ table in the ONNX file, used by both the Gather (embedding lookup)
385+ and MatMul (LM head projection) nodes.
376386
377387 Mutates *state_dict* in place.
378388
@@ -385,6 +395,12 @@ def tie_word_embeddings(
385395 state_dict [head_key ] = state_dict [embed_key ]
386396 elif embed_key not in state_dict and head_key in state_dict :
387397 state_dict [embed_key ] = state_dict [head_key ]
398+ elif embed_key not in state_dict and head_key not in state_dict :
399+ raise ValueError (
400+ f"tie_word_embeddings: neither '{ embed_key } ' nor '{ head_key } ' "
401+ f"found in state_dict. Check that the key names match the "
402+ f"weight dictionary after any prefix stripping."
403+ )
388404
389405
390406def vlm_decoder_weights (
0 commit comments