Skip to content
Draft
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
28 changes: 28 additions & 0 deletions test/quantization/config/test_quant_specs.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from tico.quantization.wrapq.observers.ema import EMAObserver
from tico.quantization.wrapq.observers.identity import IdentityObserver
from tico.quantization.wrapq.observers.minmax import MinMaxObserver
from tico.quantization.wrapq.observers.mse import MSEObserver
from tico.quantization.wrapq.observers.mx import MXObserver
from tico.quantization.wrapq.observers.percentile import PercentileObserver
from tico.quantization.wrapq.wrappers.quant_module_base import QuantModuleBase
Expand Down Expand Up @@ -265,6 +266,33 @@ def test_percentile_kwargs_pass_through(self):
self.assertEqual(spec.kwargs["percentile"], 99.9)
self.assertEqual(spec.kwargs["max_samples"], 65536)

def test_mse_observer_name_and_kwargs_pass_through(self):
spec = quant_spec_from_config(
{
"kind": "affine",
"dtype": "uint8",
"observer": "mse",
"num_grid": 40,
"alternating_search": False,
}
)
assert spec is not None
self.assertEqual(spec.observer, MSEObserver)
self.assertEqual(spec.kwargs["num_grid"], 40)
self.assertIs(spec.kwargs["alternating_search"], False)

def test_override_string_observer_resolves_to_class(self):
cfg = PTQConfig(overrides={"act_in": {"observer": "mse", "num_grid": 80}})

kwargs = cfg.get_kwargs("act_in")

self.assertIs(kwargs["observer"], MSEObserver)
self.assertEqual(kwargs["num_grid"], 80)

def test_override_unknown_string_observer_raises(self):
with self.assertRaisesRegex(ValueError, "Unknown affine observer"):
PTQConfig(overrides={"block.proj.act_in": {"observer": "bogus"}})

