|
| 1 | +from concurrent.futures import ThreadPoolExecutor |
| 2 | +from functools import partial |
| 3 | +from typing import Any, Callable, Dict, List |
| 4 | + |
| 5 | +from tensordict import TensorDict, stack |
| 6 | + |
| 7 | +from areal.api.cli_args import InferenceEngineConfig |
| 8 | +from areal.api.controller_api import RolloutController, DistributedBatch |
| 9 | +from areal.api.engine_api import InferenceEngine |
| 10 | +from areal.api.io_struct import AllocationMode, WeightUpdateMeta |
| 11 | +from areal.api.workflow_api import RolloutWorkflow |
| 12 | + |
| 13 | +from areal.api.scheduler_api import Job, Scheduler, ScheduleStrategy, Worker |
| 14 | +from areal.controller.utils import create_engine_with_retry, rpc_call |
| 15 | +from areal.utils.data import concat_padded_tensors |
| 16 | +from areal.utils import logging |
| 17 | +from areal.utils.http import wait_future_ordered |
| 18 | + |
| 19 | +logger = logging.getLogger("DistributedRolloutController") |
| 20 | + |
| 21 | + |
| 22 | +class DistributedRolloutController(RolloutController): |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + inf_engine: InferenceEngine, |
| 26 | + config: InferenceEngineConfig, |
| 27 | + scheduler: Scheduler, |
| 28 | + ): |
| 29 | + super().__init__(inf_engine, config, scheduler) |
| 30 | + self.role: str = "rollout" |
| 31 | + self.alloc_mode: AllocationMode |
| 32 | + self.enable_colocate_mode: bool |
| 33 | + self.dp_world_size: int |
| 34 | + self.dp_head_workers: List[Worker] |
| 35 | + |
| 36 | + def initialize( |
| 37 | + self, |
| 38 | + alloc_mode_str: str, |
| 39 | + target: str, |
| 40 | + ): |
| 41 | + self.alloc_mode = AllocationMode.from_str(alloc_mode_str) |
| 42 | + self.dp_world_size = self.alloc_mode.gen.world_size // self.alloc_mode.gen.dp_size |
| 43 | + |
| 44 | + job = Job( |
| 45 | + replicas=self.alloc_mode.gen.world_size, |
| 46 | + tasks=self.inf_engine.get_scheduling_config(), |
| 47 | + schedule_strategy=ScheduleStrategy(type="colocation", target=target) if target else None, |
| 48 | + role=self.role, |
| 49 | + ) |
| 50 | + logger.info(f"Start to create job: {job}") |
| 51 | + self.scheduler.create_workers(job) |
| 52 | + |
| 53 | + workers = self.scheduler.get_workers(self.role, timeout=1800) |
| 54 | + self.dp_head_workers = [worker for idx, worker in enumerate(workers) if idx % self.dp_world_size == 0] |
| 55 | + assert len(self.dp_head_workers) == self.alloc_mode.gen.dp_size |
| 56 | + |
| 57 | + engine_addrs = [f"{w.ip}:{w.serve_port}" for w in self.dp_head_workers] |
| 58 | + with ThreadPoolExecutor(max_workers=len(self.dp_head_workers)) as executor: |
| 59 | + futures = [ |
| 60 | + executor.submit( |
| 61 | + partial( |
| 62 | + create_engine_with_retry, |
| 63 | + self.scheduler.create_engine, |
| 64 | + worker.id, |
| 65 | + self.inf_engine, |
| 66 | + None, |
| 67 | + engine_addrs, |
| 68 | + self.dp_world_size, |
| 69 | + ) |
| 70 | + ) |
| 71 | + for worker in self.dp_head_workers |
| 72 | + ] |
| 73 | + |
| 74 | + wait_future_ordered(futures, exit_on_exception=True) |
| 75 | + |
| 76 | + def destroy(self): |
| 77 | + self.scheduler.delete_workers() |
| 78 | + |
| 79 | + def __del__(self): |
| 80 | + self.destroy() |
| 81 | + |
| 82 | + def update_weights(self, meta: WeightUpdateMeta) -> None: |
| 83 | + """Update weights in the inference engine.""" |
| 84 | + self.custom_function_call("update_weights", None, meta) |
| 85 | + return None |
| 86 | + |
| 87 | + def prepare_batch(self, data: DistributedBatch, workflow: RolloutWorkflow) -> None: |
| 88 | + """Asynchronously submit a request to the inference engine. Exits immediately.""" |
| 89 | + batches = data.chunk(self.alloc_mode.gen.dp_size) |
| 90 | + self.custom_function_call("prepare_batch", batches, workflow) |
| 91 | + return None |
| 92 | + |
| 93 | + def rollout_batch( |
| 94 | + self, |
| 95 | + data: DistributedBatch, |
| 96 | + workflow: RolloutWorkflow |
| 97 | + ) -> DistributedBatch: |
| 98 | + """Submit a batch of requests to the inference engine and wait for the results.""" |
| 99 | + batches = data.chunk(self.alloc_mode.gen.dp_size) |
| 100 | + results = self.custom_function_call("rollout_distributed_batch", batches, workflow) |
| 101 | + assert len(results) > 0 |
| 102 | + size = int(results[0]["input_ids"].shape[0]) |
| 103 | + bs = size * len(results) |
| 104 | + padded = concat_padded_tensors(results) |
| 105 | + if isinstance(padded, dict): |
| 106 | + padded = TensorDict(padded, batch_size=[bs]) |
| 107 | + return DistributedBatch.concat(padded.to_dict()) |
| 108 | + |
| 109 | + def set_version(self, version: int) -> None: |
| 110 | + self.custom_function_call("set_version", None, version) |
| 111 | + return None |
| 112 | + |
| 113 | + def get_version(self) -> int: |
| 114 | + results = self.custom_function_call("get_version", None) |
| 115 | + return results[0] |
| 116 | + |
| 117 | + def pause(self): |
| 118 | + self.custom_function_call("pause", None) |
| 119 | + |
| 120 | + def resume(self): |
| 121 | + self.custom_function_call("resume", None) |
| 122 | + |
| 123 | + def submit(self, data: DistributedBatch): |
| 124 | + batches = data.chunk(self.alloc_mode.gen.dp_size) |
| 125 | + self.custom_function_call("submit", batches) |
| 126 | + |
| 127 | + def wait(self, counts: List[int], timeout: float | None = None)->DistributedBatch: |
| 128 | + assert len(counts) == len(self.dp_head_workers) |
| 129 | + results = self.custom_function_call("wait", counts, timeout) |
| 130 | + return DistributedBatch.concat(results) |
| 131 | + |
| 132 | + def custom_function_call(self, method: str, batches, *args, **kwargs): |
| 133 | + return rpc_call(self.scheduler, self.dp_head_workers, method, batches, args, kwargs) |
0 commit comments