Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updates metagraph in rao-sdk #2566

Merged
merged 5 commits into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions bittensor/core/chain_data/subnet_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ class SubnetState:
validator_permit: list[bool]
pruning_score: list[float]
last_update: list[int]
emission: list[Balance]
emission: list["Balance"]
dividends: list[float]
incentives: list[float]
consensus: list[float]
trust: list[float]
rank: list[float]
block_at_registration: list[int]
local_stake: list[Balance]
global_stake: list[Balance]
stake_weight: list[float]
alpha_stake: list["Balance"]
tao_stake: list["Balance"]
total_stake: list["Balance"]
emission_history: list[list[int]]

@classmethod
Expand Down Expand Up @@ -79,12 +79,14 @@ def fix_decoded_values(cls, decoded: dict) -> "SubnetState":
trust=[u16_normalized_float(val) for val in decoded["trust"]],
rank=[u16_normalized_float(val) for val in decoded["rank"]],
block_at_registration=decoded["block_at_registration"],
local_stake=[
Balance.from_rao(val).set_unit(netuid) for val in decoded["local_stake"]
alpha_stake=[
Balance.from_rao(val).set_unit(netuid) for val in decoded["alpha_stake"]
],
global_stake=[
Balance.from_rao(val).set_unit(0) for val in decoded["global_stake"]
tao_stake=[
Balance.from_rao(val).set_unit(0) for val in decoded["tao_stake"]
],
total_stake=[
Balance.from_rao(val).set_unit(netuid) for val in decoded["total_stake"]
],
stake_weight=[u16_normalized_float(val) for val in decoded["stake_weight"]],
emission_history=decoded["emission_history"],
)
6 changes: 3 additions & 3 deletions bittensor/core/chain_data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,9 @@ def from_scale_encoding_using_type_string(
["trust", "Vec<Compact<u16>>"],
["rank", "Vec<Compact<u16>>"],
["block_at_registration", "Vec<Compact<u64>>"],
["local_stake", "Vec<Compact<u64>>"],
["global_stake", "Vec<Compact<u64>>"],
["stake_weight", "Vec<Compact<u16>>"],
["alpha_stake", "Vec<Compact<u64>>"],
["tao_stake", "Vec<Compact<u64>>"],
["total_stake", "Vec<Compact<u64>>"],
["emission_history", "Vec<Vec<Compact<u64>>>"],
],
},
Expand Down
180 changes: 67 additions & 113 deletions bittensor/core/metagraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,10 @@
if typing.TYPE_CHECKING:
from bittensor.core.subtensor import Subtensor


