Spaces:
Running
Running
feat: mlx-vlm support
Browse files- app.py +169 -28
- requirements.txt +5 -1
app.py
CHANGED
@@ -1,5 +1,7 @@
|
|
1 |
import os
|
2 |
import tempfile
|
|
|
|
|
3 |
|
4 |
os.environ["HF_HUB_CACHE"] = "cache"
|
5 |
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
@@ -15,9 +17,40 @@ from gradio_huggingfacehub_search import HuggingfaceHubSearch
|
|
15 |
from apscheduler.schedulers.background import BackgroundScheduler
|
16 |
|
17 |
from textwrap import dedent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
|
|
19 |
import mlx_lm
|
20 |
-
from mlx_lm import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
23 |
|
@@ -30,6 +63,64 @@ QUANT_PARAMS = {
|
|
30 |
"Q8": 8,
|
31 |
}
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
def list_files_in_folder(folder_path):
|
34 |
# List all files and directories in the specified folder
|
35 |
all_items = os.listdir(folder_path)
|
@@ -48,7 +139,7 @@ def clear_hf_cache_space():
|
|
48 |
scan.delete_revisions(*to_delete).execute()
|
49 |
print("Cache has been cleared")
|
50 |
|
51 |
-
def upload_to_hub(path, upload_repo, hf_path, oauth_token):
|
52 |
card = ModelCard.load(hf_path, token=oauth_token.token)
|
53 |
card.data.tags = ["mlx"] if card.data.tags is None else card.data.tags + ["mlx", "mlx-my-repo"]
|
54 |
card.data.base_model = hf_path
|
@@ -56,29 +147,9 @@ def upload_to_hub(path, upload_repo, hf_path, oauth_token):
|
|
56 |
f"""
|
57 |
# {upload_repo}
|
58 |
|
59 |
-
The Model [{upload_repo}](https://huggingface.co/{upload_repo}) was converted to
|
60 |
-
|
61 |
-
## Use with mlx
|
62 |
-
|
63 |
-
```bash
|
64 |
-
pip install mlx-lm
|
65 |
-
```
|
66 |
-
|
67 |
-
```python
|
68 |
-
from mlx_lm import load, generate
|
69 |
-
|
70 |
-
model, tokenizer = load("{upload_repo}")
|
71 |
-
|
72 |
-
prompt="hello"
|
73 |
-
|
74 |
-
if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
|
75 |
-
messages = [{{"role": "user", "content": prompt}}]
|
76 |
-
prompt = tokenizer.apply_chat_template(
|
77 |
-
messages, tokenize=False, add_generation_prompt=True
|
78 |
-
)
|
79 |
|
80 |
-
|
81 |
-
```
|
82 |
"""
|
83 |
)
|
84 |
card.save(os.path.join(path, "README.md"))
|
@@ -101,6 +172,76 @@ def upload_to_hub(path, upload_repo, hf_path, oauth_token):
|
|
101 |
|
102 |
print(f"Upload successful, go to https://huggingface.co/{upload_repo} for details.")
|
103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
def process_model(model_id, q_method, oauth_token: gr.OAuthToken | None):
|
105 |
if oauth_token.token is None:
|
106 |
raise ValueError("You must be logged in to use MLX-my-repo")
|
@@ -113,9 +254,9 @@ def process_model(model_id, q_method, oauth_token: gr.OAuthToken | None):
|
|
113 |
with tempfile.TemporaryDirectory(dir="converted") as tmpdir:
|
114 |
# The target directory must not exist
|
115 |
mlx_path = os.path.join(tmpdir, "mlx")
|
116 |
-
convert(model_id, mlx_path=mlx_path, quantize=False, dtype="float16")
|
117 |
print("Conversion done")
|
118 |
-
upload_to_hub(path=mlx_path, upload_repo=upload_repo, hf_path=model_id, oauth_token=oauth_token)
|
119 |
print("Upload done")
|
120 |
else:
|
121 |
q_bits = QUANT_PARAMS[q_method]
|
@@ -123,9 +264,9 @@ def process_model(model_id, q_method, oauth_token: gr.OAuthToken | None):
|
|
123 |
with tempfile.TemporaryDirectory(dir="converted") as tmpdir:
|
124 |
# The target directory must not exist
|
125 |
mlx_path = os.path.join(tmpdir, "mlx")
|
126 |
-
convert(model_id, mlx_path=mlx_path, quantize=True, q_bits=q_bits)
|
127 |
print("Conversion done")
|
128 |
-
upload_to_hub(path=mlx_path, upload_repo=upload_repo, hf_path=model_id, oauth_token=oauth_token)
|
129 |
print("Upload done")
|
130 |
return (
|
131 |
f'Find your repo <a href="https://hf.co/{upload_repo}" target="_blank" style="text-decoration:underline">here</a>',
|
|
|
1 |
import os
|
2 |
import tempfile
|
3 |
+
import importlib.util
|
4 |
+
from enum import Enum
|
5 |
|
6 |
os.environ["HF_HUB_CACHE"] = "cache"
|
7 |
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
|
|
17 |
from apscheduler.schedulers.background import BackgroundScheduler
|
18 |
|
19 |
from textwrap import dedent
|
20 |
+
from typing import (
|
21 |
+
Callable,
|
22 |
+
Dict,
|
23 |
+
Optional,
|
24 |
+
Union,
|
25 |
+
NamedTuple,
|
26 |
+
)
|
27 |
|
28 |
+
import mlx.nn as nn
|
29 |
import mlx_lm
|
30 |
+
from mlx_lm.utils import (
|
31 |
+
load_config,
|
32 |
+
get_model_path,
|
33 |
+
)
|
34 |
+
import mlx_vlm
|
35 |
+
|
36 |
+
|
37 |
+
# mlx-lm/mlx_lm/utils.py
|
38 |
+
MODEL_REMAPPING_MLX_LM = {
|
39 |
+
"mistral": "llama", # mistral is compatible with llama
|
40 |
+
"phi-msft": "phixtral",
|
41 |
+
"falcon_mamba": "mamba",
|
42 |
+
}
|
43 |
+
|
44 |
+
# mlx-vlm/mlx_vlm/utils.py
|
45 |
+
MODEL_REMAPPING_MLX_VLM = {
|
46 |
+
"llava-qwen2": "llava_bunny",
|
47 |
+
"bunny-llama": "llava_bunny",
|
48 |
+
}
|
49 |
+
|
50 |
+
MODEL_REMAPPING = {
|
51 |
+
**MODEL_REMAPPING_MLX_LM,
|
52 |
+
**MODEL_REMAPPING_MLX_VLM,
|
53 |
+
}
|
54 |
|
55 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
56 |
|
|
|
63 |
"Q8": 8,
|
64 |
}
|
65 |
|
66 |
+
class RuntimeInfo(NamedTuple):
|
67 |
+
name: str
|
68 |
+
package: str
|
69 |
+
version: str
|
70 |
+
convert_fn: Callable
|
71 |
+
usage_example: Callable[[str], str]
|
72 |
+
format: str = "MLX"
|
73 |
+
|
74 |
+
class Runtime(RuntimeInfo, Enum):
|
75 |
+
MLX_LM = RuntimeInfo(
|
76 |
+
name="MLX LM",
|
77 |
+
package="mlx-lm",
|
78 |
+
version=mlx_lm.__version__,
|
79 |
+
convert_fn=mlx_lm.convert,
|
80 |
+
usage_example=lambda upload_repo: dedent(
|
81 |
+
f"""
|
82 |
+
## Use with mlx
|
83 |
+
|
84 |
+
```bash
|
85 |
+
pip install mlx-lm
|
86 |
+
```
|
87 |
+
|
88 |
+
```python
|
89 |
+
from mlx_lm import load, generate
|
90 |
+
|
91 |
+
model, tokenizer = load("{upload_repo}")
|
92 |
+
|
93 |
+
prompt="hello"
|
94 |
+
|
95 |
+
if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
|
96 |
+
messages = [{{"role": "user", "content": prompt}}]
|
97 |
+
prompt = tokenizer.apply_chat_template(
|
98 |
+
messages, tokenize=False, add_generation_prompt=True
|
99 |
+
)
|
100 |
+
|
101 |
+
response = generate(model, tokenizer, prompt=prompt, verbose=True)
|
102 |
+
```
|
103 |
+
"""
|
104 |
+
)
|
105 |
+
)
|
106 |
+
MLX_VLM = RuntimeInfo(
|
107 |
+
name="MLX-VLM",
|
108 |
+
package="mlx-vlm",
|
109 |
+
version=mlx_vlm.__version__,
|
110 |
+
convert_fn=mlx_vlm.convert,
|
111 |
+
usage_example=lambda upload_repo: dedent(
|
112 |
+
f"""
|
113 |
+
```bash
|
114 |
+
pip install -U mlx-vlm
|
115 |
+
```
|
116 |
+
|
117 |
+
```bash
|
118 |
+
python -m mlx_vlm.generate --model {upload_repo} --max-tokens 100 --temp 0.0 --prompt "Describe this image." --image <path_to_image>
|
119 |
+
```
|
120 |
+
"""
|
121 |
+
)
|
122 |
+
)
|
123 |
+
|
124 |
def list_files_in_folder(folder_path):
|
125 |
# List all files and directories in the specified folder
|
126 |
all_items = os.listdir(folder_path)
|
|
|
139 |
scan.delete_revisions(*to_delete).execute()
|
140 |
print("Cache has been cleared")
|
141 |
|
142 |
+
def upload_to_hub(path, upload_repo, hf_path, oauth_token, runtime: Runtime):
|
143 |
card = ModelCard.load(hf_path, token=oauth_token.token)
|
144 |
card.data.tags = ["mlx"] if card.data.tags is None else card.data.tags + ["mlx", "mlx-my-repo"]
|
145 |
card.data.base_model = hf_path
|
|
|
147 |
f"""
|
148 |
# {upload_repo}
|
149 |
|
150 |
+
The Model [{upload_repo}](https://huggingface.co/{upload_repo}) was converted to ${runtime.format} format from [{hf_path}](https://huggingface.co/{hf_path}) using ${runtime.package} version **{runtime.version}**.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
|
152 |
+
{runtime.usage_example(upload_repo)}
|
|
|
153 |
"""
|
154 |
)
|
155 |
card.save(os.path.join(path, "README.md"))
|
|
|
172 |
|
173 |
print(f"Upload successful, go to https://huggingface.co/{upload_repo} for details.")
|
174 |
|
175 |
+
def convert(
|
176 |
+
hf_path: str,
|
177 |
+
mlx_path: str = "mlx_model",
|
178 |
+
quantize: bool = False,
|
179 |
+
q_group_size: int = 64,
|
180 |
+
q_bits: int = 4,
|
181 |
+
dtype: Optional[str] = None,
|
182 |
+
upload_repo: str = None,
|
183 |
+
revision: Optional[str] = None,
|
184 |
+
dequantize: bool = False,
|
185 |
+
quant_predicate: Optional[
|
186 |
+
Union[Callable[[str, nn.Module, dict], Union[bool, dict]], str]
|
187 |
+
] = None, # mlx-lm
|
188 |
+
skip_vision: bool = False, # mlx-vlm
|
189 |
+
trust_remote_code: bool = True, # mlx-vlm
|
190 |
+
) -> Runtime :
|
191 |
+
def mlx_lm_convert():
|
192 |
+
mlx_lm.convert(
|
193 |
+
hf_path=hf_path,
|
194 |
+
mlx_path=mlx_path,
|
195 |
+
quantize=quantize,
|
196 |
+
q_group_size=q_group_size,
|
197 |
+
q_bits=q_bits,
|
198 |
+
dtype=dtype,
|
199 |
+
upload_repo=upload_repo,
|
200 |
+
revision=revision,
|
201 |
+
dequantize=dequantize,
|
202 |
+
quant_predicate=quant_predicate,
|
203 |
+
)
|
204 |
+
|
205 |
+
def mlx_vlm_convert():
|
206 |
+
mlx_vlm.convert(
|
207 |
+
hf_path=hf_path,
|
208 |
+
mlx_path=mlx_path,
|
209 |
+
quantize=quantize,
|
210 |
+
q_group_size=q_group_size,
|
211 |
+
q_bits=q_bits,
|
212 |
+
dtype=dtype,
|
213 |
+
upload_repo=upload_repo,
|
214 |
+
revision=revision,
|
215 |
+
dequantize=dequantize,
|
216 |
+
skip_vision=skip_vision,
|
217 |
+
trust_remote_code=trust_remote_code,
|
218 |
+
)
|
219 |
+
|
220 |
+
model_path = get_model_path(hf_path, revision=revision)
|
221 |
+
config = load_config(model_path)
|
222 |
+
model_type = config["model_type"]
|
223 |
+
model_type = MODEL_REMAPPING.get(model_type, model_type)
|
224 |
+
|
225 |
+
is_lm = importlib.util.find_spec(f"mlx_lm.models.{model_type}") is not None
|
226 |
+
is_vlm = importlib.util.find_spec(f"mlx_vlm.models.{model_type}") is not None
|
227 |
+
|
228 |
+
if is_lm and (not is_vlm):
|
229 |
+
mlx_lm_convert()
|
230 |
+
runtime = Runtime.MLX_LM
|
231 |
+
elif is_vlm and (not is_lm):
|
232 |
+
mlx_vlm_convert()
|
233 |
+
runtime = Runtime.MLX_VLM
|
234 |
+
else:
|
235 |
+
# fallback in-case our MODEL_REMAPPING is outdated
|
236 |
+
try:
|
237 |
+
mlx_vlm_convert()
|
238 |
+
runtime = Runtime.MLX_VLM
|
239 |
+
except Exception as e:
|
240 |
+
mlx_lm_convert()
|
241 |
+
runtime = Runtime.MLX_LM
|
242 |
+
return runtime
|
243 |
+
|
244 |
+
|
245 |
def process_model(model_id, q_method, oauth_token: gr.OAuthToken | None):
|
246 |
if oauth_token.token is None:
|
247 |
raise ValueError("You must be logged in to use MLX-my-repo")
|
|
|
254 |
with tempfile.TemporaryDirectory(dir="converted") as tmpdir:
|
255 |
# The target directory must not exist
|
256 |
mlx_path = os.path.join(tmpdir, "mlx")
|
257 |
+
runtime = convert(model_id, mlx_path=mlx_path, quantize=False, dtype="float16")
|
258 |
print("Conversion done")
|
259 |
+
upload_to_hub(path=mlx_path, upload_repo=upload_repo, hf_path=model_id, oauth_token=oauth_token, runtime=runtime)
|
260 |
print("Upload done")
|
261 |
else:
|
262 |
q_bits = QUANT_PARAMS[q_method]
|
|
|
264 |
with tempfile.TemporaryDirectory(dir="converted") as tmpdir:
|
265 |
# The target directory must not exist
|
266 |
mlx_path = os.path.join(tmpdir, "mlx")
|
267 |
+
runtime = convert(model_id, mlx_path=mlx_path, quantize=True, q_bits=q_bits)
|
268 |
print("Conversion done")
|
269 |
+
upload_to_hub(path=mlx_path, upload_repo=upload_repo, hf_path=model_id, oauth_token=oauth_token, runtime=runtime)
|
270 |
print("Upload done")
|
271 |
return (
|
272 |
f'Find your repo <a href="https://hf.co/{upload_repo}" target="_blank" style="text-decoration:underline">here</a>',
|
requirements.txt
CHANGED
@@ -1,6 +1,10 @@
|
|
1 |
huggingface-hub
|
2 |
hf-transfer
|
3 |
gradio[oauth]>=4.28.0
|
|
|
4 |
gradio_huggingfacehub_search==0.0.7
|
5 |
APScheduler
|
6 |
-
mlx-lm
|
|
|
|
|
|
|
|
1 |
huggingface-hub
|
2 |
hf-transfer
|
3 |
gradio[oauth]>=4.28.0
|
4 |
+
gradio<5.0,>=4.0 # gradio-huggingfacehub-search 0.0.7 requires gradio<5.0,>=4.0
|
5 |
gradio_huggingfacehub_search==0.0.7
|
6 |
APScheduler
|
7 |
+
mlx-lm
|
8 |
+
mlx-vlm
|
9 |
+
torch
|
10 |
+
torchvision
|