standard_node.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import numpy as np
  2. import json
  3. import asyncio
  4. import uuid
  5. import time
  6. import traceback
  7. from typing import List, Dict, Optional, Tuple, Union
  8. from exo.networking import Discovery, PeerHandle, Server
  9. from exo.inference.inference_engine import InferenceEngine, Shard
  10. from .node import Node
  11. from exo.topology.topology import Topology
  12. from exo.topology.device_capabilities import device_capabilities
  13. from exo.topology.partitioning_strategy import Partition, PartitioningStrategy, map_partitions_to_shards
  14. from exo import DEBUG
  15. from exo.helpers import AsyncCallbackSystem
  16. from exo.viz.topology_viz import TopologyViz
  17. from exo.download.hf.hf_helpers import RepoProgressEvent
  18. class StandardNode(Node):
  19. def __init__(
  20. self,
  21. _id: str,
  22. server: Server,
  23. inference_engine: InferenceEngine,
  24. discovery: Discovery,
  25. partitioning_strategy: PartitioningStrategy = None,
  26. max_generate_tokens: int = 1024,
  27. topology_viz: Optional[TopologyViz] = None,
  28. ):
  29. self.id = _id
  30. self.inference_engine = inference_engine
  31. self.server = server
  32. self.discovery = discovery
  33. self.partitioning_strategy = partitioning_strategy
  34. self.peers: List[PeerHandle] = {}
  35. self.topology: Topology = Topology()
  36. self.device_capabilities = device_capabilities()
  37. self.buffered_token_output: Dict[str, Tuple[List[int], bool]] = {}
  38. self.max_generate_tokens = max_generate_tokens
  39. self.topology_viz = topology_viz
  40. self._on_token = AsyncCallbackSystem[str, Tuple[str, List[int], bool]]()
  41. self._on_opaque_status = AsyncCallbackSystem[str, Tuple[str, str]]()
  42. self._on_opaque_status.register("node_status").on_next(self.on_node_status)
  43. self.node_download_progress: Dict[str, RepoProgressEvent] = {}
  44. self.topology_inference_engines_pool: List[str] = []
  45. async def start(self, wait_for_peers: int = 0) -> None:
  46. await self.server.start()
  47. await self.discovery.start()
  48. await self.update_peers(wait_for_peers)
  49. await self.collect_topology()
  50. if DEBUG >= 2: print(f"Collected topology: {self.topology}")
  51. asyncio.create_task(self.periodic_topology_collection(1.0))
  52. async def stop(self) -> None:
  53. await self.discovery.stop()
  54. await self.server.stop()
  55. def on_node_status(self, request_id, opaque_status):
  56. try:
  57. status_data = json.loads(opaque_status)
  58. if status_data.get("type", "") == "node_status":
  59. if status_data.get("status", "").startswith("start_"):
  60. self.current_topology.active_node_id = status_data.get("node_id")
  61. elif status_data.get("status", "").startswith("end_"):
  62. if status_data.get("node_id") == self.current_topology.active_node_id:
  63. self.current_topology.active_node_id = None
  64. download_progress = None
  65. if status_data.get("type", "") == "download_progress":
  66. if DEBUG >= 8: print(f"Download progress from {status_data.get('node_id')}: {status_data.get('progress')}")
  67. download_progress = RepoProgressEvent.from_dict(status_data.get('progress'))
  68. self.node_download_progress[status_data.get('node_id')] = download_progress
  69. if self.topology_viz:
  70. self.topology_viz.update_visualization(self.current_topology, self.partitioning_strategy.partition(self.current_topology), self.id, self.node_download_progress)
  71. except Exception as e:
  72. if DEBUG >= 1: print(f"Error updating visualization: {e}")
  73. if DEBUG >= 1: traceback.print_exc()
  74. def get_supported_inference_engines(self):
  75. supported_engine_names = []
  76. if self.inference_engine.__class__.__name__ == 'MLXDynamicShardInferenceEngine':
  77. supported_engine_names.extend(['mlx', 'tinygrad'])
  78. else:
  79. supported_engine_names.append('tinygrad')
  80. return supported_engine_names
  81. async def broadcast_supported_engines(self, supported_engines: List):
  82. status_message = json.dumps({
  83. "type": "supported_inference_engines",
  84. "node_id": self.id,
  85. "engines": supported_engines
  86. })
  87. await self.broadcast_opaque_status("", status_message)
  88. def get_topology_inference_engines(self) -> List[str]:
  89. return self.topology_inference_engines_pool
  90. async def process_prompt(self, base_shard: Shard, prompt: str, image_str: Optional[str] = None, request_id: Optional[str] = None, inference_state: Optional[str] = None) -> Optional[np.ndarray]:
  91. shard = self.get_current_shard(base_shard)
  92. asyncio.create_task(
  93. self.broadcast_opaque_status(
  94. request_id,
  95. json.dumps({
  96. "type": "node_status",
  97. "node_id": self.id,
  98. "status": "start_process_prompt",
  99. "base_shard": base_shard.to_dict(),
  100. "shard": shard.to_dict(),
  101. "prompt": prompt,
  102. "image_str": image_str,
  103. "inference_state": inference_state,
  104. "request_id": request_id,
  105. }),
  106. )
  107. )
  108. start_time = time.perf_counter_ns()
  109. resp = await self._process_prompt(base_shard, prompt, image_str, request_id, inference_state)
  110. end_time = time.perf_counter_ns()
  111. elapsed_time_ns = end_time - start_time
  112. asyncio.create_task(
  113. self.broadcast_opaque_status(
  114. request_id,
  115. json.dumps({
  116. "type": "node_status",
  117. "node_id": self.id,
  118. "status": "end_process_prompt",
  119. "base_shard": base_shard.to_dict(),
  120. "shard": shard.to_dict(),
  121. "prompt": prompt,
  122. "image_str": image_str,
  123. "inference_state": inference_state,
  124. "request_id": request_id,
  125. "elapsed_time_ns": elapsed_time_ns,
  126. "result_size": resp.size if resp is not None else 0,
  127. }),
  128. )
  129. )
  130. return resp
  131. async def _process_prompt(self, base_shard: Shard, prompt: str, image_str: Optional[str] = None, request_id: Optional[str] = None, inference_state: Optional[str] = None) -> Optional[np.ndarray]:
  132. if request_id is None:
  133. request_id = str(uuid.uuid4())
  134. if request_id not in self.buffered_token_output:
  135. self.buffered_token_output[request_id] = ([], False)
  136. shard = self.get_current_shard(base_shard)
  137. if DEBUG >= 2: print(f"[{request_id}] process prompt: {base_shard=} {shard=} {prompt=} {image_str=}")
  138. if shard.start_layer != 0:
  139. if DEBUG >= 2: print(f"[{request_id}] forwarding to next shard: {base_shard=} {shard=} {prompt=} {image_str=}")
  140. await self.forward_to_next_shard(shard, prompt, request_id, image_str=image_str, inference_state=inference_state)
  141. return
  142. result, inference_state, is_finished = await self.inference_engine.infer_prompt(request_id, shard, prompt, image_str, inference_state=inference_state)
  143. is_finished = is_finished or len(self.buffered_token_output[request_id][0]) >= self.max_generate_tokens
  144. if is_finished:
  145. self.buffered_token_output[request_id] = (self.buffered_token_output[request_id][0], True)
  146. asyncio.create_task(self.broadcast_result(request_id, self.buffered_token_output[request_id][0], is_finished)) # TODO: this is n^2 communication complexity
  147. if result.size == 1:
  148. self.buffered_token_output[request_id][0].append(result.item())
  149. self.trigger_on_token_callbacks(request_id, self.buffered_token_output[request_id][0], is_finished)
  150. if DEBUG >= 2: print(f"[{request_id}] result size: {result.size}, is finished: {is_finished}, buffered tokens: {len(self.buffered_token_output[request_id][0])}")
  151. if not is_finished:
  152. asyncio.create_task(self.forward_to_next_shard(shard, result, request_id, image_str=image_str, inference_state=inference_state))
  153. return np.array(self.buffered_token_output[request_id][0]) if len(self.buffered_token_output[request_id][0]) > 0 else None
  154. async def process_tensor(
  155. self,
  156. base_shard: Shard,
  157. tensor: np.ndarray,
  158. request_id: Optional[str] = None,
  159. inference_state: Optional[str] = None,
  160. ) -> Optional[np.ndarray]:
  161. shard = self.get_current_shard(base_shard)
  162. asyncio.create_task(
  163. self.broadcast_opaque_status(
  164. request_id,
  165. json.dumps({
  166. "type": "node_status",
  167. "node_id": self.id,
  168. "status": "start_process_tensor",
  169. "base_shard": base_shard.to_dict(),
  170. "shard": shard.to_dict(),
  171. "tensor_size": tensor.size,
  172. "tensor_shape": tensor.shape,
  173. "request_id": request_id,
  174. "inference_state": inference_state,
  175. }),
  176. )
  177. )
  178. start_time = time.perf_counter_ns()
  179. resp = await self._process_tensor(shard, tensor, request_id, inference_state)
  180. end_time = time.perf_counter_ns()
  181. elapsed_time_ns = end_time - start_time
  182. asyncio.create_task(
  183. self.broadcast_opaque_status(
  184. request_id,
  185. json.dumps({
  186. "type": "node_status",
  187. "node_id": self.id,
  188. "status": "end_process_tensor",
  189. "base_shard": base_shard.to_dict(),
  190. "shard": shard.to_dict(),
  191. "request_id": request_id,
  192. "elapsed_time_ns": elapsed_time_ns,
  193. "result_size": resp.size if resp is not None else 0,
  194. }),
  195. )
  196. )
  197. return resp
  198. async def _process_tensor(
  199. self,
  200. base_shard: Shard,
  201. tensor: np.ndarray,
  202. request_id: Optional[str] = None,
  203. inference_state: Optional[str] = None,
  204. ) -> Optional[np.ndarray]:
  205. if request_id is None:
  206. request_id = str(uuid.uuid4())
  207. if request_id not in self.buffered_token_output:
  208. self.buffered_token_output[request_id] = ([], False)
  209. shard = self.get_current_shard(base_shard)
  210. try:
  211. if DEBUG >= 1: print(f"[{request_id}] process_tensor: {tensor.size=} {tensor.shape=}")
  212. result, inference_state, is_finished = await self.inference_engine.infer_tensor(request_id, shard, tensor, inference_state=inference_state)
  213. is_finished = is_finished or len(self.buffered_token_output[request_id][0]) >= self.max_generate_tokens
  214. if is_finished:
  215. self.buffered_token_output[request_id] = (self.buffered_token_output[request_id][0], True)
  216. asyncio.create_task(self.broadcast_result(request_id, self.buffered_token_output[request_id][0], is_finished)) # TODO: this is n^2 communication complexity
  217. if result.size == 1: # we got a new token out
  218. self.buffered_token_output[request_id][0].append(result.item())
  219. self.trigger_on_token_callbacks(request_id, self.buffered_token_output[request_id][0], is_finished)
  220. if DEBUG >= 2: print(f"[{request_id}] result size: {result.size}, is finished: {is_finished}, buffered tokens: {len(self.buffered_token_output[request_id][0])}")
  221. if not is_finished:
  222. asyncio.create_task(self.forward_to_next_shard(shard, result, request_id, inference_state=inference_state))
  223. return np.array(self.buffered_token_output[request_id][0]) if len(self.buffered_token_output[request_id][0]) > 0 else None
  224. except Exception as e:
  225. print(f"Error processing tensor for shard {shard}: {e}")
  226. traceback.print_exc()
  227. return None
  228. async def forward_to_next_shard(
  229. self,
  230. base_shard: Shard,
  231. tensor_or_prompt: Union[np.ndarray, str],
  232. request_id: str,
  233. image_str: Optional[str] = None,
  234. inference_state: Optional[str] = None,
  235. ) -> None:
  236. if not self.partitioning_strategy:
  237. if DEBUG >= 1: print("No partitioning strategy found. Skipping forward.")
  238. return
  239. shard = self.get_current_shard(base_shard)
  240. partitions = self.partitioning_strategy.partition(self.topology)
  241. shards = map_partitions_to_shards(self.partitioning_strategy.partition(self.topology), base_shard.n_layers, base_shard.model_id)
  242. current_partition_index = next((i for i, p in enumerate(partitions) if p.node_id == self.id), None)
  243. if DEBUG >= 1: print(f"Current partition index: {current_partition_index}")
  244. if current_partition_index is not None:
  245. next_partition_index = (current_partition_index+1) % len(partitions)
  246. next_partition: Partition = partitions[next_partition_index]
  247. next_shard = shards[next_partition_index]
  248. if DEBUG >= 2: print(f"Computed next from: {shard}, {self.topology}. Next partition: {next_partition}")
  249. if next_partition.node_id == self.id:
  250. if isinstance(tensor_or_prompt, np.ndarray):
  251. await self.process_tensor(shard, tensor_or_prompt, request_id, inference_state=inference_state)
  252. else:
  253. await self.process_prompt(shard, tensor_or_prompt, image_str, request_id, inference_state=inference_state)
  254. return
  255. target_peer = next((p for p in self.peers if p.id() == next_partition.node_id), None)
  256. if not target_peer:
  257. raise ValueError(f"Peer for {next_partition} not found")
  258. if DEBUG >= 1: print(f"Sending tensor_or_prompt to {target_peer.id()}: {tensor_or_prompt}")
  259. if isinstance(tensor_or_prompt, np.ndarray):
  260. await target_peer.send_tensor(next_shard, tensor_or_prompt, request_id=request_id, inference_state=inference_state)
  261. else:
  262. await target_peer.send_prompt(next_shard, tensor_or_prompt, image_str=image_str, request_id=request_id, inference_state=inference_state)
  263. def get_current_shard(self, base_shard: Shard) -> Shard:
  264. partitions = self.partitioning_strategy.partition(self.topology)
  265. shards = map_partitions_to_shards(partitions, base_shard.n_layers, base_shard.model_id)
  266. current_partition_index = next((i for i, p in enumerate(partitions) if p.node_id == self.id), None)
  267. if current_partition_index is None:
  268. raise ValueError(f"No current partition found for node: {self.id}")
  269. return shards[current_partition_index]
  270. async def update_peers(self, wait_for_peers: int = 0) -> bool:
  271. next_peers = await self.discovery.discover_peers(wait_for_peers)
  272. current_peer_ids = {peer.id() for peer in self.peers}
  273. next_peer_ids = {peer.id() for peer in next_peers}
  274. peers_added = [peer for peer in next_peers if peer.id() not in current_peer_ids]
  275. peers_removed = [peer for peer in self.peers if peer.id() not in next_peer_ids]
  276. peers_updated = [
  277. peer for peer in next_peers
  278. if peer.id() in current_peer_ids and any(p.addr() != peer.addr() for p in self.peers if p.id() == peer.id())
  279. ]
  280. peers_unchanged = [
  281. peer for peer in next_peers
  282. if peer.id() in current_peer_ids and all(p.addr() == peer.addr() for p in self.peers if p.id() == peer.id())
  283. ]
  284. peers_to_disconnect = [peer for peer in peers_removed if await peer.is_connected()]
  285. peers_to_connect = [peer for peer in peers_added + peers_updated + peers_unchanged if not await peer.is_connected()]
  286. def _pretty(peers: List[PeerHandle]) -> List[str]:
  287. return [f"{peer.id()}@{peer.addr()}" for peer in peers]
  288. if DEBUG >= 2: print(f"update_peers: added={peers_added} removed={peers_removed} updated={peers_updated} unchanged={peers_unchanged} to_disconnect={peers_to_disconnect} to_connect={peers_to_connect}")
  289. async def disconnect_with_timeout(peer, timeout=5):
  290. try:
  291. await asyncio.wait_for(peer.disconnect(), timeout)
  292. return True
  293. except Exception as e:
  294. print(f"Error disconnecting peer {peer.id()}@{peer.addr()}: {e}")
  295. traceback.print_exc()
  296. return False
  297. async def connect_with_timeout(peer, timeout=5):
  298. try:
  299. await asyncio.wait_for(peer.connect(), timeout)
  300. return True
  301. except Exception as e:
  302. print(f"Error connecting peer {peer.id()}@{peer.addr()}: {e}")
  303. traceback.print_exc()
  304. return False
  305. disconnect_results = await asyncio.gather(
  306. *(disconnect_with_timeout(peer) for peer in peers_to_disconnect),
  307. return_exceptions=True
  308. )
  309. connect_results = await asyncio.gather(
  310. *(connect_with_timeout(peer) for peer in peers_to_connect),
  311. return_exceptions=True
  312. )
  313. successful_disconnects = [peer for peer, result in zip(peers_to_disconnect, disconnect_results) if result is True]
  314. failed_disconnects = [peer for peer, result in zip(peers_to_disconnect, disconnect_results) if result is False]
  315. successful_connects = [peer for peer, result in zip(peers_to_connect, connect_results) if result is True]
  316. failed_connects = [peer for peer, result in zip(peers_to_connect, connect_results) if result is False]
  317. if DEBUG >= 1:
  318. if successful_disconnects: print(f"Successfully disconnected peers: {_pretty(successful_disconnects)}")
  319. if failed_disconnects: print(f"Failed to disconnect peers: {_pretty(failed_disconnects)}")
  320. if successful_connects: print(f"Successfully connected peers: {_pretty(successful_connects)}")
  321. if failed_connects: print(f"Failed to connect peers: {_pretty(failed_connects)}")
  322. self.peers = next_peers
  323. return len(peers_added) > 0 or len(peers_removed) > 0 or len(peers_updated) > 0
  324. async def periodic_topology_collection(self, interval: int):
  325. while True:
  326. await asyncio.sleep(interval)
  327. try:
  328. did_peers_change = await self.update_peers()
  329. if DEBUG >= 2: print(f"{did_peers_change=}")
  330. if did_peers_change:
  331. await self.collect_topology()
  332. except Exception as e:
  333. print(f"Error collecting topology: {e}")
  334. traceback.print_exc()
  335. async def get_inference_result(self, request_id: str) -> Tuple[Optional[np.ndarray], bool]:
  336. if request_id not in self.buffered_token_output:
  337. return None, False
  338. return np.array(self.buffered_token_output[request_id][0]), self.buffered_token_output[request_id][1]
  339. async def collect_topology(self, visited: set[str] = set(), max_depth: int = 4) -> Topology:
  340. next_topology = Topology()
  341. next_topology.update_node(self.id, self.device_capabilities)
  342. if DEBUG >= 2: print(f"Collecting topology {max_depth=} {visited=}")
  343. prev_visited = visited.copy()
  344. visited.add(self.id)
  345. visited.update(p.id() for p in self.peers)
  346. for peer in self.peers:
  347. next_topology.update_node(peer.id(), peer.device_capabilities())
  348. next_topology.add_edge(self.id, peer.id())
  349. if peer.id() in prev_visited:
  350. continue
  351. if max_depth <= 0:
  352. if DEBUG >= 2: print("Max depth reached. Skipping...")
  353. continue
  354. try:
  355. other_topology = await asyncio.wait_for(peer.collect_topology(visited, max_depth=max_depth - 1), timeout=5.0)
  356. if DEBUG >= 2: print(f"Collected topology from: {peer.id()}: {other_topology}")
  357. self.topology.merge(other_topology)
  358. except Exception as e:
  359. print(f"Error collecting topology from {peer.id()}: {e}")
  360. next_topology.active_node_id = self.topology.active_node_id # this is not so clean.
  361. self.topology = next_topology
  362. if self.topology_viz:
  363. self.topology_viz.update_visualization(self.current_topology, self.partitioning_strategy.partition(self.current_topology), self.id)
  364. return next_topology
  365. @property
  366. def on_token(self) -> AsyncCallbackSystem[str, Tuple[str, List[int], bool]]:
  367. return self._on_token
  368. @property
  369. def on_opaque_status(self) -> AsyncCallbackSystem[str, Tuple[str, str]]:
  370. return self._on_opaque_status
  371. def trigger_on_token_callbacks(self, request_id: str, tokens: List[int], is_finished: bool) -> None:
  372. if DEBUG >= 2: print(f"Triggering all on_token callbacks with {request_id=} num_tokens={len(tokens)} {is_finished=}")
  373. self.on_token.trigger_all(request_id, tokens, is_finished)
  374. async def broadcast_result(self, request_id: str, result: List[int], is_finished: bool) -> None:
  375. async def send_result_to_peer(peer):
  376. try:
  377. await asyncio.wait_for(peer.send_result(request_id, result, is_finished), timeout=15.0)
  378. except asyncio.TimeoutError:
  379. print(f"Timeout broadcasting result to {peer.id()}")
  380. except Exception as e:
  381. print(f"Error broadcasting result to {peer.id()}: {e}")
  382. traceback.print_exc()
  383. await asyncio.gather(*[send_result_to_peer(peer) for peer in self.peers], return_exceptions=True)
  384. async def broadcast_opaque_status(self, request_id: str, status: str) -> None:
  385. if DEBUG >= 8: print(f"Broadcasting opaque status: {request_id=} {status=}")
  386. async def send_status_to_peer(peer):
  387. try:
  388. await asyncio.wait_for(peer.send_opaque_status(request_id, status), timeout=15.0)
  389. except asyncio.TimeoutError:
  390. print(f"Timeout sending opaque status to {peer.id()}")
  391. except Exception as e:
  392. print(f"Error sending opaque status to {peer.id()}: {e}")
  393. traceback.print_exc()
  394. await asyncio.gather(*[send_status_to_peer(peer) for peer in self.peers], return_exceptions=True)
  395. # in the case of opaque status, we also want to receive our own opaque statuses
  396. self.on_opaque_status.trigger_all(request_id, status)
  397. @property
  398. def current_topology(self) -> Topology:
  399. return self.topology