-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathrun_epoch.rs
More file actions
1660 lines (1443 loc) · 66.7 KB
/
Copy pathrun_epoch.rs
File metadata and controls
1660 lines (1443 loc) · 66.7 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
use super::*;
use crate::epoch::math::*;
use alloc::collections::{BTreeMap, BTreeSet};
use frame_support::IterableStorageDoubleMap;
use safe_math::*;
use sp_runtime::PerU16;
use sp_std::collections::btree_map::IntoIter;
use sp_std::vec;
use substrate_fixed::types::{I32F32, I64F64, I96F32};
use subtensor_runtime_common::{AlphaBalance, MechId, NetUid, NetUidStorageIndex};
#[derive(Debug, Default)]
pub struct EpochTerms {
pub uid: usize,
pub dividend: u16,
pub incentive: u16,
pub validator_emission: AlphaBalance,
pub server_emission: AlphaBalance,
pub stake_weight: u16,
pub active: bool,
pub emission: AlphaBalance,
pub consensus: u16,
pub validator_trust: u16,
pub new_validator_permit: bool,
pub bond: Vec<(u16, u16)>,
pub stake: AlphaBalance,
}
pub struct EpochOutput<T: frame_system::Config>(pub BTreeMap<T::AccountId, EpochTerms>);
impl<T: frame_system::Config> EpochOutput<T> {
pub fn as_map(&self) -> &BTreeMap<T::AccountId, EpochTerms> {
&self.0
}
}
impl<T> IntoIterator for EpochOutput<T>
where
T: frame_system::Config,
T::AccountId: Ord,
{
type Item = (T::AccountId, EpochTerms);
type IntoIter = IntoIter<T::AccountId, EpochTerms>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
#[macro_export]
macro_rules! extract_from_sorted_terms {
($sorted:expr, $field:ident) => {{
($sorted)
.iter()
.copied()
.map(|t| t.$field)
.collect::<sp_std::vec::Vec<_>>()
}};
}
impl<T: Config> Pallet<T> {
/// Legacy epoch function interface (TODO: Is only used for tests, remove)
pub fn epoch(
netuid: NetUid,
rao_emission: AlphaBalance,
) -> Vec<(T::AccountId, AlphaBalance, AlphaBalance)> {
// Run mechanism-style epoch
let output = Self::epoch_mechanism(netuid, MechId::MAIN, rao_emission);
// Persist values in legacy format
Self::persist_mechanism_epoch_terms(netuid, MechId::MAIN, output.as_map());
Self::persist_netuid_epoch_terms(netuid, output.as_map());
// Remap and return
output
.into_iter()
.map(|(hotkey, terms)| (hotkey, terms.server_emission, terms.validator_emission))
.collect()
}
/// Legacy epoch_dense function interface (TODO: Is only used for tests, remove)
pub fn epoch_dense(
netuid: NetUid,
rao_emission: AlphaBalance,
) -> Vec<(T::AccountId, AlphaBalance, AlphaBalance)> {
Self::epoch_dense_mechanism(netuid, MechId::MAIN, rao_emission)
}
/// Persists per-mechanism epoch output in state
pub fn persist_mechanism_epoch_terms(
netuid: NetUid,
mecid: MechId,
output: &BTreeMap<T::AccountId, EpochTerms>,
) {
let netuid_index = Self::get_mechanism_storage_index(netuid, mecid);
let mut terms_sorted: sp_std::vec::Vec<&EpochTerms> = output.values().collect();
terms_sorted.sort_unstable_by_key(|t| t.uid);
let incentive = extract_from_sorted_terms!(terms_sorted, incentive);
let bonds: Vec<Vec<(u16, u16)>> = terms_sorted
.iter()
.cloned()
.map(|t| t.bond.clone())
.collect::<sp_std::vec::Vec<_>>();
// Epoch math stays in raw u16; wrap into PerU16 only at the storage boundary.
let incentive: Vec<PerU16> = incentive.into_iter().map(PerU16::from_parts).collect();
Incentive::<T>::insert(netuid_index, incentive);
let server_emission = extract_from_sorted_terms!(terms_sorted, server_emission);
Self::deposit_event(Event::IncentiveAlphaEmittedToMiners {
netuid: netuid_index,
emissions: server_emission,
});
bonds
.into_iter()
.enumerate()
.for_each(|(uid_usize, bond_vec)| {
let uid: u16 = uid_usize.try_into().unwrap_or_default();
Bonds::<T>::insert(netuid_index, uid, bond_vec);
});
}
/// Persists per-netuid epoch output in state
pub fn persist_netuid_epoch_terms(netuid: NetUid, output: &BTreeMap<T::AccountId, EpochTerms>) {
let mut terms_sorted: sp_std::vec::Vec<&EpochTerms> = output.values().collect();
terms_sorted.sort_unstable_by_key(|t| t.uid);
let active = extract_from_sorted_terms!(terms_sorted, active);
let emission = extract_from_sorted_terms!(terms_sorted, emission);
let consensus = extract_from_sorted_terms!(terms_sorted, consensus);
let dividend = extract_from_sorted_terms!(terms_sorted, dividend);
let validator_trust = extract_from_sorted_terms!(terms_sorted, validator_trust);
let new_validator_permit = extract_from_sorted_terms!(terms_sorted, new_validator_permit);
let stake_weight = extract_from_sorted_terms!(terms_sorted, stake_weight);
// Epoch math stays in raw u16; wrap into PerU16 only at the storage boundary.
let consensus: Vec<PerU16> = consensus.into_iter().map(PerU16::from_parts).collect();
let dividend: Vec<PerU16> = dividend.into_iter().map(PerU16::from_parts).collect();
let validator_trust: Vec<PerU16> = validator_trust
.into_iter()
.map(PerU16::from_parts)
.collect();
Active::<T>::insert(netuid, active.clone());
Emission::<T>::insert(netuid, emission);
Consensus::<T>::insert(netuid, consensus);
Dividends::<T>::insert(netuid, dividend);
ValidatorTrust::<T>::insert(netuid, validator_trust);
ValidatorPermit::<T>::insert(netuid, new_validator_permit);
StakeWeight::<T>::insert(netuid, stake_weight);
}
/// Calculates reward consensus and returns the emissions for uids/hotkeys in a given `netuid`.
/// (Dense version used only for testing purposes.)
#[allow(clippy::indexing_slicing)]
pub fn epoch_dense_mechanism(
netuid: NetUid,
mecid: MechId,
rao_emission: AlphaBalance,
) -> Vec<(T::AccountId, AlphaBalance, AlphaBalance)> {
// Calculate netuid storage index
let netuid_index = Self::get_mechanism_storage_index(netuid, mecid);
// Get subnetwork size.
let n: u16 = Self::get_subnetwork_n(netuid);
log::trace!("n: {n:?}");
// ======================
// == Active & updated ==
// ======================
// Get current block.
let current_block: u64 = Self::get_current_block_as_u64();
log::trace!("current_block: {current_block:?}");
// Get tempo.
let tempo: u64 = Self::get_tempo(netuid).into();
log::trace!("tempo: {tempo:?}");
// Get activity cutoff.
let activity_cutoff: u64 = Self::get_activity_cutoff_blocks(netuid);
log::trace!("activity_cutoff: {activity_cutoff:?}");
// Last update vector.
let last_update: Vec<u64> = Self::get_last_update(netuid_index);
log::trace!("Last update: {:?}", &last_update);
// Inactive mask.
let inactive: Vec<bool> = last_update
.iter()
.map(|updated| updated.saturating_add(activity_cutoff) < current_block)
.collect();
log::trace!("Inactive: {:?}", inactive.clone());
// Logical negation of inactive.
let active: Vec<bool> = inactive.iter().map(|&b| !b).collect();
// Block at registration vector (block when each neuron was most recently registered).
let block_at_registration: Vec<u64> = Self::get_block_at_registration(netuid);
log::trace!("Block at registration: {:?}", &block_at_registration);
// Outdated matrix, outdated_ij=True if i has last updated (weights) after j has last registered.
let outdated: Vec<Vec<bool>> = last_update
.iter()
.map(|updated| {
block_at_registration
.iter()
.map(|registered| updated <= registered)
.collect()
})
.collect();
log::trace!("Outdated: {:?}", &outdated);
// Recently registered matrix, recently_ij=True if last_tempo was *before* j was last registered.
// Mask if: the last tempo block happened *before* the registration block
// ==> last_tempo <= registered
// For dynamic tempo - we pick previous-successful-epoch block: `LastMechansimStepBlock + 1`
let lms = LastMechansimStepBlock::<T>::get(netuid);
let last_tempo: u64 = if lms == 0 {
current_block.saturating_sub(tempo)
} else {
lms.saturating_add(1)
};
let recently_registered: Vec<bool> = block_at_registration
.iter()
.map(|registered| last_tempo <= *registered)
.collect();
log::trace!("Recently registered: {:?}", &recently_registered);
// ===========
// == Stake ==
// ===========
let hotkeys: Vec<(u16, T::AccountId)> =
<Keys<T> as IterableStorageDoubleMap<NetUid, u16, T::AccountId>>::iter_prefix(netuid)
.collect();
log::trace!("hotkeys: {:?}", &hotkeys);
// Access network stake as normalized vector.
let (total_stake, _alpha_stake, _tao_stake): (Vec<I64F64>, Vec<I64F64>, Vec<I64F64>) =
Self::get_stake_weights_for_network(netuid);
// Get the minimum stake required.
let min_stake = Self::get_stake_threshold();
// Set stake of validators that doesn't meet the staking threshold to 0 as filter.
let mut filtered_stake: Vec<I64F64> = total_stake
.iter()
.map(|&s| {
if fixed64_to_u64(s) < min_stake {
return I64F64::from(0);
}
s
})
.collect();
log::debug!("Filtered stake: {:?}", &filtered_stake);
inplace_normalize_64(&mut filtered_stake);
let stake: Vec<I32F32> = vec_fixed64_to_fixed32(filtered_stake);
log::trace!("S: {:?}", &stake);
// =======================
// == Validator permits ==
// =======================
// Get validator permits.
let validator_permits: Vec<bool> = Self::get_validator_permit(netuid);
log::trace!("validator_permits: {validator_permits:?}");
// Logical negation of validator_permits.
let validator_forbids: Vec<bool> = validator_permits.iter().map(|&b| !b).collect();
// Get max allowed validators.
let max_allowed_validators: u16 = Self::get_max_allowed_validators(netuid);
log::trace!("max_allowed_validators: {max_allowed_validators:?}");
// Get new validator permits.
let new_validator_permits: Vec<bool> =
is_topk_nonzero(&stake, max_allowed_validators as usize);
log::trace!("new_validator_permits: {new_validator_permits:?}");
// ==================
// == Active Stake ==
// ==================
let mut active_stake: Vec<I32F32> = stake.clone();
// Remove inactive stake.
inplace_mask_vector(&inactive, &mut active_stake);
// Remove non-validator stake.
inplace_mask_vector(&validator_forbids, &mut active_stake);
// Normalize active stake.
inplace_normalize(&mut active_stake);
log::trace!("S: {:?}", &active_stake);
// =============
// == Weights ==
// =============
// Get owner uid.
let owner_uid: Option<u16> = Self::get_owner_uid(netuid);
// Access network weights row unnormalized.
let mut weights: Vec<Vec<I32F32>> = Self::get_weights(netuid_index);
log::trace!("W: {:?}", &weights);
// Mask weights that are not from permitted validators.
inplace_mask_rows(&validator_forbids, &mut weights);
log::trace!("W (permit): {:?}", &weights);
// Remove self-weight by masking diagonal; keep owner_uid self-weight.
if let Some(owner_uid) = owner_uid {
inplace_mask_diag_except_index(&mut weights, owner_uid);
} else {
inplace_mask_diag(&mut weights);
}
inplace_mask_diag(&mut weights);
log::trace!("W (permit+diag): {:?}", &weights);
// Mask outdated weights: remove weights referring to deregistered neurons.
inplace_mask_matrix(&outdated, &mut weights);
log::trace!("W (permit+diag+outdate): {:?}", &weights);
// Normalize remaining weights.
inplace_row_normalize(&mut weights);
log::trace!("W (mask+norm): {:?}", &weights);
// ================================
// == Consensus, Validator Trust ==
// ================================
// Consensus majority ratio, e.g. 51%.
let kappa: I32F32 = Self::get_float_kappa(netuid);
// Calculate consensus as stake-weighted median of weights.
let consensus: Vec<I32F32> = weighted_median_col(&active_stake, &weights, kappa);
// Clip weights at majority consensus.
let mut clipped_weights: Vec<Vec<I32F32>> = weights.clone();
inplace_col_clip(&mut clipped_weights, &consensus);
// Calculate validator trust as sum of clipped weights set by validator.
let validator_trust: Vec<I32F32> = row_sum(&clipped_weights);
// ====================================
// == Ranks, Server Trust, Incentive ==
// ====================================
// Compute ranks: r_j = SUM(i) w_ij * s_i
let mut ranks: Vec<I32F32> = matmul(&clipped_weights, &active_stake);
inplace_normalize(&mut ranks);
let incentive: Vec<I32F32> = ranks.clone();
log::trace!("I: {:?}", &incentive);
// =========================
// == Bonds and Dividends ==
// =========================
// Get validator bonds penalty in [0, 1].
let bonds_penalty: I32F32 = Self::get_float_bonds_penalty(netuid);
// Calculate weights for bonds, apply bonds penalty to weights.
// bonds_penalty = 0: weights_for_bonds = weights.clone()
// bonds_penalty = 1: weights_for_bonds = clipped_weights.clone()
let weights_for_bonds: Vec<Vec<I32F32>> =
interpolate(&weights, &clipped_weights, bonds_penalty);
let mut dividends: Vec<I32F32>;
let mut ema_bonds: Vec<Vec<I32F32>>;
if Yuma3On::<T>::get(netuid) {
// Access network bonds.
let mut bonds: Vec<Vec<I32F32>> = Self::get_bonds_fixed_proportion(netuid_index);
inplace_mask_cols(&recently_registered, &mut bonds); // mask outdated bonds
log::trace!("B: {:?}", &bonds);
// Compute the Exponential Moving Average (EMA) of bonds.
ema_bonds = Self::compute_bonds(netuid, &weights_for_bonds, &bonds, &consensus);
log::trace!("emaB: {:?}", &ema_bonds);
// Normalize EMA bonds.
let mut ema_bonds_norm = ema_bonds.clone();
inplace_col_normalize(&mut ema_bonds_norm);
log::trace!("emaB norm: {:?}", &ema_bonds_norm);
// # === Dividend Calculation===
let total_bonds_per_validator: Vec<I32F32> =
row_sum(&mat_vec_mul(&ema_bonds_norm, &incentive));
log::trace!(
"total_bonds_per_validator: {:?}",
&total_bonds_per_validator
);
dividends = vec_mul(&total_bonds_per_validator, &active_stake);
inplace_normalize(&mut dividends);
log::trace!("D: {:?}", ÷nds);
} else {
// original Yuma - liquid alpha disabled
// Access network bonds.
let mut bonds: Vec<Vec<I32F32>> = Self::get_bonds(netuid_index);
// Remove bonds referring to neurons that have registered since last tempo.
inplace_mask_cols(&recently_registered, &mut bonds); // mask recently registered bonds
inplace_col_normalize(&mut bonds); // sum_i b_ij = 1
log::trace!("B: {:?}", &bonds);
// Compute bonds delta column normalized.
let mut bonds_delta: Vec<Vec<I32F32>> = row_hadamard(&weights_for_bonds, &active_stake); // ΔB = W◦S
inplace_col_normalize(&mut bonds_delta); // sum_i b_ij = 1
log::trace!("ΔB: {:?}", &bonds_delta);
// Compute the Exponential Moving Average (EMA) of bonds.
ema_bonds = Self::compute_ema_bonds_normal(&bonds_delta, &bonds, netuid);
inplace_col_normalize(&mut ema_bonds); // sum_i b_ij = 1
log::trace!("emaB: {:?}", &ema_bonds);
// Compute dividends: d_i = SUM(j) b_ij * inc_j
dividends = matmul_transpose(&ema_bonds, &incentive);
inplace_normalize(&mut dividends);
log::trace!("Dividends: {:?}", ÷nds);
// Column max-upscale EMA bonds for storage: max_i w_ij = 1.
inplace_col_max_upscale(&mut ema_bonds);
}
// =================================
// == Emission and Pruning scores ==
// =================================
// Compute emission scores.
// Compute normalized emission scores. range: I32F32(0, 1)
// Compute normalized emission scores. range: I32F32(0, 1)
let combined_emission: Vec<I32F32> = incentive
.iter()
.zip(dividends.clone())
.map(|(ii, di)| ii.saturating_add(di))
.collect();
let emission_sum: I32F32 = combined_emission.iter().sum();
let mut normalized_server_emission: Vec<I32F32> = incentive.clone(); // Servers get incentive.
let mut normalized_validator_emission: Vec<I32F32> = dividends.clone(); // Validators get dividends.
let mut normalized_combined_emission: Vec<I32F32> = combined_emission.clone();
// Normalize on the sum of incentive + dividends.
inplace_normalize_using_sum(&mut normalized_server_emission, emission_sum);
inplace_normalize_using_sum(&mut normalized_validator_emission, emission_sum);
inplace_normalize(&mut normalized_combined_emission);
// If emission is zero, replace emission with normalized stake.
if emission_sum == I32F32::from(0) {
// no weights set | outdated weights | self_weights
if is_zero(&active_stake) {
// no active stake
normalized_validator_emission.clone_from(&stake); // do not mask inactive, assumes stake is normalized
normalized_combined_emission.clone_from(&stake);
} else {
normalized_validator_emission.clone_from(&active_stake); // emission proportional to inactive-masked normalized stake
normalized_combined_emission.clone_from(&active_stake);
}
}
// Compute rao based emission scores. range: I96F32(0, rao_emission)
let float_rao_emission: I96F32 = I96F32::saturating_from_num(rao_emission);
let server_emission: Vec<I96F32> = normalized_server_emission
.iter()
.map(|se: &I32F32| I96F32::saturating_from_num(*se).saturating_mul(float_rao_emission))
.collect();
let server_emission: Vec<AlphaBalance> = server_emission
.iter()
.map(|e: &I96F32| e.saturating_to_num::<u64>().into())
.collect();
let validator_emission: Vec<I96F32> = normalized_validator_emission
.iter()
.map(|ve: &I32F32| I96F32::saturating_from_num(*ve).saturating_mul(float_rao_emission))
.collect();
let validator_emission: Vec<AlphaBalance> = validator_emission
.iter()
.map(|e: &I96F32| e.saturating_to_num::<u64>().into())
.collect();
// Used only to track combined emission in the storage.
let combined_emission: Vec<I96F32> = normalized_combined_emission
.iter()
.map(|ce: &I32F32| I96F32::saturating_from_num(*ce).saturating_mul(float_rao_emission))
.collect();
let combined_emission: Vec<AlphaBalance> = combined_emission
.iter()
.map(|e: &I96F32| AlphaBalance::from(e.saturating_to_num::<u64>()))
.collect();
log::trace!("nSE: {:?}", &normalized_server_emission);
log::trace!("SE: {:?}", &server_emission);
log::trace!("nVE: {:?}", &normalized_validator_emission);
log::trace!("VE: {:?}", &validator_emission);
log::trace!("nCE: {:?}", &normalized_combined_emission);
log::trace!("CE: {:?}", &combined_emission);
// ===================
// == Value storage ==
// ===================
let cloned_emission = combined_emission.clone();
let cloned_stake_weight: Vec<u16> = stake
.iter()
.map(|xi| fixed_proportion_to_u16(*xi))
.collect::<Vec<u16>>();
let cloned_consensus: Vec<u16> = consensus
.iter()
.map(|xi| fixed_proportion_to_u16(*xi))
.collect::<Vec<u16>>();
let cloned_incentive: Vec<u16> = incentive
.iter()
.map(|xi| fixed_proportion_to_u16(*xi))
.collect::<Vec<u16>>();
let cloned_dividends: Vec<u16> = dividends
.iter()
.map(|xi| fixed_proportion_to_u16(*xi))
.collect::<Vec<u16>>();
let cloned_validator_trust: Vec<u16> = validator_trust
.iter()
.map(|xi| fixed_proportion_to_u16(*xi))
.collect::<Vec<u16>>();
StakeWeight::<T>::insert(netuid, cloned_stake_weight.clone());
Active::<T>::insert(netuid, active.clone());
Emission::<T>::insert(netuid, cloned_emission);
// Epoch math stays in raw u16; wrap into PerU16 only at the storage boundary.
Consensus::<T>::insert(
netuid,
cloned_consensus
.into_iter()
.map(PerU16::from_parts)
.collect::<Vec<PerU16>>(),
);
Incentive::<T>::insert(
NetUidStorageIndex::from(netuid),
cloned_incentive
.into_iter()
.map(PerU16::from_parts)
.collect::<Vec<PerU16>>(),
);
Dividends::<T>::insert(
netuid,
cloned_dividends
.into_iter()
.map(PerU16::from_parts)
.collect::<Vec<PerU16>>(),
);
ValidatorTrust::<T>::insert(
netuid,
cloned_validator_trust
.into_iter()
.map(PerU16::from_parts)
.collect::<Vec<PerU16>>(),
);
ValidatorPermit::<T>::insert(netuid, new_validator_permits.clone());
new_validator_permits
.iter()
.zip(validator_permits)
.zip(ema_bonds)
.enumerate()
.for_each(|(i, ((new_permit, validator_permit), ema_bond))| {
// Set bonds only if uid retains validator permit, otherwise clear bonds.
if *new_permit {
let new_bonds_row: Vec<(u16, u16)> = (0..n)
.zip(vec_fixed_proportions_to_u16(ema_bond.clone()))
.collect();
Bonds::<T>::insert(netuid_index, i as u16, new_bonds_row);
} else if validator_permit {
// Only overwrite the intersection.
let new_empty_bonds_row: Vec<(u16, u16)> = vec![];
Bonds::<T>::insert(netuid_index, i as u16, new_empty_bonds_row);
}
});
hotkeys
.into_iter()
.map(|(uid_i, hotkey)| {
(
hotkey,
server_emission[uid_i as usize],
validator_emission[uid_i as usize],
)
})
.collect()
}
/// Calculates reward consensus values, then updates rank, trust, consensus, incentive, dividend, pruning_score, emission and bonds, and
/// returns the emissions for uids/hotkeys in a given `netuid`.
///
/// # Arguments
/// * `netuid`: The network to distribute the emission onto.
///
/// * `rao_emission`: The total emission for the epoch.
///
/// * `debug`: Print debugging outputs.
///
pub fn epoch_mechanism(
netuid: NetUid,
mecid: MechId,
rao_emission: AlphaBalance,
) -> EpochOutput<T> {
// Calculate netuid storage index
let netuid_index = Self::get_mechanism_storage_index(netuid, mecid);
// Initialize output keys (neuron hotkeys) and UIDs
let mut terms_map: BTreeMap<T::AccountId, EpochTerms> = Keys::<T>::iter_prefix(netuid)
.map(|(uid, hotkey)| {
(
hotkey,
EpochTerms {
uid: uid as usize,
..Default::default()
},
)
})
.collect();
// Get subnetwork size.
let n = Self::get_subnetwork_n(netuid);
log::trace!("Number of Neurons in Network: {n:?}");
// ======================
// == Active & updated ==
// ======================
// Get current block.
let current_block: u64 = Self::get_current_block_as_u64();
log::trace!("current_block: {current_block:?}");
// Get tempo.
let tempo: u64 = Self::get_tempo(netuid).into();
log::trace!("tempo:\n{tempo:?}\n");
// Get activity cutoff.
let activity_cutoff: u64 = Self::get_activity_cutoff_blocks(netuid);
log::trace!("activity_cutoff: {activity_cutoff:?}");
// Last update vector.
let last_update: Vec<u64> = Self::get_last_update(netuid_index);
log::trace!("Last update: {:?}", &last_update);
// Inactive mask.
let inactive: Vec<bool> = last_update
.iter()
.map(|updated| updated.saturating_add(activity_cutoff) < current_block)
.collect();
log::debug!("Inactive: {:?}", inactive.clone());
// Logical negation of inactive.
let active: Vec<bool> = inactive.iter().map(|&b| !b).collect();
// Block at registration vector (block when each neuron was most recently registered).
let block_at_registration: Vec<u64> = Self::get_block_at_registration(netuid);
log::trace!("Block at registration: {:?}", &block_at_registration);
// ===========
// == Stake ==
// ===========
// Access network stake as normalized vector.
let (total_stake, _alpha_stake, _tao_stake): (Vec<I64F64>, Vec<I64F64>, Vec<I64F64>) =
Self::get_stake_weights_for_network(netuid);
// Get the minimum stake required.
let min_stake = Self::get_stake_threshold();
// Get owner uid.
let owner_uid: Option<u16> = Self::get_owner_uid(netuid);
// Set stake of validators that doesn't meet the staking threshold to 0 as filter.
let mut filtered_stake: Vec<I64F64> = total_stake
.iter()
.enumerate()
.map(|(uid, &s)| {
if owner_uid != Some(uid as u16) && fixed64_to_u64(s) < min_stake {
return I64F64::from(0);
}
s
})
.collect();
log::debug!("Filtered stake: {:?}", &filtered_stake);
inplace_normalize_64(&mut filtered_stake);
let stake: Vec<I32F32> = vec_fixed64_to_fixed32(filtered_stake);
log::debug!("Normalised Stake: {:?}", &stake);
// =======================
// == Validator permits ==
// =======================
// Get current validator permits.
let mut validator_permits: Vec<bool> = Self::get_validator_permit(netuid);
if let Some(owner_uid) = owner_uid
&& let Some(owner_permit) = validator_permits.get_mut(owner_uid as usize)
{
*owner_permit = true;
}
log::trace!("validator_permits: {validator_permits:?}");
// Logical negation of validator_permits.
let validator_forbids: Vec<bool> = validator_permits.iter().map(|&b| !b).collect();
// Get max allowed validators.
let max_allowed_validators: u16 = Self::get_max_allowed_validators(netuid);
log::trace!("max_allowed_validators: {max_allowed_validators:?}");
// Get new validator permits.
let mut new_validator_permits: Vec<bool> =
is_topk_nonzero(&stake, max_allowed_validators as usize);
if let Some(owner_uid) = owner_uid
&& let Some(owner_permit) = new_validator_permits.get_mut(owner_uid as usize)
{
*owner_permit = true;
}
log::trace!("new_validator_permits: {new_validator_permits:?}");
// ==================
// == Active Stake ==
// ==================
let mut active_stake: Vec<I32F32> = stake.clone();
// Remove inactive stake.
inplace_mask_vector(&inactive, &mut active_stake);
// Remove non-validator stake.
inplace_mask_vector(&validator_forbids, &mut active_stake);
// Normalize active stake.
inplace_normalize(&mut active_stake);
log::trace!("Active Stake: {:?}", &active_stake);
// =============
// == Weights ==
// =============
// Access network weights row unnormalized.
let mut weights: Vec<Vec<(u16, I32F32)>> = Self::get_weights_sparse(netuid_index);
log::trace!("Weights: {:?}", &weights);
// Mask weights that are not from permitted validators.
weights = mask_rows_sparse(&validator_forbids, &weights);
log::trace!("Weights (permit): {:?}", &weights);
// Remove self-weight by masking diagonal; keep owner_uid self-weight.
if let Some(owner_uid) = owner_uid {
weights = mask_diag_sparse_except_index(&weights, owner_uid);
} else {
weights = mask_diag_sparse(&weights);
}
log::trace!("Weights (permit+diag): {:?}", &weights);
// Remove weights referring to deregistered neurons.
weights = vec_mask_sparse_matrix(
&weights,
&last_update,
&block_at_registration,
&|updated, registered| updated <= registered,
);
log::trace!("Weights (permit+diag+outdate): {:?}", &weights);
if Self::get_commit_reveal_weights_enabled(netuid) {
let mut commit_blocks: Vec<u64> = vec![u64::MAX; n as usize]; // MAX ⇒ “no active commit”
// helper: hotkey → uid
let uid_of = |acct: &T::AccountId| terms_map.get(acct).map(|t| t.uid);
// ---------- v2 ------------------------------------------------------
// `WeightCommits` tuple: (hash, commit_epoch, commit_block, _).
// Expiry keys off `commit_epoch`; the column mask compares the absolute
// `commit_block` against `block_at_registration` (both block numbers).
for (who, q) in WeightCommits::<T>::iter_prefix(netuid_index) {
for (_, commit_epoch, commit_block, _) in q.iter() {
if !Self::is_commit_expired(netuid, *commit_epoch) {
if let Some(cell) = uid_of(&who).and_then(|i| commit_blocks.get_mut(i)) {
*cell = (*cell).min(*commit_block);
}
break; // earliest active found
}
}
}
// ---------- v4 ------------------------------------------------------
// `TimelockedWeightCommits` is keyed by `commit_epoch`; the value tuple
// carries the absolute `commit_block` in field 1.
for (commit_epoch, q) in TimelockedWeightCommits::<T>::iter_prefix(netuid_index) {
if Self::is_commit_expired(netuid, commit_epoch) {
continue;
}
for (who, commit_block, ..) in q.iter() {
if let Some(cell) = uid_of(who).and_then(|i| commit_blocks.get_mut(i)) {
*cell = (*cell).min(*commit_block);
}
}
}
weights = vec_mask_sparse_matrix(
&weights,
&commit_blocks,
&block_at_registration,
&|cb, reg| cb < reg,
);
log::trace!(
"Commit-reveal column mask applied ({} masked rows)",
commit_blocks.iter().filter(|&&cb| cb != u64::MAX).count()
);
}
// Normalize remaining weights.
inplace_row_normalize_sparse(&mut weights);
log::trace!("Weights (mask+norm): {:?}", &weights);
// ================================
// == Consensus, Validator Trust ==
// ================================
// Consensus majority ratio, e.g. 51%.
let kappa: I32F32 = Self::get_float_kappa(netuid);
// Calculate consensus as stake-weighted median of weights.
let consensus: Vec<I32F32> = weighted_median_col_sparse(&active_stake, &weights, n, kappa);
log::trace!("Consensus: {:?}", &consensus);
// Clip weights at majority consensus.
let clipped_weights: Vec<Vec<(u16, I32F32)>> = col_clip_sparse(&weights, &consensus);
log::trace!("Clipped Weights: {:?}", &clipped_weights);
// Calculate validator trust as sum of clipped weights set by validator.
let validator_trust: Vec<I32F32> = row_sum_sparse(&clipped_weights);
log::trace!("Validator Trust: {:?}", &validator_trust);
// =============================
// == Ranks, Trust, Incentive ==
// =============================
// Compute ranks: r_j = SUM(i) w_ij * s_i.
let mut ranks: Vec<I32F32> = matmul_sparse(&clipped_weights, &active_stake, n);
inplace_normalize(&mut ranks); // range: I32F32(0, 1)
let incentive: Vec<I32F32> = ranks.clone();
log::trace!("Incentive (=Rank): {:?}", &incentive);
// =========================
// == Bonds and Dividends ==
// =========================
// Get validator bonds penalty in [0, 1].
let bonds_penalty: I32F32 = Self::get_float_bonds_penalty(netuid);
// Calculate weights for bonds, apply bonds penalty to weights.
// bonds_penalty = 0: weights_for_bonds = weights.clone()
// bonds_penalty = 1: weights_for_bonds = clipped_weights.clone()
let weights_for_bonds: Vec<Vec<(u16, I32F32)>> =
interpolate_sparse(&weights, &clipped_weights, n, bonds_penalty);
let mut dividends: Vec<I32F32>;
let mut ema_bonds: Vec<Vec<(u16, I32F32)>>;
if Yuma3On::<T>::get(netuid) {
// Access network bonds.
let mut bonds = Self::get_bonds_sparse_fixed_proportion(netuid_index);
log::trace!("Bonds: {:?}", &bonds);
// Remove bonds referring to neurons that have registered since last tempo.
// Mask if: the last tempo block happened *before* the registration block
// ==> last_tempo <= registered
// For dynamic tempo - we pick previous-successful-epoch block: `LastMechansimStepBlock + 1`
let lms = LastMechansimStepBlock::<T>::get(netuid);
let last_tempo: u64 = if lms == 0 {
current_block.saturating_sub(tempo)
} else {
lms.saturating_add(1)
};
bonds = scalar_vec_mask_sparse_matrix(
&bonds,
last_tempo,
&block_at_registration,
&|last_tempo, registered| last_tempo <= registered,
);
log::trace!("Bonds: (mask) {:?}", &bonds);
// Compute the Exponential Moving Average (EMA) of bonds.
log::trace!("weights_for_bonds: {:?}", &weights_for_bonds);
ema_bonds =
Self::compute_bonds_sparse(netuid_index, &weights_for_bonds, &bonds, &consensus);
log::trace!("emaB: {:?}", &ema_bonds);
// Normalize EMA bonds.
let mut ema_bonds_norm = ema_bonds.clone();
inplace_col_normalize_sparse(&mut ema_bonds_norm, n); // sum_i b_ij = 1
log::trace!("emaB norm: {:?}", &ema_bonds_norm);
// # === Dividend Calculation===
let total_bonds_per_validator: Vec<I32F32> =
row_sum_sparse(&mat_vec_mul_sparse(&ema_bonds_norm, &incentive));
log::trace!(
"total_bonds_per_validator: {:?}",
&total_bonds_per_validator
);
dividends = vec_mul(&total_bonds_per_validator, &active_stake);
inplace_normalize(&mut dividends);
log::trace!("Dividends: {:?}", ÷nds);
} else {
// original Yuma - liquid alpha disabled
// Access network bonds.
let mut bonds: Vec<Vec<(u16, I32F32)>> = Self::get_bonds_sparse(netuid_index);
log::trace!("B: {:?}", &bonds);
// Remove bonds referring to neurons that have registered since last tempo.
// Mask if: the last tempo block happened *before* the registration block
// ==> last_tempo <= registered
// For dynamic tempo - we pick previous-successful-epoch block: `LastMechansimStepBlock + 1`
let lms = LastMechansimStepBlock::<T>::get(netuid);
let last_tempo: u64 = if lms == 0 {
current_block.saturating_sub(tempo)
} else {
lms.saturating_add(1)
};
bonds = scalar_vec_mask_sparse_matrix(
&bonds,
last_tempo,
&block_at_registration,
&|last_tempo, registered| last_tempo <= registered,
);
log::trace!("B (outdatedmask): {:?}", &bonds);
// Normalize remaining bonds: sum_i b_ij = 1.
inplace_col_normalize_sparse(&mut bonds, n);
log::trace!("B (mask+norm): {:?}", &bonds);
// Compute bonds delta column normalized.
let mut bonds_delta: Vec<Vec<(u16, I32F32)>> =
row_hadamard_sparse(&weights_for_bonds, &active_stake); // ΔB = W◦S (outdated W masked)
log::trace!("ΔB: {:?}", &bonds_delta);
// Normalize bonds delta.
inplace_col_normalize_sparse(&mut bonds_delta, n); // sum_i b_ij = 1
log::trace!("ΔB (norm): {:?}", &bonds_delta);
// Compute the Exponential Moving Average (EMA) of bonds.
ema_bonds = Self::compute_ema_bonds_normal_sparse(&bonds_delta, &bonds, netuid_index);
// Normalize EMA bonds.
inplace_col_normalize_sparse(&mut ema_bonds, n); // sum_i b_ij = 1
log::trace!("Exponential Moving Average Bonds: {:?}", &ema_bonds);
// Compute dividends: d_i = SUM(j) b_ij * inc_j.
// range: I32F32(0, 1)
dividends = matmul_transpose_sparse(&ema_bonds, &incentive);
inplace_normalize(&mut dividends);
log::trace!("Dividends: {:?}", ÷nds);
// Column max-upscale EMA bonds for storage: max_i w_ij = 1.
inplace_col_max_upscale_sparse(&mut ema_bonds, n);
}
// =================================
// == Emission and Pruning scores ==
// =================================
// Compute normalized emission scores. range: I32F32(0, 1)
let combined_emission: Vec<I32F32> = incentive
.iter()
.zip(dividends.clone())
.map(|(ii, di)| ii.saturating_add(di))
.collect();
let emission_sum: I32F32 = combined_emission.iter().sum();
let mut normalized_server_emission: Vec<I32F32> = incentive.clone(); // Servers get incentive.
let mut normalized_validator_emission: Vec<I32F32> = dividends.clone(); // Validators get dividends.
let mut normalized_combined_emission: Vec<I32F32> = combined_emission.clone();
// Normalize on the sum of incentive + dividends.
inplace_normalize_using_sum(&mut normalized_server_emission, emission_sum);
inplace_normalize_using_sum(&mut normalized_validator_emission, emission_sum);
inplace_normalize(&mut normalized_combined_emission);
// If emission is zero, replace emission with normalized stake.
if emission_sum == I32F32::from(0) {
// no weights set | outdated weights | self_weights
if is_zero(&active_stake) {
// no active stake
normalized_validator_emission.clone_from(&stake); // do not mask inactive, assumes stake is normalized
normalized_combined_emission.clone_from(&stake);
} else {
normalized_validator_emission.clone_from(&active_stake); // emission proportional to inactive-masked normalized stake
normalized_combined_emission.clone_from(&active_stake);
}
}
// Compute rao based emission scores. range: I96F32(0, rao_emission)
let float_rao_emission: I96F32 = I96F32::saturating_from_num(rao_emission);
let server_emission: Vec<I96F32> = normalized_server_emission
.iter()
.map(|se: &I32F32| I96F32::saturating_from_num(*se).saturating_mul(float_rao_emission))
.collect();
let server_emission: Vec<AlphaBalance> = server_emission
.iter()
.map(|e: &I96F32| e.saturating_to_num::<u64>().into())
.collect();