ONE - On-device Neural Engine
Loading...
Searching...
No Matches
q_implant_validator.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2
3# Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import h5py as h5
18import numpy as np
19import json
20
21
22def validate(h5_path, qparam_dir, qparam_json):
23 valid = True
24 with open(qparam_json, "r") as qparams:
25 json_load = json.load(qparams)
26 with h5.File(h5_path, "r") as model:
27 for node_name in model.keys():
28 # not quantized node exists (reshape, pad...)
29 if not json_load.get(node_name):
30 continue
31
32 for tensor_name in json_load[node_name]:
33 np_path = f"{qparam_dir}/{json_load[node_name][tensor_name]}"
34 if tensor_name == "value":
35 expected_weights = np.load(np_path)
36 h5_weights = model[node_name]["weights"][:]
37 if np.allclose(h5_weights, expected_weights, rtol=1.e-5,
38 atol=1.e-5) == False:
39 print("Implanted weights of " + node_name + "." + tensor_name +
40 " (" + str(h5_weights) +
41 ") do not match with expected value (" +
42 str(expected_weights) + ").")
43 valid = False
44
45 if tensor_name == "scale":
46 expected_scale = np.load(np_path)
47 h5_scale = model[node_name]["scale"][:]
48 if np.allclose(h5_scale, expected_scale, rtol=1.e-5,
49 atol=1.e-5) == False:
50 print("Implanted scale of " + node_name + "." + tensor_name +
51 " (" + str(h5_scale) +
52 ") do not match with expected value (" +
53 str(expected_scale) + ").")
54 valid = False
55
56 if tensor_name == "zerop":
57 expected_zerop = np.load(np_path)
58 input_zerop = model[node_name]["zero_point"][:]
59 if np.allclose(input_zerop, expected_zerop, rtol=0, atol=1) == False:
60 print("Implanted zero point of " + tensor_name + " (" +
61 str(input_zerop) + ") do not match with expected value (" +
62 str(expected_zerop) + ").")
63 valid = False
64
65 return valid