Skip to content

Commit

Permalink
metagraph sync fix (#2514)
Browse files Browse the repository at this point in the history
* Passes the subtensor object to the metagraph when instantiated.

* Test fix.

* Further refine.

* Updated handling of 'unknown' networks.

* Improve determining chain endpoint and network.

* Remove chain_endpoint arg for metagraph

* Test
  • Loading branch information
thewhaleking authored Dec 4, 2024
1 parent b346751 commit a1e1f5a
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 31 deletions.
85 changes: 58 additions & 27 deletions bittensor/core/metagraph.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,3 @@
# The MIT License (MIT)
# Copyright © 2024 Opentensor Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the “Software”), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

import os
import pickle
import typing
Expand Down Expand Up @@ -131,6 +114,26 @@ def latest_block_path(dir_path: str) -> str:
return latest_file_full_path


def determine_chain_endpoint_and_network(network: str) -> tuple[str, str]:
"""
Determine the chain endpoint and network name from the passed arg
Args:
network: The network name (e.g. 'finney', 'test') or
chain endpoint (e.g. wss://entrypoint-finney.opentensor.ai:443)
Returns:
(network name, chain endpoint)
"""
pathless_network = network[:-1] if network.endswith("/") else network
if pathless_network in settings.NETWORK_MAP:
return pathless_network, settings.NETWORK_MAP[pathless_network]
elif pathless_network in settings.REVERSE_NETWORK_MAP:
return settings.REVERSE_NETWORK_MAP[pathless_network], pathless_network
else:
return "unknown", network


class MetagraphMixin(ABC):
"""
The metagraph class is a core component of the Bittensor network, representing the neural graph that forms the backbone of the decentralized machine learning system.
Expand Down Expand Up @@ -211,6 +214,8 @@ class MetagraphMixin(ABC):
bonds: Union["torch.nn.Parameter", NDArray]
uids: Union["torch.nn.Parameter", NDArray]
axons: list[AxonInfo]
chain_endpoint: Optional[str]
subtensor: Optional["Subtensor"]

@property
def S(self) -> Union[NDArray, "torch.nn.Parameter"]:
Expand Down Expand Up @@ -407,7 +412,12 @@ def addresses(self) -> list[str]:

@abstractmethod
def __init__(
self, netuid: int, network: str = "finney", lite: bool = True, sync: bool = True
self,
netuid: int,
network: str = settings.DEFAULT_NETWORK,
lite: bool = True,
sync: bool = True,
subtensor: "Subtensor" = None,
):
"""
Initializes a new instance of the metagraph object, setting up the basic structure and parameters based on the provided arguments.
Expand Down Expand Up @@ -597,12 +607,17 @@ def _initialize_subtensor(self, subtensor: "Subtensor"):
subtensor = self._initialize_subtensor(subtensor)
"""
if subtensor and subtensor != self.subtensor:
self.subtensor = subtensor
if not subtensor and self.subtensor:
subtensor = self.subtensor
if not subtensor:
# TODO: Check and test the initialization of the new subtensor
# Lazy import due to circular import (subtensor -> metagraph, metagraph -> subtensor)
from bittensor.core.subtensor import Subtensor

subtensor = Subtensor(network=self.network)
subtensor = Subtensor(network=self.chain_endpoint)
self.subtensor = subtensor
return subtensor

def _assign_neurons(self, block: int, lite: bool, subtensor: "Subtensor"):
Expand Down Expand Up @@ -905,7 +920,12 @@ def load_from_path(self, dir_path: str) -> "Metagraph":

class TorchMetaGraph(MetagraphMixin, BaseClass):
def __init__(
self, netuid: int, network: str = "finney", lite: bool = True, sync: bool = True
self,
netuid: int,
network: str = settings.DEFAULT_NETWORK,
lite: bool = True,
sync: bool = True,
subtensor: "Subtensor" = None,
):
"""
Initializes a new instance of the metagraph object, setting up the basic structure and parameters based on the provided arguments.
Expand All @@ -926,9 +946,11 @@ def __init__(
metagraph = Metagraph(netuid=123, network="finney", lite=True, sync=True)
"""
torch.nn.Module.__init__(self)
MetagraphMixin.__init__(self, netuid, network, lite, sync)
MetagraphMixin.__init__(self, netuid, network, lite, sync, subtensor)
self.netuid = netuid
self.network = network
self.network, self.chain_endpoint = determine_chain_endpoint_and_network(
network
)
self.version = torch.nn.Parameter(
torch.tensor([settings.version_as_int], dtype=torch.int64),
requires_grad=False,
Expand Down Expand Up @@ -985,8 +1007,9 @@ def __init__(
torch.tensor([], dtype=torch.int64), requires_grad=False
)
self.axons: list[AxonInfo] = []
self.subtensor = subtensor
if sync:
self.sync(block=None, lite=lite)
self.sync(block=None, lite=lite, subtensor=subtensor)

def _set_metagraph_attributes(self, block: int, subtensor: "Subtensor"):
"""
Expand Down Expand Up @@ -1120,7 +1143,12 @@ def load_from_path(self, dir_path: str) -> "Metagraph":

class NonTorchMetagraph(MetagraphMixin):
def __init__(
self, netuid: int, network: str = "finney", lite: bool = True, sync: bool = True
self,
netuid: int,
network: str = settings.DEFAULT_NETWORK,
lite: bool = True,
sync: bool = True,
subtensor: "Subtensor" = None,
):
"""
Initializes a new instance of the metagraph object, setting up the basic structure and parameters based on the provided arguments.
Expand All @@ -1141,10 +1169,12 @@ def __init__(
metagraph = Metagraph(netuid=123, network="finney", lite=True, sync=True)
"""
# super(metagraph, self).__init__()
MetagraphMixin.__init__(self, netuid, network, lite, sync)
MetagraphMixin.__init__(self, netuid, network, lite, sync, subtensor)

self.netuid = netuid
self.network = network
self.network, self.chain_endpoint = determine_chain_endpoint_and_network(
network
)
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)
Expand All @@ -1164,8 +1194,9 @@ def __init__(
self.bonds = np.array([], dtype=np.int64)
self.uids = np.array([], dtype=np.int64)
self.axons: list[AxonInfo] = []
self.subtensor = subtensor
if sync:
self.sync(block=None, lite=lite)
self.sync(block=None, lite=lite, subtensor=subtensor)

def _set_metagraph_attributes(self, block: int, subtensor: "Subtensor"):
"""
Expand Down
12 changes: 10 additions & 2 deletions bittensor/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@

# Bittensor endpoints (Needs to use wss://)
FINNEY_ENTRYPOINT = "wss://entrypoint-finney.opentensor.ai:443"
FINNEY_TEST_ENTRYPOINT = "wss://test.finney.opentensor.ai:443/"
ARCHIVE_ENTRYPOINT = "wss://archive.chain.opentensor.ai:443/"
FINNEY_TEST_ENTRYPOINT = "wss://test.finney.opentensor.ai:443"
ARCHIVE_ENTRYPOINT = "wss://archive.chain.opentensor.ai:443"
LOCAL_ENTRYPOINT = os.getenv("BT_SUBTENSOR_CHAIN_ENDPOINT") or "ws://127.0.0.1:9944"
SUBVORTEX_ENTRYPOINT = "ws://subvortex.info:9944"

Expand All @@ -56,6 +56,14 @@
NETWORKS[4]: SUBVORTEX_ENTRYPOINT,
}

REVERSE_NETWORK_MAP = {
FINNEY_ENTRYPOINT: NETWORKS[0],
FINNEY_TEST_ENTRYPOINT: NETWORKS[1],
ARCHIVE_ENTRYPOINT: NETWORKS[2],
LOCAL_ENTRYPOINT: NETWORKS[3],
SUBVORTEX_ENTRYPOINT: NETWORKS[4],
}

# Currency Symbols Bittensor
TAO_SYMBOL: str = chr(0x03C4)
RAO_SYMBOL: str = chr(0x03C1)
Expand Down
6 changes: 5 additions & 1 deletion bittensor/core/subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,11 @@ def metagraph(
The metagraph is an essential tool for understanding the topology and dynamics of the Bittensor network's decentralized architecture, particularly in relation to neuron interconnectivity and consensus processes.
"""
metagraph = Metagraph(
network=self.network, netuid=netuid, lite=lite, sync=False
network=self.chain_endpoint,
netuid=netuid,
lite=lite,
sync=False,
subtensor=self,
)
metagraph.sync(block=block, lite=lite, subtensor=self)

Expand Down
6 changes: 5 additions & 1 deletion tests/unit_tests/test_subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1034,7 +1034,11 @@ def test_metagraph(subtensor, mocker):

# Asserts
mocked_metagraph.assert_called_once_with(
network=subtensor.network, netuid=fake_netuid, lite=fake_lite, sync=False
network=subtensor.chain_endpoint,
netuid=fake_netuid,
lite=fake_lite,
sync=False,
subtensor=subtensor,
)
mocked_metagraph.return_value.sync.assert_called_once_with(
block=None, lite=fake_lite, subtensor=subtensor
Expand Down

0 comments on commit a1e1f5a

Please sign in to comment.