-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.py
More file actions
719 lines (571 loc) · 31 KB
/
validator.py
File metadata and controls
719 lines (571 loc) · 31 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
"""
Core validation logic for Decloud Validator
Event-driven WebSocket architecture
"""
import asyncio
import time
from pathlib import Path
from typing import Optional, List, Dict, Tuple, Any, Set
from dataclasses import dataclass
from collections import defaultdict
import numpy as np
import torch
from rich.console import Console
from rich.table import Table
from solders.pubkey import Pubkey
from config import config, DATASETS
from dataset_manager import dataset_manager
from model_loader import model_loader, ModelPackage, LLMModelPackage
from ipfs_client import ipfs_client
from solana_client import SolanaClient, RoundInfo, GradientInfo
from websocket_listener import (
DecloudWebSocket,
RoundCreatedEvent,
GradientSubmittedEvent,
PrevalidatedEvent,
PostvalidatedEvent,
RoundFinalizedEvent,
)
console = Console()
@dataclass
class ValidationResult:
"""Result of a validation"""
round_id: int
accuracy: float
success: bool
error: Optional[str] = None
tx_signature: Optional[str] = None
@dataclass
class ValidatorStats:
"""Validator statistics"""
prevalidations: int = 0
postvalidations: int = 0
errors: int = 0
total_rounds_seen: int = 0
uptime_start: float = 0
class Validator:
"""
Decloud Validator - Event-driven validation
"""
def __init__(self, private_key: str):
self.solana = SolanaClient.from_private_key(private_key)
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.running = False
self.ws: Optional[DecloudWebSocket] = None
# Stats
self.stats = ValidatorStats()
# Track what we've validated (in-memory cache)
self.prevalidated_rounds: Set[int] = set()
self.postvalidated: Dict[int, Set[str]] = defaultdict(set)
# Pending work queues
self.prevalidate_queue: asyncio.Queue = asyncio.Queue()
self.postvalidate_queue: asyncio.Queue = asyncio.Queue()
console.print(f"[green]✓ Validator initialized[/green]")
console.print(f"[dim] Wallet: {self.solana.pubkey}[/dim]")
console.print(f"[dim] Device: {self.device}[/dim]")
console.print(f"[dim] Network: {config.network}[/dim]")
def get_balance(self) -> float:
"""Get SOL balance"""
lamports = self.solana.get_balance()
return lamports / 1e9
# ═══════════════════════════════════════════════════════════════
# Validation Logic
# ═══════════════════════════════════════════════════════════════
async def validate_model(
self,
model_cid: str,
dataset_name: str,
batch_size: int = 32,
limit: Optional[int] = None,
) -> Tuple[float, int, int]:
"""
Validate a model against a dataset
Auto-detects model type (classification vs LLM)
Returns: (accuracy, correct_count, total_count)
"""
console.print(f"[dim] Downloading model {model_cid[:20]}...[/dim]")
model_path = await ipfs_client.download_model_package(model_cid)
if model_path is None:
raise ValueError(f"Failed to download model: {model_cid}")
console.print(f"[dim] Loading model...[/dim]")
model_pkg = model_loader.load_from_directory(model_path)
model_pkg.to(self.device).eval()
# Check if LLM model
if model_pkg.is_llm:
return await self._validate_llm_model(model_pkg, dataset_name, batch_size, limit)
else:
return await self._validate_classification_model(model_pkg, dataset_name, batch_size, limit)
async def _validate_classification_model(
self,
model_pkg: ModelPackage,
dataset_name: str,
batch_size: int = 32,
limit: Optional[int] = None,
) -> Tuple[float, int, int]:
"""Validate classification model (embeddings + head)"""
limit = limit or config.validation_batch_size
console.print(f"[dim] Loading test data ({dataset_name})...[/dim]")
test_data, test_labels = dataset_manager.load_test_data(dataset_name, limit=limit)
if model_pkg.embeddings is not None:
embeddings = model_pkg.embeddings.numpy()
# Use the minimum of embeddings and labels count
min_count = min(len(embeddings), len(test_labels))
embeddings = embeddings[:min_count]
test_labels = test_labels[:min_count]
else:
if isinstance(test_data, np.ndarray) and len(test_data.shape) == 2:
embeddings = test_data
else:
raise ValueError("No embeddings in model package")
console.print(f"[dim] Running inference...[/dim]")
predictions = model_pkg.predict_batch(embeddings, batch_size=batch_size)
if len(predictions.shape) > 1:
pred_labels = np.argmax(predictions, axis=1)
else:
pred_labels = (predictions > 0.5).astype(int)
correct = (pred_labels == test_labels).sum()
total = len(test_labels)
accuracy = (correct / total) * 100
return accuracy, int(correct), total
async def _validate_llm_model(
self,
model_pkg: LLMModelPackage,
dataset_name: str,
batch_size: int = 4,
limit: Optional[int] = None,
) -> Tuple[float, int, int]:
"""
Validate LLM model using appropriate benchmark
Supports: multiple choice, perplexity, text generation evaluation
"""
if not config.allow_llm:
raise ValueError("LLM validation disabled. Enable with: decloud-validator config set allow_llm true")
limit = limit or min(config.validation_batch_size, 100) # LLM validation is slower
console.print(f"[dim] Loading LLM test data ({dataset_name})...[/dim]")
# Load LLM benchmark data
llm_data = dataset_manager.load_llm_test_data(dataset_name, limit=limit)
task_type = llm_data.get("task_type", "multiple_choice")
console.print(f"[dim] Task type: {task_type}[/dim]")
if task_type == "multiple_choice":
# Multiple choice evaluation (Arc, HellaSwag, MMLU, etc.)
questions = llm_data["questions"]
choices_list = llm_data["choices"]
labels = llm_data["labels"]
console.print(f"[dim] Running multiple choice evaluation ({len(questions)} questions)...[/dim]")
predictions = model_pkg.classify_multiple_choice(questions, choices_list, batch_size=batch_size)
correct = (predictions == np.array(labels)).sum()
total = len(labels)
elif task_type == "perplexity":
# Perplexity evaluation (WikiText, etc.)
texts = llm_data["texts"]
console.print(f"[dim] Computing perplexity ({len(texts)} samples)...[/dim]")
perplexity = model_pkg.compute_perplexity(texts, batch_size=batch_size)
# Convert perplexity to "accuracy" - lower is better
# Scale: perplexity 1 = 100%, perplexity 100+ = ~0%
accuracy = max(0, 100 - perplexity)
return accuracy, int(accuracy), 100
elif task_type == "text_classification":
# Text classification using next token probability
texts = llm_data["texts"]
labels = llm_data["labels"]
label_tokens = llm_data.get("label_tokens", ["negative", "positive"])
console.print(f"[dim] Running text classification ({len(texts)} samples)...[/dim]")
correct = 0
total = len(texts)
for text, label in zip(texts, labels):
# Get probability of each label token
probs = model_pkg.predict_next_token_probs([text], label_tokens)
pred = np.argmax(probs)
if pred == label:
correct += 1
elif task_type == "qa":
# Question answering (exact match or F1)
contexts = llm_data["contexts"]
questions = llm_data["questions"]
answers = llm_data["answers"]
console.print(f"[dim] Running QA evaluation ({len(questions)} questions)...[/dim]")
prompts = [f"Context: {c}\nQuestion: {q}\nAnswer:" for c, q in zip(contexts, questions)]
generated = model_pkg.generate(prompts, max_new_tokens=50)
correct = 0
total = len(answers)
for gen, expected in zip(generated, answers):
# Simple exact match (normalized)
gen_norm = gen.lower().strip()
if isinstance(expected, list):
if any(ans.lower().strip() in gen_norm for ans in expected):
correct += 1
else:
if expected.lower().strip() in gen_norm:
correct += 1
else:
raise ValueError(f"Unknown LLM task type: {task_type}")
accuracy = (correct / total) * 100
console.print(f"[dim] LLM accuracy: {accuracy:.2f}% ({correct}/{total})[/dim]")
return accuracy, int(correct), total
# ═══════════════════════════════════════════════════════════════
# Pre-validation
# ═══════════════════════════════════════════════════════════════
async def prevalidate_round(self, round_id: int) -> ValidationResult:
"""Pre-validate a round's base model"""
if round_id in self.prevalidated_rounds:
return ValidationResult(round_id, 0, False, "Already prevalidated (cached)")
round_info = self.solana.get_round(round_id)
if not round_info:
return ValidationResult(round_id, 0, False, "Round not found")
if round_info.status != "Active":
return ValidationResult(round_id, 0, False, f"Round not active: {round_info.status}")
if round_info.gradients_count > 0:
return ValidationResult(round_id, 0, False, "Prevalidation closed")
if not dataset_manager.is_installed(round_info.dataset):
return ValidationResult(round_id, 0, False, f"Dataset not installed: {round_info.dataset}")
if self.solana.has_prevalidated(round_id):
self.prevalidated_rounds.add(round_id)
return ValidationResult(round_id, 0, False, "Already prevalidated (chain)")
try:
console.print(f"[cyan]⚡ Prevalidating round {round_id} ({round_info.dataset})...[/cyan]")
accuracy, correct, total = await self.validate_model(
round_info.model_cid,
round_info.dataset,
)
accuracy_bps = int(accuracy * 100)
console.print(f"[dim] Submitting to blockchain...[/dim]")
tx = self.solana.prevalidate(round_id, accuracy_bps)
self.prevalidated_rounds.add(round_id)
self.stats.prevalidations += 1
console.print(f"[green]✓ Prevalidated round {round_id}: {accuracy:.2f}%[/green]")
console.print(f"[dim] TX: {tx}[/dim]")
return ValidationResult(round_id, accuracy, True, tx_signature=tx)
except Exception as e:
self.stats.errors += 1
console.print(f"[red]✗ Prevalidation failed: {e}[/red]")
return ValidationResult(round_id, 0, False, str(e))
# ═══════════════════════════════════════════════════════════════
# Post-validation
# ═══════════════════════════════════════════════════════════════
async def postvalidate_gradient(self, round_id: int, trainer_pubkey: str) -> ValidationResult:
"""Post-validate a gradient submission (supports both classification and LLM)"""
if trainer_pubkey in self.postvalidated.get(round_id, set()):
return ValidationResult(round_id, 0, False, "Already postvalidated (cached)")
trainer = Pubkey.from_string(trainer_pubkey)
round_info = self.solana.get_round(round_id)
if not round_info:
return ValidationResult(round_id, 0, False, "Round not found")
if round_info.status != "Active":
return ValidationResult(round_id, 0, False, f"Round not active: {round_info.status}")
if not dataset_manager.is_installed(round_info.dataset):
return ValidationResult(round_id, 0, False, f"Dataset not installed: {round_info.dataset}")
gradient_info = self.solana.get_gradient(round_id, trainer)
if not gradient_info:
return ValidationResult(round_id, 0, False, "Gradient not found")
if self.solana.has_postvalidated(round_id, trainer):
self.postvalidated[round_id].add(trainer_pubkey)
return ValidationResult(round_id, 0, False, "Already postvalidated (chain)")
try:
console.print(f"[cyan]⚡ Postvalidating round {round_id} trainer {trainer_pubkey[:12]}...[/cyan]")
# Download gradient/trained model
console.print(f"[dim] Downloading gradient...[/dim]")
gradient_path = await ipfs_client.download_model_package(gradient_info.cid)
if not gradient_path:
raise ValueError("Failed to download gradient")
gradient_pkg = model_loader.load_from_directory(gradient_path)
gradient_pkg.to(self.device).eval()
# Check if LLM model
if gradient_pkg.is_llm:
accuracy, correct, total = await self._postvalidate_llm(
gradient_pkg, round_info.dataset
)
else:
accuracy, correct, total = await self._postvalidate_classification(
gradient_pkg, round_info
)
accuracy_bps = int(accuracy * 100)
console.print(f"[dim] Submitting to blockchain...[/dim]")
tx = self.solana.postvalidate(round_id, trainer, accuracy_bps)
self.postvalidated[round_id].add(trainer_pubkey)
self.stats.postvalidations += 1
console.print(f"[green]✓ Postvalidated round {round_id}: {accuracy:.2f}%[/green]")
console.print(f"[dim] TX: {tx}[/dim]")
return ValidationResult(round_id, accuracy, True, tx_signature=tx)
except Exception as e:
self.stats.errors += 1
console.print(f"[red]✗ Postvalidation failed: {e}[/red]")
return ValidationResult(round_id, 0, False, str(e))
async def _postvalidate_classification(
self,
gradient_pkg: ModelPackage,
round_info: RoundInfo,
) -> Tuple[float, int, int]:
"""Postvalidate classification model (embeddings + head)"""
# Download base model for embeddings
console.print(f"[dim] Downloading base model...[/dim]")
base_path = await ipfs_client.download_model_package(round_info.model_cid)
if not base_path:
raise ValueError("Failed to download base model")
base_pkg = model_loader.load_from_directory(base_path)
if base_pkg.embeddings is None:
raise ValueError("No embeddings in base model")
embeddings = base_pkg.embeddings.numpy()
limit = config.validation_batch_size
_, test_labels = dataset_manager.load_test_data(round_info.dataset, limit=limit)
# Use the minimum of embeddings and labels count
min_count = min(len(embeddings), len(test_labels))
embeddings = embeddings[:min_count]
test_labels = test_labels[:min_count]
console.print(f"[dim] Running inference...[/dim]")
predictions = gradient_pkg.predict_batch(embeddings, batch_size=32)
if len(predictions.shape) > 1:
pred_labels = np.argmax(predictions, axis=1)
else:
pred_labels = (predictions > 0.5).astype(int)
correct = (pred_labels == test_labels).sum()
total = len(test_labels)
accuracy = (correct / total) * 100
return accuracy, int(correct), total
async def _postvalidate_llm(
self,
gradient_pkg: LLMModelPackage,
dataset_name: str,
) -> Tuple[float, int, int]:
"""Postvalidate LLM model"""
if not config.allow_llm:
raise ValueError("LLM validation disabled")
return await self._validate_llm_model(
gradient_pkg,
dataset_name,
batch_size=4,
limit=min(config.validation_batch_size, 100),
)
# ═══════════════════════════════════════════════════════════════
# Event Handlers
# ═══════════════════════════════════════════════════════════════
async def on_round_created(self, event: RoundCreatedEvent):
"""Handle new round created event"""
self.stats.total_rounds_seen += 1
console.print(f"\n[yellow]📢 New Round #{event.round_id}[/yellow]")
console.print(f"[dim] Dataset: {event.dataset}[/dim]")
console.print(f"[dim] Reward: {event.reward_amount / 1e9:.4f} SOL[/dim]")
if dataset_manager.is_installed(event.dataset):
await self.prevalidate_queue.put(event.round_id)
else:
console.print(f"[dim] ⏭ Skipping (dataset not installed)[/dim]")
async def on_gradient_submitted(self, event: GradientSubmittedEvent):
"""Handle gradient submitted event"""
console.print(f"\n[yellow]📢 Gradient submitted to Round #{event.round_id}[/yellow]")
console.print(f"[dim] Trainer: {event.trainer[:16]}...[/dim]")
round_info = self.solana.get_round(event.round_id)
if round_info and dataset_manager.is_installed(round_info.dataset):
await self.postvalidate_queue.put((event.round_id, event.trainer))
else:
console.print(f"[dim] ⏭ Skipping[/dim]")
async def on_prevalidated(self, event: PrevalidatedEvent):
"""Handle prevalidation event (from others)"""
console.print(f"[dim]👁 Round #{event.round_id} prevalidated by {event.validator[:12]}... ({event.accuracy/100:.2f}%)[/dim]")
async def on_postvalidated(self, event: PostvalidatedEvent):
"""Handle postvalidation event (from others)"""
console.print(f"[dim]👁 Round #{event.round_id} postvalidated ({event.accuracy/100:.2f}%)[/dim]")
async def on_round_finalized(self, event: RoundFinalizedEvent):
"""Handle round finalized event"""
console.print(f"\n[green]🏁 Round #{event.round_id} finalized![/green]")
if event.round_id in self.prevalidated_rounds:
console.print(f"[yellow] 💰 You have rewards! Run: decloud-validator claim {event.round_id}[/yellow]")
# ═══════════════════════════════════════════════════════════════
# Worker Tasks
# ═══════════════════════════════════════════════════════════════
async def prevalidate_worker(self):
"""Worker that processes prevalidation queue"""
while self.running:
try:
round_id = await asyncio.wait_for(self.prevalidate_queue.get(), timeout=1.0)
await self.prevalidate_round(round_id)
except asyncio.TimeoutError:
continue
except Exception as e:
console.print(f"[red]Prevalidate worker error: {e}[/red]")
async def postvalidate_worker(self):
"""Worker that processes postvalidation queue"""
while self.running:
try:
item = await asyncio.wait_for(self.postvalidate_queue.get(), timeout=1.0)
round_id, trainer = item
await self.postvalidate_gradient(round_id, trainer)
except asyncio.TimeoutError:
continue
except Exception as e:
console.print(f"[red]Postvalidate worker error: {e}[/red]")
# ═══════════════════════════════════════════════════════════════
# Initial Scan
# ═══════════════════════════════════════════════════════════════
async def scan_existing_rounds(self):
"""Scan existing rounds on startup"""
console.print("\n[cyan]🔍 Scanning existing rounds...[/cyan]")
installed = set(config.installed_datasets)
rounds = self.solana.get_active_rounds()
console.print(f"[dim] Found {len(rounds)} active rounds[/dim]")
prevalidate_count = 0
postvalidate_count = 0
for round_info in rounds:
if round_info.dataset not in installed:
continue
# Check prevalidation
if round_info.gradients_count == 0:
if not self.solana.has_prevalidated(round_info.id):
await self.prevalidate_queue.put(round_info.id)
prevalidate_count += 1
else:
self.prevalidated_rounds.add(round_info.id)
# Check postvalidation - scan all gradients for this round
if round_info.gradients_count > 0:
console.print(f"[dim] Round {round_info.id}: {round_info.gradients_count} gradients, scanning...[/dim]")
gradients = self.solana.get_all_gradients_for_round(round_info.id)
console.print(f"[dim] Found {len(gradients)} gradient accounts[/dim]")
for gradient in gradients:
trainer_pubkey = gradient.trainer
# Check if we already postvalidated this
if trainer_pubkey in self.postvalidated.get(round_info.id, set()):
continue
# Check on chain
try:
trainer = Pubkey.from_string(trainer_pubkey)
if self.solana.has_postvalidated(round_info.id, trainer):
self.postvalidated[round_info.id].add(trainer_pubkey)
continue
except Exception as e:
console.print(f"[dim] Error checking trainer {trainer_pubkey[:12]}: {e}[/dim]")
continue
# Queue for postvalidation
await self.postvalidate_queue.put((round_info.id, trainer_pubkey))
postvalidate_count += 1
console.print(f"[green]✓ Found {prevalidate_count} rounds to prevalidate[/green]")
console.print(f"[green]✓ Found {postvalidate_count} gradients to postvalidate[/green]")
# ═══════════════════════════════════════════════════════════════
# Main Loop
# ═══════════════════════════════════════════════════════════════
async def start(self):
"""Start the validator"""
self.running = True
self.stats.uptime_start = time.time()
self.show_status()
if not config.installed_datasets:
console.print("\n[red]✗ No datasets installed![/red]")
console.print("[dim]Run: decloud-validator dataset install-all[/dim]")
return
console.print("\n[cyan]🔌 Connecting to Solana WebSocket...[/cyan]")
self.ws = DecloudWebSocket()
self.ws.on_round_created = self.on_round_created
self.ws.on_gradient_submitted = self.on_gradient_submitted
self.ws.on_prevalidated = self.on_prevalidated
self.ws.on_postvalidated = self.on_postvalidated
self.ws.on_round_finalized = self.on_round_finalized
if not await self.ws.connect():
console.print("[red]✗ Failed to connect WebSocket[/red]")
return
if not await self.ws.subscribe():
console.print("[red]✗ Failed to subscribe[/red]")
return
await self.scan_existing_rounds()
console.print("\n[green]🚀 Validator running! Listening for events...[/green]")
console.print("[dim]Press Ctrl+C to stop[/dim]\n")
workers = [
asyncio.create_task(self.ws.listen()),
asyncio.create_task(self.prevalidate_worker()),
asyncio.create_task(self.postvalidate_worker()),
]
try:
await asyncio.gather(*workers)
except asyncio.CancelledError:
pass
finally:
self.running = False
await self.ws.disconnect()
def stop(self):
"""Stop the validator"""
self.running = False
console.print("\n[yellow]Stopping validator...[/yellow]")
# ═══════════════════════════════════════════════════════════════
# Rewards
# ═══════════════════════════════════════════════════════════════
def claim_rewards(self, round_id: int) -> Dict[str, Any]:
"""Claim all rewards for a round"""
results = {"pre": None, "post": [], "total_claimed": 0}
round_info = self.solana.get_round(round_id)
if not round_info:
return {"error": "Round not found"}
if round_info.status != "Finalized":
return {"error": f"Round not finalized: {round_info.status}"}
pre = self.solana.get_pre_validation(round_id, self.solana.pubkey)
if pre and not pre.reward_claimed:
try:
tx = self.solana.claim_validator_pre(round_id)
results["pre"] = {"tx": tx, "success": True}
console.print(f"[green]✓ Claimed pre-validation reward[/green]")
except Exception as e:
results["pre"] = {"error": str(e), "success": False}
elif pre and pre.reward_claimed:
results["pre"] = {"error": "Already claimed", "success": False}
for trainer in self.postvalidated.get(round_id, set()):
try:
trainer_pk = Pubkey.from_string(trainer)
post = self.solana.get_post_validation(round_id, trainer_pk, self.solana.pubkey)
if post and not post.reward_claimed:
tx = self.solana.claim_validator_post(round_id, trainer_pk)
results["post"].append({"trainer": trainer, "tx": tx, "success": True})
console.print(f"[green]✓ Claimed post reward (trainer: {trainer[:12]}...)[/green]")
except Exception as e:
results["post"].append({"trainer": trainer, "error": str(e), "success": False})
return results
# ═══════════════════════════════════════════════════════════════
# Status
# ═══════════════════════════════════════════════════════════════
def show_status(self):
"""Display validator status"""
try:
balance = self.get_balance()
except:
balance = -1
installed = config.installed_datasets
table = Table(title="🤖 Validator Status")
table.add_column("Property", style="cyan")
table.add_column("Value", style="green")
table.add_row("Wallet", str(self.solana.pubkey))
table.add_row("Balance", f"{balance:.4f} SOL" if balance >= 0 else "Error")
table.add_row("Network", config.network)
table.add_row("Device", self.device)
table.add_row("Datasets", str(len(installed)))
table.add_row("LLM Support", "Unified (same as classification)")
table.add_row("Prevalidations", str(self.stats.prevalidations))
table.add_row("Postvalidations", str(self.stats.postvalidations))
console.print(table)
if installed:
console.print(f"\n[dim]Datasets: {', '.join(installed[:10])}{'...' if len(installed) > 10 else ''}[/dim]")
def show_rounds(self, limit: int = 10):
"""Display active rounds"""
rounds = self.solana.get_active_rounds()
installed = set(config.installed_datasets)
table = Table(title=f"Active Rounds ({len(rounds)} total)")
table.add_column("ID", style="cyan")
table.add_column("Dataset", style="yellow")
table.add_column("Reward", style="green")
table.add_column("Min ★", style="magenta")
table.add_column("Pre", style="blue")
table.add_column("Gradients", style="white")
table.add_column("Status", style="white")
for round_info in rounds[:limit]:
can_validate = round_info.dataset in installed
has_prevalidated = round_info.id in self.prevalidated_rounds or self.solana.has_prevalidated(round_info.id)
min_rating = round_info.min_trainer_rating / 100
if has_prevalidated:
status = "[green]✓ done[/green]"
elif can_validate:
status = "[yellow]⏳ pending[/yellow]"
else:
status = "[dim]⏭ skip[/dim]"
table.add_row(
str(round_info.id),
round_info.dataset,
f"{round_info.reward_amount / 1e9:.4f}",
f"{min_rating:.2f}",
str(round_info.pre_count),
str(round_info.gradients_count),
status,
)
console.print(table)