Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -65,26 +65,33 @@ def _has_gemma4_vision() -> bool:
class TinyVisionOwner(QuantModuleBase):
"""Own production vision wrappers without allocating a language model."""

def __init__(self):
def __init__(self, *, vision_config=None, qcfg=None):
from transformers.models.gemma4.configuration_gemma4 import Gemma4VisionConfig
from transformers.models.gemma4.modeling_gemma4 import Gemma4VisionModel

qcfg = PTQConfig(activation=affine(DType.int(16)), weight=affine(DType.int(16)))
if qcfg is None:
qcfg = PTQConfig(
activation=affine(DType.int(16)), weight=affine(DType.int(16))
)
super().__init__(qcfg)
config = Gemma4VisionConfig(
hidden_size=8,
intermediate_size=16,
num_hidden_layers=2,
num_attention_heads=2,
num_key_value_heads=2,
head_dim=4,
patch_size=1,
position_embedding_size=8,
pooling_kernel_size=2,
attention_dropout=0.0,
use_clipped_linears=False,
rope_parameters={"rope_type": "default", "rope_theta": 100.0},
standardize=True,
config = (
vision_config
if vision_config is not None
else Gemma4VisionConfig(
hidden_size=8,
intermediate_size=16,
num_hidden_layers=2,
num_attention_heads=2,
num_key_value_heads=2,
head_dim=4,
patch_size=1,
position_embedding_size=8,
pooling_kernel_size=2,
attention_dropout=0.0,
use_clipped_linears=False,
rope_parameters={"rope_type": "default", "rope_theta": 100.0},
standardize=True,
)
)
config._attn_implementation = "eager"
fp_vision = Gemma4VisionModel(config).eval()
Expand Down

Large diffs are not rendered by default.

151 changes: 114 additions & 37 deletions test/quantization/recipes/export/test_export_gemma4_vision_split.py
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ def fake_convert_and_save(module, example_inputs, save_path, **kwargs):
self.assertIn("scale", manifest["boundaries"][0]["observer"])

def test_granularities_keep_distinct_artifact_sets_and_default(self) -> None:
"""Encoder groups the stack; both and the API default keep their meaning."""
"""Every granularity keeps its artifact set and manifest composition."""
split = [
"vision_patch_embedder",
"vision_encoder_layer_00",
Expand All @@ -663,6 +663,10 @@ def test_granularities_keep_distinct_artifact_sets_and_default(self) -> None:
("layer", split),
("both", ["vision_prefill", *split]),
("encoder", encoder),
(
"encoder_with_post",
["vision_patch_embedder", "vision_encoder_with_post"],
),
):
with self.subTest(tag=tag, granularity=granularity):
export_model = FakeExportModel(num_vision_layers=3)
Expand Down Expand Up @@ -703,41 +707,87 @@ def record_conversion(module, example_inputs, save_path, **kwargs):
sorted(p.name for p in out.glob("vision_*.circle")),
sorted(f"{stem}.{tag}.circle" for stem in stems),
)
self.assertEqual(
[
name
for _, _, name, _ in calls
if name.startswith("vision_")
],
[f"{stem}.{tag}.circle" for stem in stems],
)
self.assertEqual(
{
p.name
for p in out.glob("*.circle")
if not p.name.startswith("vision_")
},
{
f"token_embedding.{tag}.circle",
f"multimodal_fusion_prefill.{tag}.circle",
f"decoder_layer_prefill_0.{tag}.circle",
f"decoder_layer_decode_0.{tag}.circle",
f"lm_head.{tag}.circle",
},
)
for _, _, name, kwargs in calls:
if name.startswith("vision_"):
self.assertIs(kwargs["config"], config)
self.assertTrue(kwargs["strict"])
if granularity != "encoder":
self.assertTrue((out / "vision_profile.json").exists())
if granularity in (None, "monolithic"):
self.assertFalse((out / "vision_pipeline.json").exists())
continue
manifest = json.loads(
(out / "vision_pipeline.json").read_text()
)
self.assertEqual(manifest["granularity"], "encoder")
self.assertIsNone(manifest["monolithic_artifact"])
self.assertEqual(manifest["granularity"], granularity)
expected_monolithic = (
f"vision_prefill.{tag}.circle"
if granularity == "both"
else None
)
self.assertEqual(
manifest["monolithic_artifact"], expected_monolithic
)
self.assertEqual(
len(manifest["stages"]),
len(stems) - (granularity == "both"),
)
self.assertEqual(
len(manifest["boundaries"]), len(manifest["stages"]) - 1
)
if granularity not in ("encoder", "encoder_with_post"):
continue
stage_ids = (
["patch_embedder", "encoder_with_post"]
if granularity == "encoder_with_post"
else [
"patch_embedder",
"encoder",
"pooler",
"post_projection",
]
)
self.assertEqual(manifest["schema_version"], 1)
self.assertEqual(manifest["artifact_tag"], tag)
self.assertEqual(
[s["id"] for s in manifest["stages"]],
["patch_embedder", "encoder", "pooler", "post_projection"],
stage_ids,
)
self.assertEqual(
[s["artifact"] for s in manifest["stages"]],
[f"{stem}.{tag}.circle" for stem in encoder],
[f"{stem}.{tag}.circle" for stem in stems],
)
self.assertEqual(
[
(b["producer"], b["consumer"])
for b in manifest["boundaries"]
],
[
("patch_embedder", "encoder"),
("encoder", "pooler"),
("pooler", "post_projection"),
],
list(zip(stage_ids, stage_ids[1:])),
)
stage = manifest["stages"][1]
self.assertEqual(stage["num_layers"], 3)
self.assertEqual(stage["kind"], "encoder")
self.assertEqual(stage["kind"], granularity)
self.assertNotIn("layer_index", stage)
self.assertEqual(
[t["name"] for t in stage["inputs"]],
Expand All @@ -749,7 +799,27 @@ def record_conversion(module, example_inputs, save_path, **kwargs):
],
)
self.assertEqual(stage["inputs"][0]["shape"], [1, 4, 2])
self.assertEqual(stage["outputs"][0]["shape"], [1, 4, 2])
output = stage["outputs"][0]
self.assertEqual(
output["shape"],
[4, 4] if granularity == "encoder_with_post" else [1, 4, 2],
)
self.assertEqual(
output["name"],
(
"visual_embeds"
if granularity == "encoder_with_post"
else "hidden_states"
),
)
self.assertEqual(output["compute_dtype"], "float32")
self.assertEqual(stage["inputs"][0]["compute_dtype"], "float32")
boundary = manifest["boundaries"][0]["observer"]
self.assertEqual(boundary["scale"]["values"], [0.25])
self.assertEqual(boundary["zero_point"]["values"], [0])
self.assertEqual(
stage["inputs"][1:], manifest["shared_encoder_inputs"]
)
context = torch.load(
out / manifest["shared_encoder_inputs_artifact"],
weights_only=True,
Expand All @@ -769,31 +839,36 @@ def record_conversion(module, example_inputs, save_path, **kwargs):
)
self.assertEqual(manifest["static_profile"]["num_patches"], 4)

