Skip to content

Commit da9acaa

Browse files
ratgrtensorflower-gardener
authored andcommitted
Enforce Keras safe mode when loading models in evaluate_pruning.
The evaluate_pruning tool now loads models with Keras safe mode enabled for all formats, including HDF5 and SavedModel. Python code embedded in the model (e.g. in Lambda layers) is no longer deserialized by default. Pass the new --allow_unsafe_deserialization flag to allow it, but only for models from trusted sources. PiperOrigin-RevId: 1029425737
1 parent f0547d3 commit da9acaa

3 files changed

Lines changed: 213 additions & 5 deletions

File tree

‎tensorflow_model_optimization/python/core/sparsity/keras/tools/BUILD‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,40 @@ py_test(
4242
],
4343
)
4444

45+
py_library(
46+
name = "evaluate_pruning_lib",
47+
srcs = ["evaluate_pruning.py"],
48+
deps = [
49+
":sparsity_tooling",
50+
# absl:app dep1,
51+
# absl/flags dep1,
52+
# tensorflow dep1,
53+
"//tensorflow_model_optimization/python/core/keras:compat",
54+
"//tensorflow_model_optimization/python/core/sparsity/keras:prune",
55+
],
56+
)
57+
4558
py_binary(
4659
name = "evaluate_pruning",
4760
srcs = ["evaluate_pruning.py"],
4861
# strict_deps = False,
4962
deps = [
50-
":sparsity_tooling",
63+
":evaluate_pruning_lib",
5164
# google/protobuf:use_fast_cpp_protos dep1, # Automatically added
65+
],
66+
)
67+
68+
py_test(
69+
name = "evaluate_pruning_test",
70+
size = "medium",
71+
srcs = ["evaluate_pruning_test.py"],
72+
deps = [
73+
":evaluate_pruning_lib",
74+
# absl/testing:parameterized dep1,
75+
# google/protobuf:use_fast_cpp_protos dep1,
76+
# numpy dep1,
5277
# tensorflow dep1,
5378
"//tensorflow_model_optimization/python/core/keras:compat",
54-
"//tensorflow_model_optimization/python/core/sparsity/keras:prune",
5579
],
5680
)
5781

‎tensorflow_model_optimization/python/core/sparsity/keras/tools/evaluate_pruning.py‎

Lines changed: 65 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,11 @@
2525

2626
from __future__ import print_function
2727

28+
import importlib
2829
import os
2930
import tempfile
3031
import textwrap
32+
import types
3133
import zipfile
3234

3335
from absl import app
@@ -51,6 +53,13 @@
5153
'block_size', '1,1',
5254
'Comma-separated dimensions (height,weight) of the block sparsity pattern.'
5355
)
56+
_ALLOW_UNSAFE_DESERIALIZATION = flags.DEFINE_bool(
57+
'allow_unsafe_deserialization',
58+
False,
59+
'Allow deserialization of Python bytecode embedded in the model (e.g. '
60+
'`Lambda` layers). This can lead to arbitrary code execution, so only '
61+
'enable it for models from trusted sources.',
62+
)
5463

5564

5665
def _parse_block_size_flag(value):
@@ -67,6 +76,47 @@ def _check_block_size(flag_value):
6776
raise flags.ValidationError('Invalid block size value "%s".' % flag_value)
6877

6978

