Skip to content

Commit

Permalink
Merge pull request #1036 from opentensor/chore/cleanup-pallet-subtensor
Browse files Browse the repository at this point in the history
Remove dead code in pallet-subtensor
  • Loading branch information
sam0x17 authored Dec 4, 2024
2 parents 4914867 + 6bb1afe commit 7f5bd9d
Show file tree
Hide file tree
Showing 11 changed files with 85 additions and 155 deletions.
5 changes: 3 additions & 2 deletions pallets/subtensor/src/coinbase/root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,9 @@ impl<T: Config> Pallet<T> {

/// Checks if registrations are allowed for a given subnet.
///
/// This function retrieves the subnet hyperparameters for the specified subnet and checks the `registration_allowed` flag.
/// If the subnet doesn't exist or doesn't have hyperparameters defined, it returns `false`.
/// This function retrieves the subnet hyperparameters for the specified subnet and checks the
/// `registration_allowed` flag. If the subnet doesn't exist or doesn't have hyperparameters
/// defined, it returns `false`.
///
/// # Arguments
///
Expand Down
28 changes: 15 additions & 13 deletions pallets/subtensor/src/coinbase/run_coinbase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,30 @@ pub struct WeightsTlockPayload {
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.
/// 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.
/// 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.
/// 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.
/// 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: 0 additions & 12 deletions pallets/subtensor/src/epoch/run_epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -803,18 +803,6 @@ impl<T: Config> Pallet<T> {
I32F32::from_num(Self::get_kappa(netuid)).saturating_div(I32F32::from_num(u16::MAX))
}

pub fn get_normalized_stake(netuid: u16) -> Vec<I32F32> {
let n = Self::get_subnetwork_n(netuid);
let mut stake_64: Vec<I64F64> = (0..n)
.map(|neuron_uid| {
I64F64::from_num(Self::get_stake_for_uid_and_subnetwork(netuid, neuron_uid))
})
.collect();
inplace_normalize_64(&mut stake_64);
let stake: Vec<I32F32> = vec_fixed64_to_fixed32(stake_64);
stake
}

pub fn get_block_at_registration(netuid: u16) -> Vec<u64> {
let n = Self::get_subnetwork_n(netuid);
let block_at_registration: Vec<u64> = (0..n)
Expand Down
55 changes: 22 additions & 33 deletions pallets/subtensor/src/macros/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,33 +22,42 @@ mod errors {
HotKeyAccountNotExists,
/// The hotkey is not registered in any subnet.
HotKeyNotRegisteredInNetwork,
/// Request to stake, unstake or subscribe is made by a coldkey that is not associated with the hotkey account.
/// Request to stake, unstake or subscribe is made by a coldkey that is not associated with
/// the hotkey account.
NonAssociatedColdKey,
/// The hotkey is not a delegate and the signer is not the owner of the hotkey.
HotKeyNotDelegateAndSignerNotOwnHotKey,
/// Stake amount to withdraw is zero.
StakeToWithdrawIsZero,
/// The caller is requesting removing more stake than there exists in the staking account. See: "[remove_stake()]".
/// The caller is requesting removing more stake than there exists in the staking account.
/// See: "[remove_stake()]".
NotEnoughStakeToWithdraw,
/// The caller is requesting to set weights but the caller has less than minimum stake required to set weights (less than WeightsMinStake).
/// The caller is requesting to set weights but the caller has less than minimum stake
/// required to set weights (less than WeightsMinStake).
NotEnoughStakeToSetWeights,
/// The caller is requesting adding more stake than there exists in the coldkey account. See: "[add_stake()]"
/// The caller is requesting adding more stake than there exists in the coldkey account.
/// See: "[add_stake()]"
NotEnoughBalanceToStake,
/// The caller is trying to add stake, but for some reason the requested amount could not be withdrawn from the coldkey account.
/// The caller is trying to add stake, but for some reason the requested amount could not be
/// withdrawn from the coldkey account.
BalanceWithdrawalError,
/// Unsuccessfully withdraw, balance could be zero (can not make account exist) after withdrawal.
/// Unsuccessfully withdraw, balance could be zero (can not make account exist) after
/// withdrawal.
ZeroBalanceAfterWithdrawn,
/// The caller is attempting to set non-self weights without being a permitted validator.
NeuronNoValidatorPermit,
/// The caller is attempting to set the weight keys and values but these vectors have different size.
/// The caller is attempting to set the weight keys and values but these vectors have
/// different size.
WeightVecNotEqualSize,
/// The caller is attempting to set weights with duplicate UIDs in the weight matrix.
DuplicateUids,
/// The caller is attempting to set weight to at least one UID that does not exist in the metagraph.
/// The caller is attempting to set weight to at least one UID that does not exist in the
/// metagraph.
UidVecContainInvalidOne,
/// The dispatch is attempting to set weights on chain with fewer elements than are allowed.
WeightVecLengthIsLow,
/// Number of registrations in this block exceeds the allowed number (i.e., exceeds the subnet hyperparameter "max_regs_per_block").
/// Number of registrations in this block exceeds the allowed number (i.e., exceeds the
/// subnet hyperparameter "max_regs_per_block").
TooManyRegistrationsThisBlock,
/// The caller is requesting registering a neuron which already exists in the active set.
HotKeyAlreadyRegisteredInSubNet,
Expand All @@ -60,7 +69,8 @@ mod errors {
InvalidDifficulty,
/// The supplied PoW hash seal does not match the supplied work.
InvalidSeal,
/// The dispatch is attempting to set weights on chain with weight value exceeding the MaxWeightLimit (max_weight_limit subnet hyperparameter).
/// The dispatch is attempting to set weights on chain with weight value exceeding the
/// MaxWeightLimit (max_weight_limit subnet hyperparameter).
MaxWeightExceeded,
/// The hotkey is attempting to become a delegate when the hotkey is already a delegate.
HotKeyAlreadyDelegate,
Expand Down Expand Up @@ -114,7 +124,8 @@ mod errors {
DelegateTakeTooLow,
/// Delegate take is too high.
DelegateTakeTooHigh,
/// No commit found for the provided hotkey+netuid combination when attempting to reveal the weights.
/// No commit found for the provided hotkey+netuid combination when attempting to reveal the
/// weights.
NoWeightsCommitFound,
/// Committed hash does not equal the hashed reveal data.
InvalidRevealCommitHashNotMatch,
Expand All @@ -132,28 +143,10 @@ mod errors {
AlphaLowOutOfRange,
/// The coldkey has already been swapped
ColdKeyAlreadyAssociated,
/// The coldkey swap transaction rate limit exceeded
ColdKeySwapTxRateLimitExceeded,
/// The new coldkey is the same as the old coldkey
NewColdKeyIsSameWithOld,
/// The coldkey does not exist
NotExistColdkey,
/// The coldkey balance is not enough to pay for the swap
NotEnoughBalanceToPaySwapColdKey,
/// No balance to transfer
NoBalanceToTransfer,
/// Same coldkey
SameColdkey,
/// The coldkey is in arbitration
ColdkeyIsInArbitration,
/// The new coldkey is already registered for the drain
DuplicateColdkey,
/// Error thrown on a coldkey swap.
ColdkeySwapError,
/// Insufficient Balance to Schedule coldkey swap
InsufficientBalanceToPerformColdkeySwap,
/// The maximum number of coldkey destinations has been reached
MaxColdkeyDestinationsReached,
/// Attempting to set an invalid child for a hotkey on a network.
InvalidChild,
/// Duplicate child when setting children.
Expand All @@ -164,16 +157,12 @@ mod errors {
TooManyChildren,
/// Default transaction rate limit exceeded.
TxRateLimitExceeded,
/// Swap coldkey only callable by root.
SwapColdkeyOnlyCallableByRoot,
/// Swap already scheduled.
SwapAlreadyScheduled,
/// failed to swap coldkey
FailedToSchedule,
/// New coldkey is hotkey
NewColdKeyIsHotkey,
/// New coldkey is in arbitration
NewColdkeyIsInArbitration,
/// Childkey take is invalid.
InvalidChildkeyTake,
/// Childkey take rate limit exceeded.
Expand Down
14 changes: 0 additions & 14 deletions pallets/subtensor/src/rpc_info/delegate_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,20 +156,6 @@ impl<T: Config> Pallet<T> {
total_delegated
}

// Helper function to get total delegated stake for a hotkey
pub fn get_total_hotkey_delegated_stake(hotkey: &T::AccountId) -> u64 {
let mut total_delegated = 0u64;

// Iterate through all delegators for this hotkey
for (delegator, stake) in Stake::<T>::iter_prefix(hotkey) {
if delegator != Self::get_coldkey_for_hotkey(hotkey) {
total_delegated = total_delegated.saturating_add(stake);
}
}

total_delegated
}

// Helper function to get the coldkey associated with a hotkey
pub fn get_coldkey_for_hotkey(hotkey: &T::AccountId) -> T::AccountId {
Owner::<T>::get(hotkey)
Expand Down
9 changes: 1 addition & 8 deletions 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 Expand Up @@ -341,13 +341,6 @@ impl<T: Config> Pallet<T> {
let _ = T::Currency::deposit(coldkey, amount, Precision::BestEffort);
}

pub fn set_balance_on_coldkey_account(
coldkey: &T::AccountId,
amount: <<T as Config>::Currency as fungible::Inspect<<T as system::Config>::AccountId>>::Balance,
) {
T::Currency::set_balance(coldkey, amount);
}

pub fn can_remove_balance_from_coldkey_account(
coldkey: &T::AccountId,
amount: <<T as Config>::Currency as fungible::Inspect<<T as system::Config>::AccountId>>::Balance,
Expand Down
8 changes: 0 additions & 8 deletions pallets/subtensor/src/subnets/serving.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,14 +246,6 @@ impl<T: Config> Pallet<T> {
rate_limit == 0 || last_serve == 0 || current_block.saturating_sub(last_serve) >= rate_limit
}

pub fn has_axon_info(netuid: u16, hotkey: &T::AccountId) -> bool {
Axons::<T>::contains_key(netuid, hotkey)
}

pub fn has_prometheus_info(netuid: u16, hotkey: &T::AccountId) -> bool {
Prometheus::<T>::contains_key(netuid, hotkey)
}

pub fn get_axon_info(netuid: u16, hotkey: &T::AccountId) -> AxonInfoOf {
if let Some(axons) = Axons::<T>::get(netuid, hotkey) {
axons
Expand Down
7 changes: 0 additions & 7 deletions 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 Expand Up @@ -127,12 +126,6 @@ impl<T: Config> Pallet<T> {
}
}

/// Return the total number of subnetworks available on the chain.
///
pub fn get_number_of_subnets() -> u16 {
<SubnetworkN<T> as IterableStorageMap<u16, u16>>::iter().count() as u16
}

/// Return a list of all networks a hotkey is registered on.
///
pub fn get_registered_networks_for_hotkey(hotkey: &T::AccountId) -> Vec<u16> {
Expand Down
86 changes: 44 additions & 42 deletions pallets/subtensor/src/tests/epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2737,46 +2737,48 @@ fn test_blocks_since_last_step() {
});
}

// // 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]
// 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;
Expand Down Expand Up @@ -2811,10 +2813,10 @@ fn test_blocks_since_last_step() {
// 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] {
Expand Down
3 changes: 0 additions & 3 deletions pallets/subtensor/src/utils/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,9 +424,6 @@ impl<T: Config> Pallet<T> {
Self::deposit_event(Event::AdjustmentAlphaSet(netuid, adjustment_alpha));
}

pub fn get_validator_prune_len(netuid: u16) -> u64 {
ValidatorPruneLen::<T>::get(netuid)
}
pub fn set_validator_prune_len(netuid: u16, validator_prune_len: u64) {
ValidatorPruneLen::<T>::insert(netuid, validator_prune_len);
Self::deposit_event(Event::ValidatorPruneLenSet(netuid, validator_prune_len));
Expand Down
Loading

0 comments on commit 7f5bd9d

Please sign in to comment.