| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import multiprocessing |
| 8 | import os |
| 9 | import pickle |
| 10 | import tempfile |
| 11 | import time |
| 12 | import uuid |
| 13 | |
| 14 | from typing import Callable, Generator |
| 15 | |
| 16 | import torch |
| 17 | |
| 18 | import zmq |
| 19 | |
| 20 | from fairscale.nn.model_parallel.initialize import ( |
| 21 | get_model_parallel_group, |
| 22 | get_model_parallel_rank, |
| 23 | get_model_parallel_src_rank, |
| 24 | ) |
| 25 | |
| 26 | from torch.distributed.launcher.api import elastic_launch, LaunchConfig |
| 27 | |
| 28 | |
| 29 | _END_SENTINEL = "__end_sentinel__" |
| 30 | _CANCEL_SENTINEL = "__cancel_sentinel__" |
| 31 | |
| 32 | |
| 33 | def mp_rank_0() -> bool: |
| 34 | return get_model_parallel_rank() == 0 |
| 35 | |
| 36 | |
| 37 | def retrieve_requests(reply_socket_url: str): |
| 38 | if mp_rank_0(): |
| 39 | context = zmq.Context() |
| 40 | reply_socket = context.socket(zmq.ROUTER) |
| 41 | reply_socket.connect(reply_socket_url) |
| 42 | |
| 43 | while True: |
| 44 | client_id, obj = maybe_get_work(reply_socket) |
| 45 | if obj is None: |
| 46 | time.sleep(0.01) |
| 47 | continue |
| 48 | |
| 49 | reply_socket.send_multipart([client_id, pickle.dumps("YES READY")]) |
| 50 | break |
| 51 | |
| 52 | def send_obj(obj): |
| 53 | reply_socket.send_multipart([client_id, pickle.dumps(obj)]) |
| 54 | |
| 55 | while True: |
| 56 | tasks = [None] |
| 57 | if mp_rank_0(): |
| 58 | client_id, task = maybe_get_work(reply_socket) |
| 59 | # there is still an unknown unclean GeneratorExit happening resulting in a |
| 60 | # cancel sentinel getting queued _after_ we have finished sending everything :/ |
| 61 | # kind of a hack this is :/ |
| 62 | if task != _CANCEL_SENTINEL: |
| 63 | tasks = [task] |
| 64 | |
| 65 | torch.distributed.broadcast_object_list( |
| 66 | tasks, |
| 67 | src=get_model_parallel_src_rank(), |
| 68 | group=get_model_parallel_group(), |
| 69 | ) |
| 70 | |
| 71 | task = tasks[0] |
| 72 | if task is None: |
| 73 | time.sleep(0.1) |
| 74 | else: |
| 75 | try: |
| 76 | out = yield task |
| 77 | if out is None: |
| 78 | break |
| 79 | |
| 80 | for obj in out: |
| 81 | updates = [None] |
| 82 | if mp_rank_0(): |
| 83 | _, update = maybe_get_work(reply_socket) |
| 84 | if update == _CANCEL_SENTINEL: |
| 85 | updates = [update] |
| 86 | else: |
| 87 | # only send the update if it's not cancelled otherwise the object sits in the socket |
| 88 | # and gets pulled in the next request lol |
| 89 | send_obj(obj) |
| 90 | |
| 91 | torch.distributed.broadcast_object_list( |
| 92 | updates, |
| 93 | src=get_model_parallel_src_rank(), |
| 94 | group=get_model_parallel_group(), |
| 95 | ) |
| 96 | if updates[0] == _CANCEL_SENTINEL: |
| 97 | print("quitting generation loop because request was cancelled") |
| 98 | break |
| 99 | |
| 100 | if mp_rank_0(): |
| 101 | send_obj(_END_SENTINEL) |
| 102 | except Exception as e: |
| 103 | print(f"[debug] got exception {e}") |
| 104 | import traceback |
| 105 | |
| 106 | traceback.print_exc() |
| 107 | if mp_rank_0(): |
| 108 | send_obj(e) |
| 109 | |
| 110 | if mp_rank_0(): |
| 111 | send_obj("DONE") |
| 112 | |
| 113 | |
| 114 | def maybe_get_work(sock: zmq.Socket): |
| 115 | message = None |
| 116 | client_id = None |
| 117 | try: |
| 118 | client_id, obj = sock.recv_multipart(zmq.NOBLOCK) |
| 119 | message = pickle.loads(obj) |
| 120 | except zmq.ZMQError as e: |
| 121 | if e.errno != zmq.EAGAIN: |
| 122 | raise e |
| 123 | |
| 124 | return client_id, message |
| 125 | |
| 126 | |
| 127 | def worker_process_entrypoint( |
| 128 | reply_socket_url: str, |
| 129 | init_model_cb: Callable, |
| 130 | ) -> None: |
| 131 | model = init_model_cb() |
| 132 | torch.distributed.barrier() |
| 133 | time.sleep(1) |
| 134 | |
| 135 | # run the requests co-routine which retrieves requests from the socket |
| 136 | # and sends responses (we provide) back to the caller |
| 137 | req_gen = retrieve_requests(reply_socket_url) |
| 138 | result = None |
| 139 | while True: |
| 140 | try: |
| 141 | task = req_gen.send(result) |
| 142 | if isinstance(task, str) and task == _END_SENTINEL: |
| 143 | break |
| 144 | |
| 145 | result = model(task) |
| 146 | except StopIteration: |
| 147 | break |
| 148 | |
| 149 | print("[debug] worker process done") |
| 150 | |
| 151 | |
| 152 | def launch_dist_group( |
| 153 | reply_socket_url: str, |
| 154 | model_parallel_size: int, |
| 155 | init_model_cb: Callable, |
| 156 | **kwargs, |
| 157 | ) -> None: |
| 158 | id = uuid.uuid4().hex |
| 159 | dist_url = f"file:///tmp/llama3_{id}_{time.time()}" |
| 160 | |
| 161 | with tempfile.TemporaryDirectory() as tmpdir: |
| 162 | # TODO: track workers and if they terminate, tell parent process about it so cleanup can happen |
| 163 | launch_config = LaunchConfig( |
| 164 | max_nodes=1, |
| 165 | min_nodes=1, |
| 166 | nproc_per_node=model_parallel_size, |
| 167 | start_method="fork", |
| 168 | rdzv_backend="c10d", |
| 169 | rdzv_endpoint=os.path.join(tmpdir, "rdzv"), |
| 170 | rdzv_configs={"store_type": "file", "timeout": 90}, |
| 171 | max_restarts=0, |
| 172 | monitor_interval=1, |
| 173 | run_id=str(uuid.uuid4()), |
| 174 | ) |
| 175 | elastic_launch(launch_config, entrypoint=worker_process_entrypoint)( |
| 176 | reply_socket_url, |
| 177 | init_model_cb, |
| 178 | ) |
| 179 | |
| 180 | |
| 181 | def start_model_parallel_process( |
| 182 | model_parallel_size: int, |
| 183 | init_model_cb: Callable, |
| 184 | **kwargs, |
| 185 | ): |
| 186 | context = zmq.Context() |
| 187 | request_socket = context.socket(zmq.DEALER) |
| 188 | |
| 189 | # Binding the request socket to a random port |
| 190 | request_socket.bind("tcp://127.0.0.1:0") |
| 191 | |
| 192 | main_process_url = request_socket.getsockopt_string(zmq.LAST_ENDPOINT) |
| 193 | |
| 194 | ctx = multiprocessing.get_context("fork") |
| 195 | process = ctx.Process( |
| 196 | target=launch_dist_group, |
| 197 | args=( |
| 198 | main_process_url, |
| 199 | model_parallel_size, |
| 200 | init_model_cb, |
| 201 | ), |
| 202 | kwargs=kwargs, |
| 203 | ) |
| 204 | process.start() |
| 205 | |
| 206 | # wait until the model is loaded; rank 0 will send a message to indicate it's ready |
| 207 | |
| 208 | request_socket.send_pyobj("READY?") |
| 209 | response = request_socket.recv_pyobj() |
| 210 | print(f"Finished model load {response}") |
| 211 | |
| 212 | return request_socket, process |
| 213 | |
| 214 | |
| 215 | class ModelParallelProcessGroup: |
| 216 | def __init__( |
| 217 | self, |
| 218 | model_parallel_size: int, |
| 219 | init_model_cb: Callable, |
| 220 | **kwargs, |
| 221 | ): |
| 222 | self.model_parallel_size = model_parallel_size |
| 223 | self.init_model_cb = init_model_cb |
| 224 | self.started = False |
| 225 | self.running = False |
| 226 | |
| 227 | def start(self): |
| 228 | assert not self.started, "process group already started" |
| 229 | self.request_socket, self.process = start_model_parallel_process( |
| 230 | self.model_parallel_size, |
| 231 | self.init_model_cb, |
| 232 | ) |
| 233 | self.started = True |
| 234 | |
| 235 | def stop(self): |
| 236 | assert self.started, "process group not started" |
| 237 | if self.process.is_alive(): |
| 238 | self.request_socket.send_pyobj(_END_SENTINEL, zmq.NOBLOCK) |
| 239 | self.process.join() |
| 240 | self.started = False |
| 241 | |
| 242 | def run_inference(self, request) -> Generator: |
| 243 | assert not self.running, "inference already running" |
| 244 | |
| 245 | self.running = True |
| 246 | self.request_socket.send_pyobj(request) |
| 247 | try: |
| 248 | while True: |
| 249 | obj = self.request_socket.recv_pyobj() |
| 250 | if obj == _END_SENTINEL: |
| 251 | break |
| 252 | |
| 253 | if isinstance(obj, Exception): |
| 254 | print(f"[debug] got exception {obj}") |
| 255 | raise obj |
| 256 | |
| 257 | yield obj |
| 258 | except GeneratorExit as e: |
| 259 | self.request_socket.send_pyobj(_CANCEL_SENTINEL) |
| 260 | while True: |
| 261 | obj = self.request_socket.recv_pyobj() |
| 262 | if obj == _END_SENTINEL: |
| 263 | break |
| 264 | finally: |
| 265 | self.running = False |