Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
37bb233
add 'Subtensor.commit_reveal_enabled' + tests
Nov 26, 2024
e85c85b
add 'AsyncSubtensor.commit_reveal_enabled' + test
Nov 26, 2024
2eb8613
add extrinsic
Nov 27, 2024
e2bbf7b
add tests for extrinsic
Nov 27, 2024
d382e88
add commit reveal v3 logic to set_weights methods
Nov 27, 2024
ecbc57c
add tests
Nov 27, 2024
97e5804
Merge branch 'staging' into feat/roman/cr-v-3
Nov 27, 2024
bff8496
update get_encrypted_commit and extrinsic tests
Nov 27, 2024
b61c408
ruff
Nov 27, 2024
2db55f5
unused import
Nov 27, 2024
6fbda51
Merge branch 'staging' into feat/roman/cr-v-3
Nov 27, 2024
00628ab
update commit_reveal.py
Nov 27, 2024
49b1301
update extrinsic
Nov 30, 2024
cafc7d0
remove old function
Nov 30, 2024
3211594
Merge branch 'staging' into feat/roman/cr-v-3
Nov 30, 2024
fcffeb6
Merge branch 'staging' into feat/roman/cr-v-3
basfroman Dec 2, 2024
588b778
Merge branch 'staging' into feat/roman/cr-v-3
thewhaleking Dec 3, 2024
a536474
add params
JohnReedV Dec 3, 2024
ea50baa
More efficient use of hyperparam grabbing.
thewhaleking Dec 3, 2024
084e3b4
Updated tests.
thewhaleking Dec 3, 2024
79a2c1c
Merge pull request #2509 from opentensor/john/crv3
thewhaleking Dec 3, 2024
33d6040
Updated Name.
thewhaleking Dec 3, 2024
389d311
Added catch for unable to communicate with drand server.
thewhaleking Dec 3, 2024
dd272d0
Removed valueerror catch
thewhaleking Dec 3, 2024
e7d7fcd
Added skeleton of cr3 e2e
thewhaleking Dec 3, 2024
c2d2ae1
Adds bittensor-commit-reveal as a requirement
ibraheem-abe Dec 3, 2024
26ae576
Adds devnet in network map
ibraheem-abe Dec 4, 2024
6dedc1c
Changed commit log to hash instead of the bytes.
thewhaleking Dec 4, 2024
1b453f7
Fix tests.
thewhaleking Dec 4, 2024
8e540f2
chore: fix some comments
lvyaoting Dec 5, 2024
6ce9b20
Adds a factory function to create an initialised AsyncSubstrate object.
thewhaleking Dec 5, 2024
fd91948
Add default value to the get_block_number method in AsyncSubstrateInt…
FLiotta Dec 9, 2024
7ddee3d
Merge pull request #2529 from FLiotta/fix/typeerror/get_block_number-…
thewhaleking Dec 10, 2024
07a2204
Mismatched "archive" index
thewhaleking Dec 10, 2024
578b400
Merge branch 'staging' into fix/thewhaleking/metagraph-archive-network
thewhaleking Dec 10, 2024
93c7c30
Merge branch 'staging' into feat/thewhaleking/factory-fn-for-async-su…
thewhaleking Dec 10, 2024
74e0eac
Merge pull request #2530 from opentensor/fix/thewhaleking/metagraph-a…
thewhaleking Dec 10, 2024
8d22952
Merge branch 'staging' into feat/thewhaleking/factory-fn-for-async-su…
thewhaleking Dec 10, 2024
b3d027c
Merge pull request #2516 from opentensor/feat/thewhaleking/factory-fn…
thewhaleking Dec 10, 2024
2a13553
Merge branch 'staging' into master
thewhaleking Dec 10, 2024
24678d5
Fixes buffer overflow in stdout
ibraheem-abe Dec 10, 2024
92d5c7b
Testing on devnet
ibraheem-abe Dec 10, 2024
b352c3f
Switching back to testnet
ibraheem-abe Dec 10, 2024
6ef0d6c
Merge pull request #2515 from lvyaoting/master
thewhaleking Dec 10, 2024
924d660
Merge branch 'staging' into fix/tests-buffer-overflow
ibraheem-abe Dec 11, 2024
1d708c9
Merge pull request #2531 from opentensor/fix/tests-buffer-overflow
ibraheem-abe Dec 11, 2024
ac9cc8b
Added e2e test for CRv3 + enhancements (#2532)
ibraheem-abe Dec 12, 2024
8e05d39
Fixes var name
ibraheem-abe Dec 12, 2024
7ee0001
Merge branch 'master' into backmerge/master-to-staging-850
ibraheem-abe Dec 12, 2024
ae37b61
Merge branch 'staging' into feat/roman/cr-v-3
ibraheem-abe Dec 12, 2024
837ddab
Merge pull request #2535 from opentensor/backmerge/master-to-staging-850
ibraheem-abe Dec 12, 2024
858ed4a
Merge branch 'staging' into feat/roman/cr-v-3
ibraheem-abe Dec 12, 2024
822d36c
Cleanup
ibraheem-abe Dec 12, 2024
a3c4c08
Update bittensor/core/async_subtensor.py
ibraheem-abe Dec 12, 2024
a621657
Update bittensor/core/async_subtensor.py
ibraheem-abe Dec 12, 2024
11250a1
Update bittensor/core/async_subtensor.py
ibraheem-abe Dec 12, 2024
4f8b4c5
Updates e2e test
ibraheem-abe Dec 12, 2024
927ad92
Fixes get_current_block
thewhaleking Dec 12, 2024
4aa2b2a
Merge branch 'staging' into fix/thewhaleking/get-current-block
thewhaleking Dec 12, 2024
eb69248
Adds methods to fetch stake
ibraheem-abe Dec 12, 2024
70b020c
Cleanup
ibraheem-abe Dec 12, 2024
f4bbdbb
Update bittensor/core/subtensor.py
ibraheem-abe Dec 12, 2024
2450d37
Update bittensor/core/subtensor.py
ibraheem-abe Dec 12, 2024
2f2f0b9
Removes if not
ibraheem-abe Dec 12, 2024
e7ace15
Merge pull request #2537 from opentensor/enhancement/adds-total-stake…
ibraheem-abe Dec 12, 2024
fe6e298
Merge branch 'staging' into fix/thewhaleking/get-current-block
ibraheem-abe Dec 12, 2024
11dc376
Merge pull request #2536 from opentensor/fix/thewhaleking/get-current…
ibraheem-abe Dec 13, 2024
1b45dc4
Bumps drand ffi and updates test
ibraheem-abe Dec 13, 2024
5fe5fbf
Merge branch 'staging' into feat/roman/cr-v-3
ibraheem-abe Dec 13, 2024
3dbb7a0
Fix comparision in test
ibraheem-abe Dec 13, 2024
a34920f
Merge pull request #2484 from opentensor/feat/roman/cr-v-3
ibraheem-abe Dec 13, 2024
3de9519
Bumps version and updates changelog
ibraheem-abe Dec 13, 2024
42e2a0c
Rename method to fetch subnet commits
ibraheem-abe Dec 13, 2024
6317f19
Ruff
ibraheem-abe Dec 13, 2024
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
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
# Changelog

## 8.5.0 /2024-12-12

## What's Changed
* add improved reveal-round params by @JohnReedV in https://github.com/opentensor/bittensor/pull/2509
* fix: add default value to the get_block_number method in AsyncSubstrateInterface by @FLiotta in https://github.com/opentensor/bittensor/pull/2529
* Mismatched "archive" index by @thewhaleking in https://github.com/opentensor/bittensor/pull/2530
* Adds a factory function to create an initialised AsyncSubtensor object. by @thewhaleking in https://github.com/opentensor/bittensor/pull/2516
* chore: fix some comments by @lvyaoting in https://github.com/opentensor/bittensor/pull/2515
* Fixes E2E test chain buffer issues on devnet by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2531
* Added e2e test for CRv3 + enhancements by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2532
* Backmerge master to staging 850 by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2535
* Enhancement/adds total stake functions by @ibraheem-opentensor in https://github.com/opentensor/bittensor/pull/2537
* Fixes get_current_block by @thewhaleking in https://github.com/opentensor/bittensor/pull/2536
* [SDK] Add `commit reveal v3` logic (python part only) by @roman-opentensor in https://github.com/opentensor/bittensor/pull/2484

## New Contributors
* @JohnReedV made their first contribution in https://github.com/opentensor/bittensor/pull/2509
* @FLiotta made their first contribution in https://github.com/opentensor/bittensor/pull/2529
* @lvyaoting made their first contribution in https://github.com/opentensor/bittensor/pull/2515

**Full Changelog**: https://github.com/opentensor/bittensor/compare/v8.4.5...v8.5.0

## 8.4.5 /2024-12-05

## What's Changed
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
8.4.5
8.5.0
11 changes: 10 additions & 1 deletion bittensor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,20 @@

import warnings

from .core.settings import __version__, version_split, DEFAULTS
from .core.settings import __version__, version_split, DEFAULTS, DEFAULT_NETWORK
from .core.async_subtensor import AsyncSubtensor
from .utils.btlogging import logging
from .utils.deprecated import *


async def async_subtensor(network: str = DEFAULT_NETWORK) -> AsyncSubtensor:
"""
Creates an initialised AsyncSubtensor object.
"""
async with AsyncSubtensor(network=network) as subtensor_:
return subtensor_


def __getattr__(name):
if name == "version_split":
warnings.warn(
Expand Down
94 changes: 65 additions & 29 deletions bittensor/core/async_subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ async def get_current_block(self) -> int:

Knowing the current block number is essential for querying real-time data and performing time-sensitive operations on the blockchain. It serves as a reference point for network activities and data synchronization.
"""
return await self.substrate.get_block_number()
return await self.substrate.get_block_number(None)

async def get_block_hash(self, block_id: Optional[int] = None):
"""
Expand Down Expand Up @@ -1427,6 +1427,34 @@ async def blocks_since_last_update(self, netuid: int, uid: int) -> Optional[int]
call = await self.get_hyperparameter(param_name="LastUpdate", netuid=netuid)
return None if call is None else await self.get_current_block() - int(call[uid])

async def commit_reveal_enabled(
self, netuid: int, block_hash: Optional[str] = None
) -> bool:
"""
Check if commit-reveal mechanism is enabled for a given network at a specific block.

Arguments:
netuid (int): The network identifier for which to check the commit-reveal mechanism.
block_hash (Optional[str]): The block hash of block at which to check the parameter (default is None, which implies the current block).

Returns:
(bool): Returns the integer value of the hyperparameter if available; otherwise, returns None.
"""
call = await self.get_hyperparameter(
param_name="CommitRevealWeightsEnabled",
block_hash=block_hash,
netuid=netuid,
)
return True if call is True else False

async def get_subnet_reveal_period_epochs(
self, netuid: int, block_hash: Optional[str] = None
) -> int:
"""Retrieve the SubnetRevealPeriodEpochs hyperparameter."""
return await self.get_hyperparameter(
param_name="RevealPeriodEpochs", block_hash=block_hash, netuid=netuid
)

# Extrinsics =======================================================================================================

async def transfer(
Expand Down Expand Up @@ -1568,35 +1596,43 @@ async def set_weights(

This function is crucial in shaping the network's collective intelligence, where each neuron's learning and contribution are influenced by the weights it sets towards others【81†source】.
"""
uid = await self.get_uid_for_hotkey_on_subnet(
wallet.hotkey.ss58_address, netuid
)
retries = 0
success = False
message = "No attempt made. Perhaps it is too soon to set weights!"
while retries < max_retries and await self.blocks_since_last_update(
netuid, uid
) > await self.weights_rate_limit(netuid):
try:
logging.info(
f"Setting weights for subnet #[blue]{netuid}[/blue]. Attempt [blue]{retries + 1} of {max_retries}[/blue]."
)
success, message = await set_weights_extrinsic(
subtensor=self,
wallet=wallet,
netuid=netuid,
uids=uids,
weights=weights,
version_key=version_key,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)
except Exception as e:
logging.error(f"Error setting weights: {e}")
finally:
retries += 1
if self.commit_reveal_enabled(netuid=netuid) is True:
# go with `commit reveal v3` extrinsic
raise NotImplemented("Not implemented yet for AsyncSubtensor. Coming soon.")
else:
# go with classic `set weights extrinsic`
uid = await self.get_uid_for_hotkey_on_subnet(
wallet.hotkey.ss58_address, netuid
)
retries = 0
success = False
message = "No attempt made. Perhaps it is too soon to set weights!"
while (
retries < max_retries
and await self.blocks_since_last_update(netuid, uid)
> await self.weights_rate_limit(netuid)
and success is False
):
try:
logging.info(
f"Setting weights for subnet #[blue]{netuid}[/blue]. Attempt [blue]{retries + 1} of {max_retries}[/blue]."
)
success, message = await set_weights_extrinsic(
subtensor=self,
wallet=wallet,
netuid=netuid,
uids=uids,
weights=weights,
version_key=version_key,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)
except Exception as e:
logging.error(f"Error setting weights: {e}")
finally:
retries += 1

return success, message
return success, message

async def root_set_weights(
self,
Expand Down
165 changes: 165 additions & 0 deletions bittensor/core/extrinsics/commit_reveal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
from typing import Optional, Union, TYPE_CHECKING

import numpy as np
from bittensor_commit_reveal import get_encrypted_commit
from numpy.typing import NDArray

from bittensor.core.extrinsics.utils import submit_extrinsic
from bittensor.core.settings import version_as_int
from bittensor.utils import format_error_message
from bittensor.utils.btlogging import logging
from bittensor.utils.networking import ensure_connected
from bittensor.utils.registration import torch, use_torch
from bittensor.utils.weight_utils import convert_weights_and_uids_for_emit

if TYPE_CHECKING:
from bittensor_wallet import Wallet
from bittensor.core.subtensor import Subtensor


@ensure_connected
def _do_commit_reveal_v3(
self: "Subtensor",
wallet: "Wallet",
netuid: int,
commit: bytes,
reveal_round: int,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
) -> tuple[bool, Optional[str]]:
"""
Executes the commit-reveal phase 3 for a given netuid and commit, and optionally waits for extrinsic inclusion or finalization.

Arguments:
wallet: Wallet An instance of the Wallet class containing the user's keypair.
netuid: int The network unique identifier.
commit bytes The commit data in bytes format.
reveal_round: int The round number for the reveal phase.
wait_for_inclusion: bool, optional Flag indicating whether to wait for the extrinsic to be included in a block.
wait_for_finalization: bool, optional Flag indicating whether to wait for the extrinsic to be finalized.

Returns:
A tuple where the first element is a boolean indicating success or failure, and the second element is an optional string containing error message if any.
"""
logging.info(
f"Committing weights hash [blue]{commit.hex()}[/blue] for subnet #[blue]{netuid}[/blue] with "
f"reveal round [blue]{reveal_round}[/blue]..."
)

call = self.substrate.compose_call(
call_module="SubtensorModule",
call_function="commit_crv3_weights",
call_params={
"netuid": netuid,
"commit": commit,
"reveal_round": reveal_round,
},
)
extrinsic = self.substrate.create_signed_extrinsic(
call=call,
keypair=wallet.hotkey,
)

response = submit_extrinsic(
subtensor=self,
extrinsic=extrinsic,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)

if not wait_for_finalization and not wait_for_inclusion:
return True, "Not waiting for finalization or inclusion."

response.process_events()
if response.is_success:
return True, None
else:
return False, format_error_message(
response.error_message, substrate=self.substrate
)


def commit_reveal_v3_extrinsic(
subtensor: "Subtensor",
wallet: "Wallet",
netuid: int,
uids: Union[NDArray[np.int64], "torch.LongTensor", list],
weights: Union[NDArray[np.float32], "torch.FloatTensor", list],
version_key: int = version_as_int,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
) -> tuple[bool, str]:
"""
Commits and reveals weights for given subtensor and wallet with provided uids and weights.

Arguments:
subtensor: The Subtensor instance.
wallet: The wallet to use for committing and revealing.
netuid: The id of the network.
uids: The uids to commit.
weights: The weights associated with the uids.
version_key: The version key to use for committing and revealing. Default is version_as_int.
wait_for_inclusion: Whether to wait for the inclusion of the transaction. Default is False.
wait_for_finalization: Whether to wait for the finalization of the transaction. Default is False.

Returns:
tuple[bool, str]: A tuple where the first element is a boolean indicating success or failure, and the second element is a message associated with the result.
"""
try:
# Convert uids and weights
if use_torch():
if isinstance(uids, list):
uids = torch.tensor(uids, dtype=torch.int64)
if isinstance(weights, list):
weights = torch.tensor(weights, dtype=torch.float32)
else:
if isinstance(uids, list):
uids = np.array(uids, dtype=np.int64)
if isinstance(weights, list):
weights = np.array(weights, dtype=np.float32)

# Reformat and normalize.
uids, weights = convert_weights_and_uids_for_emit(uids, weights)

current_block = subtensor.get_current_block()
subnet_hyperparameters = subtensor.get_subnet_hyperparameters(
netuid, block=current_block
)
tempo = subnet_hyperparameters.tempo
subnet_reveal_period_epochs = (
subnet_hyperparameters.commit_reveal_weights_interval
)

# Encrypt `commit_hash` with t-lock and `get reveal_round`
commit_for_reveal, reveal_round = get_encrypted_commit(
uids=uids,
weights=weights,
version_key=version_key,
tempo=tempo,
current_block=current_block,
netuid=netuid,
subnet_reveal_period_epochs=subnet_reveal_period_epochs,
)

success, message = _do_commit_reveal_v3(
self=subtensor,
wallet=wallet,
netuid=netuid,
commit=commit_for_reveal,
reveal_round=reveal_round,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
)

if success is True:
logging.success(
f"[green]Finalized![/green] Weights commited with reveal round [blue]{reveal_round}[/blue]."
)
return True, f"reveal_round:{reveal_round}"
else:
logging.error(message)
return False, message

except Exception as e:
logging.error(f":cross_mark: [red]Failed. Error:[/red] {e}")
return False, str(e)
6 changes: 3 additions & 3 deletions bittensor/core/extrinsics/set_weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def set_weights_extrinsic(
logging.debug(f"Weights: {[float(v / 65535) for v in weight_vals]}")

try:
success, error_message = do_set_weights(
success, message = do_set_weights(
self=subtensor,
wallet=wallet,
netuid=netuid,
Expand All @@ -166,8 +166,8 @@ def set_weights_extrinsic(
logging.success(f"[green]Finalized![/green] Set weights: {str(success)}")
return True, "Successfully set weights and Finalized."
else:
logging.error(error_message)
return False, error_message
logging.error(message)
return False, message

except Exception as e:
logging.error(f":cross_mark: [red]Failed.[/red]: Error: {e}")
Expand Down
2 changes: 1 addition & 1 deletion bittensor/core/metagraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,7 @@ def sync(

if (
subtensor.chain_endpoint != settings.ARCHIVE_ENTRYPOINT
or subtensor.network != settings.NETWORKS[3]
or subtensor.network != "archive"
):
cur_block = subtensor.get_current_block()
if block and block < (cur_block - 300):
Expand Down
2 changes: 1 addition & 1 deletion bittensor/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

__version__ = "8.4.5"
__version__ = "8.5.0"

import os
import re
Expand Down
Loading
Loading