Skip to content

Contribute Hugging Face models to the MLX Community #155

Open

Description

@awni

We encourage you to join the MLX Community on Hugging Face 🤗 and upload new MLX converted models and versions of existing models.

Activity

  1. pinned this issue on Dec 20, 2023
  2. Vaibhavs10 commented on Dec 20, 2023

    @Vaibhavs10
    Contributor

    Love it! Here's some more information about uploading to the 🤗 hub.

    Once you've converted the checkpoints via the convert.py files in the respective model directory, you can upload large files over to the hub as follows:

    First, make sure to install huggingface_hub via pip install --upgrade huggingface_hub.

    Second, run huggingface-cli login and paste a write token over from https://huggingface.co/settings/tokens.

    Next, run the below code:

    from huggingface_hub import HfApi
    from huggingface_hub import logging
    
    logging.set_verbosity_info()
    
    api = HfApi()
    
    api.upload_folder(folder_path="<LOCAL FOLDER PATH>", 
                      repo_id="mlx-community/<MODEL_NAME>", 
                      repo_type="model", 
                      multi_commits=True, 
                      multi_commits_verbose=True)

    Read more here about file uploads here: https://huggingface.co/docs/huggingface_hub/guides/upload

  3. maxtheman commented on Dec 20, 2023

    @maxtheman

    Is there any more information about what's needed to author a convert.py for a given model? I'm seeing a lot of similarities between them in terms of loading the weights and then grouping into a .npz file but I'm not clear what's driving all of the differences.

    Bert needs lots of keys replaced: https://github.com/ml-explore/mlx-examples/blob/main/bert/convert.py
    Phi needs some: https://github.com/ml-explore/mlx-examples/blob/main/llms/phi2/convert.py
    Mistral doesn't need any, very straightforward: https://github.com/ml-explore/mlx-examples/blob/main/llms/mistral/convert.py
    and Mixtral has a bunch of stuff going on, but I think mostly for handling the MoE architecture.

    In my case — I was just looking at converting Mamba to MLX. I think I have a good reference implementation for running the model but I'm having trouble understanding how I would convert the weights appropriately to test it. Looking at the repo on HF it's not obvious to me what I should be keying in on to start making decisions. https://huggingface.co/state-spaces/mamba-370m/tree/main

    Any suggestions are appreciated.

  4. awni commented on Dec 20, 2023

    @awni
    MemberAuthor

    It's a bit more of an art at this point, we've been pushing for some standardization / consistency which is why things look the same. But there are still some subtle differences.

    The short answer to your question is:

    The output of convert.py should be two things:

    1. weights.npz (or multiple weights files for large models)
    2. config.json (to store the model metadata). Add a model_type field to this (for now it's unused, but will be important to work with Hugging Face in the future).

    Beyond that it's really up to you how to structure the weights.npz and the config.json. You just need to be able to load them and construct the model in the file which actually runs the model. For the examples in mlx-examples, the weights.npz has keys which match the nn.Module hierarchy of the corresponding model. So you can basically do:

    model.load_weights("weights.npz")
    

    So to make that work cleanly, in the conversion code remap the keys in the PyTorch model state_dicts so they match the keys expected by the MLX model.

  5. mzbac commented on Dec 21, 2023

    @mzbac
    Contributor

    @awni Thanks for this great initiative. I'm just curious why we can't provide the conversion script for people to convert the HF format model to mlx format? For example, the current conversion script for tiny_llama is pretty much compatible with the llama mode in HF format. What's the reason behind naming it as tinay_llama instead of something like hf_llama? https://github.com/ml-explore/mlx-examples/blob/main/llms/llama/convert.py#L54

  6. awni commented on Dec 21, 2023

    @awni
    MemberAuthor

    @mzbac that's a good question. Since different models have slight differences, we are doing a convention now where each model gets a converter. The underlying converters can use HF format (as in Tiny Llama) or original distributed format (as in Llama).

    I know it's a bit convoluted at the moment. As we work with the community and you all we'll work towards simplifying and standardizing. Any suggestions and/or pinpoints on that front are appreciated.

    PS the short term future I would like to move towards is to avoid a pre conversion step entirely:

    1. Read the repo from HF in the safetensors format directly
    2. Do any necessary remapping of keys in the weights and config on a model specific basis to make it all work

    And someday MLX in Transformers directly, so no model.py file necessary either :)

  7. mzbac commented on Dec 22, 2023

    @mzbac
    Contributor

    It would be better if we provided a script for downloading the models. That way, people wouldn't have to install git-lfs and pull the model via git.
    Here is an example script I used in the past to pull the public model from Hugging Face.

    import argparse
    import requests
    import os
    from tqdm import tqdm
    
    def download_file(url, path):
        response = requests.get(url, stream=True)
        total_size_in_bytes = int(response.headers.get('content-length', 0))
        block_size = 1024 #1 Kbyte
        progress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True)
    
        with open(path, 'wb') as file:
            for data in response.iter_content(block_size):
                progress_bar.update(len(data))
                file.write(data)
                
        progress_bar.close()
    
    def download_model(model_name, destination_folder="models"):
        # Define the base URL and headers for the Hugging Face API
        base_url = f"https://huggingface.co/{model_name}/resolve/main"
        headers = {"User-Agent": "Hugging Face Python"}
    
        # Send a GET request to the Hugging Face API to get a list of all files
        response = requests.get(f"https://huggingface.co/api/models/{model_name}", headers=headers)
        response.raise_for_status()
        
        # Extract the list of files from the response JSON
        files_to_download = [file["rfilename"] for file in response.json()["siblings"]]
    
        # Ensure the directory exists
        os.makedirs(f"{destination_folder}/{model_name}", exist_ok=True)
    
        # Download each file
        for file in files_to_download:
            print(f"Downloading {file}...")
            download_file(f"{base_url}/{file}", f"{destination_folder}/{model_name}/{file}")
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.add_argument("model_name", type=str, help="Name of the model to download.")
        args = parser.parse_args()
    
        download_model(args.model_name)

    Just run

    python download.py <huggingface_model_name> .eg. mlx-community/Llama-2-7b-chat-mlx
  8. rupurt commented on Jan 3, 2024

    @rupurt

    @maxtheman I would also love to try an run mamba models with MLX. Did you end up finding any good resources?

  9. Vaibhavs10 commented on Jan 4, 2024

    @Vaibhavs10
    Contributor

    Hi all, I hope you are doing well. With recently merged support for hf_llms, you should be able to use models directly from the Hugging Face Hub (Mistral and llama architectures are currently supported). 🔥

    In addition to this we've shipped an updated conversion script - which allows you to provide a HF Hub model name and it automagically quantises and uploads the weights to mlx-community org.

    You would need to do the following:

    1. git clone https://github.com/ml-explore/mlx-examples

    2. cd mlx-examples/llms/hf_llms

    3. pip install -r requirements.txt

    4. python convert. py --hf-path "codellama/CodeLlama-13b-Python-hf" -q --upload-name CodeLlama-13b-Python-hf-4bit-mlx

    That's it!

    Help us increase the coverage of MLX quantised checkpoints by quantising llama & mistral checkpoints from the hub.

    Note: Currently, there is a minor bug in the conversion script, which errors out on upload. You can check out this PR (#221) for conversion.

    Edit: The PR is now merged, so no need to worry about the Note above.

    P.S. Feel free to tag @awni, @pcuenca or me (@Vaibhavs10) if you face any issues!

  10. sukkritsharmaofficial commented on Jan 4, 2024

    @sukkritsharmaofficial

    Hey @Vaibhavs10 , i'm getting this error while quantizing hf models to 4bit mlx :

    self.weight, self.scales, self.biases = mx.quantize(weight, group_size, bits)
    ValueError: [quantize] All dimensions should be divisible by 32 for now

    conversion script :

    python convert.py --hf-path "teknium/OpenHermes-2.5-Mistral-7B" -q --upload-name OpenHermes-2.5-Mistral-7B-hf-4bit-mlx

    how do i fix this?

  11. awni commented on Jan 4, 2024

    @awni
    MemberAuthor

    @sukkritsharmaofficial check the issue here for the reason.

    Looking at that model I think it's possible the issue is the vocab size is not divisible by 32 (I see in the config "vocab_size": 32002). That's a tricky one. It may need to wait for non-32 multiples.

    CC @angeloskath

  12. tingbaozhao commented on Feb 1, 2024

    @tingbaozhao

    Hi all, I hope you are doing well. With recently merged support for hf_llms, you should be able to use models directly from the Hugging Face Hub (Mistral and llama architectures are currently supported). 🔥

    In addition to this we've shipped an updated conversion script - which allows you to provide a HF Hub model name and it automagically quantises and uploads the weights to mlx-community org.

    You would need to do the following:

    1. git clone https://github.com/ml-explore/mlx-examples
    2. cd mlx-examples/llms/hf_llms
    3. pip install -r requirements.txt
    4. python convert. py --hf-path "codellama/CodeLlama-13b-Python-hf" -q --upload-name CodeLlama-13b-Python-hf-4bit-mlx

    That's it!

    Help us increase the coverage of MLX quantised checkpoints by quantising llama & mistral checkpoints from the hub.

    Note: Currently, there is a minor bug in the conversion script, which errors out on upload. You can check out this PR (#221) for conversion.

    Edit: The PR is now merged, so no need to worry about the Note above.

    P.S. Feel free to tag @awni, @pcuenca or me (@Vaibhavs10) if you face any issues!

    the link is not exists ? click hf_llms, i got a 404 error !

  13. mzbac commented on Feb 1, 2024

    @mzbac
    Contributor

    Hi all, I hope you are doing well. With recently merged support for hf_llms, you should be able to use models directly from the Hugging Face Hub (Mistral and llama architectures are currently supported). 🔥
    In addition to this we've shipped an updated conversion script - which allows you to provide a HF Hub model name and it automagically quantises and uploads the weights to mlx-community org.
    You would need to do the following:

    1. git clone https://github.com/ml-explore/mlx-examples
    2. cd mlx-examples/llms/hf_llms
    3. pip install -r requirements.txt
    4. python convert. py --hf-path "codellama/CodeLlama-13b-Python-hf" -q --upload-name CodeLlama-13b-Python-hf-4bit-mlx

    That's it!
    Help us increase the coverage of MLX quantised checkpoints by quantising llama & mistral checkpoints from the hub.
    Note: Currently, there is a minor bug in the conversion script, which errors out on upload. You can check out this PR (#221) for conversion.
    Edit: The PR is now merged, so no need to worry about the Note above.
    P.S. Feel free to tag @awni, @pcuenca or me (@Vaibhavs10) if you face any issues!

    the link is not exists ? click hf_llms, i got a 404 error !

    It has been moved to https://github.com/ml-explore/mlx-examples/tree/main/llms :)

  14. Anirud-Mohan commented on Feb 15, 2024

    @Anirud-Mohan

    hey @awni , I'm trying to fuse my finetuned model into a GGUF file. But while I execute the fuse command, I'm getting list index out of range error. The fuse command I used is as follows :
    python fuse.py --model mistralai/Mistral-7B-Instruct-v0.2 --save-path ./lora-fused-model --adapter-file adapters.npz --de-quantize

    The error thrown is as follows :
    File "/Users/tis-ai-server/workspace/mlx-examples/.venv/lib/python3.11/site-packages/mlx/utils.py", line 123, in tree_unflatten int(tree[0][0].split(".", maxsplit=1)[0]) ~~~~^^^ IndexError: list index out of range

  15. awni commented on Feb 15, 2024

    @awni
    MemberAuthor

    That is strange. Can you share the full stack trace so we can see more precisely the issue arises?

  16. Anirud-Mohan commented on Feb 15, 2024

    @Anirud-Mohan

    @awni Here's the full stack trace, hope this helps :

    None of PyTorch, TensorFlow >= 2.0, or Flax have been found. Models won't be available and only tokenizers, configuration and file/data utilities can be used. Loading pretrained model Fetching 11 files: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████| 11/11 [00:00<00:00, 109071.74it/s] Traceback (most recent call last): File "/Users/tis-ai-server/workspace/mlx-examples/lora/fuse.py", line 98, in <module> model.update_modules(tree_unflatten(de_quantize_layers)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/tis-ai-server/workspace/mlx-examples/.venv/lib/python3.11/site-packages/mlx/utils.py", line 123, in tree_unflatten int(tree[0][0].split(".", maxsplit=1)[0]) ~~~~^^^ IndexError: list index out of range

  17. sukhvir1313 commented on Mar 23, 2024

    @sukhvir1313

    @awni Here's the full stack trace, hope this helps :

    None of PyTorch, TensorFlow >= 2.0, or Flax have been found. Models won't be available and only tokenizers, configuration and file/data utilities can be used. Loading pretrained model Fetching 11 files: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████| 11/11 [00:00<00:00, 109071.74it/s] Traceback (most recent call last): File "/Users/tis-ai-server/workspace/mlx-examples/lora/fuse.py", line 98, in <module> model.update_modules(tree_unflatten(de_quantize_layers)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/tis-ai-server/workspace/mlx-examples/.venv/lib/python3.11/site-packages/mlx/utils.py", line 123, in tree_unflatten int(tree[0][0].split(".", maxsplit=1)[0]) ~~~~^^^ IndexError: list index out of range

    Any updates on this error, I am also receiving this kind of error.

  18. awni commented on Mar 23, 2024

    @awni
    MemberAuthor

    Can you share steps to reproduce?

  19. sukhvir1313 commented on Mar 24, 2024

    @sukhvir1313

    Can you share steps to reproduce?

    Below is the command and result that I got.

    `conda activate AppleMLXExample

    (AppleMLXExample) usermlx@MacBook-Pro lora % python fuse.py --model mistralai/Mistral-7B-Instruct-v0.2 --adapter-file adapters.npz --save-path Models/My-Mistral-7B-fine-tuned --upload-name My-Mistral-7B-fine-tuned --de-quantize
    Loading pretrained model
    Fetching 11 files: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 11/11 [00:00<00:00, 111983.84it/s]
    Traceback (most recent call last):
    File "/Users/usermlx/Documents/Me/programming/ai/mlx-examples/lora/fuse.py", line 98, in
    model.update_modules(tree_unflatten(de_quantize_layers))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/Users/usermlx/miniconda3/envs/AppleMLXExample/lib/python3.11/site-packages/mlx/utils.py", line 122, in tree_unflatten
    int(tree[0][0].split(".", maxsplit=1)[0])
    ~~~~^^^
    IndexError: list index out of range`

  20. mzbac commented on Mar 24, 2024

    @mzbac
    Contributor

    Can you share steps to reproduce?

    Below is the command and result that I got.

    `conda activate AppleMLXExample

    (AppleMLXExample) usermlx@MacBook-Pro lora % python fuse.py --model mistralai/Mistral-7B-Instruct-v0.2 --adapter-file adapters.npz --save-path Models/My-Mistral-7B-fine-tuned --upload-name My-Mistral-7B-fine-tuned --de-quantize Loading pretrained model Fetching 11 files: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 11/11 [00:00<00:00, 111983.84it/s] Traceback (most recent call last): File "/Users/usermlx/Documents/Me/programming/ai/mlx-examples/lora/fuse.py", line 98, in model.update_modules(tree_unflatten(de_quantize_layers)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/usermlx/miniconda3/envs/AppleMLXExample/lib/python3.11/site-packages/mlx/utils.py", line 122, in tree_unflatten int(tree[0][0].split(".", maxsplit=1)[0]) ~~~~^^^ IndexError: list index out of range`

    It seems like this was caused by trying to de-quantize a non-quantized model. Would you try running the fuse without the --de-quantize flag?

  21. sukhvir1313 commented on Mar 24, 2024

    @sukhvir1313
  22. DePasqualeOrg commented on Feb 28, 2025

    @DePasqualeOrg
    Contributor

    I just wanted to note some UX issues that I encountered when converting and uploading a repo to the Hub. I'm sure there are nuances that I'm missing, but I think the UX could be improved. I have a notebook that converts the model like this:

    # The original model will be downloaded to ~/.cache/huggingface/hub
    hub_id = 'microsoft/Phi-4-mini-instruct'
    q_bits = 4
    
    model_name = hub_id.split('/')[-1]
    # The converted model will be saved to this directory
    output_path = f'mlx-community/{model_name}-{q_bits}bit'
    quantize = True
    
    mlx_lm.convert(hf_path=hub_id, mlx_path=output_path, quantize=quantize, q_bits=q_bits)

    I generally want to convert and test the model first before uploading to the Hub.

    However, I noticed that no readme is being generated. I suppose it will be generated if I set upload_repo in mlx_lm.convert? But now I have no readme when I upload my repo, and I don't know how to generate one. Also, the license and other tags are not set automatically. I have to set them manually, and even then it doesn't match the other repos I see in MLX Community.

    I created a git repo in the resulting directory. I created a repo in MLX Community on Hugging Face and set its URL as the remote in my git repo. Then I pushed the repo to the remote, but I got an error because vocab.json was not added as a large file. I had to run some git commands to fix that.

    Another issue I noticed is that there is a commonly followed naming convention in the MLX Community (in this case: Phi-4-mini-instruct-4bit), but some people use a divergent naming scheme. It would be great if the tools we use to convert and upload would automatically generate a name that follows the most common convention.

  23. awni commented on Feb 28, 2025

    @awni
    MemberAuthor

    Yes, the README is only created when you set upload_repo.

    One way to do what you want is:

    • Convert without upload and test
    • Re-convert with upload

    Converting is not so expensive.. unless it's a very very big model.

    That said, it should not be too difficult to:

    1. Save the card in the conversion step rather than the upload step. That has some sense to it.
    2. Have an "upload only" mode which uploads a model from a given path so you don't have to reconvert after testing.

    Regarding naming conventions:

    • This is difficult to control and standardize. We can make a best effort, but given the mlx-community is publicly open it will be hard to ensure every model follows a strict pattern.
    • One thing that would be useful is to put it in the community readme.
    • That said, if you want to ensure a model is a certain quant, the most reliable way is to check it's quantization config in the model config json
  24. KatoStevenMubiru commented on Aug 24, 2025

    @KatoStevenMubiru

    Hi all 👋,

    I'm working with Crane AI Labs, where we've been developing and open-sourcing African language LLMs on Hugging Face (e.g. Swahili-Gemma : https://huggingface.co/CraneAILabs/swahili-gemma-1b).

    We'd love to contribute these models to the MLX Community so they can run natively on Apple Silicon (M1/M2/M3) and be easily accessible to developers via MLX.

    Questions

    1. Would it be best to create a new repo under mlx-community/ (e.g. mlx-community/swahili-gemma-1b-mlx) after conversion + quantization, or to contribute conversion scripts back to this repo?

    2. Since Gemma models are supported in Hugging Face Transformers, is there guidance for extending the hf_llms conversion workflow to cover Gemma as well (similar to Mistral/Llama)?

    3. We'd like to benchmark and document Apple Silicon performance (tokens/sec, memory) — is there a recommended format so it's consistent with other MLX Community models?

    Our Goal

    Our goal is to make African-language models first-class citizens in the Apple MLX ecosystem and open them up for wider developer use. Happy to do the conversion and push the models — just want to make sure we align with community standards.

    Thanks for leading this awesome initiative 🚀

    — Kato Steven Mubiru

  25. awni commented on Aug 25, 2025

    @awni
    MemberAuthor

    Would it be best to create a new repo under mlx-community/ (e.g. mlx-community/swahili-gemma-1b-mlx) after conversion + quantization, or to contribute conversion scripts back to this repo?

    Yes you can easily make a new repo in mlx-community. You just have to be a member (and membership is open)

    Since Gemma models are supported in Hugging Face Transformers, is there guidance for extending the hf_llms conversion workflow to cover Gemma as well (similar to Mistral/Llama)?

    Not sure I'm following your question. But it sounds like a question for Transformers.

    We'd like to benchmark and document Apple Silicon performance (tokens/sec, memory) — is there a recommended format so it's consistent with other MLX Community models?

    I would use mlx-lm to benchmark tokens/sec and memory. There is no specific format.. you can benchmark quantized or unquantized models, just good to be clear in the benchmark what it is.

  26. KatoStevenMubiru commented on Aug 26, 2025

    @KatoStevenMubiru

    Thanks for the quick response, @awni!

    Appreciate the guidance—this aligns perfectly with our goals at Crane AI Labs.We've joined the mlx-community org (membership was seamless, as you mentioned) and have now uploaded our first converted model: Swahili-Gemma-1B in FP16 precision.

    You can check it out here: https://huggingface.co/mlx-community/swahili-gemma-1b-mlx-fp16. We created a new repo under mlx-community/ (mlx-community/swahili-gemma-1b-mlx-fp16) after converting from our base HF model (CraneAILabs/swahili-gemma-1b) using mlx-lm. For now, we focused on FP16 to verify compatibility, but we're planning quantized variants (e.g., 4-bit) soon to optimize for lower memory and faster inference on Apple Silicon.

    Regarding the hf_llms workflow: Understood— we'll direct any Gemma-specific questions to the Transformers team if needed. Gemma support worked smoothly out-of-the-box with mlx-lm

    We're excited to make African-language models like this one first-class in the MLX ecosystem—potentially the first of its kind optimized for Apple Silicon.

    We'll continue aligning with community standards, adding more models (e.g., other African languages), and polishing cards with consistent benchmarks.

    Thanks again for the support—happy to iterate based on feedback!

    Kato Steven Mubiru

  27. pcuenca commented on Aug 27, 2025

    @pcuenca
    Contributor

    Hello @KatoStevenMubiru, Hugging Face team member here. Thanks a lot for your contribution, and looking forward for more models! 🥳 Please, don't hesitate to open an issue in the transformers repo if you experience friction with the process!

  28. KatoStevenMubiru commented on Aug 27, 2025

    @KatoStevenMubiru

    Thanks so much, @pcuenca! 🙏 We’ll be adding more African language models in the coming weeks to expand this effort, and we’re also excited to contribute directly to the Hugging Face Transformers repo where relevant.

    We’d love to explore opportunities for deeper collaboration with the Hugging Face and Apple teams on AI-related open-source work, similar to how we’ve been engaging with the Google and Meta teams. Our goal is to make African language models first-class citizens in these ecosystems, optimized for Apple Silicon and beyond.

    Looking forward to building together! 🚀

  29. hermitdave commented on Sep 10, 2026

    @hermitdave

    I am facing a token error when trying to upload model to mlx community namespace. It works for my personal namespace without issues

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions