-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.py
More file actions
1871 lines (1678 loc) · 79.9 KB
/
app.py
File metadata and controls
1871 lines (1678 loc) · 79.9 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
# -*- coding: utf-8 -*-
"""
PyTorch + Akave O3 Training Dashboard
Exact replica of the enterprise dark-theme design
"""
import streamlit as st
import os
import sys
import time
import json
import subprocess
import threading
import io
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from pathlib import Path
from datetime import datetime
try:
import plotly.graph_objects as plotly_go
HAS_PLOTLY = True
except ImportError:
HAS_PLOTLY = False
sys.path.insert(0, str(Path(__file__).parent / "src"))
try:
from pytorch_o3 import O3Client
from pytorch_o3.exceptions import O3AuthError
except ImportError:
O3Client = None
# ============================================================================
# PAGE CONFIG
# ============================================================================
st.set_page_config(
page_title="O3 Training Dashboard",
page_icon="🔴",
layout="wide",
initial_sidebar_state="expanded",
)
# ============================================================================
# CUSTOM CSS — exact dark theme from screenshot
# ============================================================================
st.markdown("""
<style>
/* ── Global Reset ── */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
html, body, [data-testid="stAppViewContainer"],
[data-testid="stApp"] {
background-color: #110a06 !important;
color: #f0e4d8 !important;
font-family: 'Inter', sans-serif !important;
}
/* ── Sidebar ── */
[data-testid="stSidebar"] {
background: #1c120c !important;
border-right: 1px solid #2d1f16 !important;
}
[data-testid="stSidebar"] * {
color: #f0e4d8 !important;
}
/* ── Hide default Streamlit chrome ── */
#MainMenu, footer, header {visibility: hidden;}
.stDeployButton {display: none;}
/* ── Cards ── */
.card {
background: #1c120c;
border: 1px solid #2d1f16;
border-radius: 12px;
padding: 24px;
margin-bottom: 16px;
}
.card-inner {
background: #110a06;
border: 1px solid #2d1f16;
border-radius: 8px;
padding: 16px;
}
/* ── Top Bar ── */
.topbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 0;
margin-bottom: 24px;
border-bottom: 1px solid #2d1f16;
}
.topbar-title {
font-size: 22px;
font-weight: 700;
color: #f0e4d8;
}
.topbar-badge {
background: #e8451e;
color: white;
padding: 4px 12px;
border-radius: 4px;
font-size: 10px;
font-weight: 700;
letter-spacing: 1px;
margin-left: 12px;
vertical-align: middle;
}
.connect-wallet-btn {
background: #e8451e;
color: white;
border: none;
border-radius: 8px;
padding: 10px 20px;
font-weight: 600;
font-size: 14px;
cursor: pointer;
}
.connect-wallet-btn:hover {
background: #c73a18;
}
/* ── Sidebar items ── */
.nav-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px;
border-radius: 8px;
margin-bottom: 4px;
cursor: pointer;
color: #a08070;
font-size: 14px;
font-weight: 500;
text-decoration: none;
}
.nav-item:hover {
background: #251a12;
color: #f0e4d8;
}
.nav-item.active {
background: #e8451e;
color: white;
}
/* ── Wallet badge ── */
.wallet-badge {
background: rgba(232, 69, 30, 0.15);
border: 1px solid #e8451e;
border-radius: 8px;
padding: 10px 14px;
margin-bottom: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.wallet-addr {
font-size: 13px;
font-weight: 500;
color: #f0e4d8;
}
.green-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #3fb950;
display: inline-block;
}
/* ── Section Headers ── */
.section-title {
font-size: 16px;
font-weight: 600;
color: #f0e4d8;
margin-bottom: 16px;
display: flex;
align-items: center;
gap: 8px;
}
/* ── Input fields dark ── */
.stTextInput > div > div > input,
.stNumberInput > div > div > input,
.stSelectbox > div > div {
background: #110a06 !important;
border: 1px solid #2d1f16 !important;
color: #f0e4d8 !important;
border-radius: 8px !important;
}
.stTextInput label, .stNumberInput label,
.stSelectbox label, .stSlider label {
color: #a08070 !important;
font-weight: 500 !important;
}
/* ── Upload area ── */
.upload-zone {
background: #110a06;
border: 2px dashed #2d1f16;
border-radius: 12px;
padding: 40px;
text-align: center;
margin-bottom: 16px;
}
.upload-zone:hover {
border-color: #e8451e;
}
.upload-icon {
font-size: 36px;
margin-bottom: 8px;
}
.upload-title {
font-size: 15px;
font-weight: 600;
color: #f0e4d8;
}
.upload-sub {
font-size: 12px;
color: #a08070;
margin-top: 4px;
}
/* ── Object table ── */
.obj-table {
width: 100%;
border-collapse: collapse;
}
.obj-table th {
text-align: left;
font-size: 11px;
font-weight: 600;
color: #a08070;
letter-spacing: 0.5px;
padding: 10px 12px;
border-bottom: 1px solid #2d1f16;
}
.obj-table td {
padding: 12px;
font-size: 13px;
color: #f0e4d8;
border-bottom: 1px solid #251a12;
vertical-align: middle;
}
.status-streaming {
background: rgba(232, 69, 30, 0.2);
color: #e8451e;
padding: 4px 10px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
}
.status-ready {
background: rgba(63, 185, 80, 0.2);
color: #3fb950;
padding: 4px 10px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
}
.inspect-link {
color: #e8451e;
font-size: 13px;
font-weight: 500;
cursor: pointer;
}
/* ── Progress bar ── */
.progress-outer {
background: #251a12;
border-radius: 8px;
height: 10px;
width: 100%;
overflow: hidden;
margin: 8px 0;
}
.progress-inner {
background: linear-gradient(90deg, #e8451e, #ff6b3d);
height: 100%;
border-radius: 8px;
transition: width 0.5s ease;
}
/* ── Log viewer ── */
.log-viewer {
background: #110a06;
border: 1px solid #2d1f16;
border-radius: 8px;
padding: 14px;
font-family: 'JetBrains Mono', 'Courier New', monospace;
font-size: 12px;
line-height: 1.7;
color: #a08070;
max-height: 200px;
overflow-y: auto;
}
.log-info {
color: #a08070;
}
/* ── Start Training Button ── */
.start-btn {
background: #e8451e;
color: white;
border: none;
border-radius: 10px;
padding: 14px 28px;
font-weight: 700;
font-size: 15px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
width: 100%;
justify-content: center;
}
.start-btn:hover {
background: #c73a18;
}
/* ── Footer status bar ── */
.footer-bar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 0;
border-top: 1px solid #2d1f16;
margin-top: 24px;
font-size: 12px;
color: #a08070;
}
/* ── Streamlit overrides ── */
.stButton > button {
background: #251a12 !important;
color: #f0e4d8 !important;
border: 1px solid #2d1f16 !important;
border-radius: 8px !important;
font-weight: 500 !important;
}
.stButton > button:hover {
background: #2d1f16 !important;
border-color: #e8451e !important;
}
/* Slider override */
.stSlider > div > div > div {
background: #e8451e !important;
}
/* Metrics */
div[data-testid="stMetric"] {
background: #1c120c;
border: 1px solid #2d1f16;
border-radius: 8px;
padding: 16px;
}
/* file uploader */
[data-testid="stFileUploader"] {
background: #110a06;
border: 2px dashed #2d1f16;
border-radius: 12px;
padding: 16px;
}
/* dataframe */
[data-testid="stDataFrame"] {
border: 1px solid #2d1f16;
border-radius: 8px;
}
/* tabs */
.stTabs [data-baseweb="tab-list"] {
gap: 2px;
background: #1c120c;
border-radius: 8px;
padding: 4px;
}
.stTabs [data-baseweb="tab"] {
background: transparent;
color: #a08070;
border-radius: 6px;
padding: 8px 16px;
}
.stTabs [aria-selected="true"] {
background: #e8451e !important;
color: white !important;
}
/* plotly charts dark bg */
.js-plotly-plot .plotly .main-svg {
background: #1c120c !important;
}
</style>
""", unsafe_allow_html=True)
# ============================================================================
# SESSION STATE
# ============================================================================
DEFAULTS = {
"page": "Overview",
"connected": False,
"wallet_addr": None,
"o3_client": None,
"data_bucket": "",
"ckpt_bucket": "",
"objects": [],
"selected_dataset": None,
"training_running": False,
"training_done": False,
"training_logs": [],
"training_epoch": 0,
"training_total_epochs": 5,
"training_loss": 0.0,
"training_accuracy": 0.0,
"checkpoints": [], # list of dicts: {epoch, loss, accuracy, cid, timestamp, path, size}
"stop_training": False,
}
for k, v in DEFAULTS.items():
if k not in st.session_state:
st.session_state[k] = v
# ============================================================================
# SAMPLE DATASETS (bundled for demo)
# ============================================================================
SAMPLE_DIR = Path(__file__).parent / "data" / "samples"
def get_sample_datasets():
"""Discover bundled sample datasets from data/samples/."""
datasets = {}
if not SAMPLE_DIR.exists():
return datasets
for d in sorted(SAMPLE_DIR.iterdir()):
if not d.is_dir():
continue
meta_path = d / "metadata.json"
meta = {}
if meta_path.exists():
with open(meta_path) as f:
meta = json.load(f)
files = []
total_size = 0
for fp in sorted(d.iterdir()):
if fp.is_file():
sz = fp.stat().st_size
total_size += sz
files.append({"name": fp.name, "size": sz, "path": str(fp)})
datasets[d.name] = {
"meta": meta,
"files": files,
"total_size": total_size,
"dir": str(d),
}
return datasets
def fmt_size(b):
if b >= 1e6: return f"{b/1e6:.1f} MB"
if b >= 1e3: return f"{b/1e3:.1f} KB"
return f"{b} B"
# ============================================================================
# SIMPLE CNN MODEL
# ============================================================================
class SimpleCNN(nn.Module):
"""Small CNN that works for 28x28 grayscale or 32x32 RGB."""
def __init__(self, in_channels=1, num_classes=10):
super().__init__()
self.conv1 = nn.Conv2d(in_channels, 16, 3, padding=1)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.adaptive = nn.AdaptiveAvgPool2d(4)
self.fc1 = nn.Linear(32 * 4 * 4, 64)
self.fc2 = nn.Linear(64, num_classes)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x)))
x = self.pool(torch.relu(self.conv2(x)))
x = self.adaptive(x)
x = x.view(x.size(0), -1)
x = torch.relu(self.fc1(x))
return self.fc2(x)
# ============================================================================
# REAL TRAINING FUNCTION
# ============================================================================
def run_training(dataset_name, epochs, batch_size, lr, ckpt_bucket):
"""Train on the selected sample dataset. Updates st.session_state live."""
samples = get_sample_datasets()
ds = samples.get(dataset_name)
if not ds:
st.session_state.training_logs.append(f"[ERROR] Dataset '{dataset_name}' not found")
st.session_state.training_running = False
return
train_file = next((f for f in ds["files"] if f["name"] == "train.pt"), None)
test_file = next((f for f in ds["files"] if f["name"] == "test.pt"), None)
if not train_file:
st.session_state.training_logs.append("[ERROR] No train.pt in dataset")
st.session_state.training_running = False
return
st.session_state.training_logs.append(f"[INFO] Loading {train_file['path']}...")
train_data = torch.load(train_file["path"], map_location="cpu", weights_only=True)
images = train_data["images"].float()
labels = train_data["labels"].long()
# Normalize to [0,1]
if images.max() > 1.0:
images = images / 255.0
# Add channel dim if needed
if images.ndim == 3: # (N, H, W) -> (N, 1, H, W)
images = images.unsqueeze(1)
in_channels = images.shape[1]
meta = ds.get("meta", {})
num_classes = meta.get("classes", 10)
st.session_state.training_logs.append(
f"[INFO] Dataset: {images.shape[0]} samples, shape={list(images.shape[1:])}, classes={num_classes}"
)
# Test data
test_images, test_labels = None, None
if test_file:
td = torch.load(test_file["path"], map_location="cpu", weights_only=True)
test_images = td["images"].float()
if test_images.max() > 1.0:
test_images = test_images / 255.0
if test_images.ndim == 3:
test_images = test_images.unsqueeze(1)
test_labels = td["labels"].long()
train_loader = DataLoader(
TensorDataset(images, labels),
batch_size=batch_size, shuffle=True
)
model = SimpleCNN(in_channels=in_channels, num_classes=num_classes)
optimizer = optim.Adam(model.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
ckpt_dir = Path("data/checkpoints")
ckpt_dir.mkdir(parents=True, exist_ok=True)
st.session_state.training_logs.append(
f"[INFO] Model: SimpleCNN ({sum(p.numel() for p in model.parameters()):,} params)"
)
st.session_state.training_logs.append(
f"[INFO] Config: epochs={epochs}, batch_size={batch_size}, lr={lr}"
)
st.session_state.training_logs.append(f"[INFO] Training started at {datetime.now().strftime('%H:%M:%S')}")
for epoch in range(1, epochs + 1):
if st.session_state.get("stop_training", False):
st.session_state.training_logs.append(f"[WARN] Training stopped by user at epoch {epoch}")
break
model.train()
running_loss = 0.0
correct = 0
total = 0
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
running_loss += loss.item() * data.size(0)
pred = output.argmax(dim=1)
correct += pred.eq(target).sum().item()
total += data.size(0)
train_loss = running_loss / total
train_acc = 100.0 * correct / total
# Test evaluation
test_acc = 0.0
if test_images is not None:
model.eval()
with torch.no_grad():
out = model(test_images)
pred = out.argmax(dim=1)
test_acc = 100.0 * pred.eq(test_labels).sum().item() / len(test_labels)
# Update session state
st.session_state.training_epoch = epoch
st.session_state.training_loss = train_loss
st.session_state.training_accuracy = test_acc if test_images is not None else train_acc
st.session_state.training_logs.append(
f"[EPOCH {epoch}/{epochs}] loss={train_loss:.4f} train_acc={train_acc:.1f}% test_acc={test_acc:.1f}%"
)
# Save checkpoint locally
ckpt_path = ckpt_dir / f"epoch_{epoch:03d}.pt"
ckpt_payload = {
"epoch": epoch,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"loss": train_loss,
"accuracy": test_acc if test_images is not None else train_acc,
}
torch.save(ckpt_payload, ckpt_path)
ckpt_size = ckpt_path.stat().st_size
# Try O3 upload if connected
cid = None
client = st.session_state.get("o3_client")
if client and ckpt_bucket:
try:
buf = io.BytesIO()
torch.save(ckpt_payload, buf)
data_bytes = buf.getvalue()
file_meta = client.upload_object(ckpt_bucket, f"checkpoint_epoch_{epoch:03d}.pt", data_bytes)
# Extract CID
if hasattr(file_meta, 'root_cid'):
cid = file_meta.root_cid
elif hasattr(file_meta, 'RootCid'):
cid = file_meta.RootCid
elif isinstance(file_meta, dict):
cid = file_meta.get('root_cid', file_meta.get('RootCid'))
if cid:
st.session_state.training_logs.append(f"[O3] Checkpoint uploaded → CID: {cid}")
else:
st.session_state.training_logs.append(f"[O3] Checkpoint uploaded (CID extraction pending)")
except Exception as e:
st.session_state.training_logs.append(f"[O3] Upload failed: {e}")
cid = None
# Store checkpoint record
st.session_state.checkpoints.append({
"epoch": epoch,
"loss": round(train_loss, 4),
"accuracy": round(test_acc if test_images is not None else train_acc, 2),
"cid": cid or "local-only",
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"path": str(ckpt_path),
"size": ckpt_size,
})
# Done
st.session_state.training_logs.append(f"[INFO] Training complete at {datetime.now().strftime('%H:%M:%S')}")
if st.session_state.checkpoints:
best = max(st.session_state.checkpoints, key=lambda c: c["accuracy"])
st.session_state.training_logs.append(
f"[INFO] Best: epoch {best['epoch']} — accuracy {best['accuracy']}% — CID: {best['cid']}"
)
st.session_state.training_running = False
st.session_state.training_done = True
# ============================================================================
# HELPERS
# ============================================================================
def validate_key(key):
return len(key) == 64 and all(c in "0123456789abcdef" for c in key.lower())
def shorten_addr(key):
return f"0x{key[:4]}...{key[-4:]}" if len(key) >= 8 else key
def do_connect(key):
if not validate_key(key):
st.error("Invalid key — must be 64 hex characters")
return False
try:
client = O3Client(private_key=key) if O3Client else None
st.session_state.o3_client = client
st.session_state.connected = True
st.session_state.wallet_addr = shorten_addr(key)
return True
except Exception as e:
st.error(f"Connection failed: {e}")
return False
# ============================================================================
# SIDEBAR
# ============================================================================
with st.sidebar:
# Logo
st.markdown("""
<div style="display:flex; align-items:center; gap:10px; margin-bottom:4px;">
<div style="background:#e8451e; border-radius:10px; width:40px; height:40px; display:flex; align-items:center; justify-content:center; font-size:20px;">🔴</div>
<div>
<div style="font-size:16px; font-weight:700;">PyTorch + Akave</div>
<div style="font-size:11px; color:#e8451e; font-weight:600; letter-spacing:1px;">O3 INTEGRATION</div>
</div>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# Wallet status
if st.session_state.connected:
st.markdown(f"""
<div class="wallet-badge">
<div>
<div style="font-size:11px; color:#e8451e; font-weight:600;">WALLET STATUS</div>
<div class="wallet-addr">{st.session_state.wallet_addr}</div>
</div>
<span class="green-dot"></span>
</div>
""", unsafe_allow_html=True)
else:
st.markdown("""
<div class="wallet-badge" style="border-color:#2d1f16; background:rgba(45,31,22,0.3);">
<div>
<div style="font-size:11px; color:#a08070; font-weight:600;">WALLET STATUS</div>
<div class="wallet-addr" style="color:#a08070;">Not Connected</div>
</div>
<span style="width:8px;height:8px;border-radius:50%;background:#f85149;display:inline-block;"></span>
</div>
""", unsafe_allow_html=True)
# Navigation
nav_items = [
("🏠", "Overview"),
("📊", "Dashboard"),
("📦", "Datasets"),
("🤖", "Training"),
("💾", "Checkpoints"),
("🪣", "Buckets"),
("📖", "API Docs"),
]
for icon, label in nav_items:
active = "active" if st.session_state.page == label else ""
if st.button(f"{icon} {label}", key=f"nav_{label}", width='stretch'):
st.session_state.page = label
st.rerun()
st.markdown("""<div style="margin-top:16px; font-size:11px; color:#a08070; font-weight:600; letter-spacing:0.5px; padding-left:16px;">SYSTEM</div>""", unsafe_allow_html=True)
if st.button("⚙️ Settings", key="nav_Settings", width='stretch'):
st.session_state.page = "Settings"
st.rerun()
# Footer
st.markdown("---")
st.markdown(f"""
<div style="font-size:12px; color:#a08070; padding:0 8px;">
<div>📡 connect.akave.ai:5500</div>
<div style="margin-top:4px;">
<span class="green-dot"></span>
<span style="color:#3fb950; font-weight:600; font-size:11px; margin-left:6px;">NODE CONNECTED</span>
</div>
</div>
""", unsafe_allow_html=True)
# ============================================================================
# TOP BAR
# ============================================================================
def top_bar():
col1, col2 = st.columns([4, 1])
with col1:
st.markdown("""
<div style="display:flex; align-items:center; gap:12px;">
<span style="font-size:22px; font-weight:700; color:#f0e4d8;">O3 Training Dashboard</span>
<span class="topbar-badge">ENTERPRISE BETA</span>
</div>
""", unsafe_allow_html=True)
with col2:
if not st.session_state.connected:
if st.button("🔴 Connect Wallet", key="top_connect", width='stretch'):
st.session_state.page = "Settings"
st.rerun()
else:
st.markdown(f"""
<div style="text-align:right; display:flex; align-items:center; justify-content:flex-end; gap:8px;">
<span style="font-size:13px; color:#a08070;">{st.session_state.wallet_addr}</span>
<div style="width:32px; height:32px; border-radius:50%; background:#2d1f16; display:flex; align-items:center; justify-content:center;">👤</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<div style='border-bottom:1px solid #2d1f16; margin:8px 0 24px 0;'></div>", unsafe_allow_html=True)
# ============================================================================
# PAGE: OVERVIEW (Landing page — scannable project summary)
# ============================================================================
def page_overview():
top_bar()
# ── Hero ──
st.markdown("""
<div style="text-align:center; padding:20px 0 10px 0;">
<div style="font-size:36px; font-weight:700; color:#f0e4d8; margin-bottom:4px;">PyTorch + Akave O3</div>
<div style="font-size:15px; color:#a08070; max-width:650px; margin:0 auto;">Decentralized ML training pipeline — stream datasets, train models, and store CID-based immutable checkpoints on Akave O3 storage.</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# ── 4 Core Components ──
st.markdown("""<div class="section-title">🧩 Core Components</div>""", unsafe_allow_html=True)
comp1, comp2, comp3, comp4 = st.columns(4)
with comp1:
st.markdown("""
<div class="card-inner" style="padding:20px; text-align:center; min-height:210px;">
<div style="font-size:28px; margin-bottom:8px;">🔌</div>
<div style="font-size:14px; font-weight:700; color:#e8451e; margin-bottom:6px;">O3Client</div>
<div style="font-size:12px; color:#a08070; line-height:1.6;">Thin wrapper around <code>akavesdk</code>. Range & full-object streaming, uploads with CID return, retry logic with exponential backoff.</div>
<div style="margin-top:10px; font-size:11px; color:#f0e4d8;">client.py</div>
</div>
""", unsafe_allow_html=True)
with comp2:
st.markdown("""
<div class="card-inner" style="padding:20px; text-align:center; min-height:210px;">
<div style="font-size:28px; margin-bottom:8px;">📦</div>
<div style="font-size:14px; font-weight:700; color:#e8451e; margin-bottom:6px;">O3Dataset</div>
<div style="font-size:12px; color:#a08070; line-height:1.6;">PyTorch <code>Dataset</code> that streams samples from O3. Two-tier caching (LRU memory + SHA256 disk), multiprocessing-safe.</div>
<div style="margin-top:10px; font-size:11px; color:#f0e4d8;">dataset.py</div>
</div>
""", unsafe_allow_html=True)
with comp3:
st.markdown("""
<div class="card-inner" style="padding:20px; text-align:center; min-height:210px;">
<div style="font-size:28px; margin-bottom:8px;">💾</div>
<div style="font-size:14px; font-weight:700; color:#e8451e; margin-bottom:6px;">O3CheckpointManager</div>
<div style="font-size:12px; color:#a08070; line-height:1.6;">CID-based checkpoint persistence. Immutable snapshots with lineage tracking, auto-resume from latest checkpoint.</div>
<div style="margin-top:10px; font-size:11px; color:#f0e4d8;">checkpoint.py</div>
</div>
""", unsafe_allow_html=True)
with comp4:
st.markdown("""
<div class="card-inner" style="padding:20px; text-align:center; min-height:210px;">
<div style="font-size:28px; margin-bottom:8px;">🧠</div>
<div style="font-size:14px; font-weight:700; color:#e8451e; margin-bottom:6px;">MNIST Example</div>
<div style="font-size:12px; color:#a08070; line-height:1.6;">End-to-end training with <code>O3Dataset</code> for streaming + <code>O3CheckpointManager</code> for CID-tracked snapshots.</div>
<div style="margin-top:10px; font-size:11px; color:#f0e4d8;">examples/train_mnist.py</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# ── Architecture / Data Flow ──
st.markdown("""<div class="section-title">🔄 Architecture & Data Flow</div>""", unsafe_allow_html=True)
st.markdown("""
<div class="card-inner" style="padding:24px;">
<div style="display:flex; align-items:center; justify-content:center; gap:14px; flex-wrap:wrap; font-size:13px;">
<div style="background:#251a12; border:2px solid #e8451e; border-radius:10px; padding:12px 18px; text-align:center;">
<div style="font-weight:700; color:#e8451e;">1. Connect</div>
<div style="color:#a08070; font-size:11px; margin-top:4px;">O3Client + PRIVATE_KEY<br/>IPC → connect.akave.ai:5500</div>
</div>
<span style="color:#e8451e; font-size:20px;">→</span>
<div style="background:#251a12; border:2px solid #e8451e; border-radius:10px; padding:12px 18px; text-align:center;">
<div style="font-weight:700; color:#e8451e;">2. Stream Data</div>
<div style="color:#a08070; font-size:11px; margin-top:4px;">O3Dataset fetches objects<br/>LRU cache → disk cache</div>
</div>
<span style="color:#e8451e; font-size:20px;">→</span>
<div style="background:#251a12; border:2px solid #e8451e; border-radius:10px; padding:12px 18px; text-align:center;">
<div style="font-weight:700; color:#e8451e;">3. Train Model</div>
<div style="color:#a08070; font-size:11px; margin-top:4px;">PyTorch DataLoader<br/>SimpleCNN / custom model</div>
</div>
<span style="color:#e8451e; font-size:20px;">→</span>
<div style="background:#251a12; border:2px solid #e8451e; border-radius:10px; padding:12px 18px; text-align:center;">
<div style="font-weight:700; color:#e8451e;">4. Checkpoint</div>
<div style="color:#a08070; font-size:11px; margin-top:4px;">O3CheckpointManager<br/>CID-versioned .pt + JSON</div>
</div>
<span style="color:#e8451e; font-size:20px;">→</span>
<div style="background:#251a12; border:2px solid #e8451e; border-radius:10px; padding:12px 18px; text-align:center;">
<div style="font-weight:700; color:#e8451e;">5. Resume</div>
<div style="color:#a08070; font-size:11px; margin-top:4px;">Auto-detect latest CID<br/>Continue from last epoch</div>
</div>
</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# ── Quick Start ──
st.markdown("""<div class="section-title">🚀 Quick Start</div>""", unsafe_allow_html=True)
qs1, qs2 = st.columns(2)
with qs1:
st.markdown(r"""
<div class="card-inner" style="padding:20px;">
<div style="font-size:13px; font-weight:600; color:#e8451e; margin-bottom:10px;">📋 Setup (CLI)</div>
<div style="font-family:'JetBrains Mono','Courier New',monospace; font-size:11px; color:#a08070; line-height:2; background:#110a06; padding:14px; border-radius:6px;">
<span style="color:#3fb950;">$</span> python -m venv .venv<br>
<span style="color:#3fb950;">$</span> .venv\Scripts\activate<br>
<span style="color:#3fb950;">$</span> pip install -r requirements.txt<br>
<span style="color:#3fb950;">$</span> pip install -e .<br>
<span style="color:#3fb950;">$</span> export AKAVE_PRIVATE_KEY="your_key"<br>
<span style="color:#3fb950;">$</span> python examples/train_mnist.py --o3-data-bucket mnist-data --o3-checkpoint-bucket mnist-ckpt --epochs 5
</div>
</div>
""", unsafe_allow_html=True)
with qs2:
st.markdown("""
<div class="card-inner" style="padding:20px;">
<div style="font-size:13px; font-weight:600; color:#e8451e; margin-bottom:10px;">🖥️ This Dashboard</div>
<div style="font-size:12px; color:#a08070; line-height:1.8;">
<strong style="color:#f0e4d8;">1.</strong> Go to <strong style="color:#f0e4d8;">Settings</strong> → enter your AKAVE_PRIVATE_KEY<br>
<strong style="color:#f0e4d8;">2.</strong> Go to <strong style="color:#f0e4d8;">Dashboard</strong> → pick a sample dataset<br>
<strong style="color:#f0e4d8;">3.</strong> Set epochs, batch size, learning rate<br>
<strong style="color:#f0e4d8;">4.</strong> Click <strong style="color:#e8451e;">▶ Start Training</strong><br>
<strong style="color:#f0e4d8;">5.</strong> Watch real-time logs, loss, accuracy<br>
<strong style="color:#f0e4d8;">6.</strong> View checkpoints with CIDs on <strong style="color:#f0e4d8;">Checkpoints</strong> page<br>
</div>
<div style="margin-top:12px; font-size:11px; color:#a08070;">No wallet? Training still works locally — CIDs appear when connected to O3.</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# ── Key Concepts ──
st.markdown("""<div class="section-title">📚 Key Concepts</div>""", unsafe_allow_html=True)
kc1, kc2, kc3 = st.columns(3)
with kc1:
st.markdown("""
<div class="card-inner" style="padding:18px;">
<div style="font-size:13px; font-weight:600; color:#e8451e; margin-bottom:8px;">🔑 CID-based Versioning</div>
<div style="font-size:12px; color:#a08070; line-height:1.7;">Every checkpoint upload returns a Content Identifier (CID) — a hash-based address. Checkpoints are <strong style="color:#f0e4d8;">immutable</strong>: same CID always → same bytes. Parent CID creates a lineage chain.</div>
</div>
""", unsafe_allow_html=True)
with kc2:
st.markdown("""
<div class="card-inner" style="padding:18px;">
<div style="font-size:13px; font-weight:600; color:#e8451e; margin-bottom:8px;">🔄 Auto-Resume</div>
<div style="font-size:12px; color:#a08070; line-height:1.7;"><code>O3CheckpointManager.resume_training()</code> finds the latest checkpoint, loads model + optimizer state, and returns the epoch to continue from. No manual bookkeeping.</div>
</div>
""", unsafe_allow_html=True)
with kc3:
st.markdown("""
<div class="card-inner" style="padding:18px;">
<div style="font-size:13px; font-weight:600; color:#e8451e; margin-bottom:8px;">📡 Chunked Streaming</div>
<div style="font-size:12px; color:#a08070; line-height:1.7;"><code>O3Dataset</code> splits objects into configurable chunks (default 1 MB). LRU memory cache + optional SHA256-keyed disk cache. Per-worker O3Client for multiprocessing safety.</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# ── Failure Modes ──
st.markdown("""<div class="section-title">⚠️ Common Failure Modes</div>""", unsafe_allow_html=True)
st.markdown("""
<div class="card-inner" style="padding:18px;">
<table style="width:100%; font-size:12px; border-collapse:collapse;">
<tr style="border-bottom:1px solid #2d1f16;">
<td style="padding:8px 12px; color:#e8451e; font-weight:600; width:30%;">Missing AKAVE_PRIVATE_KEY</td>
<td style="padding:8px 12px; color:#a08070;">O3Client raises <code>O3AuthError</code>. Set the key in Settings or export it before running CLI.</td>
</tr>
<tr style="border-bottom:1px solid #2d1f16;">
<td style="padding:8px 12px; color:#e8451e; font-weight:600;">Rate limits on upload</td>
<td style="padding:8px 12px; color:#a08070;">Large checkpoints can trigger gRPC RESOURCE_EXHAUSTED. Retries with 2-8 min backoff. Wait and re-run if persistent; training auto-resumes.</td>
</tr>
<tr style="border-bottom:1px solid #2d1f16;">
<td style="padding:8px 12px; color:#e8451e; font-weight:600;">Malformed checkpoint metadata</td>
<td style="padding:8px 12px; color:#a08070;">Logged as warning, remaining files still processed. Unexpected errors logged + re-raised.</td>
</tr>
<tr>
<td style="padding:8px 12px; color:#e8451e; font-weight:600;">Object size unknown</td>
<td style="padding:8px 12px; color:#a08070;">O3Dataset raises ValueError with the object key. Check that objects have valid metadata in the bucket.</td>
</tr>
</table>
</div>
""", unsafe_allow_html=True)
# Footer
st.markdown(f"""
<div class="footer-bar">
<div>📡 connect.akave.ai:5500 | torch {torch.__version__}</div>
<div>v0.1.0 • <span style="color:#e8451e;">PyTorch + Akave O3 Integration</span></div>
</div>
""", unsafe_allow_html=True)
# ============================================================================
# PAGE: API DOCS (scannable reference from README)
# ============================================================================
def page_api_docs():
top_bar()
st.markdown("""<div class="section-title" style="font-size:20px;">📖 API Reference</div>""", unsafe_allow_html=True)
# ── O3Client ──
st.markdown("### 🔌 O3Client")
st.markdown('<div style="font-size:13px; color:#a08070; margin-bottom:12px;">Defined in <code>pytorch_o3.client.O3Client</code> — light wrapper around akavesdk for object operations.</div>', unsafe_allow_html=True)
st.markdown("""
<div class="card-inner" style="padding:18px; font-size:12px; line-height:1.8;">
<table style="width:100%; border-collapse:collapse;">
<tr style="border-bottom:1px solid #2d1f16;">
<td style="padding:6px 10px; color:#e8451e; font-weight:600; width:40%; font-family:monospace;">O3Client(private_key=None, ipc_address="connect.akave.ai:5500")</td>
<td style="padding:6px 10px; color:#a08070;">Initialize. Uses AKAVE_PRIVATE_KEY env var if key not provided.</td>
</tr>
<tr style="border-bottom:1px solid #2d1f16;">
<td style="padding:6px 10px; color:#f0e4d8; font-family:monospace;">list_buckets()</td>
<td style="padding:6px 10px; color:#a08070;">Return all available buckets.</td>
</tr>
<tr style="border-bottom:1px solid #2d1f16;">
<td style="padding:6px 10px; color:#f0e4d8; font-family:monospace;">list_objects(bucket, prefix="", limit=1000)</td>