forked from tancheng/CGRA-Flow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmode_dark_light.py
More file actions
executable file
·3151 lines (2627 loc) · 137 KB
/
mode_dark_light.py
File metadata and controls
executable file
·3151 lines (2627 loc) · 137 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import math
import os
import platform
import re
import subprocess
import threading
import time
import tkinter
import tkinter.messagebox
import requests
import ai_assistant
from functools import partial
from tkinter import filedialog as fd
from common.constants import *
from common.cgra_param_tile import ParamTile
from common.cgra_param_spm import ParamSPM
from common.cgra_param_link import ParamLink
from common.cgra_param import CGRAParam
from common.cgra_multi_param import MultiCGRAParam
import customtkinter
from PIL import Image, ImageTk, ImageFile
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--theme")
args = parser.parse_args()
customtkinter.set_appearance_mode("dark") # Modes: system (default), light, dark
customtkinter.set_default_color_theme("dark-blue") # Themes: blue (default), dark-blue, green
# CANVAS_BG_COLOR = "#2B2B2B"
CANVAS_BG_COLOR = "#212121"
CANVAS_LINE_COLOR = "white"
MULTI_CGRA_FRAME_COLOR = "#14375E"
MULTI_CGRA_TILE_COLOR = "#1F538D"
MULTI_CGRA_TXT_COLOR = "white"
MULTI_CGRA_SELECTED_COLOR = "lightblue"
if args.theme:
# print(f'Input theme argument: {args.theme}')
if args.theme == 'light':
customtkinter.set_appearance_mode("light") # Modes: system (default), light, dark
customtkinter.set_default_color_theme("dark-blue") # Themes: blue (default), dark-blue, green
CANVAS_BG_COLOR = "#E5E5E5"
CANVAS_LINE_COLOR = "black"
MULTI_CGRA_FRAME_COLOR = "#325882"
MULTI_CGRA_TILE_COLOR = "#3A7EBF"
MULTI_CGRA_TXT_COLOR = "black"
from VectorCGRA.cgra.test.CgraTemplateRTL_test import test_cgra_universal
from VectorCGRA.multi_cgra.test.MeshMultiCgraTemplateRTL_test import test_mesh_multi_cgra_universal, test_simplified_multi_cgra
# importing module
import logging
# Create and configure logger
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s')
def window_size(window, width, height):
window.geometry(f"{width}x{height}")
master = customtkinter.CTk()
master.title(
"Neura: An Integrated End-to-End Framework for Multi-CGRA Exploration, Compilation, Synthesis and Evaluation")
# Stores the UI elements that need to communicate between UI components
widgets = {}
images = {}
entireTileCheckVar = tkinter.IntVar()
mappingAlgoCheckVar = tkinter.IntVar()
fuCheckVars = {}
fuCheckbuttons = {}
xbarCheckVars = {}
xbarCheckbuttons = {}
kernelOptions = tkinter.StringVar()
kernelOptions.set("Not selected yet")
synthesisRunning = False
constraintFilePath = ""
configFilePath = ""
mapped_tile_color_list = ['#FFF113', '#75D561', '#F2CB67', '#FFAC73', '#F3993A', '#B3FF04', '#C2FFFF']
processOptions = tkinter.StringVar()
processOptions.set("asap7")
# TODO: Removes this and uses MultiCGRAParams.py
class CgraOfMultiCgra:
def __init__(s, cgraId, xStartPos, yStartPos, tileRows, tileCols):
s.cgraId = cgraId
s.xStartPos = xStartPos
s.yStartPos = yStartPos
s.tileRows = tileRows
s.tileCols = tileCols
class ToolTip(object):
def __init__(self, widget):
self.widget = widget
self.tipwindow = None
self.id = None
self.x = self.y = 0
def showtip(self, text):
"Display text in tooltip window"
self.text = text
if self.tipwindow or not self.text:
return
x, y, cx, cy = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 57
y = y + cy + self.widget.winfo_rooty() + 27
# self.tipwindow = tw = tkinter.Toplevel(self.widget)
self.tipwindow = tw = customtkinter.CTkToplevel(self.widget)
tw.wm_overrideredirect(1)
tw.wm_geometry("+%d+%d" % (x, y))
# label = tkinter.Label(tw, text=self.text, justify=tkinter.LEFT,
# background="#ffffe0", relief=tkinter.SOLID, borderwidth=1,
# font=("tahoma", "8", "normal"))
label = customtkinter.CTkLabel(tw, text=self.text)
label.pack(ipadx=1)
def hidetip(self):
tw = self.tipwindow
self.tipwindow = None
if tw:
tw.destroy()
def CreateToolTip(widget, text):
toolTip = ToolTip(widget)
def enter(event):
toolTip.showtip(text)
def leave(event):
toolTip.hidetip()
widget.bind('<Enter>', enter)
widget.bind('<Leave>', leave)
def clickTile(ID):
logging.info("click Title ")
# widgets["fuConfigPannel"].configure(text='Tile ' + str(ID) + ' functional units')
widgets["fuConfigPannel"].configure(label_text='Tile ' + str(ID) + '\nfunctional units')
# widgets["xbarConfigPannel"].config(text='Tile ' + str(ID) + ' crossbar outgoing links')
widgets["xbarConfigPannel"].configure(label_text='Tile ' + str(ID) + '\ncrossbar outgoing links')
widgets["xbarCentralTilelabel"].configure(text='Tile ' + str(ID))
# logging.info(widgets['spmOutlinksSwitches'])
# After clicking the tile, the pannel will fill all directions
# widgets["xbarConfigPannel"].grid(columnspan=4, row=9, column=0, rowspan=3, sticky="nsew")
widgets["entireTileCheckbutton"].configure(text='Disable entire Tile ' + str(ID), state="normal")
# widgets["spmConfigPannel"].grid_forget()
selectedCgraParam.targetTileID = ID
disabled = selectedCgraParam.getTileOfID(ID).disabled
for fuType in fuTypeList:
fuCheckVars[fuType].set(selectedCgraParam.tiles[ID].fuDict[fuType])
fuCheckbuttons[fuType].configure(state="disabled" if disabled else "normal")
for xbarType in xbarTypeList:
xbarCheckVars[xbarType].set(selectedCgraParam.tiles[ID].xbarDict[xbarType])
xbarCheckbuttons[xbarType].configure(
state="disabled" if disabled or xbarType2Port[xbarType] in selectedCgraParam.tiles[
ID].neverUsedOutPorts else "normal")
entireTileCheckVar.set(1 if selectedCgraParam.getTileOfID(ID).disabled else 0)
def clickSPM():
logging.info('clickSPM')
# widgets["fuConfigPannel"].config(text='Tile ' + str(cgraParam.targetTileID) + ' functional units')
# widgets["fuConfigPannelLabel"].configure(text='Tile ' + str(cgraParam.targetTileID) + ' functional units')
#
# for fuType in fuTypeList:
# fuCheckVars[fuType].set(cgraParam.tiles[cgraParam.targetTileID].fuDict[fuType])
# fuCheckbuttons[fuType].configure(state="disabled")
#
# widgets["xbarConfigPannel"].grid_forget()
#
# spmConfigPannel = widgets["spmConfigPannel"]
# spmConfigPannel.config(text='DataSPM outgoing links')
# # After clicking the SPM, the pannel will fill all directions
# spmConfigPannel.grid(row=9, column=0, rowspan=3, columnspan=4, sticky="nsew")
#
# spmEnabledListbox = widgets["spmEnabledListbox"]
# spmDisabledListbox = widgets["spmDisabledListbox"]
#
# widgets["entireTileCheckbutton"].configure(text='Disable entire Tile ' + str(cgraParam.targetTileID), state="disabled")
def switchDataSPMOutLinks():
spmOutlinksSwitches = widgets['spmOutlinksSwitches']
for portIdx, switch in enumerate(spmOutlinksSwitches):
link = selectedCgraParam.dataSPM.outLinks[portIdx]
if switch.get():
link.disabled = False
else:
link.disabled = True
# TODO : move this inside CGRAParams and trigger UI update.
def updateFunCheckVars(type, value):
fuCheckVars[type].set(value)
def updateFunCheckoutButtons(type, updatedState):
fuCheckbuttons[type].configure(state=updatedState)
# TODO : move this inside CGRAParams and trigger UI update.
def updateXbarCheckVars(type, value):
xbarCheckVars[type].set(value)
def updateXbarCheckbuttons(type, updateState):
xbarCheckbuttons[type].configure(state=updateState)
def getFunCheckVars():
return fuCheckVars
def getXbarCheckVars():
return xbarCheckVars
multiCgraParam = MultiCGRAParam(rows=CGRA_ROWS, cols=CGRA_COLS, globalWidgets=widgets)
multiCgraParam.setSelectedCgra(0, 0)
selectedCgraParam = multiCgraParam.getSelectedCgra()
selectedCgraParam.set_cgra_param_callbacks(switchDataSPMOutLinks=switchDataSPMOutLinks,
updateFunCheckoutButtons=updateFunCheckoutButtons,
updateFunCheckVars=updateFunCheckVars,
updateXbarCheckbuttons=updateXbarCheckbuttons,
updateXbarCheckVars=updateXbarCheckVars,
getFunCheckVars=getFunCheckVars,
getXbarCheckVars=getXbarCheckVars)
def apply_fu_types_to_cgra(fu_types):
"""Apply FU types to the current selectedCgraParam tiles and update UI checkboxes."""
if not fu_types:
return
for tile in selectedCgraParam.tiles:
for fuType in fuTypeList:
tile.fuDict[fuType] = 1 if fuType in fu_types else 0
for fuType in fuTypeList:
if fuType in fuCheckVars:
fuCheckVars[fuType].set(1 if fuType in fu_types else 0)
def display_ai_response(response, error):
"""Display AI response in chat (called from main thread)."""
chatDisplay = widgets.get("chatDisplay")
sendButton = widgets.get("sendButton")
applyButton = widgets.get("applyConfigButton")
if not chatDisplay:
return
chatDisplay.configure(state="normal")
if error:
chatDisplay.insert(tkinter.END, f"AI: ⚠️ {error}\n")
else:
chatDisplay.insert(tkinter.END, f"AI: {response}\n")
# Check if response contains CGRA configuration
if ai_assistant.extract_cgra_config(response):
# Auto-apply balanced config as default
config = ai_assistant.lastRecommendedConfigs.get("balanced", {})
if config:
apply_config_by_mode("balanced")
updateMultiCgraPanelOnly(master) # Update Multi-CGRA panel without resetting Per-CGRA entries
clickUpdate(master) # Update Per-CGRA panel with AI values
# Apply FU types after clickUpdate to avoid being overwritten
fu_types = config.get("fu_types", [])
apply_fu_types_to_cgra(fu_types)
chatDisplay.configure(state="normal")
chatDisplay.insert(tkinter.END, "\n✅ Balanced configuration has been applied to update the CGRA.\n")
chatDisplay.insert(tkinter.END, "You can also click 'Apply AI Generated CGRA Design' to switch to a different configuration mode.\n")
if applyButton:
applyButton.configure(state="normal")
chatDisplay.insert(tkinter.END, "─" * 30 + "\n\n")
chatDisplay.configure(state="disabled")
chatDisplay.see(tkinter.END)
# Re-enable send button
if sendButton:
sendButton.configure(state="normal")
def clickSendChat():
"""Handle sending a chat message."""
chatInput = widgets.get("chatInput")
chatDisplay = widgets.get("chatDisplay")
sendButton = widgets.get("sendButton")
if not chatInput or not chatDisplay:
return
user_message = chatInput.get().strip()
if not user_message:
return
# Clear input and disable send button
chatInput.delete(0, tkinter.END)
if sendButton:
sendButton.configure(state="disabled")
# Display user message
chatDisplay.configure(state="normal")
chatDisplay.insert(tkinter.END, f"You: {user_message}\n")
chatDisplay.insert(tkinter.END, "─" * 30 + "\n")
chatDisplay.insert(tkinter.END, "AI: Thinking...\n")
chatDisplay.configure(state="disabled")
chatDisplay.see(tkinter.END)
# Call API in background thread
def on_response(response, error):
# Schedule UI update on main thread
chatDisplay.after(0, lambda: update_response(response, error))
def update_response(response, error):
chatDisplay.configure(state="normal")
# Remove "Thinking..." line
chatDisplay.delete("end-2l", "end-1l")
chatDisplay.configure(state="disabled")
display_ai_response(response, error)
thread = threading.Thread(target=ai_assistant.call_ai_api, args=(user_message, on_response))
thread.daemon = True
thread.start()
def clickClearChat():
"""Clear the chat history."""
chatDisplay = widgets.get("chatDisplay")
if chatDisplay:
chatDisplay.configure(state="normal")
chatDisplay.delete("1.0", tkinter.END)
chatDisplay.configure(state="disabled")
# Also clear conversation history
ai_assistant.aiChatConfig["chat_history"] = []
def handle_chat_enter(event):
"""Handle Enter key press in chat input."""
clickSendChat()
return "break" # Prevent default behavior
def on_provider_change(choice):
"""Handle provider selection change."""
ai_assistant.aiChatConfig["provider"] = choice
ai_assistant.aiChatConfig["chat_history"] = [] # Clear history when switching provider
# Update model menu with provider's models
provider_config = ai_assistant.AI_PROVIDERS[choice]
models = provider_config["models"]
ai_assistant.aiChatConfig["model"] = models[0]
modelMenu = widgets.get("modelMenu")
if modelMenu:
modelMenu.configure(values=models)
modelMenu.set(models[0])
# Update API key from environment
env_key = provider_config["env_key"]
env_value = os.environ.get(env_key, "")
ai_assistant.aiChatConfig["api_key"] = env_value
apiKeyEntry = widgets.get("apiKeyEntry")
if apiKeyEntry:
apiKeyEntry.delete(0, tkinter.END)
if env_value:
apiKeyEntry.insert(0, env_value)
logging.info(f"AI provider changed to: {choice}")
def on_model_change(choice):
"""Handle model selection change."""
ai_assistant.aiChatConfig["model"] = choice
logging.info(f"AI model changed to: {choice}")
def on_api_key_change(event=None):
"""Handle API key input change."""
apiKeyEntry = widgets.get("apiKeyEntry")
if apiKeyEntry:
ai_assistant.aiChatConfig["api_key"] = apiKeyEntry.get().strip()
def apply_config_by_mode(mode):
"""Apply the specified mode configuration to the GUI."""
config = ai_assistant.lastRecommendedConfigs.get(mode, {})
if not config:
return False
try:
# Get configuration values (already validated)
rows = config.get("cgra_rows", 4)
columns = config.get("cgra_columns", 4)
data_mem = config.get("data_spm_kb", 8)
config_mem = config.get("configMemSize", 64)
mc_rows = config.get("multi_cgra_rows", 1)
mc_cols = config.get("multi_cgra_columns", 1)
# Update CGRA config entries
rowsEntry = widgets.get("rowsEntry")
columnsEntry = widgets.get("columnsEntry")
dataMemEntry = widgets.get("dataMemEntry")
configMemEntry = widgets.get("configMemEntry")
if rowsEntry:
rowsEntry.delete(0, tkinter.END)
rowsEntry.insert(0, str(rows))
if columnsEntry:
columnsEntry.delete(0, tkinter.END)
columnsEntry.insert(0, str(columns))
if dataMemEntry:
dataMemEntry.delete(0, tkinter.END)
dataMemEntry.insert(0, str(data_mem))
if configMemEntry:
configMemEntry.delete(0, tkinter.END)
configMemEntry.insert(0, str(config_mem))
# Update Multi-CGRA config entries if available
mcRowsEntry = widgets.get("multiCgraRowsLabelEntry")
mcColsEntry = widgets.get("multiCgraColumnsEntry")
if mcRowsEntry:
mcRowsEntry.delete(0, tkinter.END)
mcRowsEntry.insert(0, str(mc_rows))
if mcColsEntry:
mcColsEntry.delete(0, tkinter.END)
mcColsEntry.insert(0, str(mc_cols))
# Apply FU types to all tiles if specified
fu_types = config.get("fu_types", [])
fu_applied = False
if fu_types:
apply_fu_types_to_cgra(fu_types)
fu_applied = True
# Show success message
mode_labels = {"high_performance": "High Performance", "balanced": "Balanced", "low_power": "Low Power"}
mode_label = mode_labels.get(mode, mode)
chatDisplay = widgets.get("chatDisplay")
if chatDisplay:
chatDisplay.configure(state="normal")
chatDisplay.insert(tkinter.END, f"✓ {mode_label} Config Applied:\n")
chatDisplay.insert(tkinter.END, f" CGRA: {rows}x{columns}\n")
chatDisplay.insert(tkinter.END, f" Multi-CGRA: {mc_rows}x{mc_cols}\n")
chatDisplay.insert(tkinter.END, f" Data SPM: {data_mem} KB\n")
chatDisplay.insert(tkinter.END, f" Config Memory: {config_mem} entries\n")
if fu_applied:
chatDisplay.insert(tkinter.END, f" FU Types: {', '.join(fu_types)}\n")
chatDisplay.insert(tkinter.END, "─" * 30 + "\n")
chatDisplay.configure(state="disabled")
chatDisplay.see(tkinter.END)
logging.info(f"Applied {mode} config: rows={rows}, cols={columns}")
return True
except Exception as e:
logging.error(f"Failed to apply config: {e}")
return False
def apply_recommended_config():
"""Show dialog to choose between high_performance, balanced, and low power config."""
has_perf = bool(ai_assistant.lastRecommendedConfigs.get("high_performance"))
has_bal = bool(ai_assistant.lastRecommendedConfigs.get("balanced"))
has_lp = bool(ai_assistant.lastRecommendedConfigs.get("low_power"))
if not has_perf and not has_bal and not has_lp:
tkinter.messagebox.showwarning("No Configuration",
"No recommended configuration available.\nAsk AI to recommend parameters first.")
return
# Create selection dialog
dialog = customtkinter.CTkToplevel()
dialog.title("Select Configuration Mode")
dialog.geometry("450x180")
dialog.transient()
# dialog.grab_set()
dialog.update_idletasks()
try:
dialog.grab_set()
except Exception as e:
print(f"Warning: Cannot set grab on dialog: {e}")
label = customtkinter.CTkLabel(
dialog,
text="Choose configuration mode:",
font=customtkinter.CTkFont(size=14, weight="bold")
)
label.pack(pady=(15, 10))
btn_frame = customtkinter.CTkFrame(dialog)
btn_frame.pack(pady=10, padx=15, fill="x")
def apply_and_update(mode):
dialog.destroy()
apply_config_by_mode(mode)
updateMultiCgraPanelOnly(master) # Update Multi-CGRA panel without resetting Per-CGRA entries
clickUpdate(master) # Update Per-CGRA panel with AI values
fu_types = ai_assistant.lastRecommendedConfigs.get(mode, {}).get("fu_types", [])
apply_fu_types_to_cgra(fu_types)
def apply_perf():
apply_and_update("high_performance")
def apply_bal():
apply_and_update("balanced")
def apply_lp():
apply_and_update("low_power")
# Performance button
perf_btn = customtkinter.CTkButton(
btn_frame,
text="High Performance",
command=apply_perf,
state="normal" if has_perf else "disabled",
fg_color="#1565C0",
hover_color="#0D47A1",
height=40
)
perf_btn.pack(side="left", padx=3, expand=True, fill="x")
# Balanced button
bal_btn = customtkinter.CTkButton(
btn_frame,
text="Balanced",
command=apply_bal,
state="normal" if has_bal else "disabled",
fg_color="#F57C00",
hover_color="#E65100",
height=40
)
bal_btn.pack(side="left", padx=3, expand=True, fill="x")
# Low Power button
lp_btn = customtkinter.CTkButton(
btn_frame,
text="Low Power",
command=apply_lp,
state="normal" if has_lp else "disabled",
fg_color="#2E7D32",
hover_color="#1B5E20",
height=40
)
lp_btn.pack(side="left", padx=3, expand=True, fill="x")
# Cancel button
cancel_btn = customtkinter.CTkButton(
dialog,
text="Cancel",
command=dialog.destroy,
width=80
)
cancel_btn.pack(pady=10)
def clickAutoConfig():
"""Send auto-configuration request to AI."""
chatInput = widgets.get("chatInput")
chatDisplay = widgets.get("chatDisplay")
if not chatInput or not chatDisplay:
return
# Show prompt dialog for application description
dialog = customtkinter.CTkInputDialog(
text="Describe your application/kernel:\n(e.g., 'matrix multiplication', 'convolution for CNN', 'FFT processing')",
title="Auto Configure CGRA"
)
user_input = dialog.get_input()
if not user_input or not user_input.strip():
return
# Create the auto-config request message
auto_config_prompt = f"Please recommend optimal CGRA parameters for: {user_input.strip()}"
# Insert the prompt into chat input and send
chatInput.delete(0, tkinter.END)
chatInput.insert(0, auto_config_prompt)
clickSendChat()
def clickAIAnalyzeCurrentState():
"""Analyze current kernel/mapping state and send to AI for recommendations."""
chatDisplay = widgets.get("chatDisplay")
if not chatDisplay:
return
# Check if mapping has been done
map_ii_entry = widgets.get("mapIIEntry")
has_mapping = map_ii_entry and map_ii_entry.get() and map_ii_entry.get().strip() != ""
if not has_mapping or selectedCgraParam.DFGNodeCount <= 0:
tkinter.messagebox.showinfo(
"Mapping Required",
" Please first enter a kernel and complete the compilation and mapping work in the Kernel panel.\n"
"Then click this button again for AI analysis."
)
return
# Gather mapping results
current_rows = widgets.get("rowsEntry").get() if widgets.get("rowsEntry") else "4"
current_cols = widgets.get("columnsEntry").get() if widgets.get("columnsEntry") else "4"
config_mem = widgets.get("configMemEntry").get() if widgets.get("configMemEntry") else "64"
data_mem = widgets.get("dataMemEntry").get() if widgets.get("dataMemEntry") else "8"
kernel_name = selectedCgraParam.targetKernelName or "unknown"
dfg_nodes = selectedCgraParam.DFGNodeCount
rec_mii = widgets.get("recMIIEntry").get() if widgets.get("recMIIEntry") else "0"
res_mii = widgets.get("resMIIEntry").get() if widgets.get("resMIIEntry") else "0"
map_ii = map_ii_entry.get()
try:
speedup = dfg_nodes / int(map_ii)
except:
speedup = 0
# Build prompt for AI
analyze_prompt = f"""Based on the following CGRA mapping results, analyze and recommend a better configuration:
## Current Configuration
- CGRA Size: {current_rows}x{current_cols}
- Config Memory: {config_mem}
- Data SPM: {data_mem} KB
## Mapping Results
- Kernel: {kernel_name}
- DFG Node Count: {dfg_nodes}
- RecMII (recurrence): {rec_mii}
- ResMII (resource): {res_mii}
- Mapping II (actual): {map_ii}
- Speedup: {speedup:.2f}x
## Analysis Required
1. Is Mapping II close to the theoretical optimum (RecMII/ResMII)?
2. If there's a gap, what might be the bottleneck?
3. What configuration would improve high_performance?
Please provide specific CGRA parameter recommendations."""
# Show in chat
chatDisplay.configure(state="normal")
chatDisplay.insert(tkinter.END, f"You: Analyze {kernel_name} mapping\n")
chatDisplay.insert(tkinter.END, f" CGRA: {current_rows}x{current_cols}, ")
chatDisplay.insert(tkinter.END, f"DFG: {dfg_nodes} nodes\n")
chatDisplay.insert(tkinter.END, f" II: {map_ii} (Rec:{rec_mii}, Res:{res_mii})\n")
chatDisplay.insert(tkinter.END, "─" * 30 + "\n")
chatDisplay.configure(state="disabled")
chatDisplay.see(tkinter.END)
# Send to AI
def on_response(response, error):
chatDisplay.configure(state="normal")
if error:
chatDisplay.insert(tkinter.END, f"Error: {error}\n")
else:
chatDisplay.insert(tkinter.END, f"AI: {response}\n")
if ai_assistant.extract_cgra_config(response):
widgets["applyConfigButton"].configure(state="normal")
chatDisplay.insert(tkinter.END, "─" * 30 + "\n\n")
chatDisplay.configure(state="disabled")
chatDisplay.see(tkinter.END)
import threading
thread = threading.Thread(target=lambda: ai_assistant.call_ai_api(analyze_prompt, on_response))
thread.daemon = True
thread.start()
def clickSPMPortDisable():
spmEnabledListbox = widgets["spmEnabledListbox"]
portIndex = spmEnabledListbox.curselection()
if portIndex:
port = spmEnabledListbox.get(portIndex)
spmEnabledListbox.delete(portIndex)
widgets["spmDisabledListbox"].insert(0, port)
link = selectedCgraParam.dataSPM.outLinks[port]
link.disabled = True
def clickSPMPortEnable():
spmDisabledListbox = widgets["spmDisabledListbox"]
portIndex = spmDisabledListbox.curselection()
if portIndex:
port = spmDisabledListbox.get(portIndex)
spmDisabledListbox.delete(portIndex)
widgets["spmEnabledListbox"].insert(0, port)
link = selectedCgraParam.dataSPM.outLinks[port]
link.disabled = False
def clickEntireTileCheckbutton():
if entireTileCheckVar.get() == 1:
for fuType in fuTypeList:
fuCheckVars[fuType].set(0)
tile = selectedCgraParam.getTileOfID(selectedCgraParam.targetTileID)
tile.fuDict[fuType] = 0
# clickFuCheckbutton(fuType)
fuCheckbuttons[fuType].configure(state="disabled")
selectedCgraParam.getTileOfID(selectedCgraParam.targetTileID).disabled = True
else:
for fuType in fuTypeList:
fuCheckVars[fuType].set(0)
tile = selectedCgraParam.getTileOfID(selectedCgraParam.targetTileID)
tile.fuDict[fuType] = 0
# clickFuCheckbutton(fuType)
fuCheckbuttons[fuType].configure(state="normal")
# cgraParam.getTileOfID(cgraParam.targetTileID).disabled = False
def clickFuCheckbutton(fuType):
selectedCgraParam.updateFuCheckbutton(fuType, fuCheckVars[fuType].get())
def clickXbarCheckbutton(xbarType):
selectedCgraParam.updateXbarCheckbutton(xbarType, xbarCheckVars[xbarType].get())
def clickUpdate(root):
rows = int(widgets["rowsEntry"].get())
columns = int(widgets["columnsEntry"].get())
configMemSize = int(widgets["configMemEntry"].get())
dataMemSize = int(widgets["dataMemEntry"].get())
global selectedCgraParam
oldCGRA = selectedCgraParam
old_rows_num = selectedCgraParam.rows
if selectedCgraParam.rows != rows or selectedCgraParam.columns != columns:
selectedCgraParam = CGRAParam(rows, columns, CONFIG_MEM_SIZE, DATA_MEM_SIZE, widgets)
selectedCgraParam.set_cgra_param_callbacks(switchDataSPMOutLinks=switchDataSPMOutLinks,
updateFunCheckoutButtons=updateFunCheckoutButtons,
updateFunCheckVars=updateFunCheckVars,
updateXbarCheckbuttons=updateXbarCheckbuttons,
updateXbarCheckVars=updateXbarCheckVars,
getFunCheckVars=getFunCheckVars,
getXbarCheckVars=getXbarCheckVars)
multiCgraParam.cgras[multiCgraParam.selected_row][multiCgraParam.selected_col] = selectedCgraParam
# dataSPM = ParamSPM(MEM_WIDTH, rows, rows)
# cgraParam.initDataSPM(dataSPM)
create_cgra_pannel(root, rows, columns)
# kernel related information and be kept to avoid redundant compilation
selectedCgraParam.updateMemSize(configMemSize, dataMemSize)
selectedCgraParam.updateTiles()
selectedCgraParam.updateLinks()
if old_rows_num != rows:
selectedCgraParam.updateSpmOutlinks()
selectedCgraParam.targetAppName = oldCGRA.targetAppName
selectedCgraParam.compilationDone = oldCGRA.compilationDone
selectedCgraParam.targetKernels = oldCGRA.targetKernels
selectedCgraParam.targetKernelName = oldCGRA.targetKernelName
selectedCgraParam.DFGNodeCount = oldCGRA.DFGNodeCount
selectedCgraParam.recMII = oldCGRA.recMII
selectedCgraParam.verilogDone = False
widgets["verilogText"].delete("1.0", tkinter.END)
widgets["resMIIEntry"].delete(0, tkinter.END)
if len(selectedCgraParam.getValidTiles()) > 0 and selectedCgraParam.DFGNodeCount > 0:
selectedCgraParam.resMII = math.ceil(
(selectedCgraParam.DFGNodeCount + 0.0) / len(selectedCgraParam.getValidTiles())) // 1
widgets["resMIIEntry"].insert(0, selectedCgraParam.resMII)
else:
widgets["resMIIEntry"].insert(0, 0)
def clickReset(root):
rows = int(widgets["rowsEntry"].get())
columns = int(widgets["columnsEntry"].get())
configMemSize = int(widgets["configMemEntry"].get())
dataMemSize = int(widgets["dataMemEntry"].get())
global selectedCgraParam
oldCGRA = selectedCgraParam
if selectedCgraParam.rows != rows or selectedCgraParam.columns != columns:
selectedCgraParam = CGRAParam(rows, columns, CONFIG_MEM_SIZE, DATA_MEM_SIZE, widgets)
selectedCgraParam.set_cgra_param_callbacks(switchDataSPMOutLinks=switchDataSPMOutLinks,
updateFunCheckoutButtons=updateFunCheckoutButtons,
updateFunCheckVars=updateFunCheckVars,
updateXbarCheckbuttons=updateXbarCheckbuttons,
updateXbarCheckVars=updateXbarCheckVars,
getFunCheckVars=getFunCheckVars,
getXbarCheckVars=getXbarCheckVars)
selectedCgraParam.updateMemSize(configMemSize, dataMemSize)
selectedCgraParam.resetTiles()
selectedCgraParam.enableAllTemplateLinks()
selectedCgraParam.resetLinks()
selectedCgraParam.updateSpmOutlinks()
create_cgra_pannel(root, rows, columns)
# for _ in range(cgraParam.rows):
# widgets["spmEnabledListbox"].delete(0)
# widgets["spmDisabledListbox"].delete(0)
# widgets['spmOutlinksSwitches'] = []
# spmOutlinksSwitches = []
# spmConfigPannel = widgets["spmConfigPannel"]
# for port in cgraParam.dataSPM.outLinks:
# switch = customtkinter.CTkSwitch(spmConfigPannel, text=f"link {port}", command=switchDataSPMOutLinks)
# if not cgraParam.dataSPM.outLinks[port].disabled:
# switch.select()
# switch.pack(pady=(5, 10))
# spmOutlinksSwitches.insert(0, switch)
# widgets['spmOutlinksSwitches'] = spmOutlinksSwitches
# kernel related information and be kept to avoid redundant compilation
selectedCgraParam.targetAppName = oldCGRA.targetAppName
selectedCgraParam.compilationDone = oldCGRA.compilationDone
selectedCgraParam.targetKernels = oldCGRA.targetKernels
selectedCgraParam.targetKernelName = oldCGRA.targetKernelName
selectedCgraParam.DFGNodeCount = oldCGRA.DFGNodeCount
selectedCgraParam.recMII = oldCGRA.recMII
widgets["verilogText"].delete(0, tkinter.END)
widgets["resMIIEntry"].delete(0, tkinter.END)
if len(selectedCgraParam.getValidTiles()) > 0 and selectedCgraParam.DFGNodeCount > 0:
selectedCgraParam.resMII = math.ceil(
(selectedCgraParam.DFGNodeCount + 0.0) / len(selectedCgraParam.getValidTiles())) // 1
widgets["resMIIEntry"].insert(0, selectedCgraParam.resMII)
else:
widgets["resMIIEntry"].insert(0, 0)
# Customizes class to force flow style dump.
class FlowList(list):
pass
import yaml
def flow_list_representer(dumper, data):
return dumper.represent_sequence('tag:yaml.org,2002:seq', data, flow_style=True)
# Forces dumping the FlowList in the flow style.
yaml.add_representer(FlowList, flow_list_representer)
def dumpArchYaml(yamlPath = 'arch.yaml'):
"""
Dumps the architecture to a YAML file.
The default path is `build/arch.yaml`.
"""
# Extract values from widgets
# Multi-CGRA Defaults
topo = widgets["topologyVariable"].get() if "topologyVariable" in widgets else "mesh"
mc_rows_str = widgets["multiCgraRowsLabelEntry"].get()
mc_rows = int(mc_rows_str)
mc_cols_str = widgets["multiCgraColumnsEntry"].get()
mc_cols = int(mc_cols_str)
mem_cap_str = widgets["totalSRAMSizeLabelEntry"].get()
mem_cap = int(mem_cap_str)
data_bw_str = widgets["dataBitwidthEntry"].get()
data_bw = int(data_bw_str)
vec_lanes_str = widgets["vectorLanesEntry"].get()
vec_lanes = int(vec_lanes_str)
# CGRA Defaults
cgra_rows_str = widgets["rowsEntry"].get()
cgra_rows = int(cgra_rows_str)
cgra_cols_str = widgets["columnsEntry"].get()
cgra_cols = int(cgra_cols_str)
cfg_mem_str = widgets["configMemEntry"].get()
cfg_mem = int(cfg_mem_str)
sram_str = widgets["dataMemEntry"].get()
sram = int(sram_str)
data = {
"architecture": {
"name": "NeuraMultiCgra",
"version": "1.0"
},
"multi_cgra_defaults": {
"base_topology": topo,
"rows": mc_rows,
"columns": mc_cols,
"memory": {
"capacity": mem_cap,
"data bitwidth": data_bw,
"vector lanes": vec_lanes
}
},
"cgra_defaults": {
"rows": cgra_rows,
"columns": cgra_cols,
"configMemSize": cfg_mem,
"per bank sram": sram
},
"tile_defaults": {
"num_registers": 16,
"fu_types": FlowList(fuTypeList)
}
}
# Collects the links information.
link_overrides = []
for r in range(multiCgraParam.rows):
for c in range(multiCgraParam.cols):
target_cgra = multiCgraParam.getCgraParam(r, c)
# Checks all template links in the CGRA.
for link in target_cgra.templateLinks:
if link.disabled:
if isinstance(link.srcTile, ParamTile) and isinstance(link.dstTile, ParamTile):
link_overrides.append({
"src_cgra_x": c,
"src_cgra_y": r,
"dst_cgra_x": c,
"dst_cgra_y": r,
"src_tile_x": link.srcTile.dimX,
"src_tile_y": link.srcTile.dimY,
"dst_tile_x": link.dstTile.dimX,
"dst_tile_y": link.dstTile.dimY,
"existence": False
})
if link_overrides:
data["link_overrides"] = link_overrides
# Collects the tile information.
tile_overrides = []
for r in range(multiCgraParam.rows):
for c in range(multiCgraParam.cols):
target_cgra = multiCgraParam.getCgraParam(r, c)
for tile in target_cgra.tiles:
# Case 1: Tile is totally disabled.
if tile.disabled:
tile_overrides.append({
"cgra_x": c,
"cgra_y": r,
"tile_x": tile.dimX,
"tile_y": tile.dimY,
"existence": False
})
# Case 2: Tile is enabled but has non-default functional units.
elif not tile.isDefaultFus():
fuTypes = []
for fu in fuTypeList:
if tile.fuDict[fu] == 1:
fuTypes.append(fu)
tile_overrides.append({
"cgra_x": c,
"cgra_y": r,
"tile_x": tile.dimX,
"tile_y": tile.dimY,
"fu_types": FlowList(fuTypes),
"existence": True
})
if tile_overrides:
data["tile_overrides"] = tile_overrides
with open(yamlPath, 'w') as file:
yaml.dump(data, file, sort_keys=False, default_flow_style=False)
logging.info(f"Successfully dumped architecture config to {yamlPath}")
def clickTest():
# Dumps the architecture to `build/arch.yaml`.
dumpArchYaml('arch.yaml')
# need to provide the paths for lib.so and kernel.bc
os.system("mkdir test")
# os.system("cd test")
os.chdir("test")
widgets["testShow"].configure(text="0%")
widgets["testProgress"].set(0)
master.update_idletasks()
pytest_cmd = pytest_cmd = "pytest ../../VectorCGRA/cgra/test \
../../VectorCGRA/multi_cgra/test/MeshMultiCgraTemplateRTL_test.py --tb=short -v"
testProc = subprocess.Popen(
pytest_cmd,