diff --git a/test/quantization/recipes/export/test_export_gemma4_vision_encoder.py b/test/quantization/recipes/export/test_export_gemma4_vision_encoder.py index b46eaa220..fa8fd04d1 100644 --- a/test/quantization/recipes/export/test_export_gemma4_vision_encoder.py +++ b/test/quantization/recipes/export/test_export_gemma4_vision_encoder.py @@ -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() diff --git a/test/quantization/recipes/export/test_export_gemma4_vision_encoder_with_post.py b/test/quantization/recipes/export/test_export_gemma4_vision_encoder_with_post.py new file mode 100644 index 000000000..60db4aada --- /dev/null +++ b/test/quantization/recipes/export/test_export_gemma4_vision_encoder_with_post.py @@ -0,0 +1,582 @@ +# Copyright (c) 2026 Samsung Electronics Co., Ltd. All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Checkpoint-free numerical and serialized contracts for the two-stage vision path.""" + +import json +import tempfile +import unittest +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import patch + +import numpy as np + +import tico +import torch + +from circle_schema import circle as circle_schema +from tico.circle import CircleDocument +from tico.circle.runtime import CircleReferenceRuntime, ExecutionMode, run_circle +from tico.quantization.recipes.export.gemma4 import _export_gemma4_vision_stages +from tico.quantization.wrapq.dtypes import DType +from tico.quantization.wrapq.wrappers.gemma4.static_vision_profile import ( + DEFAULT_GEMMA4_STATIC_VISION_PROFILE, + Gemma4StaticVisionProfile, + get_gemma4_static_vision_profile, +) +from tico.quantization.wrapq.wrappers.gemma4.vision_split_export import ( + build_gemma4_vision_split_export_bundle, +) + +from test.quantization.quant_spec_helpers import make_affine_ptq_config + +try: + from quantization.recipes.export import ( + test_export_gemma4_vision_encoder as encoder_test, + ) +except ModuleNotFoundError: + from test.quantization.recipes.export import ( + test_export_gemma4_vision_encoder as encoder_test, + ) + + +def _profile(): + """One valid pooled token and one padded pooled slot exercise finalization.""" + return Gemma4StaticVisionProfile( + name="tiny_padded", + visual_start_idx=0, + num_visual_tokens=1, + max_soft_tokens=2, + patch_grid_height=2, + patch_grid_width=2, + patch_size=1, + pooling_kernel_size=2, + ) + + +@unittest.skipUnless( + encoder_test._has_gemma4_vision(), "transformers Gemma4 vision is unavailable" +) +class TestGemma4VisionEncoderWithPostExport(unittest.TestCase): + """Exercise real vision fixtures and their frozen-state comparison helpers.""" + + _assert_observer_state = ( + encoder_test.TestGemma4VisionEncoderExport._assert_observer_state + ) + + def _build(self, *, quantized, spatial_pooling=True): + helper = encoder_test.TestGemma4VisionEncoderExport() + model, _, pixels, before = helper._build(quantized=quantized, padded=True) + bundle = build_gemma4_vision_split_export_bundle( + model, + pixel_position_ids=_profile().build_image_position_ids(), + output_dtype=pixels.dtype, + spatial_pooling=spatial_pooling, + ) + for stage in ( + bundle.monolithic, + bundle.patch_embedder, + bundle.encoder_with_post, + ): + stage.eval() + self._assert_observer_state(before, model) + # Include the prepared profile observers when checking execution/export. + return model, bundle, pixels, encoder_test._observer_state(model) + + def _build_spatial(self, *, quantized): + """Keep the supported geometry while shrinking only the real encoder.""" + from transformers.models.gemma4.configuration_gemma4 import Gemma4VisionConfig + + profile = get_gemma4_static_vision_profile(DEFAULT_GEMMA4_STATIC_VISION_PROFILE) + config = Gemma4VisionConfig( + hidden_size=4, + intermediate_size=8, + num_hidden_layers=1, + num_attention_heads=1, + num_key_value_heads=1, + head_dim=4, + patch_size=profile.patch_size, + position_embedding_size=max( + profile.patch_grid_height, profile.patch_grid_width + ), + pooling_kernel_size=profile.pooling_kernel_size, + attention_dropout=0.0, + use_clipped_linears=False, + rope_parameters={"rope_type": "default", "rope_theta": 100.0}, + standardize=True, + ) + profile.validate(vision_config=config) + torch.manual_seed(17) + # The standalone spatial-pooler test uses this scalar INT16 policy; + # its generated pooling-weight grid preserves the coefficient exactly. + model = encoder_test.TinyVisionOwner( + vision_config=config, + qcfg=make_affine_ptq_config(dtype=DType.int(16)), + ).eval() + pixels = torch.rand(1, profile.num_patches, profile.patch_vector_size) + pixels[:, profile.num_valid_patches :] = 0 + positions = profile.build_image_position_ids() + if quantized: + model.enable_calibration() + with torch.no_grad(): + model(pixels, positions) + model.freeze_qparams() + before = encoder_test._observer_state(model) + bundle = build_gemma4_vision_split_export_bundle( + model, + pixel_position_ids=positions, + output_dtype=pixels.dtype, + spatial_pooling=True, + ) + for stage in ( + bundle.monolithic, + bundle.patch_embedder, + bundle.encoder_with_post, + ): + stage.eval() + self._assert_observer_state(before, model) + return model, bundle, pixels, profile + + def _assert_spatial_circle_matches_pipeline(self, *, quantized): + """Execute actual AveragePool through the full tail, including padding/std. + + Frozen INT16 runs in reference FAKE_QUANTIZE mode, not a native integer + or NPU backend. Compare serialized graphs on the same reference runtime; + eager kernels can accumulate rounding across several quantized stages. + """ + with torch.no_grad(): + model, bundle, pixels, profile = self._build_spatial(quantized=quantized) + pooler = bundle.pooler.wrapped + self.assertIsNotNone(pooler.spatial_profile) + self.assertEqual(pooler.spatial_profile, profile) + self.assertEqual(bundle.encoder.quantized, quantized) + if quantized: + for observer in ( + pooler.obs_act_in, + pooler.obs_pool_in, + pooler.obs_pool_matmul_out, + pooler.obs_pool_out, + ): + state = observer.require_frozen() + self.assertEqual(observer.dtype, DType.int(16)) + self.assertIsNone(observer.channel_axis) + self.assertEqual(state.kind, "affine") + self.assertTrue(state.fake_quant_enabled) + self.assertTrue( + pooler.obs_pool_weight.require_frozen().fake_quant_enabled + ) + torch.testing.assert_close( + pooler.obs_pool_weight.fake_quant(pooler.pool_weights), + pooler.pool_weights, + rtol=0, + atol=0, + ) + before = encoder_test._observer_state(model) + hidden = bundle.patch_embedder(pixels) + context = encoder_test._context(bundle) + encoded = bundle.encoder(hidden, *context) + pooled = bundle.pooler(encoded) + self.assertEqual( + pooled.shape, + (1, profile.max_soft_tokens, model.vision_tower.config.hidden_size), + ) + self.assertEqual( + torch.count_nonzero(pooled[:, profile.num_visual_tokens :]).item(), 0 + ) + expected = bundle.post_projection(pooled) + torch.testing.assert_close( + expected, bundle.monolithic(pixels), rtol=0, atol=0 + ) + args = (hidden, *context) + torch.testing.assert_close( + bundle.encoder_with_post(*args), expected, rtol=0, atol=0 + ) + converted = tico.convert(bundle.encoder_with_post, args, strict=False) + document = CircleDocument.from_bytes(converted.circle_binary) + document.verify() + runtime = CircleReferenceRuntime(document) + program = runtime.program + self.assertEqual( + [op.name for op in program.operators].count("AVERAGE_POOL_2D"), 1 + ) + average_pool = next( + op for op in program.operators if op.name == "AVERAGE_POOL_2D" + ) + self.assertEqual( + (average_pool.options.filterHeight, average_pool.options.filterWidth), + (1, profile.pooling_kernel_size**2), + ) + if quantized: + for index in ( + average_pool.inputs[0], + average_pool.outputs[0], + program.outputs[0], + ): + self.assertEqual(program.tensor(index).dtype, np.dtype(np.int16)) + mode = ExecutionMode.FAKE_QUANTIZE if quantized else ExecutionMode.NATIVE + actual = runtime.run(args, mode=mode).outputs[0] + self.assertEqual(actual.shape, (profile.num_visual_tokens, 4)) + self.assertEqual(actual.dtype, np.dtype(np.float32)) + # The patch stage is shared. Convert only the three existing stages + # after it, keeping the reference comparison checkpoint-free. + split_result = hidden.numpy() + for index, (stage, example_inputs) in enumerate( + ( + (bundle.encoder, args), + (bundle.pooler, (encoded,)), + (bundle.post_projection, (pooled,)), + ) + ): + split_circle = tico.convert(stage, example_inputs, strict=False) + split_document = CircleDocument.from_bytes(split_circle.circle_binary) + split_document.verify() + split_runtime = CircleReferenceRuntime(split_document) + if index == 1: + self.assertIn( + "AVERAGE_POOL_2D", + [op.name for op in split_runtime.program.operators], + ) + split_inputs = ( + (split_result, *context) if index == 0 else (split_result,) + ) + split_result = split_runtime.run(split_inputs, mode=mode).outputs[0] + np.testing.assert_allclose(actual, split_result, rtol=1e-5, atol=1e-5) + if not quantized: + np.testing.assert_allclose( + actual, expected.numpy(), rtol=1e-5, atol=1e-5 + ) + self._assert_observer_state(before, model) + + def test_float_circle_uses_spatial_average_pool(self): + """Default geometry must export and execute AveragePool in the composite.""" + self._assert_spatial_circle_matches_pipeline(quantized=False) + + def test_int16_circle_uses_spatial_average_pool(self): + """Scalar frozen INT16 must activate AveragePool and run FAKE_QUANTIZE.""" + self._assert_spatial_circle_matches_pipeline(quantized=True) + + def test_eager_matches_four_stages_and_monolithic_with_padding_and_standardization( + self, + ): + """Float and frozen INT16 retain valid-token slicing and nontrivial scaling.""" + for quantized in (False, True): + for spatial_pooling in (False, True): + with ( + self.subTest(quantized=quantized, spatial_pooling=spatial_pooling), + torch.no_grad(), + ): + model, bundle, pixels, before = self._build( + quantized=quantized, spatial_pooling=spatial_pooling + ) + composite = bundle.encoder_with_post + self.assertIs(composite.encoder, bundle.encoder) + self.assertIs(composite.pooler, bundle.pooler) + self.assertIs(composite.post_projection, bundle.post_projection) + self.assertEqual( + tuple(dict(composite.named_children())), + ("encoder", "pooler", "post_projection"), + ) + hidden = bundle.patch_embedder(pixels) + context = encoder_test._context(bundle) + encoded = bundle.encoder(hidden, *context) + pooled = bundle.pooler(encoded) + self.assertEqual(pooled.shape, (1, 2, 8)) + four_stages = bundle.post_projection(pooled) + two_stages = composite(hidden, *context) + self.assertEqual(two_stages.shape, (1, 4)) + self.assertEqual(two_stages.dtype, pixels.dtype) + torch.testing.assert_close(two_stages, four_stages, rtol=0, atol=0) + torch.testing.assert_close( + two_stages, bundle.monolithic(pixels), rtol=0, atol=0 + ) + # This negative comparison makes an embed_vision-only tail fail. + projection_only = bundle.post_projection.vision_projection( + pooled[:, :1].reshape(1, 8) + ) + self.assertFalse(torch.allclose(two_stages, projection_only)) + self._assert_observer_state(before, model) + + def test_existing_boundary_observers_are_preserved_inside_composite(self): + """Joining graphs retains both applications of the frozen boundary grids.""" + model, bundle, pixels, before = self._build(quantized=True) + pooler = bundle.pooler.wrapped + with torch.no_grad(): + hidden = bundle.patch_embedder(pixels) + with ExitStack() as stack: + spies = [ + stack.enter_context( + patch.object(observer, "fake_quant", wraps=observer.fake_quant) + ) + for observer in (pooler.obs_act_in, pooler.obs_pool_out) + ] + bundle.encoder_with_post(hidden, *encoder_test._context(bundle)) + self.assertEqual([spy.call_count for spy in spies], [2, 2]) + self._assert_observer_state(before, model) + + def test_torch_export_uses_external_context_and_only_required_state(self): + """Every layer and the full tail are captured without owner/template state.""" + for quantized in (False, True): + with self.subTest(quantized=quantized), torch.no_grad(): + model, bundle, pixels, before = self._build(quantized=quantized) + args = (bundle.patch_embedder(pixels), *encoder_test._context(bundle)) + composite = bundle.encoder_with_post + exported = torch.export.export(composite, args, strict=False) + self.assertEqual( + tuple(exported.graph_signature.user_inputs), + ( + "hidden_states", + "attention_mask", + "position_embeddings_cos", + "position_embeddings_sin", + ), + ) + placeholders = { + str(node.target): node + for node in exported.graph.nodes + if node.op == "placeholder" + } + for name in exported.graph_signature.user_inputs: + self.assertTrue(placeholders[name].users, name) + parameters = tuple(exported.graph_signature.parameters) + for index in range(2): + self.assertTrue( + any( + name.startswith(f"encoder.layers.{index}.") + for name in parameters + ) + ) + self.assertTrue( + any( + name.startswith("post_projection.vision_projection.") + for name in parameters + ) + ) + self.assertTrue( + all( + name.startswith( + ("encoder.layers.", "post_projection.vision_projection.") + ) + for name in parameters + ) + ) + buffers = tuple(exported.graph_signature.buffers) + self.assertFalse(any("template" in name for name in buffers)) + self.assertIn("pooler.wrapped.pool_weights", buffers) + self.assertIn("post_projection.std_bias", buffers) + self.assertIn("post_projection.std_scale", buffers) + # Exported operators also prove pooling and valid-token finalization + # participate; numerical parity alone would miss an unused buffer. + targets = { + str(node.target) + for node in exported.graph.nodes + if node.op == "call_function" + } + self.assertIn("aten.matmul.default", targets) + self.assertIn("aten.slice.Tensor", targets) + self.assertIn("aten.reshape.default", targets) + self.assertIn("aten.sub.Tensor", targets) + self.assertIn("aten.mul.Tensor", targets) + torch.testing.assert_close( + exported.module()(*args), composite(*args), rtol=0, atol=0 + ) + self._assert_observer_state(before, model) + + def _assert_serialized_boundary(self, patch_graph, composite_graph, bundle): + output = patch_graph.tensors[patch_graph.outputs[0]] + input_ = composite_graph.tensors[composite_graph.inputs[0]] + self.assertEqual(output.type, circle_schema.TensorType.TensorType.INT16) + self.assertEqual(input_.type, output.type) + np.testing.assert_array_equal(input_.shape, output.shape) + for field in ("scale", "zeroPoint"): + np.testing.assert_array_equal( + getattr(input_.quantization, field), getattr(output.quantization, field) + ) + self.assertEqual( + input_.quantization.quantizedDimension, + output.quantization.quantizedDimension, + ) + for tensor_index, observer in zip( + composite_graph.inputs, + ( + bundle.encoder.input_observer, + bundle.encoder.attention_mask_observer, + bundle.encoder.position_cos_observer, + bundle.encoder.position_sin_observer, + ), + ): + tensor = composite_graph.tensors[tensor_index] + self.assertEqual(tensor.type, circle_schema.TensorType.TensorType.INT16) + np.testing.assert_array_equal( + tensor.quantization.scale, + observer.frozen_state.scale.reshape(-1).numpy(), + ) + np.testing.assert_array_equal( + tensor.quantization.zeroPoint, + observer.frozen_state.zero_point.reshape(-1).numpy(), + ) + + def test_real_circle_pipeline_routing_contract_and_reference_parity(self): + """Saved two-stage files execute with external context in both pooler policies. + + INT16 files run in FAKE_QUANTIZE reference mode, exchanging real-valued + FLOAT32 tensors. This does not validate a native integer backend. + """ + for quantized in (False, True): + for spatial_pooling in (False, True): + with ( + self.subTest(quantized=quantized, spatial_pooling=spatial_pooling), + tempfile.TemporaryDirectory() as tmpdir, + torch.no_grad(), + ): + model, bundle, pixels, before = self._build( + quantized=quantized, spatial_pooling=spatial_pooling + ) + output_dir = Path(tmpdir) + tag = "q" if quantized else "f32" + _export_gemma4_vision_stages( + gemma_model=model, + qvision=model.vision_tower, + profile=_profile(), + pixel_values=pixels, + pixel_position_ids=_profile().build_image_position_ids(), + text_hidden_size=4, + artifact_tag=tag, + output_dir=output_dir, + granularity="encoder_with_post", + spatial_pooling=spatial_pooling, + strict=False, + ) + manifest = json.loads( + (output_dir / "vision_pipeline.json").read_text() + ) + self.assertEqual( + [stage["id"] for stage in manifest["stages"]], + ["patch_embedder", "encoder_with_post"], + ) + self.assertEqual( + {path.name for path in output_dir.glob("*.circle")}, + { + f"vision_patch_embedder.{tag}.circle", + f"vision_encoder_with_post.{tag}.circle", + }, + ) + self.assertEqual(len(manifest["boundaries"]), 1) + boundary = manifest["boundaries"][0] + self.assertEqual(boundary["producer"], "patch_embedder") + self.assertEqual(boundary["consumer"], "encoder_with_post") + stage = manifest["stages"][1] + self.assertEqual(stage["num_layers"], 2) + self.assertEqual( + [entry["name"] for entry in stage["inputs"]], + [ + "hidden_states", + "attention_mask", + "position_embeddings_cos", + "position_embeddings_sin", + ], + ) + self.assertEqual(stage["outputs"][0]["name"], "visual_embeds") + self.assertEqual(stage["outputs"][0]["shape"], [1, 4]) + self.assertEqual(manifest["profile"], _profile().name) + self.assertTrue(manifest["context_externalized"]) + self.assertEqual(manifest["quantized_export"], quantized) + context_dict = torch.load( + output_dir / manifest["shared_encoder_inputs_artifact"], + weights_only=True, + ) + context = tuple( + context_dict[name] + for name in ( + "attention_mask", + "position_embeddings_cos", + "position_embeddings_sin", + ) + ) + circles = [ + CircleDocument.load(output_dir / entry["artifact"]) + for entry in manifest["stages"] + ] + for document in circles: + document.verify() + graphs = [document.model.subgraphs[0] for document in circles] + self.assertEqual(len(graphs[1].inputs), 4) + for index in graphs[1].inputs: + self.assertTrue( + any( + index in operator.inputs + for operator in graphs[1].operators + ) + ) + final_output = graphs[1].tensors[graphs[1].outputs[0]] + np.testing.assert_array_equal(final_output.shape, [1, 4]) + if quantized: + self._assert_serialized_boundary(graphs[0], graphs[1], bundle) + else: + self.assertEqual( + final_output.type, + circle_schema.TensorType.TensorType.FLOAT32, + ) + mode = ( + ExecutionMode.FAKE_QUANTIZE + if quantized + else ExecutionMode.NATIVE + ) + binaries = [ + (output_dir / entry["artifact"]).read_bytes() + for entry in manifest["stages"] + ] + patch_output = run_circle( + binaries[0], (pixels,), mode=mode + ).outputs[0] + actual = run_circle( + binaries[1], (patch_output, *context), mode=mode + ).outputs[0] + expected = bundle.monolithic(pixels).numpy() + # FP32 attention/matmul kernels may reassociate operations. + # INT16 fake-quant reference also uses floating-point kernels; + # it is not required to be bit-exact across different graphs. + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) + hidden = bundle.patch_embedder(pixels) + encoded = bundle.encoder(hidden, *context) + pooled = bundle.pooler(encoded) + modules_and_args = ( + (bundle.encoder, (hidden, *context)), + (bundle.pooler, (encoded,)), + (bundle.post_projection, (pooled,)), + ) + four_stage = patch_output + for index, (module, args) in enumerate(modules_and_args): + circle = tico.convert(module, args, strict=False) + runtime_args = ( + (four_stage, *context) if index == 0 else (four_stage,) + ) + four_stage = run_circle( + circle.circle_binary, runtime_args, mode=mode + ).outputs[0] + monolithic = tico.convert( + bundle.monolithic, (pixels,), strict=False + ) + monolithic_output = run_circle( + monolithic.circle_binary, (pixels,), mode=mode + ).outputs[0] + np.testing.assert_allclose(actual, four_stage, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose( + actual, monolithic_output, rtol=1e-5, atol=1e-5 + ) + self._assert_observer_state(before, model) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/quantization/recipes/export/test_export_gemma4_vision_split.py b/test/quantization/recipes/export/test_export_gemma4_vision_split.py index 3022b576a..51f5fcf8e 100644 --- a/test/quantization/recipes/export/test_export_gemma4_vision_split.py +++ b/test/quantization/recipes/export/test_export_gemma4_vision_split.py @@ -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", @@ -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) @@ -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"]], @@ -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, @@ -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.""" @@ -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( @@ -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, diff --git a/tico/quantization/examples/configs/README.md b/tico/quantization/examples/configs/README.md index 92bb3f4c0..86a60cbf7 100644 --- a/tico/quantization/examples/configs/README.md +++ b/tico/quantization/examples/configs/README.md @@ -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 diff --git a/tico/quantization/examples/configs/gemma4_e4b_export.yaml b/tico/quantization/examples/configs/gemma4_e4b_export.yaml index ea784d373..7d48fa637 100644 --- a/tico/quantization/examples/configs/gemma4_e4b_export.yaml +++ b/tico/quantization/examples/configs/gemma4_e4b_export.yaml @@ -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 diff --git a/tico/quantization/examples/configs/gemma4_export.yaml b/tico/quantization/examples/configs/gemma4_export.yaml index 208dc9742..7018a1a00 100644 --- a/tico/quantization/examples/configs/gemma4_export.yaml +++ b/tico/quantization/examples/configs/gemma4_export.yaml @@ -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 diff --git a/tico/quantization/recipes/export/README.md b/tico/quantization/recipes/export/README.md index 13cbcbea2..b042d9f2b 100644 --- a/tico/quantization/recipes/export/README.md +++ b/tico/quantization/recipes/export/README.md @@ -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. diff --git a/tico/quantization/recipes/export/gemma4.py b/tico/quantization/recipes/export/gemma4.py index 35b210e63..1ecd41042 100644 --- a/tico/quantization/recipes/export/gemma4.py +++ b/tico/quantization/recipes/export/gemma4.py @@ -82,7 +82,9 @@ ) from tico.quantization.wrapq.wrappers.ptq_wrapper import PTQWrapper -_VISION_EXPORT_GRANULARITIES = frozenset({"monolithic", "encoder", "layer", "both"}) +_VISION_EXPORT_GRANULARITIES = frozenset( + {"monolithic", "encoder", "encoder_with_post", "layer", "both"} +) _PLE_EMBEDDING_FORMATS = frozenset({"auto", "circle", "pt"}) @@ -365,6 +367,12 @@ def _save_vision_pipeline_manifest( context_artifact: str, ) -> None: """Write the execution and shared-input contract for split vision graphs.""" + if granularity == "encoder_with_post": + boundary_contracts = bundle.encoder_with_post_boundary_contracts + elif granularity == "encoder": + boundary_contracts = bundle.encoder_boundary_contracts + else: + boundary_contracts = bundle.boundary_contracts manifest = { "schema_version": 1, "profile": profile.name, @@ -402,11 +410,7 @@ def _save_vision_pipeline_manifest( "consumer": boundary.consumer, "observer": _observer_manifest(boundary.observer), } - for boundary in ( - bundle.encoder_boundary_contracts - if granularity == "encoder" - else bundle.boundary_contracts - ) + for boundary in boundary_contracts ], "stages": stage_artifacts, } @@ -526,17 +530,23 @@ def _export_gemma4_vision_stages( bundle.position_embeddings_cos, bundle.position_embeddings_sin, ) - encoder_stages = ( - [ + encoder_stages: list[tuple[str, str, torch.nn.Module, dict[str, int]]] + if granularity in {"encoder", "encoder_with_post"}: + encoder_module = ( + bundle.encoder_with_post + if granularity == "encoder_with_post" + else bundle.encoder + ) + encoder_stages = [ ( - "encoder", - "vision_encoder", - bundle.encoder, - {"num_layers": len(bundle.encoder_layers)}, + granularity, + f"vision_{granularity}", + encoder_module, + {"num_layers": len(bundle.encoder.layers)}, ) ] - if granularity == "encoder" - else [ + else: + encoder_stages = [ ( f"encoder_layer_{layer_index}", _vision_encoder_stage_stem(layer_index), @@ -545,7 +555,6 @@ def _export_gemma4_vision_stages( ) for layer_index, layer in enumerate(bundle.encoder_layers) ] - ) for stage_id, stem, encoder_stage, metadata in encoder_stages: artifact = _circle_name(stem, artifact_tag) _convert_and_save( @@ -558,7 +567,11 @@ def _export_gemma4_vision_stages( stage_artifacts.append( { "id": stage_id, - "kind": "encoder" if granularity == "encoder" else "encoder_layer", + "kind": ( + granularity + if granularity in {"encoder", "encoder_with_post"} + else "encoder_layer" + ), "artifact": artifact, **metadata, "inputs": [ @@ -582,6 +595,42 @@ def _export_gemma4_vision_stages( ], ], "outputs": [ + { + "name": ( + "visual_embeds" + if granularity == "encoder_with_post" + else "hidden_states" + ), + "shape": ( + [profile.num_visual_tokens, text_hidden_size] + if granularity == "encoder_with_post" + else list(hidden_states.shape) + ), + "compute_dtype": str( + pixel_values.dtype + if granularity == "encoder_with_post" + else hidden_states.dtype + ).removeprefix("torch."), + } + ], + } + ) + + if granularity != "encoder_with_post": + pooler_artifact = _circle_name("vision_pooler", artifact_tag) + _convert_and_save( + bundle.pooler, + (hidden_states,), + output_dir / pooler_artifact, + strict=strict, + config=compile_config, + ) + stage_artifacts.append( + { + "id": "pooler", + "kind": "pooler", + "artifact": pooler_artifact, + "inputs": [ { "name": "hidden_states", "shape": list(hidden_states.shape), @@ -590,72 +639,49 @@ def _export_gemma4_vision_stages( ), } ], + "outputs": [ + { + "name": "pooled_hidden_states", + "shape": list(pooled_hidden_states.shape), + "compute_dtype": str(pooled_hidden_states.dtype).removeprefix( + "torch." + ), + } + ], } ) - pooler_artifact = _circle_name("vision_pooler", artifact_tag) - _convert_and_save( - bundle.pooler, - (hidden_states,), - output_dir / pooler_artifact, - strict=strict, - config=compile_config, - ) - stage_artifacts.append( - { - "id": "pooler", - "kind": "pooler", - "artifact": pooler_artifact, - "inputs": [ - { - "name": "hidden_states", - "shape": list(hidden_states.shape), - "compute_dtype": str(hidden_states.dtype).removeprefix("torch."), - } - ], - "outputs": [ - { - "name": "pooled_hidden_states", - "shape": list(pooled_hidden_states.shape), - "compute_dtype": str(pooled_hidden_states.dtype).removeprefix( - "torch." - ), - } - ], - } - ) - - post_projection_artifact = _circle_name("vision_post_projection", artifact_tag) - _convert_and_save( - bundle.post_projection, - (pooled_hidden_states,), - output_dir / post_projection_artifact, - strict=strict, - config=compile_config, - ) - stage_artifacts.append( - { - "id": "post_projection", - "kind": "post_projection", - "artifact": post_projection_artifact, - "inputs": [ - { - "name": "pooled_hidden_states", - "shape": list(pooled_hidden_states.shape), - "compute_dtype": str(pooled_hidden_states.dtype).removeprefix( - "torch." - ), - } - ], - "outputs": [ - { - "name": "visual_embeds", - "shape": [profile.num_visual_tokens, text_hidden_size], - "compute_dtype": str(pixel_values.dtype).removeprefix("torch."), - } - ], - } - ) + post_projection_artifact = _circle_name("vision_post_projection", artifact_tag) + _convert_and_save( + bundle.post_projection, + (pooled_hidden_states,), + output_dir / post_projection_artifact, + strict=strict, + config=compile_config, + ) + stage_artifacts.append( + { + "id": "post_projection", + "kind": "post_projection", + "artifact": post_projection_artifact, + "inputs": [ + { + "name": "pooled_hidden_states", + "shape": list(pooled_hidden_states.shape), + "compute_dtype": str(pooled_hidden_states.dtype).removeprefix( + "torch." + ), + } + ], + "outputs": [ + { + "name": "visual_embeds", + "shape": [profile.num_visual_tokens, text_hidden_size], + "compute_dtype": str(pixel_values.dtype).removeprefix("torch."), + } + ], + } + ) _save_vision_pipeline_manifest( path=output_dir / "vision_pipeline.json", @@ -1236,9 +1262,10 @@ def export_gemma4_per_layer( dynamic token embedding, fixed-slot multimodal fusion, every text decoder layer, and final norm/LM head. ``vision_granularity`` selects the existing monolithic vision graph, a split patch/encoder-stack/pool/post-projection - pipeline (``encoder``), per-layer encoder artifacts (``layer``), or monolithic - plus per-layer artifacts (``both``). Split encoders share mask and RoPE inputs instead - of embedding duplicate profile tensors. + pipeline (``encoder``), patch plus combined encoder/pool/post-projection + (``encoder_with_post``), per-layer encoder artifacts (``layer``), or monolithic + plus per-layer artifacts (``both``). Split encoders share external mask and + RoPE inputs instead of embedding duplicate profile tensors. When Per-Layer Embeddings are enabled (``hidden_size_per_layer_input > 0``) the exporter additionally emits: diff --git a/tico/quantization/recipes/export/gemma4_artifacts.md b/tico/quantization/recipes/export/gemma4_artifacts.md index f7be73a50..818c25f77 100644 --- a/tico/quantization/recipes/export/gemma4_artifacts.md +++ b/tico/quantization/recipes/export/gemma4_artifacts.md @@ -293,7 +293,7 @@ export: artifacts: - circle_per_layer vision: - granularity: encoder # monolithic | encoder | layer | both + granularity: encoder # monolithic | encoder | encoder_with_post | layer | both spatial_pooling: true # default; applies to e2b_66x36_264 and its geometry alias ``` @@ -302,14 +302,16 @@ With `spatial_pooling: true`, the 36×66 row-major patch grid is grouped into The pooler retains its 280 output slots, frozen activation boundaries and final scaling. The default is `true`; set `false` to keep the pooling MatMul. Other layouts and quantization policies that require the pooling matrix continue to -use MatMul. The option applies to all four granularities, including the separate -pooler graph in `encoder` mode. Integer rounding can differ between target +use MatMul. The option applies to all five granularities, including the separate +pooler graph in `encoder` mode and the combined graph in `encoder_with_post`. +Integer rounding can differ between target kernels. | Granularity | Vision graphs | |---|---| | `monolithic` | One graph containing patch embedding, all encoder layers, pooling, and post projection. | | `encoder` | Four graphs: patch embedder, the complete encoder stack, pooler, and post projection. | +| `encoder_with_post` | Two graphs: a separate patch embedder, then the complete encoder stack + pooler + entire post projection in one graph. | | `layer` | Patch embedder, one graph per encoder layer, pooler, and post projection. | | `both` | The `monolithic` and `layer` forms together. It does not add the `encoder` graph. | @@ -334,6 +336,7 @@ come from the loaded model rather than the E2B example values below. | `vision_prefill.q.circle` | Monolithic vision tower plus `embed_vision` projection. Input `pixel_values` `[1, 2520, 768]`, output visual tokens `[264, 1536]`. | | `vision_patch_embedder.q.circle` | Split stage 1: patch embedding plus the baked positional embedding, output `[1, 2520, 768]`. | | `vision_encoder.q.circle` | `encoder` stage 2: all encoder layers in model order in one graph. Inputs are `hidden_states`, `attention_mask`, `position_embeddings_cos`, `position_embeddings_sin`; output `hidden_states` `[1, 2520, 768]`. | +| `vision_encoder_with_post.q.circle` | `encoder_with_post` stage 2: the complete encoder stack, pooler, and full post projection. Same four encoder inputs; final `visual_embeds` output `[264, 1536]`. | | `vision_encoder_layer_00..15.q.circle` | Split stage 2: the 16 vision encoder layers. Each takes `hidden_states` and the three tensors stored in `vision_context.pt`. | | `vision_pooler.q.circle` | Split stage 3: pools 2520 patches into 280 soft tokens. | | `vision_post_projection.q.circle` | Split stage 4: selects the 264 valid tokens and applies `embed_vision`, output `[264, 1536]`. | @@ -403,6 +406,64 @@ neighboring serialized boundaries directly chainable without recalibration. Pooling, padding removal, valid-token selection, standardization, and the final projection keep their existing stage responsibilities and model/profile settings. +### Encoder with post projection + +`encoder_with_post` exports the patch embedder separately and combines the +entire encoder stack, pooler, and full post projection into one Circle. +Select it through YAML (`export.vision.granularity: encoder_with_post`) or the +existing CLI override: + +```bash +python -m tico.quantization.examples.export \ + --config tico/quantization/examples/configs/gemma4_export.yaml \ + --checkpoint ./out/gemma4_quantized/quantized_model.pt \ + --set export.vision.granularity=encoder_with_post \ + --output-dir ./out/gemma4_quantized/encoder_with_post_circle_layers +``` + +For floating-point export, replace `--checkpoint ...` with `--source model`. +The same option works with `gemma4_e4b_export.yaml`; dimensions and layer count +come from the loaded model and static profile. The existing Python and YAML +defaults remain unchanged. + +In a clean output directory, the only vision Circle files are +`vision_patch_embedder..circle` and +`vision_encoder_with_post..circle`, with `` equal to `q` or `f32`. +The export also writes `vision_context.pt`, `vision_pipeline.json`, and +`vision_profile.json`; text, PLE, and other requested artifacts retain their +existing settings. Export does not remove artifacts from earlier runs. + +```text +vision_patch_embedder(pixel_values) + -> hidden_states +vision_encoder_with_post(hidden_states, attention_mask, position_embeddings_cos, position_embeddings_sin) + -> visual_embeds +``` + +The four inputs follow the encoder contract above: hidden states `[1, S, H]`, +mask `[1, 1, S, S]`, and each RoPE tensor `[1, S, D]`. Mask and RoPE remain +external inputs from `vision_context.pt`. The output is final visual embeddings +`[V, T]`, where `V` is the valid pooled-token count and `T` the text hidden width. +The complete post projection retains padded-token removal, reshape, related +observers, configured standardization, dtype conversion, and `embed_vision`. +Its output semantics match the existing four-stage and monolithic paths. + +The manifest contains exactly two stages, `patch_embedder` and +`encoder_with_post`, with one artifact boundary connecting them. `num_layers` +records the whole encoder stack; the four inputs, final output, profile, and +external context reference describe its contract. Encoder-to-pooler and +pooler-to-post-projection connections are internal operations. All existing +frozen observer applications remain, including repeated quantizers at those +former artifact boundaries. No source observer is recalibrated. Compute/raw +context dtypes and serialized integer dtype/qparams remain distinct as above. + +The existing `StaticGemma4Runtime` debug path constructs a monolithic adapter +directly and does not consume `vision_pipeline.json`. This option changes saved +artifact composition without changing that runtime path. Relative to `encoder`, +vision graph calls decrease from four to two and artifact boundaries from three +to one. Actual NPU comparisons must measure vision latency, intermediate tensor +transfer cost, memory, and final visual embedding numerical agreement. + ### Static vision profile ownership Constants generated for a static export profile have separate local observers diff --git a/tico/quantization/wrapq/wrappers/gemma4/vision_split_export.py b/tico/quantization/wrapq/wrappers/gemma4/vision_split_export.py index 25bfe0727..dc073c308 100644 --- a/tico/quantization/wrapq/wrappers/gemma4/vision_split_export.py +++ b/tico/quantization/wrapq/wrappers/gemma4/vision_split_export.py @@ -302,6 +302,45 @@ def forward( ) +class Gemma4VisionEncoderWithPostExportAdapter(nn.Module): + """Export the encoder, pooler, and complete post-projection as one graph. + + The prepared split components retain all existing quantization operations, + including the frozen observers on either side of their former artifact + boundaries. Only the participating components are registered; context stays + external and no monolithic model or encoder template is owned by this stage. + Capability checks remain at the component entrypoints. + """ + + def __init__( + self, + encoder: nn.Module, + pooler: nn.Module, + post_projection: nn.Module, + ) -> None: + super().__init__() + self.encoder = encoder + self.pooler = pooler + self.post_projection = post_projection + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor, + position_embeddings_cos: torch.Tensor, + position_embeddings_sin: torch.Tensor, + ) -> torch.Tensor: + """Return final visual embeddings from external encoder inputs.""" + hidden_states = self.encoder( + hidden_states, + attention_mask, + position_embeddings_cos, + position_embeddings_sin, + ) + pooled_hidden_states = self.pooler(hidden_states) + return self.post_projection(pooled_hidden_states) + + class Gemma4VisionPostProjectionExportAdapter(nn.Module): """Export static pool-output finalization and text-width projection. @@ -459,6 +498,7 @@ class Gemma4VisionSplitExportBundle: patch_embedder: nn.Module encoder_layers: tuple[nn.Module, ...] encoder: Gemma4VisionEncoderExportAdapter + encoder_with_post: Gemma4VisionEncoderWithPostExportAdapter pooler: nn.Module post_projection: nn.Module attention_mask: torch.Tensor @@ -466,6 +506,7 @@ class Gemma4VisionSplitExportBundle: position_embeddings_sin: torch.Tensor boundary_contracts: tuple[Gemma4VisionBoundaryContract, ...] encoder_boundary_contracts: tuple[Gemma4VisionBoundaryContract, ...] + encoder_with_post_boundary_contracts: tuple[Gemma4VisionBoundaryContract, ...] def build_gemma4_vision_split_export_bundle( @@ -492,7 +533,8 @@ def build_gemma4_vision_split_export_bundle( Returns: A bundle containing the existing monolithic module, the whole encoder - stack, one module per encoder layer, and shared external context tensors. + stack, the encoder with its pooler and complete post-projection, one + module per encoder layer, and shared external context tensors. """ monolithic = build_gemma4_vision_prefill_export_module( wrapped_model, @@ -651,11 +693,26 @@ def build_gemma4_vision_split_export_bundle( capability_owner=wrapped_model, ) + encoder_with_post = Gemma4VisionEncoderWithPostExportAdapter( + encoder_stage, + pooler_export, + post_projection, + ) + encoder_with_post_boundary_contracts = ( + Gemma4VisionBoundaryContract( + name="patch_embedder_to_encoder_with_post", + producer="patch_embedder", + consumer="encoder_with_post", + observer=encoder.obs_act_in, + ), + ) + return Gemma4VisionSplitExportBundle( monolithic=monolithic, patch_embedder=patch_stage, encoder_layers=tuple(layer_stages), encoder=encoder_stage, + encoder_with_post=encoder_with_post, pooler=pooler_export, post_projection=post_projection, attention_mask=encoder.attention_mask_template.detach().clone(), @@ -667,4 +724,5 @@ def build_gemma4_vision_split_export_bundle( ), boundary_contracts=tuple(boundary_contracts), encoder_boundary_contracts=encoder_boundary_contracts, + encoder_with_post_boundary_contracts=encoder_with_post_boundary_contracts, )