Skip to content

Commit

Permalink
Updates vali and miner
Browse files Browse the repository at this point in the history
  • Loading branch information
ibraheem-opentensor committed Dec 17, 2024
1 parent fef7c87 commit dd52cf6
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 28 deletions.
50 changes: 36 additions & 14 deletions miner.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from protocol import Dummy


class Miner:
def __init__(self):
self.config = self.get_config()
Expand All @@ -17,9 +18,15 @@ def get_config(self):
# Set up the configuration parser
parser = argparse.ArgumentParser()
# TODO: Add your custom miner arguments to the parser.
parser.add_argument('--custom', default='my_custom_value', help='Adds a custom value to the parser.')
parser.add_argument(
"--custom",
default="my_custom_value",
help="Adds a custom value to the parser.",
)
# Adds override arguments for network and netuid.
parser.add_argument('--netuid', type=int, default=1, help="The chain subnet uid.")
parser.add_argument(
"--netuid", type=int, default=1, help="The chain subnet uid."
)
# Adds subtensor specific arguments.
bt.subtensor.add_args(parser)
# Adds logging specific arguments.
Expand All @@ -37,7 +44,7 @@ def get_config(self):
config.wallet.name,
config.wallet.hotkey_str,
config.netuid,
'miner',
"miner",
)
)
# Ensure the directory for logging exists.
Expand All @@ -47,7 +54,9 @@ def get_config(self):
def setup_logging(self):
# Activate Bittensor's logging with the set configurations.
bt.logging(config=self.config, logging_dir=self.config.full_path)
bt.logging.info(f"Running miner for subnet: {self.config.netuid} on network: {self.config.subtensor.network} with config:")
bt.logging.info(
f"Running miner for subnet: {self.config.netuid} on network: {self.config.subtensor.network} with config:"
)
bt.logging.info(self.config)

def setup_bittensor_objects(self):
Expand All @@ -67,40 +76,52 @@ def setup_bittensor_objects(self):
bt.logging.info(f"Metagraph: {self.metagraph}")

if self.wallet.hotkey.ss58_address not in self.metagraph.hotkeys:
bt.logging.error(f"\nYour miner: {self.wallet} is not registered to chain connection: {self.subtensor} \nRun 'btcli register' and try again.")
bt.logging.error(
f"\nYour miner: {self.wallet} is not registered to chain connection: {self.subtensor} \nRun 'btcli register' and try again."
)
exit()
else:
# Each miner gets a unique identity (UID) in the network.
self.my_subnet_uid = self.metagraph.hotkeys.index(self.wallet.hotkey.ss58_address)
self.my_subnet_uid = self.metagraph.hotkeys.index(
self.wallet.hotkey.ss58_address
)
bt.logging.info(f"Running miner on uid: {self.my_subnet_uid}")

def blacklist_fn(self, synapse: Dummy) -> Tuple[bool, str]:
# Ignore requests from unrecognized entities.
if synapse.dendrite.hotkey not in self.metagraph.hotkeys:
bt.logging.trace(f'Blacklisting unrecognized hotkey {synapse.dendrite.hotkey}')
bt.logging.trace(
f"Blacklisting unrecognized hotkey {synapse.dendrite.hotkey}"
)
return True, None
bt.logging.trace(f'Not blacklisting recognized hotkey {synapse.dendrite.hotkey}')
bt.logging.trace(
f"Not blacklisting recognized hotkey {synapse.dendrite.hotkey}"
)
return False, None

def dummy(self, synapse: Dummy) -> Dummy:
# Simple logic: return the input value multiplied by 2.
synapse.dummy_output = synapse.dummy_input * 2
bt.logging.info(f"Received input: {synapse.dummy_input}, sending output: {synapse.dummy_output}")
bt.logging.info(
f"Received input: {synapse.dummy_input}, sending output: {synapse.dummy_output}"
)
return synapse

def setup_axon(self):
# Build and link miner functions to the axon.
self.axon = bt.axon(wallet=self.wallet, config=self.config)

# Attach functions to the axon.
bt.logging.info(f"Attaching forward function to axon.")
bt.logging.info("Attaching forward function to axon.")
self.axon.attach(
forward_fn=self.dummy,
blacklist_fn=self.blacklist_fn,
)

# Serve the axon.
bt.logging.info(f"Serving axon on network: {self.config.subtensor.network} with netuid: {self.config.netuid}")
bt.logging.info(
f"Serving axon on network: {self.config.subtensor.network} with netuid: {self.config.netuid}"
)
self.axon.serve(netuid=self.config.netuid, subtensor=self.subtensor)
bt.logging.info(f"Axon: {self.axon}")

Expand All @@ -120,21 +141,22 @@ def run(self):
if step % 60 == 0:
self.metagraph.sync()
log = (
f'Block: {self.metagraph.block.item()} | '
f'Incentive: {self.metagraph.I[self.my_subnet_uid]} | '
f"Block: {self.metagraph.block.item()} | "
f"Incentive: {self.metagraph.I[self.my_subnet_uid]} | "
)
bt.logging.info(log)
step += 1
time.sleep(1)

except KeyboardInterrupt:
self.axon.stop()
bt.logging.success('Miner killed by keyboard interrupt.')
bt.logging.success("Miner killed by keyboard interrupt.")
break
except Exception as e:
bt.logging.error(traceback.format_exc())
continue


