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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
| import sys import os
import fcntl
import json import time import torch from typing import List, Tuple, Union, Optional
from sglang.srt.server_args import ServerArgs, PortArgs
print(f"[SGLANG_PATCH] Patch Module loaded in process: {os.getpid()}")
def _patched_acquire_weight_lock(self, timeout=10): """acquire weight metadata saving file lock""" os.makedirs("weights_metadata", exist_ok=True) lock_file = os.path.join("weights_metadata", f"weight_saving_{self.gpu_id}.lock")
try: self._lock_fd = os.open(lock_file, os.O_CREAT | os.O_WRONLY) start_time = time.time()
while True: try: fcntl.flock(self._lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) return True except IOError: if time.time() - start_time > timeout: os.close(self._lock_fd) return False time.sleep(0.1) except Exception as e: return False
def _patched_release_weight_lock(self): """release weight metadata saving file lock""" if hasattr(self, '_lock_fd'): try: fcntl.flock(self._lock_fd, fcntl.LOCK_UN) os.close(self._lock_fd) lock_file = os.path.join("weights_metadata", f"weight_saving_{self.gpu_id}.lock") if os.path.exists(lock_file): os.remove(lock_file) finally: delattr(self, '_lock_fd')
def _patched_register_weight_hooks(self): self._clear_old_weight_data()
def tensor_hook(tensor: torch.Tensor, name: str): if tensor.is_cuda: self.weight_infos[name] = { "ptr": tensor.data_ptr(), "size": tensor.numel() * tensor.element_size(), "device": str(tensor.device), "dtype": str(tensor.dtype), "shape": list(tensor.shape) }
if not self._acquire_weight_lock(): raise RuntimeError("Failed to acquire weight metadata update lock")
for name, param in self.model.named_parameters(): tensor_hook(param, name) self._save_weight_meta() self.total_weight_dict = self._calculate_device_weight_sizes(unit="GB") self._save_total_weight_meta() self._release_weight_lock()
def _patched_save_weight_meta(self): os.makedirs("weights_metadata", exist_ok=True) meta_path = os.path.join("weights_metadata", f"weights_meta_{self.gpu_id}.json") try: with open(meta_path, 'w') as f: json.dump(self.weight_infos, f, indent=2) except IOError as e: raise
def _patched_save_total_weight_meta(self): os.makedirs("weights_metadata", exist_ok=True) meta_path = os.path.join("weights_metadata", f"total_weight_meta_{self.gpu_id}.json") try: with open(meta_path, 'w') as f: json.dump(self.total_weight_dict, f, indent=2) except IOError as e: raise
def _patched_calculate_device_weight_sizes(self, unit: str = "bytes") -> dict: """Calculate the total size of weights per device in self.weight_infos. Args: unit (str): The unit to return the size in. Options: "bytes", "KB", "MB", "GB". Returns: dict: {device: total_size} where total_size is in the specified unit. """ device_sizes = {}
for info in self.weight_infos.values(): device = info["device"] size = info["size"] if device in device_sizes: device_sizes[device] += size else: device_sizes[device] = size
unit = unit.upper() if unit == "KB": return {device: size / 1024 for device, size in device_sizes.items()} elif unit == "MB": return {device: size / (1024 ** 2) for device, size in device_sizes.items()} elif unit == "GB": return {device: size / (1024 ** 3) for device, size in device_sizes.items()} else: return device_sizes
def _patched_handle_weight_update_hooks(self): """ Handle weight updates during inference - clean old data and capture new weight information """ if not self._acquire_weight_lock(): raise RuntimeError("Failed to acquire weight metadata update lock")
self._clear_old_weight_data()
self._register_updated_weight_hooks()
self._save_updated_weight_metadata()
self._release_weight_lock()
def _patched_clear_old_weight_data(self): """ Clear old weight information and metadata files """ if hasattr(self, 'weight_infos'): self.weight_infos.clear() else: self.weight_infos = {}
if hasattr(self, 'total_weight_dict'): self.total_weight_dict.clear() else: self.total_weight_dict = {}
try: weights_dir = "weights_metadata" if os.path.exists(weights_dir): old_weight_file = os.path.join(weights_dir, f"weights_meta_{self.gpu_id}.json") old_total_file = os.path.join(weights_dir, f"total_weight_meta_{self.gpu_id}.json")
if os.path.exists(old_weight_file): os.remove(old_weight_file)
if os.path.exists(old_total_file): os.remove(old_total_file)
except Exception as e: return
def _patched_register_updated_weight_hooks(self): """ Register hooks for updated model weights (similar to _register_weight_hooks but for updates) """ def tensor_hook(tensor: torch.Tensor, name: str): if tensor.is_cuda: self.weight_infos[name] = { "ptr": tensor.data_ptr(), "size": tensor.numel() * tensor.element_size(), "device": str(tensor.device), "dtype": str(tensor.dtype), "shape": list(tensor.shape), "updated": True }
for name, param in self.model.named_parameters(): tensor_hook(param, name)
self.total_weight_dict = self._calculate_device_weight_sizes(unit="GB")
def _patched_save_updated_weight_metadata(self): """ Save updated weight metadata to JSON files """ try: self._save_weight_meta()
self._save_total_weight_meta()
self._save_weight_update_summary()
except Exception as e: return
def _patched_save_weight_update_summary(self): """ Save a summary of the weight update operation """ import time
summary = { "update_timestamp": time.time(), "update_time_readable": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "gpu_id": self.gpu_id, "total_weights": len(self.weight_infos), "total_devices": len(self.total_weight_dict), "device_weight_summary": self.total_weight_dict, "memory_usage_gb": sum(self.total_weight_dict.values()) if self.total_weight_dict else 0 }
os.makedirs("weights_metadata", exist_ok=True) summary_path = os.path.join("weights_metadata", f"weight_update_summary_{self.gpu_id}.json")
try: with open(summary_path, 'w') as f: json.dump(summary, f, indent=2) except IOError as e: return
def _patched_validate_weight_update(self): """ Validate that weight update was successful by checking if weights have new pointers """ if not self.weight_infos: return False
expected_weight_count = sum(1 for _ in self.model.named_parameters()) actual_weight_count = len(self.weight_infos)
if actual_weight_count != expected_weight_count: return False
cuda_weights = sum(1 for info in self.weight_infos.values() if "cuda" in info["device"]) if cuda_weights == 0: return False
return True
def _patched_update_weights_metadata(self): """ Public interface to update weight metadata """ try: self._handle_weight_update_hooks()
if self._validate_weight_update(): return True else: return False
except Exception as e: return False
def apply_model_runner_patches(): print(f"[PATCH] Applying model runner patches in process {os.getpid()}...") try: from sglang.srt.model_executor.model_runner import ModelRunner
ModelRunner._acquire_weight_lock = _patched_acquire_weight_lock ModelRunner._release_weight_lock = _patched_release_weight_lock ModelRunner._register_weight_hooks = _patched_register_weight_hooks ModelRunner._save_weight_meta = _patched_save_weight_meta ModelRunner._save_total_weight_meta = _patched_save_total_weight_meta ModelRunner._calculate_device_weight_sizes = _patched_calculate_device_weight_sizes ModelRunner._handle_weight_update_hooks = _patched_handle_weight_update_hooks ModelRunner._clear_old_weight_data = _patched_clear_old_weight_data ModelRunner._register_updated_weight_hooks = _patched_register_updated_weight_hooks ModelRunner._save_updated_weight_metadata = _patched_save_updated_weight_metadata ModelRunner._save_weight_update_summary = _patched_save_weight_update_summary ModelRunner._validate_weight_update = _patched_validate_weight_update ModelRunner.update_weights_metadata = _patched_update_weights_metadata
if not hasattr(ModelRunner, '_original_load_model'): ModelRunner._original_load_model = ModelRunner.load_model def patched_load_model(self): print("[PATCH] Patching ModelRunner.load_model to handle weight metadata loading") self._original_load_model() self._register_weight_hooks() ModelRunner.load_model = patched_load_model
if not hasattr(ModelRunner, '_original_update_weights_from_disk'): ModelRunner._original_update_weights_from_disk = ModelRunner.update_weights_from_disk def patched_update_weights_from_disk( self, model_path: str, load_format: str ) -> tuple[bool, str]: print("[PATCH] Patching ModelRunner.update_weights_from_disk to handle update weight metadata loading") result = self._original_update_weights_from_disk(model_path, load_format) self.update_weights_metadata() return result ModelRunner.update_weights_from_disk = patched_update_weights_from_disk
if not hasattr(ModelRunner, '_original_update_weights_from_tensor'): ModelRunner._original_update_weights_from_tensor = ModelRunner.update_weights_from_tensor def patched_update_weights_from_tensor( self, named_tensors: List[Tuple[str, Union[torch.Tensor, "LocalSerializedTensor"]]], load_format: Optional[str] = None, ): print("[PATCH] Patching ModelRunner.update_weights_from_tensor to handle update weight metadata loading") result = self._original_update_weights_from_tensor(named_tensors, load_format) self.update_weights_metadata() return result ModelRunner.update_weights_from_tensor = patched_update_weights_from_tensor
except Exception as e: print(f"[PATCH] Failed to apply ModelRunner patches: {e}") raise
def patched_run_scheduler_process( server_args: ServerArgs, port_args: PortArgs, gpu_id: int, tp_rank: int, pp_rank: int, dp_rank: Optional[int], pipe_writer, ): print(f"[PATCH] Patching run_scheduler_process for GPU {gpu_id}, TP rank {tp_rank}, PP rank {pp_rank}, DP rank {dp_rank} in process {os.getpid()} ...") apply_model_runner_patches()
import sglang.srt.managers.scheduler as scheduler_module
if not hasattr(scheduler_module, '_original_run_scheduler_process'): scheduler_module._original_run_scheduler_process = scheduler_module.run_scheduler_process
assert hasattr(scheduler_module, '_original_run_scheduler_process') scheduler_module._original_run_scheduler_process( server_args, port_args, gpu_id, tp_rank, pp_rank, dp_rank, pipe_writer )
def patched_run_data_parallel_controller_process( server_args: ServerArgs, port_args: PortArgs, pipe_writer, ): print(f"[PATCH] Patching run_data_parallel_controller_process in process {os.getpid()} ...") apply_model_runner_patches()
import sglang.srt.managers.data_parallel_controller as dp_controller_module
if not hasattr(dp_controller_module, '_original_run_data_parallel_controller_process'): dp_controller_module._original_run_data_parallel_controller_process = dp_controller_module.run_data_parallel_controller_process
assert hasattr(dp_controller_module, '_original_run_data_parallel_controller_process') dp_controller_module._original_run_data_parallel_controller_process(server_args, port_args, pipe_writer)
def apply_entrypoint_patches(): print(f"[PATCH] Applying entrypoint patches for SGLang server in {os.getpid()} ...")
try: import sglang.srt.managers.scheduler as scheduler_module import sglang.srt.managers.data_parallel_controller as dp_controller_module
if not hasattr(scheduler_module, '_original_run_scheduler_process'): scheduler_module._original_run_scheduler_process = scheduler_module.run_scheduler_process
scheduler_module.run_scheduler_process = patched_run_scheduler_process
if not hasattr(dp_controller_module, '_original_run_data_parallel_controller_process'): dp_controller_module._original_run_data_parallel_controller_process = dp_controller_module.run_data_parallel_controller_process
dp_controller_module.run_data_parallel_controller_process = patched_run_data_parallel_controller_process
except Exception as e: print(f"[PATCH] Failed to import necessary modules for entrypoint patching: {e}") raise
|