METAGRAPH_STATE_DICT_NDARRAY_KEYS = [
"version",
"n",
"block",
"stake",
"total_stake",
"ranks",
"trust",
"consensus",
Expand All @@ -68,8 +65,6 @@
- **version** (`str`): The version identifier of the metagraph state.
- **n** (`int`): The total number of nodes in the metagraph.
- **block** (`int`): The current block number in the blockchain or ledger.
- **stake** (`ndarray`): An array representing the stake of each node.
- **total_stake** (`float`): The sum of all individual stakes in the metagraph.
- **ranks** (`ndarray`): An array of rank scores assigned to each node.
- **trust** (`ndarray`): An array of trust scores for the nodes.
- **consensus** (`ndarray`): An array indicating consensus levels among nodes.
Expand Down Expand Up @@ -149,8 +144,6 @@ class MetagraphMixin(ABC):
version (NDArray): The version number of the network, integral for tracking network updates.
n (NDArray): The total number of neurons in the network, reflecting its size and complexity.
block (NDArray): The current block number in the blockchain, crucial for synchronizing with the network's latest state.
stake: Represents the cryptocurrency staked by neurons, impacting their influence and earnings within the network.
total_stake: The cumulative stake across all neurons.
ranks: Neuron rankings as per the Yuma Consensus algorithm, influencing their incentive distribution and network authority.
trust: Scores indicating the reliability of neurons, mainly miners, within the network's operational context.
consensus: Scores reflecting each neuron's alignment with the network's collective decisions.
Expand Down Expand Up @@ -194,84 +187,56 @@ class MetagraphMixin(ABC):

netuid: int
network: str
version: Union["torch.nn.Parameter", tuple[NDArray]]
n: Union["torch.nn.Parameter", NDArray]
block: Union["torch.nn.Parameter", NDArray]
stake: Union["torch.nn.Parameter", NDArray]
total_stake: Union["torch.nn.Parameter", NDArray]
ranks: Union["torch.nn.Parameter", NDArray]
trust: Union["torch.nn.Parameter", NDArray]
consensus: Union["torch.nn.Parameter", NDArray]
validator_trust: Union["torch.nn.Parameter", NDArray]
incentive: Union["torch.nn.Parameter", NDArray]
emission: Union["torch.nn.Parameter", NDArray]
dividends: Union["torch.nn.Parameter", NDArray]
active: Union["torch.nn.Parameter", NDArray]
last_update: Union["torch.nn.Parameter", NDArray]
validator_permit: Union["torch.nn.Parameter", NDArray]
weights: Union["torch.nn.Parameter", NDArray]
bonds: Union["torch.nn.Parameter", NDArray]
uids: Union["torch.nn.Parameter", NDArray]
local_stake: Union["torch.nn.Parameter", NDArray]
global_stake: Union["torch.nn.Parameter", NDArray]
stake_weights: Union["torch.nn.Parameter", NDArray]
global_weight: Union["torch.nn.Parameter", NDArray]
axons: list[AxonInfo]

@property
def GS(self) -> list[Balance]:
"""
Represents the global stake of each neuron in the Bittensor network.

Returns:
List[Balance]: The list of global stake of each neuron in the network.
"""
return self.global_stake
version: Union["torch.nn.Parameter", tuple["NDArray"]]
n: Union["torch.nn.Parameter", "NDArray"]
block: Union["torch.nn.Parameter", "NDArray"]
ranks: Union["torch.nn.Parameter", "NDArray"]
trust: Union["torch.nn.Parameter", "NDArray"]
consensus: Union["torch.nn.Parameter", "NDArray"]
validator_trust: Union["torch.nn.Parameter", "NDArray"]
incentive: Union["torch.nn.Parameter", "NDArray"]
emission: Union["torch.nn.Parameter", "NDArray"]
dividends: Union["torch.nn.Parameter", "NDArray"]
active: Union["torch.nn.Parameter", "NDArray"]
last_update: Union["torch.nn.Parameter", "NDArray"]
validator_permit: Union["torch.nn.Parameter", "NDArray"]
weights: Union["torch.nn.Parameter", "NDArray"]
bonds: Union["torch.nn.Parameter", "NDArray"]
uids: Union["torch.nn.Parameter", "NDArray"]
alpha_stake: Union["torch.nn.Parameter", "NDArray"]
tao_stake: Union["torch.nn.Parameter", "NDArray"]
total_stake: Union["torch.nn.Parameter", "NDArray"]
axons: list["AxonInfo"]

@property
def LS(self) -> list[Balance]:
def Ts(self) -> list["Balance"]:
"""
Represents the local stake of each neuron in the Bittensor network.
Represents the tao stake of each neuron in the Bittensor network.

Returns:
List[Balance]: The list of local stake of each neuron in the network.
list["Balance"]: The list of tao stake of each neuron in the network.
"""
return self.local_stake
return self.tao_stake

@property
def SW(self) -> list[float]:
def AS(self) -> list["Balance"]:
"""
Represents the stake weights of each neuron in the Bittensor network.
Represents the alpha stake of each neuron in the Bittensor network.

Returns:
List[float]: Each value is calculated based on local_stake and global_stake.
list["Balance"]: The list of alpha stake of each neuron in the network.
"""
return self.stake_weights
return self.alpha_stake

@property
def S(self) -> float:
def S(self) -> list["Balance"]:
"""
Represents the value between 0.0 and 1.0. This gives the users do blacklists in terms of stake values.
Represents the total stake of each neuron in the Bittensor network.

Returns:
float: The value between 0.0 and 1.0 or None if stake_weights doesn't have zero index value.
list["Balance"]: The list of total stake of each neuron in the network.
"""
try:
value = self.stake_weights[0] * max(self.global_stake).tao
except IndexError:
logging.warning("Stake weights is empty.")
value = None
return value

@property
def GW(self) -> float:
"""
Represents Global Weights of subnet across all subnets.

Returns:
float: The value of Global Weights.
"""
return self.global_weight
return self.total_stake

@property
def R(self) -> Union[NDArray, "torch.nn.Parameter"]:
Expand Down Expand Up @@ -540,8 +505,6 @@ def state_dict(self):
"version": self.version,
"n": self.n,
"block": self.block,
"stake": self.stake,
"total_stake": self.total_stake,
"ranks": self.ranks,
"trust": self.trust,
"consensus": self.consensus,
Expand All @@ -557,6 +520,9 @@ def state_dict(self):
"uids": self.uids,
"axons": self.axons,
"neurons": self.neurons,
"alpha_stake": self.alpha_stake,
"tao_stake": self.tao_stake,
"total_stake": self.total_stake,
}

