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

fix setup.py and run black #1

Merged
merged 2 commits into from
Sep 5, 2023
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
101 changes: 63 additions & 38 deletions neurons/miner.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,28 @@
# import this repo
import prompting


def get_config():
# Step 2: Set up the configuration parser
# This function initializes the necessary command-line arguments.
# Using command-line arguments allows users to customize various miner settings.
parser = argparse.ArgumentParser()
# TODO(developer): Adds your custom miner arguments to the parser.
parser.add_argument( '--axon.port', type=int, default=8098, help='Port to run the axon on.' )
parser.add_argument(
"--axon.port", type=int, default=8098, help="Port to run the axon on."
)
# Subtensor network to connect to
parser.add_argument( '--subtensor.network', default='test', help='Bittensor network to connect to.' )
parser.add_argument(
"--subtensor.network", default="test", help="Bittensor network to connect to."
)
# Chain endpoint to connect to
parser.add_argument( '--subtensor.chain_endpoint', default='wss://test.finney.opentensor.ai:443', help='Chain endpoint to connect to.' )
parser.add_argument(
"--subtensor.chain_endpoint",
default="wss://test.finney.opentensor.ai:443",
help="Chain endpoint to connect to.",
)
# 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 i.e. --subtensor.chain_endpoint ... --subtensor.network ...
bt.subtensor.add_args(parser)
# Adds logging specific arguments i.e. --logging.debug ..., --logging.trace .. or --logging.logging_dir ...
Expand All @@ -63,20 +72,22 @@ def get_config():
config.wallet.name,
config.wallet.hotkey,
config.netuid,
'miner',
"miner",
)
)
# Ensure the directory for logging exists, else create one.
if not os.path.exists(config.full_path): os.makedirs(config.full_path, exist_ok=True)
if not os.path.exists(config.full_path):
os.makedirs(config.full_path, exist_ok=True)
return config


# Main takes the config and starts the miner.
def main( config ):

def main(config):
# Activating Bittensor's logging with the set configurations.
bt.logging(config=config, logging_dir=config.full_path)
bt.logging.info(f"Running miner for subnet: {config.netuid} on network: {config.subtensor.chain_endpoint} with config:")
bt.logging.info(
f"Running miner for subnet: {config.netuid} on network: {config.subtensor.chain_endpoint} with config:"
)

# This logs the active configuration to the specified logging directory for review.
bt.logging.info(config)
Expand All @@ -86,11 +97,11 @@ def main( config ):
bt.logging.info("Setting up bittensor objects.")

# Wallet holds cryptographic information, ensuring secure transactions and communication.
wallet = bt.wallet( config = config )
wallet = bt.wallet(config=config)
bt.logging.info(f"Wallet: {wallet}")

# subtensor manages the blockchain connection, facilitating interaction with the Bittensor blockchain.
subtensor = bt.subtensor( config = config )
subtensor = bt.subtensor(config=config)
bt.logging.info(f"Subtensor: {subtensor}")

# metagraph provides the network's current state, holding state about other participants in a subnet.
Expand All @@ -102,7 +113,9 @@ def main( config ):
bt.logging.info(f"UID: {uid}")

