diff --git a/bittensor/__init__.py b/bittensor/__init__.py index 8d2049b355..e63ef9b7ab 100644 --- a/bittensor/__init__.py +++ b/bittensor/__init__.py @@ -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 warnings from .core.settings import __version__, version_split, DEFAULTS, DEFAULT_NETWORK diff --git a/bittensor/__main__.py b/bittensor/__main__.py index f9f56b9002..65734ad99f 100644 --- a/bittensor/__main__.py +++ b/bittensor/__main__.py @@ -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 subprocess import sys diff --git a/bittensor/core/axon.py b/bittensor/core/axon.py index 5b851b7e92..ce6923c2bd 100644 --- a/bittensor/core/axon.py +++ b/bittensor/core/axon.py @@ -1,19 +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. """Create and initialize Axon, which services the forward and backward requests from other neurons.""" import argparse @@ -33,7 +17,6 @@ import uvicorn from bittensor_wallet import Wallet, Keypair - from fastapi import APIRouter, Depends, FastAPI from fastapi.responses import JSONResponse from fastapi.routing import serialize_response @@ -41,7 +24,6 @@ from starlette.requests import Request from starlette.responses import Response - from bittensor.core.chain_data import AxonInfo from bittensor.core.config import Config from bittensor.core.errors import ( @@ -73,31 +55,40 @@ class FastAPIThreadedServer(uvicorn.Server): """ - The ``FastAPIThreadedServer`` class is a specialized server implementation for the Axon server in the Bittensor network. - - It extends the functionality of :func:`uvicorn.Server` to run the FastAPI application in a separate thread, allowing the Axon server to handle HTTP requests concurrently and non-blocking. + The ``FastAPIThreadedServer`` class is a specialized server implementation for the Axon server in the Bittensor + network. + It extends the functionality of :func:`uvicorn.Server` to run the FastAPI application in a separate thread, allowing + the Axon server to handle HTTP requests concurrently and non-blocking. - This class is designed to facilitate the integration of FastAPI with the Axon's asynchronous architecture, ensuring efficient and scalable handling of network requests. + This class is designed to facilitate the integration of FastAPI with the Axon's asynchronous architecture, ensuring + efficient and scalable handling of network requests. Importance and Functionality Threaded Execution - The class allows the FastAPI application to run in a separate thread, enabling concurrent handling of HTTP requests which is crucial for the performance and scalability of the Axon server. + The class allows the FastAPI application to run in a separate thread, enabling concurrent handling of HTTP + requests which is crucial for the performance and scalability of the Axon server. Seamless Integration - By running FastAPI in a threaded manner, this class ensures seamless integration of FastAPI's capabilities with the Axon server's asynchronous and multi-threaded architecture. + By running FastAPI in a threaded manner, this class ensures seamless integration of FastAPI's capabilities + with the Axon server's asynchronous and multi-threaded architecture. Controlled Server Management - The methods start and stop provide controlled management of the server's lifecycle, ensuring that the server can be started and stopped as needed, which is vital for maintaining the Axon server's reliability and availability. + The methods start and stop provide controlled management of the server's lifecycle, ensuring that the server + can be started and stopped as needed, which is vital for maintaining the Axon server's reliability and + availability. Signal Handling - Overriding the default signal handlers prevents potential conflicts with the Axon server's main application flow, ensuring stable operation in various network conditions. + Overriding the default signal handlers prevents potential conflicts with the Axon server's main application + flow, ensuring stable operation in various network conditions. Use Cases Starting the Server - When the Axon server is initialized, it can use this class to start the FastAPI application in a separate thread, enabling it to begin handling HTTP requests immediately. + When the Axon server is initialized, it can use this class to start the FastAPI application in a separate + thread, enabling it to begin handling HTTP requests immediately. Stopping the Server - During shutdown or maintenance of the Axon server, this class can be used to stop the FastAPI application gracefully, ensuring that all resources are properly released. + During shutdown or maintenance of the Axon server, this class can be used to stop the FastAPI application + gracefully, ensuring that all resources are properly released. Example Usage:: @@ -113,7 +104,8 @@ class FastAPIThreadedServer(uvicorn.Server): should_exit (bool): Flag to indicate whether the server should stop running. is_running (bool): Flag to indicate whether the server is currently running. - The server overrides the default signal handlers to prevent interference with the main application flow and provides methods to start and stop the server in a controlled manner. + The server overrides the default signal handlers to prevent interference with the main application flow and provides + methods to start and stop the server in a controlled manner. """ should_exit: bool = False @@ -121,13 +113,17 @@ class FastAPIThreadedServer(uvicorn.Server): def install_signal_handlers(self): """ - Overrides the default signal handlers provided by ``uvicorn.Server``. This method is essential to ensure that the signal handling in the threaded server does not interfere with the main application's flow, especially in a complex asynchronous environment like the Axon server. + Overrides the default signal handlers provided by ``uvicorn.Server``. This method is essential to ensure that + the signal handling in the threaded server does not interfere with the main application's flow, especially in a + complex asynchronous environment like the Axon server. """ @contextlib.contextmanager def run_in_thread(self): """ - Manages the execution of the server in a separate thread, allowing the FastAPI application to run asynchronously without blocking the main thread of the Axon server. This method is a key component in enabling concurrent request handling in the Axon server. + Manages the execution of the server in a separate thread, allowing the FastAPI application to run asynchronously + without blocking the main thread of the Axon server. This method is a key component in enabling concurrent + request handling in the Axon server. Yields: None: This method yields control back to the caller while the server is running in the background thread. @@ -144,7 +140,8 @@ def run_in_thread(self): def _wrapper_run(self): """ - A wrapper method for the :func:`run_in_thread` context manager. This method is used internally by the ``start`` method to initiate the server's execution in a separate thread. + A wrapper method for the :func:`run_in_thread` context manager. This method is used internally by the ``start`` + method to initiate the server's execution in a separate thread. """ with self.run_in_thread(): while not self.should_exit: @@ -152,9 +149,11 @@ def _wrapper_run(self): def start(self): """ - Starts the FastAPI server in a separate thread if it is not already running. This method sets up the server to handle HTTP requests concurrently, enabling the Axon server to efficiently manage incoming network requests. + Starts the FastAPI server in a separate thread if it is not already running. This method sets up the server to + handle HTTP requests concurrently, enabling the Axon server to efficiently manage incoming network requests. - The method ensures that the server starts running in a non-blocking manner, allowing the Axon server to continue its other operations seamlessly. + The method ensures that the server starts running in a non-blocking manner, allowing the Axon server to continue + its other operations seamlessly. """ if not self.is_running: self.should_exit = False @@ -164,9 +163,11 @@ def start(self): def stop(self): """ - Signals the FastAPI server to stop running. This method sets the :func:`should_exit` flag to ``True``, indicating that the server should cease its operations and exit the running thread. + Signals the FastAPI server to stop running. This method sets the :func:`should_exit` flag to ``True``, + indicating that the server should cease its operations and exit the running thread. - Stopping the server is essential for controlled shutdowns and resource management in the Axon server, especially during maintenance or when redeploying with updated configurations. + Stopping the server is essential for controlled shutdowns and resource management in the Axon server, especially + during maintenance or when redeploying with updated configurations. """ if self.is_running: self.should_exit = True @@ -174,7 +175,8 @@ def stop(self): class Axon: """ - The ``Axon`` class in Bittensor is a fundamental component that serves as the server-side interface for a neuron within the Bittensor network. + The ``Axon`` class in Bittensor is a fundamental component that serves as the server-side interface for a neuron + within the Bittensor network. This class is responsible for managing incoming requests from other neurons and implements various mechanisms to ensure efficient @@ -290,17 +292,21 @@ def prioritize_my_synapse( synapse: MySynapse ) -> float: Importance and Functionality Endpoint Registration - This method dynamically registers API endpoints based on the Synapse used, allowing the Axon to respond to specific types of requests and synapses. + This method dynamically registers API endpoints based on the Synapse used, allowing the Axon to respond to + specific types of requests and synapses. Customization of Request Handling By attaching different functions, the Axon can customize how it - handles, verifies, prioritizes, and potentially blocks incoming requests, making it adaptable to various network scenarios. + handles, verifies, prioritizes, and potentially blocks incoming requests, making it adaptable to various + network scenarios. Security and Efficiency - The method contributes to both the security (via verification and blacklisting) and efficiency (via prioritization) of request handling, which are crucial in a decentralized network environment. + The method contributes to both the security (via verification and blacklisting) and efficiency (via + prioritization) of request handling, which are crucial in a decentralized network environment. Flexibility - The ability to define custom functions for different aspects of request handling provides great flexibility, allowing the Axon to be tailored to specific needs and use cases within the Bittensor network. + The ability to define custom functions for different aspects of request handling provides great flexibility, + allowing the Axon to be tailored to specific needs and use cases within the Bittensor network. Error Handling and Validation The method ensures that the attached functions meet the required @@ -326,7 +332,8 @@ def __init__( ip (:type:`Optional[str]`): Binding ip. external_ip (:type:`Optional[str]`): The external ip of the server to broadcast to the network. external_port (:type:`Optional[int]`): The external port of the server to broadcast to the network. - max_workers (:type:`Optional[int]`): Used to create the threadpool if not passed, specifies the number of active threads servicing requests. + max_workers (:type:`Optional[int]`): Used to create the threadpool if not passed, specifies the number of + active threads servicing requests. """ # Build and check config. if config is None: @@ -432,13 +439,21 @@ def attach( and ensuring efficient and secure handling of requests within the Bittensor network. Args: - forward_fn (Callable): Function to be called when the API endpoint is accessed. It should have at least one argument. - blacklist_fn (Optional[Callable]): Function to filter out undesired requests. It should take the same arguments as :func:`forward_fn` and return a boolean value. Defaults to ``None``, meaning no blacklist filter will be used. - priority_fn (Optional[Callable]): Function to rank requests based on their priority. It should take the same arguments as :func:`forward_fn` and return a numerical value representing the request's priority. Defaults to ``None``, meaning no priority sorting will be applied. - verify_fn (Optional[Callable]): Function to verify requests. It should take the same arguments as :func:`forward_fn` and return a boolean value. If ``None``, :func:`self.default_verify` function will be used. + forward_fn (Callable): Function to be called when the API endpoint is accessed. It should have at least one + argument. + blacklist_fn (Optional[Callable]): Function to filter out undesired requests. It should take the same + arguments as :func:`forward_fn` and return a boolean value. Defaults to ``None``, meaning no blacklist + filter will be used. + priority_fn (Optional[Callable]): Function to rank requests based on their priority. It should take the same + arguments as :func:`forward_fn` and return a numerical value representing the request's priority. + Defaults to ``None``, meaning no priority sorting will be applied. + verify_fn (Optional[Callable]): Function to verify requests. It should take the same arguments as + :func:`forward_fn` and return a boolean value. If ``None``, :func:`self.default_verify` function will be + used. Note: - The methods :func:`forward_fn`, :func:`blacklist_fn`, :func:`priority_fn`, and :func:`verify_fn` should be designed to receive the same parameters. + The methods :func:`forward_fn`, :func:`blacklist_fn`, :func:`priority_fn`, and :func:`verify_fn` should be + designed to receive the same parameters. Raises: AssertionError: If :func:`forward_fn` does not have the signature: ``forward( synapse: YourSynapse ) -> synapse``. @@ -672,10 +687,13 @@ async def verify_body_integrity(self, request: "Request"): request (Request): The incoming FastAPI request object containing both headers and the request body. Returns: - dict: Returns the parsed body of the request as a dictionary if all the hash comparisons match, indicating that the body is intact and has not been tampered with. + dict: Returns the parsed body of the request as a dictionary if all the hash comparisons match, indicating + that the body is intact and has not been tampered with. Raises: - JSONResponse: Raises a JSONResponse with a 400 status code if any of the hash comparisons fail, indicating a potential integrity issue with the incoming request payload. The response includes the detailed error message specifying which field has a hash mismatch. + JSONResponse: Raises a JSONResponse with a 400 status code if any of the hash comparisons fail, indicating + a potential integrity issue with the incoming request payload. The response includes the detailed error + message specifying which field has a hash mismatch. This method performs several key functions: @@ -686,7 +704,9 @@ async def verify_body_integrity(self, request: "Request"): 5. Comparing the recomputed hash with the hash provided in the request headers for verification. Note: - The integrity verification is an essential step in ensuring the security of the data exchange within the Bittensor network. It helps prevent tampering and manipulation of data during transit, thereby maintaining the reliability and trust in the network communication. + The integrity verification is an essential step in ensuring the security of the data exchange within the + Bittensor network. It helps prevent tampering and manipulation of data during transit, thereby maintaining + the reliability and trust in the network communication. """ # Await and load the request body, so we can inspect it body = await request.body() @@ -773,7 +793,8 @@ def start(self) -> "Axon": my_axon.start() # Starts the axon server Note: - After invoking this method, the Axon is ready to handle requests as per its configured endpoints and custom logic. + After invoking this method, the Axon is ready to handle requests as per its configured endpoints and custom + logic. """ self.fast_server.start() self.started = True @@ -801,7 +822,8 @@ def stop(self) -> "Axon": Note: - It is advisable to ensure that all ongoing processes or requests are completed or properly handled before invoking this method. + It is advisable to ensure that all ongoing processes or requests are completed or properly handled before + invoking this method. """ self.fast_server.stop() self.started = False @@ -820,8 +842,10 @@ def serve( of information. Args: - netuid (int): The unique identifier of the subnet to register on. This ID is essential for the Axon to correctly position itself within the Bittensor network topology. - subtensor (Optional[bittensor.core.subtensor.Subtensor]): The subtensor connection to use for serving. If not provided, a new connection is established based on default configurations. + netuid (int): The unique identifier of the subnet to register on. This ID is essential for the Axon to + correctly position itself within the Bittensor network topology. + subtensor (Optional[bittensor.core.subtensor.Subtensor]): The subtensor connection to use for serving. If + not provided, a new connection is established based on default configurations. Returns: bittensor.core.axon.Axon: The Axon instance that is now actively serving on the specified subtensor. @@ -854,8 +878,8 @@ async def default_verify(self, synapse: "Synapse"): Key Features Security Assurance - The default_verify method is crucial for ensuring the security of the Bittensor network. By verifying digital signatures, it guards against unauthorized access - and data manipulation. + The default_verify method is crucial for ensuring the security of the Bittensor network. By verifying + digital signatures, it guards against unauthorized access and data manipulation. Preventing Replay Attacks The method checks for increasing nonce values, which is a vital @@ -961,7 +985,8 @@ def create_error_response(synapse: "Synapse") -> "JSONResponse": """Creates an error response based on the provided synapse object. Args: - synapse (bittensor.core.synapse.Synapse): The synapse object containing details about the request and the associated axon. + synapse (bittensor.core.synapse.Synapse): The synapse object containing details about the request and the + associated axon. Returns: JSONResponse: A JSON response with a status code and content indicating the error message. @@ -993,7 +1018,8 @@ def log_and_handle_error( synapse (bittensor.core.synapse.Synapse): The synapse object to be updated with error information. exception (Exception): The exception that was raised and needs to be logged and handled. status_code (Optional[int]): The HTTP status code to be set on the synapse object. Defaults to None. - start_time (Optional[float]): The timestamp marking the start of the processing, used to calculate process time. Defaults to None. + start_time (Optional[float]): The timestamp marking the start of the processing, used to calculate process time. + Defaults to None. Returns: Synapse: The updated synapse object with error details. @@ -1074,7 +1100,8 @@ def __init__(self, app: "AxonMiddleware", axon: "Axon"): Initialize the AxonMiddleware class. Args: - app (bittensor.core.axon.AxonMiddleware): An instance of the application where the middleware processor is used. + app (bittensor.core.axon.AxonMiddleware): An instance of the application where the middleware processor is + used. axon (bittensor.core.axon.Axon): The axon instance used to process the requests. """ super().__init__(app) @@ -1390,7 +1417,8 @@ async def submit_task( The function will run in the provided executor and return the priority value along with the result. Args: - executor (bittensor.core.threadpool.PriorityThreadPoolExecutor): The executor in which the priority function will be run. + executor (bittensor.core.threadpool.PriorityThreadPoolExecutor): The executor in which the priority + function will be run. priority (float): The priority function to be executed. Returns: @@ -1480,7 +1508,8 @@ async def synapse_to_response( Args: synapse (bittensor.core.synapse.Synapse): The Synapse object representing the request. start_time (float): The timestamp when the request processing started. - response_override: Instead of serializing the synapse, mutate the provided response object. This is only really useful for StreamingSynapse responses. + response_override: Instead of serializing the synapse, mutate the provided response object. This is only + really useful for StreamingSynapse responses. Returns: Response: The final HTTP response, with updated headers, ready to be sent back to the client. diff --git a/bittensor/core/chain_data/axon_info.py b/bittensor/core/chain_data/axon_info.py index eee9cb82a1..9ee341df3d 100644 --- a/bittensor/core/chain_data/axon_info.py +++ b/bittensor/core/chain_data/axon_info.py @@ -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. - """ This module defines the `AxonInfo` class, a data structure used to represent information about an axon endpoint in the bittensor network. @@ -105,7 +88,8 @@ def from_string(cls, json_string: str) -> "AxonInfo": json_string (str): The JSON string representation of the AxonInfo object. Returns: - AxonInfo: An instance of AxonInfo created from the JSON string. If decoding fails, returns a default `AxonInfo` object with default values. + AxonInfo: An instance of AxonInfo created from the JSON string. If decoding fails, returns a default + `AxonInfo` object with default values. Raises: json.JSONDecodeError: If there is an error in decoding the JSON string. diff --git a/bittensor/core/chain_data/neuron_info.py b/bittensor/core/chain_data/neuron_info.py index ec9df2b671..bf27b4d752 100644 --- a/bittensor/core/chain_data/neuron_info.py +++ b/bittensor/core/chain_data/neuron_info.py @@ -82,8 +82,10 @@ def from_weights_bonds_and_neuron_lite( Args: neuron_lite (NeuronInfoLite): A lite version of the neuron containing basic attributes. - weights_as_dict (dict[int, list[tuple[int, int]]]): A dictionary where the key is the UID and the value is a list of weight tuples associated with the neuron. - bonds_as_dict (dict[int, list[tuple[int, int]]]): A dictionary where the key is the UID and the value is a list of bond tuples associated with the neuron. + weights_as_dict (dict[int, list[tuple[int, int]]]): A dictionary where the key is the UID and the value is + a list of weight tuples associated with the neuron. + bonds_as_dict (dict[int, list[tuple[int, int]]]): A dictionary where the key is the UID and the value is a + list of bond tuples associated with the neuron. Returns: NeuronInfo: An instance of NeuronInfo populated with the provided weights and bonds. diff --git a/bittensor/core/chain_data/subnet_hyperparameters.py b/bittensor/core/chain_data/subnet_hyperparameters.py index c28f802cfc..a8e750d302 100644 --- a/bittensor/core/chain_data/subnet_hyperparameters.py +++ b/bittensor/core/chain_data/subnet_hyperparameters.py @@ -72,13 +72,15 @@ def from_vec_u8(cls, vec_u8: bytes) -> Optional["SubnetHyperparameters"]: """ Create a `SubnetHyperparameters` instance from a vector of bytes. - This method decodes the given vector of bytes using the `bt_decode` module and creates a new instance of `SubnetHyperparameters` with the decoded values. + This method decodes the given vector of bytes using the `bt_decode` module and creates a new instance of + `SubnetHyperparameters` with the decoded values. Args: vec_u8 (bytes): A vector of bytes to decode into `SubnetHyperparameters`. Returns: - Optional[SubnetHyperparameters]: An instance of `SubnetHyperparameters` if decoding is successful, None otherwise. + Optional[SubnetHyperparameters]: An instance of `SubnetHyperparameters` if decoding is successful, None + otherwise. """ decoded = bt_decode.SubnetHyperparameters.decode(vec_u8) return SubnetHyperparameters( diff --git a/bittensor/core/config.py b/bittensor/core/config.py index f38aff20e6..554a61b76b 100644 --- a/bittensor/core/config.py +++ b/bittensor/core/config.py @@ -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. - """Implementation of the config class, which manages the configuration of different Bittensor modules.""" import argparse @@ -42,7 +25,8 @@ class Config(DefaultMunch): parser (argparse.ArgumentParser): Command line parser object. strict (bool): If ``true``, the command line arguments are strictly parsed. args (list of str): Command line arguments. - default (Optional[Any]): Default value for the Config. Defaults to ``None``. This default will be returned for attributes that are undefined. + default (Optional[Any]): Default value for the Config. Defaults to ``None``. This default will be returned for + attributes that are undefined. Returns: config (bittensor.core.config.Config): Nested config object created from parser arguments. diff --git a/bittensor/core/dendrite.py b/bittensor/core/dendrite.py index 9e56ab4585..8ab2e15acb 100644 --- a/bittensor/core/dendrite.py +++ b/bittensor/core/dendrite.py @@ -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. - from __future__ import annotations import asyncio @@ -61,19 +44,27 @@ class DendriteMixin: network requests and processing server responses. Args: - keypair (Option[Union[bittensor_wallet.Wallet, bittensor_wallet.Keypair]]): The wallet or keypair used for signing messages. + keypair (Option[Union[bittensor_wallet.Wallet, bittensor_wallet.Keypair]]): The wallet or keypair used for + signing messages. external_ip (str): The external IP address of the local system. synapse_history (list): A list of Synapse objects representing the historical responses. Methods: __str__(): Returns a string representation of the Dendrite object. __repr__(): Returns a string representation of the Dendrite object, acting as a fallback for __str__(). - query(self, *args, **kwargs) -> Union[Synapse, list[Synapse]]: Makes synchronous requests to one or multiple target Axons and returns responses. - forward(self, axons, synapse=Synapse(), timeout=12, deserialize=True, run_async=True, streaming=False) -> Synapse: Asynchronously sends requests to one or multiple Axons and collates their responses. - call(self, target_axon, synapse=Synapse(), timeout=12.0, deserialize=True) -> Synapse: Asynchronously sends a request to a specified Axon and processes the response. - call_stream(self, target_axon, synapse=Synapse(), timeout=12.0, deserialize=True) -> AsyncGenerator[Synapse, None]: Sends a request to a specified Axon and yields an AsyncGenerator that contains streaming response chunks before finally yielding the filled Synapse as the final element. - preprocess_synapse_for_request(self, target_axon_info, synapse, timeout=12.0) -> Synapse: Preprocesses the synapse for making a request, including building headers and signing. - process_server_response(self, server_response, json_response, local_synapse): Processes the server response, updates the local synapse state, and merges headers. + query(self, *args, **kwargs) -> Union[Synapse, list[Synapse]]: Makes synchronous requests to one or multiple + target Axons and returns responses. + forward(self, axons, synapse=Synapse(), timeout=12, deserialize=True, run_async=True, streaming=False) -> + Synapse: Asynchronously sends requests to one or multiple Axons and collates their responses. + call(self, target_axon, synapse=Synapse(), timeout=12.0, deserialize=True) -> Synapse: Asynchronously sends a + request to a specified Axon and processes the response. + call_stream(self, target_axon, synapse=Synapse(), timeout=12.0, deserialize=True) -> + AsyncGenerator[Synapse, None]: Sends a request to a specified Axon and yields an AsyncGenerator that + contains streaming response chunks before finally yielding the filled Synapse as the final element. + preprocess_synapse_for_request(self, target_axon_info, synapse, timeout=12.0) -> Synapse: Preprocesses the + synapse for making a request, including building headers and signing. + process_server_response(self, server_response, json_response, local_synapse): Processes the server response, + updates the local synapse state, and merges headers. close_session(self): Synchronously closes the internal aiohttp client session. aclose_session(self): Asynchronously closes the internal aiohttp client session. @@ -104,7 +95,9 @@ def __init__(self, wallet: Optional[Union["Wallet", "Keypair"]] = None): Initializes the Dendrite object, setting up essential properties. Args: - wallet (Optional[Union[bittensor_wallet.Wallet, bittensor_wallet..Keypair]]): The user's wallet or keypair used for signing messages. Defaults to ``None``, in which case a new :func:`bittensor_wallet.Wallet().hotkey` is generated and used. + wallet (Optional[Union[bittensor_wallet.Wallet, bittensor_wallet.Keypair]]): The user's wallet or keypair + used for signing messages. Defaults to ``None``, in which case a new + :func:`bittensor_wallet.Wallet().hotkey` is generated and used. """ # Initialize the parent class super(DendriteMixin, self).__init__() @@ -127,19 +120,21 @@ def __init__(self, wallet: Optional[Union["Wallet", "Keypair"]] = None): @property async def session(self) -> aiohttp.ClientSession: """ - An asynchronous property that provides access to the internal `aiohttp `_ client session. + An asynchronous property that provides access to the internal `aiohttp `_ + client session. This property ensures the management of HTTP connections in an efficient way. It lazily - initializes the `aiohttp.ClientSession `_ on its first use. The session is then reused for subsequent - HTTP requests, offering performance benefits by reusing underlying connections. + initializes the `aiohttp.ClientSession `_ + on its first use. The session is then reused for subsequent HTTP requests, offering performance benefits by + reusing underlying connections. This is used internally by the dendrite when querying axons, and should not be used directly unless absolutely necessary for your application. Returns: - aiohttp.ClientSession: The active `aiohttp `_ client session instance. If no session exists, a - new one is created and returned. This session is used for asynchronous HTTP requests within - the dendrite, adhering to the async nature of the network interactions in the Bittensor framework. + aiohttp.ClientSession: The active `aiohttp `_ client session instance. + If no session exists, a new one is created and returned. This session is used for asynchronous HTTP requests + within the dendrite, adhering to the async nature of the network interactions in the Bittensor framework. Example usage:: @@ -169,7 +164,8 @@ def close_session(self): and should be called when the dendrite instance is no longer in use, especially in synchronous contexts. Note: - This method utilizes asyncio's event loop to close the session asynchronously from a synchronous context. It is advisable to use this method only when asynchronous context management is not feasible. + This method utilizes asyncio's event loop to close the session asynchronously from a synchronous context. + It is advisable to use this method only when asynchronous context management is not feasible. Usage: When finished with dendrite in a synchronous context @@ -305,7 +301,8 @@ def _log_outgoing_request(self, synapse: "Synapse"): request, the name of the synapse, the axon's details, and a success indicator. This information is crucial for monitoring and debugging network activity within the Bittensor network. - To turn on debug messages, set the environment variable BITTENSOR_DEBUG to ``1``, or call the bittensor debug method like so:: + To turn on debug messages, set the environment variable BITTENSOR_DEBUG to ``1``, or call the bittensor debug + method like so:: Example:: @@ -351,12 +348,16 @@ def query( Cleanup is automatically handled and sessions are closed upon completed requests. Args: - axons (Union[list[Union[bittensor.core.chain_data.axon_info.AxonInfo, 'bittensor.core.axon.Axon']], Union['bittensor.core.chain_data.axon_info.AxonInfo', 'bittensor.core.axon.Axon']]): The list of target Axon information. + axons (Union[list[Union[bittensor.core.chain_data.axon_info.AxonInfo, 'bittensor.core.axon.Axon']], + Union['bittensor.core.chain_data.axon_info.AxonInfo', 'bittensor.core.axon.Axon']]): The list of target + Axon information. synapse (Optional[bittensor.core.synapse.Synapse]): The Synapse object. Defaults to :func:`Synapse()`. timeout (Optional[float]): The request timeout duration in seconds. Defaults to ``12.0`` seconds. Returns: - Union[bittensor.core.synapse.Synapse, list[bittensor.core.synapse.Synapse]]: If a single target axon is provided, returns the response from that axon. If multiple target axons are provided, returns a list of responses from all target axons. + Union[bittensor.core.synapse.Synapse, list[bittensor.core.synapse.Synapse]]: If a single target axon is + provided, returns the response from that axon. If multiple target axons are provided, returns a list of + responses from all target axons. """ if event_loop_is_running(): warnings.warn( @@ -423,15 +424,20 @@ async def forward( print(chunk) Args: - axons (Union[list[Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]], Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]]): The target Axons to send requests to. Can be a single Axon or a list of Axons. - synapse (bittensor.core.synapse.Synapse): The Synapse object encapsulating the data. Defaults to a new :func:`Synapse` instance. + axons (Union[list[Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]], + Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]]): The target Axons to + send requests to. Can be a single Axon or a list of Axons. + synapse (bittensor.core.synapse.Synapse): The Synapse object encapsulating the data. Defaults to a new + :func:`Synapse` instance. timeout (float): Maximum duration to wait for a response from an Axon in seconds. Defaults to ``12.0``. deserialize (bool): Determines if the received response should be deserialized. Defaults to ``True``. - run_async (bool): If ``True``, sends requests concurrently. Otherwise, sends requests sequentially. Defaults to ``True``. + run_async (bool): If ``True``, sends requests concurrently. Otherwise, sends requests sequentially. + Defaults to ``True``. streaming (bool): Indicates if the response is expected to be in streaming format. Defaults to ``False``. Returns: - Union[AsyncGenerator, bittensor.core.synapse.Synapse, list[bittensor.core.synapse.Synapse]]: If a single `Axon` is targeted, returns its response. + Union[AsyncGenerator, bittensor.core.synapse.Synapse, list[bittensor.core.synapse.Synapse]]: If a single + `Axon` is targeted, returns its response. If multiple Axons are targeted, returns a list of their responses. """ is_list = True @@ -463,7 +469,9 @@ async def query_all_axons( If ``True``, responses are handled in streaming mode. Returns: - list[Union[AsyncGenerator, bittensor.core.synapse.Synapse, bittensor.core.stream.StreamingSynapse]]: A list containing the responses from each axon. The type of each response depends on the streaming mode and the type of synapse used. + list[Union[AsyncGenerator, bittensor.core.synapse.Synapse, bittensor.core.stream.StreamingSynapse]]: + A list containing the responses from each axon. The type of each response depends on the streaming + mode and the type of synapse used. """ async def single_axon_response( @@ -472,13 +480,20 @@ async def single_axon_response( """ Manages the request and response process for a single axon, supporting both streaming and non-streaming modes. - This function is responsible for initiating a request to a single axon. Depending on the ``is_stream`` flag, it either uses ``call_stream`` for streaming responses or ``call`` for standard responses. The function handles the response processing, catering to the specifics of streaming or non-streaming data. + This function is responsible for initiating a request to a single axon. Depending on the ``is_stream`` + flag, it either uses ``call_stream`` for streaming responses or ``call`` for standard responses. The + function handles the response processing, catering to the specifics of streaming or non-streaming data. Args: - target_axon (Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon): The target axon object to which the request is to be sent. This object contains the necessary information like IP address and port to formulate the request. + target_axon (Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon): The + target axon object to which the request is to be sent. This object contains the necessary + information like IP address and port to formulate the request. Returns: - Union[AsyncGenerator, bittensor.core.synapse.Synapse, bittensor.core.stream.StreamingSynapse]: The response from the targeted axon. In streaming mode, an AsyncGenerator is returned, yielding data chunks. In non-streaming mode, a Synapse or StreamingSynapse object is returned containing the response. + Union[AsyncGenerator, bittensor.core.synapse.Synapse, bittensor.core.stream.StreamingSynapse]: The + response from the targeted axon. In streaming mode, an AsyncGenerator is returned, yielding data + chunks. In non-streaming mode, a Synapse or StreamingSynapse object is returned containing the + response. """ if is_stream: # If in streaming mode, return the async_generator @@ -522,11 +537,14 @@ async def call( """ Asynchronously sends a request to a specified Axon and processes the response. - This function establishes a connection with a specified Axon, sends the encapsulated data through the Synapse object, waits for a response, processes it, and then returns the updated Synapse object. + This function establishes a connection with a specified Axon, sends the encapsulated data through the Synapse + object, waits for a response, processes it, and then returns the updated Synapse object. Args: - target_axon (Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]): The target Axon to send the request to. - synapse (bittensor.core.synapse.Synapse): The Synapse object encapsulating the data. Defaults to a new :func:`Synapse` instance. + target_axon (Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]): The target Axon + to send the request to. + synapse (bittensor.core.synapse.Synapse): The Synapse object encapsulating the data. Defaults to a new + :func:`Synapse` instance. timeout (float): Maximum duration to wait for a response from the Axon in seconds. Defaults to ``12.0``. deserialize (bool): Determines if the received response should be deserialized. Defaults to ``True``. @@ -594,9 +612,12 @@ async def call_stream( data to be transmitted. Args: - target_axon (Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]): The target Axon to send the request to. - synapse (bittensor.core.synapse.Synapse): The Synapse object encapsulating the data. Defaults to a new :func:`Synapse` instance. - timeout (float): Maximum duration to wait for a response (or a chunk of the response) from the Axon in seconds. Defaults to ``12.0``. + target_axon (Union[bittensor.core.chain_data.axon_info.AxonInfo, bittensor.core.axon.Axon]): The target Axon + to send the request to. + synapse (bittensor.core.synapse.Synapse): The Synapse object encapsulating the data. Defaults to a new + :func:`Synapse` instance. + timeout (float): Maximum duration to wait for a response (or a chunk of the response) from the Axon in + seconds. Defaults to ``12.0``. deserialize (bool): Determines if each received chunk should be deserialized. Defaults to ``True``. Yields: @@ -666,7 +687,8 @@ def preprocess_synapse_for_request( timeout: float = 12.0, ) -> "Synapse": """ - Preprocesses the synapse for making a request. This includes building headers for Dendrite and Axon and signing the request. + Preprocesses the synapse for making a request. This includes building headers for Dendrite and Axon and signing + the request. Args: target_axon_info (bittensor.core.chain_data.axon_info.AxonInfo): The target axon information. @@ -706,7 +728,8 @@ def process_server_response( local_synapse: "Synapse", ): """ - Processes the server response, updates the local synapse state with the server's state and merges headers set by the server. + Processes the server response, updates the local synapse state with the server's state and merges headers set + by the server. Args: server_response (object): The `aiohttp `_ response object from the server. @@ -782,7 +805,8 @@ async def __aenter__(self): """ Asynchronous context manager entry method. - Enables the use of the ``async with`` statement with the Dendrite instance. When entering the context, the current instance of the class is returned, making it accessible within the asynchronous context. + Enables the use of the ``async with`` statement with the Dendrite instance. When entering the context, the + current instance of the class is returned, making it accessible within the asynchronous context. Returns: Dendrite: The current instance of the Dendrite class. @@ -797,12 +821,14 @@ async def __aexit__(self, exc_type, exc_value, traceback): """ Asynchronous context manager exit method. - Ensures proper cleanup when exiting the ``async with`` context. This method will close the `aiohttp `_ client session asynchronously, releasing any tied resources. + Ensures proper cleanup when exiting the ``async with`` context. This method will close the + `aiohttp `_ client session asynchronously, releasing any tied resources. Args: exc_type (Type[BaseException]): The type of exception that was raised. exc_value (BaseException): The instance of exception that was raised. - traceback (TracebackType): A traceback object encapsulating the call stack at the point where the exception was raised. + traceback (TracebackType): A traceback object encapsulating the call stack at the point where the exception + was raised. Usage:: import bittensor @@ -820,10 +846,12 @@ def __del__(self): """ Dendrite destructor. - This method is invoked when the Dendrite instance is about to be destroyed. The destructor ensures that the aiohttp client session is closed before the instance is fully destroyed, releasing any remaining resources. + This method is invoked when the Dendrite instance is about to be destroyed. The destructor ensures that the + aiohttp client session is closed before the instance is fully destroyed, releasing any remaining resources. Note: - Relying on the destructor for cleanup can be unpredictable. It is recommended to explicitly close sessions using the provided methods or the ``async with`` context manager. + Relying on the destructor for cleanup can be unpredictable. It is recommended to explicitly close sessions + using the provided methods or the ``async with`` context manager. Usage:: diff --git a/bittensor/core/extrinsics/__init__.py b/bittensor/core/extrinsics/__init__.py index 640a132503..e69de29bb2 100644 --- a/bittensor/core/extrinsics/__init__.py +++ b/bittensor/core/extrinsics/__init__.py @@ -1,16 +0,0 @@ -# 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. diff --git a/bittensor/core/extrinsics/asyncex/commit_reveal.py b/bittensor/core/extrinsics/asyncex/commit_reveal.py index e26e1fb9cc..9d095b9e91 100644 --- a/bittensor/core/extrinsics/asyncex/commit_reveal.py +++ b/bittensor/core/extrinsics/asyncex/commit_reveal.py @@ -27,7 +27,8 @@ async def _do_commit_reveal_v3( 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. + Executes the commit-reveal phase 3 for a given netuid and commit, and optionally waits for extrinsic inclusion or + finalization. Arguments: subtensor: An instance of the Subtensor class. @@ -39,7 +40,8 @@ async def _do_commit_reveal_v3( 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. + 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 " diff --git a/bittensor/core/extrinsics/asyncex/registration.py b/bittensor/core/extrinsics/asyncex/registration.py index 371b52e834..aea5699b83 100644 --- a/bittensor/core/extrinsics/asyncex/registration.py +++ b/bittensor/core/extrinsics/asyncex/registration.py @@ -106,7 +106,8 @@ async def burned_register_extrinsic( ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. Returns: - success (bool): Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for finalization / inclusion, the response is ``true``. + success (bool): Flag is ``true`` if extrinsic was finalized or uncluded in the block. If we did not wait for + finalization / inclusion, the response is ``true``. """ if not await subtensor.subnet_exists(netuid): logging.error( @@ -249,11 +250,14 @@ async def register_extrinsic( """Registers the wallet to the chain. Args: - subtensor (bittensor.core.async_subtensor.AsyncSubtensor): initialized AsyncSubtensor object to use for chain interactions + subtensor (bittensor.core.async_subtensor.AsyncSubtensor): initialized AsyncSubtensor object to use for chain + interactions wallet (bittensor_wallet.Wallet): Bittensor wallet object. netuid (int): The ``netuid`` of the subnet to register on. - wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns `False` if the extrinsic fails to enter the block within the timeout. - wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns + `False` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning + `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. max_allowed_attempts (int): Maximum number of attempts to register the wallet. output_in_place (bool): Whether the POW solving should be outputted to the console as it goes along. cuda (bool): If `True`, the wallet should be registered using CUDA device(s). @@ -264,7 +268,8 @@ async def register_extrinsic( log_verbose: If `True`, the registration process will log more information. Returns: - `True` if extrinsic was finalized or included in the block. If we did not wait for finalization/inclusion, the response is `True`. + `True` if extrinsic was finalized or included in the block. If we did not wait for finalization/inclusion, the + response is `True`. """ logging.debug("[magenta]Checking subnet status... [/magenta]") diff --git a/bittensor/core/extrinsics/asyncex/root.py b/bittensor/core/extrinsics/asyncex/root.py index 9a77051039..0c6ada4215 100644 --- a/bittensor/core/extrinsics/asyncex/root.py +++ b/bittensor/core/extrinsics/asyncex/root.py @@ -55,11 +55,14 @@ async def root_register_extrinsic( subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The AsyncSubtensor object wallet (bittensor_wallet.Wallet): Bittensor wallet object. netuid (int): Subnet uid. - wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns `False` if the extrinsic fails to enter the block within the timeout. - wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns + `False` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning + `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. Returns: - `True` if extrinsic was finalized or included in the block. If we did not wait for finalization/inclusion, the response is `True`. + `True` if extrinsic was finalized or included in the block. If we did not wait for finalization/inclusion, the + response is `True`. """ if not (unlock := unlock_key(wallet)).success: @@ -132,14 +135,17 @@ async def _do_set_root_weights( It waits for inclusion or finalization of the extrinsic based on the provided parameters. Arguments: - subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The AsyncSubtensor object used to interact with the blockchain. + subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The AsyncSubtensor object used to interact with the + blockchain. wallet (bittensor_wallet.Wallet): The wallet containing the hotkey and coldkey for the transaction. netuids (Union[NDArray[np.int64], list[int]]): List of UIDs to set weights for. weights (Union[NDArray[np.float32], list[float]]): Corresponding weights to set for each UID. netuid (int): The netuid of the subnet to set weights for. Defaults to 0. version_key (int, optional): The version key of the validator. Defaults to 0. - wait_for_inclusion (bool, optional): If True, waits for the extrinsic to be included in a block. Defaults to False. - wait_for_finalization (bool, optional): If True, waits for the extrinsic to be finalized on the chain. Defaults to False. + wait_for_inclusion (bool, optional): If True, waits for the extrinsic to be included in a block. Defaults to + False. + wait_for_finalization (bool, optional): If True, waits for the extrinsic to be finalized on the chain. Defaults + to False. period (int, optional): The period in seconds to wait for extrinsic inclusion or finalization. Defaults to 5. Returns: @@ -198,13 +204,17 @@ async def set_root_weights_extrinsic( subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The AsyncSubtensor object wallet (bittensor_wallet.Wallet): Bittensor wallet object. netuids (Union[NDArray[np.int64], list[int]]): The `netuid` of the subnet to set weights for. - weights (Union[NDArray[np.float32], list[float]]): Weights to set. These must be `float` s and must correspond to the passed `netuid` s. + weights (Union[NDArray[np.float32], list[float]]): Weights to set. These must be `float` s and must correspond + to the passed `netuid` s. version_key (int): The version key of the validator. - wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns `False` if the extrinsic fails to enter the block within the timeout. - wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns + `False` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning + `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. Returns: - `True` if extrinsic was finalized or included in the block. If we did not wait for finalization/inclusion, the response is `True`. + `True` if extrinsic was finalized or included in the block. If we did not wait for finalization/inclusion, the + response is `True`. """ my_uid = await subtensor.substrate.query( "SubtensorModule", "Uids", [0, wallet.hotkey.ss58_address] diff --git a/bittensor/core/extrinsics/asyncex/transfer.py b/bittensor/core/extrinsics/asyncex/transfer.py index f1d3bc65e2..68b31a1c20 100644 --- a/bittensor/core/extrinsics/asyncex/transfer.py +++ b/bittensor/core/extrinsics/asyncex/transfer.py @@ -32,8 +32,10 @@ async def _do_transfer( wallet (bittensor_wallet.Wallet): Bittensor wallet object to make transfer from. destination (str): Destination public key address (ss58_address or ed25519) of recipient. amount (bittensor.utils.balance.Balance): Amount to stake as Bittensor balance. - wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns `False` if the extrinsic fails to enter the block within the timeout. - wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns + `False` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning + `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. Returns: success, block hash, formatted error message @@ -81,12 +83,15 @@ async def transfer_extrinsic( destination (str): Destination public key address (ss58_address or ed25519) of recipient. amount (bittensor.utils.balance.Balance): Amount to stake as Bittensor balance. transfer_all (bool): Whether to transfer all funds from this wallet to the destination address. - wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns `False` if the extrinsic fails to enter the block within the timeout. - wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns + `False` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning + `True`, or returns `False` if the extrinsic fails to be finalized within the timeout. keep_alive (bool): If set, keeps the account alive by keeping the balance above the existential deposit. Returns: - success (bool): Flag is `True` if extrinsic was finalized or included in the block. If we did not wait for finalization / inclusion, the response is `True`, regardless of its inclusion. + success (bool): Flag is `True` if extrinsic was finalized or included in the block. If we did not wait for + finalization / inclusion, the response is `True`, regardless of its inclusion. """ # Validate destination address. if not is_valid_bittensor_address_or_public_key(destination): diff --git a/bittensor/core/extrinsics/asyncex/unstaking.py b/bittensor/core/extrinsics/asyncex/unstaking.py index f9e8fb58a3..381b54f1d3 100644 --- a/bittensor/core/extrinsics/asyncex/unstaking.py +++ b/bittensor/core/extrinsics/asyncex/unstaking.py @@ -22,7 +22,8 @@ async def _check_threshold_amount( stake_balance (bittensor.utils.balance.Balance): the balance to check for threshold limits. Returns: - success (bool): ``true`` if the unstaking is above the threshold or 0, or ``false`` if the unstaking is below the threshold, but not 0. + success (bool): ``true`` if the unstaking is above the threshold or 0, or ``false`` if the unstaking is below + the threshold, but not 0. """ min_req_stake: Balance = await subtensor.get_minimum_required_stake() diff --git a/bittensor/core/extrinsics/asyncex/weights.py b/bittensor/core/extrinsics/asyncex/weights.py index f2affa3b5d..4a0c9e14c3 100644 --- a/bittensor/core/extrinsics/asyncex/weights.py +++ b/bittensor/core/extrinsics/asyncex/weights.py @@ -39,7 +39,8 @@ async def _do_commit_weights( Returns: tuple[bool, Optional[str]]: A tuple containing a success flag and an optional error message. - This method ensures that the weight commitment is securely recorded on the Bittensor blockchain, providing a verifiable record of the neuron's weight distribution at a specific point in time. + This method ensures that the weight commitment is securely recorded on the Bittensor blockchain, providing a + verifiable record of the neuron's weight distribution at a specific point in time. """ call = await subtensor.substrate.compose_call( call_module="SubtensorModule", @@ -98,7 +99,8 @@ async def commit_weights_extrinsic( tuple[bool, str]: ``True`` if the weight commitment is successful, False otherwise. And `msg`, a string value describing the success or potential error. - This function provides a user-friendly interface for committing weights to the Bittensor blockchain, ensuring proper error handling and user interaction when required. + This function provides a user-friendly interface for committing weights to the Bittensor blockchain, ensuring proper + error handling and user interaction when required. """ success, error_message = await _do_commit_weights( @@ -213,9 +215,11 @@ async def reveal_weights_extrinsic( wait_for_finalization (bool): Waits for the transaction to be finalized on the blockchain. Returns: - tuple[bool, str]: ``True`` if the weight revelation is successful, False otherwise. And `msg`, a string value describing the success or potential error. + tuple[bool, str]: ``True`` if the weight revelation is successful, False otherwise. And `msg`, a string value + describing the success or potential error. - This function provides a user-friendly interface for revealing weights on the Bittensor blockchain, ensuring proper error handling and user interaction when required. + This function provides a user-friendly interface for revealing weights on the Bittensor blockchain, ensuring proper + error handling and user interaction when required. """ success, error_message = await _do_reveal_weights( @@ -328,13 +332,17 @@ async def set_weights_extrinsic( wallet (bittensor_wallet.Wallet): Bittensor wallet object. netuid (int): The ``netuid`` of the subnet to set weights for. uids (Union[NDArray[np.int64], torch.LongTensor, list]): The ``uint64`` uids of destination neurons. - weights (Union[NDArray[np.float32], torch.FloatTensor, list]): The weights to set. These must be ``float`` s and correspond to the passed ``uid`` s. + weights (Union[NDArray[np.float32], torch.FloatTensor, list]): The weights to set. These must be ``float`` s and + correspond to the passed ``uid`` s. version_key (int): The version key of the validator. - wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or returns ``false`` if the extrinsic fails to enter the block within the timeout. - wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. + wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning ``true``, or + returns ``false`` if the extrinsic fails to enter the block within the timeout. + wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning + ``true``, or returns ``false`` if the extrinsic fails to be finalized within the timeout. Returns: - success (bool): Flag is ``true`` if extrinsic was finalized or included in the block. If we did not wait for finalization / inclusion, the response is ``true``. + success (bool): Flag is ``true`` if extrinsic was finalized or included in the block. If we did not wait for + finalization / inclusion, the response is ``true``. """ # First convert types. if isinstance(uids, list): diff --git a/bittensor/core/metagraph.py b/bittensor/core/metagraph.py index 20c18db41c..ae3e898cdb 100644 --- a/bittensor/core/metagraph.py +++ b/bittensor/core/metagraph.py @@ -941,30 +941,39 @@ def save(self, root_dir: Optional[list[str]] = None) -> "AsyncMetagraph": def load(self, root_dir: Optional[list[str]] = None) -> None: """ - Loads the state of the metagraph from the default save directory. This method is instrumental for restoring the metagraph to its last saved state. It automatically identifies the save directory based on the ``network`` and ``netuid`` properties of the metagraph, locates the latest block file in that directory, and loads all metagraph parameters from it. + Loads the state of the metagraph from the default save directory. This method is instrumental for restoring the + metagraph to its last saved state. It automatically identifies the save directory based on the ``network`` and + ``netuid`` properties of the metagraph, locates the latest block file in that directory, and loads all metagraph + parameters from it. This functionality is particularly beneficial when continuity in the state of the metagraph is necessary across different runtime sessions, or after a restart of the system. It ensures that the metagraph reflects the exact state it was in at the last save point, maintaining consistency in the network's representation. - The method delegates to ``load_from_path``, supplying it with the directory path constructed from the metagraph's current ``network`` and ``netuid`` properties. This abstraction simplifies the process of loading the metagraph's state for the user, requiring no direct path specifications. + The method delegates to ``load_from_path``, supplying it with the directory path constructed from the + metagraph's current ``network`` and ``netuid`` properties. This abstraction simplifies the process of loading + the metagraph's state for the user, requiring no direct path specifications. Args: root_dir: list to the file path for the root directory of your metagraph saves (i.e. ['/', 'tmp', 'metagraphs'], defaults to ["~", ".bittensor", "metagraphs"] Returns: - metagraph (bittensor.core.metagraph.Metagraph): The metagraph instance after loading its state from the default directory. + metagraph (bittensor.core.metagraph.Metagraph): The metagraph instance after loading its state from the + default directory. Example: Load the metagraph state from the last saved snapshot in the default directory:: metagraph.load() - After this operation, the metagraph's parameters and neuron data are restored to their state at the time of the last save in the default directory. + After this operation, the metagraph's parameters and neuron data are restored to their state at the time of + the last save in the default directory. Note: - The default save directory is determined based on the metagraph's ``network`` and ``netuid`` attributes. It is important to ensure that these attributes are set correctly and that the default save directory contains the appropriate state files for the metagraph. + The default save directory is determined based on the metagraph's ``network`` and ``netuid`` attributes. It + is important to ensure that these attributes are set correctly and that the default save directory contains + the appropriate state files for the metagraph. """ self.load_from_path(get_save_dir(self.network, self.netuid, root_dir=root_dir)) @@ -1421,8 +1430,8 @@ def load_from_path(self, dir_path: str) -> "AsyncMetagraph": dir_path (str): The directory path where the metagraph's state file is located. Returns: - metagraph (:func:`bittensor.core.metagraph.AsyncMetagraph`): An instance of the Metagraph with the state loaded - from the file. + metagraph (:func:`bittensor.core.metagraph.AsyncMetagraph`): An instance of the Metagraph with the state + loaded from the file. Raises: pickle.UnpicklingError: If there is an error unpickling the state file. diff --git a/bittensor/core/settings.py b/bittensor/core/settings.py index 04d94436ef..3786fd783f 100644 --- a/bittensor/core/settings.py +++ b/bittensor/core/settings.py @@ -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. - __version__ = "8.5.1" import os @@ -38,9 +21,6 @@ # Bittensor networks name NETWORKS = ["finney", "test", "archive", "local", "subvortex"] -DEFAULT_ENDPOINT = "wss://entrypoint-finney.opentensor.ai:443" -DEFAULT_NETWORK = NETWORKS[0] - # Bittensor endpoints (Needs to use wss://) FINNEY_ENTRYPOINT = "wss://entrypoint-finney.opentensor.ai:443" FINNEY_TEST_ENTRYPOINT = "wss://test.finney.opentensor.ai:443" @@ -64,6 +44,9 @@ SUBVORTEX_ENTRYPOINT: NETWORKS[4], } +DEFAULT_ENDPOINT = FINNEY_ENTRYPOINT +DEFAULT_NETWORK = NETWORKS[0] + # Currency Symbols Bittensor TAO_SYMBOL: str = chr(0x03C4) RAO_SYMBOL: str = chr(0x03C1) diff --git a/bittensor/core/stream.py b/bittensor/core/stream.py index 9e880ffa87..628a459501 100644 --- a/bittensor/core/stream.py +++ b/bittensor/core/stream.py @@ -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. - from abc import ABC, abstractmethod from typing import Callable, Awaitable, Optional @@ -28,9 +11,10 @@ class BTStreamingResponseModel(BaseModel): """ - :func:`BTStreamingResponseModel` is a Pydantic model that encapsulates the token streamer callable for Pydantic validation. - It is used within the :func:`StreamingSynapse` class to create a :func:`BTStreamingResponse` object, which is responsible for handling - the streaming of tokens. + :func:`BTStreamingResponseModel` is a Pydantic model that encapsulates the token streamer callable for Pydantic + validation. + It is used within the :func:`StreamingSynapse` class to create a :func:`BTStreamingResponse` object, which is + responsible for handling the streaming of tokens. The token streamer is a callable that takes a send function and returns an awaitable. It is responsible for generating the content of the streaming response, typically by processing tokens and sending them to the client. @@ -39,7 +23,9 @@ class BTStreamingResponseModel(BaseModel): passing the token streamer to the BTStreamingResponse class. Attributes: - token_streamer: Callable[[Send], Awaitable[None]] The token streamer callable, which takes a send function (provided by the ASGI server) and returns an awaitable. It is responsible for generating the content of the streaming response. + token_streamer: Callable[[Send], Awaitable[None]] The token streamer callable, which takes a send function + (provided by the ASGI server) and returns an awaitable. It is responsible for generating the content of the + streaming response. """ token_streamer: Callable[[Send], Awaitable[None]] @@ -56,13 +42,13 @@ class StreamingSynapse(Synapse, ABC): class BTStreamingResponse(_StreamingResponse): """ - :func:`BTStreamingResponse` is a specialized subclass of the Starlette StreamingResponse designed to handle the streaming - of tokens within the Bittensor network. It is used internally by the StreamingSynapse class to manage the response - streaming process, including sending headers and calling the token streamer provided by the subclass. + :func:`BTStreamingResponse` is a specialized subclass of the Starlette StreamingResponse designed to handle the + streaming of tokens within the Bittensor network. It is used internally by the StreamingSynapse class to manage + the response streaming process, including sending headers and calling the token streamer provided by the subclass. This class is not intended to be directly instantiated or modified by developers subclassing StreamingSynapse. - Instead, it is used by the :func:`create_streaming_response` method to create a response object based on the token streamer - provided by the subclass. + Instead, it is used by the :func:`create_streaming_response` method to create a response object based on the + token streamer provided by the subclass. """ def __init__( @@ -76,8 +62,10 @@ def __init__( Initializes the BTStreamingResponse with the given token streamer model. Args: - model (bittensor.core.stream.BTStreamingResponseModel): A BTStreamingResponseModel instance containing the token streamer callable, which is responsible for generating the content of the response. - synapse (bittensor.core.stream.StreamingSynapse): The response Synapse to be used to update the response headers etc. + model (bittensor.core.stream.BTStreamingResponseModel): A BTStreamingResponseModel instance containing + the token streamer callable, which is responsible for generating the content of the response. + synapse (bittensor.core.stream.StreamingSynapse): The response Synapse to be used to update the response + headers etc. **kwargs: Additional keyword arguments passed to the parent StreamingResponse class. """ super().__init__(content=iter(()), **kwargs) @@ -88,7 +76,9 @@ async def stream_response(self, send: "Send"): """ Asynchronously streams the response by sending headers and calling the token streamer. - This method is responsible for initiating the response by sending the appropriate headers, including the content type for event-streaming. It then calls the token streamer to generate the content and sends the response body to the client. + This method is responsible for initiating the response by sending the appropriate headers, including the + content type for event-streaming. It then calls the token streamer to generate the content and sends the + response body to the client. Args: send (starlette.types.Send): A callable to send the response, provided by the ASGI server. @@ -105,12 +95,15 @@ async def stream_response(self, send: "Send"): async def __call__(self, scope: "Scope", receive: "Receive", send: "Send"): """ - Asynchronously calls the :func:`stream_response method`, allowing the :func:`BTStreamingResponse` object to be used as an ASGI application. + Asynchronously calls the :func:`stream_response method`, allowing the :func:`BTStreamingResponse` object to + be used as an ASGI application. - This method is part of the ASGI interface and is called by the ASGI server to handle the request and send the response. It delegates to the :func:`stream_response` method to perform the actual streaming process. + This method is part of the ASGI interface and is called by the ASGI server to handle the request and send + the response. It delegates to the :func:`stream_response` method to perform the actual streaming process. Args: - scope (starlette.types.Scope): The scope of the request, containing information about the client, server, and request itself. + scope (starlette.types.Scope): The scope of the request, containing information about the client, + server, and request itself. receive (starlette.types.Receive): A callable to receive the request, provided by the ASGI server. send (starlette.types.Send): A callable to send the response, provided by the ASGI server. """ @@ -121,7 +114,8 @@ async def process_streaming_response(self, response: "ClientResponse"): """ Abstract method that must be implemented by the subclass. This method should provide logic to handle the streaming response, such as parsing and accumulating data. - It is called as the response is being streamed from the network, and should be implemented to handle the specific streaming data format and requirements of the subclass. + It is called as the response is being streamed from the network, and should be implemented to handle the + specific streaming data format and requirements of the subclass. Args: response (aiohttp.ClientResponse): The response object to be processed, typically containing chunks of data. @@ -133,7 +127,8 @@ def extract_response_json(self, response: "ClientResponse") -> dict: """ Abstract method that must be implemented by the subclass. This method should provide logic to extract JSON data from the response, including headers and content. - It is called after the response has been processed and is responsible for retrieving structured data that can be used by the application. + It is called after the response has been processed and is responsible for retrieving structured data that can be + used by the application. Args: response (aiohttp.ClientResponse): The response object from which to extract JSON data. @@ -145,13 +140,16 @@ def create_streaming_response( """ Creates a streaming response using the provided token streamer. This method can be used by the subclass to create a response object that can be sent back to the client. - The token streamer should be implemented to generate the content of the response according to the specific requirements of the subclass. + The token streamer should be implemented to generate the content of the response according to the specific + requirements of the subclass. Args: - token_streamer (Callable[[starlette.types.Send], Awaitable[None]]): A callable that takes a send function and returns an awaitable. It's responsible for generating the content of the response. + token_streamer (Callable[[starlette.types.Send], Awaitable[None]]): A callable that takes a send function + and returns an awaitable. It's responsible for generating the content of the response. Returns: - BTStreamingResponse (bittensor.core.stream.StreamingSynapse.BTStreamingResponse): The streaming response object, ready to be sent to the client. + BTStreamingResponse (bittensor.core.stream.StreamingSynapse.BTStreamingResponse): The streaming response + object, ready to be sent to the client. """ model_instance = BTStreamingResponseModel(token_streamer=token_streamer) diff --git a/bittensor/core/synapse.py b/bittensor/core/synapse.py index a96a92e1a1..253e899878 100644 --- a/bittensor/core/synapse.py +++ b/bittensor/core/synapse.py @@ -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 base64 import json import sys @@ -103,7 +86,8 @@ class TerminalInfo(BaseModel): TerminalInfo encapsulates detailed information about a network synapse (node) involved in a communication process. This class serves as a metadata carrier, - providing essential details about the state and configuration of a terminal during network interactions. This is a crucial class in the Bittensor framework. + providing essential details about the state and configuration of a terminal during network interactions. This is a + crucial class in the Bittensor framework. The TerminalInfo class contains information such as HTTP status codes and messages, processing times, IP addresses, ports, Bittensor version numbers, and unique identifiers. These details are vital for @@ -114,16 +98,23 @@ class TerminalInfo(BaseModel): is used as a helper class for Synapses. Args: - status_code (int): HTTP status code indicating the result of a network request. Essential for identifying the outcome of network interactions. - status_message (str): Descriptive message associated with the status code, providing additional context about the request's result. - process_time (float): Time taken by the terminal to process the call, important for performance monitoring and optimization. + status_code (int): HTTP status code indicating the result of a network request. Essential for identifying the + outcome of network interactions. + status_message (str): Descriptive message associated with the status code, providing additional context about + the request's result. + process_time (float): Time taken by the terminal to process the call, important for performance monitoring and + optimization. ip (str): IP address of the terminal, crucial for network routing and data transmission. port (int): Network port used by the terminal, key for establishing network connections. - version (int): Bittensor version running on the terminal, ensuring compatibility between different nodes in the network. - nonce (int): Unique, monotonically increasing number for each terminal, aiding in identifying and ordering network interactions. + version (int): Bittensor version running on the terminal, ensuring compatibility between different nodes in the + network. + nonce (int): Unique, monotonically increasing number for each terminal, aiding in identifying and ordering + network interactions. uuid (str): Unique identifier for the terminal, fundamental for network security and identification. - hotkey (str): Encoded hotkey string of the terminal wallet, important for transaction and identity verification in the network. - signature (str): Digital signature verifying the tuple of nonce, axon_hotkey, dendrite_hotkey, and uuid, critical for ensuring data authenticity and security. + hotkey (str): Encoded hotkey string of the terminal wallet, important for transaction and identity verification + in the network. + signature (str): Digital signature verifying the tuple of nonce, axon_hotkey, dendrite_hotkey, and uuid, + critical for ensuring data authenticity and security. Usage:: @@ -147,9 +138,11 @@ class TerminalInfo(BaseModel): ip_address = terminal_info.ip processing_duration = terminal_info.process_time - # TerminalInfo can be used to monitor and verify network interactions, ensuring proper communication and security within the Bittensor network. + # TerminalInfo can be used to monitor and verify network interactions, ensuring proper communication and + security within the Bittensor network. - TerminalInfo plays a pivotal role in providing transparency and control over network operations, making it an indispensable tool for developers and users interacting with the Bittensor ecosystem. + TerminalInfo plays a pivotal role in providing transparency and control over network operations, making it an + indispensable tool for developers and users interacting with the Bittensor ecosystem. """ model_config = ConfigDict(validate_assignment=True) @@ -387,7 +380,9 @@ def deserialize(self) -> "Synapse": By default, if a subclass does not provide its own implementation of this method, the Synapse's deserialize method will be used, returning the object instance as-is. - In its default form, this method simply returns the instance of the Synapse itself without any modifications. Subclasses of Synapse can override this method to add specific deserialization behaviors, such as converting serialized data back into complex object types or performing additional data integrity checks. + In its default form, this method simply returns the instance of the Synapse itself without any modifications. + Subclasses of Synapse can override this method to add specific deserialization behaviors, such as converting + serialized data back into complex object types or performing additional data integrity checks. Example:: @@ -602,10 +597,13 @@ def to_headers(self) -> dict: Process: - 1. Basic Information: It starts by including the ``name`` and ``timeout`` of the Synapse, which are fundamental for identifying the query and managing its lifespan on the network. - 2. Complex Objects: The method serializes the ``axon`` and ``dendrite`` objects, if present, into strings. This serialization is crucial for preserving the state and structure of these objects over the network. + 1. Basic Information: It starts by including the ``name`` and ``timeout`` of the Synapse, which are fundamental + for identifying the query and managing its lifespan on the network. + 2. Complex Objects: The method serializes the ``axon`` and ``dendrite`` objects, if present, into strings. This + serialization is crucial for preserving the state and structure of these objects over the network. 3. Encoding: Non-optional complex objects are serialized and encoded in base64, making them safe for HTTP transport. - 4. Size Metrics: The method calculates and adds the size of headers and the total object size, providing valuable information for network bandwidth management. + 4. Size Metrics: The method calculates and adds the size of headers and the total object size, providing + valuable information for network bandwidth management. Example Usage:: @@ -614,7 +612,8 @@ def to_headers(self) -> dict: # headers now contains a dictionary representing the Synapse instance Returns: - dict: A dictionary containing key-value pairs representing the Synapse's properties, suitable for HTTP communication. + dict: A dictionary containing key-value pairs representing the Synapse's properties, suitable for HTTP + communication. """ # Initializing headers with 'name' and 'timeout' headers = {"name": self.name, "timeout": str(self.timeout)} @@ -691,7 +690,8 @@ def body_hash(self) -> str: # hash_value is the SHA3-256 hash of the serialized body of the Synapse instance Returns: - str: The SHA3-256 hash as a hexadecimal string, providing a fingerprint of the Synapse instance's data for integrity checks. + str: The SHA3-256 hash as a hexadecimal string, providing a fingerprint of the Synapse instance's data for + integrity checks. """ hashes = [] @@ -729,7 +729,8 @@ def body_hash(self) -> str: @classmethod def parse_headers_to_inputs(cls, headers: dict) -> dict: """ - Interprets and transforms a given dictionary of headers into a structured dictionary, facilitating the reconstruction of Synapse objects. + Interprets and transforms a given dictionary of headers into a structured dictionary, facilitating the + reconstruction of Synapse objects. This method is essential for parsing network-transmitted data back into a Synapse instance, ensuring data consistency and integrity. @@ -751,7 +752,8 @@ def parse_headers_to_inputs(cls, headers: dict) -> dict: # inputs now contains a structured representation of Synapse properties based on the headers Note: - This is handled automatically when calling :func:`Synapse.from_headers(headers)` and does not need to be called directly. + This is handled automatically when calling :func:`Synapse.from_headers(headers)` and does not need to be + called directly. Args: headers (dict): The headers dictionary to parse. @@ -820,7 +822,8 @@ def parse_headers_to_inputs(cls, headers: dict) -> dict: @classmethod def from_headers(cls, headers: dict) -> "Synapse": """ - Constructs a new Synapse instance from a given headers dictionary, enabling the re-creation of the Synapse's state as it was prior to network transmission. + Constructs a new Synapse instance from a given headers dictionary, enabling the re-creation of the Synapse's + state as it was prior to network transmission. This method is a key part of the deserialization process in the Bittensor network, allowing nodes to accurately reconstruct Synapse @@ -840,7 +843,8 @@ def from_headers(cls, headers: dict) -> "Synapse": headers (dict): The dictionary of headers containing serialized Synapse information. Returns: - bittensor.core.synapse.Synapse: A new instance of Synapse, reconstructed from the parsed header information, replicating the original instance's state. + bittensor.core.synapse.Synapse: A new instance of Synapse, reconstructed from the parsed header information, + replicating the original instance's state. """ # Get the inputs dictionary from the headers diff --git a/bittensor/core/tensor.py b/bittensor/core/tensor.py index 4ec71cc44f..5cafd0986a 100644 --- a/bittensor/core/tensor.py +++ b/bittensor/core/tensor.py @@ -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 base64 from typing import Optional, Union diff --git a/bittensor/core/types.py b/bittensor/core/types.py index 908e384015..75092c4328 100644 --- a/bittensor/core/types.py +++ b/bittensor/core/types.py @@ -1,21 +1,5 @@ -# 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. - from typing import TypedDict, Optional + from bittensor.utils import Certificate diff --git a/bittensor/utils/axon_utils.py b/bittensor/utils/axon_utils.py index d042358246..b24f4b6be7 100644 --- a/bittensor/utils/axon_utils.py +++ b/bittensor/utils/axon_utils.py @@ -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. - from typing import Optional ALLOWED_DELTA = 4_000_000_000 # Delta of 4 seconds for nonce validation diff --git a/bittensor/utils/balance.py b/bittensor/utils/balance.py index a22cdb8703..a5ba744ae6 100644 --- a/bittensor/utils/balance.py +++ b/bittensor/utils/balance.py @@ -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. - from typing import Union from bittensor.core import settings diff --git a/bittensor/utils/btlogging/__init__.py b/bittensor/utils/btlogging/__init__.py index a5e6d2518c..9fee61cd80 100644 --- a/bittensor/utils/btlogging/__init__.py +++ b/bittensor/utils/btlogging/__init__.py @@ -1,24 +1,8 @@ -# 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. - """ btlogging sub-package standardized logging for Bittensor. -This module provides logging functionality for the Bittensor package. It includes custom loggers, handlers, and formatters to ensure consistent logging throughout the project. +This module provides logging functionality for the Bittensor package. It includes custom loggers, handlers, and +formatters to ensure consistent logging throughout the project. """ from .loggingmachine import LoggingMachine diff --git a/bittensor/utils/btlogging/console.py b/bittensor/utils/btlogging/console.py index b169ac1be9..20e09bdf60 100644 --- a/bittensor/utils/btlogging/console.py +++ b/bittensor/utils/btlogging/console.py @@ -15,8 +15,9 @@ logging.info("test info") """ -from typing import Callable, TYPE_CHECKING from functools import wraps +from typing import Callable, TYPE_CHECKING + from .helpers import all_loggers if TYPE_CHECKING: diff --git a/bittensor/utils/btlogging/defines.py b/bittensor/utils/btlogging/defines.py index 9e1dada25b..f71a99e702 100644 --- a/bittensor/utils/btlogging/defines.py +++ b/bittensor/utils/btlogging/defines.py @@ -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. - """Btlogging constant definition module.""" BASE_LOG_FORMAT = "%(asctime)s | %(levelname)s | %(message)s" diff --git a/bittensor/utils/btlogging/format.py b/bittensor/utils/btlogging/format.py index ebb353525f..989a49b925 100644 --- a/bittensor/utils/btlogging/format.py +++ b/bittensor/utils/btlogging/format.py @@ -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. - """ btlogging.format module diff --git a/bittensor/utils/btlogging/helpers.py b/bittensor/utils/btlogging/helpers.py index 3fdca4ee04..266a67b25d 100644 --- a/bittensor/utils/btlogging/helpers.py +++ b/bittensor/utils/btlogging/helpers.py @@ -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. - """ btlogging.helpers module provides helper functions for the Bittensor logging system. """ diff --git a/bittensor/utils/btlogging/loggingmachine.py b/bittensor/utils/btlogging/loggingmachine.py index 92fc80217d..24a714b35a 100644 --- a/bittensor/utils/btlogging/loggingmachine.py +++ b/bittensor/utils/btlogging/loggingmachine.py @@ -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. - """ Module provides a logging framework for Bittensor, managing both Bittensor-specific and third-party logging states. It leverages the StateMachine from the statemachine package to transition between different logging states such as @@ -34,6 +17,7 @@ from statemachine import State, StateMachine from bittensor.core.config import Config +from bittensor.utils.btlogging.console import BittensorConsole from .defines import ( BITTENSOR_LOGGER_NAME, DATE_FORMAT, @@ -44,7 +28,6 @@ ) from .format import BtFileFormatter, BtStreamFormatter from .helpers import all_loggers -from bittensor.utils.btlogging.console import BittensorConsole # https://github.com/python/cpython/issues/97941 CUSTOM_LOGGER_METHOD_STACK_LEVEL = 2 if sys.version_info >= (3, 11) else 1 diff --git a/bittensor/utils/deprecated.py b/bittensor/utils/deprecated.py index ce534f922c..0e6b5d327b 100644 --- a/bittensor/utils/deprecated.py +++ b/bittensor/utils/deprecated.py @@ -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. - """ The Bittensor Compatibility Module is designed to ensure seamless integration and functionality with legacy versions of the Bittensor framework, specifically up to and including version 7.3.0. This module addresses changes and deprecated @@ -24,6 +7,7 @@ import importlib import sys +from bittensor_wallet import Keypair # noqa: F401 from bittensor_wallet.errors import KeyFileError # noqa: F401 from bittensor_wallet.keyfile import ( # noqa: F401 serialized_keypair_to_keyfile_data, @@ -42,7 +26,6 @@ Keyfile, ) from bittensor_wallet.wallet import display_mnemonic_msg, Wallet # noqa: F401 -from bittensor_wallet import Keypair # noqa: F401 from bittensor.core import settings from bittensor.core.async_subtensor import AsyncSubtensor @@ -112,8 +95,8 @@ get_hash, ) from bittensor.utils.balance import Balance as Balance # noqa: F401 -from bittensor.utils.mock.subtensor_mock import MockSubtensor as MockSubtensor # noqa: F401 from bittensor.utils.btlogging import logging +from bittensor.utils.mock.subtensor_mock import MockSubtensor as MockSubtensor # noqa: F401 from bittensor.utils.subnets import SubnetsAPI # noqa: F401 # Backwards compatibility with previous bittensor versions. diff --git a/bittensor/utils/formatting.py b/bittensor/utils/formatting.py index 1ee3fd6671..02023e189e 100644 --- a/bittensor/utils/formatting.py +++ b/bittensor/utils/formatting.py @@ -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 math diff --git a/bittensor/utils/mock/__init__.py b/bittensor/utils/mock/__init__.py index 218579a153..04893c78a3 100644 --- a/bittensor/utils/mock/__init__.py +++ b/bittensor/utils/mock/__init__.py @@ -1,18 +1 @@ -# The MIT License (MIT) -# Copyright © 2023 Opentensor Technologies Inc - -# 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 .subtensor_mock import MockSubtensor diff --git a/bittensor/utils/networking.py b/bittensor/utils/networking.py index c8a943e708..e8edf1ef49 100644 --- a/bittensor/utils/networking.py +++ b/bittensor/utils/networking.py @@ -143,7 +143,8 @@ def get_formatted_ws_endpoint_url(endpoint_url: Optional[str]) -> Optional[str]: endpoint_url (Optional[str]): The endpoint url to format. Returns: - formatted_endpoint_url (Optional[str]): The formatted endpoint url. In the form of ws:// or wss:// + formatted_endpoint_url (Optional[str]): The formatted endpoint url. In the form of ws:// or + wss:// """ if endpoint_url is None: return None diff --git a/bittensor/utils/registration.py b/bittensor/utils/registration.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/bittensor/utils/registration/async_pow.py b/bittensor/utils/registration/async_pow.py index e02e8c7bb8..ebdce4bc72 100644 --- a/bittensor/utils/registration/async_pow.py +++ b/bittensor/utils/registration/async_pow.py @@ -38,7 +38,8 @@ async def _get_block_with_retry( Gets the current block number, difficulty, and block hash from the substrate node. Args: - subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor object to use to get the block number, difficulty, and block hash. + subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor object to use to get the block number, + difficulty, and block hash. netuid (int): The netuid of the network to get the block number, difficulty, and block hash from. Returns: @@ -364,13 +365,15 @@ async def _solve_for_difficulty_fast_cuda( Solves the registration fast using CUDA Args: - subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor object to use to get the block number, difficulty, and block hash. + subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor object to use to get the block number, + difficulty, and block hash. wallet (bittensor_wallet.Wallet): The wallet to register netuid (int): The netuid of the subnet to register to. output_in_place (bool): If true, prints the output in place, otherwise prints to new lines update_interval (int): The number of nonces to try before checking for more blocks tpb (int): The number of threads per block. CUDA param that should match the GPU capability - dev_id (Union[list[int], int]): The CUDA device IDs to execute the registration on, either a single device or a list of devices + dev_id (Union[list[int], int]): The CUDA device IDs to execute the registration on, either a single device or a + list of devices n_samples (int): The number of samples of the hash_rate to keep for the EWMA alpha_ (float): The alpha for the EWMA for the hash_rate calculation log_verbose (bool): If true, prints more verbose logging of the registration metrics. @@ -431,7 +434,8 @@ async def _solve_for_difficulty_fast( Solves the POW for registration using multiprocessing. Args: - subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor object to use to get the block number, difficulty, and block hash. + subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor object to use to get the block number, + difficulty, and block hash. wallet (bittensor_wallet.Wallet): wallet to use for registration. netuid (int): The netuid of the subnet to register to. output_in_place (bool): If true, prints the status in place. Otherwise, prints the status on a new line. @@ -443,7 +447,8 @@ async def _solve_for_difficulty_fast( Notes: The hash rate is calculated as an exponentially weighted moving average in order to make the measure more robust. - We can also modify the update interval to do smaller blocks of work, while still updating the block information after a different number of nonces, to increase the transparency of the process while still keeping the speed. + We can also modify the update interval to do smaller blocks of work, while still updating the block information + after a different number of nonces, to increase the transparency of the process while still keeping the speed. """ if not num_processes: # get the number of allowed processes for this process @@ -491,14 +496,17 @@ async def create_pow_async( Creates a proof of work for the given subtensor and wallet. Args: - subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor object to use to get the block number, difficulty, and block hash. + subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The subtensor instance. wallet (bittensor_wallet.Wallet): The wallet to create a proof of work for. netuid (int): The netuid for the subnet to create a proof of work for. - output_in_place (bool): If true, prints the progress of the proof of work to the console in-place. Meaning the progress is printed on the same lines. + output_in_place (bool): If true, prints the progress of the proof of work to the console in-place. Meaning the + progress is printed on the same lines. cuda (bool): If true, uses CUDA to solve the proof of work. - dev_id (Union[list[int], int]): The CUDA device id(s) to use. If cuda is true and dev_id is a list, then multiple CUDA devices will be used to solve the proof of work. + dev_id (Union[list[int], int]): The CUDA device id(s) to use. If cuda is true and dev_id is a list, then + multiple CUDA devices will be used to solve the proof of work. tpb (int): The number of threads per block to use when solving the proof of work. Should be a multiple of 32. - num_processes (int): The number of processes to use when solving the proof of work. If None, then the number of processes is equal to the number of CPU cores. + num_processes (int): The number of processes to use when solving the proof of work. If None, then the number of + processes is equal to the number of CPU cores. update_interval (int): The number of nonces to run before checking for a new block. log_verbose (bool): If true, prints the progress of the proof of work more verbosely. diff --git a/bittensor/utils/registration/pow.py b/bittensor/utils/registration/pow.py index c96295b0cd..1eac5d255e 100644 --- a/bittensor/utils/registration/pow.py +++ b/bittensor/utils/registration/pow.py @@ -1,7 +1,6 @@ """This module provides utilities for solving Proof-of-Work (PoW) challenges in Bittensor network.""" import binascii -from dataclasses import dataclass import functools import hashlib import math @@ -10,6 +9,7 @@ import random import subprocess import time +from dataclasses import dataclass from datetime import timedelta from multiprocessing.queues import Queue as QueueType from queue import Empty, Full @@ -113,7 +113,9 @@ def _create_seal_hash(block_and_hotkey_hash_bytes: bytes, nonce: int) -> bytes: Create a cryptographic seal hash from the given block and hotkey hash bytes and nonce. This function generates a seal hash by combining the given block and hotkey hash bytes with a nonce. - It first converts the nonce to a byte representation, then concatenates it with the first 64 hex characters of the block and hotkey hash bytes. The result is then hashed using SHA-256 followed by the Keccak-256 algorithm to produce the final seal hash. + It first converts the nonce to a byte representation, then concatenates it with the first 64 hex characters of the + block and hotkey hash bytes. The result is then hashed using SHA-256 followed by the Keccak-256 algorithm to produce + the final seal hash. Args: block_and_hotkey_hash_bytes (bytes): The combined hash bytes of the block and hotkey. @@ -189,13 +191,23 @@ class _SolverBase(mp.Process): proc_num (int): The number of the process being created. num_proc (int): The total number of processes running. update_interval (int): The number of nonces to try to solve before checking for a new block. - finished_queue (multiprocessing.Queue): The queue to put the process number when a process finishes each update_interval. Used for calculating the average time per update_interval across all processes. + finished_queue (multiprocessing.Queue): The queue to put the process number when a process finishes each + update_interval. Used for calculating the average time per update_interval across all processes. solution_queue (multiprocessing.Queue): The queue to put the solution the process has found during the pow solve. - stopEvent (multiprocessing.Event): The event to set by the main process when all the solver processes should stop. The solver process will check for the event after each update_interval. The solver process will stop when the event is set. Used to stop the solver processes when a solution is found. - curr_block (multiprocessing.Array): The array containing this process's current block hash. The main process will set the array to the new block hash when a new block is finalized in the network. The solver process will get the new block hash from this array when newBlockEvent is set. - curr_block_num (multiprocessing.Value): The value containing this process's current block number. The main process will set the value to the new block number when a new block is finalized in the network. The solver process will get the new block number from this value when newBlockEvent is set. - curr_diff (multiprocessing.Array): The array containing this process's current difficulty. The main process will set the array to the new difficulty when a new block is finalized in the network. The solver process will get the new difficulty from this array when newBlockEvent is set. - check_block (multiprocessing.Lock): The lock to prevent this process from getting the new block data while the main process is updating the data. + stopEvent (multiprocessing.Event): The event to set by the main process when all the solver processes should + stop. The solver process will check for the event after each update_interval. The solver process will stop + when the event is set. Used to stop the solver processes when a solution is found. + curr_block (multiprocessing.Array): The array containing this process's current block hash. The main process + will set the array to the new block hash when a new block is finalized in the network. The solver process + will get the new block hash from this array when newBlockEvent is set. + curr_block_num (multiprocessing.Value): The value containing this process's current block number. The main + process will set the value to the new block number when a new block is finalized in the network. The + solver process will get the new block number from this value when newBlockEvent is set. + curr_diff (multiprocessing.Array): The array containing this process's current difficulty. The main process will + set the array to the new difficulty when a new block is finalized in the network. The solver process will + get the new difficulty from this array when newBlockEvent is set. + check_block (multiprocessing.Lock): The lock to prevent this process from getting the new block data while the + main process is updating the data. limit (int): The limit of the pow solve for a valid solution. """ @@ -458,7 +470,8 @@ def update_curr_block( """ Update the current block data with the provided block information and difficulty. - This function updates the current block and its difficulty in a thread-safe manner. It sets the current block number, hashes the block with the hotkey, updates the current block bytes, and packs the difficulty. + This function updates the current block and its difficulty in a thread-safe manner. It sets the current block + number, hashes the block with the hotkey, updates the current block bytes, and packs the difficulty. Arguments: curr_diff: Shared array to store the current difficulty. @@ -575,7 +588,7 @@ def _solve_for_difficulty_fast( Solves the POW for registration using multiprocessing. Args: - subtensor (bittensor.core.subtensor.Subtensor): Subtensor instance to connect to for block information and to submit. + subtensor (bittensor.core.subtensor.Subtensor): Subtensor instance. wallet (bittensor_wallet.Wallet): wallet to use for registration. netuid (int): The netuid of the subnet to register to. output_in_place (bool): If true, prints the status in place. Otherwise, prints the status on a new line. @@ -585,8 +598,11 @@ def _solve_for_difficulty_fast( alpha_ (float): The alpha for the EWMA for the hash_rate calculation. log_verbose (bool): If true, prints more verbose logging of the registration metrics. - Note: The hash rate is calculated as an exponentially weighted moving average in order to make the measure more robust. - Note: We can also modify the update interval to do smaller blocks of work, while still updating the block information after a different number of nonces, to increase the transparency of the process while still keeping the speed. + Note: The hash rate is calculated as an exponentially weighted moving average in order to make the measure more + robust. + Note: We can also modify the update interval to do smaller blocks of work, while still updating the block + information after a different number of nonces, to increase the transparency of the process while still + keeping the speed. """ if num_processes is None: # get the number of allowed processes for this process @@ -763,7 +779,7 @@ def _get_block_with_retry(subtensor: "Subtensor", netuid: int) -> tuple[int, int Gets the current block number, difficulty, and block hash from the substrate node. Args: - subtensor (bittensor.core.subtensor.Subtensor): The subtensor object to use to get the block number, difficulty, and block hash. + subtensor (bittensor.core.subtensor.Subtensor): The subtensor instance. netuid (int): The netuid of the network to get the block number, difficulty, and block hash from. Returns: @@ -874,7 +890,8 @@ def _solve_for_difficulty_fast_cuda( output_in_place (bool) If true, prints the output in place, otherwise prints to new lines. update_interval (int): The number of nonces to try before checking for more blocks. tpb (int): The number of threads per block. CUDA param that should match the GPU capability - dev_id (Union[list[int], int]): The CUDA device IDs to execute the registration on, either a single device or a list of devices. + dev_id (Union[list[int], int]): The CUDA device IDs to execute the registration on, either a single device or a + list of devices. n_samples (int): The number of samples of the hash_rate to keep for the EWMA. alpha_ (float): The alpha for the EWMA for the hash_rate calculation. log_verbose (bool): If true, prints more verbose logging of the registration metrics. @@ -1096,16 +1113,21 @@ def create_pow( subtensor (bittensor.core.subtensor.Subtensor): The subtensor to create a proof of work for. wallet (bittensor_wallet.Wallet): The wallet to create a proof of work for. netuid (int): The netuid for the subnet to create a proof of work for. - output_in_place (bool): If true, prints the progress of the proof of work to the console in-place. Meaning the progress is printed on the same lines. Default is ``True``. + output_in_place (bool): If true, prints the progress of the proof of work to the console in-place. Meaning the + progress is printed on the same lines. Default is ``True``. cuda (bool): If true, uses CUDA to solve the proof of work. Default is ``False``. - dev_id (Union[List[int], int]): The CUDA device id(s) to use. If cuda is true and dev_id is a list, then multiple CUDA devices will be used to solve the proof of work. Default is ``0``. - tpb (int): The number of threads per block to use when solving the proof of work. Should be a multiple of 32. Default is ``256``. - num_processes (Optional[int]): The number of processes to use when solving the proof of work. If None, then the number of processes is equal to the number of CPU cores. Default is None. + dev_id (Union[List[int], int]): The CUDA device id(s) to use. If cuda is true and dev_id is a list, then + multiple CUDA devices will be used to solve the proof of work. Default is ``0``. + tpb (int): The number of threads per block to use when solving the proof of work. Should be a multiple of 32. + Default is ``256``. + num_processes (Optional[int]): The number of processes to use when solving the proof of work. If None, then the + number of processes is equal to the number of CPU cores. Default is None. update_interval (Optional[int]): The number of nonces to run before checking for a new block. Default is ``None``. log_verbose (bool): If true, prints the progress of the proof of work more verbosely. Default is ``False``. Returns: - Optional[Dict[str, Any]]: The proof of work solution or None if the wallet is already registered or there is a different error. + Optional[Dict[str, Any]]: The proof of work solution or None if the wallet is already registered or there is a + different error. Raises: ValueError: If the subnet does not exist. diff --git a/bittensor/utils/registration/register_cuda.py b/bittensor/utils/registration/register_cuda.py index 756250f068..b46dab9f0c 100644 --- a/bittensor/utils/registration/register_cuda.py +++ b/bittensor/utils/registration/register_cuda.py @@ -64,7 +64,8 @@ def solve_cuda( dev_id (int): The CUDA device ID. Defaults to ``0``. Returns: - (Union[tuple[Any, bytes], tuple[int, bytes], tuple[Any, None]]): Tuple of the nonce and the seal corresponding to the solution. Returns -1 for nonce if no solution is found. + (Union[tuple[Any, bytes], tuple[int, bytes], tuple[Any, None]]): Tuple of the nonce and the seal corresponding + to the solution. Returns -1 for nonce if no solution is found. """ try: diff --git a/bittensor/utils/subnets.py b/bittensor/utils/subnets.py index 2b42bead98..d92a4f58f3 100644 --- a/bittensor/utils/subnets.py +++ b/bittensor/utils/subnets.py @@ -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. - from abc import ABC, abstractmethod from typing import Any, Union, Optional, TYPE_CHECKING diff --git a/bittensor/utils/substrate_utils/hasher.py b/bittensor/utils/substrate_utils/hasher.py index cbeefd9a34..0075bb69dd 100644 --- a/bittensor/utils/substrate_utils/hasher.py +++ b/bittensor/utils/substrate_utils/hasher.py @@ -1,6 +1,7 @@ """Helper functions used to calculate keys for Substrate storage items""" from hashlib import blake2b + import xxhash diff --git a/bittensor/utils/substrate_utils/storage.py b/bittensor/utils/substrate_utils/storage.py index 6c1f617cbe..b5e95296e5 100644 --- a/bittensor/utils/substrate_utils/storage.py +++ b/bittensor/utils/substrate_utils/storage.py @@ -1,10 +1,10 @@ import binascii from typing import Any, Optional -from bittensor.core.errors import StorageFunctionNotFound - from scalecodec import ScaleBytes, GenericMetadataVersioned, ss58_decode from scalecodec.base import ScaleDecoder, RuntimeConfigurationObject, ScaleType + +from bittensor.core.errors import StorageFunctionNotFound from bittensor.utils.substrate_utils.hasher import ( blake2_256, two_x64_concat, diff --git a/bittensor/utils/version.py b/bittensor/utils/version.py index 1134361ade..040a46a311 100644 --- a/bittensor/utils/version.py +++ b/bittensor/utils/version.py @@ -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 time from pathlib import Path from typing import Optional diff --git a/bittensor/utils/weight_utils.py b/bittensor/utils/weight_utils.py index dc31184476..a93f584728 100644 --- a/bittensor/utils/weight_utils.py +++ b/bittensor/utils/weight_utils.py @@ -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. - """Conversion for weight between chain representation and np.array or torch.Tensor""" import hashlib @@ -22,10 +5,9 @@ from typing import Union, Optional import numpy as np - +from bittensor_wallet import Keypair from numpy.typing import NDArray from scalecodec import U16, ScaleBytes, Vec -from bittensor_wallet import Keypair from bittensor.utils.btlogging import logging from bittensor.utils.registration import legacy_torch_api_compat, torch, use_torch @@ -93,7 +75,8 @@ def convert_weight_uids_and_vals_to_tensor( n: int, uids: list[int], weights: list[int] ) -> Union[NDArray[np.float32], "torch.FloatTensor"]: """ - Converts weights and uids from chain representation into a np.array (inverse operation from convert_weights_and_uids_for_emit). + Converts weights and uids from chain representation into a np.array (inverse operation from + convert_weights_and_uids_for_emit). Args: n (int): number of neurons on network. @@ -122,7 +105,9 @@ def convert_weight_uids_and_vals_to_tensor( def convert_root_weight_uids_and_vals_to_tensor( n: int, uids: list[int], weights: list[int], subnets: list[int] ) -> Union[NDArray[np.float32], "torch.FloatTensor"]: - """Converts root weights and uids from chain representation into a np.array or torch FloatTensor (inverse operation from convert_weights_and_uids_for_emit) + """Converts root weights and uids from chain representation into a np.array or torch FloatTensor + (inverse operation from convert_weights_and_uids_for_emit) + Args: n (int): number of neurons on network. uids (list[int]): Tensor of uids as destinations for passed weights. @@ -240,18 +225,23 @@ def process_weights_for_netuid( tuple[NDArray[np.int64], NDArray[np.float32]], ]: """ - Processes weight tensors for a given subnet id using the provided weight and UID arrays, applying constraints and normalization based on the subtensor and metagraph data. This function can handle both NumPy arrays and PyTorch tensors. + Processes weight tensors for a given subnet id using the provided weight and UID arrays, applying constraints + and normalization based on the subtensor and metagraph data. This function can handle both NumPy arrays and PyTorch + tensors. Args: uids (Union[NDArray[np.int64], "torch.Tensor"]): Array of unique identifiers of the neurons. weights (Union[NDArray[np.float32], "torch.Tensor"]): Array of weights associated with the user IDs. netuid (int): The network uid to process weights for. subtensor (Subtensor): Subtensor instance to access blockchain data. - metagraph (Optional[Metagraph]): Metagraph instance for additional network data. If None, it is fetched from the subtensor using the netuid. + metagraph (Optional[Metagraph]): Metagraph instance for additional network data. If None, it is fetched from + the subtensor using the netuid. exclude_quantile (int): Quantile threshold for excluding lower weights. Defaults to ``0``. Returns: - Union[tuple["torch.Tensor", "torch.FloatTensor"], tuple[NDArray[np.int64], NDArray[np.float32]]]: tuple containing the array of user IDs and the corresponding normalized weights. The data type of the return matches the type of the input weights (NumPy or PyTorch). + Union[tuple["torch.Tensor", "torch.FloatTensor"], tuple[NDArray[np.int64], NDArray[np.float32]]]: tuple + containing the array of user IDs and the corresponding normalized weights. The data type of the return + matches the type of the input weights (NumPy or PyTorch). """ logging.debug("process_weights_for_netuid()") diff --git a/setup.py b/setup.py index 99d5891e12..d552f47f22 100644 --- a/setup.py +++ b/setup.py @@ -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 codecs import os import pathlib diff --git a/tests/__init__.py b/tests/__init__.py index 1c7bc4757e..e69de29bb2 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,18 +0,0 @@ -# The MIT License (MIT) -# Copyright © 2022 Yuma Rao -# Copyright © 2022-2023 Opentensor Foundation -# Copyright © 2023 Opentensor Technologies Inc - -# 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. diff --git a/tests/helpers/__init__.py b/tests/helpers/__init__.py index 3c6badb91c..624c3a08d7 100644 --- a/tests/helpers/__init__.py +++ b/tests/helpers/__init__.py @@ -1,20 +1,3 @@ -# The MIT License (MIT) -# Copyright © 2023 Opentensor Technologies Inc - -# 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 from .helpers import ( # noqa: F401 CLOSE_IN_VALUE, diff --git a/tests/helpers/helpers.py b/tests/helpers/helpers.py index ffbcf7f591..a6e9f292df 100644 --- a/tests/helpers/helpers.py +++ b/tests/helpers/helpers.py @@ -1,19 +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 asyncio from collections import deque import json diff --git a/tests/integration_tests/__init__.py b/tests/integration_tests/__init__.py index 640a132503..e69de29bb2 100644 --- a/tests/integration_tests/__init__.py +++ b/tests/integration_tests/__init__.py @@ -1,16 +0,0 @@ -# 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. diff --git a/tests/integration_tests/test_metagraph_integration.py b/tests/integration_tests/test_metagraph_integration.py index 4ec58285ee..45ce51a6b8 100644 --- a/tests/integration_tests/test_metagraph_integration.py +++ b/tests/integration_tests/test_metagraph_integration.py @@ -1,19 +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. from unittest import mock import bittensor diff --git a/tests/unit_tests/test_axon.py b/tests/unit_tests/test_axon.py index 9c473665fe..868e89ee01 100644 --- a/tests/unit_tests/test_axon.py +++ b/tests/unit_tests/test_axon.py @@ -1,21 +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 re import time from dataclasses import dataclass diff --git a/tests/unit_tests/test_chain_data.py b/tests/unit_tests/test_chain_data.py index 65232e3382..ec5c44ef94 100644 --- a/tests/unit_tests/test_chain_data.py +++ b/tests/unit_tests/test_chain_data.py @@ -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 pytest import torch diff --git a/tests/unit_tests/test_dendrite.py b/tests/unit_tests/test_dendrite.py index a23f959a31..113138bef1 100644 --- a/tests/unit_tests/test_dendrite.py +++ b/tests/unit_tests/test_dendrite.py @@ -1,22 +1,3 @@ -# The MIT License (MIT) -# Copyright © 2022 Yuma Rao -# Copyright © 2022-2023 Opentensor Foundation -# Copyright © 2023 Opentensor Technologies Inc - -# 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 asyncio import typing from unittest.mock import MagicMock, Mock diff --git a/tests/unit_tests/test_deprecated.py b/tests/unit_tests/test_deprecated.py index c4b906a0ca..f47337e019 100644 --- a/tests/unit_tests/test_deprecated.py +++ b/tests/unit_tests/test_deprecated.py @@ -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 sys diff --git a/tests/unit_tests/test_synapse.py b/tests/unit_tests/test_synapse.py index 80c127c587..72acddbcb2 100644 --- a/tests/unit_tests/test_synapse.py +++ b/tests/unit_tests/test_synapse.py @@ -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 base64 import json from typing import Optional, ClassVar diff --git a/tests/unit_tests/test_tensor.py b/tests/unit_tests/test_tensor.py index 8bf7bf06ac..5a1ada61cf 100644 --- a/tests/unit_tests/test_tensor.py +++ b/tests/unit_tests/test_tensor.py @@ -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 numpy import numpy as np import pytest diff --git a/tests/unit_tests/utils/test_formatting.py b/tests/unit_tests/utils/test_formatting.py index 3c223a48b3..57ba6541d3 100644 --- a/tests/unit_tests/utils/test_formatting.py +++ b/tests/unit_tests/utils/test_formatting.py @@ -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 math from bittensor.utils import formatting diff --git a/tests/unit_tests/utils/test_registration.py b/tests/unit_tests/utils/test_registration.py index ccef37dfb2..a4ec066279 100644 --- a/tests/unit_tests/utils/test_registration.py +++ b/tests/unit_tests/utils/test_registration.py @@ -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 pytest from bittensor.utils.registration import LazyLoadedTorch diff --git a/tests/unit_tests/utils/test_utils.py b/tests/unit_tests/utils/test_utils.py index c2e8faca5b..4c2c6b8b08 100644 --- a/tests/unit_tests/utils/test_utils.py +++ b/tests/unit_tests/utils/test_utils.py @@ -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 pytest from bittensor_wallet import Wallet diff --git a/tests/unit_tests/utils/test_version.py b/tests/unit_tests/utils/test_version.py index fa96bddad3..6d1785b0bd 100644 --- a/tests/unit_tests/utils/test_version.py +++ b/tests/unit_tests/utils/test_version.py @@ -1,22 +1,3 @@ -# The MIT License (MIT) -# Copyright © 2021 Yuma Rao -# Copyright © 2022 Opentensor Foundation -# Copyright © 2023 Opentensor Technologies Inc - -# 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 pathlib import Path import pytest from freezegun import freeze_time diff --git a/tests/unit_tests/utils/test_weight_utils.py b/tests/unit_tests/utils/test_weight_utils.py index 74009434b9..e49a814e00 100644 --- a/tests/unit_tests/utils/test_weight_utils.py +++ b/tests/unit_tests/utils/test_weight_utils.py @@ -1,22 +1,3 @@ -# The MIT License (MIT) -# Copyright © 2021 Yuma Rao -# Copyright © 2022 Opentensor Foundation -# Copyright © 2023 Opentensor Technologies Inc - -# 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 logging import numpy as np from hypothesis import settings