Repository: huggingface/transformers
File: src/transformers/integrations/deepspeed.py (Python)

Code before:
    # Apply the conversions and build the new state dict
    new_state_dict = {}
    for first_param_name, mapping in conversion_mapping.items():
        try:
            realized_value, _ = mapping.convert(
                first_param_name,
                model=model,
                config=model.config,
            )
            for target_name, param in realized_value.items():
                param = param[0] if isinstance(param, list) else param
                new_state_dict[target_name] = param
            # Free memory by clearing source tensors (only WeightConverter has this)
            if hasattr(mapping, "source_tensors"):
                mapping.source_tensors = {}
        except Exception as e:
            raise RuntimeError(
                f"Failed to apply weight conversion for '{first_param_name}'. "
                f"This likely means the checkpoint format is incompatible with the current model version. "
                f"Error: {e}"
            ) from e

    # Add any keys that didn't need conversion (use cached rename results)
    for key, tensor in sorted_state_dict:
        renamed_key = key_rename_cache[key]
        if renamed_key not in new_state_dict and renamed_key in meta_model_state_dict:
            new_state_dict[renamed_key] = tensor

    # Attach metadata to the new state dict
    if metadata is not None:
        new_state_dict._metadata = metadata

    return new_state_dict


def _load_state_dict_into_zero3_model(model_to_load, state_dict, load_config=None):
    """
    Loads state dict into a model specifically for Zero3, since DeepSpeed does not support the `transformers`
    tensor parallelism API.

    Nearly identical code to PyTorch's `_load_from_state_dict`

    Args:
        model_to_load: The model to load weights into
        state_dict: The state dict containing the weights
        load_config: Optional LoadStateDictConfig containing weight_mapping and other loading options
    """
    # copy state_dict so `_load_state_dict_into_zero3_model` can modify it
    metadata = getattr(state_dict, "_metadata", None)
    state_dict = state_dict.copy()
    if metadata is not None:

Review comment (suggestion):
```suggestion
        if renamed_key not in new_state_dict and renamed_key in model_state_dict:
```

Code after:
                source_pattern = original_key

            # Add the tensor directly (not a Future, since it's already materialized)
            mapping.add_tensor(renamed_key, original_key, source_pattern, tensor)

    # Apply the conversions and build the new state dict
    new_state_dict = {}
    # Track which renamed_keys came from WeightConverter (need to skip their originals)
    converted_renamed_keys = set()
    for renamed_key, mapping in conversion_mapping.items():
        try:
            # Only WeightConverter needs convert(); WeightRenaming is just a simple rename
            if not isinstance(mapping, WeightConverter):
                continue
            realized_value, _ = mapping.convert(
                renamed_key,
                model=model,
                config=model.config,
            )
            for target_name, param in realized_value.items():
                param = param[0] if isinstance(param, list) else param
                new_state_dict[target_name] = param
            # Track that this key was converted
            converted_renamed_keys.add(renamed_key)
            # Free memory by clearing source tensors
            if hasattr(mapping, "source_tensors"):
                mapping.source_tensors = {}
        except Exception as e:
            raise RuntimeError(
                f"Failed to apply weight conversion for '{renamed_key}'. "
                f"This likely means the checkpoint format is incompatible with the current model version. "
                f"Error: {e}"
            ) from e

    # Add any keys that didn't need conversion (use cached rename results)
    # At this point, state_dict only contains unconverted keys (others were popped)
    for key in list(state_dict.keys()):
        renamed_key = key_rename_cache.get(key)
        if renamed_key is None:
            # Key wasn't in our cache, compute rename
            renamed_key, _ = rename_source_key(key, renamings, [], prefix, model_state_dict)
        if renamed_key not in new_state_dict and renamed_key in model_state_dict:
            new_state_dict[renamed_key] = state_dict.pop(key)

    # Attach metadata to the new state dict
    if metadata is not None:
        new_state_dict._metadata = metadata

    return new_state_dict