forked from SocialTensor/SocialTensorSubnet
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathminer.py
More file actions
165 lines (135 loc) · 6.91 KB
/
miner.py
File metadata and controls
165 lines (135 loc) · 6.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import time
import asyncio
import threading
import traceback
import bittensor as bt
from logicnet.base.neuron import BaseNeuron
class BaseMinerNeuron(BaseNeuron):
"""
Base class for Bittensor miners.
"""
def __init__(self, config=None):
super().__init__(config=config)
# The axon handles request processing, allowing validators to send this miner requests.
self.axon = bt.axon(wallet=self.wallet, config=self.config)
# Attach determiners which functions are called when servicing a request.
bt.logging.info("\033[1;32m🧠 Attaching forward function to miner axon.\033[0m")
self.axon.attach(
forward_fn=self.forward,
blacklist_fn=self.blacklist,
).attach(
forward_fn=self.forward_info,
blacklist_fn=self.blacklist_info,
)
bt.logging.info(f"\033[1;32m🧠 Axon created: {self.axon}\033[0m")
# Instantiate runners
self.should_exit: bool = False
self.is_running: bool = False
self.thread: threading.Thread = None
self.lock = asyncio.Lock()
def run(self):
"""
Initiates and manages the main loop for the miner on the Bittensor network. The main loop handles graceful shutdown on keyboard interrupts and logs unforeseen errors.
This function performs the following primary tasks:
1. Check for registration on the Bittensor network.
2. Starts the miner's axon, making it active on the network.
3. Periodically resynchronizes with the chain; updating the metagraph with the latest network state and setting weights.
The miner continues its operations until `should_exit` is set to True or an external interruption occurs.
During each epoch of its operation, the miner waits for new blocks on the Bittensor network, updates its
knowledge of the network (metagraph), and sets its weights. This process ensures the miner remains active
and up-to-date with the network's latest state.
Note:
- The function leverages the global configurations set during the initialization of the miner.
- The miner's axon serves as its interface to the Bittensor network, handling incoming and outgoing requests.
Raises:
KeyboardInterrupt: If the miner is stopped by a manual interruption.
Exception: For unforeseen errors during the miner's operation, which are logged for diagnosis.
"""
# Check that miner is registered on the network.
self.sync()
last_sync_block = self.block
# Serve passes the axon information to the network + netuid we are hosting on.
# This will auto-update if the axon port of external ip have changed.
bt.logging.info(
f"\033[1;32m🧠 Serving miner axon {self.axon} on network: {self.config.subtensor.chain_endpoint} with netuid: {self.config.netuid}\033[0m"
)
self.axon.serve(netuid=self.config.netuid, subtensor=self.subtensor)
# Start starts the miner's axon, making it active on the network.
self.axon.start()
bt.logging.info(f"\033[1;32m🧠 Miner starting at block: {self.block}\033[0m")
# This loop maintains the miner's operations until intentionally stopped.
try:
RESYNC_INTERVAL = self.config.neuron.epoch_length # resync every self.config.neuron.epoch_length blocks
SLEEP_TIME = 30 # sleep time between checks (seconds)
while not self.should_exit:
try:
if self.block - last_sync_block > RESYNC_INTERVAL:
self.sync()
self.step += 1
last_sync_block = self.block
time.sleep(SLEEP_TIME)
except Exception as e:
bt.logging.error(f"\033[1;31m❌ Miner exception: {e}\033[0m")
# If someone intentionally stops the miner, it'll safely terminate operations.
except KeyboardInterrupt:
self.axon.stop()
bt.logging.success("\033[1;31m🛑 Miner killed by keyboard interrupt.\033[0m")
exit()
# In case of unforeseen errors, the miner will log the error and continue operations.
except Exception:
bt.logging.error(f"\033[1;31m❌ {traceback.format_exc()}\033[0m")
def run_in_background_thread(self):
"""
Starts the miner's operations in a separate background thread.
This is useful for non-blocking operations.
"""
if not self.is_running:
bt.logging.debug("\033[1;34m🔄 Starting miner in background thread.\033[0m")
self.should_exit = False
self.thread = threading.Thread(target=self.run, daemon=True)
self.thread.start()
self.is_running = True
bt.logging.debug("\033[1;34m🔄 Started\033[0m")
def stop_run_thread(self):
"""
Stops the miner's operations that are running in the background thread.
"""
if self.is_running:
bt.logging.debug("\033[1;34m🔄 Stopping miner in background thread.\033[0m")
self.should_exit = True
self.thread.join(5)
self.is_running = False
bt.logging.debug("\033[1;34m🔄 Stopped\033[0m")
def __enter__(self):
"""
Starts the miner's operations in a background thread upon entering the context.
This method facilitates the use of the miner in a 'with' statement.
"""
self.run_in_background_thread()
return self
def __exit__(self, exc_type, exc_value, traceback):
"""
Stops the miner's background operations upon exiting the context.
This method facilitates the use of the miner in a 'with' statement.
Args:
exc_type: The type of the exception that caused the context to be exited.
None if the context was exited without an exception.
exc_value: The instance of the exception that caused the context to be exited.
None if the context was exited without an exception.
traceback: A traceback object encoding the stack trace.
None if the context was exited without an exception.
"""
self.stop_run_thread()
def set_weights(self):
"""
NO MORE NEEDED IN SUBNET 35
Self-assigns a weight of 1 to the current miner (identified by its UID) and
a weight of 0 to all other peers in the network. The weights determine the trust level the miner assigns to other nodes on the network.
Raises:
Exception: If there's an error while setting weights, the exception is logged for diagnosis.
"""
pass
def resync_metagraph(self):
"""Resyncs the metagraph and updates the hotkeys and moving averages based on the new metagraph."""
# Sync the metagraph.
self.metagraph.sync(subtensor=self.subtensor)