| 4296 | |
| 4297 | @staticmethod |
| 4298 | def load_moe_state_dict(checkpoint_path, |
| 4299 | tag, |
| 4300 | state_dict, |
| 4301 | old_moe_load, |
| 4302 | model=None, |
| 4303 | mpu=None, |
| 4304 | num_experts=1, |
| 4305 | checkpoint_engine=TorchCheckpointEngine(), |
| 4306 | autoep_layers=None, |
| 4307 | folding_spec=None, |
| 4308 | checkpoint_mp_rank=None): |
| 4309 | if checkpoint_mp_rank is None: |
| 4310 | checkpoint_mp_rank = 0 if mpu is None else mpu.get_model_parallel_rank() |
| 4311 | |
| 4312 | try: |
| 4313 | from deepspeed.module_inject.auto_ep_layer import AutoEPMoELayer as _AutoEPMoELayer |
| 4314 | except ImportError: |
| 4315 | _AutoEPMoELayer = None |
| 4316 | |
| 4317 | has_autoep_layers = _AutoEPMoELayer is not None and model is not None and any( |
| 4318 | isinstance(m, _AutoEPMoELayer) for _, m in model.named_modules()) |
| 4319 | folded_autoep_tp = folding_spec is not None and folding_spec.tp_size > 1 |
| 4320 | |
| 4321 | if old_moe_load: |
| 4322 | if has_autoep_layers: |
| 4323 | raise RuntimeError("Legacy checkpoint format (old_moe_load) is incompatible with AutoEP layers. " |
| 4324 | "Use Universal Checkpointing to convert the checkpoint first.") |
| 4325 | expp_rank = groups._get_expert_data_parallel_rank(groups._get_max_expert_size_name()) |
| 4326 | |
| 4327 | num_local_experts = max(num_experts) // groups._get_expert_parallel_world_size( |
| 4328 | groups._get_max_expert_size_name()) |
| 4329 | for local_expert_id in range(num_local_experts): |
| 4330 | global_expert_id = expp_rank * num_local_experts + local_expert_id |
| 4331 | expert_state_dict = checkpoint_engine.load( |
| 4332 | DeepSpeedEngine._get_expert_ckpt_name( |
| 4333 | checkpoint_path, |
| 4334 | -1, # -1 means ignore layer_id |
| 4335 | global_expert_id, |
| 4336 | tag, |
| 4337 | checkpoint_mp_rank=checkpoint_mp_rank), |
| 4338 | map_location=torch.device('cpu')) |
| 4339 | |
| 4340 | # Updating global -> local expert ids |
| 4341 | moe_str_prefix = '.deepspeed_moe.experts.deepspeed_experts.' |
| 4342 | for key in list(expert_state_dict.keys()): |
| 4343 | local_key = key.replace(f'{moe_str_prefix}{global_expert_id}', |
| 4344 | f'{moe_str_prefix}{local_expert_id}') |
| 4345 | expert_state_dict[local_key] = expert_state_dict.pop(key) |
| 4346 | state_dict.update(expert_state_dict) |
| 4347 | |
| 4348 | else: |
| 4349 | # Validate AutoEP metadata if present |
| 4350 | if autoep_layers is not None: |
| 4351 | DeepSpeedEngine._validate_autoep_zero3_partitioned_metadata(autoep_layers, |
| 4352 | model=model, |
| 4353 | require_partitioned=False) |
| 4354 | elif has_autoep_layers: |
| 4355 | logger.warning("Checkpoint does not contain ds_autoep_layers metadata. " |