Skip to content

Commit 6dc9f43

Browse files
justinchubyCopilot
andauthored
Add T5 GGUF import cohort (#580)
## Summary - add suffix-exact pinned llama.cpp mappings and config extraction for `t5` and `t5encoder` - preserve separate encoder/decoder namespaces, per-layer relative bias ownership, FFN gating, shared embeddings, unequal stack depths, masks, and T5 cross-attention caching - preserve compatible quantized projections through `MatMulNBits` while explicitly dequantizing token embeddings and rejecting unsupported sidecars/layouts - add encoder-only and seq2seq synthetic float/quantized ORT coverage, value-level transforms, malformed-input falsification, save/load, variable masks, prefill/decode cache tests, and HuggingFace T5/mT5/FLAN-T5/BART parity - document pinned real GGUF candidates and keep runtime support deferred pending independent real-artifact parity ## Validation - `lintrunner f --output oneline --all-files` - `python -m pytest tests/seq2seq_integration_test.py -q --tb=short` — 10 passed - broad non-integration suite excluding the pre-existing `glm_moe_dsa` shape-inference failure — 5,742 passed, 52 skipped - the two `glm_moe_dsa` failures in the unfiltered broad run reproduce unchanged on base commit `032a967` Stacked on #579 / `justinchuby-gguf-encoder-cohort`. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Copilot-Session: 59c34ad7-370a-4534-96f4-d5a97f36f808
1 parent a96e74a commit 6dc9f43

17 files changed

Lines changed: 1514 additions & 131 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,8 @@ reason.
194194
| `smollm3` | — | `smollm3` | supported | supported |
195195
| `stablelm` | — | `stablelm` | supported | supported |
196196
| `starcoder2` | — | `starcoder2` | supported | supported |
197-
| `t5` | — | `t5` | tensor_map deferred | unreachable |
197+
| `t5` | — | `t5` | runtime deferred | supported |
198+
| `t5encoder` | — | `t5encoder` | runtime deferred | supported |
198199

199200
<!-- END GGUF SUPPORT MATRIX -->
200201

@@ -242,6 +243,48 @@ EuroBERT, JinaBERT v2/v3, NeoBERT, NomicBERT, and NomicBERT-MoE remain deferred
242243
because their pinned normalization, ALiBi/RoPE, gated FFN, Q/K norm, or routed
243244
expert semantics do not match the existing encoder graphs.
244245

246+
### T5 and T5-encoder GGUF contract
247+
248+
`t5` produces separate `encoder` and `decoder` components with masked encoder
249+
states, decoder self-attention cache, and cross-attention cache. The same decoder
250+
graph handles prefill (empty cross cache plus encoder states) and decode (populated
251+
cross cache plus zero-length encoder states). `t5encoder` produces only a `model`
252+
component with `input_ids` and `attention_mask` inputs and a
253+
`last_hidden_state` output; it has no decoder, logits, or cache.
254+
255+
The importer preserves unequal encoder/decoder layer counts, head width,
256+
feed-forward width, RMS-norm epsilon, relative-position buckets, decoder start,
257+
EOS, and padding token IDs. Layer 0 must own each stack's relative-attention bias;
258+
later per-layer overrides remain attached to their source layer. Non-gated files
259+
use ReLU. Gated files are rejected as ambiguous: pinned llama.cpp executes any
260+
gate tensor through tanh-approximate `LLM_FFN_GELU`/`ggml_geglu_split`, but its
261+
converter does not serialize `feed_forward_proj` or `dense_act_fn`, so identical
262+
GGUF metadata and tensor shapes can originate from `gated-gelu`, `gated-silu`,
263+
or another gated activation. Mixed gated/non-gated layers, GQA, unequal key/value
264+
widths, fused projections, projection biases, malformed suffixes, and
265+
`.scale`/`.input_scale` sidecars are rejected before graph construction.
266+
267+
Compatible quantized 2-D projections use `MatMulNBits`. Shared token embeddings
268+
explicitly dequantize to `Gather`, and relative bias, norms, and other small
269+
tensors remain float. A `t5encoder` `output.weight` and decoder
270+
`cross_attn_rel_b.weight` are accepted only with an explicit warning because the
271+
pinned llama.cpp encoder output and cross-attention graph do not consume them.
272+
273+
Runtime remains **deferred**. The real-file audit pinned these representatives
274+
before payload download:
275+
276+
| Architecture | GGUF revision and file | Size | LFS SHA-256 | Header evidence |
277+
|---|---|---:|---|---|
278+
| T5 | `noumenalabs/t5-small-gguf@222e7698299802b6a592054305063f22759aed0f`<br>`t5-small-f16.gguf` | 122,074,752 | `4331d3b568593e17d0de10c8755705256c2912af4338ecace92fcef0122da646` | 131-tensor full encoder/decoder census; source config/tokenizer `google-t5/t5-small@df1b051c49625cf57a3d0d8d3863ed4d13564fe4` |
279+
| T5 encoder | `chatpig/t5-base-encoder-gguf@1d307eff4d9de02b9f74cff9a9928187606040ee`<br>`t5base-encoder-q8_0.gguf` | 117,563,552 | `36067e77cb097a99b0a1d47b4e49525c6a0c6c845abb9d22d5798b2633880b54` | 99-tensor encoder census; candidate source config/tokenizer `google-t5/t5-base@a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1`, but conversion provenance is weaker |
280+
281+
Synthetic float and quantized tests cover full hidden states/logits, padding
282+
masks, save/load, prefill, cached decode, and packed-versus-explicit-dequantized
283+
parity. They are not independent HuggingFace parity. Full-logit and generated-token
284+
parity are still required for T5, and independently sourced full encoder-hidden
285+
parity is still required for T5 encoder, before either runtime verdict can become
286+
supported.
287+
245288
### Pure recurrent Mamba evidence
246289

247290
`mamba` and `mamba2` have config, suffix-exact C++ tensor-name closure,

‎src/mobius/_configs/_base.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -460,8 +460,11 @@ class ArchitectureConfig(BaseModelConfig):
460460

461461
# Encoder-decoder config
462462
num_decoder_layers: int | None = None
463+
decoder_start_token_id: int | None = None
463464
relative_attention_num_buckets: int = 32
464465
relative_attention_max_distance: int = 128
466+
encoder_relative_attention_bias_layers: list[int] | None = None
467+
decoder_relative_attention_bias_layers: list[int] | None = None
465468
is_gated_act: bool = False
466469
scale_decoder_outputs: bool | None = None
467470

@@ -1026,12 +1029,19 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
10261029
getattr(config, "num_decoder_layers", None)
10271030
or getattr(config, "decoder_layers", None)
10281031
),
1032+
decoder_start_token_id=getattr(config, "decoder_start_token_id", None),
10291033
relative_attention_num_buckets=getattr(
10301034
config, "relative_attention_num_buckets", 32
10311035
),
10321036
relative_attention_max_distance=getattr(
10331037
config, "relative_attention_max_distance", 128
10341038
),
1039+
encoder_relative_attention_bias_layers=getattr(
1040+
config, "encoder_relative_attention_bias_layers", None
1041+
),
1042+
decoder_relative_attention_bias_layers=getattr(
1043+
config, "decoder_relative_attention_bias_layers", None
1044+
),
10351045
is_gated_act=getattr(config, "is_gated_act", False),
10361046
scale_decoder_outputs=getattr(config, "scale_decoder_outputs", None),
10371047
# Standalone vision (coerce list to int — some HF configs use [H, W])
@@ -1481,6 +1491,7 @@ def from_transformers(cls, config, parent_config=None) -> NemotronParseConfig:
14811491
)
14821492
fields.update(
14831493
model_type="nemotron_parse",
1494+
decoder_start_token_id=int(getattr(config, "decoder_start_token_id", 2)),
14841495
bos_token_id=getattr(config, "bos_token_id", fields.get("bos_token_id")),
14851496
eos_token_id=getattr(config, "eos_token_id", fields.get("eos_token_id")),
14861497
pad_token_id=getattr(config, "pad_token_id", fields["pad_token_id"]),
@@ -1511,7 +1522,6 @@ def from_transformers(cls, config, parent_config=None) -> NemotronParseConfig:
15111522
image_width=image_width,
15121523
vision_max_grid_size=max_resolution // patch_size,
15131524
num_summary_tokens=3,
1514-
decoder_start_token_id=int(getattr(config, "decoder_start_token_id", 2)),
15151525
scale_embedding=bool(getattr(decoder, "scale_embedding", True)),
15161526
add_final_layer_norm=bool(getattr(decoder, "add_final_layer_norm", True)),
15171527
)