def sync(
Expand Down Expand Up @@ -626,9 +592,6 @@ def sync(
if not lite:
self._set_weights_and_bonds(subtensor=subtensor)

# Get global weight for netuid
self.global_weight = subtensor.get_global_weight(netuid=self.netuid)

# Fills in the stake associated attributes of a class instance from a chain response.
self._get_all_stakes_from_chain(subtensor=subtensor)

Expand Down Expand Up @@ -779,7 +742,7 @@ def _process_weights_or_bonds(
len(self.neurons), list(uids), list(values)
).astype(np.float32)
)
tensor_param: Union["torch.nn.Parameter", NDArray] = (
tensor_param: Union["torch.nn.Parameter", "NDArray"] = (
(
torch.nn.Parameter(torch.stack(data_array), requires_grad=False)
if len(data_array)
Expand Down Expand Up @@ -823,12 +786,13 @@ def _get_all_stakes_from_chain(self, subtensor: "Subtensor"):
bytes_result = bytes.fromhex(hex_bytes_result)

subnet_state: "SubnetState" = SubnetState.from_vec_u8(bytes_result)
self.global_stake = subnet_state.global_stake
self.local_stake = subnet_state.local_stake
self.stake_weights = subnet_state.stake_weight
self.alpha_stake = subnet_state.alpha_stake
self.tao_stake = subnet_state.tao_stake
self.total_stake = subnet_state.total_stake

except (SubstrateRequestException, AttributeError):
logging.debug(
"Fields `global_stake`, `local_stake`, `stake_weights` can be obtained only from the RAO network."
"Fields `alpha_stake`, `tao_stake`, `total_stake` can be obtained only from the RAO network."
)

def _process_root_weights(
Expand Down Expand Up @@ -1022,12 +986,6 @@ def __init__(
self.block: torch.nn.Parameter = torch.nn.Parameter(
torch.tensor([0], dtype=torch.int64), requires_grad=False
)
self.stake = torch.nn.Parameter(
torch.tensor([], dtype=torch.float32), requires_grad=False
)
self.total_stake: torch.nn.Parameter = torch.nn.Parameter(
torch.tensor([], dtype=torch.float32), requires_grad=False
)
self.ranks: torch.nn.Parameter = torch.nn.Parameter(
torch.tensor([], dtype=torch.float32), requires_grad=False
)
Expand Down Expand Up @@ -1067,11 +1025,10 @@ def __init__(
self.uids = torch.nn.Parameter(
torch.tensor([], dtype=torch.int64), requires_grad=False
)
self.local_stake: list[Balance] = []
self.global_stake: list[Balance] = []
self.stake_weights: list[float] = []
self.global_weight: Optional[float] = None
self.axons: list[AxonInfo] = []
self.alpha_stake: list["Balance"] = []
self.tao_stake: list["Balance"] = []
self.total_stake: list["Balance"] = []
self.axons: list["AxonInfo"] = []
if sync:
self.sync(block=None, lite=lite)

Expand Down Expand Up @@ -1133,12 +1090,6 @@ def _set_metagraph_attributes(self, block: int, subtensor: "Subtensor"):
self.validator_trust = self._create_tensor(
[neuron.validator_trust for neuron in self.neurons], dtype=torch.float32
)
self.total_stake = self._create_tensor(
[neuron.total_stake.tao for neuron in self.neurons], dtype=torch.float32
)
self.stake = self._create_tensor(
[neuron.stake for neuron in self.neurons], dtype=torch.float32
)
self.axons = [n.axon_info for n in self.neurons]

def load_from_path(self, dir_path: str) -> "Metagraph":
Expand Down Expand Up @@ -1167,10 +1118,6 @@ def load_from_path(self, dir_path: str) -> "Metagraph":
self.n = torch.nn.Parameter(state_dict["n"], requires_grad=False)
self.block = torch.nn.Parameter(state_dict["block"], requires_grad=False)
self.uids = torch.nn.Parameter(state_dict["uids"], requires_grad=False)
self.stake = torch.nn.Parameter(state_dict["stake"], requires_grad=False)
self.total_stake = torch.nn.Parameter(
state_dict["total_stake"], requires_grad=False
)
self.ranks = torch.nn.Parameter(state_dict["ranks"], requires_grad=False)
self.trust = torch.nn.Parameter(state_dict["trust"], requires_grad=False)
self.consensus = torch.nn.Parameter(
Expand Down Expand Up @@ -1202,6 +1149,18 @@ def load_from_path(self, dir_path: str) -> "Metagraph":
)
if "bonds" in state_dict:
self.bonds = torch.nn.Parameter(state_dict["bonds"], requires_grad=False)
if "alpha_stake" in state_dict:
self.alpha_stake = torch.nn.Parameter(
state_dict["alpha_stake"], requires_grad=False
)
if "tao_stake" in state_dict:
self.tao_stake = torch.nn.Parameter(
state_dict["tao_stake"], requires_grad=False
)
if "total_stake" in state_dict:
self.total_stake = torch.nn.Parameter(
state_dict["total_stake"], requires_grad=False
)
return self


Expand Down Expand Up @@ -1235,8 +1194,6 @@ def __init__(
self.version = (np.array([settings.version_as_int], dtype=np.int64),)
self.n = np.array([0], dtype=np.int64)
self.block = np.array([0], dtype=np.int64)
self.stake = np.array([], dtype=np.float32)
self.total_stake = np.array([], dtype=np.float32)
self.ranks = np.array([], dtype=np.float32)
self.trust = np.array([], dtype=np.float32)
self.consensus = np.array([], dtype=np.float32)
Expand All @@ -1250,11 +1207,10 @@ def __init__(
self.weights = np.array([], dtype=np.float32)
self.bonds = np.array([], dtype=np.int64)
self.uids = np.array([], dtype=np.int64)
self.local_stake: list[Balance] = []
self.global_stake: list[Balance] = []
self.stake_weights: list[float] = []
self.global_weight: Optional[float] = None
self.axons: list[AxonInfo] = []
self.alpha_stake: list["Balance"] = []
self.tao_stake: list["Balance"] = []
self.total_stake: list["Balance"] = []
self.axons: list["AxonInfo"] = []
if sync:
self.sync(block=None, lite=lite)

Expand Down Expand Up @@ -1312,12 +1268,6 @@ def _set_metagraph_attributes(self, block: int, subtensor: "Subtensor"):
self.validator_trust = self._create_tensor(
[neuron.validator_trust for neuron in self.neurons], dtype=np.float32
)
self.total_stake = self._create_tensor(
[neuron.total_stake.tao for neuron in self.neurons], dtype=np.float32
)
self.stake = self._create_tensor(
[neuron.stake for neuron in self.neurons], dtype=np.float32
)
self.axons = [n.axon_info for n in self.neurons]

def load_from_path(self, dir_path: str) -> "Metagraph":
Expand Down Expand Up @@ -1361,8 +1311,6 @@ def load_from_path(self, dir_path: str) -> "Metagraph":
self.n = state_dict["n"]
self.block = state_dict["block"]
self.uids = state_dict["uids"]
self.stake = state_dict["stake"]
self.total_stake = state_dict["total_stake"]
self.ranks = state_dict["ranks"]
self.trust = state_dict["trust"]
self.consensus = state_dict["consensus"]
Expand All @@ -1379,6 +1327,12 @@ def load_from_path(self, dir_path: str) -> "Metagraph":
self.weights = state_dict["weights"]
if "bonds" in state_dict:
self.bonds = state_dict["bonds"]
if "alpha_stake" in state_dict:
self.alpha_stake = state_dict["alpha_stake"]
if "tao_stake" in state_dict:
self.tao_stake = state_dict["tao_stake"]
if "total_stake" in state_dict:
self.total_stake = state_dict["total_stake"]
return self


Expand Down
Loading