def test_unknown_observer_raises(self):
with self.assertRaisesRegex(ValueError, "Unknown affine observer"):
quant_spec_from_config(
Expand Down
43 changes: 37 additions & 6 deletions test/quantization/recipes/debug/test_static_gemma4_split_ple.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,34 @@ def forward(self, *args):

@unittest.skipUnless(_has_gemma4(), "transformers Gemma4 modules are required")
class TestStaticGemma4SplitPLE(unittest.TestCase):
def assert_caches_close(self, runtime, expected):
def assert_caches_close(self, runtime, expected, *, producer_rows=None):
"""Compare layer caches with an exact producer-prefix row boundary.

``producer_rows`` is the number of leading K-axis rows written by the
producer's original S-token execution; those stay bit-identical.
Later rows are written by the single-token finalize/decode consumers,
whose GEMM reduction order may round differently across platforms —
the same roundoff the three-path logits tolerance allows. ``None``
requires every row to be bit-identical.
"""
for cache, (key, value) in zip(runtime.layer_caches, expected):
# The producer prefix always has the original S-token execution.
torch.testing.assert_close(cache.past_k, key, atol=0, rtol=0)
torch.testing.assert_close(cache.past_v, value, atol=0, rtol=0)
if producer_rows is None:
torch.testing.assert_close(cache.past_k, key, atol=0, rtol=0)
torch.testing.assert_close(cache.past_v, value, atol=0, rtol=0)
continue
for actual, ref in ((cache.past_k, key), (cache.past_v, value)):
torch.testing.assert_close(
actual[:, :, :producer_rows, :],
ref[:, :, :producer_rows, :],
atol=0,
rtol=0,
)
torch.testing.assert_close(
actual[:, :, producer_rows:, :],
ref[:, :, producer_rows:, :],
atol=1e-5,
rtol=1e-5,
)

def _compare_three_paths(self, *, length, quantized=False, visual_tokens=0):
runtime = fixture.make_runtime(quantized=quantized, visual_tokens=visual_tokens)
Expand All @@ -65,6 +88,10 @@ def _compare_three_paths(self, *, length, quantized=False, visual_tokens=0):
full_hidden = last_hidden[-1]
expected_cache = fixture.cache_snapshot(runtime)
self.assertEqual(runtime.past_len, length)
# The finalize/decode consumers start at the last prompt token's
# physical slot; everything before it is the producer's S-token
# execution and must stay bit-identical across the three paths.
producer_rows = length - 1
continuation = []
for token in (17, 8, 29)[: min(3, 9 - length)]:
result = runtime.decode_one(torch.tensor([[token]]))
Expand All @@ -86,14 +113,18 @@ def _compare_three_paths(self, *, length, quantized=False, visual_tokens=0):
torch.testing.assert_close(
last_hidden[-1], full_hidden, atol=1e-5, rtol=1e-5
)
self.assert_caches_close(runtime, expected_cache)
self.assert_caches_close(
runtime, expected_cache, producer_rows=producer_rows
)
self.assertEqual(runtime.past_len, length)
for token, expected_logits, cache, past_len in continuation:
actual = runtime.decode_one(torch.tensor([[token]]))
torch.testing.assert_close(
actual, expected_logits, atol=1e-5, rtol=1e-5
)
self.assert_caches_close(runtime, cache)
self.assert_caches_close(
runtime, cache, producer_rows=producer_rows
)
self.assertEqual(runtime.past_len, past_len)
handle.remove()
if quantized:
Expand Down
114 changes: 114 additions & 0 deletions test/quantization/wrapq/observers/test_collection_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# 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.

"""Keyword-argument plumbing from ``collect()`` to ``_update_stats()``."""

import unittest

import torch

from tico.quantization.wrapq.observers.base import ObserverBase
from tico.quantization.wrapq.observers.minmax import MinMaxObserver


class _ContextObserver(ObserverBase):
"""Minimal concrete observer whose statistics hook declares ``**kwargs``."""

def __init__(self, **kwargs):
super().__init__(**kwargs)
self.contexts = []

def reset(self) -> None:
self.contexts = []

def _update_stats(self, x: torch.Tensor, **kwargs) -> None:
self.contexts.append(kwargs)

def compute_qparams(self):
return None

def fake_quant(self, x: torch.Tensor) -> torch.Tensor:
return x


class _PlainObserver(ObserverBase):
"""Observer keeping the traditional one-argument statistics override."""

def __init__(self, **kwargs):
super().__init__(**kwargs)
self.updates = 0

def reset(self) -> None:
self.updates = 0

def _update_stats(self, x: torch.Tensor) -> None:
self.updates += 1

def compute_qparams(self):
return None

def fake_quant(self, x: torch.Tensor) -> torch.Tensor:
return x


class TestCollectionContext(unittest.TestCase):
def test_context_observer_receives_kwargs(self):
obs = _ContextObserver(name="ctx")
weight = torch.randn(4)
obs.collect(torch.randn(2, 4), weight=weight, step=3)
self.assertEqual(len(obs.contexts), 1)
self.assertIs(obs.contexts[0]["weight"], weight)
self.assertEqual(obs.contexts[0]["step"], 3)

def test_context_observer_without_kwargs(self):
obs = _ContextObserver(name="ctx")
obs.collect(torch.randn(3))
self.assertEqual(obs.contexts, [{}])

def test_minmax_observer_works_with_and_without_kwargs(self):
data = torch.tensor([-2.0, 5.0, 0.5])
plain = MinMaxObserver(name="plain")
with_context = MinMaxObserver(name="with_context")
plain.collect(data)
with_context.collect(data, weight=torch.randn(2), note="ignored")
self.assertTrue(torch.equal(with_context.min_val, plain.min_val))
self.assertTrue(torch.equal(with_context.max_val, plain.max_val))
self.assertTrue(torch.equal(plain.min_val, torch.tensor(-2.0)))
self.assertTrue(torch.equal(plain.max_val, torch.tensor(5.0)))

def test_plain_override_drops_context_kwargs(self):
obs = _PlainObserver(name="plain")
obs.collect(torch.randn(3))
self.assertEqual(obs.updates, 1)
# A context kwarg must not raise and must still reach the hook.
obs.collect(torch.randn(3), weight=torch.randn(2))
self.assertEqual(obs.updates, 2)

def test_disabled_collection_skips_stats_even_with_kwargs(self):
obs = _ContextObserver(name="ctx")
obs.enabled = False
obs.collect(torch.randn(2, 3), weight=torch.randn(2))
self.assertEqual(obs.contexts, [])
# Shape observation still happened, matching the existing gate contract.
self.assertEqual(obs._observed_shape, (2, 3))

def test_frozen_observer_ignores_context_kwargs(self):
obs = _ContextObserver(name="ctx")
obs._frozen = True
obs.collect(torch.randn(3), weight=torch.randn(2))
self.assertEqual(obs.contexts, [])


if __name__ == "__main__":
unittest.main()
9 changes: 5 additions & 4 deletions test/quantization/wrapq/observers/test_frozen_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from tico.quantization.wrapq.observers.ema import EMAObserver
from tico.quantization.wrapq.observers.identity import IdentityObserver
from tico.quantization.wrapq.observers.minmax import MinMaxObserver
from tico.quantization.wrapq.observers.mse import MSEObserver
from tico.quantization.wrapq.observers.mx import MXObserver
from tico.quantization.wrapq.observers.percentile import PercentileObserver
from tico.quantization.wrapq.qscheme import QScheme
Expand All @@ -37,7 +38,7 @@ def _tensor(value: Optional[torch.Tensor]) -> torch.Tensor:

class FrozenObserverStateTest(unittest.TestCase):
def test_missing_empty_and_zero_are_distinct(self):
for cls in (MinMaxObserver, EMAObserver, PercentileObserver):
for cls in (MinMaxObserver, EMAObserver, MSEObserver, PercentileObserver):
for dtype, scheme in (
(UINT8, QScheme.PER_TENSOR_ASYMM),
(INT16, QScheme.PER_TENSOR_SYMM),
Expand All @@ -59,7 +60,7 @@ def test_missing_empty_and_zero_are_distinct(self):

def test_nonfinite_is_invalid_not_missing(self):
for values in ([float("nan"), 1.0], [float("-inf"), float("inf")]):
for cls in (MinMaxObserver, EMAObserver):
for cls in (MinMaxObserver, EMAObserver, MSEObserver):
with self.subTest(observer=cls.__name__, values=values):
obs = cls(name="bad")
obs.collect(torch.tensor(values))
Expand All @@ -73,7 +74,7 @@ def test_nonfinite_is_invalid_not_missing(self):
self.assertEqual(percentile.derive_candidate().provenance, "calibrated")

def test_every_affine_subtype_prefers_locked_grid(self):
for cls in (MinMaxObserver, EMAObserver, PercentileObserver):
for cls in (MinMaxObserver, EMAObserver, MSEObserver, PercentileObserver):
with self.subTest(observer=cls.__name__):
obs = cls(name="locked")
scale, zp = torch.tensor(0.3), torch.tensor(7)
Expand Down Expand Up @@ -278,7 +279,7 @@ def test_grid_shape_axis_and_symmetric_policy_validation(self):
invalid_axis.load_qparams(torch.ones(2), torch.zeros(2))

def test_exact_calibrated_and_imported_state_roundtrip(self):
for cls in (MinMaxObserver, EMAObserver, PercentileObserver):
for cls in (MinMaxObserver, EMAObserver, MSEObserver, PercentileObserver):
for imported in (False, True):
with self.subTest(observer=cls.__name__, imported=imported):
obs = cls(name="roundtrip")
Expand Down
Loading
Loading