‎src/mobius/_registry.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@
168168
from mobius.models.sensenova_u1 import SenseNovaU1Model
169169
from mobius.models.sensevoice_small import SenseVoiceSmallModel
170170
from mobius.models.starcoder2 import StarCoder2CausalLMModel
171-
from mobius.models.t5 import T5ForConditionalGeneration
171+
from mobius.models.t5 import T5EncoderModel, T5ForConditionalGeneration
172172
from mobius.models.trocr import TrOCRForConditionalGeneration
173173
from mobius.models.vit import ViTModel
174174
from mobius.models.wav2vec2 import Wav2Vec2Model
@@ -808,6 +808,7 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
808808
"prophetnet": ModelRegistration(BartForConditionalGeneration, task="seq2seq"),
809809
"switch_transformers": ModelRegistration(T5ForConditionalGeneration, task="seq2seq"),
810810
"t5": ModelRegistration(T5ForConditionalGeneration, task="seq2seq"),
811+
"t5encoder": ModelRegistration(T5EncoderModel, task="t5-text-encoding"),
811812
"trocr": ModelRegistration(TrOCRForConditionalGeneration, task="seq2seq"),
812813
"umt5": ModelRegistration(T5ForConditionalGeneration, task="seq2seq"),
813814
"xlm-prophetnet": ModelRegistration(BartForConditionalGeneration, task="seq2seq"),

