Package: bittensor
BittensorInternet-scale Neural NetworksDiscord•Network•ResearchBittensor is a mining network, similar to Bitcoin, that includes built-in incentives designed to encourage computers to provide access to machine learning models in an efficient and censorship-resistant manner. These models can be queried by users seeking outputs from the network, for instance; generating text, audio, and images, or for extracting numerical representations of these input types. Under the hood, Bittensor’seconomic market, is facilitated by a blockchain token mechanism, through which producers (miners) and the verification of the work done by those miners (validators) are rewarded. Miners host, train or otherwise procure machine learning systems into the network as a means of fulfilling the verification problems defined by the validators, like the ability to generate responses from prompts i.e. “What is the capital of Texas?.The token based mechanism under which the miners are incentivized ensures that they are constantly driven to make their knowledge output more useful, in terms of speed, intelligence and diversity. The value generated by the network is distributed directly to the individuals producing that value, without intermediaries. Anyone can participate in this endeavour, extract value from the network, and govern Bittensor. The network is open to all participants, and no individual or group has full control over what is learned, who can profit from it, or who can access it.To learn more about Bittensor, please read ourpaper.InstallThere are three ways to install BittensorThrough the installer:$/bin/bash-c"$(curl-fsSLhttps://raw.githubusercontent.com/opentensor/bittensor/master/scripts/install.sh)"With pip:$pip3installbittensorFrom source:$gitclonehttps://github.com/opentensor/bittensor.git
$python3-mpipinstall-ebittensor/Using Conda (recommended forApple M1):$condaenvcreate-f~/.bittensor/bittensor/scripts/environments/apple_m1_environment.yml
$condaactivatebittensorTo test your installation, type:$btcli--helpor using pythonimportbittensorCUDAIf you anticipate using PoW registration for subnets or the faucet (only available on staging), please installcubitas well for your version of python. You can find the Opentensor cubit implementation and instructionshere.For example with python 3.10:pipinstallhttps://github.com/opentensor/cubit/releases/download/v1.1.2/cubit-1.1.2-cp310-cp310-linux_x86_64.whlWalletsWallets are the core ownership and identity technology around which all functions on Bittensor are carried out. Bittensor wallets consists of a coldkey and hotkey where the coldkey may contain many hotkeys, while each hotkey can only belong to a single coldkey. Coldkeys store funds securely, and operate functions such as transfers and staking, while hotkeys are used for all online operations such as signing queries, running miners and validating.Wallets can be created in two ways.Using the python-apiimportbittensorwallet=bittensor.wallet()wallet.create_new_coldkey()wallet.create_new_hotkey()print(wallet)"Wallet (default, default, ~/.bittensor/wallets/)"Or using btcliUse the subcommandwalletor it's aliasw:$btcliwalletnew_coldkeyEnterwalletname(default):IMPORTANT:Storethismnemonicinasecure(preferablyofflineplace),asanyonewhohaspossessionofthismnemoniccanuseittoregeneratethekeyandaccessyourtokens.Themnemonictothenewcoldkeyis:*************************************************Youcanusethemnemonictorecreatethekeyincaseitgetslost.Thecommandtousetoregeneratethekeyusingthismnemonicis:btcliwregen_coldkey--mnemonicpostmaiderodeshycaptainverifyscanshoulderbriskmountainpelicanelbow

$btcliwalletnew_hotkeyEnterwalletname(default):d1Enterhotkeyname(default):IMPORTANT:Storethismnemonicinasecure(preferablyofflineplace),asanyonewhohaspossessionofthismnemoniccanuseittoregeneratethekeyandaccessyourtokens.Themnemonictothenewhotkeyis:*************************************************Youcanusethemnemonictorecreatethekeyincaseitgetslost.Thecommandtousetoregeneratethekeyusingthismnemonicis:btcliwregen_hotkey--mnemonictotalsteakhourbirdhedgehogtrimtimbercanfrienddryworrytextIn both cases you should be able to view your keys by navigating to ~/.bittensor/wallets or viewed by runningbtcli wallet list$tree~/.bittensor/.bittensor/# Bittensor, root directory.wallets/# The folder containing all bittensor wallets.default/# The name of your wallet, "default"coldkey# You encrypted coldkey.coldkeypub.txt# Your coldkey public addresshotkeys/# The folder containing all of your hotkeys.default# You unencrypted hotkey information.Your default walletWallet (default, default, ~/.bittensor/wallets/)is always used unless you specify otherwise. Be sure to store your mnemonics safely. If you lose your password to your wallet, or the access to the machine where the wallet is stored, you can always regenerate the coldkey using the mnemonic you saved from above.$btcliwalletregen_coldkey--mnemonic*************************************************Using the cliThe Bittensor command line interface (btcli) is the primary command line tool for interacting with the Bittensor network. It can be used to deploy nodes, manage wallets, stake/unstake, nominate, transfer tokens, and more.Basic UsageTo get the list of all the available commands and their descriptions, you can use:btcli--help

