-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
451 lines (370 loc) · 14.1 KB
/
utils.py
File metadata and controls
451 lines (370 loc) · 14.1 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import torch
from torch_geometric.data import Data
from torch_geometric.utils import from_networkx
import networkx as nx
from typing import Iterable
import random
from pathlib import Path
from tqdm import tqdm
import json
import csv
from zipfile import ZipFile
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from .convert import MODULE_ATTRIBUTES, OpWord
def load_component_parameters(
components_path: str | Path, objective: str = "mse"
) -> dict[str, dict[str, float]]:
"""Loads component error metrics from EvoApproxLib.
:param components_path: EvoApproxLib meta JSON path.
:param objective: EvoApproxLib objective.
:return: Mapping of component names to metric dictionary.
:rtype: `dict[str, dict[str, float]]`
"""
components_path = Path(components_path)
with open(components_path) as f:
meta = json.load(f)
components: dict[str, dict[str, float]] = {}
for group in meta:
if group["folder"] == "adders":
for dataset in group["datasets"]:
for subdataset in dataset["datasets"]:
if subdataset["folder"].split("/")[-1] != f"pareto_pwr_{objective}":
continue
for instance in subdataset["instances"]:
name = instance["name"]
params = instance["params"]
components[name] = {
attr: float(params[attr])
for attr in [
"mae%",
"mre%",
"ep%",
"wce%",
"wcre%",
"area",
"pwr",
"delay",
]
if attr in params
}
return components
def get_verilog_paths(
components_path: str | Path,
objective: str = "mse",
unsigned: bool = True,
signed: bool = False,
) -> dict[str, Path]:
"""Gets a mapping of component names to Verilog paths from EvoApproxLib.
:param components_path: EvoApproxLib meta JSON path.
:param objective: EvoApproxLib objective.
:param unsigned: Load unsigned components.
:param signed: Load signed components.
:return: Mapping of component names to Verilog paths.
:rtype: `dict[str, Path]`
"""
components_path = Path(components_path)
with open(components_path) as f:
meta = json.load(f)
components: dict[str, Path] = {}
for group in meta:
if group["folder"] == "adders":
for dataset in group["datasets"]:
if not signed and dataset["signed"]:
continue
elif not unsigned and not dataset["signed"]:
continue
for subdataset in dataset["datasets"]:
if subdataset["folder"].split("/")[-1] != f"pareto_pwr_{objective}":
continue
for instance in subdataset["instances"]:
name = instance["name"]
files = instance["files"]
try:
verilog = next(
x["file"] for x in files if x["type"] == "Verilog file"
)
except StopIteration:
continue
components[name] = Path(subdataset["folder"]) / verilog
return components
def _instantiate_template(
instance_id: str,
wirings: dict[str, nx.DiGraph],
configs: dict[str, dict[str, str | list[str]]],
qor: dict[str, dict[str, float]],
metrics: list[str],
targets: str | list[str] = "psnr",
components: dict[str, dict[str, float]] | None = None,
adder_to_id: dict[str, int] | None = None,
critical_path: Iterable[str] | None = None,
) -> tuple[Data, str]:
"""Instantiates an accelerator from a networkx graph and a component assignment.
Sets node_critical when critical_path is used.
Sets adder_id to assigned components' IDs when adder_to_id is used.
:param instance_id: Configuration ID.
:param wirings: Mapping of accelerator IDs to networkx graphs.
:param configs: Configuration data (ID -> {assignments, wiring ID}).
:param qor: Mapping of configuration IDs to QoR results.
:param components: Component parameters.
:param adder_to_id: Mapping of component names to IDs.
:param critical_path: List of nodes IDs on the critical path.
:return: PyG graph and wiring ID.
:rtype: `tuple[Data, str]`
"""
if components is None and adder_to_id is None:
raise ValueError("Either components or adder_to_id has to be defined.")
wiring_id: str = configs[instance_id]["wiring"]
wiring = wirings[wiring_id]
if critical_path is not None:
for node, data in wiring.nodes(data=True):
data["node_critical"] = 1 if node in critical_path else 0
graph = from_networkx(wiring)
graph.x = torch.zeros((len(graph.x), len(metrics)), dtype=torch.float32)
module_indices = {
index.item(): i for i, index in enumerate(graph.adder_id) if index >= 0
}
q = qor[instance_id]
if type(targets) is str:
graph.y = torch.tensor(q[targets])
else:
graph.y = torch.tensor([q[target] for target in targets])
if adder_to_id is not None:
for i, v in enumerate(configs[instance_id]["assignments"]):
graph.adder_id[module_indices[i]] = adder_to_id[v]
else:
def adjust_attr(attr: str, component):
if attr not in component:
return 0.0
if attr.endswith("%"):
return component[attr] * 0.01
else:
return component[attr]
for i, v in enumerate(configs[instance_id]["assignments"]):
comp = components[v]
graph.x[module_indices[i]] = torch.tensor(
[adjust_attr(attr, comp) for attr in metrics]
)
graph.id = instance_id
return graph, wiring_id
def load_dataset(
dir: str | Path,
components: dict[str, dict[str, float]] | None = None,
adder_to_id: dict[str, int] | None = None,
add_critical_paths: bool = False,
component_graphs: dict[str, nx.DiGraph] | None = None,
targets: str | list[str] = "psnr",
metrics: list[str] = MODULE_ATTRIBUTES,
) -> tuple[list[Data], list[str]]:
"""Loads a dataset from a directory.
Sets node_critical when add_critical_paths and component graphs is used.
Sets adder_id to assigned components' IDs when adder_to_id is used.
:param dir: Dataset directory.
:param components: Component parameters. Used for metric-based prediction.
:param adder_to_id: Mapping of component names to IDs.
:param add_critical_paths: Set critical paths.
:param component_graphs: Component networkx graphs.
:return: List of PyG graphs and accelerator IDs they were instantiated from.
:rtype: `tuple[list[Data], list[str]]`
"""
if components is None and adder_to_id is None:
raise ValueError("Either components or adder_to_id has to be defined.")
dir = Path(dir)
with open(dir / "results.csv") as f:
reader = csv.DictReader(f)
qor: dict[str, dict[str, float]] = {
x["config"]: {
k: float(v) for k, v in x.items() if k not in ["config", "wiring"]
}
for x in reader
}
with open(dir / "_eval.tsv") as f:
configs: dict[str, dict[str, str | list[str]]] = {}
for line in f:
words = line.split()
configs[words[0]] = {"wiring": words[1], "assignments": words[4:]}
with ZipFile(dir / "accelerators.json.zip") as f:
wirings = json.loads(f.read("accelerators.json").decode())
wirings = {k: nx.adjacency_graph(v["graph"]) for k, v in wirings.items()}
if add_critical_paths:
if component_graphs is None:
raise ValueError(
"component_graphs has to be set when adding critical paths."
)
component_critical_paths = {
k: find_longest_paths(v) for k, v in component_graphs.items()
}
component_critical_lengths = {
k: [len(x) for x in v] for k, v in component_critical_paths.items()
}
longest_paths = {
cid: find_longest_paths(
wirings[config["wiring"]],
config["assignments"],
component_critical_lengths,
)
for cid, config in configs.items()
}
critical_paths = {
cid: set(max((len(p), p) for p in paths)[1])
for cid, paths in longest_paths.items()
}
else:
critical_paths = None
dataset = [
_instantiate_template(
instance_id,
wirings,
configs,
qor,
metrics,
targets=targets,
components=components,
adder_to_id=adder_to_id,
critical_path=(
critical_paths[instance_id] if critical_paths is not None else None
),
)
for instance_id in tqdm(
configs, total=len(configs), ncols=100, desc="Loading dataset"
)
if instance_id in qor
]
graphs = [d[0] for d in dataset]
wiring_ids = [d[1] for d in dataset]
return graphs, wiring_ids
def random_color():
"""Creates a random color for matplotlib."""
r = hex(random.randint(0, 255))[2:].ljust(2, "0")
g = hex(random.randint(0, 255))[2:].ljust(2, "0")
b = hex(random.randint(0, 255))[2:].ljust(2, "0")
return f"#{r}{g}{b}"
def prepare_pyplot(
square: bool = False,
width: float | None = None,
height: float | None = None,
grayscale: bool = False,
rows: int = 1,
cols: int = 1,
shared_x: bool = False,
shared_y: bool = False,
) -> tuple[Figure, Axes | list[Axes] | list[list[Axes]]]:
"""Prepares matplotlib for publication figures.
:param square: Create a square figure.
:param height: Height override.
:param grayscale: Set to grayscale.
:return: Figure and axis.
"""
if grayscale:
plt.style.use("grayscale")
plt.rcParams["pdf.fonttype"] = 42
plt.rcParams["font.size"] = 14
if square:
size = (
3.5 if width is None else width,
3.5 if height is None else height,
)
else:
size = (7 if width is None else width, 4 if height is None else height)
fig, ax = plt.subplots(
nrows=rows,
ncols=cols,
figsize=size,
sharex=shared_x,
sharey=shared_y,
)
return fig, ax
def save_figure(
fig: Figure,
fig_path: Path,
joined: bool = False,
top: float | None = None,
bottom: float | None = None,
right: float | None = None,
left: float | None = None,
):
print(f"Saving figure to: {fig_path}")
if joined:
fig.subplots_adjust(wspace=0, hspace=0)
if top is not None:
fig.subplots_adjust(top=top)
if bottom is not None:
fig.subplots_adjust(bottom=bottom)
if right is not None:
fig.subplots_adjust(right=right)
if left is not None:
fig.subplots_adjust(left=left)
fig.savefig(fig_path, dpi=300, bbox_inches="tight")
plt.close(fig)
def find_loops(
node: str, G: nx.DiGraph, in_use: dict[str, bool], loops: set[tuple[str, str]]
):
"""Finds edges creating loops and adds them to the `loops` argument.
:param node: Root node name.
:param G: Input graph.
:param in_use: Table marking nodes on currently explored path.
:param loops: Resulting set of edges.
"""
in_use[node] = True
for _, child in G.out_edges(node):
if in_use[child]:
loops.add((node, child))
else:
find_loops(child, G, in_use, loops)
in_use[node] = False
def find_longest_paths(
G: nx.DiGraph,
assignments: list[str] | None = None,
modules: dict[str, list[int]] | None = None,
):
"""Finds longest paths in a given graph.
:param G: Input graph.
:param assignments: List of adder assignments.
:param modules: Mapping of component names to critical paths from their inputs.
"""
input_nodes = [
node[0]
for node in G.nodes(data=True)
if OpWord(node[1]["node_type"]) == OpWord.INPUT
]
output_nodes = [
node[0]
for node in G.nodes(data=True)
if OpWord(node[1]["node_type"]) == OpWord.OUTPUT
]
paths: list[list[str]] = []
for input_node in input_nodes:
loops: set[tuple[str, str]] = set()
find_loops(input_node, G, {k: False for k in G.nodes}, loops)
pqueue: list[(int, str, str)] = [(0, input_node, "")]
distances: dict[str, tuple[str, int]] = {input_node: ("", 0)}
while len(pqueue) > 0:
current_dist, node, _ = pqueue.pop()
if current_dist < distances[node][1]:
# replaced by other path
continue
for _, child in G.out_edges(node):
if (node, child) in loops:
continue
if OpWord(G.nodes[child]["node_type"]) == OpWord.MODULE:
if modules is not None and assignments is not None:
adder_id = G.nodes[child]["adder_id"]
edge_id = G.edges[(node, child)]["edge_id"]
adjusted_dist = (
current_dist + modules[assignments[adder_id]][edge_id]
)
else:
adjusted_dist = current_dist
if child not in distances or adjusted_dist >= distances[child][1]:
new_dist = adjusted_dist + 1
distances[child] = (node, new_dist)
pqueue.append((new_dist, child, node))
pqueue = sorted(pqueue)
target_node = output_nodes[0]
path = []
while target_node != "":
path.append(target_node)
target_node = distances[target_node][0]
paths.append(list(path[::-1]))
return paths