79+
def _get_serialization_lib() -> types.ModuleType:
80+
"""Returns the Keras `serialization_lib` module, which holds safe mode."""
81+
# `serialization_lib` lives next to `load_model` in the Keras `saving`
82+
# package, whose import path differs between Keras distributions (e.g.
83+
# `tf_keras.saving` vs `tf_keras.src.saving`).
84+
saving_package = keras.models.load_model.__module__.rpartition('.')[0]
85+
return importlib.import_module(saving_package + '.serialization_lib')
86+
87+
88+
def load_model(
89+
model_path: str, allow_unsafe_deserialization: bool = False
90+
) -> keras.Model:
91+
"""Loads a Keras model, disallowing unsafe deserialization by default.
92+
93+
`keras.models.load_model(..., safe_mode=True)` only guards the native
94+
`.keras` format. Legacy formats (e.g. HDF5) can embed Python bytecode in
95+
`Lambda` layers, which would be executed on load. To protect against
96+
arbitrary code execution, safe mode is enforced for every format through
97+
Keras' `SafeModeScope`.
98+
99+
For SavedModel directories, safe mode does not raise an error. Instead, Keras
100+
revives such layers from their traced graph functions, without deserializing
101+
the embedded Python bytecode.
102+
103+
Args:
104+
model_path: Path to the Keras model to load.
105+
allow_unsafe_deserialization: Whether to allow deserialization of Python
106+
bytecode embedded in the model. Only set this for trusted models.
107+
108+
Returns:
109+
The loaded Keras model.
110+
111+
Raises:
112+
ValueError: If an HDF5 or `.keras` model contains unsafe objects and
113+
`allow_unsafe_deserialization` is False.
114+
"""
115+
safe_mode = not allow_unsafe_deserialization
116+
with _get_serialization_lib().SafeModeScope(safe_mode):
117+
return keras.models.load_model(model_path, safe_mode=safe_mode)
118+
119+
70120
def convert_to_tflite(keras_model, output_path):
71121
"""Converts the given Keras model to TFLite and write it to a file."""
72122
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
@@ -93,15 +143,21 @@ def pruned_model_filename(sparsity, block_size):
93143
sparsity, '%dx%d' % block_size)
94144

95145

96-
def run(input_model_path, output_dir, target_sparsity, block_size):
146+
def run(
147+
input_model_path: str,
148+
output_dir: str,
149+
target_sparsity: float,
150+
block_size: tuple[int, int],
151+
allow_unsafe_deserialization: bool = False,
152+
) -> None:
97153
"""Prunes the model and converts both pruned and unpruned versions to TFLite."""
98154

99155
print(textwrap.dedent("""\
100156
Warning: The sparse models produced by this tool have poor accuracy. They
101157
are not intended to be served in production, but to be used for
102158
performance benchmarking."""))
103159

104-
input_model = keras.models.load_model(input_model_path)
160+
input_model = load_model(input_model_path, allow_unsafe_deserialization)
105161