if wallet.hotkey.ss58_address not in metagraph.hotkeys:
bt.logging.error(f"\nYour validator: {wallet} if not registered to chain connection: {subtensor} \nRun btcli register and try again. ")
bt.logging.error(
f"\nYour validator: {wallet} if not registered to chain connection: {subtensor} \nRun btcli register and try again. "
)
exit()
else:
# Each miner gets a unique identity (UID) in the network for differentiation.
Expand All @@ -112,60 +125,70 @@ def main( config ):
# Step 4: Set up miner functionalities
# The following functions control the miner's response to incoming requests.
# The blacklist function decides if a request should be ignored.
def blacklist_fn( synapse: prompting.protocol.Prompting ) -> bool:
# TODO(developer): Define how miners should blacklist requests. This Function
def blacklist_fn(synapse: prompting.protocol.Prompting) -> bool:
# TODO(developer): Define how miners should blacklist requests. This Function
# Runs before the synapse data has been deserialized (i.e. before synapse.data is available).
# The synapse is instead contructed via the headers of the request. It is important to blacklist
# requests before they are deserialized to avoid wasting resources on requests that will be ignored.
# Below: Check that the hotkey is a registered entity in the metagraph.
if synapse.dendrite.hotkey not in metagraph.hotkeys:
# Ignore requests from unrecognized entities.
bt.logging.trace(f'Blacklisting unrecognized hotkey {synapse.dendrite.hotkey}')
bt.logging.trace(
f"Blacklisting unrecognized hotkey {synapse.dendrite.hotkey}"
)
return True
# TODO(developer): In practice it would be wise to blacklist requests from entities that
# TODO(developer): In practice it would be wise to blacklist requests from entities that
# are not validators, or do not have enough stake. This can be checked via metagraph.S
# and metagraph.validator_permit. You can always attain the uid of the sender via a
# metagraph.hotkeys.index( synapse.dendrite.hotkey ) call.
# Otherwise, allow the request to be processed further.
bt.logging.trace(f'Not Blacklisting recognized hotkey {synapse.dendrite.hotkey}')
bt.logging.trace(
f"Not Blacklisting recognized hotkey {synapse.dendrite.hotkey}"
)
return False

# The priority function determines the order in which requests are handled.
# More valuable or higher-priority requests are processed before others.
def priority_fn( synapse: prompting.protocol.Prompting ) -> float:
def priority_fn(synapse: prompting.protocol.Prompting) -> float:
# TODO(developer): Define how miners should prioritize requests.
# Miners may recieve messages from multiple entities at once. This function
# determines which request should be processed first. Higher values indicate
# that the request should be processed first. Lower values indicate that the
# request should be processed later.
# Below: simple logic, prioritize requests from entities with more stake.
caller_uid = metagraph.hotkeys.index( synapse.dendrite.hotkey ) # Get the caller index.
prirority = float( metagraph.S[ caller_uid ] ) # Return the stake as the priority.
bt.logging.trace(f'Prioritizing {synapse.dendrite.hotkey} with value: ', prirority)
caller_uid = metagraph.hotkeys.index(
synapse.dendrite.hotkey
) # Get the caller index.
prirority = float(metagraph.S[caller_uid]) # Return the stake as the priority.
bt.logging.trace(
f"Prioritizing {synapse.dendrite.hotkey} with value: ", prirority
)
return prirority

def prompt( synapse: prompting.protocol.Prompting ) -> prompting.protocol.Prompting:
def prompt(synapse: prompting.protocol.Prompting) -> prompting.protocol.Prompting:
bt.logging.debug("In prompt!")
synapse.completion = "I am a chatbot"
return synapse

# Step 5: Build and link miner functions to the axon.
# The axon handles request processing, allowing validators to send this process requests.
axon = bt.axon( wallet = wallet, port = config.axon.port )
axon = bt.axon(wallet=wallet, port=config.axon.port)
bt.logging.info(f"Axon {axon}")

# Attach determiners which functions are called when servicing a request.
bt.logging.info(f"Attaching forward function to axon.")
axon.attach(
forward_fn = prompt,
blacklist_fn = blacklist_fn,
priority_fn = priority_fn,
forward_fn=prompt,
blacklist_fn=blacklist_fn,
priority_fn=priority_fn,
)

# Serve passes the axon information to the network + netuid we are hosting on.
# This will auto-update if the axon port of external ip have changed.
bt.logging.info(f"Serving axon {prompting} on network: {config.subtensor.chain_endpoint} with netuid: {config.netuid}")
axon.serve( netuid = config.netuid, subtensor = subtensor )
bt.logging.info(
f"Serving axon {prompting} on network: {config.subtensor.chain_endpoint} with netuid: {config.netuid}"
)
axon.serve(netuid=config.netuid, subtensor=subtensor)

