-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdemo_interface.py
More file actions
759 lines (691 loc) · 31.4 KB
/
demo_interface.py
File metadata and controls
759 lines (691 loc) · 31.4 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
# Copyright 2024 D-Wave
#
# 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.
"""This file stores the Dash HTML layout for the app."""
from __future__ import annotations
import json
from typing import Any, Optional
from dash import dcc, html
from dwave.cloud import Client
from plotly import graph_objects as go
import dash_bootstrap_components as dbc
from demo_configs import (
DEFAULT_QPU,
DESCRIPTION,
EXAMPLE_IMAGE_INDEX,
MAIN_HEADER,
SLIDER_EPOCHS,
SLIDER_LATENTS,
THEME_COLOR_SECONDARY,
THUMBNAIL,
)
from src.utils.callback_helpers import (
get_example_image,
LATENT_ENCODED_FILE,
STEP_1_FILE,
STEP_2_FILE,
STEP_4_FILE,
STEP_5_FILE_DEFAULT
)
# Initialize available QPUs
try:
client = Client.from_config(client="qpu")
SOLVERS = [qpu.name for qpu in client.get_solvers()]
if not len(SOLVERS):
raise Exception
except Exception:
SOLVERS = ["No Leap Access"]
# Initialize the latent diagram with either the available file or random +/- 1s
try:
with open(LATENT_ENCODED_FILE, "r") as f:
latent_qpu = json.load(f)
LATENT_DIAGRAM_START = latent_qpu[:5]
LATENT_DIAGRAM_END = latent_qpu[-1]
except Exception:
LATENT_DIAGRAM_START = [1, -1, -1, 1, -1]
LATENT_DIAGRAM_END = 1
# An empty black fig to show when loading
DEFAULT_FIG = go.Figure(
layout=go.Layout(paper_bgcolor="black", plot_bgcolor="black")
)
DEFAULT_FIG.update_xaxes(showgrid=False, zeroline=False)
DEFAULT_FIG.update_yaxes(showgrid=False, zeroline=False)
def slider(label: str, id: str, config: dict) -> html.Div:
"""Slider element for value selection.
Args:
label: The title that goes above the slider.
id: A unique selector for this element.
config: A dictionary of slider configerations, see dcc.Slider Dash docs.
"""
return html.Div(
className="slider-wrapper",
children=[
html.Label(label),
dcc.Slider(
id=id,
className="slider",
**config,
marks={
config["min"]: str(config["min"]),
config["max"]: str(config["max"]),
},
tooltip={
"placement": "bottom",
"always_visible": True,
},
),
],
)
def dropdown(label: str, id: str, options: list, value: Optional[Any] = None) -> html.Div:
"""Dropdown element for option selection.
Args:
label: The title that goes above the dropdown.
id: A unique selector for this element.
options: A list of dictionaries of labels and values.
value: Optional default value.
"""
return html.Div(
className="dropdown-wrapper",
children=[
html.Label(label),
dcc.Dropdown(
id=id,
options=options,
value=value if value else options[0]["value"],
clearable=False,
searchable=False,
),
],
)
def checklist(label: str, id: str, options: list, values: list, inline: bool = True) -> html.Div:
"""Checklist element for option selection.
Args:
label: The title that goes above the checklist.
id: A unique selector for this element.
options: A list of dictionaries of labels and values.
values: A list of values that should be preselected in the checklist.
inline: Whether the options of the checklist are displayed beside or below each other.
"""
return html.Div(
className="checklist-wrapper",
children=[
html.Label(label),
dcc.Checklist(
id=id,
className=f"checklist{' checklist--inline' if inline else ''}",
inline=inline,
options=options,
value=values,
),
],
)
def radio(label: str, id: str, options: list, value: int, inline: bool = True) -> html.Div:
"""Radio element for option selection.
Args:
label: The title that goes above the radio.
id: A unique selector for this element.
options: A list of dictionaries of labels and values.
value: The value of the radio that should be preselected.
inline: Whether the options are displayed beside or below each other.
"""
return html.Div(
className="radio-wrapper",
children=[
html.Label(label),
dcc.RadioItems(
id=id,
className=f"radio{' radio--inline' if inline else ''}",
inline=inline,
options=options,
value=value,
),
],
)
def generate_model_data(model_data: dict) -> html.Div:
"""Display model data.
Returns:
html.Div: A Div containing the model data associated with the selected model.
"""
return html.Div(
children=[
html.Div(
[
html.P([html.B("QPU: "), model_data["qpu"]]),
html.P([html.B("Epochs: "), model_data["n_epochs"]]),
]
),
html.Div(
[
html.P([html.B("Latents: "), model_data["n_latents"]]),
html.P([html.B("Batch Size: "), model_data["batch_size"]]),
]
),
],
className="display-flex model-details",
)
def generate_options(options_list: list) -> list[dict]:
"""Generates options for dropdowns, checklists, radios, etc."""
return [{"label": label, "value": i} for i, label in enumerate(options_list)]
def generate_train_tab() -> html.Div:
"""Settings for training the model.
Returns:
html.Div: A Div containing the settings for latents and save file name.
"""
qpu_options = [{"label": qpu, "value": qpu} for qpu in SOLVERS]
return html.Div(
className="settings",
children=[
dropdown(
"QPU",
"qpu-setting",
qpu_options,
value=DEFAULT_QPU if DEFAULT_QPU in SOLVERS else SOLVERS[0],
),
slider(
"Latents",
"n-latents",
SLIDER_LATENTS,
),
slider(
"Epochs",
{"type": "n-epochs", "index": 0},
SLIDER_EPOCHS,
),
html.Label("Save to File Name"),
html.Div(
[
dcc.Input(
id="file-name",
type="text",
required=True,
),
html.P(
"Invalid file name characters",
id="file-name-help-text",
className="display-none",
),
],
className="display-flex file-name-wrapper",
),
],
)
def generate_generate_tab() -> html.Div:
"""Settings for generating.
Returns:
html.Div: A Div containing the settings for selecting the training file and other settings.
"""
return html.Div(
className="settings",
children=[
dropdown(
"Trained Model",
"model-file-name",
generate_options(["No Models Found (please train and save a model)"]),
),
html.Div(id="model-details"),
checklist(
"",
"tune-params",
generate_options(["Tune Parameters"]),
[],
),
html.Div(
[
slider(
"Epochs",
{"type": "n-epochs", "index": 1},
SLIDER_EPOCHS,
),
],
id="tune-parameter-settings",
),
],
)
def generate_progress_bar(index: int) -> html.Div:
"""Create progress bar.
Returns:
html.Div: A Div containing a progress bar and captions.
"""
return html.Div(
[
html.Progress(value="0", id={"type": "progress", "index": index}),
html.Div(
[
html.P(
"Epochs Completed:", id={"type": "progress-caption-epoch", "index": index}
),
html.P("Batch:", id={"type": "progress-caption-batch", "index": index}),
],
className="display-flex",
),
],
id={"type": "progress-wrapper", "index": index},
className="visibility-hidden",
)
def generate_settings_form() -> dcc.Tabs:
"""This function generates settings training and generating.
Returns:
dcc.Tabs: Tabs containing settings for training and generation.
"""
return dcc.Tabs(
id="setting-tabs",
value="generate-tab",
mobile_breakpoint=0,
children=[
dcc.Tab(
label="Train",
id="train-tab",
className="tab",
children=[
generate_train_tab(),
html.Div(
[
generate_run_buttons("Train", "Cancel Training"),
generate_progress_bar(0),
]
),
],
),
dcc.Tab(
label="Generate",
id="generate-tab",
value="generate-tab",
className="tab",
children=[
generate_generate_tab(),
html.Div(
[
generate_run_buttons("Generate", "Cancel Generation"),
generate_progress_bar(1),
]
),
],
),
],
)
def generate_run_buttons(run_text: str, cancel_text: str) -> html.Div:
"""Run and cancel buttons to run the problem."""
return html.Div(
className="button-group",
children=[
html.Button(
id=f'{"-".join(run_text.lower().split(" "))}-button',
children=run_text,
n_clicks=0,
disabled=False,
),
html.Button(
id=f'{"-".join(cancel_text.lower().split(" "))}-button',
children=cancel_text,
n_clicks=0,
className="display-none",
),
],
)
def generate_problem_details_table(details: dict) -> html.Table:
"""Generate the problem details table.
Args:
details: A dict containing the details to display in the table with headers as keys
and content as values.
Returns:
html.Table: The table containing the problem details.
"""
return html.Table(
className="problem-details-table",
children=[
html.Thead([html.Tr([html.Th(header) for header in details.keys()])]),
html.Tbody([html.Tr([html.Td(detail) for detail in details.values()])]),
],
)
def generate_latent_vector(
latent_start: list[int]=LATENT_DIAGRAM_START,
latent_end: int=LATENT_DIAGRAM_END
) -> list:
"""Generate the visual +/- ones vector
Args:
latent_start: The first few +/- ones to show before the ``...``.
latent_end: The last digit of the latent vector.
Returns:
A list containing the visuals for the first few +/- ones and the last +/- one.
"""
latent_start_html = [
html.Div(
one, className=f"latent-{'plus' if one > 0 else 'minus'}"
) for one in latent_start
]
return [
*latent_start_html,
html.Div("..."),
html.Div(
latent_end,
className=f"latent-{'plus' if latent_end > 0 else 'minus'}"
),
]
def generate_graph(type: str) -> list:
"""Generate graph with loading.
Args:
type: Type of graph being displayed.
Returns:
A list the graph wrapped in dcc.Loading.
"""
return dcc.Loading(
parent_className="graph",
type="circle",
color=THEME_COLOR_SECONDARY,
overlay_style={"visibility": "visible"},
delay_show=100,
children=[
html.Div(
dcc.Graph(
id=f"fig-{type}-graph",
responsive=True,
config={
"displayModeBar": False,
},
figure=DEFAULT_FIG,
),
className="graph",
id=f"{type}-graph-wrapper",
),
]
)
def generate_tooltip(title: str, description: str, target: str) -> list:
"""Generate tooltip.
Args:
title: The title for the tooltip.
description: The description for the tooltip.
target: What id opens the tooltip.
Returns:
A tooltip.
"""
return dbc.Tooltip(
children=html.Div(
[
html.H5(title),
html.P(description),
],
className="dbc-tooltip-content"
),
className="dbc-tooltip",
target=target,
delay={"show": 0, "hide": 100},
)
def create_interface():
"""Set the application HTML."""
return html.Div(
id="app-container",
children=[
# Below are any temporary storage items, e.g., for sharing data between callbacks.
dcc.Store(id="has-loaded-diagram"),
dcc.Store(id="last-trained-model"),
dcc.Store(id="last-saved-id"),
dcc.Store(id="latent-mapping"),
dcc.Store(id="example-image", data=get_example_image(EXAMPLE_IMAGE_INDEX)),
dcc.Interval(id="epoch-checker", interval=500, disabled=True),
# Header brand banner
html.Div(
id="popup",
className="display-none",
children=[
html.Div(
[
html.H2("Inaccessible QPU"),
html.P(
"The model selected was trained on a QPU that you do not have access to."
),
html.P("Please select or train a new model."),
html.P("x", id="popup-toggle"),
]
)
],
),
html.Div(className="banner", children=[html.Img(src=THUMBNAIL)]),
# Settings and results columns
html.Div(
className="columns-main",
children=[
# Left column
html.Div(
id={"type": "to-collapse-class", "index": 0},
className="left-column",
children=[
html.Div(
className="left-column-layer-1", # Fixed width Div to collapse
children=[
html.Div(
className="left-column-layer-2", # Padding and content wrapper
children=[
html.Div(
[
html.H1(MAIN_HEADER),
html.P(DESCRIPTION),
],
className="header-wrapper",
),
generate_settings_form(),
],
)
],
),
# Left column collapse button
html.Div(
html.Button(
id={"type": "collapse-trigger", "index": 0},
className="left-column-collapse",
children=[html.Div(className="collapse-arrow")],
),
),
],
),
# Right column
html.Div(
className="right-column",
children=[
dcc.Tabs(
id="tabs",
value="input-tab",
mobile_breakpoint=0,
children=[
dcc.Tab(
label="Machine Learning Model",
id="input-tab",
value="input-tab", # used for switching tabs programatically
className="tab",
children=[
html.Div(
[
html.Img(
src=STEP_1_FILE,
id="step-1-input-img",
),
html.Div([
html.Div(className="forward-arrow"),
html.Img(
src=STEP_2_FILE,
id="step-2-encode-img",
),
], className="graph-model-itermediate-step"),
html.Div(
[
generate_graph("qpu"),
generate_graph("encoded"),
html.Div([
html.Div(id="arrow-left-pointer-events"), # Only here to act as the pointer event for the hover
html.Div(id="arrow-right-pointer-events"), # Only here to act as the pointer event for the hover
html.Div(className="arrow-left", id="arrow-left"),
html.Div(className="arrow-right", id="arrow-right"),
], className="latent-loss-arrows"),
html.Div([
html.Div(generate_latent_vector(), id="latent-space-vector"),
html.Div([html.Div(), html.Div()], className="curly-brace"),
html.Div("256", id="latent-diagram-size")
], className="latent-vector-diagram", id="latent-vector-diagram"),
],
className="latent-space-graph-wrapper",
),
html.Div([
html.Div(className="forward-arrow"),
html.Img(src=STEP_4_FILE, id="step-4-decode-img"),
], className="graph-model-itermediate-step"),
html.Img(src=STEP_5_FILE_DEFAULT, id="step-5-output-img"),
],
className="graph-model-wrapper"
),
generate_tooltip(
"Input Image",
"An input image from the MNIST dataset.",
"step-1-input-img",
),
generate_tooltip(
"Encoding",
"Each collection of 4 pixels represents a feature of the input image.",
"step-2-encode-img",
),
generate_tooltip(
"Quantum Computer Sample",
"The quantum computer is sampled to obtain a new list of +/- 1s. These +/- 1s can be decoded to create a new never before seen image.",
"qpu-graph-wrapper",
),
generate_tooltip(
"Mapping of Latent +/- 1s onto the Quantum Computer",
"Each +/- 1 of the latent representation is mapped to a qubit on the quantum computer. This allows for a comparison between the quantum computer and the latent representation.",
"encoded-graph-wrapper",
),
generate_tooltip(
"Negative Log-Likelihood (NLL)",
"NLL is a function that trains the quantum computer by comparing the quantum computer samples to the encoded images. This helps the quantum computer generate new +/- 1s that more accurately describe the encoded image.",
"arrow-left-pointer-events",
),
generate_tooltip(
"Max Mean Discrepancy (MMD)",
"MMD is a function that trains the encoder to encode data into +/- 1s that more closely match the quantum computer's +/- 1s. NLL and MMD alternate to make the output of the quantum computer and the encoder as similar as possible.",
"arrow-right-pointer-events",
),
generate_tooltip(
"Latent Representation",
"The encoded latent representation of the image. The number of +/- 1s is determined by the size of the latent space that was selected during training.",
"latent-vector-diagram",
),
generate_tooltip(
"Decoding",
"Each collection of 4 pixels represents a feature of the output image.",
"step-4-decode-img",
),
generate_tooltip(
"Output Image",
"The image decoded from the latent +/- 1s. The quality of the image can be impacted by the number of epochs, the size of the latent space, the batch size, and the QPU used.",
"step-5-output-img",
),
],
),
dcc.Tab(
label="Generated Images",
id="results-tab",
className="tab",
disabled=True,
children=[
html.Div(
className="tab-content-results",
children=[
html.Div(
className="graph-wrapper-flex",
children=[
html.Div(
[
html.H4("Generated"),
html.Div(
dcc.Graph(
id="fig-output",
responsive=True,
config={
"displayModeBar": False,
},
),
className="graph",
),
],
),
html.Div(
[
html.H4(
"Reconstructed Comparison"
),
html.Div(
dcc.Graph(
id="fig-reconstructed",
responsive=True,
config={
"displayModeBar": False
},
),
className="graph",
),
],
),
],
),
html.Div(id="problem-details"),
],
)
],
),
dcc.Tab(
label="Loss Graphs",
id="loss-tab",
className="tab",
disabled=True,
children=[
html.Div(
className="tab-content-results",
children=[
html.Div(
className="graph-wrapper",
children=[
html.H4(
"Mean Squared Error Loss (MSE)"
),
html.Div(
dcc.Graph(
id="fig-mse-loss",
responsive=True,
config={
"displayModeBar": False
},
),
className="graph",
),
html.H4("Total Loss (MSE + MMD)"),
html.Div(
dcc.Graph(
id="fig-total-loss",
responsive=True,
config={
"displayModeBar": False
},
),
className="graph",
),
],
),
],
)
],
),
],
)
],
),
],
),
],
)