From f26585217b2ef3f87e718a06ae3d13740926d66b Mon Sep 17 00:00:00 2001 From: Pablo Carmona Gonzalez Date: Wed, 18 Nov 2026 13:11:24 +0100 Subject: [PATCH 1/5] fix(inference): apply g_max reference correctly in pcm and reram noise models ReRamWan2022NoiseModel raised an AttributeError when coeff_g_max_reference was passed and, with the default coefficients, scaled the noise against g_max instead of the 40 uS fitting reference. The reference is now stored as prog_coeff_g_max_reference, consistent with the PCM models, and legacy pickles are mapped on load. PCMLikeNoiseModel raised the same AttributeError when prog_coeff and prog_coeff_g_max_reference were given together. Both models now warn when the calibrated reference (25 uS for PCM, 40 uS for ReRAM) is overridden while using the default coefficients, since this can produce noise values that differ from the measured hardware ones. Signed-off-by: Pablo Carmona Gonzalez --- src/aihwkit/inference/noise/pcm.py | 23 +++- src/aihwkit/inference/noise/reram.py | 34 +++++- tests/test_inference.py | 176 ++++++++++++++++++++++++++- 3 files changed, 222 insertions(+), 11 deletions(-) diff --git a/src/aihwkit/inference/noise/pcm.py b/src/aihwkit/inference/noise/pcm.py index ad0971d6..8c084097 100644 --- a/src/aihwkit/inference/noise/pcm.py +++ b/src/aihwkit/inference/noise/pcm.py @@ -10,6 +10,7 @@ from copy import deepcopy from typing import List, Optional +from warnings import warn from numpy import log as numpy_log from numpy import sqrt, interp @@ -55,7 +56,8 @@ class PCMLikeNoiseModel(BaseNoiseModel): polynomial fit is given in uS. If ``prog_coeff_g_max_reference`` is not given and `prog_coeffs` are given explicitly, it will be set to - ``g_max`` of the conductance converter. + ``g_max`` of the conductance converter. With the default + coefficients it is 25 uS; overriding it issues a warning. .. _`Nandakumar et al. ICECS (2019)`: https://ieeexplore.ieee.org/abstract/document/8964852 @@ -80,16 +82,29 @@ def __init__( if self.g_max is None: raise ValueError("g_max cannot be established from g_converter") - if prog_coeff_g_max_reference is None: - self.prog_coeff_g_max_reference = self.g_max - if prog_coeff is None: # standard g_max are defined in respect to 25.0 uS. Need to # adjust for that in case g_max is not equal to 25.0 uS self.prog_coeff = [0.26348, 1.9650, -1.1731] self.prog_coeff_g_max_reference = 25.0 + if ( + prog_coeff_g_max_reference is not None + and prog_coeff_g_max_reference != self.prog_coeff_g_max_reference + ): + warn( + f"{self.__class__.__name__}: the default coefficients were fitted with a " + f"reference g_max of {self.prog_coeff_g_max_reference} uS, which is the " + f"value set to prog_coeff_g_max_reference. Overriding it with " + f"prog_coeff_g_max_reference={prog_coeff_g_max_reference} uS could result " + f"in unexpected noise values differing from the measured hardware ones." + ) + self.prog_coeff_g_max_reference = prog_coeff_g_max_reference else: self.prog_coeff = prog_coeff + if prog_coeff_g_max_reference is None: + self.prog_coeff_g_max_reference = self.g_max + else: + self.prog_coeff_g_max_reference = prog_coeff_g_max_reference self.t_0 = t_0 self.t_read = t_read diff --git a/src/aihwkit/inference/noise/reram.py b/src/aihwkit/inference/noise/reram.py index 630d7b7e..223d2618 100644 --- a/src/aihwkit/inference/noise/reram.py +++ b/src/aihwkit/inference/noise/reram.py @@ -10,6 +10,7 @@ from copy import deepcopy from typing import List, Optional, Dict +from warnings import warn from torch import randn_like, Tensor from torch.autograd import no_grad @@ -58,7 +59,9 @@ class ReRamWan2022NoiseModel(BaseNoiseModel): polynomial fit is given in uS. If ``coeff_g_max_reference`` is not given and `coeffs` are given explicitely, it will be set to - ``g_max`` of the conductance converter. + ``g_max`` of the conductance converter. With the default + coefficients it is 40 uS; overriding it issues a warning. + The value is stored as ``prog_coeff_g_max_reference``. .. _`Wan et al. Nature (2022)`: https://www.nature.com/articles/s41586-022-04992-8 @@ -79,22 +82,41 @@ def __init__( if self.g_max is None: raise ValueError("g_max cannot be established from g_converter") - if coeff_g_max_reference is None: - self.coeff_g_max_reference = self.g_max - if coeff_dic is None: # standard g_max are defined in respect to 40.0 uS. Need to # adjust for that in case g_max is not equal to 40.0 uS - coeff_dic = { 1.0: [-16.815, 45.393, -43.853, 16.030, 0.348][::-1], 3600 * 24.0: [-16.458, 47.095, -50.773, 22.086, 0.701][::-1], 3600 * 24.0 * 2: [-11.934, 37.062, -43.507, 20.274, 0.782][::-1], } self.prog_coeff_g_max_reference = 40.0 + if ( + coeff_g_max_reference is not None + and coeff_g_max_reference != self.prog_coeff_g_max_reference + ): + warn( + f"ReRamWan2022NoiseModel: the default coefficients were fitted with a " + f"reference g_max of {self.prog_coeff_g_max_reference} uS, which is the " + f"value set to prog_coeff_g_max_reference. Overriding it with " + f"coeff_g_max_reference={coeff_g_max_reference} uS could result in " + f"unexpected noise values differing from the measured hardware ones." + ) + self.prog_coeff_g_max_reference = coeff_g_max_reference + elif coeff_g_max_reference is None: + self.prog_coeff_g_max_reference = self.g_max + else: + self.prog_coeff_g_max_reference = coeff_g_max_reference self.coeff_dic = coeff_dic self.noise_scale = noise_scale + def __setstate__(self, state: Dict) -> None: + """Map the legacy ``coeff_g_max_reference`` attribute when unpickling.""" + if "coeff_g_max_reference" in state: + legacy_reference = state.pop("coeff_g_max_reference") + state.setdefault("prog_coeff_g_max_reference", legacy_reference) + self.__dict__.update(state) + def _apply_poly(self, g_target: Tensor, coeff: List, scale: float = 1.0) -> Tensor: """Applied polynomial noise""" @@ -104,7 +126,7 @@ def _apply_poly(self, g_target: Tensor, coeff: List, scale: float = 1.0) -> Tens mat *= g_target / self.g_max sig_prog += mat * value - sig_prog *= self.g_max / self.coeff_g_max_reference # type: ignore + sig_prog *= self.g_max / self.prog_coeff_g_max_reference # type: ignore g_prog = g_target + scale * sig_prog * randn_like(g_target) g_prog.clamp_(min=0.0) # no negative conductances allowed diff --git a/tests/test_inference.py b/tests/test_inference.py index 4c50bf11..5dece719 100644 --- a/tests/test_inference.py +++ b/tests/test_inference.py @@ -6,11 +6,16 @@ """Tests for general functionality of layers.""" -from torch import randn +import pickle +import warnings + +from parameterized import parameterized +from torch import randn, full, manual_seed from aihwkit.inference import ( PCMLikeNoiseModel, ReRamCMONoiseModel, + ReRamWan2022NoiseModel, CustomDriftPCMLikeNoiseModel, StateIndependentNoiseModel, SinglePairConductanceConverter, @@ -76,6 +81,175 @@ def test_apply_custom_drift(self): self.assertNotAlmostEqualTensor(noisy_weights, weights) +def _reference_warnings(caught): + """Filter the g_max reference override warnings out of the recorded ones.""" + return [w for w in caught if "prog_coeff_g_max_reference" in str(w.message)] + + +def _custom_drift_model(): + """Minimal custom drift model for ``CustomDriftPCMLikeNoiseModel``.""" + return dict( + g_lst=[0.0, 10.0, 25.0], nu_mean_lst=[0.08, 0.05, 0.03], nu_std_lst=[0.03, 0.02, 0.01] + ) + + +class NoiseModelGMaxReferenceTest(AihwkitTestCase): + """Tests for the ``prog_coeff_g_max_reference`` handling of the noise models. + + The default programming noise coefficients are fitted at a fixed + reference g_max (25 uS for PCM, 40 uS for ReRAM) and the noise is + scaled by ``g_max / prog_coeff_g_max_reference``. + """ + + @parameterized.expand( + [ + ("pcm", PCMLikeNoiseModel, 25.0), + ("reram", ReRamWan2022NoiseModel, 40.0), + ] + ) + def test_default_reference(self, _, model_cls, expected_reference): + """Default coefficients use the calibrated reference regardless of g_max.""" + for g_max in [None, 25.0, 40.0, 80.0]: + kwargs = {} if g_max is None else {"g_max": g_max} + noise_model = model_cls(**kwargs) + self.assertEqual(noise_model.prog_coeff_g_max_reference, expected_reference) + + def test_reram_has_no_legacy_attribute(self): + """ReRAM stores the reference only as ``prog_coeff_g_max_reference``.""" + noise_model = ReRamWan2022NoiseModel() + self.assertFalse(hasattr(noise_model, "coeff_g_max_reference")) + + def test_reram_explicit_reference(self): + """Passing ``coeff_g_max_reference`` does not raise an AttributeError.""" + noise_model = ReRamWan2022NoiseModel(g_max=25.0, coeff_g_max_reference=40.0) + g_prog = noise_model.apply_programming_noise_to_conductance(full((2, 2), 10.0)) + + self.assertEqual(noise_model.prog_coeff_g_max_reference, 40.0) + self.assertEqual(g_prog.shape, (2, 2)) + + def test_pcm_explicit_reference_with_custom_coeff(self): + """Passing ``prog_coeff`` and a reference does not raise an AttributeError.""" + noise_model = PCMLikeNoiseModel( + g_max=40.0, prog_coeff=[0.26348, 1.9650, -1.1731], prog_coeff_g_max_reference=25.0 + ) + g_prog = noise_model.apply_programming_noise_to_conductance(full((2, 2), 10.0)) + + self.assertEqual(noise_model.prog_coeff_g_max_reference, 25.0) + self.assertEqual(g_prog.shape, (2, 2)) + + @parameterized.expand( + [ + ( + "pcm", + PCMLikeNoiseModel, + {"prog_coeff": [0.1, 0.2, 0.3]}, + "prog_coeff_g_max_reference", + ), + ( + "reram", + ReRamWan2022NoiseModel, + {"coeff_dic": {1.0: [0.1, 0.2, 0.3]}}, + "coeff_g_max_reference", + ), + ] + ) + def test_custom_coeff_reference(self, _, model_cls, coeff_kwargs, ref_key): + """With custom coefficients the reference defaults to g_max or the given value.""" + noise_model = model_cls(g_max=50.0, **coeff_kwargs) + self.assertEqual(noise_model.prog_coeff_g_max_reference, 50.0) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + noise_model = model_cls(g_max=50.0, **coeff_kwargs, **{ref_key: 20.0}) + self.assertEqual(noise_model.prog_coeff_g_max_reference, 20.0) + self.assertEqual(_reference_warnings(caught), []) + + @parameterized.expand( + [ + ("pcm", PCMLikeNoiseModel, "prog_coeff_g_max_reference", 25.0), + ("reram", ReRamWan2022NoiseModel, "coeff_g_max_reference", 40.0), + ] + ) + def test_override_default_reference_warns(self, _, model_cls, ref_key, default_reference): + """Overriding the calibrated reference warns and applies the given value.""" + with self.assertWarns(UserWarning) as context: + noise_model = model_cls(g_max=40.0, **{ref_key: 30.0}) + + self.assertEqual(noise_model.prog_coeff_g_max_reference, 30.0) + message = str(context.warning) + self.assertIn(model_cls.__name__, message) + self.assertIn(str(default_reference), message) + self.assertIn("prog_coeff_g_max_reference", message) + + @parameterized.expand( + [ + ("pcm", PCMLikeNoiseModel, "prog_coeff_g_max_reference", 25.0), + ("reram", ReRamWan2022NoiseModel, "coeff_g_max_reference", 40.0), + ] + ) + def test_default_reference_value_does_not_warn(self, _, model_cls, ref_key, reference): + """Passing the calibrated reference explicitly does not warn.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + noise_model = model_cls(g_max=25.0, **{ref_key: reference}) + + self.assertEqual(noise_model.prog_coeff_g_max_reference, reference) + self.assertEqual(_reference_warnings(caught), []) + + def test_custom_drift_pcm_override_warns(self): + """``CustomDriftPCMLikeNoiseModel`` inherits the override warning.""" + with self.assertWarns(UserWarning) as context: + noise_model = CustomDriftPCMLikeNoiseModel( + _custom_drift_model(), g_max=25.0, prog_coeff_g_max_reference=40.0 + ) + + self.assertEqual(noise_model.prog_coeff_g_max_reference, 40.0) + self.assertIn("CustomDriftPCMLikeNoiseModel", str(context.warning)) + + @parameterized.expand( + [ + ("pcm", PCMLikeNoiseModel, "prog_noise_scale"), + ("reram", ReRamWan2022NoiseModel, "noise_scale"), + ] + ) + def test_programming_noise_scales_with_g_max(self, _, model_cls, scale_key): + """Doubling g_max (same relative target) doubles the programming noise.""" + # small noise scale so that no value is clamped at zero conductance + deltas = [] + for g_max in [40.0, 80.0]: + noise_model = model_cls(g_max=g_max, **{scale_key: 0.01}) + g_target = full((10, 10), 0.5 * g_max) + manual_seed(42) + g_prog = noise_model.apply_programming_noise_to_conductance(g_target) + self.assertTrue((g_prog > 0).all()) + deltas.append(g_prog - g_target) + + self.assertTensorAlmostEqual(deltas[1], 2.0 * deltas[0]) + + def test_reram_legacy_pickle(self): + """Pickled ReRAM models with ``coeff_g_max_reference`` are mapped on load.""" + noise_model = ReRamWan2022NoiseModel(g_max=50.0, coeff_dic={1.0: [0.1, 0.2, 0.3]}) + state = dict(noise_model.__dict__) + state["coeff_g_max_reference"] = state.pop("prog_coeff_g_max_reference") + noise_model.__dict__ = state + + loaded = pickle.loads(pickle.dumps(noise_model)) + + self.assertFalse(hasattr(loaded, "coeff_g_max_reference")) + self.assertEqual(loaded.prog_coeff_g_max_reference, 50.0) + loaded.apply_programming_noise_to_conductance(full((2, 2), 10.0)) + + def test_reram_legacy_pickle_keeps_calibrated_reference(self): + """Legacy pickles with default coefficients keep the 40 uS reference.""" + noise_model = ReRamWan2022NoiseModel(g_max=25.0) + noise_model.__dict__["coeff_g_max_reference"] = 25.0 # old buggy state + + loaded = pickle.loads(pickle.dumps(noise_model)) + + self.assertFalse(hasattr(loaded, "coeff_g_max_reference")) + self.assertEqual(loaded.prog_coeff_g_max_reference, 40.0) + + class ConductanceConverterTest(AihwkitTestCase): """Conductance converter test.""" From 1e34c539042756edc6eb03069f9e6077e3103a90 Mon Sep 17 00:00:00 2001 From: Pablo Carmona Gonzalez Date: Wed, 18 Nov 2026 13:43:37 +0100 Subject: [PATCH 2/5] fix(utils): narrow g_max type when setting legacy pcm reference PCMLikeNoiseModel.prog_coeff_g_max_reference is now inferred as float, so assigning the optional g_max in the legacy checkpoint conversion failed mypy. Only copy g_max when it is set, which the noise model constructor already guarantees. Signed-off-by: Pablo Carmona Gonzalez --- src/aihwkit/utils/legacy.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/aihwkit/utils/legacy.py b/src/aihwkit/utils/legacy.py index 78669a55..8b7eabc7 100644 --- a/src/aihwkit/utils/legacy.py +++ b/src/aihwkit/utils/legacy.py @@ -115,10 +115,13 @@ def get_key_from_ending(key_name: str, par_name: str, prefix: str) -> str: rpu_config.mapping.max_input_size = 0 rpu_config.mapping.max_output_size = 0 - if isinstance(rpu_config.noise_model, PCMLikeNoiseModel) and not hasattr( - rpu_config.noise_model, "prog_coeff_g_max_reference" + noise_model = rpu_config.noise_model + if ( + isinstance(noise_model, PCMLikeNoiseModel) + and not hasattr(noise_model, "prog_coeff_g_max_reference") + and noise_model.g_max is not None ): - rpu_config.noise_model.prog_coeff_g_max_reference = rpu_config.noise_model.g_max + noise_model.prog_coeff_g_max_reference = noise_model.g_max if not hasattr(rpu_config, "pre_post"): rpu_config.pre_post = PrePostProcessingParameter() From d02a37ef99185ef85abd739963ebecce050b6498 Mon Sep 17 00:00:00 2001 From: Pablo Carmona Gonzalez Date: Wed, 18 Nov 2026 18:24:41 +0100 Subject: [PATCH 3/5] fix(inference): enforce g_max against prog_coeff_g_max_reference as in hermes Follow the HermesPCMNoiseModel approach: with the default coefficients the reference g_max is fixed (25 uS for PCM, 40 uS for ReRAM) and cannot be overridden, while g_max can be set. With custom coefficients the reference can still be given and falls back to g_max. A g_max larger than prog_coeff_g_max_reference now raises a ValueError, since the coefficients are not characterized beyond it, and a smaller g_max issues a warning. The check lives in BaseNoiseModel and runs on the resolved g_max, so it also covers a g_max coming from the conductance converter. ReRamWan2022NoiseModel defaults g_max to 40 uS when neither g_max nor g_converter are given. Signed-off-by: Pablo Carmona Gonzalez --- src/aihwkit/inference/noise/base.py | 32 +++++ src/aihwkit/inference/noise/pcm.py | 25 ++-- src/aihwkit/inference/noise/reram.py | 26 ++-- tests/test_inference.py | 192 +++++++++++++++++---------- 4 files changed, 177 insertions(+), 98 deletions(-) diff --git a/src/aihwkit/inference/noise/base.py b/src/aihwkit/inference/noise/base.py index 21899636..c64bce61 100644 --- a/src/aihwkit/inference/noise/base.py +++ b/src/aihwkit/inference/noise/base.py @@ -7,6 +7,8 @@ """Base class for the phenomenological noise models for inference.""" from typing import List, Tuple, Optional +from warnings import warn + from torch import Tensor from torch.autograd import no_grad @@ -23,6 +25,36 @@ def __init__(self, g_converter: Optional[BaseConductanceConverter] = None): def __eq__(self, other: object) -> bool: return self.__class__ == other.__class__ and self.__dict__ == other.__dict__ + def _check_g_max_reference(self, g_max: float, g_max_reference: float) -> None: + """Check ``g_max`` against the programming noise reference ``g_max``. + + Args: + g_max: maximal conductance in :math:`\\mu S` used by the model. + g_max_reference: reference :math:`g_\\max` in :math:`\\mu S` the + programming noise coefficients were fitted with. + + Raises: + ValueError: if ``g_max`` is larger than ``g_max_reference``, since + the coefficients are not characterized beyond it. + + Warns: + UserWarning: if ``g_max`` is smaller than ``g_max_reference``. + """ + name = self.__class__.__name__ + if g_max > g_max_reference: + raise ValueError( + f"{name}: g_max ({g_max} uS) cannot be larger than " + f"prog_coeff_g_max_reference ({g_max_reference} uS), the maximal " + f"conductance the programming noise coefficients are characterized for." + ) + if g_max < g_max_reference: + warn( + f"{name}: g_max ({g_max} uS) is smaller than prog_coeff_g_max_reference " + f"({g_max_reference} uS). The programming noise is scaled by " + f"g_max / prog_coeff_g_max_reference, which could result in unexpected " + f"noise values differing from the measured hardware ones." + ) + def __str__( self, exclude_keys: Optional[List[str]] = None, keys: Optional[List[str]] = None ) -> str: diff --git a/src/aihwkit/inference/noise/pcm.py b/src/aihwkit/inference/noise/pcm.py index 8c084097..891692d1 100644 --- a/src/aihwkit/inference/noise/pcm.py +++ b/src/aihwkit/inference/noise/pcm.py @@ -10,7 +10,6 @@ from copy import deepcopy from typing import List, Optional -from warnings import warn from numpy import log as numpy_log from numpy import sqrt, interp @@ -40,7 +39,9 @@ class PCMLikeNoiseModel(BaseNoiseModel): g_converter: instantiated class of the conductance converter (defaults to single pair) g_max: In :math:`\mu S`, the maximal conductance, ie the value - the absolute max of the weights will be mapped to. + the absolute max of the weights will be mapped to. It cannot be + larger than ``prog_coeff_g_max_reference`` (25 uS for the default + coefficients), and a smaller value issues a warning. t_read: Parameter of the 1/f fit (in seconds). t_0: Parameter of the drift fit (first reading time). @@ -57,7 +58,7 @@ class PCMLikeNoiseModel(BaseNoiseModel): ``prog_coeff_g_max_reference`` is not given and `prog_coeffs` are given explicitly, it will be set to ``g_max`` of the conductance converter. With the default - coefficients it is 25 uS; overriding it issues a warning. + coefficients it is fixed to 25 uS and the given value is ignored. .. _`Nandakumar et al. ICECS (2019)`: https://ieeexplore.ieee.org/abstract/document/8964852 @@ -87,18 +88,6 @@ def __init__( # adjust for that in case g_max is not equal to 25.0 uS self.prog_coeff = [0.26348, 1.9650, -1.1731] self.prog_coeff_g_max_reference = 25.0 - if ( - prog_coeff_g_max_reference is not None - and prog_coeff_g_max_reference != self.prog_coeff_g_max_reference - ): - warn( - f"{self.__class__.__name__}: the default coefficients were fitted with a " - f"reference g_max of {self.prog_coeff_g_max_reference} uS, which is the " - f"value set to prog_coeff_g_max_reference. Overriding it with " - f"prog_coeff_g_max_reference={prog_coeff_g_max_reference} uS could result " - f"in unexpected noise values differing from the measured hardware ones." - ) - self.prog_coeff_g_max_reference = prog_coeff_g_max_reference else: self.prog_coeff = prog_coeff if prog_coeff_g_max_reference is None: @@ -106,6 +95,8 @@ def __init__( else: self.prog_coeff_g_max_reference = prog_coeff_g_max_reference + self._check_g_max_reference(self.g_max, self.prog_coeff_g_max_reference) + self.t_0 = t_0 self.t_read = t_read self.prog_noise_scale = prog_noise_scale @@ -186,7 +177,9 @@ class CustomDriftPCMLikeNoiseModel(PCMLikeNoiseModel): g_converter: instantiated class of the conductance converter (defaults to single pair) g_max: In :math:`\mu S`, the maximal conductance, ie the value - the absolute max of the weights will be mapped to. + the absolute max of the weights will be mapped to. It cannot be + larger than ``prog_coeff_g_max_reference`` (25 uS for the default + coefficients), and a smaller value issues a warning. t_read: Parameter of the 1/f fit (in seconds). t_0: Parameter of the drift fit (first reading time). diff --git a/src/aihwkit/inference/noise/reram.py b/src/aihwkit/inference/noise/reram.py index 223d2618..a65831e4 100644 --- a/src/aihwkit/inference/noise/reram.py +++ b/src/aihwkit/inference/noise/reram.py @@ -10,7 +10,6 @@ from copy import deepcopy from typing import List, Optional, Dict -from warnings import warn from torch import randn_like, Tensor from torch.autograd import no_grad @@ -52,7 +51,10 @@ class ReRamWan2022NoiseModel(BaseNoiseModel): g_converter: Instantiated class of the conductance converter (defaults to single pair). g_max: In :math:`\mu S`, the maximal conductance, i.e. the value - the absolute max of the weights will be mapped to. + the absolute max of the weights will be mapped to. It cannot be + larger than ``prog_coeff_g_max_reference``, and a smaller value + issues a warning. With the default coefficients it defaults to + 40 uS when neither ``g_max`` nor ``g_converter`` are given. noise_scale: Additional scale for the noise. coeff_g_max_reference: reference :math:`g_\max` value when fitting the coefficients, since the result of the @@ -60,7 +62,7 @@ class ReRamWan2022NoiseModel(BaseNoiseModel): ``coeff_g_max_reference`` is not given and `coeffs` are given explicitely, it will be set to ``g_max`` of the conductance converter. With the default - coefficients it is 40 uS; overriding it issues a warning. + coefficients it is fixed to 40 uS and the given value is ignored. The value is stored as ``prog_coeff_g_max_reference``. .. _`Wan et al. Nature (2022)`: https://www.nature.com/articles/s41586-022-04992-8 @@ -75,6 +77,10 @@ def __init__( noise_scale: float = 1.0, coeff_g_max_reference: Optional[float] = None, ): + # Fix g_max now: the default coefficients are characterized up to 40.0 uS + if coeff_dic is None and g_max is None: + g_max = 40.0 + g_converter = deepcopy(g_converter) or SinglePairConductanceConverter(g_max=g_max) super().__init__(g_converter) @@ -91,22 +97,12 @@ def __init__( 3600 * 24.0 * 2: [-11.934, 37.062, -43.507, 20.274, 0.782][::-1], } self.prog_coeff_g_max_reference = 40.0 - if ( - coeff_g_max_reference is not None - and coeff_g_max_reference != self.prog_coeff_g_max_reference - ): - warn( - f"ReRamWan2022NoiseModel: the default coefficients were fitted with a " - f"reference g_max of {self.prog_coeff_g_max_reference} uS, which is the " - f"value set to prog_coeff_g_max_reference. Overriding it with " - f"coeff_g_max_reference={coeff_g_max_reference} uS could result in " - f"unexpected noise values differing from the measured hardware ones." - ) - self.prog_coeff_g_max_reference = coeff_g_max_reference elif coeff_g_max_reference is None: self.prog_coeff_g_max_reference = self.g_max else: self.prog_coeff_g_max_reference = coeff_g_max_reference + + self._check_g_max_reference(self.g_max, self.prog_coeff_g_max_reference) self.coeff_dic = coeff_dic self.noise_scale = noise_scale diff --git a/tests/test_inference.py b/tests/test_inference.py index 5dece719..28318b4f 100644 --- a/tests/test_inference.py +++ b/tests/test_inference.py @@ -81,9 +81,13 @@ def test_apply_custom_drift(self): self.assertNotAlmostEqualTensor(noisy_weights, weights) -def _reference_warnings(caught): - """Filter the g_max reference override warnings out of the recorded ones.""" - return [w for w in caught if "prog_coeff_g_max_reference" in str(w.message)] +def _construct(model_cls, *args, **kwargs): + """Construct a noise model and return it with its g_max reference warnings.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + noise_model = model_cls(*args, **kwargs) + reference_warnings = [w for w in caught if "prog_coeff_g_max_reference" in str(w.message)] + return noise_model, reference_warnings def _custom_drift_model(): @@ -94,11 +98,12 @@ def _custom_drift_model(): class NoiseModelGMaxReferenceTest(AihwkitTestCase): - """Tests for the ``prog_coeff_g_max_reference`` handling of the noise models. + """Tests for the ``g_max`` / ``prog_coeff_g_max_reference`` handling of the noise models. The default programming noise coefficients are fitted at a fixed - reference g_max (25 uS for PCM, 40 uS for ReRAM) and the noise is - scaled by ``g_max / prog_coeff_g_max_reference``. + reference g_max (25 uS for PCM, 40 uS for ReRAM) that cannot be + changed. ``g_max`` cannot be larger than the reference, and a + smaller ``g_max`` issues a warning. """ @parameterized.expand( @@ -107,12 +112,84 @@ class NoiseModelGMaxReferenceTest(AihwkitTestCase): ("reram", ReRamWan2022NoiseModel, 40.0), ] ) - def test_default_reference(self, _, model_cls, expected_reference): - """Default coefficients use the calibrated reference regardless of g_max.""" - for g_max in [None, 25.0, 40.0, 80.0]: - kwargs = {} if g_max is None else {"g_max": g_max} - noise_model = model_cls(**kwargs) - self.assertEqual(noise_model.prog_coeff_g_max_reference, expected_reference) + def test_defaults(self, _, model_cls, reference): + """Without arguments g_max equals the calibrated reference and nothing warns.""" + noise_model, caught = _construct(model_cls) + + self.assertEqual(noise_model.g_max, reference) + self.assertEqual(noise_model.prog_coeff_g_max_reference, reference) + self.assertEqual(caught, []) + + @parameterized.expand( + [ + ("pcm", PCMLikeNoiseModel, 25.0), + ("reram", ReRamWan2022NoiseModel, 40.0), + ] + ) + def test_g_max_equal_to_reference_does_not_warn(self, _, model_cls, reference): + """Setting g_max to the calibrated reference does not warn.""" + noise_model, caught = _construct(model_cls, g_max=reference) + + self.assertEqual(noise_model.prog_coeff_g_max_reference, reference) + self.assertEqual(caught, []) + + @parameterized.expand( + [ + ("pcm", PCMLikeNoiseModel, "prog_coeff_g_max_reference", 25.0), + ("reram", ReRamWan2022NoiseModel, "coeff_g_max_reference", 40.0), + ] + ) + def test_reference_ignored_with_default_coeff(self, _, model_cls, ref_key, reference): + """With the default coefficients the given reference is ignored.""" + noise_model, caught = _construct(model_cls, g_max=reference, **{ref_key: 30.0}) + + self.assertEqual(noise_model.prog_coeff_g_max_reference, reference) + self.assertEqual(caught, []) + + @parameterized.expand( + [ + ("pcm", PCMLikeNoiseModel, 25.0), + ("reram", ReRamWan2022NoiseModel, 40.0), + ] + ) + def test_g_max_larger_than_reference_raises(self, _, model_cls, reference): + """g_max larger than the calibrated reference raises an error.""" + with self.assertRaises(ValueError) as context: + model_cls(g_max=reference + 1.0) + + message = str(context.exception) + self.assertIn(model_cls.__name__, message) + self.assertIn(str(reference), message) + self.assertIn("cannot be larger", message) + + @parameterized.expand( + [ + ("pcm", PCMLikeNoiseModel, 25.0), + ("reram", ReRamWan2022NoiseModel, 40.0), + ] + ) + def test_g_max_from_converter_larger_than_reference_raises(self, _, model_cls, reference): + """The check also applies when g_max comes from the conductance converter.""" + g_converter = SinglePairConductanceConverter(g_max=reference + 1.0) + with self.assertRaises(ValueError): + model_cls(g_converter=g_converter) + + @parameterized.expand( + [ + ("pcm", PCMLikeNoiseModel, 25.0), + ("reram", ReRamWan2022NoiseModel, 40.0), + ] + ) + def test_g_max_smaller_than_reference_warns(self, _, model_cls, reference): + """g_max smaller than the calibrated reference warns and keeps the reference.""" + noise_model, caught = _construct(model_cls, g_max=reference / 2) + + self.assertEqual(noise_model.g_max, reference / 2) + self.assertEqual(noise_model.prog_coeff_g_max_reference, reference) + self.assertEqual(len(caught), 1) + message = str(caught[0].message) + self.assertIn(model_cls.__name__, message) + self.assertIn("is smaller than", message) def test_reram_has_no_legacy_attribute(self): """ReRAM stores the reference only as ``prog_coeff_g_max_reference``.""" @@ -121,16 +198,22 @@ def test_reram_has_no_legacy_attribute(self): def test_reram_explicit_reference(self): """Passing ``coeff_g_max_reference`` does not raise an AttributeError.""" - noise_model = ReRamWan2022NoiseModel(g_max=25.0, coeff_g_max_reference=40.0) + noise_model, caught = _construct( + ReRamWan2022NoiseModel, g_max=25.0, coeff_g_max_reference=40.0 + ) g_prog = noise_model.apply_programming_noise_to_conductance(full((2, 2), 10.0)) self.assertEqual(noise_model.prog_coeff_g_max_reference, 40.0) + self.assertEqual(len(caught), 1) # g_max < reference self.assertEqual(g_prog.shape, (2, 2)) def test_pcm_explicit_reference_with_custom_coeff(self): """Passing ``prog_coeff`` and a reference does not raise an AttributeError.""" - noise_model = PCMLikeNoiseModel( - g_max=40.0, prog_coeff=[0.26348, 1.9650, -1.1731], prog_coeff_g_max_reference=25.0 + noise_model, _ = _construct( + PCMLikeNoiseModel, + g_max=20.0, + prog_coeff=[0.26348, 1.9650, -1.1731], + prog_coeff_g_max_reference=25.0, ) g_prog = noise_model.apply_programming_noise_to_conductance(full((2, 2), 10.0)) @@ -154,70 +237,45 @@ def test_pcm_explicit_reference_with_custom_coeff(self): ] ) def test_custom_coeff_reference(self, _, model_cls, coeff_kwargs, ref_key): - """With custom coefficients the reference defaults to g_max or the given value.""" - noise_model = model_cls(g_max=50.0, **coeff_kwargs) + """With custom coefficients the reference can be set and is checked against g_max.""" + # no reference: falls back to g_max + noise_model, caught = _construct(model_cls, g_max=50.0, **coeff_kwargs) self.assertEqual(noise_model.prog_coeff_g_max_reference, 50.0) + self.assertEqual(caught, []) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - noise_model = model_cls(g_max=50.0, **coeff_kwargs, **{ref_key: 20.0}) - self.assertEqual(noise_model.prog_coeff_g_max_reference, 20.0) - self.assertEqual(_reference_warnings(caught), []) - - @parameterized.expand( - [ - ("pcm", PCMLikeNoiseModel, "prog_coeff_g_max_reference", 25.0), - ("reram", ReRamWan2022NoiseModel, "coeff_g_max_reference", 40.0), - ] - ) - def test_override_default_reference_warns(self, _, model_cls, ref_key, default_reference): - """Overriding the calibrated reference warns and applies the given value.""" - with self.assertWarns(UserWarning) as context: - noise_model = model_cls(g_max=40.0, **{ref_key: 30.0}) - - self.assertEqual(noise_model.prog_coeff_g_max_reference, 30.0) - message = str(context.warning) - self.assertIn(model_cls.__name__, message) - self.assertIn(str(default_reference), message) - self.assertIn("prog_coeff_g_max_reference", message) + # reference above g_max: applied, with a warning + noise_model, caught = _construct(model_cls, g_max=50.0, **coeff_kwargs, **{ref_key: 60.0}) + self.assertEqual(noise_model.prog_coeff_g_max_reference, 60.0) + self.assertEqual(len(caught), 1) - @parameterized.expand( - [ - ("pcm", PCMLikeNoiseModel, "prog_coeff_g_max_reference", 25.0), - ("reram", ReRamWan2022NoiseModel, "coeff_g_max_reference", 40.0), - ] - ) - def test_default_reference_value_does_not_warn(self, _, model_cls, ref_key, reference): - """Passing the calibrated reference explicitly does not warn.""" - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - noise_model = model_cls(g_max=25.0, **{ref_key: reference}) - - self.assertEqual(noise_model.prog_coeff_g_max_reference, reference) - self.assertEqual(_reference_warnings(caught), []) + # reference below g_max: error + with self.assertRaises(ValueError): + model_cls(g_max=50.0, **coeff_kwargs, **{ref_key: 20.0}) - def test_custom_drift_pcm_override_warns(self): - """``CustomDriftPCMLikeNoiseModel`` inherits the override warning.""" - with self.assertWarns(UserWarning) as context: - noise_model = CustomDriftPCMLikeNoiseModel( - _custom_drift_model(), g_max=25.0, prog_coeff_g_max_reference=40.0 - ) + def test_custom_drift_pcm_inherits_checks(self): + """``CustomDriftPCMLikeNoiseModel`` applies the same g_max checks.""" + with self.assertRaises(ValueError): + CustomDriftPCMLikeNoiseModel(_custom_drift_model(), g_max=30.0) - self.assertEqual(noise_model.prog_coeff_g_max_reference, 40.0) - self.assertIn("CustomDriftPCMLikeNoiseModel", str(context.warning)) + noise_model, caught = _construct( + CustomDriftPCMLikeNoiseModel, _custom_drift_model(), g_max=20.0 + ) + self.assertEqual(noise_model.prog_coeff_g_max_reference, 25.0) + self.assertEqual(len(caught), 1) + self.assertIn("CustomDriftPCMLikeNoiseModel", str(caught[0].message)) @parameterized.expand( [ - ("pcm", PCMLikeNoiseModel, "prog_noise_scale"), - ("reram", ReRamWan2022NoiseModel, "noise_scale"), + ("pcm", PCMLikeNoiseModel, "prog_noise_scale", 25.0), + ("reram", ReRamWan2022NoiseModel, "noise_scale", 40.0), ] ) - def test_programming_noise_scales_with_g_max(self, _, model_cls, scale_key): + def test_programming_noise_scales_with_g_max(self, _, model_cls, scale_key, reference): """Doubling g_max (same relative target) doubles the programming noise.""" # small noise scale so that no value is clamped at zero conductance deltas = [] - for g_max in [40.0, 80.0]: - noise_model = model_cls(g_max=g_max, **{scale_key: 0.01}) + for g_max in [reference / 2, reference]: + noise_model, _ = _construct(model_cls, g_max=g_max, **{scale_key: 0.01}) g_target = full((10, 10), 0.5 * g_max) manual_seed(42) g_prog = noise_model.apply_programming_noise_to_conductance(g_target) @@ -241,7 +299,7 @@ def test_reram_legacy_pickle(self): def test_reram_legacy_pickle_keeps_calibrated_reference(self): """Legacy pickles with default coefficients keep the 40 uS reference.""" - noise_model = ReRamWan2022NoiseModel(g_max=25.0) + noise_model = ReRamWan2022NoiseModel() noise_model.__dict__["coeff_g_max_reference"] = 25.0 # old buggy state loaded = pickle.loads(pickle.dumps(noise_model)) From 76dce7f5e6fa588a0122607cfce7a814582d8899 Mon Sep 17 00:00:00 2001 From: Pablo Carmona Gonzalez Date: Mon, 23 Nov 2026 16:47:27 +0100 Subject: [PATCH 4/5] fix(noise): set default g_max value in PCMLikeNoiseModel Signed-off-by: Pablo Carmona Gonzalez --- src/aihwkit/inference/noise/pcm.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/aihwkit/inference/noise/pcm.py b/src/aihwkit/inference/noise/pcm.py index 891692d1..cca609f7 100644 --- a/src/aihwkit/inference/noise/pcm.py +++ b/src/aihwkit/inference/noise/pcm.py @@ -79,6 +79,9 @@ def __init__( g_converter = deepcopy(g_converter) or SinglePairConductanceConverter(g_max=g_max) super().__init__(g_converter) + if g_max is None: + g_max = 25.0 + self.g_max = getattr(self.g_converter, "g_max", g_max) if self.g_max is None: raise ValueError("g_max cannot be established from g_converter") From dbd146b43a85b2c77ffaadc2659887d9b9688dc9 Mon Sep 17 00:00:00 2001 From: Pablo Carmona Gonzalez Date: Tue, 24 Nov 2026 17:53:11 +0100 Subject: [PATCH 5/5] fix(noise): handle g_max initialization with prog_coeff check Signed-off-by: Pablo Carmona Gonzalez --- src/aihwkit/inference/noise/pcm.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/aihwkit/inference/noise/pcm.py b/src/aihwkit/inference/noise/pcm.py index cca609f7..b43ad986 100644 --- a/src/aihwkit/inference/noise/pcm.py +++ b/src/aihwkit/inference/noise/pcm.py @@ -41,7 +41,10 @@ class PCMLikeNoiseModel(BaseNoiseModel): g_max: In :math:`\mu S`, the maximal conductance, ie the value the absolute max of the weights will be mapped to. It cannot be larger than ``prog_coeff_g_max_reference`` (25 uS for the default - coefficients), and a smaller value issues a warning. + coefficients), and a smaller value issues a warning. Defaults to + 25 uS when the default ``prog_coeff`` are used. When custom + ``prog_coeff`` are given, it must be passed explicitly (or set + through ``g_converter``), otherwise a ``ValueError`` is raised. t_read: Parameter of the 1/f fit (in seconds). t_0: Parameter of the drift fit (first reading time). @@ -76,12 +79,18 @@ def __init__( drift_scale: float = 1.0, prog_coeff_g_max_reference: Optional[float] = None, ): + if g_max is None and prog_coeff is None: + # default coefficients are fitted with respect to 25 uS + g_max = 25.0 + if g_max is None and g_converter is None: + raise ValueError( + "g_max must be given explicitly (or via g_converter) when " + "custom prog_coeff are used" + ) + g_converter = deepcopy(g_converter) or SinglePairConductanceConverter(g_max=g_max) super().__init__(g_converter) - if g_max is None: - g_max = 25.0 - self.g_max = getattr(self.g_converter, "g_max", g_max) if self.g_max is None: raise ValueError("g_max cannot be established from g_converter")