Skip to content
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

Generate report for troubleshooting the quantized model #1090

Merged
merged 50 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
22675ca
Init commit of xquant
May 27, 2024
58bfb76
remove commented out code
May 27, 2024
86a2ff2
add dummy methods if fw packages were not found
May 27, 2024
9b5b730
add histograms collection
May 29, 2024
87b0f1d
Fix comments in pytorch facade
May 29, 2024
90f19f4
Remove core config comments
Jun 3, 2024
6c8f10d
simplify xquantconfig
Jun 3, 2024
8bfa93d
rename core report generator
Jun 3, 2024
c0365a4
add similarity metrics
Jun 3, 2024
124c9d5
Add dataset utils
Jun 3, 2024
f17baee
Add model folding module
Jun 3, 2024
d978834
add tensorboard utils
Jun 4, 2024
c5c3f61
remove logger and use python logging
Jun 4, 2024
2afa2b2
Move default similarity metrics names to SimilarityMetrics
Jun 4, 2024
a1a18e2
split similarity into module with similairty functions and similarity…
Jun 5, 2024
7592a3f
add tests for more networks
Jun 5, 2024
122f1bd
Add tests to workflows
Jun 5, 2024
3f45e7a
add temp logger
Jun 5, 2024
332d96e
finalize logger
Jun 6, 2024
401c9d6
add comments
Jun 6, 2024
794a561
rename wrapped_dataset to prepare_dataset
Jun 6, 2024
3c67bfe
rename metrics to similarity metrics
Jun 9, 2024
c38e43f
add comments
Jun 9, 2024
36136f7
move package into model_compression_toolkit
Jun 9, 2024
7dd9e3d
add keras notebook
Jun 9, 2024
e23663f
add pytorch notebook
Jun 9, 2024
01da6e9
fix imports in keras notebook
Jun 9, 2024
072034c
replace inference manner to solve issue with tf2.13
Jun 10, 2024
092f8f9
use mct logger
Jun 13, 2024
b866f7a
remove duplicated license
Jun 13, 2024
0e367ec
rename arguments in similairty functions to be more general
Jun 13, 2024
4f7dc18
avoid double access to dict in similarity calculator
Jun 13, 2024
32b112a
rename ModelAnalyzerUtils to ModelAnalyzer
Jun 13, 2024
10e00ea
add no cover for abstract methods error
Jun 13, 2024
c94559f
use tag for tensorboard artifacts
Jun 13, 2024
7c177a9
take stats collection out of tensorboard class
Jun 13, 2024
1478bf9
store model outputs in activation dict during activations extraction
Jun 13, 2024
15e56e1
add keras model analyzer unit tests
Jun 13, 2024
ddd178b
add similarity functions unit tests
Jun 15, 2024
d6d8265
add tests to tensorboard
Jun 16, 2024
660b201
add colab links to notebooks
Jun 16, 2024
648fb23
remove outputs from keras notebook
Jun 16, 2024
eb5e3f6
fix install sections in notebooks
Jun 16, 2024
0bc2e61
remove sys part from notebooks
Jun 16, 2024
7a0830c
fix bad import in pytorch notebook
Jun 16, 2024
c8d764c
fix PR comments
Jun 16, 2024
517f8f9
use different images in notebooks with red marks for clarity
Jun 16, 2024
f186664
limit numpy to version < 2.0 that was just released
Jun 16, 2024
8e35f8b
Revert "limit numpy to version < 2.0 that was just released"
Jun 17, 2024
9272a97
Merge remote-tracking branch 'origin/main' into xquant
Jun 17, 2024
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
15 changes: 15 additions & 0 deletions tests/xquant_tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2024 Sony Semiconductor Israel, Inc. 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.
# ==============================================================================
#
15 changes: 15 additions & 0 deletions tests/xquant_tests/keras_tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2024 Sony Semiconductor Israel, Inc. 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.
# ==============================================================================
#
176 changes: 176 additions & 0 deletions tests/xquant_tests/keras_tests/test_xquant_report.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# Copyright 2024 Sony Semiconductor Israel, Inc. 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.
# ==============================================================================
#

import unittest
from functools import partial
import tempfile

import model_compression_toolkit as mct
from mct_quantizers import KerasQuantizationWrapper
from xquant import XQuantConfig
import tensorflow as tf

import keras
import numpy as np

from xquant.common.constants import OUTPUT_METRICS_REPR, OUTPUT_METRICS_VAL, INTERMEDIATE_METRICS_REPR, INTERMEDIATE_METRICS_VAL
from xquant.common.framework_report_utils import DEFAULT_METRICS_NAMES
from xquant.keras.facade_xquant_report import xquant_report_keras_experimental


def get_model_to_test():
inputs = keras.layers.Input(shape=(3, 8, 8))
x = keras.layers.Conv2D(3, 3)(inputs)
x = keras.layers.BatchNormalization()(x)
outputs = keras.layers.Activation('relu')(x)
model = keras.Model(inputs=inputs, outputs=outputs)
return model


