Skip to content

Commit

Permalink
Satisfy linter
Browse files Browse the repository at this point in the history
  • Loading branch information
ales-otf committed Nov 28, 2024
1 parent efd0a27 commit 75581ee
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 133 deletions.
46 changes: 24 additions & 22 deletions pallets/subtensor/src/coinbase/run_coinbase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,30 @@ use substrate_fixed::types::I96F32;
impl<T: Config> Pallet<T> {
/// The `coinbase` function performs a four-part emission distribution process involving
/// subnets, epochs, hotkeys, and nominators.
// It is divided into several steps, each handling a specific part of the distribution:

// Step 1: Compute the block-wise emission for each subnet.
// This involves calculating how much (TAO) should be emitted into each subnet using the
// root epoch function.

// Step 2: Accumulate the subnet block emission.
// After calculating the block-wise emission, these values are accumulated to keep track
// of how much each subnet should emit before the next distribution phase. This accumulation
// is a running total that gets updated each block.

// Step 3: Distribute the accumulated emissions through epochs.
// Subnets periodically distribute their accumulated emissions to hotkeys (active validators/miners)
// in the network on a `tempo` --- the time between epochs. This step runs Yuma consensus to
// determine how emissions are split among hotkeys based on their contributions and roles.
// The accumulation of hotkey emissions is done through the `accumulate_hotkey_emission` function.
// The function splits the rewards for a hotkey amongst itself and its `parents`. The parents are
// the hotkeys that are delegating their stake to the hotkey.

// Step 4: Further distribute emissions from hotkeys to nominators.
// Finally, the emissions received by hotkeys are further distributed to their nominators,
// who are stakeholders that support the hotkeys.
///
/// It is divided into several steps, each handling a specific part of the distribution:
///
/// Step 1: Compute the block-wise emission for each subnet.
/// This involves calculating how much (TAO) should be emitted into each subnet using the root
/// epoch function.
///
/// Step 2: Accumulate the subnet block emission.
/// After calculating the block-wise emission, these values are accumulated to keep track of how
/// much each subnet should emit before the next distribution phase. This accumulation is a
/// running total that gets updated each block.
///
/// Step 3: Distribute the accumulated emissions through epochs.
/// Subnets periodically distribute their accumulated emissions to hotkeys (active
/// validators/miners) in the network on a `tempo` --- the time between epochs. This step runs
/// Yuma consensus to determine how emissions are split among hotkeys based on their
/// contributions and roles. The accumulation of hotkey emissions is done through the
/// `accumulate_hotkey_emission` function. The function splits the rewards for a hotkey amongst
/// itself and its `parents`. The parents are the hotkeys that are delegating their stake to the
/// hotkey.
///
/// Step 4: Further distribute emissions from hotkeys to nominators.
/// Finally, the emissions received by hotkeys are further distributed to their nominators, who
/// are stakeholders that support the hotkeys.
pub fn run_coinbase() {
// --- 0. Get current block.
let current_block: u64 = Self::get_current_block_as_u64();
Expand Down
12 changes: 5 additions & 7 deletions pallets/subtensor/src/epoch/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,26 +113,24 @@ pub fn vec_max_upscale_to_u16(vec: &[I32F32]) -> Vec<u16> {
})
.collect();
}
return vec
.iter()
vec.iter()
.map(|e: &I32F32| {
e.saturating_mul(u16_max)
.saturating_div(*val)
.round()
.to_num::<u16>()
})
.collect();
.collect()
}
None => {
let sum: I32F32 = vec.iter().sum();
return vec
.iter()
vec.iter()
.map(|e: &I32F32| {
e.saturating_mul(u16_max)
.saturating_div(sum)
.to_num::<u16>()
})
.collect();
.collect()
}
}
}
Expand Down Expand Up @@ -246,7 +244,7 @@ pub fn is_topk(vector: &[I32F32], k: usize) -> Vec<bool> {
pub fn normalize(x: &[I32F32]) -> Vec<I32F32> {
let x_sum: I32F32 = sum(x);
if x_sum != I32F32::from_num(0.0_f32) {
return x.iter().map(|xi| xi.saturating_div(x_sum)).collect();
x.iter().map(|xi| xi.saturating_div(x_sum)).collect()
} else {
x.to_vec()
}
Expand Down
2 changes: 1 addition & 1 deletion pallets/subtensor/src/staking/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use frame_support::{
storage::IterableStorageDoubleMap,
traits::{
tokens::{
fungible::{Balanced as _, Inspect as _, Mutate as _},
fungible::{Balanced as _, Inspect as _},
Fortitude, Precision, Preservation,
},
Imbalance,
Expand Down
1 change: 0 additions & 1 deletion pallets/subtensor/src/subnets/uids.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use super::*;
use frame_support::storage::IterableStorageDoubleMap;
use frame_support::storage::IterableStorageMap;
use sp_std::vec;

impl<T: Config> Pallet<T> {
Expand Down
100 changes: 1 addition & 99 deletions pallets/subtensor/src/tests/epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2736,106 +2736,8 @@ fn test_blocks_since_last_step() {
assert_eq!(SubtensorModule::get_blocks_since_last_step(netuid), 27);
});
}
// // Map the retention graph for consensus guarantees with an single epoch on a graph with 512 nodes, of which the first 64 are validators, the graph is split into a major and minor set, each setting specific weight on itself and the complement on the other.
// //
// // ```import torch
// // import matplotlib.pyplot as plt
// // from matplotlib.pyplot import cm
// // %matplotlib inline
// //
// // with open('finney_consensus_0.4.txt') as f: # test output saved to finney_consensus.txt
// // retention_map = eval(f.read())
// //
// // major_ratios = {}
// // avg_weight_devs = {}
// // for major_stake, major_weight, minor_weight, avg_weight_dev, major_ratio in retention_map:
// // major_stake = f'{major_stake:.2f}'
// // maj, min = int(round(50 * major_weight)), int(round(50 * minor_weight))
// // avg_weight_devs.setdefault(major_stake, torch.zeros((51, 51)))
// // avg_weight_devs[major_stake][maj][min] = avg_weight_dev
// // major_ratios.setdefault(major_stake, torch.zeros((51, 51)))
// // major_ratios[major_stake][maj][min] = major_ratio
// //
// // _x = torch.linspace(0, 1, 51); _y = torch.linspace(0, 1, 51)
// // x, y = torch.meshgrid(_x, _y, indexing='ij')
// //
// // fig = plt.figure(figsize=(6, 6), dpi=70); ax = fig.gca()
// // ax.set_xticks(torch.arange(0, 1, 0.05)); ax.set_yticks(torch.arange(0, 1., 0.05))
// // ax.set_xticklabels([f'{_:.2f}'[1:] for _ in torch.arange(0, 1., 0.05)])
// // plt.grid(); plt.rc('grid', linestyle="dotted", color=[0.85, 0.85, 0.85])
// //
// // isolate = ['0.60']; stakes = [0.51, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99]
// // colors = cm.viridis(torch.linspace(0, 1, len(stakes) + 1))
// // for i, stake in enumerate(stakes):
// // contours = plt.contour(x, y, major_ratios[f'{stake:.2f}'], levels=[0., stake], colors=[colors[i + 1]])
// // if f'{stake:.2f}' in isolate:
// // contours.collections[1].set_linewidth(3)
// // plt.clabel(contours, inline=True, fontsize=10)
// //
// // plt.title(f'Major emission [$stake_{{maj}}=emission_{{maj}}$ retention lines]')
// // plt.ylabel('Minor self-weight'); plt.xlabel('Major self-weight'); plt.show()
// // ```
// // #[test]
// fn _map_consensus_guarantees() {
// let netuid: u16 = 1;
// let network_n: u16 = 512;
// let validators_n: u16 = 64;
// let epochs: u16 = 1;
// let interleave = 0;
// let weight_stddev: I32F32 = fixed(0.4);
// println!("[");
// for _major_stake in vec![0.51, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99] {
// let major_stake: I32F32 = I32F32::from_num(_major_stake);
// for _major_weight in 0..51 {
// let major_weight: I32F32 = I32F32::from_num(50 - _major_weight) / I32F32::from_num(50);
// for _minor_weight in 0..51 {
// let minor_weight: I32F32 =
// I32F32::from_num(50 - _minor_weight) / I32F32::from_num(50);
// let (
// validators,
// servers,
// major_validators,
// minor_validators,
// major_servers,
// minor_servers,
// stake,
// weights,
// avg_weight_dev,
// ) = split_graph(
// major_stake,
// major_weight,
// minor_weight,
// 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, true);

// 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));
// println!("[{major_stake}, {major_weight:.2}, {minor_weight:.2}, {avg_weight_dev:.3}, {major_ratio:.3}], ");
// });
// }
// }
// }
// println!("]");
// }

/// Helpers
// Helpers

/// Asserts that two I32F32 values are approximately equal within a given epsilon.
///
Expand Down
9 changes: 6 additions & 3 deletions runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,12 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall {
}
}

#[cfg(feature = "runtime-benchmarks")]
impl frame_system_benchmarking::Config for Runtime {}

#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::baseline::Config for Runtime {}

// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
pub struct Runtime
Expand Down Expand Up @@ -1867,9 +1873,6 @@ impl_runtime_apis! {
use frame_system_benchmarking::Pallet as SystemBench;
use baseline::Pallet as BaselineBench;

impl frame_system_benchmarking::Config for Runtime {}
impl baseline::Config for Runtime {}

use frame_support::traits::WhitelistedStorageKeys;
let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();

Expand Down

0 comments on commit 75581ee

Please sign in to comment.