# Start starts the miner's axon, making it active on the network.
bt.logging.info(f"Starting axon server on port: {config.axon.port}")
Expand All @@ -181,22 +204,24 @@ def prompt( synapse: prompting.protocol.Prompting ) -> prompting.protocol.Prompt
# Below: Periodically update our knowledge of the network graph.
if step % 5 == 0:
metagraph = subtensor.metagraph(config.netuid)
log = (f'Step:{step} | '\
f'Block:{metagraph.block.item()} | '\
f'Stake:{metagraph.S[my_subnet_uid]} | '\
f'Rank:{metagraph.R[my_subnet_uid]} | '\
f'Trust:{metagraph.T[my_subnet_uid]} | '\
f'Consensus:{metagraph.C[my_subnet_uid] } | '\
f'Incentive:{metagraph.I[my_subnet_uid]} | '\
f'Emission:{metagraph.E[my_subnet_uid]}')
log = (
f"Step:{step} | "
f"Block:{metagraph.block.item()} | "
f"Stake:{metagraph.S[my_subnet_uid]} | "
f"Rank:{metagraph.R[my_subnet_uid]} | "
f"Trust:{metagraph.T[my_subnet_uid]} | "
f"Consensus:{metagraph.C[my_subnet_uid] } | "
f"Incentive:{metagraph.I[my_subnet_uid]} | "
f"Emission:{metagraph.E[my_subnet_uid]}"
)
bt.logging.info(log)
step += 1
time.sleep(1)

# If someone intentionally stops the miner, it'll safely terminate operations.
except KeyboardInterrupt:
axon.stop()
bt.logging.success('Miner killed by keyboard interrupt.')
bt.logging.success("Miner killed by keyboard interrupt.")
break
# In case of unforeseen errors, the miner will log the error and continue operations.
except Exception as e:
Expand All @@ -206,4 +231,4 @@ def prompt( synapse: prompting.protocol.Prompting ) -> prompting.protocol.Prompt

# This is the main function, which runs the miner.
if __name__ == "__main__":
main( get_config() )
main(get_config())
74 changes: 46 additions & 28 deletions neurons/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,23 @@
# Step 2: Set up the configuration parser
# This function is responsible for setting up and parsing command-line arguments.
def get_config():

parser = argparse.ArgumentParser()
# TODO(developer): Adds your custom validator arguments to the parser.
parser.add_argument( '--axon.port', type=int, default=8099, help='Port to run the axon on.' )
parser.add_argument(
"--axon.port", type=int, default=8099, help="Port to run the axon on."
)
# Subtensor network to connect to
parser.add_argument( '--subtensor.network', default='test', help='Bittensor network to connect to.' )
parser.add_argument(
"--subtensor.network", default="test", help="Bittensor network to connect to."
)
# Chain endpoint to connect to
parser.add_argument( '--subtensor.chain_endpoint', default='wss://test.finney.opentensor.ai:443', help='Chain endpoint to connect to.' )
parser.add_argument(
"--subtensor.chain_endpoint",
default="wss://test.finney.opentensor.ai:443",
help="Chain endpoint to connect to.",
)
# 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 i.e. --subtensor.chain_endpoint ... --subtensor.network ...
bt.subtensor.add_args(parser)
# Adds logging specific arguments i.e. --logging.debug ..., --logging.trace .. or --logging.logging_dir ...
Expand All @@ -53,7 +60,7 @@ def get_config():
bt.wallet.add_args(parser)
# Parse the config (will take command-line arguments if provided)
# To print help message, run python3 template/miner.py --help
config = bt.config(parser)
config = bt.config(parser)

# Step 3: Set up logging directory
# Logging is crucial for monitoring and debugging purposes.
Expand All @@ -63,19 +70,23 @@ def get_config():
config.wallet.name,
config.wallet.hotkey,
config.netuid,
'validator',
"validator",
)
)
# Ensure the logging directory exists.
if not os.path.exists(config.full_path): os.makedirs(config.full_path, exist_ok=True)
if not os.path.exists(config.full_path):
os.makedirs(config.full_path, exist_ok=True)

# Return the parsed config.
return config

def main( config ):

def main(config):
# Set up logging with the provided configuration and directory.
bt.logging(config=config, logging_dir=config.full_path)
bt.logging.info(f"Running validator for subnet: {config.netuid} on network: {config.subtensor.chain_endpoint} with config:")
bt.logging.info(
f"Running validator for subnet: {config.netuid} on network: {config.subtensor.chain_endpoint} with config:"
)
# Log the configuration for reference.
bt.logging.info(config)