def random_data_gen(shape=(2, 3, 8, 8), use_labels=False):
if use_labels:
for _ in range(2):
yield [[np.random.randn(*shape)], np.random.randn(shape[0])]
else:
for _ in range(2):
yield [np.random.randn(*shape)]


class TestXQuantReport(unittest.TestCase):

def setUp(self):
self.float_model = get_model_to_test()
self.core_config = mct.core.CoreConfig()
self.repr_dataset = random_data_gen
self.quantized_model, _ = mct.ptq.keras_post_training_quantization(in_model=self.float_model,
core_config=self.core_config,
representative_data_gen=self.repr_dataset)

self.validation_dataset = partial(random_data_gen, use_labels=True)
self.tmpdir = tempfile.mkdtemp()
self.xquant_config = XQuantConfig(report_dir=self.tmpdir)

def test_xquant_report_output_metrics_repr(self):
self.xquant_config.compute_output_metrics_repr = True
self.xquant_config.custom_metrics_output = None

result = xquant_report_keras_experimental(
self.float_model,
self.quantized_model,
self.repr_dataset,
self.validation_dataset,
# self.core_config,
self.xquant_config
)

self.assertIn(OUTPUT_METRICS_REPR, result)
self.assertEqual(len(result[OUTPUT_METRICS_REPR]), len(DEFAULT_METRICS_NAMES))

def test_xquant_report_output_metrics_val(self):
self.xquant_config.compute_output_metrics_val = True
self.xquant_config.custom_metrics_output = None

result = xquant_report_keras_experimental(
self.float_model,
self.quantized_model,
self.repr_dataset,
self.validation_dataset,
# self.core_config,
self.xquant_config
)

self.assertIn(OUTPUT_METRICS_VAL, result)
self.assertEqual(len(result[OUTPUT_METRICS_VAL]), len(DEFAULT_METRICS_NAMES))



def test_custom_output_metric(self):
self.xquant_config.compute_output_metrics_repr = True
self.xquant_config.compute_output_metrics_val = True
self.xquant_config.custom_metrics_output = {'mae': lambda x,y: float(tf.keras.losses.MAE(x.flatten(), y.flatten()).numpy())}

result = xquant_report_keras_experimental(
self.float_model,
self.quantized_model,
self.repr_dataset,
self.validation_dataset,
# self.core_config,
self.xquant_config
)

self.assertIn(OUTPUT_METRICS_REPR, result)
self.assertEqual(len(result[OUTPUT_METRICS_REPR]), len(DEFAULT_METRICS_NAMES) + 1)
self.assertIn("mae", result[OUTPUT_METRICS_REPR])

def test_intermediate_metrics_repr(self):
self.xquant_config.compute_intermediate_metrics_repr = True
self.xquant_config.custom_metrics_intermediate = None

result = xquant_report_keras_experimental(
self.float_model,
self.quantized_model,
self.repr_dataset,
self.validation_dataset,
# self.core_config,
self.xquant_config
)

self.assertIn(INTERMEDIATE_METRICS_REPR, result)
linear_layers = [l.name for l in self.quantized_model.layers if isinstance(l, KerasQuantizationWrapper)]
self.assertEqual(len(linear_layers), 1, msg=f"Expected to find one linear layer. Found {len(linear_layers)}")
self.assertIn(linear_layers[0], result[INTERMEDIATE_METRICS_REPR])

for k,v in result[INTERMEDIATE_METRICS_REPR].items():
self.assertEqual(len(v), len(DEFAULT_METRICS_NAMES))


def test_intermediate_metrics_val(self):
self.xquant_config.compute_intermediate_metrics_val = True
self.xquant_config.custom_metrics_intermediate = None

result = xquant_report_keras_experimental(
self.float_model,
self.quantized_model,
self.repr_dataset,
self.validation_dataset,
# self.core_config,
self.xquant_config
)
self.assertIn(INTERMEDIATE_METRICS_VAL, result)
for k,v in result[INTERMEDIATE_METRICS_VAL].items():
self.assertEqual(len(v), len(DEFAULT_METRICS_NAMES))

def test_custom_intermediate_metrics(self):
self.xquant_config.compute_intermediate_metrics_repr = True
self.xquant_config.custom_metrics_intermediate = {'mae': lambda x,y: float(tf.keras.losses.MAE(x.flatten(), y.flatten()).numpy())}

result = xquant_report_keras_experimental(
self.float_model,
self.quantized_model,
self.repr_dataset,
self.validation_dataset,
# self.core_config,
self.xquant_config
)

self.assertIn(INTERMEDIATE_METRICS_REPR, result)
for k,v in result[INTERMEDIATE_METRICS_REPR].items():
self.assertEqual(len(v), len(DEFAULT_METRICS_NAMES)+1)
self.assertIn("mae", v)


if __name__ == '__main__':
unittest.main()
15 changes: 15 additions & 0 deletions tests/xquant_tests/pytorch_tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2024 Sony Semiconductor Israel, Inc. 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.
# ==============================================================================
#
Loading
Loading