mlx icon indicating copy to clipboard operation
mlx copied to clipboard

[Feature request] Add metadata to safetensors saving and loading

Open mzbac opened this issue 2 years ago • 13 comments

Just found the model weight saved in SafeTensor by mlx cannot be loaded by Transformers. An error is thrown, stating that the format is not supported. This issue seems to caused from the metadata format being saved as mlx (https://github.com/ml-explore/mlx/blob/main/mlx/io/safetensor.cpp#L165). However, mlx has no trouble loading HF model weights. so, I'm curious about the differences in the saved weights between them. Thanks in advance.

mzbac avatar Feb 05 '24 22:02 mzbac

Hmm, that should not be the case. We don't save or load metadata from safetensors in MLX but that should not preclude them from being loading by HF safetensors (I think?). There might be a bug in how we save them if they cannot be loaded by the HF safetensor library.

CC @dc-dc-dc

awni avatar Feb 05 '24 22:02 awni

FYI, there is the code where the transformers throw an error -> https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_utils.py#L507

mzbac avatar Feb 05 '24 22:02 mzbac

Ah I see. That is actually expected. The metadata can contain anything. So the caller is just using the metadata there as a way to determine when it's safe to continue with the file they are loading. It's on the saver to put the right field in the metadata.

I'm curious, how did this come up? Were you trying to load a MLX saved model via Transformers?

awni avatar Feb 05 '24 22:02 awni

Yeah, I try to load the mlx fine-tuned model via transformer, so I can do some advanced quantization using gptq/awq. also, currently, mlx-lm lacks support for loading and sharing custom models., loading mlx model from transformer is the easiest way to share custom models at the moment.

mzbac avatar Feb 05 '24 22:02 mzbac

Got it.

  • I think I will change this to a feature request for metadata in save_safetensors. That's what we'd need for the current path to work
  • In the interim, you should be able to use the safetensors package directly to save the MLX weights:
>>> from safetensors.mlx import save_file
>>> import mlx.core as mx
>>> params = {"weight": mx.array([1.0, 2.0])}
>>> save_file(params, "model.safetensors", metadata={"format": "pt"})
>>> f = safe_open("model.safetensors", framework="pt")
>>> print(f.metadata())
{'format': 'pt'}
>>> f.get_tensor("weight")
tensor([1., 2.])

awni avatar Feb 05 '24 22:02 awni

Thanks, @awni. I will try the safetensors package for now

mzbac avatar Feb 05 '24 23:02 mzbac

I can add metadata support to our implementation.

I think that the temporary workaround should be used with caution as there are some slight differences in how we store data in comparison with torch. For example Convolutions are stored as BCHW in torch vs BHWC in mlx.

We might want to open a pr with transformers to handle mlx properly? Also this might impact us as well. Thoughts on this @awni

dc-dc-dc avatar Feb 05 '24 23:02 dc-dc-dc

  1. Adding metadata for MLX would be awesome!

  2. It's a great point re convolutions / caution with loading into a model from a different framework. But I don't think they will want to change it at the array i/o level which is quite unopinionated regarding how tensors are stored. My thought is that is better handled by reading metadata at the NN level.

awni avatar Feb 05 '24 23:02 awni

Would this enable to convert custom models not supported right now? I tried to convert a CodeT5 Transformer Model, but it doesnt seem supported yet so I figured I´d have to wait.

vincentdsf avatar Feb 07 '24 11:02 vincentdsf

@awni @dc-dc-dc I tried using the save_file function from safetensor.mx to save the weights, but I encountered an error: RuntimeError: Item size 2 for PEP 3118 buffer format string B does not match the dtype B item size 1., I have to convert the mx array back to fp32 and then convert it to torch.tensor before using save_file from safetensor.torch as a workaround. here is the code that I used to save the weights:

def save_weights(save_path: Union[str, Path], weights: Dict[str, Any]) -> None:
    if isinstance(save_path, str):
        save_path = Path(save_path)
    save_path.mkdir(parents=True, exist_ok=True)

    shards = make_shards(weights)
    shards_count = len(shards)
    shard_file_format = "model-{:05d}-of-{:05d}.safetensors" if shards_count > 1 else "model.safetensors"

    total_size = sum(v.nbytes for v in weights.values())
    index_data = {"metadata": {"total_size": total_size}, "weight_map": {}}

    for i, shard in enumerate(shards):
        shard_name = shard_file_format.format(i + 1, shards_count)
        shard_path = save_path / shard_name
        
        # shard = { k: np.array(v.astype(mx.float32)) for k, v in shard.items()}
        # shard = { k: torch.from_numpy(v).to(dtype=torch.bfloat16) for k, v in shard.items()}

        save_file(shard, str(shard_path), metadata={"format": "pt"}) // this doesn't work
        for tensor_name in shard.keys():
            index_data["weight_map"][tensor_name] = shard_name


    sorted_weight_map = {k: index_data["weight_map"][k] for k in sorted(index_data["weight_map"])}
    
    with open(save_path / 'model.safetensors.index.json', 'w') as f:
        json.dump({"metadata": index_data["metadata"], "weight_map": sorted_weight_map}, f, indent=4)

Please let me know if you need more details on how to replicate the error.

mzbac avatar Feb 07 '24 12:02 mzbac

Hmm, that is not an MLX bug but an issue with bfloat16 in safetensors.

awni avatar Feb 07 '24 13:02 awni

I filed an issue with safetensors: https://github.com/huggingface/safetensors/issues/436

awni avatar Feb 07 '24 13:02 awni

Looks like they are trying to convert to numpy before saving so bfloat wont work

dc-dc-dc avatar Feb 07 '24 16:02 dc-dc-dc