usage:btcli<command><commandargs>

bittensorcliv{bittensor.__version__}commands:subnets(s,subnet)-Commandsformanagingandviewingsubnetworks.root(r,roots)-Commandsformanagingandviewingtherootnetwork.wallet(w,wallets)-Commandsformanagingandviewingwallets.stake(st,stakes)-Commandsforstakingandremovingstakefromhotkeyaccounts.sudo(su,sudos)-Commandsforsubnetmanagement.legacy(l)-Miscellaneouscommands.Example CommandsViewing Senate ProposalsbtclirootproposalsViewing Senate Membersbtclirootlist_delegatesViewing Proposal Votesbtclirootsenate_vote--proposal=[PROPOSAL_HASH]Registering for SenatebtclirootregisterLeaving SenatebtclirootundelegateVoting in Senatebtclirootsenate_vote--proposal=[PROPOSAL_HASH]Miscellaneous Commandsbtclilegacyupdate
btclilegacyfaucetManaging Subnetsbtclisubnetslist
btclisubnetscreateManaging Walletsbtcliwalletlist
btcliwallettransferNotePlease replace the subcommands and arguments as necessary to suit your needs, and always refer tobtcli --helporbtcli <command> --helpfor the most up-to-date and accurate information.For example:btclisubnets--help

usage:btcli<command><commandargs>subnets[-h]{list,metagraph,lock_cost,create,register,pow_register,hyperparameters}...

positionalarguments:{list,metagraph,lock_cost,create,register,pow_register,hyperparameters}Commandsformanagingandviewingsubnetworks.listListallsubnetsonthenetwork.metagraphViewasubnetmetagraphinformation.lock_costReturnthelockcosttoregisterasubnet.createCreateanewbittensorsubnetworkonthischain.registerRegisterawallettoanetwork.pow_registerRegisterawallettoanetworkusingPoW.hyperparametersViewsubnethyperparameters.

