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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/aihwkit/inference/noise/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
Expand Down
32 changes: 26 additions & 6 deletions src/aihwkit/inference/noise/pcm.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,12 @@ 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. 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).

Expand All @@ -55,7 +60,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 fixed to 25 uS and the given value is ignored.

.. _`Nandakumar et al. ICECS (2019)`: https://ieeexplore.ieee.org/abstract/document/8964852

Expand All @@ -73,23 +79,35 @@ 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)

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")

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
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._check_g_max_reference(self.g_max, self.prog_coeff_g_max_reference)

self.t_0 = t_0
self.t_read = t_read
Expand Down Expand Up @@ -171,7 +189,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).

Expand Down
32 changes: 25 additions & 7 deletions src/aihwkit/inference/noise/reram.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ 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
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 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

Expand All @@ -72,29 +77,42 @@ 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)

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")

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
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

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"""

Expand All @@ -104,7 +122,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

Expand Down
9 changes: 6 additions & 3 deletions src/aihwkit/utils/legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading
Loading