Skip to content

fix quantization save and load error #21504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
41 changes: 40 additions & 1 deletion keras/src/layers/layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1359,10 +1359,32 @@ def save_own_variables(self, store):
Args:
store: Dict where the state of the model will be saved.
"""
if not getattr(self, "_is_quantized", False):
all_vars = self._trainable_variables + self._non_trainable_variables
for i, v in enumerate(all_vars):
store[f"{i}"] = v
return

# Case: quantized layer
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you invert the if? If getattr(self, "_is_quantized", False): ... (more readable)

quantized_vars = self._get_quantized_variables()
for i, v in enumerate(quantized_vars):
store[f"quantized_{i}"] = v

# Save non-quantized variables
all_vars = self._trainable_variables + self._non_trainable_variables
for i, v in enumerate(all_vars):
non_quantized_vars = [
v for v in all_vars if v not in quantized_vars and v.trainable
]
for i, v in enumerate(non_quantized_vars):
store[f"{i}"] = v

def _get_quantized_variables(self):
quantized_vars = []
for v in self._trainable_variables + self._non_trainable_variables:
if not backend.is_float_dtype(v.dtype):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This assumes that all integral variables come from quantization. But what if you have variables that intrinsically represent ints and are unrelated to quantization? We definitely have layers using int vars.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed this to check for _is_quantized instead

quantized_vars.append(v)
return quantized_vars

def load_own_variables(self, store):
"""Loads the state of the layer.

Expand All @@ -1372,6 +1394,10 @@ def load_own_variables(self, store):
Args:
store: Dict from which the state of the model will be loaded.
"""
if any(key.startswith("quantized_") for key in store.keys()):
self._load_quantized_variables(store)
return

all_vars = self._trainable_variables + self._non_trainable_variables
if len(store.keys()) != len(all_vars):
if len(all_vars) == 0 and not self.built:
Expand Down Expand Up @@ -1407,6 +1433,19 @@ def load_own_variables(self, store):
for i, v in enumerate(all_vars):
v.assign(store[f"{i}"])

def _load_quantized_variables(self, store):
quantized_vars = self._get_quantized_variables()
for i, v in enumerate(quantized_vars):
v.assign(store[f"quantized_{i}"])

# Load non-quantized variables
all_vars = self._trainable_variables + self._non_trainable_variables
non_quantized_vars = [
v for v in all_vars if v not in quantized_vars and v.trainable
]
for i, v in enumerate(non_quantized_vars):
v.assign(store[f"{i}"])

def _track_variable(self, variable):
if variable.trainable:
self._tracker.add_to_store("trainable_variables", variable)
Expand Down
15 changes: 15 additions & 0 deletions keras/src/layers/layer_test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import pickle
from unittest import mock

Expand All @@ -12,6 +13,7 @@
from keras.src import metrics
from keras.src import models
from keras.src import ops
from keras.src import saving
from keras.src import testing
from keras.src.backend.common import global_state
from keras.src.backend.common.remat import RematScope
Expand Down Expand Up @@ -1758,3 +1760,16 @@ def call(self, x):
# foo_mode omitted -> foo_mode defaults to False -> no change
y2 = model(sample_input)
self.assertAllClose(y2, sample_input)

def test_quantized_model_save_and_load(self):
inputs = layers.Input(shape=(None,))
x = layers.Embedding(input_dim=10, output_dim=10)(inputs)
x = layers.Dense(10)(x)
model = models.Model(inputs=inputs, outputs=x)
path = os.path.join(self.get_temp_dir(), "quantized_model.keras")
model.quantize(mode="int8")
model.save(path)

quantized_model = saving.load_model(path)

self.assertTrue(quantized_model.built)