forked from opentensor/subtensor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathepoch.rs
2894 lines (2706 loc) · 141 KB
/
epoch.rs
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
#![allow(
clippy::arithmetic_side_effects,
clippy::indexing_slicing,
clippy::unwrap_used
)]
use crate::mock::*;
use frame_support::{assert_err, assert_ok};
use frame_system::Config;
use pallet_subtensor::epoch::math::safe_exp;
use pallet_subtensor::*;
use rand::{distributions::Uniform, rngs::StdRng, seq::SliceRandom, thread_rng, Rng, SeedableRng};
use sp_core::U256;
use sp_runtime::DispatchError;
use std::time::Instant;
use substrate_fixed::types::I32F32;
mod mock;
pub fn fixed(val: f32) -> I32F32 {
I32F32::from_num(val)
}
pub fn fixed_to_u16(x: I32F32) -> u16 {
x.to_num::<u16>()
}
pub fn fixed_proportion_to_u16(x: I32F32) -> u16 {
fixed_to_u16(x * I32F32::from_num(u16::MAX))
}
// Normalizes (sum to 1 except 0) the input vector directly in-place.
#[allow(dead_code)]
pub fn inplace_normalize(x: &mut [I32F32]) {
let x_sum: I32F32 = x.iter().sum();
if x_sum == I32F32::from_num(0.0_f32) {
return;
}
for i in x.iter_mut() {
*i /= x_sum;
}
}
// Inplace normalize the passed positive integer weights so that they sum to u16 max value.
fn normalize_weights(mut weights: Vec<u16>) -> Vec<u16> {
let sum: u64 = weights.iter().map(|x| *x as u64).sum();
if sum == 0 {
return weights;
}
weights.iter_mut().for_each(|x| {
*x = (*x as u64 * u16::MAX as u64 / sum) as u16;
});
weights
}
// // Return as usize an I32F32 ratio of a usize input, avoiding the 0% and 100% extremes.
// fn non_extreme_fixed_ratio(ratio: I32F32, total: usize) -> usize {
// if total == 0 {
// return total;
// }
// let mut subset: usize = (ratio * I32F32::from_num(total)).to_num::<usize>();
// if subset == 0 {
// subset = 1;
// } else if subset == total {
// subset = total - 1;
// }
// return subset;
// }
// // Box-Muller Transform converting two uniform random samples to a normal random sample.
// fn normal(size: usize, rng: &mut StdRng, dist: &Uniform<u16>) -> Vec<I32F32> {
// let max: I32F32 = I32F32::from_num(u16::MAX);
// let two: I32F32 = I32F32::from_num(2);
// let eps: I32F32 = I32F32::from_num(0.000001);
// let pi: I32F32 = I32F32::from_num(PI);
// let uniform_u16: Vec<u16> = (0..(2 * size)).map(|_| rng.sample(&dist)).collect();
// let uniform: Vec<I32F32> = uniform_u16
// .iter()
// .map(|&x| I32F32::from_num(x) / max)
// .collect();
// let mut normal: Vec<I32F32> = vec![I32F32::from_num(0); size as usize];
// for i in 0..size {
// let u1: I32F32 = uniform[i] + eps;
// let u2: I32F32 = uniform[i + size] + eps;
// normal[i] = sqrt::<I32F32, I32F32>(-two * ln::<I32F32, I32F32>(u1).expect("")).expect("")
// * cos(two * pi * u2);
// }
// normal
// }
// Returns validators and servers uids with either blockwise, regular, or random interleaving.
fn distribute_nodes(
validators_n: usize,
network_n: usize,
interleave: usize,
) -> (Vec<u16>, Vec<u16>) {
let mut validators: Vec<u16> = vec![];
let mut servers: Vec<u16> = vec![];
if interleave == 0 {
// blockwise [validator_block, server_block]
validators = (0..validators_n as u16).collect();
servers = (validators_n as u16..network_n as u16).collect();
} else if interleave == 1 {
// regular interleaving [val, srv, srv, ..., srv, val, srv, srv, ..., srv, val, srv, ..., srv]
(validators, servers) = (0..network_n as u16)
.collect::<Vec<u16>>()
.iter()
.partition(|&i| *i as usize % (network_n / validators_n) == 0);
} else if interleave == 2 {
// random interleaving
let mut permuted_uids: Vec<u16> = (0..network_n as u16).collect();
permuted_uids.shuffle(&mut thread_rng());
validators = permuted_uids[0..validators_n].into();
servers = permuted_uids[validators_n..network_n].into();
}
(validators, servers)
}
#[allow(dead_code)]
fn uid_stats(netuid: u16, uid: u16) {
log::info!(
"stake: {:?}",
SubtensorModule::get_total_stake_for_hotkey(&(U256::from(uid)))
);
log::info!("rank: {:?}", SubtensorModule::get_rank_for_uid(netuid, uid));
log::info!(
"trust: {:?}",
SubtensorModule::get_trust_for_uid(netuid, uid)
);
log::info!(
"consensus: {:?}",
SubtensorModule::get_consensus_for_uid(netuid, uid)
);
log::info!(
"incentive: {:?}",
SubtensorModule::get_incentive_for_uid(netuid, uid)
);
log::info!(
"dividend: {:?}",
SubtensorModule::get_dividends_for_uid(netuid, uid)
);
log::info!(
"emission: {:?}",
SubtensorModule::get_emission_for_uid(netuid, uid)
);
}
#[allow(clippy::too_many_arguments)]
fn init_run_epochs(
netuid: u16,
n: u16,
validators: &[u16],
servers: &[u16],
epochs: u16,
stake_per_validator: u64,
server_self: bool,
input_stake: &[u64],
use_input_stake: bool,
input_weights: &[Vec<(u16, u16)>],
use_input_weights: bool,
random_weights: bool,
random_seed: u64,
sparse: bool,
) {
// === Create the network
add_network(netuid, u16::MAX - 1, 0); // set higher tempo to avoid built-in epoch, then manual epoch instead
// === Register uids
SubtensorModule::set_max_allowed_uids(netuid, n);
for key in 0..n {
let stake = if use_input_stake {
input_stake[key as usize]
} else if validators.contains(&key) {
stake_per_validator
} else {
// only validators receive stake
0
};
// let stake: u64 = 1; // alternative test: all nodes receive stake, should be same outcome, except stake
SubtensorModule::add_balance_to_coldkey_account(&(U256::from(key)), stake);
SubtensorModule::append_neuron(netuid, &(U256::from(key)), 0);
SubtensorModule::increase_stake_on_coldkey_hotkey_account(
&U256::from(key),
&U256::from(key),
stake,
);
}
assert_eq!(SubtensorModule::get_subnetwork_n(netuid), n);
// === Issue validator permits
SubtensorModule::set_max_allowed_validators(netuid, validators.len() as u16);
assert_eq!(
SubtensorModule::get_max_allowed_validators(netuid),
validators.len() as u16
);
SubtensorModule::epoch(netuid, 1_000_000_000); // run first epoch to set allowed validators
run_to_block(1); // run to next block to ensure weights are set on nodes after their registration block
// === Set weights
let mut rng = StdRng::seed_from_u64(random_seed); // constant seed so weights over multiple runs are equal
let range = Uniform::new(0, u16::MAX);
let mut weights: Vec<u16> = vec![u16::MAX / n; servers.len()];
for uid in validators {
if random_weights {
weights = (0..servers.len()).map(|_| rng.sample(range)).collect();
weights = normalize_weights(weights);
// assert_eq!(weights.iter().map(|x| *x as u64).sum::<u64>(), u16::MAX as u64); // normalized weight sum not always u16::MAX
}
if use_input_weights {
let sparse_weights = input_weights[*uid as usize].clone();
weights = sparse_weights.iter().map(|(_, w)| *w).collect();
let srvs: Vec<u16> = sparse_weights.iter().map(|(s, _)| *s).collect();
assert_ok!(SubtensorModule::set_weights(
RuntimeOrigin::signed(U256::from(*uid as u64)),
netuid,
srvs,
weights.clone(),
0
));
} else {
assert_ok!(SubtensorModule::set_weights(
RuntimeOrigin::signed(U256::from(*uid as u64)),
netuid,
servers.to_vec(),
weights.clone(),
0
));
}
}
if server_self {
for uid in servers {
assert_ok!(SubtensorModule::set_weights(
RuntimeOrigin::signed(U256::from(*uid as u64)),
netuid,
vec![*uid],
vec![u16::MAX],
0
)); // server self-weight
}
}
// === Run the epochs.
log::info!("Start {epochs} epoch(s)");
let start = Instant::now();
for _ in 0..epochs {
if sparse {
SubtensorModule::epoch(netuid, 1_000_000_000);
} else {
SubtensorModule::epoch_dense(netuid, 1_000_000_000);
}
}
let duration = start.elapsed();
log::info!(
"Time elapsed in (sparse={sparse}) epoch() is: {:?}",
duration
);
// let bonds = SubtensorModule::get_bonds( netuid );
// for (uid, node) in vec![ (validators[0], "validator"), (servers[0], "server") ] {
// log::info!("\n{node}" );
// uid_stats(netuid, uid);
// log::info!("bonds: {:?} (on validator), {:?} (on server)", bonds[uid as usize][0], bonds[uid as usize][servers[0] as usize]);
// }
}
// // Generate a random graph that is split into a major and minor set, each setting specific weight on itself and the complement on the other.
// fn split_graph(
// major_stake: I32F32,
// major_weight: I32F32,
// minor_weight: I32F32,
// weight_stddev: I32F32,
// validators_n: usize,
// network_n: usize,
// interleave: usize,
// ) -> (
// Vec<u16>,
// Vec<u16>,
// Vec<u16>,
// Vec<u16>,
// Vec<u16>,
// Vec<u16>,
// Vec<u64>,
// Vec<Vec<(u16, u16)>>,
// I32F32,
// ) {
// let servers_n: usize = network_n - validators_n;
// let major_servers_n: usize = non_extreme_fixed_ratio(major_stake, servers_n);
// let major_validators_n: usize = non_extreme_fixed_ratio(major_stake, validators_n);
// let (validators, servers) = distribute_nodes(validators_n, network_n, interleave as usize);
// let major_validators: Vec<u16> = (0..major_validators_n).map(|i| validators[i]).collect();
// let minor_validators: Vec<u16> = (major_validators_n..validators_n)
// .map(|i| validators[i])
// .collect();
// let major_servers: Vec<u16> = (0..major_servers_n).map(|i| servers[i]).collect();
// let minor_servers: Vec<u16> = (major_servers_n..servers_n).map(|i| servers[i]).collect();
// let zero: I32F32 = I32F32::from_num(0);
// let one: I32F32 = I32F32::from_num(1);
// let stddev: I32F32 = I32F32::from_num(0.3);
// let total_stake: I64F64 = I64F64::from_num(21_000_000_000_000_000 as u64);
// let mut rng = StdRng::seed_from_u64(0); // constant seed so weights over multiple runs are equal
// let dist = Uniform::new(0, u16::MAX);
// let mut stake: Vec<u64> = vec![0; network_n];
// let mut stake_fixed: Vec<I32F32> = vec![zero; network_n];
// for (ratio, vals) in vec![
// (major_stake, &major_validators),
// (one - major_stake, &minor_validators),
// ] {
// let mut sample = normal(vals.len(), &mut rng, &dist)
// .iter()
// .map(|x: &I32F32| {
// let v: I32F32 = (stddev * x) + one;
// if v < zero {
// zero
// } else {
// v
// }
// })
// .collect();
// inplace_normalize(&mut sample);
// for (i, &val) in vals.iter().enumerate() {
// stake[val as usize] =
// (I64F64::from_num(ratio) * I64F64::from_num(sample[i]) * total_stake)
// .to_num::<u64>();
// stake_fixed[val as usize] =
// I32F32::from_num(I64F64::from_num(ratio) * I64F64::from_num(sample[i]));
// }
// }
// let mut weights: Vec<Vec<(u16, u16)>> = vec![vec![]; network_n as usize];
// let mut weights_fixed: Vec<Vec<I32F32>> = vec![vec![zero; network_n]; network_n];
// for (first, second, vals) in vec![
// (major_weight, one - major_weight, &major_validators),
// (one - minor_weight, minor_weight, &minor_validators),
// ] {
// for &val in vals {
// for (weight, srvs) in vec![(first, &major_servers), (second, &minor_servers)] {
// let mut sample: Vec<I32F32> = normal(srvs.len(), &mut rng, &dist)
// .iter()
// .map(|x: &I32F32| {
// let v: I32F32 = (weight_stddev * x) + one;
// if v < zero {
// zero
// } else {
// v
// }
// })
// .collect();
// inplace_normalize(&mut sample);
// for (i, &srv) in srvs.iter().enumerate() {
// weights[val as usize].push((srv, fixed_proportion_to_u16(weight * sample[i])));
// weights_fixed[val as usize][srv as usize] = weight * sample[i];
// }
// }
// inplace_normalize(&mut weights_fixed[val as usize]);
// }
// }
// inplace_normalize(&mut stake_fixed);
// // Calculate stake-weighted mean per server
// let mut weight_mean: Vec<I32F32> = vec![zero; network_n];
// for val in 0..network_n {
// if stake_fixed[val] > zero {
// for srv in 0..network_n {
// weight_mean[srv] += stake_fixed[val] * weights_fixed[val][srv];
// }
// }
// }
// // Calculate stake-weighted absolute standard deviation
// let mut weight_dev: Vec<I32F32> = vec![zero; network_n];
// for val in 0..network_n {
// if stake_fixed[val] > zero {
// for srv in 0..network_n {
// weight_dev[srv] +=
// stake_fixed[val] * (weight_mean[srv] - weights_fixed[val][srv]).abs();
// }
// }
// }
// // Calculate rank-weighted mean of weight_dev
// let avg_weight_dev: I32F32 =
// weight_dev.iter().sum::<I32F32>() / weight_mean.iter().sum::<I32F32>();
// (
// validators,
// servers,
// major_validators,
// minor_validators,
// major_servers,
// minor_servers,
// stake,
// weights,
// avg_weight_dev,
// )
// }
// Test consensus guarantees with an epoch on a graph with 4096 nodes, of which the first 128 are validators, the graph is split into a major and minor set, each setting specific weight on itself and the complement on the other. Asserts that the major emission ratio >= major stake ratio.
// #[test]
// fn test_consensus_guarantees() {
// let netuid: u16 = 0;
// let network_n: u16 = 512;
// let validators_n: u16 = 64;
// let epochs: u16 = 1;
// let interleave = 2;
// log::info!("test_consensus_guarantees ({network_n:?}, {validators_n:?} validators)");
// for (major_stake, major_weight, minor_weight, weight_stddev) in vec![
// (0.51, 1., 1., 0.001),
// (0.51, 0.03, 0., 0.001),
// (0.51, 0.51, 0.49, 0.001),
// (0.51, 0.51, 1., 0.001),
// (0.51, 0.61, 0.8, 0.1),
// (0.6, 0.67, 0.65, 0.2),
// (0.6, 0.74, 0.77, 0.4),
// (0.6, 0.76, 0.8, 0.4),
// (0.6, 0.76, 1., 0.4),
// (0.6, 0.92, 1., 0.4),
// (0.6, 0.94, 1., 0.4),
// (0.65, 0.78, 0.85, 0.6),
// (0.7, 0.81, 0.85, 0.8),
// (0.7, 0.83, 0.85, 1.),
// ] {
// let (
// validators,
// servers,
// major_validators,
// minor_validators,
// major_servers,
// minor_servers,
// stake,
// weights,
// _avg_weight_dev,
// ) = split_graph(
// fixed(major_stake),
// fixed(major_weight),
// fixed(minor_weight),
// fixed(weight_stddev),
// validators_n as usize,
// network_n as usize,
// interleave as usize,
// );
// new_test_ext(1).execute_with(|| {
// init_run_epochs(
// netuid,
// network_n,
// &validators,
// &servers,
// epochs,
// 1,
// true,
// &stake,
// true,
// &weights,
// true,
// false,
// 0,
// false,
// );
// let mut major_emission: I64F64 = I64F64::from_num(0);
// let mut minor_emission: I64F64 = I64F64::from_num(0);
// for set in vec![major_validators, major_servers] {
// for uid in set {
// major_emission +=
// I64F64::from_num(SubtensorModule::get_emission_for_uid(netuid, uid));
// }
// }
// for set in vec![minor_validators, minor_servers] {
// for uid in set {
// minor_emission +=
// I64F64::from_num(SubtensorModule::get_emission_for_uid(netuid, uid));
// }
// }
// let major_ratio: I32F32 =
// I32F32::from_num(major_emission / (major_emission + minor_emission));
// assert!(major_stake <= major_ratio);
// });
// }
// }
// Test an epoch on an empty graph.
// #[test]
// fn test_overflow() {
// new_test_ext(1).execute_with(|| {
// log::info!("test_overflow:");
// let netuid: u16 = 1;
// add_network(netuid, 0, 0);
// SubtensorModule::set_max_allowed_uids(netuid, 3);
// SubtensorModule::increase_stake_on_coldkey_hotkey_account(
// &U256::from(0),
// &U256::from(0),
// 10,
// );
// SubtensorModule::increase_stake_on_coldkey_hotkey_account(
// &U256::from(1),
// &U256::from(1),
// 10,
// );
// SubtensorModule::increase_stake_on_coldkey_hotkey_account(
// &U256::from(2),
// &U256::from(2),
// 10,
// );
// SubtensorModule::append_neuron(netuid, &U256::from(0), 0);
// SubtensorModule::append_neuron(netuid, &U256::from(1), 0);
// SubtensorModule::append_neuron(netuid, &U256::from(2), 0);
// SubtensorModule::set_validator_permit_for_uid(0, 0, true);
// SubtensorModule::set_validator_permit_for_uid(0, 1, true);
// SubtensorModule::set_validator_permit_for_uid(0, 2, true);
// assert_ok!(SubtensorModule::set_weights(
// RuntimeOrigin::signed(U256::from(0)),
// netuid,
// vec![0, 1, 2],
// vec![u16::MAX / 3, u16::MAX / 3, u16::MAX],
// 0
// ));
// assert_ok!(SubtensorModule::set_weights(
// RuntimeOrigin::signed(U256::from(1)),
// netuid,
// vec![1, 2],
// vec![u16::MAX / 2, u16::MAX / 2],
// 0
// ));
// assert_ok!(SubtensorModule::set_weights(
// RuntimeOrigin::signed(U256::from(2)),
// netuid,
// vec![2],
// vec![u16::MAX],
// 0
// ));
// SubtensorModule::epoch(0, u64::MAX);
// });
// }
// Test an epoch on an empty graph.
// #[test]
// fn test_nill_epoch_subtensor() {
// new_test_ext(1).execute_with(|| {
// log::info!("test_nill_epoch:");
// SubtensorModule::epoch(0, 0);
// });
// }
// Test an epoch on a graph with a single item.
#[test]
fn test_1_graph() {
new_test_ext(1).execute_with(|| {
log::info!("test_1_graph:");
let netuid: u16 = 1;
let coldkey = U256::from(0);
let hotkey = U256::from(0);
let uid: u16 = 0;
let stake_amount: u64 = 1;
add_network(netuid, u16::MAX - 1, 0); // set higher tempo to avoid built-in epoch, then manual epoch instead
SubtensorModule::set_max_allowed_uids(netuid, 1);
SubtensorModule::add_balance_to_coldkey_account(&coldkey, stake_amount);
SubtensorModule::increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake_amount);
SubtensorModule::append_neuron(netuid, &hotkey, 0);
assert_eq!(SubtensorModule::get_subnetwork_n(netuid), 1);
run_to_block(1); // run to next block to ensure weights are set on nodes after their registration block
assert_ok!(SubtensorModule::set_weights(
RuntimeOrigin::signed(U256::from(uid)),
netuid,
vec![uid],
vec![u16::MAX],
0
));
// SubtensorModule::set_weights_for_testing( netuid, i as u16, vec![ ( 0, u16::MAX )]); // doesn't set update status
// SubtensorModule::set_bonds_for_testing( netuid, uid, vec![ ( 0, u16::MAX )]); // rather, bonds are calculated in epoch
SubtensorModule::set_emission_values(&[netuid], vec![1_000_000_000]).unwrap();
assert_eq!(
SubtensorModule::get_subnet_emission_value(netuid),
1_000_000_000
);
SubtensorModule::epoch(netuid, 1_000_000_000);
assert_eq!(
SubtensorModule::get_total_stake_for_hotkey(&hotkey),
stake_amount
);
assert_eq!(SubtensorModule::get_rank_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_trust_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, uid), 0);
assert_eq!(
SubtensorModule::get_emission_for_uid(netuid, uid),
1_000_000_000
);
});
}
// Test an epoch on a graph with two items.
#[test]
fn test_10_graph() {
new_test_ext(1).execute_with(|| {
log::info!("test_10_graph");
// Function for adding a nodes to the graph.
pub fn add_node(netuid: u16, coldkey: U256, hotkey: U256, uid: u16, stake_amount: u64) {
log::info!(
"+Add net:{:?} coldkey:{:?} hotkey:{:?} uid:{:?} stake_amount: {:?} subn: {:?}",
netuid,
coldkey,
hotkey,
uid,
stake_amount,
SubtensorModule::get_subnetwork_n(netuid),
);
SubtensorModule::increase_stake_on_coldkey_hotkey_account(
&coldkey,
&hotkey,
stake_amount,
);
SubtensorModule::append_neuron(netuid, &hotkey, 0);
assert_eq!(SubtensorModule::get_subnetwork_n(netuid) - 1, uid);
}
// Build the graph with 10 items
// each with 1 stake and self weights.
let n: usize = 10;
let netuid: u16 = 1;
add_network(netuid, u16::MAX - 1, 0); // set higher tempo to avoid built-in epoch, then manual epoch instead
SubtensorModule::set_max_allowed_uids(netuid, n as u16);
for i in 0..10 {
add_node(netuid, U256::from(i), U256::from(i), i as u16, 1)
}
assert_eq!(SubtensorModule::get_subnetwork_n(netuid), 10);
run_to_block(1); // run to next block to ensure weights are set on nodes after their registration block
for i in 0..10 {
assert_ok!(SubtensorModule::set_weights(
RuntimeOrigin::signed(U256::from(i)),
netuid,
vec![i as u16],
vec![u16::MAX],
0
));
}
// Run the epoch.
SubtensorModule::epoch(netuid, 1_000_000_000);
// Check return values.
for i in 0..n {
assert_eq!(
SubtensorModule::get_total_stake_for_hotkey(&(U256::from(i))),
1
);
assert_eq!(SubtensorModule::get_rank_for_uid(netuid, i as u16), 0);
assert_eq!(SubtensorModule::get_trust_for_uid(netuid, i as u16), 0);
assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, i as u16), 0);
assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, i as u16), 0);
assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, i as u16), 0);
assert_eq!(
SubtensorModule::get_emission_for_uid(netuid, i as u16),
99999999
);
}
});
}
// Test an epoch on a graph with 512 nodes, of which the first 64 are validators setting non-self weights, and the rest servers setting only self-weights.
#[test]
fn test_512_graph() {
let netuid: u16 = 1;
let network_n: u16 = 512;
let validators_n: u16 = 64;
let max_stake_per_validator: u64 = 328_125_000_000_000; // 21_000_000_000_000_000 / 64
let epochs: u16 = 3;
log::info!("test_{network_n:?}_graph ({validators_n:?} validators)");
for interleave in 0..3 {
for server_self in [false, true] {
// server-self weight off/on
let (validators, servers) = distribute_nodes(
validators_n as usize,
network_n as usize,
interleave as usize,
);
let server: usize = servers[0] as usize;
let validator: usize = validators[0] as usize;
new_test_ext(1).execute_with(|| {
init_run_epochs(
netuid,
network_n,
&validators,
&servers,
epochs,
max_stake_per_validator,
server_self,
&[],
false,
&[],
false,
false,
0,
false,
);
let bonds = SubtensorModule::get_bonds(netuid);
for uid in validators {
assert_eq!(
SubtensorModule::get_total_stake_for_hotkey(&(U256::from(uid))),
max_stake_per_validator
);
assert_eq!(SubtensorModule::get_rank_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_trust_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, uid), 1023); // Note D = floor(1 / 64 * 65_535) = 1023
assert_eq!(SubtensorModule::get_emission_for_uid(netuid, uid), 7812500); // Note E = 0.5 / 200 * 1_000_000_000 = 7_812_500
assert_eq!(bonds[uid as usize][validator], 0.0);
assert_eq!(bonds[uid as usize][server], I32F32::from_num(65_535));
// Note B_ij = floor(1 / 64 * 65_535) / 65_535 = 1023 / 65_535, then max-upscaled to 65_535
}
for uid in servers {
assert_eq!(
SubtensorModule::get_total_stake_for_hotkey(&(U256::from(uid))),
0
);
assert_eq!(SubtensorModule::get_rank_for_uid(netuid, uid), 146); // Note R = floor(1 / (512 - 64) * 65_535) = 146
assert_eq!(SubtensorModule::get_trust_for_uid(netuid, uid), 65535);
assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, uid), 146); // Note C = floor(1 / (512 - 64) * 65_535) = 146
assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, uid), 146); // Note I = floor(1 / (512 - 64) * 65_535) = 146
assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_emission_for_uid(netuid, uid), 1116071); // Note E = floor(0.5 / (512 - 64) * 1_000_000_000) = 1_116_071
assert_eq!(bonds[uid as usize][validator], 0.0);
assert_eq!(bonds[uid as usize][server], 0.0);
}
});
}
}
}
// Test an epoch on a graph with 4096 nodes, of which the first 256 are validators setting random non-self weights, and the rest servers setting only self-weights.
#[test]
fn test_512_graph_random_weights() {
let netuid: u16 = 1;
let network_n: u16 = 512;
let validators_n: u16 = 64;
let epochs: u16 = 1;
log::info!("test_{network_n:?}_graph_random_weights ({validators_n:?} validators)");
for interleave in 0..3 {
for server_self in [false, true] {
// server-self weight off/on
let (validators, servers) = distribute_nodes(
validators_n as usize,
network_n as usize,
interleave as usize,
);
let server: usize = servers[0] as usize;
let validator: usize = validators[0] as usize;
#[allow(clippy::type_complexity)]
let (mut rank, mut incentive, mut dividend, mut emission, mut bondv, mut bonds): (
Vec<u16>,
Vec<u16>,
Vec<u16>,
Vec<u64>,
Vec<I32F32>,
Vec<I32F32>,
) = (vec![], vec![], vec![], vec![], vec![], vec![]);
// Dense epoch
new_test_ext(1).execute_with(|| {
init_run_epochs(
netuid,
network_n,
&validators,
&servers,
epochs,
1,
server_self,
&[],
false,
&[],
false,
true,
interleave as u64,
false,
);
let bond = SubtensorModule::get_bonds(netuid);
for uid in 0..network_n {
rank.push(SubtensorModule::get_rank_for_uid(netuid, uid));
incentive.push(SubtensorModule::get_incentive_for_uid(netuid, uid));
dividend.push(SubtensorModule::get_dividends_for_uid(netuid, uid));
emission.push(SubtensorModule::get_emission_for_uid(netuid, uid));
bondv.push(bond[uid as usize][validator]);
bonds.push(bond[uid as usize][server]);
}
});
// Sparse epoch (same random seed as dense)
new_test_ext(1).execute_with(|| {
init_run_epochs(
netuid,
network_n,
&validators,
&servers,
epochs,
1,
server_self,
&[],
false,
&[],
false,
true,
interleave as u64,
true,
);
// Assert that dense and sparse epoch results are equal
let bond = SubtensorModule::get_bonds(netuid);
for uid in 0..network_n {
assert_eq!(
SubtensorModule::get_rank_for_uid(netuid, uid),
rank[uid as usize]
);
assert_eq!(
SubtensorModule::get_incentive_for_uid(netuid, uid),
incentive[uid as usize]
);
assert_eq!(
SubtensorModule::get_dividends_for_uid(netuid, uid),
dividend[uid as usize]
);
assert_eq!(
SubtensorModule::get_emission_for_uid(netuid, uid),
emission[uid as usize]
);
assert_eq!(bond[uid as usize][validator], bondv[uid as usize]);
assert_eq!(bond[uid as usize][server], bonds[uid as usize]);
}
});
}
}
}
// Test an epoch on a graph with 4096 nodes, of which the first 256 are validators setting non-self weights, and the rest servers setting only self-weights.
// #[test]
#[allow(dead_code)]
fn test_4096_graph() {
let netuid: u16 = 1;
let network_n: u16 = 4096;
let validators_n: u16 = 256;
let epochs: u16 = 1;
let max_stake_per_validator: u64 = 82_031_250_000_000; // 21_000_000_000_000_000 / 256
log::info!("test_{network_n:?}_graph ({validators_n:?} validators)");
for interleave in 0..3 {
let (validators, servers) = distribute_nodes(
validators_n as usize,
network_n as usize,
interleave as usize,
);
let server: usize = servers[0] as usize;
let validator: usize = validators[0] as usize;
for server_self in [false, true] {
// server-self weight off/on
new_test_ext(1).execute_with(|| {
init_run_epochs(
netuid,
network_n,
&validators,
&servers,
epochs,
max_stake_per_validator,
server_self,
&[],
false,
&[],
false,
false,
0,
true,
);
assert_eq!(SubtensorModule::get_total_stake(), 21_000_000_000_000_000);
let bonds = SubtensorModule::get_bonds(netuid);
for uid in &validators {
assert_eq!(
SubtensorModule::get_total_stake_for_hotkey(&(U256::from(*uid as u64))),
max_stake_per_validator
);
assert_eq!(SubtensorModule::get_rank_for_uid(netuid, *uid), 0);
assert_eq!(SubtensorModule::get_trust_for_uid(netuid, *uid), 0);
assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, *uid), 0);
assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, *uid), 0);
assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, *uid), 255); // Note D = floor(1 / 256 * 65_535)
assert_eq!(SubtensorModule::get_emission_for_uid(netuid, *uid), 1953125); // Note E = 0.5 / 256 * 1_000_000_000 = 1953125
assert_eq!(bonds[*uid as usize][validator], 0.0);
assert_eq!(
bonds[*uid as usize][server],
I32F32::from_num(255) / I32F32::from_num(65_535)
); // Note B_ij = floor(1 / 256 * 65_535) / 65_535
}
for uid in &servers {
assert_eq!(
SubtensorModule::get_total_stake_for_hotkey(&(U256::from(*uid as u64))),
0
);
assert_eq!(SubtensorModule::get_rank_for_uid(netuid, *uid), 17); // Note R = floor(1 / (4096 - 256) * 65_535) = 17
assert_eq!(SubtensorModule::get_trust_for_uid(netuid, *uid), 65535);
assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, *uid), 17); // Note C = floor(1 / (4096 - 256) * 65_535) = 17
assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, *uid), 17); // Note I = floor(1 / (4096 - 256) * 65_535) = 17
assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, *uid), 0);
assert_eq!(SubtensorModule::get_emission_for_uid(netuid, *uid), 130208); // Note E = floor(0.5 / (4096 - 256) * 1_000_000_000) = 130208
assert_eq!(bonds[*uid as usize][validator], 0.0);
assert_eq!(bonds[*uid as usize][server], 0.0);
}
});
}
}
}
// Test an epoch_sparse on a graph with 16384 nodes, of which the first 512 are validators setting non-self weights, and the rest servers setting only self-weights.
// #[test]
#[allow(dead_code)]
fn test_16384_graph_sparse() {
new_test_ext(1).execute_with(|| {
let netuid: u16 = 1;
let n: u16 = 16384;
let validators_n: u16 = 512;
let validators: Vec<u16> = (0..validators_n).collect();
let servers: Vec<u16> = (validators_n..n).collect();
let server: u16 = servers[0];
let epochs: u16 = 1;
log::info!("test_{n:?}_graph ({validators_n:?} validators)");
init_run_epochs(
netuid,
n,
&validators,
&servers,
epochs,
1,
false,
&[],
false,
&[],
false,
false,
0,
true,
);
let bonds = SubtensorModule::get_bonds(netuid);
for uid in validators {
assert_eq!(
SubtensorModule::get_total_stake_for_hotkey(&(U256::from(uid))),
1
);
assert_eq!(SubtensorModule::get_rank_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_trust_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, uid), 438); // Note C = 0.0066928507 = (0.0066928507*65_535) = floor( 438.6159706245 )
assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, uid), 127); // Note D = floor(1 / 512 * 65_535) = 127
assert_eq!(SubtensorModule::get_emission_for_uid(netuid, uid), 976085); // Note E = 0.5 / 512 * 1_000_000_000 = 976_562 (discrepancy)
assert_eq!(bonds[uid as usize][0], 0.0);
assert_eq!(
bonds[uid as usize][server as usize],
I32F32::from_num(127) / I32F32::from_num(65_535)
); // Note B_ij = floor(1 / 512 * 65_535) / 65_535 = 127 / 65_535
}
for uid in servers {
assert_eq!(
SubtensorModule::get_total_stake_for_hotkey(&(U256::from(uid))),
0
);
assert_eq!(SubtensorModule::get_rank_for_uid(netuid, uid), 4); // Note R = floor(1 / (16384 - 512) * 65_535) = 4
assert_eq!(SubtensorModule::get_trust_for_uid(netuid, uid), 65535);
assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, uid), 4); // Note C = floor(1 / (16384 - 512) * 65_535) = 4
assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, uid), 4); // Note I = floor(1 / (16384 - 512) * 65_535) = 4
assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, uid), 0);
assert_eq!(SubtensorModule::get_emission_for_uid(netuid, uid), 31517); // Note E = floor(0.5 / (16384 - 512) * 1_000_000_000) = 31502 (discrepancy)
assert_eq!(bonds[uid as usize][0], 0.0);
assert_eq!(bonds[uid as usize][server as usize], 0.0);
}
});
}
// Test bonds exponential moving average over a sequence of epochs.
#[test]
fn test_bonds() {
new_test_ext(1).execute_with(|| {
let sparse: bool = true;
let n: u16 = 8;
let netuid: u16 = 1;
let tempo: u16 = u16::MAX - 1; // high tempo to skip automatic epochs in on_initialize, use manual epochs instead
let max_stake: u64 = 4;
let stakes: Vec<u64> = vec![1, 2, 3, 4, 0, 0, 0, 0];
let block_number = System::block_number();
add_network(netuid, tempo, 0);
SubtensorModule::set_max_allowed_uids( netuid, n );
assert_eq!(SubtensorModule::get_max_allowed_uids(netuid), n);
SubtensorModule::set_max_registrations_per_block( netuid, n );
SubtensorModule::set_target_registrations_per_interval(netuid, n);
SubtensorModule::set_weights_set_rate_limit( netuid, 0 );
SubtensorModule::set_min_allowed_weights( netuid, 1 );
SubtensorModule::set_max_weight_limit( netuid, u16::MAX );
// === Register [validator1, validator2, validator3, validator4, server1, server2, server3, server4]