Export text decoder. Returns ExportedProgram.
(
checkpoint_path: str,
quantize: str,
max_seq_len: int,
group_size: int = 128,
tied_embedding: bool = False,
variant: str = "e2b",
quantize_kv_cache: bool = False,
use_custom_sdpa: bool = True,
)
| 444 | |
| 445 | |
| 446 | def _export_text_decoder( |
| 447 | checkpoint_path: str, |
| 448 | quantize: str, |
| 449 | max_seq_len: int, |
| 450 | group_size: int = 128, |
| 451 | tied_embedding: bool = False, |
| 452 | variant: str = "e2b", |
| 453 | quantize_kv_cache: bool = False, |
| 454 | use_custom_sdpa: bool = True, |
| 455 | ): |
| 456 | """Export text decoder. Returns ExportedProgram.""" |
| 457 | from executorch.examples.models.gemma4.quant_utils import ( |
| 458 | apply_embedding_quantization, |
| 459 | apply_linear_quantization, |
| 460 | parse_quantize, |
| 461 | ) |
| 462 | from executorch.examples.models.gemma4.text_decoder.gemma4_config import ( |
| 463 | Gemma4Config, |
| 464 | ) |
| 465 | from executorch.examples.models.gemma4.text_decoder.gemma4_model import Gemma4Model |
| 466 | |
| 467 | config = Gemma4Config.from_config(variant) |
| 468 | config.use_kv_cache = True |
| 469 | config.max_seq_len = max_seq_len |
| 470 | config.enable_dynamic_shape = True |
| 471 | config.use_custom_sdpa = use_custom_sdpa |
| 472 | |
| 473 | if use_custom_sdpa: |
| 474 | from executorch.extension.llm.custom_ops import custom_ops # noqa: F401 |
| 475 | |
| 476 | logger.info("Custom SDPA enabled (tiled flash attention)") |
| 477 | |
| 478 | model_wrapper = Gemma4Model( |
| 479 | config=config, checkpoint_path=checkpoint_path, dtype=torch.float32 |
| 480 | ) |
| 481 | model = model_wrapper.get_eager_model() |
| 482 | model.eval() |
| 483 | |
| 484 | linear_quant, emb_quant = parse_quantize(quantize) |
| 485 | if emb_quant and linear_quant and tied_embedding: |
| 486 | # Share embed_tokens + lm_head via TiedEmbeddingQuantizer. |
| 487 | # weight_dtype matches the embedding quantization (emb8 -> int8, emb4 -> int4). |
| 488 | # lm_head is tied to embed_tokens — linear quantization skips it. |
| 489 | from torchao.prototype.quantization.embedding.api import TiedEmbeddingQuantizer |
| 490 | from torchao.quantization.granularity import PerAxis |
| 491 | |
| 492 | weight_dtype = torch.int4 if emb_quant == "emb4" else torch.int8 |
| 493 | logger.info(f"Applying tied embedding (embed_tokens + lm_head, {emb_quant})...") |
| 494 | TiedEmbeddingQuantizer( |
| 495 | weight_dtype=weight_dtype, |
| 496 | granularity=PerAxis(0), |
| 497 | ).quantize( |
| 498 | model, |
| 499 | embedding_to_unembedding={ |
| 500 | "model.self_decoder.embed_tokens": "model.lm_head", |
| 501 | }, |
| 502 | ) |
| 503 | # Quantize embed_tokens_per_layer with llama's EmbeddingQuantHandler |
no test coverage detected