options:-h,--helpshowthishelpmessageandexitPost-Installation StepsTo enable autocompletion for Bittensor CLI, run the following commands:btcli--print-completionbash>>~/.bashrc# For Bashbtcli--print-completionzsh>>~/.zshrc# For Zshsource~/.bashrc# Reload Bash configuration to take effectThe Bittensor PackageThe bittensor package contains data structures for interacting with the bittensor ecosystem, writing miners, validators and querying the network. Additionally, it provides many utilities for efficient serialization of Tensors over the wire, performing data analysis of the network, and other useful utilities.Wallet: Interface over locally stored bittensor hot + coldkey styled wallets.importbittensor# Bittensor's wallet maintenance class.wallet=bittensor.wallet()# Access the hotkeywallet.hotkey# Access the coldkeywallet.coldkey(requiresdecryption)# Sign data with the keypair.wallet.coldkey.sign(data)Subtensor: Interfaces with bittensor's blockchain and can perform operations like extracting state information or sending transactions.importbittensor# Bittensor's chain interface.subtensor=bittensor.subtensor()# Get the chain blocksubtensor.get_current_block()# Transfer Tao to a destination address.subtensor.transfer(wallet=wallet,dest="xxxxxxx..xxxxx",amount=10.0)# Register a wallet onto a subnetworksubtensor.register(wallet=wallet,netuid=1)Metagraph: Encapsulates the chain state of a particular subnetwork at a specific block.importbittensor# Bittensor's chain state object.metagraph=bittensor.metagraph(netuid=1)# Resync the graph with the most recent chain statemetagraph.sync()# Get the list of stake valuesprint(metagraph.S)# Get endpoint information for the entire subnetworkprint(metagraph.axons)# Get the hotkey information for the miner in the 10th slotprint(metagraph.hotkeys[10])# Sync the metagraph at another blockmetagraph.sync(block=100000)# Save the metagraphmetagraph.save()# Load the samemetagraph.load()Synapse: Responsible for defining the protocol definition between axon servers and dendrite clientsclassTopk(bittensor.Synapse):topk:int=2# Number of "top" elements to selectinput:bittensor.Tensor=pydantic.Field(...,allow_mutation=False)# Ensure that input cannot be set on the server side.v:bittensor.Tensor=Nonei:bittensor.Tensor=Nonedeftopk(synapse:Topk)->Topk:v,i=torch.topk(synapse.input.deserialize(),k=synapse.topk)synapse.v=bittensor.Tensor.serialize(v)synapse.i=bittensor.Tensor.serialize(i)returnsynapse# Attach the forward function to the axon and start.axon=bittensor.axon().attach(topk).start()Axon: Serves Synapse protocols with custom blacklist, priority and verify functions.importbittensorclassMySynapse(bittensor.Synapse):input:int=1output:int=None# Define a custom request forwarding functiondefforward(synapse:MySynapse)->MySynapse:# Apply custom logic to synapse and return itsynapse.output=2returnsynapse# Define a custom request verification functiondefverify_my_synapse(synapse:MySynapse):# Apply custom verification logic to synapse# Optionally raise Exception# Define a custom request blacklist functiondefblacklist_my_synapse(synapse:MySynapse)->bool:# Apply custom blacklist# return False ( if non blacklisted ) or True ( if blacklisted )# Define a custom request priority functiondefprioritize_my_synape(synapse:MySynapse)->float:# Apply custom priorityreturn1.0# Initialize Axon object with a custom configurationmy_axon=bittensor.axon(config=my_config,wallet=my_wallet,port=9090,ip="192.0.2.0",external_ip="203.0.113.0",external_port=7070)# Attach the endpoint with the specified verification and forwarding functionsmy_axon.attach(forward_fn=forward_my_synapse,verify_fn=verify_my_synapse,blacklist_fn=blacklist_my_synapse,priority_fn=prioritize_my_synape).start()Dendrite: Inheriting from PyTorch's Module class, represents the abstracted implementation of a network client module designed
to send requests to those endpoints to receive inputs.Example:dendrite_obj=dendrite(wallet=bittensor.wallet())# pings the axon endpointawaitd(<axon>)# ping multiple axon endpointsawaitd([<axons>])# Send custom synapse request to axon.awaitd(bittensor.axon(),bittensor.Synapse())# Query all metagraph objects.awaitd(meta.axons,bittensor.Synapse())Setting weights on root networkUse therootsubcommand to access setting weights on the network across subnets.btclirootweights--wallet.name<coldname>--wallet.hotkey<hotname>
Enternetuids(e.g.0,1,2...):# Here enter your selected netuids to set weights on1,2>Enterweights(e.g.0.09,0.09,0.09...):# These do not need to sum to 1, we do normalization on the backend.# Values must be > 00.5,10Normalizedweights:tensor([0.5000,10.0000])->tensor([0.0476,0.9524])Doyouwanttosetthefollowingrootweights?:weights:tensor([0.0476,0.9524])uids:tensor([1,2])?[y/n]:y

⠏📡Settingrootweightsontest...Bittensor Subnets APIThis guide provides instructions on how to extend the Bittensor Subnets API, a powerful interface for interacting with the Bittensor network across subnets. The Bittensor Subnets API facilitates querying across any subnet that has exposed API endpoints to unlock utility of the Bittensor decentralized network.The Bittensor Subnets API consists of abstract classes and a registry system to dynamically handle API interactions. It allows developers to implement custom logic for storing and retrieving data, while also providing a straightforward way for end users to interact with these functionalities.Core ComponentsAPIRegistry: A central registry that manages API handlers. It allows for dynamic retrieval of handlers based on keys.SubnetsAPI (Abstract Base Class): Defines the structure for API implementations, including methods for querying the network and processing responses.StoreUserAPI & RetrieveUserAPI: Concrete implementations of theSubnetsAPIfor storing and retrieving user data.Implementing Custom Subnet APIsTo implement your own subclasses ofbittensor.SubnetsAPIto integrate an API into your subnet.Inherit fromSubnetsAPI: Your class should inherit from theSubnetsAPIabstract base class.Implement Required Methods: Implement theprepare_synapseandprocess_responsesabstract methods with your custom logic.That's it! For example:importbittensorclassCustomSubnetAPI(bittensor.SubnetsAPI):def__init__(self,wallet:"bittensor.wallet"):super().__init__(wallet)# Custom initialization heredefprepare_synapse(self,*args,**kwargs):# Custom synapse preparation logicpassdefprocess_responses(self,responses):# Custom response processing logicpassReleaseThe release manager should follow the instructions of theRELEASE_GUIDELINES.mddocument.ContributionsPlease review thecontributing guidefor more information before making a pull request.LicenseThe MIT License (MIT)
Copyright © 2021 Yuma RaoPermission 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.Acknowledgmentslearning-at-home/hivemind