‎src/mobius/components/_encoder_decoder_attention.py‎

Lines changed: 51 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,18 +45,23 @@ def __init__(
4545
has_relative_attention_bias: bool = False,
4646
bias: bool = True,
4747
scale: float | None = None,
48+
linear_class: type | None = None,
4849
):
4950
super().__init__()
51+
if linear_class is None:
52+
linear_class = Linear
5053
self.hidden_size = config.hidden_size
5154
self.num_heads = config.num_attention_heads
5255
self.head_dim = config.head_dim
5356
self.is_causal = is_causal
5457
self._scale = scale if scale is not None else float(self.head_dim**-0.5)
5558

56-
self.q_proj = Linear(self.hidden_size, self.num_heads * self.head_dim, bias=bias)
57-
self.k_proj = Linear(self.hidden_size, self.num_heads * self.head_dim, bias=bias)
58-
self.v_proj = Linear(self.hidden_size, self.num_heads * self.head_dim, bias=bias)
59-
self.out_proj = Linear(self.num_heads * self.head_dim, self.hidden_size, bias=bias)
59+
self.q_proj = linear_class(self.hidden_size, self.num_heads * self.head_dim, bias=bias)
60+
self.k_proj = linear_class(self.hidden_size, self.num_heads * self.head_dim, bias=bias)
61+
self.v_proj = linear_class(self.hidden_size, self.num_heads * self.head_dim, bias=bias)
62+
self.out_proj = linear_class(
63+
self.num_heads * self.head_dim, self.hidden_size, bias=bias
64+
)
6065

