|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import shutil |
| 5 | +from argparse import Namespace |
| 6 | +from collections.abc import Sequence |
| 7 | + |
| 8 | +import safetensors.torch |
| 9 | +import torch |
| 10 | +import torch.distributed as dist |
| 11 | + |
| 12 | +from miles.backends.sglang_utils.sglang_api_client import SGLangApiClient |
| 13 | +from miles.backends.training_utils.parallel import ParallelState |
| 14 | +from miles.backends.training_utils.weight_update.hf_weight_iterator import WeightUpdatePlacement |
| 15 | +from miles.backends.training_utils.weight_update.protocol import WeightTransferProtocol |
| 16 | +from miles.backends.training_utils.weight_update.protocols.utils.data_replica import get_data_replica_rank_and_size |
| 17 | +from miles.backends.training_utils.weight_update.rollout_cell_updater import create_rollout_cell_updaters |
| 18 | +from miles.backends.training_utils.weight_update.session import ( |
| 19 | + check_weight_sync_results, |
| 20 | + maybe_pause_engines, |
| 21 | + maybe_resume_engines, |
| 22 | +) |
| 23 | +from miles.utils import async_utils |
| 24 | +from miles.utils.distributed_utils import get_gloo_group |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | +# everything else in the HF checkpoint (config, tokenizer, remote code) is copied into each version |
| 29 | +_WEIGHT_FILE_SUFFIXES = (".safetensors", ".bin", ".pt", ".pth", ".index.json") |
| 30 | + |
| 31 | + |
| 32 | +class UpdateWeightFromDisk(WeightTransferProtocol): |
| 33 | + """ |
| 34 | + Full-checkpoint weight sync over a shared filesystem. The ranks holding the gathered HF buckets |
| 35 | + split them round-robin and write each as a safetensors shard of a fresh version dir, rank 0 adds |
| 36 | + the index and HF assets, and the engines reload it via /update_weights_from_disk. Needs no NCCL, |
| 37 | + CUDA IPC or /pull_weights, so it works with engines on another accelerator stack. |
| 38 | + """ |
| 39 | + |
| 40 | + # /update_weights_from_disk replaces every weight in one call, so no begin/end session |
| 41 | + use_weight_update_session = False |
| 42 | + |
| 43 | + def __init__(self, args: Namespace) -> None: |
| 44 | + super().__init__(args) |
| 45 | + self.root_dir = args.update_weight_disk_dir |
| 46 | + self._version_dir: str | None = None |
| 47 | + self._previous_version_dir: str | None = None |
| 48 | + self._weight_map: dict[str, str] = {} |
| 49 | + self._bucket_index = 0 |
| 50 | + self._owned_buckets: list[tuple[int, list[tuple[str, torch.Tensor]]]] = [] |
| 51 | + |
| 52 | + def connect( |
| 53 | + self, |
| 54 | + rollout_engines: Sequence[SGLangApiClient], |
| 55 | + engine_gpu_counts: Sequence[int] | None, |
| 56 | + engine_gpu_offsets: Sequence[int] | None, |
| 57 | + engine_cell_ids: Sequence[str], |
| 58 | + parallel_state: ParallelState, |
| 59 | + placement: WeightUpdatePlacement, |
| 60 | + selector: str, |
| 61 | + ) -> None: |
| 62 | + self.rollout_engines = rollout_engines |
| 63 | + self.cell_updaters_of_cell_id = create_rollout_cell_updaters(self.args, self.rollout_engines, engine_cell_ids) |
| 64 | + self.group_name = "miles-disk" |
| 65 | + self._replica_rank, self._replica_size = get_data_replica_rank_and_size(parallel_state, placement) |
| 66 | + self.is_sender = True |
| 67 | + |
| 68 | + def begin_sync(self, weight_version: int, iter_buckets) -> bool: |
| 69 | + self._version_dir = os.path.join(self.root_dir, f"weight_v{weight_version:06d}") |
| 70 | + self._weight_map = {} |
| 71 | + self._bucket_index = 0 |
| 72 | + self._owned_buckets = [] |
| 73 | + os.makedirs(self._version_dir, exist_ok=True) |
| 74 | + return True |
| 75 | + |
| 76 | + def send_bucket(self, bucket: list[tuple[str, torch.Tensor]]) -> None: |
| 77 | + if self._bucket_index % self._replica_size == self._replica_rank: |
| 78 | + self._owned_buckets.append((self._bucket_index, bucket)) |
| 79 | + self._bucket_index += 1 |
| 80 | + |
| 81 | + def after_base_weights(self) -> None: |
| 82 | + # written only after the collective gathers finish, so the ranks' host copies run in parallel |
| 83 | + for bucket_index, bucket in self._owned_buckets: |
| 84 | + tensors = {name: tensor.detach().to("cpu").contiguous() for name, tensor in bucket} |
| 85 | + shard = f"rank{dist.get_rank():03d}-shard{bucket_index:05d}.safetensors" |
| 86 | + safetensors.torch.save_file(tensors, os.path.join(self._version_dir, shard)) |
| 87 | + self._weight_map.update({name: shard for name in tensors}) |
| 88 | + self._owned_buckets = [] |
| 89 | + |
| 90 | + def finalize(self, weight_version: int) -> None: |
| 91 | + self._write_index() |
| 92 | + self._reload_engines(weight_version) |
| 93 | + self._drop_previous_version() |
| 94 | + |
| 95 | + def _write_index(self) -> None: |
| 96 | + weight_maps: list = [None] * dist.get_world_size() |
| 97 | + dist.all_gather_object(weight_maps, self._weight_map, group=get_gloo_group()) |
| 98 | + if dist.get_rank() == 0: |
| 99 | + weight_map = {name: shard for rank_map in weight_maps for name, shard in rank_map.items()} |
| 100 | + index = {"metadata": {}, "weight_map": weight_map} |
| 101 | + with open(os.path.join(self._version_dir, "model.safetensors.index.json"), "w") as f: |
| 102 | + json.dump(index, f) |
| 103 | + for fname in os.listdir(self.args.hf_checkpoint): |
| 104 | + path = os.path.join(self.args.hf_checkpoint, fname) |
| 105 | + if os.path.isfile(path) and not fname.endswith(_WEIGHT_FILE_SUFFIXES): |
| 106 | + shutil.copy(path, self._version_dir) |
| 107 | + logger.info("[disk] wrote %d tensors to %s", len(weight_map), self._version_dir) |
| 108 | + |
| 109 | + def _reload_engines(self, weight_version: int) -> None: |
| 110 | + if dist.get_rank() == 0: |
| 111 | + cell_updaters = list(self.cell_updaters_of_cell_id.values()) |
| 112 | + maybe_pause_engines(self.args, cell_updaters) |
| 113 | + results = async_utils.wait_futures( |
| 114 | + [ |
| 115 | + updater.submit_client_call( |
| 116 | + "update_weights_from_disk", model_path=self._version_dir, weight_version=str(weight_version) |
| 117 | + ) |
| 118 | + for updater in cell_updaters |
| 119 | + ] |
| 120 | + ) |
| 121 | + check_weight_sync_results(results, is_lora=False) |
| 122 | + maybe_resume_engines(self.args, cell_updaters) |
| 123 | + |
| 124 | + def _drop_previous_version(self) -> None: |
| 125 | + if dist.get_rank() == 0 and self._previous_version_dir not in (None, self._version_dir): |
| 126 | + shutil.rmtree(self._previous_version_dir, ignore_errors=True) |
| 127 | + self._previous_version_dir = self._version_dir |
0 commit comments