# Run the miner.
if __name__ == "__main__":
miner = Miner()
Expand Down
57 changes: 43 additions & 14 deletions validator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import time
import random
import argparse
import traceback
Expand All @@ -14,7 +15,9 @@ def __init__(self):
self.setup_bittensor_objects()
self.my_uid = self.metagraph.hotkeys.index(self.wallet.hotkey.ss58_address)
self.scores = [1.0] * len(self.metagraph.S)
self.last_update = self.subtensor.blocks_since_last_update(self.config.netuid, self.my_uid)
self.last_update = self.subtensor.blocks_since_last_update(
self.config.netuid, self.my_uid
)
self.tempo = self.subtensor.tempo(self.config.netuid)
self.moving_avg_scores = [1.0] * len(self.metagraph.S)
self.alpha = 0.1
Expand All @@ -23,9 +26,15 @@ def get_config(self):
# Set up the configuration parser.
parser = argparse.ArgumentParser()
# TODO: Add your custom validator arguments to the parser.
parser.add_argument('--custom', default='my_custom_value', help='Adds a custom value to the parser.')
parser.add_argument(
"--custom",
default="my_custom_value",
help="Adds a custom value to the parser.",
)
# Adds override arguments for network and netuid.
parser.add_argument('--netuid', type=int, default=1, help="The chain subnet uid.")
parser.add_argument(
"--netuid", type=int, default=1, help="The chain subnet uid."
)
# Adds subtensor specific arguments.
bt.subtensor.add_args(parser)
# Adds logging specific arguments.
Expand All @@ -41,7 +50,7 @@ def get_config(self):
config.wallet.name,
config.wallet.hotkey_str,
config.netuid,
'validator',
"validator",
)
)
# Ensure the logging directory exists.
Expand All @@ -51,7 +60,9 @@ def get_config(self):
def setup_logging(self):
# Set up logging.
bt.logging(config=self.config, logging_dir=self.config.full_path)
bt.logging.info(f"Running validator for subnet: {self.config.netuid} on network: {self.config.subtensor.network} with config:")
bt.logging.info(
f"Running validator for subnet: {self.config.netuid} on network: {self.config.subtensor.network} with config:"
)
bt.logging.info(self.config)

def setup_bittensor_objects(self):
Expand All @@ -76,11 +87,15 @@ def setup_bittensor_objects(self):

# Connect the validator to the network.
if self.wallet.hotkey.ss58_address not in self.metagraph.hotkeys:
bt.logging.error(f"\nYour validator: {self.wallet} is not registered to chain connection: {self.subtensor} \nRun 'btcli register' and try again.")
bt.logging.error(
f"\nYour validator: {self.wallet} is not registered to chain connection: {self.subtensor} \nRun 'btcli register' and try again."
)
exit()
else:
# Each validator gets a unique identity (UID) in the network.
self.my_subnet_uid = self.metagraph.hotkeys.index(self.wallet.hotkey.ss58_address)
self.my_subnet_uid = self.metagraph.hotkeys.index(
self.wallet.hotkey.ss58_address
)
bt.logging.info(f"Running validator on uid: {self.my_subnet_uid}")

# Set up initial scoring weights for validation.
Expand All @@ -98,24 +113,36 @@ def run(self):

# Broadcast a query to all miners on the network.
responses = self.dendrite.query(
axons=self.metagraph.axons,
synapse=synapse,
timeout=12
axons=self.metagraph.axons, synapse=synapse, timeout=12
)
bt.logging.info(f"sending input {synapse.dummy_input}")
if responses:
responses = [response.dummy_output for response in responses if response is not None]
responses = [
response.dummy_output
for response in responses
if response is not None
]

# Log the results.
bt.logging.info(f"Received dummy responses: {responses}")

# Adjust the length of moving_avg_scores to match the number of responses
if len(self.moving_avg_scores) < len(responses):
self.moving_avg_scores.extend(
[1] * (len(responses) - len(self.moving_avg_scores))
)

# Adjust the scores based on responses from miners and update moving average.
for i, resp_i in enumerate(responses):
current_score = 1 if resp_i == synapse.dummy_input * 2 else 0
self.moving_avg_scores[i] = (1 - self.alpha) * self.moving_avg_scores[i] + self.alpha * current_score
self.moving_avg_scores[i] = (
1 - self.alpha
) * self.moving_avg_scores[i] + self.alpha * current_score

bt.logging.info(f"Moving Average Scores: {self.moving_avg_scores}")
self.last_update = self.subtensor.blocks_since_last_update(self.config.netuid, self.my_uid)
self.last_update = self.subtensor.blocks_since_last_update(
self.config.netuid, self.my_uid
)

# set weights once every tempo + 1
if self.last_update > self.tempo + 1:
Expand All @@ -128,9 +155,10 @@ def run(self):
wallet=self.wallet,
uids=self.metagraph.uids,
weights=weights,
wait_for_inclusion=True
wait_for_inclusion=True,
)
self.metagraph.sync()
time.sleep(5)

except RuntimeError as e:
bt.logging.error(e)
Expand All @@ -140,6 +168,7 @@ def run(self):
bt.logging.success("Keyboard interrupt detected. Exiting validator.")
exit()


# Run the validator.
if __name__ == "__main__":
validator = Validator()
Expand Down

0 comments on commit dd52cf6

Please sign in to comment.