Skip to content

Commit

Permalink
clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
Samuel Dare committed Jun 24, 2024
1 parent abe2f3e commit abc7798
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 42 deletions.
29 changes: 11 additions & 18 deletions pallets/subtensor/src/epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl<T: Config> Pallet<T> {
// Inactive mask.
let inactive: Vec<bool> = last_update
.iter()
.map(|updated| updated.saturating_add(activity_cutoff) < current_block)
.map(|updated| *updated + activity_cutoff < current_block)
.collect();
log::trace!("Inactive:\n{:?}\n", inactive.clone());

Expand Down Expand Up @@ -176,11 +176,6 @@ impl<T: Config> Pallet<T> {
// Compute the Exponential Moving Average (EMA) of bonds.
let mut ema_bonds = Self::compute_ema_bonds(netuid, consensus.clone(), bonds_delta, bonds);

// Compute bonds moving average.
let bonds_moving_average: I64F64 =
I64F64::from_num(Self::get_bonds_moving_average(netuid)) / I64F64::from_num(1_000_000);
let alpha: I32F32 = I32F32::from_num(1) - I32F32::from_num(bonds_moving_average);
let mut ema_bonds: Vec<Vec<I32F32>> = mat_ema(&bonds_delta, &bonds, alpha);
inplace_col_normalize(&mut ema_bonds); // sum_i b_ij = 1
log::trace!("emaB:\n{:?}\n", &ema_bonds);

Expand All @@ -194,13 +189,11 @@ impl<T: Config> Pallet<T> {
// =================================

// 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))
.map(|(ii, di)| ii + di)
.collect();
let emission_sum: I32F32 = combined_emission.iter().sum();

Expand Down Expand Up @@ -230,7 +223,7 @@ impl<T: Config> Pallet<T> {

let server_emission: Vec<I96F32> = normalized_server_emission
.iter()
.map(|se: &I32F32| I96F32::from_num(*se).saturating_mul(float_rao_emission))
.map(|se: &I32F32| I96F32::from_num(*se) * float_rao_emission)
.collect();
let server_emission: Vec<u64> = server_emission
.iter()
Expand All @@ -239,7 +232,7 @@ impl<T: Config> Pallet<T> {

let validator_emission: Vec<I96F32> = normalized_validator_emission
.iter()
.map(|ve: &I32F32| I96F32::from_num(*ve).saturating_mul(float_rao_emission))
.map(|ve: &I32F32| I96F32::from_num(*ve) * float_rao_emission)
.collect();
let validator_emission: Vec<u64> = validator_emission
.iter()
Expand All @@ -249,7 +242,7 @@ impl<T: Config> Pallet<T> {
// Used only to track combined emission in the storage.
let combined_emission: Vec<I96F32> = normalized_combined_emission
.iter()
.map(|ce: &I32F32| I96F32::from_num(*ce).saturating_mul(float_rao_emission))
.map(|ce: &I32F32| I96F32::from_num(*ce) * float_rao_emission)
.collect();
let combined_emission: Vec<u64> = combined_emission
.iter()
Expand Down Expand Up @@ -378,7 +371,7 @@ impl<T: Config> Pallet<T> {
// Inactive mask.
let inactive: Vec<bool> = last_update
.iter()
.map(|updated| updated.saturating_add(activity_cutoff) < current_block)
.map(|updated| *updated + activity_cutoff < current_block)
.collect();
log::trace!("Inactive: {:?}", inactive.clone());

Expand Down Expand Up @@ -558,7 +551,7 @@ impl<T: Config> Pallet<T> {
let combined_emission: Vec<I32F32> = incentive
.iter()
.zip(dividends.clone())
.map(|(ii, di)| ii.saturating_add(di))
.map(|(ii, di)| ii + di)
.collect();
let emission_sum: I32F32 = combined_emission.iter().sum();

Expand Down Expand Up @@ -588,7 +581,7 @@ impl<T: Config> Pallet<T> {

let server_emission: Vec<I96F32> = normalized_server_emission
.iter()
.map(|se: &I32F32| I96F32::from_num(*se).saturating_mul(float_rao_emission))
.map(|se: &I32F32| I96F32::from_num(*se) * float_rao_emission)
.collect();
let server_emission: Vec<u64> = server_emission
.iter()
Expand All @@ -597,7 +590,7 @@ impl<T: Config> Pallet<T> {

let validator_emission: Vec<I96F32> = normalized_validator_emission
.iter()
.map(|ve: &I32F32| I96F32::from_num(*ve).saturating_mul(float_rao_emission))
.map(|ve: &I32F32| I96F32::from_num(*ve) * float_rao_emission)
.collect();
let validator_emission: Vec<u64> = validator_emission
.iter()
Expand All @@ -607,7 +600,7 @@ impl<T: Config> Pallet<T> {
// Only used to track emission in storage.
let combined_emission: Vec<I96F32> = normalized_combined_emission
.iter()
.map(|ce: &I32F32| I96F32::from_num(*ce).saturating_mul(float_rao_emission))
.map(|ce: &I32F32| I96F32::from_num(*ce) * float_rao_emission)
.collect();
let combined_emission: Vec<u64> = combined_emission
.iter()
Expand Down Expand Up @@ -713,7 +706,7 @@ impl<T: Config> Pallet<T> {
I32F32::from_num(Self::get_rho(netuid))
}
pub fn get_float_kappa(netuid: u16) -> I32F32 {
I32F32::from_num(Self::get_kappa(netuid)).saturating_div(I32F32::from_num(u16::MAX))
I32F32::from_num(Self::get_kappa(netuid)) / I32F32::from_num(u16::MAX)
}

pub fn get_normalized_stake(netuid: u16) -> Vec<I32F32> {
Expand Down
52 changes: 32 additions & 20 deletions pallets/subtensor/src/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use crate::alloc::borrow::ToOwned;
#[allow(unused)]
use num_traits::float::Float;
use sp_runtime::traits::CheckedAdd;
use sp_runtime::traits::{CheckedAdd, Saturating};
use sp_std::cmp::Ordering;
use sp_std::vec;
use substrate_fixed::transcendental::{exp, ln};
Expand Down Expand Up @@ -1200,8 +1200,8 @@ pub fn mat_ema_alpha_vec_sparse(
for (j, value) in new[i].iter() {
// Retrieve the alpha value for the current column.
let alpha_val: I32F32 = alpha[*j as usize];
// Compute the EMA component for the new value.
row[*j as usize] = alpha_val * value;
// Compute the EMA component for the new value using saturating multiplication.
row[*j as usize] = alpha_val.saturating_mul(*value);
log::trace!(
"new[{}][{}] * alpha[{}] = {} * {} = {}",
i,
Expand All @@ -1217,18 +1217,19 @@ pub fn mat_ema_alpha_vec_sparse(
for (j, value) in old[i].iter() {
// Retrieve the alpha value for the current column.
let alpha_val: I32F32 = alpha[*j as usize];
// Calculate the complement of the alpha value.
let one_minus_alpha: I32F32 = I32F32::from_num(1.0) - alpha_val;
// Compute the EMA component for the old value and add it to the row.
row[*j as usize] += one_minus_alpha * value;
// Calculate the complement of the alpha value using saturating subtraction.
let one_minus_alpha: I32F32 = I32F32::from_num(1.0).saturating_sub(alpha_val);
// Compute the EMA component for the old value and add it to the row using saturating operations.
row[*j as usize] =
row[*j as usize].saturating_add(one_minus_alpha.saturating_mul(*value));
log::trace!(
"old[{}][{}] * (1 - alpha[{}]) = {} * {} = {}",
i,
j,
j,
value,
one_minus_alpha,
one_minus_alpha * value
one_minus_alpha.saturating_mul(*value)
);
}

Expand All @@ -1244,7 +1245,6 @@ pub fn mat_ema_alpha_vec_sparse(
// Return the computed EMA sparse matrix.
result
}

/// Return matrix exponential moving average: `alpha_j * a_ij + one_minus_alpha_j * b_ij`.
/// `alpha_` is the EMA coefficient passed as a vector per column.
#[allow(dead_code)]
Expand All @@ -1263,7 +1263,8 @@ pub fn mat_ema_alpha_vec(
assert!(new[0].len() == alpha.len());

// Initialize the result matrix with zeros, having the same dimensions as the new matrix.
let mut result: Vec<Vec<I32F32>> = vec![vec![I32F32::from_num(0.0); new[0].len()]; new.len()];
let mut result: Vec<Vec<I32F32>> =
vec![vec![I32F32::from_num(0.0); new.first().map_or(0, |row| row.len())]; new.len()];

// Iterate over each row of the matrices.
for (i, (new_row, old_row)) in new.iter().zip(old).enumerate() {
Expand All @@ -1272,11 +1273,13 @@ pub fn mat_ema_alpha_vec(

// Iterate over each column of the current row.
for (j, &alpha_val) in alpha.iter().enumerate().take(new_row.len()) {
// Calculate the complement of the alpha value.
let one_minus_alpha = I32F32::from_num(1.0) - alpha_val;
// Calculate the complement of the alpha value using saturating subtraction.
let one_minus_alpha = I32F32::from_num(1.0).saturating_sub(alpha_val);

// Compute the EMA for the current element.
result[i][j] = alpha_val * new_row[j] + one_minus_alpha * old_row[j];
// Compute the EMA for the current element using saturating operations.
result[i][j] = alpha_val
.saturating_mul(new_row[j])
.saturating_add(one_minus_alpha.saturating_mul(old_row[j]));
}
}

Expand All @@ -1301,7 +1304,7 @@ pub fn quantile(data: &[I32F32], quantile: f64) -> I32F32 {
}

// Calculate the position in the sorted array corresponding to the quantile.
let pos = quantile * (len - 1) as f64;
let pos = quantile * (len.saturating_sub(1)) as f64;

// Determine the lower index by flooring the position.
let low = pos.floor() as usize;
Expand All @@ -1311,17 +1314,26 @@ pub fn quantile(data: &[I32F32], quantile: f64) -> I32F32 {

// If the low and high indices are the same, return the value at that index.
if low == high {
sorted_data[low]
sorted_data
.get(low)
.copied()
.unwrap_or_else(|| I32F32::from_num(0))
} else {
// Otherwise, perform linear interpolation between the low and high values.
let low_value = sorted_data[low];
let high_value = sorted_data[high];
let low_value = sorted_data
.get(low)
.copied()
.unwrap_or_else(|| I32F32::from_num(0));
let high_value = sorted_data
.get(high)
.copied()
.unwrap_or_else(|| I32F32::from_num(0));

// Calculate the weight for interpolation.
let weight = I32F32::from_num(pos - low as f64);

// Return the interpolated value.
low_value + (high_value - low_value) * weight
// Return the interpolated value using saturating operations.
low_value.saturating_add((high_value.saturating_sub(low_value)).saturating_mul(weight))
}
}

Expand Down
2 changes: 1 addition & 1 deletion pallets/subtensor/src/subnet_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub struct SubnetInfo<T: Config> {
owner: T::AccountId,
}

#[freeze_struct("76f4053b3cc4c7ec")]
#[freeze_struct("55b472510f10e76a")]
#[derive(Decode, Encode, PartialEq, Eq, Clone, Debug)]
pub struct SubnetHyperparams {
rho: Compact<u16>,
Expand Down
6 changes: 3 additions & 3 deletions pallets/subtensor/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -669,9 +669,9 @@ impl<T: Config> Pallet<T> {

pub fn get_alpha_values_32(netuid: u16) -> (I32F32, I32F32) {
let (alpha_low, alpha_high): (u16, u16) = AlphaValues::<T>::get(netuid);
let converted_low = I32F32::from_num(alpha_low) / I32F32::from_num(u16::MAX);
let converted_high = I32F32::from_num(alpha_high) / I32F32::from_num(u16::MAX);

let converted_low = I32F32::from_num(alpha_low).saturating_div(I32F32::from_num(u16::MAX));
let converted_high =
I32F32::from_num(alpha_high).saturating_div(I32F32::from_num(u16::MAX));
(converted_low, converted_high)
}

Expand Down
3 changes: 3 additions & 0 deletions pallets/subtensor/tests/math.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
#![allow(clippy::indexing_slicing)]
use substrate_fixed::types::{I32F32, I64F64};

use pallet_subtensor::math::*;
Expand Down

0 comments on commit abc7798

Please sign in to comment.