106162
os.makedirs(output_dir, exist_ok=True)
107163
unpruned_tflite_path = os.path.join(
@@ -136,7 +192,13 @@ def main(argv):
136192
raise app.UsageError('Too many command-line arguments.')
137193

138194
block_size = _parse_block_size_flag(_BLOCK_SIZE.value)
139-
run(_MODEL_PATH.value, _OUTPUT_DIR.value, _SPARSITY.value, block_size)
195+
run(
196+
_MODEL_PATH.value,
197+
_OUTPUT_DIR.value,
198+
_SPARSITY.value,
199+
block_size,
200+
_ALLOW_UNSAFE_DESERIALIZATION.value,
201+
)
140202

141203

142204
if __name__ == '__main__':
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# Copyright 2026 The TensorFlow Authors. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# ==============================================================================
15+
import os
16+
17+
from absl.testing import parameterized
18+
import numpy as np
19+
import tensorflow as tf
20+
21+
from tensorflow_model_optimization.python.core.keras.compat import keras
22+
from tensorflow_model_optimization.python.core.sparsity.keras.tools import evaluate_pruning
23+
24+
25+
def _build_model(with_lambda):
26+
layers = [keras.layers.Dense(4, input_shape=(3,))]
27+
if with_lambda:
28+
layers.append(keras.layers.Lambda(lambda x: x * 2.0))
29+
layers.append(keras.layers.Dense(2))
30+
return keras.Sequential(layers)
31+
32+
33+
class EvaluatePruningLoadModelTest(tf.test.TestCase, parameterized.TestCase):
34+
35+
def _save_model(self, model, filename, **kwargs):
36+
path = os.path.join(self.create_tempdir().full_path, filename)
37+
model.save(path, **kwargs)
38+
return path
39+
40+
@parameterized.parameters('model.h5', 'model.keras')
41+
def test_load_model_rejects_lambda_by_default(self, filename):
42+
path = self._save_model(_build_model(with_lambda=True), filename)
43+
44+
with self.assertRaisesRegex(ValueError, 'safe_mode=False'):
45+
evaluate_pruning.load_model(path)
46+
47+
def test_load_model_does_not_deserialize_lambda_from_saved_model(self):
48+
path = self._save_model(
49+
_build_model(with_lambda=True), 'saved_model', save_format='tf'
50+
)
51+
52+
loaded_model = evaluate_pruning.load_model(path)
53+
54+
self.assertLen(loaded_model.layers, 3)
55+
self.assertNotIsInstance(loaded_model.layers[1], keras.layers.Lambda)
56+
57+
@parameterized.parameters('model.h5', 'model.keras')
58+
def test_load_model_allows_lambda_when_unsafe_allowed(self, filename):
59+
model = _build_model(with_lambda=True)
60+
path = self._save_model(model, filename)
61+
62+
loaded_model = evaluate_pruning.load_model(
63+
path, allow_unsafe_deserialization=True
64+
)
65+
66+
x = np.ones((1, 3), dtype=np.float32)
67+
self.assertAllClose(model.predict(x), loaded_model.predict(x))
68+
69+
@parameterized.parameters('model.h5', 'model.keras')
70+
def test_load_model_loads_safe_model(self, filename):
71+
model = _build_model(with_lambda=False)
72+
path = self._save_model(model, filename)
73+
74+
loaded_model = evaluate_pruning.load_model(path)
75+
76+
x = np.ones((1, 3), dtype=np.float32)
77+
self.assertAllClose(model.predict(x), loaded_model.predict(x))
78+
79+
def test_load_model_restores_safe_mode_state(self):
80+
serialization_lib = evaluate_pruning._get_serialization_lib() # pylint: disable=protected-access
81+
original_safe_mode = serialization_lib.in_safe_mode()
82+
unsafe_path = self._save_model(_build_model(with_lambda=True), 'model.h5')
83+
84+
evaluate_pruning.load_model(unsafe_path, allow_unsafe_deserialization=True)
85+
86+
# Allowing unsafe deserialization once must not leak to later loads.
87+
self.assertEqual(serialization_lib.in_safe_mode(), original_safe_mode)
88+
89+
def test_run_rejects_lambda_model(self):
90+
path = self._save_model(_build_model(with_lambda=True), 'model.h5')
91+
output_dir = self.create_tempdir().full_path
92+
93+
with self.assertRaisesRegex(ValueError, 'safe_mode=False'):
94+
evaluate_pruning.run(
95+
path, output_dir, target_sparsity=0.5, block_size=(1, 1)
96+
)
97+
98+
self.assertEmpty(os.listdir(output_dir))
99+
100+
def test_run_converts_lambda_model_when_unsafe_allowed(self):
101+
path = self._save_model(_build_model(with_lambda=True), 'model.h5')
102+
output_dir = self.create_tempdir().full_path
103+
104+
evaluate_pruning.run(
105+
path,
106+
output_dir,
107+
target_sparsity=0.5,
108+
block_size=(1, 1),
109+
allow_unsafe_deserialization=True,
110+
)
111+
112+
self.assertCountEqual(
113+
os.listdir(output_dir),
114+
[
115+
'unpruned_model.tflite',
116+
evaluate_pruning.pruned_model_filename(0.5, (1, 1)),
117+
],
118+
)
119+
120+
121+
if __name__ == '__main__':
122+
tf.test.main()

0 commit comments

Comments
 (0)