Expand All @@ -84,19 +95,19 @@ def main( config ):
bt.logging.info("Setting up bittensor objects.")

# The wallet holds the cryptographic key pairs for the validator.
wallet = bt.wallet( config = config )
wallet = bt.wallet(config=config)
bt.logging.info(f"Wallet: {wallet}")

# The subtensor is our connection to the Bittensor blockchain.
subtensor = bt.subtensor( config = config )
subtensor = bt.subtensor(config=config)
bt.logging.info(f"Subtensor: {subtensor}")

# Dendrite is the RPC client; it lets us send messages to other nodes (axons) in the network.
dendrite = bt.dendrite( wallet = wallet )
dendrite = bt.dendrite(wallet=wallet)
bt.logging.info(f"Dendrite: {dendrite}")

# The metagraph holds the state of the network, letting us know about other miners.
metagraph = subtensor.metagraph( config.netuid )
metagraph = subtensor.metagraph(config.netuid)
bt.logging.info(f"Metagraph: {metagraph}")

# Grab UID of the wallet.
Expand All @@ -105,7 +116,9 @@ def main( config ):

# Step 5: Connect the validator to the network
if wallet.hotkey.ss58_address not in metagraph.hotkeys:
bt.logging.error(f"\nYour validator: {wallet} if not registered to chain connection: {subtensor} \nRun btcli register and try again.")
bt.logging.error(
f"\nYour validator: {wallet} if not registered to chain connection: {subtensor} \nRun btcli register and try again."
)
exit()
else:
# Each miner gets a unique identity (UID) in the network for differentiation.
Expand All @@ -129,12 +142,14 @@ def main( config ):
# Send the query to all axons in the network.
metagraph.axons,
# Construct a dummy query.
prompting.protocol.Prompting(
roles = ['user'],
messages = ['This is a test validator query. Who is your daddy, and what does he do?']
), # Construct a dummy query.
prompting.protocol.Prompting(
roles=["user"],
messages=[
"This is a test validator query. Who is your daddy, and what does he do?"
],
), # Construct a dummy query.
# All responses have the deserialize function called on them before returning.
deserialize = True,
deserialize=True,
)

# Log the results for monitoring purposes.
Expand Down Expand Up @@ -164,14 +179,16 @@ def main( config ):
# This is a crucial step that updates the incentive mechanism on the Bittensor blockchain.
# Miners with higher scores (or weights) receive a larger share of TAO rewards on this subnet.
result = subtensor.set_weights(
netuid = config.netuid, # Subnet to set weights on.
wallet = wallet, # Wallet to sign set weights using hotkey.
uids = metagraph.uids, # Uids of the miners to set weights for.
weights = weights, # Weights to set for the miners.
wait_for_inclusion = True
netuid=config.netuid, # Subnet to set weights on.
wallet=wallet, # Wallet to sign set weights using hotkey.
uids=metagraph.uids, # Uids of the miners to set weights for.
weights=weights, # Weights to set for the miners.
wait_for_inclusion=True,
)
if result: bt.logging.success('Successfully set weights.')
else: bt.logging.error('Failed to set weights.')
if result:
bt.logging.success("Successfully set weights.")
else:
bt.logging.error("Failed to set weights.")

# End the current step and prepare for the next iteration.
step += 1
Expand All @@ -190,9 +207,10 @@ def main( config ):
bt.logging.success("Keyboard interrupt detected. Exiting validator.")
exit()


# The main function parses the configuration and runs the validator.
if __name__ == "__main__":
# Parse the configuration.
config = get_config()
# Run the main function.
main( config )
main(config)
26 changes: 26 additions & 0 deletions prompting/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# The MIT License (MIT)
# Copyright © 2021 Yuma Rao

# 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.

from . import prompting

__version__ = "0.0.1"
version_split = __version__.split(".")
__spec_version__ = (
(1000 * int(version_split[0]))
+ (10 * int(version_split[1]))
+ (1 * int(version_split[2]))
)
Loading