Skip to content

Commit dcf6bef

Browse files
justinchubyCopilot
andcommitted
Clean up PR #153: remove stray weight-tying changes; rename EpCapabilities field
Rename EpCapabilities.past_present_share_buffer to supports_past_present_share_buffer for consistency with other capability flags. Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 25bd339 commit dcf6bef

5 files changed

Lines changed: 9 additions & 123 deletions

File tree

‎src/mobius/_execution_providers.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ class EpCapabilities:
7171
quantization (0 = highest accuracy, 4 = fastest).
7272
provider_options: Default ORT GenAI provider options dict for this EP.
7373
enable_graph_capture: Whether this EP defaults to GPU graph capture.
74-
past_present_share_buffer: Whether this EP requires past and present
74+
supports_past_present_share_buffer: Whether this EP requires past and present
7575
KV-cache tensors to share the same pre-allocated backing buffer.
7676
``True`` for WebGPU, which allocates the full KV-cache at model
7777
load time and maps both past and present views into it. ``False``
@@ -89,7 +89,7 @@ class EpCapabilities:
8989
default_int4_accuracy_level: int = 0
9090
provider_options: dict[str, str] = dataclasses.field(default_factory=dict)
9191
enable_graph_capture: bool = False
92-
past_present_share_buffer: bool = False
92+
supports_past_present_share_buffer: bool = False
9393

