Skip to content

Commit a4a2f71

Browse files
committed
Restore StarCoder2 GGUF sliding attention
Apply StarCoder2's architecture-owned 4096-token sliding window when GGUF metadata omits it. Add exact-artifact cached-position parity that rejects full causal attention, and refresh the config, graph, and runtime-package fingerprints. Co-authored-by: Copilot App <[email protected]> Copilot-Session: f5f288c7-b4e5-4371-ad46-9d163511ade9 Signed-off-by: Justin Chu <[email protected]>
1 parent 951517b commit a4a2f71

7 files changed

Lines changed: 118 additions & 7 deletions

File tree

‎src/mobius/integrations/gguf/_arch_registry.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1613,6 +1613,7 @@
16131613
gguf_arch="starcoder2",
16141614
model_type="starcoder2",
16151615
tensor_map_recipe=("llama",),
1616+
config_postprocessor="starcoder2",
16161617
runtime=Support.SUPPORTED,
16171618
runtime_evidence_ids=("tiny-starcoder2-q2-k-ort-genai-0.15.2",),
16181619
reason=(

‎src/mobius/integrations/gguf/_config_mapping.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,6 +1542,18 @@ def _qwen3_postprocess(
15421542
return dataclasses.replace(config, attn_qk_norm=True, attn_qk_norm_full=False)
15431543

15441544

1545+
def _starcoder2_postprocess(
1546+
config: ArchitectureConfig,
1547+
metadata: dict[str, Any],
1548+
model: Any = None,
1549+
) -> ArchitectureConfig:
1550+
"""Restore StarCoder2's architecture-owned uniform sliding window."""
1551+
del metadata, model
1552+
if config.sliding_window is not None:
1553+
return config
1554+
return dataclasses.replace(config, sliding_window=4096)
1555+
1556+
15451557
def _dbrx_postprocess(
15461558
config: ArchitectureConfig,
15471559
metadata: dict[str, Any],
@@ -4726,6 +4738,7 @@ def _qwen4exp_postprocess(
47264738
"pangu_embedded": _pangu_embedded_postprocess,
47274739
"dense_sliding": _dense_sliding_postprocess,
47284740
"qwen3": _qwen3_postprocess,
4741+
"starcoder2": _starcoder2_postprocess,
47294742
"gemma2": _gemma2_postprocess,
47304743
"baichuan": _baichuan_postprocess,
47314744
"chatglm": _chatglm_postprocess,

‎src/mobius/integrations/gguf/_config_mapping_test.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1423,6 +1423,26 @@ def test_qwen3_qk_norm_weights_have_graph_consumers() -> None:
14231423
assert layer.self_attn.k_norm is not None
14241424

14251425

1426+
@pytest.mark.parametrize(
1427+
("metadata_window", "expected_window"),
1428+
[(None, 4096), (2048, 2048)],
1429+
)
1430+
def test_starcoder2_restores_architecture_sliding_window(
1431+
metadata_window: int | None,
1432+
expected_window: int,
1433+
) -> None:
1434+
from mobius.integrations.gguf._config_mapping import gguf_to_config
1435+
1436+
metadata = _dense_metadata("starcoder2")
1437+
if metadata_window is not None:
1438+
metadata["starcoder2.attention.sliding_window"] = metadata_window
1439+
config = gguf_to_config(_FakeDenseGGUF("starcoder2", metadata, []))
1440+
1441+
assert config.sliding_window == expected_window
1442+
module = registry.get(config.model_type)(config)
1443+
assert module.model._sliding_window == expected_window
1444+
1445+
14261446
class TestQwen35MtpBlockExclusion:
14271447
"""Qwen3.5/3.8 GGUF ``block_count`` includes trailing MTP (nextn) blocks.
14281448

‎src/mobius/integrations/gguf/_runtime_evidence.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -824,15 +824,15 @@ def _is_hex(value: str) -> bool:
824824
("Q4_K", 2),
825825
("Q6_K", 1),
826826
),
827-
import_route='{"architecture":"starcoder2","config_sha256":"fe2d8c7611ab003e9802bc5629f05b98ce3b6c5ce0645cef07023df0604b570e","execution_provider":"cpu","model_type":"starcoder2","module_type":"starcoder2","preserve_quantization":false,"registry_import":{"config_key_map":null,"config_postprocessor":null,"llama_qk_permute":false,"offset_norm":false,"required_metadata":[],"rope_interleave":false,"tensor_processor":null,"v_head_reorder":false,"vlm_builder":null},"route_schema":1,"static_cache":false,"task":{"class":"builtins.str","state":"text-generation"},"tensor_map_recipe":["llama"]}',
827+
import_route='{"architecture":"starcoder2","config_sha256":"25eaa4f5baa4e4725930298aaa921804d1e6f202737a3b10ec32070c4acfcb71","execution_provider":"cpu","model_type":"starcoder2","module_type":"starcoder2","preserve_quantization":false,"registry_import":{"config_key_map":null,"config_postprocessor":"starcoder2","llama_qk_permute":false,"offset_norm":false,"required_metadata":[],"rope_interleave":false,"tensor_processor":null,"v_head_reorder":false,"vlm_builder":null},"route_schema":1,"static_cache":false,"task":{"class":"builtins.str","state":"text-generation"},"tensor_map_recipe":["llama"]}',
828828
source_fidelity=False,
829829
storage_quantized=False,
830830
target_storage_format="float",
831831
compute_mode="float operators",
832832
graph_files=_LOW_COST_GRAPH_FILES,
833-
graph_sha256="03a123ea3fddf885f14c9b1e34912364be569e6768580632347a326717d755f5",
833+
graph_sha256="34c3e58ac9d95b5d1097393782d41a942ac9b6188e6d57adff21212030897a23",
834834
runtime_package_files=_LOW_COST_RUNTIME_PACKAGE_FILES,
835-
runtime_package_sha256="bc0ae61859226c31792235af87f0a491174fdeb4a7a115bbdaf3c27fbcd01fd5",
835+
runtime_package_sha256="4a9ab2edf80d8cf778fccd56d306cb56dfda5bb190068faf04c78ac5d180f564",
836836
parity_test="test_promoted_gguf_full_runtime_evidence[tiny-starcoder2-q2-k]",
837837
parity_kind="full-logit",
838838
deterministic_test="test_promoted_gguf_full_runtime_evidence[tiny-starcoder2-q2-k]",

‎testdata/cases/causal-lm/tiny-starcoder2-q2-k.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ gguf:
1313
tensor_count: 36
1414
tensor_qtypes: {F32: 22, Q2_K: 7, Q3_K: 4, Q4_K: 2, Q6_K: 1}
1515
execution_provider: "cpu"
16-
config_sha256: "fe2d8c7611ab003e9802bc5629f05b98ce3b6c5ce0645cef07023df0604b570e"
16+
config_sha256: "25eaa4f5baa4e4725930298aaa921804d1e6f202737a3b10ec32070c4acfcb71"
1717
preserve_quantization: false
1818
tokenizer:
1919
repository: "hyper-accel/tiny-random-starcoder2"

‎testdata/evidence/gguf_quantization_capabilities.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2953,14 +2953,14 @@
29532953
"downstream_runtime_version": "0.15.2",
29542954
"evidence_id": "tiny-starcoder2-q2-k-ort-genai-0.15.2",
29552955
"execution_provider": "CPUExecutionProvider",
2956-
"graph_sha256": "03a123ea3fddf885f14c9b1e34912364be569e6768580632347a326717d755f5",
2957-
"import_route": "{\"architecture\":\"starcoder2\",\"config_sha256\":\"fe2d8c7611ab003e9802bc5629f05b98ce3b6c5ce0645cef07023df0604b570e\",\"execution_provider\":\"cpu\",\"model_type\":\"starcoder2\",\"module_type\":\"starcoder2\",\"preserve_quantization\":false,\"registry_import\":{\"config_key_map\":null,\"config_postprocessor\":null,\"llama_qk_permute\":false,\"offset_norm\":false,\"required_metadata\":[],\"rope_interleave\":false,\"tensor_processor\":null,\"v_head_reorder\":false,\"vlm_builder\":null},\"route_schema\":1,\"static_cache\":false,\"task\":{\"class\":\"builtins.str\",\"state\":\"text-generation\"},\"tensor_map_recipe\":[\"llama\"]}",
2956+
"graph_sha256": "34c3e58ac9d95b5d1097393782d41a942ac9b6188e6d57adff21212030897a23",
2957+
"import_route": "{\"architecture\":\"starcoder2\",\"config_sha256\":\"25eaa4f5baa4e4725930298aaa921804d1e6f202737a3b10ec32070c4acfcb71\",\"execution_provider\":\"cpu\",\"model_type\":\"starcoder2\",\"module_type\":\"starcoder2\",\"preserve_quantization\":false,\"registry_import\":{\"config_key_map\":null,\"config_postprocessor\":\"starcoder2\",\"llama_qk_permute\":false,\"offset_norm\":false,\"required_metadata\":[],\"rope_interleave\":false,\"tensor_processor\":null,\"v_head_reorder\":false,\"vlm_builder\":null},\"route_schema\":1,\"static_cache\":false,\"task\":{\"class\":\"builtins.str\",\"state\":\"text-generation\"},\"tensor_map_recipe\":[\"llama\"]}",
29582958
"limitations": "Explicit-float correctness route; source GGUF blocks are dequantized. The tiny source config declares BOS/EOS ID 50256 outside its 49152-token model vocabulary.",
29592959
"onnxruntime_version": "1.29.0",
29602960
"parity_kind": "full-logit",
29612961
"parity_test": "test_promoted_gguf_full_runtime_evidence[tiny-starcoder2-q2-k]",
29622962
"result": "passed",
2963-
"runtime_package_sha256": "bc0ae61859226c31792235af87f0a491174fdeb4a7a115bbdaf3c27fbcd01fd5",
2963+
"runtime_package_sha256": "4a9ab2edf80d8cf778fccd56d306cb56dfda5bb190068faf04c78ac5d180f564",
29642964
"source_fidelity": false,
29652965
"stateful_semantics": "dynamic KV cache prefill, full-sequence replay, rollback, reorder, and 20 decode steps",
29662966
"storage_quantized": false,

‎tests/gguf_small_model_runtime_integration_test.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
AutoConfig,
3737
AutoModelForCausalLM,
3838
AutoTokenizer,
39+
DynamicCache,
3940
GPTBigCodeForCausalLM,
4041
GPTNeoXForCausalLM,
4142
MptConfig,
@@ -903,6 +904,74 @@ def _run_promoted_ort(
903904
return dict(zip(output_names, session.run(output_names, feeds), strict=True))
904905

905906

907+
def _assert_starcoder2_long_context_sliding_window(
908+
session: ort.InferenceSession,
909+
reference: torch.nn.Module,
910+
token_id: int,
911+
*,
912+
atol: float,
913+
) -> None:
914+
"""Prove the exact route applies StarCoder2's window past position 4096."""
915+
window = int(reference.config.sliding_window)
916+
assert window == 4096
917+
past_length = window
918+
num_layers = int(reference.config.num_hidden_layers)
919+
num_kv_heads = int(reference.config.num_key_value_heads)
920+
head_dim = int(reference.config.hidden_size // reference.config.num_attention_heads)
921+
922+
state: dict[str, np.ndarray] = {}
923+
cache_data: list[tuple[torch.Tensor, torch.Tensor]] = []
924+
for layer_idx in range(num_layers):
925+
key = np.zeros((1, num_kv_heads, past_length, head_dim), dtype=np.float32)
926+
value = np.zeros_like(key)
927+
# Only the oldest value is nonzero. Sliding attention must exclude it at
928+
# position 4096; full causal attention still observes it.
929+
value[:, :, 0, :] = 1024.0
930+
state[f"past_key_values.{layer_idx}.key"] = key
931+
state[f"past_key_values.{layer_idx}.value"] = value
932+
cache_data.append((torch.from_numpy(key.copy()), torch.from_numpy(value.copy())))
933+
934+
input_ids = np.asarray([[token_id]], dtype=np.int64)
935+
ort_logits = _run_promoted_ort(session, input_ids, state, past_length)["logits"]
936+
attention_mask = torch.ones((1, past_length + 1), dtype=torch.int64)
937+
position_ids = torch.asarray([[past_length]], dtype=torch.int64)
938+
939+
def reference_logits(sliding_window: int | None) -> np.ndarray:
940+
reference.config.sliding_window = sliding_window
941+
cache = DynamicCache(
942+
((key.clone(), value.clone()) for key, value in cache_data),
943+
config=reference.config,
944+
)
945+
with torch.no_grad():
946+
return (
947+
reference(
948+
torch.from_numpy(input_ids),
949+
attention_mask=attention_mask,
950+
position_ids=position_ids,
951+
past_key_values=cache,
952+
use_cache=False,
953+
)
954+
.logits.numpy()
955+
.copy()
956+
)
957+
958+
try:
959+
expected_logits = reference_logits(window)
960+
np.testing.assert_allclose(ort_logits, expected_logits, rtol=1e-4, atol=atol)
961+
962+
full_causal_logits = reference_logits(None)
963+
assert np.max(np.abs(ort_logits - full_causal_logits)) > 1e-3
964+
with pytest.raises(AssertionError):
965+
np.testing.assert_allclose(
966+
ort_logits,
967+
full_causal_logits,
968+
rtol=1e-4,
969+
atol=atol,
970+
)
971+
finally:
972+
reference.config.sliding_window = window
973+
974+
906975
def _assert_replay_rollback_and_reorder(
907976
session: ort.InferenceSession,
908977
prompt_ids: np.ndarray,
@@ -1680,6 +1749,14 @@ def capture_save(package: ModelPackage, *args: object, **kwargs: object) -> None
16801749
)
16811750
del mutated, mutated_logits
16821751

1752+
if evidence.architecture == "starcoder2":
1753+
_assert_starcoder2_long_context_sliding_window(
1754+
session,
1755+
reference,
1756+
int(prompt_ids[0, -1]),
1757+
atol=case.atol,
1758+
)
1759+
16831760
state = _next_cache(ort_output)
16841761
generated: list[int] = []
16851762
reference_generated: list[int] = []

0 commit comments

Comments
 (0)