| 4214 | |
| 4215 | @staticmethod |
| 4216 | def load_moe_state_dict(checkpoint_path, |
| 4217 | tag, |
| 4218 | state_dict, |
| 4219 | old_moe_load, |
| 4220 | model=None, |
| 4221 | mpu=None, |
| 4222 | num_experts=1, |
| 4223 | checkpoint_engine=TorchCheckpointEngine(), |
| 4224 | autoep_layers=None, |
| 4225 | folding_spec=None, |
| 4226 | checkpoint_mp_rank=None): |
| 4227 | if checkpoint_mp_rank is None: |
| 4228 | checkpoint_mp_rank = 0 if mpu is None else mpu.get_model_parallel_rank() |
| 4229 | |
| 4230 | try: |
| 4231 | from deepspeed.module_inject.auto_ep_layer import AutoEPMoELayer as _AutoEPMoELayer |
| 4232 | except ImportError: |
| 4233 | _AutoEPMoELayer = None |
| 4234 | |
| 4235 | has_autoep_layers = _AutoEPMoELayer is not None and model is not None and any( |
| 4236 | isinstance(m, _AutoEPMoELayer) for _, m in model.named_modules()) |
| 4237 | folded_autoep_tp = folding_spec is not None and folding_spec.tp_size > 1 |
| 4238 | |
| 4239 | if old_moe_load: |
| 4240 | if has_autoep_layers: |
| 4241 | raise RuntimeError("Legacy checkpoint format (old_moe_load) is incompatible with AutoEP layers. " |
| 4242 | "Use Universal Checkpointing to convert the checkpoint first.") |
| 4243 | expp_rank = groups._get_expert_data_parallel_rank(groups._get_max_expert_size_name()) |
| 4244 | |
| 4245 | num_local_experts = max(num_experts) // groups._get_expert_parallel_world_size( |
| 4246 | groups._get_max_expert_size_name()) |
| 4247 | for local_expert_id in range(num_local_experts): |
| 4248 | global_expert_id = expp_rank * num_local_experts + local_expert_id |
| 4249 | expert_state_dict = checkpoint_engine.load( |
| 4250 | DeepSpeedEngine._get_expert_ckpt_name( |
| 4251 | checkpoint_path, |
| 4252 | -1, # -1 means ignore layer_id |
| 4253 | global_expert_id, |
| 4254 | tag, |
| 4255 | checkpoint_mp_rank=checkpoint_mp_rank), |
| 4256 | map_location=torch.device('cpu')) |
| 4257 | |
| 4258 | # Updating global -> local expert ids |
| 4259 | moe_str_prefix = '.deepspeed_moe.experts.deepspeed_experts.' |
| 4260 | for key in list(expert_state_dict.keys()): |
| 4261 | local_key = key.replace(f'{moe_str_prefix}{global_expert_id}', |
| 4262 | f'{moe_str_prefix}{local_expert_id}') |
| 4263 | expert_state_dict[local_key] = expert_state_dict.pop(key) |
| 4264 | state_dict.update(expert_state_dict) |
| 4265 | |
| 4266 | else: |
| 4267 | # Validate AutoEP metadata if present |
| 4268 | if autoep_layers is not None: |
| 4269 | DeepSpeedEngine._validate_autoep_zero3_partitioned_metadata(autoep_layers, |
| 4270 | model=model, |
| 4271 | require_partitioned=False) |
| 4272 | elif has_autoep_layers: |
| 4273 | logger.warning("Checkpoint does not contain ds_autoep_layers metadata. " |