9494
def __post_init__(self) -> None:
9595
if not self.supports_fused_rope and self.qkv_pack_dtypes:
@@ -228,7 +228,7 @@ def _register_builtins() -> None:
228228
qkv_pack_dtypes=frozenset({ir.DataType.FLOAT, ir.DataType.FLOAT16}),
229229
default_int4_accuracy_level=4,
230230
provider_options={"enableGraphCapture": "0", "validationMode": "basic"},
231-
past_present_share_buffer=True,
231+
supports_past_present_share_buffer=True,
232232
),
233233
EpCapabilities(
234234
name="trt-rtx",

‎src/mobius/_weight_loading.py‎

Lines changed: 2 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -85,13 +85,7 @@ def apply_weights(model: ir.Model, state_dict: dict[str, torch.Tensor]) -> None:
8585
"""Apply weights from a state dict to an ONNX model.
8686
8787
Assigns each tensor in *state_dict* to the matching initializer in the
88-
model. When two entries in *state_dict* are the **same Python object**
89-
(i.e. genuinely tied weights such as ``lm_head.weight`` /
90-
``embed_tokens.weight``), the second initializer's value is redirected to
91-
share the first one — a single ONNX initializer is emitted instead of two
92-
identical copies.
93-
94-
After all weights are assigned,
88+
model. After all weights are assigned,
9589
:func:`~mobius._optimizations.fold_initializers_after_weights` is called to
9690
fold ``Transpose`` and ``Concat`` nodes over initializers into pre-computed
9791
weights and remove unused source initializers.
@@ -100,11 +94,6 @@ def apply_weights(model: ir.Model, state_dict: dict[str, torch.Tensor]) -> None:
10094
model: The ONNX IR model.
10195
state_dict: Mapping of parameter names to torch tensors.
10296
"""
103-
# Map tensor id → the ir.Value of the first initializer assigned for that tensor.
104-
# Enables genuine weight sharing: if lm_head.weight IS embed_tokens.weight
105-
# (same Python object), the second initializer is merged into the first.
106-
tensor_id_to_value: dict[int, ir.Value] = {}
107-
10897
for name, tensor in state_dict.items():
10998
if name not in model.graph.initializers:
11099
logger.warning(
@@ -113,24 +102,7 @@ def apply_weights(model: ir.Model, state_dict: dict[str, torch.Tensor]) -> None:
113102
)
114103
continue
115104

116-
initializer = model.graph.initializers[name]
117-
tid = id(tensor)
118-
119-
if tid in tensor_id_to_value:
120-
# This tensor was already assigned to another initializer.
121-
# Redirect all graph uses of this initializer to the canonical one,
122-
# then delete this initializer — genuine single-copy weight sharing.
123-
canonical = tensor_id_to_value[tid]
124-
initializer.replace_all_uses_with(canonical)
125-
del model.graph.initializers[name]
126-
logger.debug(
127-
"Weight tying: '%s' shares initializer with '%s'",
128-
name,
129-
canonical.name,
130-
)
131-
else:
132-
_assign_weight(initializer, tensor, name)
133-
tensor_id_to_value[tid] = initializer
105+
_assign_weight(model.graph.initializers[name], tensor, name)
134106

135107
fold_initializers_after_weights(model)
136108

‎src/mobius/_weight_loading_test.py‎

Lines changed: 0 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -460,92 +460,6 @@ def test_zero_byte_safetensors_file_raises(self, tmp_path):
460460
safetensors.torch.load_file(str(empty))
461461

462462

463-
# ===========================================================================
464-
# (6b) Weight tying — genuine ONNX initializer sharing
465-
# ===========================================================================
466-
467-
468-
class TestWeightTying:
469-
"""Verify that tied weights (lm_head = embed_tokens) share one ONNX initializer."""
470-
471-
def _build_tied_model(self) -> tuple[ir.Model, CausalLMModel]:
472-
config = make_config(tie_word_embeddings=True)
473-
module = CausalLMModel(config)
474-
pkg = build_from_module(module, config)
475-
return pkg["model"], module
476-
477-
def test_tied_weights_share_single_initializer(self):
478-
"""When tie_word_embeddings=True, lm_head.weight must NOT be a separate initializer."""
479-
model, module = self._build_tied_model()
480-
weight = torch.zeros(make_config().vocab_size, make_config().hidden_size)
481-
sd = module.preprocess_weights({"model.embed_tokens.weight": weight})
482-
assert sd["model.embed_tokens.weight"] is sd["lm_head.weight"], (
483-
"preprocess_weights must produce the same tensor object for tied weights"
484-
)
485-
486-
apply_weights(model, sd)
487-
488-
assert "lm_head.weight" not in model.graph.initializers, (
489-
"lm_head.weight initializer should be removed — merged into embed_tokens"
490-
)
491-
assert "model.embed_tokens.weight" in model.graph.initializers, (
492-
"embed_tokens initializer must remain as the canonical shared weight"
493-
)
494-
495-
def test_untied_weights_have_separate_initializers(self):
496-
"""When tie_word_embeddings=False, both initializers remain independent."""
497-
config = make_config(tie_word_embeddings=False)
498-
module = CausalLMModel(config)
499-
pkg = build_from_module(module, config)
500-
model = pkg["model"]
501-
502-
vocab_size = config.vocab_size
503-
hidden_size = config.hidden_size
504-
sd = {
505-
"model.embed_tokens.weight": torch.zeros(vocab_size, hidden_size),
506-
"lm_head.weight": torch.zeros(vocab_size, hidden_size),
507-
}
508-
apply_weights(model, sd)
509-
510-
assert "model.embed_tokens.weight" in model.graph.initializers
511-
assert "lm_head.weight" in model.graph.initializers
512-
513-
def test_tied_model_initializer_count_lower_than_untied(self):
514-
"""Tied model must have fewer initializers than untied (one embed weight, not two)."""
515-
from mobius._testing import make_config as mc
516-
517-
config_tied = mc(tie_word_embeddings=True)
518-
module_tied = CausalLMModel(config_tied)
519-
pkg_tied = build_from_module(module_tied, config_tied)
520-
model_tied = pkg_tied["model"]
521-
sd_tied = module_tied.preprocess_weights(
522-
{
523-
"model.embed_tokens.weight": torch.zeros(
524-
config_tied.vocab_size, config_tied.hidden_size
525-
)
526-
}
527-
)
528-
apply_weights(model_tied, sd_tied)
529-
530-
config_untied = mc(tie_word_embeddings=False)
531-
module_untied = CausalLMModel(config_untied)
532-
pkg_untied = build_from_module(module_untied, config_untied)
533-
model_untied = pkg_untied["model"]
534-
sd_untied = {
535-
"model.embed_tokens.weight": torch.zeros(
536-
config_untied.vocab_size, config_untied.hidden_size
537-
),
538-
"lm_head.weight": torch.zeros(config_untied.vocab_size, config_untied.hidden_size),
539-
}
540-
apply_weights(model_untied, sd_untied)
541-
542-
n_tied = len(model_tied.graph.initializers)
543-
n_untied = len(model_untied.graph.initializers)
544-
assert n_tied < n_untied, (
545-
f"Tied model should have fewer initializers ({n_tied}) than untied ({n_untied})"
546-
)
547-
548-
549463
# ===========================================================================
550464
# (6) build_from_module contract preservation
551465
# ===========================================================================

‎src/mobius/integrations/ort_genai/genai_config.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def _default_search_params(*, ep: str, context_length: int) -> dict[str, Any]:
6060
from mobius._execution_providers import ep_registry
6161

6262
caps = ep_registry.get(ep)
63-
share_buffer = caps.past_present_share_buffer if caps is not None else False
63+
share_buffer = caps.supports_past_present_share_buffer if caps is not None else False
6464
if share_buffer:
6565
# EPs that pre-allocate KV-cache for the full max_length at load time
6666
# (e.g. WebGPU) need a capped default to avoid pre-allocating huge

‎src/mobius/integrations/ort_genai/genai_config_test.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def test_search_params_defaults(self):
140140
assert search["past_present_share_buffer"] is False
141141

142142
def test_search_params_webgpu_sets_past_present_share_buffer(self):
143-
"""WebGPU EP sets past_present_share_buffer=True via EpCapabilities and caps max_length."""
143+
"""WebGPU EP sets supports_past_present_share_buffer=True via EpCapabilities and caps max_length."""
144144
gen = GenaiConfigGenerator(
145145
"qwen2",
146146
vocab_size=151936,
@@ -190,15 +190,15 @@ def test_search_params_cuda_does_not_share_buffer(self):
190190
assert config["search"]["past_present_share_buffer"] is False
191191

192192
def test_search_params_custom_ep_with_share_buffer(self):
193-
"""A custom EP registered with past_present_share_buffer=True gets the flag set.
193+
"""A custom EP registered with supports_past_present_share_buffer=True gets the flag set.
194194
195195
This proves the value comes from EpCapabilities, not from a hardcoded
196196
'ep == webgpu' check.
197197
"""
198198
from mobius._execution_providers import EpCapabilities, ep_registry
199199

200200
ep_registry.register(
201-
EpCapabilities(name="test-custom-ep", past_present_share_buffer=True),
201+
EpCapabilities(name="test-custom-ep", supports_past_present_share_buffer=True),
202202
overwrite=True,
203203
)
204204
try:

0 commit comments

Comments
 (0)