1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
|
#!/usr/bin/env python3
"""
analyze-config - generate NFP model from system config benchmarks
analyze-config generates an NFP model from benchmarks with various system
configs (.config entries generated from a common Kconfig definition). The
NFP model is not yet compatible with the type of models generated
by analyze-archive and analyze-timing
"""
import argparse
import json
import kconfiglib
import logging
import os
import numpy as np
from dfatool.functions import SplitFunction, StaticFunction
from dfatool.model import AnalyticModel, ModelAttribute
from dfatool.utils import NpEncoder
def make_config_vector(kconf, params, symbols, choices):
config_vector = [None for i in params]
for i, param in enumerate(params):
if param in choices:
choice = kconf.choices[choices.index(param)]
if choice.selection:
config_vector[i] = choice.selection.name
else:
config_vector[i] = kconf.syms[param].str_value
return tuple(config_vector)
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__
)
parser.add_argument(
"--log-level",
metavar="LEVEL",
choices=["debug", "info", "warning", "error"],
default="warning",
help="Set log level",
)
parser.add_argument(
"--with-choice-node",
action="store_true",
help="Add special decisiontree nodes for Kconfig choice symbols",
)
parser.add_argument("kconfig_file")
parser.add_argument("data_dir")
args = parser.parse_args()
if args.log_level:
numeric_level = getattr(logging, args.log_level.upper(), None)
if not isinstance(numeric_level, int):
print(f"Invalid log level: {args.log_level}", file=sys.stderr)
sys.exit(1)
logging.basicConfig(level=numeric_level)
experiments = list()
for direntry in os.listdir(args.data_dir):
if "Multipass" in direntry:
config_path = f"{args.data_dir}/{direntry}/.config"
attr_path = f"{args.data_dir}/{direntry}/attributes.json"
if os.path.exists(attr_path):
experiments.append((config_path, attr_path))
kconf = kconfiglib.Kconfig(args.kconfig_file)
# TODO Optional neben bool auch choices unterstützen.
# Später ebenfalls int u.ä. -> dfatool-modeling
symbols = sorted(
map(
lambda sym: sym.name,
filter(
lambda sym: kconfiglib.TYPE_TO_STR[sym.type] == "bool",
kconf.syms.values(),
),
)
)
if args.with_choice_node:
choices = list(map(lambda choice: choice.name, kconf.choices))
else:
choices = list()
params = sorted(symbols + choices)
by_name = {
"multipass": {
"isa": "state",
"attributes": ["rom_usage", "ram_usage"],
"rom_usage": list(),
"ram_usage": list(),
"param": list(),
}
}
data = list()
config_vectors = set()
for config_path, attr_path in experiments:
kconf.load_config(config_path)
with open(attr_path, "r") as f:
attr = json.load(f)
config_vector = make_config_vector(kconf, params, symbols, choices)
config_vectors.add(config_vector)
by_name["multipass"]["rom_usage"].append(attr["total"]["ROM"])
by_name["multipass"]["ram_usage"].append(attr["total"]["RAM"])
by_name["multipass"]["param"].append(config_vector)
data.append((config_vector, (attr["total"]["ROM"], attr["total"]["RAM"])))
print(
"Processing {:d} unique configurations of {:d} total".format(
len(config_vectors), len(experiments)
)
)
print(
"std of all data: {:5.0f} Bytes".format(
np.std(list(map(lambda x: x[1][0], data)))
)
)
model = AnalyticModel(by_name, params, compute_stats=False)
def get_min(this_symbols, this_data, data_index=0, threshold=100, level=0):
"""
Build a Decision Tree on `this_data`.
:param this_symbols: parameter names
:param this_data: list of measurements. Each entry is a (param vector, mearusements vector) tuple.
param vector holds parameter values (same order as parameter names). mearuserements vector holds measurements.
:param data_index: Index in measurements vector to use for model generation. Default 0.
:param threshold: Return a StaticFunction leaf node if std(data[data_index]) < threshold. Default 100.
:returns: SplitFunction or StaticFunction
"""
rom_sizes = list(map(lambda x: x[1][data_index], this_data))
if np.std(rom_sizes) < threshold or len(this_symbols) == 0:
return StaticFunction(np.mean(rom_sizes))
# sf.value_error["std"] = np.std(rom_sizes)
mean_stds = list()
for i, param in enumerate(this_symbols):
unique_values = list(set(map(lambda vrr: vrr[0][i], this_data)))
if None in unique_values:
# param is a choice and undefined in some configs. Do not split on it.
mean_stds.append(np.inf)
continue
child_values = list()
for value in unique_values:
child_values.append(
list(filter(lambda vrr: vrr[0][i] == value, this_data))
)
if len(list(filter(len, child_values))) < 2:
# this param only has a single value. there's no point in splitting.
mean_stds.append(np.inf)
continue
children = list()
for child in child_values:
children.append(np.std(list(map(lambda x: x[1][data_index], child))))
if np.any(np.isnan(children)):
mean_stds.append(np.inf)
else:
mean_stds.append(np.mean(children))
if np.all(np.isinf(mean_stds)):
# all children have the same configuration. We shouldn't get here due to the threshold check above...
logging.warning("Waht")
return StaticFunction(np.mean(rom_sizes))
symbol_index = np.argmin(mean_stds)
symbol = this_symbols[symbol_index]
unique_values = list(set(map(lambda vrr: vrr[0][symbol_index], this_data)))
child = dict()
for value in unique_values:
children = list(
filter(lambda vrr: vrr[0][symbol_index] == value, this_data)
)
if len(children):
print(
f"Level {level} split on {symbol} == {value} has {len(children)} children"
)
child[value] = get_min(
this_symbols, children, data_index, threshold, level + 1
)
assert len(child.values()) >= 2
return SplitFunction(np.mean(rom_sizes), symbol_index, child)
model.attr_by_name["multipass"] = dict()
model.attr_by_name["multipass"]["rom_usage"] = ModelAttribute(
"multipass",
"rom_usage",
by_name["multipass"]["rom_usage"],
by_name["multipass"]["param"],
params,
)
model.attr_by_name["multipass"]["ram_usage"] = ModelAttribute(
"multipass",
"rom_usage",
by_name["multipass"]["ram_usage"],
by_name["multipass"]["param"],
params,
)
model.attr_by_name["multipass"]["rom_usage"].model_function = get_min(
params, data, 0, 100
)
model.attr_by_name["multipass"]["ram_usage"].model_function = get_min(
params, data, 1, 20
)
with open("kconfigmodel.json", "w") as f:
json_model = model.to_json(with_param_name=True, param_names=params)
json.dump(json_model, f, sort_keys=True, cls=NpEncoder)
if __name__ == "__main__":
main()
|