6166
if has_relative_attention_bias:
6267
self.relative_attention_bias = Embedding(
@@ -72,6 +77,7 @@ def forward(
7277
key_value_states: ir.Value | None = None,
7378
attention_bias: ir.Value | None = None,
7479
past_key_value: tuple | None = None,
80+
use_cross_attention_cache: bool = False,
7581
):
7682
"""Forward pass.
7783
@@ -89,15 +95,39 @@ def forward(
8995
query_states = self.q_proj(op, hidden_states)
9096

9197
if key_value_states is not None:
92-
# Cross-attention: K/V projected from encoder hidden states.
93-
# Encoder output is constant across decode steps, so we
94-
# recompute the same projections each step and never
95-
# concatenate with past — concatenation would incorrectly
96-
# double the cross-attention sequence length.
98+
# Cache-enabled cross-attention accepts an empty encoder sequence
99+
# during decode; other callers continue to project full encoder
100+
# states on every step.
97101
key_states = self.k_proj(op, key_value_states)
98102
value_states = self.v_proj(op, key_value_states)
99-
past_key = None
100-
past_value = None
103+
if past_key_value is not None:
104+
past_key, past_value = past_key_value
105+
if use_cross_attention_cache:
106+
# Attention requires a non-empty current K/V sequence even
107+
# when past is supplied. Flatten the cached head layout and
108+
# concatenate it with the newly projected encoder suffix.
109+
flat_shape = op.Concat(
110+
op.Shape(past_key, start=0, end=1),
111+
op.Shape(past_key, start=2, end=3),
112+
op.Constant(value_ints=[self.num_heads * self.head_dim]),
113+
axis=0,
114+
)
115+
flat_past_key = op.Reshape(
116+
op.Transpose(past_key, perm=[0, 2, 1, 3]), flat_shape
117+
)
118+
flat_past_value = op.Reshape(
119+
op.Transpose(past_value, perm=[0, 2, 1, 3]), flat_shape
120+
)
121+
key_states = op.Concat(flat_past_key, key_states, axis=1)
122+
value_states = op.Concat(flat_past_value, value_states, axis=1)
123+
# Cross-attention presents the complete K/V sequence as current
124+
# input. Non-caching callers keep the historical behavior of
125+
# recomputing it from full encoder states.
126+
past_key = None
127+
past_value = None
128+
else:
129+
past_key = None
130+
past_value = None
101131
else:
102132
key_states = self.k_proj(op, hidden_states)
103133
value_states = self.v_proj(op, hidden_states)
@@ -120,6 +150,16 @@ def forward(
120150
is_causal=1 if self.is_causal else 0,
121151
_outputs=3,
122152
)
153+
if key_value_states is not None and use_cross_attention_cache:
154+
present_shape = op.Concat(
155+
op.Shape(key_states, start=0, end=1),
156+
op.Constant(value_ints=[self.num_heads]),
157+
op.Shape(key_states, start=1, end=2),
158+
op.Constant(value_ints=[self.head_dim]),
159+
axis=0,
160+
)
161+
present_key = op.Reshape(present_key, present_shape)
162+
present_value = op.Reshape(present_value, present_shape)
123163

124164
output = self.out_proj(op, attn_output)
125165
return output, (present_key, present_value)

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

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -531,12 +531,43 @@
531531
GGUFArchitectureSpec(
532532
gguf_arch="t5",
533533
model_type="t5",
534-
tensor_map=Support.DEFERRED,
535-
quantized_import=Support.REJECTED,
534+
tensor_map_recipe=("t5",),
535+
config_key_map="t5",
536+
config_postprocessor="t5",
537+
required_metadata=(
538+
"context_length",
539+
"embedding_length",
540+
"block_count",
541+
"feed_forward_length",
542+
"attention.head_count",
543+
"attention.layer_norm_rms_epsilon",
544+
"attention.relative_buckets_count",
545+
),
546+
runtime=Support.DEFERRED,
547+
reason=(
548+
"Graph import is covered, but no independent full-logit and generation "
549+
"parity run has yet validated a pinned real T5 GGUF runtime package."
550+
),
551+
),
552+
GGUFArchitectureSpec(
553+
gguf_arch="t5encoder",
554+
model_type="t5encoder",
555+
tensor_map_recipe=("t5",),
556+
config_key_map="t5",
557+
config_postprocessor="t5",
558+
required_metadata=(
559+
"context_length",
560+
"embedding_length",
561+
"block_count",
562+
"feed_forward_length",
563+
"attention.head_count",
564+
"attention.layer_norm_rms_epsilon",
565+
"attention.relative_buckets_count",
566+
),
567+
runtime=Support.DEFERRED,
536568
reason=(
537-
"T5 is an encoder-decoder with separate enc.*/dec.* tensor namespaces, "
538-
"relative attention bias, and cross-attention, none of which the "
539-
"decoder-only GGUF tensor mapping models. " + _NO_TENSOR_MAP
569+
"Encoder hidden-state import is covered, but the pinned real artifact lacks "
570+
"independent provenance and full hidden-state parity evidence."
540571
),
541572
),
542573
GGUFArchitectureSpec(

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

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
#: Number of importable architectures. Pinned so that adding support is a
5757
#: deliberate act that also updates the documented support matrix, and so that
5858
#: accidentally losing an architecture is a failure rather than a silence.
59-
_EXPECTED_SUPPORTED_COUNT = 35
59+
_EXPECTED_SUPPORTED_COUNT = 37
6060

6161
# Quantized reachability is separately pinned from float importability. A new
6262
# architecture must explicitly prove that its graph exposes packed projection
@@ -95,6 +95,8 @@
9595
"smollm3",
9696
"stablelm",
9797
"starcoder2",
98+
"t5",
99+
"t5encoder",
98100
}
99101
)
100102

@@ -288,6 +290,8 @@ class TestPinnedTensorClosure:
288290
"mamba2",
289291
"bert",
290292
"modern-bert",
293+
"t5",
294+
"t5encoder",
291295
)
292296

293297
@staticmethod
@@ -356,6 +360,25 @@ def test_deleting_encoder_mapping_breaks_closure(
356360
mapping[mapping_key] = removed
357361
_build_mapping.cache_clear()
358362

363+
@pytest.mark.parametrize(
364+
("architecture", "mapping_key"),
365+
[
366+
("t5", "dec.blk.{bid}.cross_attn_q"),
367+
("t5encoder", "enc.blk.{bid}.attn_rel_b"),
368+
],
369+
)
370+
def test_deleting_t5_mapping_breaks_closure(
371+
self, architecture: str, mapping_key: str
372+
) -> None:
373+
mapping = _MAPPING_TABLES["t5"]
374+
removed = mapping.pop(mapping_key)
375+
_build_mapping.cache_clear()
376+
try:
377+
assert any(name.startswith(mapping_key) for name in self._unmapped(architecture))
378+
finally:
379+
mapping[mapping_key] = removed
380+
_build_mapping.cache_clear()
381+
359382
def test_deleting_expert_mapping_breaks_moe_closure(self) -> None:
360383
moe_mapping = _MAPPING_TABLES["moe_extras"]
361384
removed = moe_mapping.pop("blk.{bid}.ffn_gate_exps")
@@ -447,7 +470,7 @@ def test_deleting_recurrent_mapping_breaks_closure(
447470
class TestRejectionsAreActionable:
448471
"""An unsupported input must say what it is and what to do instead."""
449472

450-
@pytest.mark.parametrize("architecture", ["bloom", "t5"])
473+
@pytest.mark.parametrize("architecture", ["bloom"])
451474
def test_configurable_but_unmappable_architectures_are_refused(
452475
self, architecture: str
453476
) -> None:

0 commit comments

Comments
 (0)