def test_encoder_forwards_spatial_pooling_options(self) -> None:
def test_encoder_and_composite_forward_spatial_pooling_options(self) -> None:
"""Encoder granularity retains both configured pooler export policies."""
for spatial_pooling in (False, True):
with self.subTest(spatial_pooling=spatial_pooling):
export_model = FakeExportModel(num_vision_layers=3)
with (
tempfile.TemporaryDirectory() as tmpdir,
patch.object(
gemma_export,
"_prepare_gemma4_export_model",
return_value=(export_model, "q"),
),
patch.object(gemma_export, "_convert_and_save"),
for granularity in ("encoder", "encoder_with_post"):
for spatial_pooling in (False, True):
with self.subTest(
granularity=granularity, spatial_pooling=spatial_pooling
):
gemma_export.export_gemma4_per_layer(
q_model=torch.nn.Identity(),
max_seq_len=4,
output_dir=tmpdir,
model_args=_model_args(),
vision_granularity="encoder",
spatial_pooling=spatial_pooling,
export_model = FakeExportModel(num_vision_layers=3)
with (
tempfile.TemporaryDirectory() as tmpdir,
patch.object(
gemma_export,
"_prepare_gemma4_export_model",
return_value=(export_model, "q"),
),
patch.object(gemma_export, "_convert_and_save"),
):
gemma_export.export_gemma4_per_layer(
q_model=torch.nn.Identity(),
max_seq_len=4,
output_dir=tmpdir,
model_args=_model_args(),
vision_granularity=granularity,
spatial_pooling=spatial_pooling,
)
gemma_model = cast(
FakeGemmaModel, export_model.wrapped.model.wrapped
)
gemma_model = cast(FakeGemmaModel, export_model.wrapped.model.wrapped)
vision = cast(FakeVision, gemma_model.vision_tower.wrapped)
self.assertIs(vision.last_spatial_pooling, spatial_pooling)
vision = cast(FakeVision, gemma_model.vision_tower.wrapped)
self.assertIs(vision.last_spatial_pooling, spatial_pooling)

def test_invalid_vision_options_fail_before_model_preparation(self) -> None:
"""Invalid split options should fail before loading or wrapping a model."""
Expand Down Expand Up @@ -841,7 +916,9 @@ def test_adapter_forwards_nested_vision_export_options(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
config_path = Path(tmpdir) / "export.json"
config_path.write_text(json.dumps(cfg))
cfg = load_recipe_config(config_path, ["export.vision.granularity=encoder"])
cfg = load_recipe_config(
config_path, ["export.vision.granularity=encoder_with_post"]
)
ctx = RecipeContext(cfg=cfg, adapter=Gemma4Adapter(), model=model)

with patch.object(
Expand All @@ -857,7 +934,7 @@ def test_adapter_forwards_nested_vision_export_options(self) -> None:
model_args=_model_args(),
prefill_decode=True,
strict=False,
vision_granularity="encoder",
vision_granularity="encoder_with_post",
spatial_pooling=False,
ple_embedding_format="auto",
ple_prefill_split=False,
Expand Down
10 changes: 7 additions & 3 deletions tico/quantization/examples/configs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -947,9 +947,13 @@ Rules:
and [generation CLI](../README.md#generate-from-a-llama-circle-bundle).
- Qwen3-VL Circle export requires `model_args.profile: npu_export`, and its
fixed vision grid/start/merge values must match the wrapped checkpoint.
- Gemma4 `export.vision.granularity` accepts `monolithic`, `encoder`, `layer`,
or `both`. `encoder` exports the complete vision pipeline as patch embedder,
whole encoder stack, pooler, and post projection. `layer` splits each encoder
- Gemma4 `export.vision.granularity` accepts `monolithic`, `encoder`,
`encoder_with_post`, `layer`, or `both`. `encoder` exports the complete vision
pipeline as patch embedder, whole encoder stack, pooler, and post projection.
`encoder_with_post` keeps the patch embedder separate and combines the entire
encoder stack, pooler, and full post projection into one graph (two vision
Circle files). Select it with
`--set export.vision.granularity=encoder_with_post`. `layer` splits each encoder
layer instead; `both` retains monolithic plus layer export. The API default
is `monolithic`, while the E2B/E4B export presets keep `both`. Select the
four-stage form with `--set export.vision.granularity=encoder`; see the
Expand Down
3 changes: 2 additions & 1 deletion tico/quantization/examples/configs/gemma4_e4b_export.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ export:
ple_prefill_split: false # Requires .pt lookup and last-token-only runtime prefill.
strict: false
vision:
granularity: both # monolithic | encoder | layer | both
granularity: both # monolithic | encoder | encoder_with_post | layer | both
# Use 'encoder' to export all encoder layers as a single graph,
# with the patch embedder, pooler, and post projection exported separately.
# 'encoder_with_post': patch separately, then encoder + pooler + full post projection.
artifacts:
- circle_per_layer
3 changes: 2 additions & 1 deletion tico/quantization/examples/configs/gemma4_export.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ export:
ple_prefill_split: false # Requires .pt lookup and last-token-only runtime prefill.
strict: false
vision:
granularity: both # monolithic | encoder | layer | both
granularity: both # monolithic | encoder | encoder_with_post | layer | both
# Use 'encoder' to export all encoder layers as a single graph,
# with the patch embedder, pooler, and post projection exported separately.
# 'encoder_with_post': patch separately, then encoder + pooler + full post projection.
artifacts:
- circle_per_layer
6 changes: 4 additions & 2 deletions tico/quantization/recipes/export/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,14 @@ prefill-only variant.

`export.vision.granularity` selects `monolithic` (the whole vision pipeline),
`encoder` (one encoder-stack graph and separate patch, pooler, and projection
graphs), `layer` (one graph per encoder layer plus those three stages), or
graphs), `encoder_with_post` (a separate patch graph and one combined graph for
the entire encoder stack, pooler, and full post projection),
`layer` (one graph per encoder layer plus those three stages), or
`both` (monolithic and layer forms). The Python API default remains
`monolithic`; the E2B/E4B export presets retain `both`.
`export.vision.spatial_pooling` (default `true`) exports the default static
profile's pooler as AveragePool; `false` keeps the pooling MatMul. This setting
applies to all four granularities, including `encoder`.
applies to all five granularities, including `encoder_with_post`.
See the [vision artifact contract](gemma4_artifacts.md#circle_layers-vision-pipeline)
for the stage files, runtime context, manifest, and profile ownership rules.

Expand Down
Loading
Loading