-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
llm_gguf.py
367 lines (329 loc) · 12.3 KB
/
llm_gguf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import click
import httpx
import json
from llama_cpp import Llama
from llama_cpp import llama_chat_format
import llm
import pathlib
def _ensure_models_dir():
directory = llm.user_dir() / "gguf" / "models"
directory.mkdir(parents=True, exist_ok=True)
return directory
def _ensure_models_file():
directory = llm.user_dir() / "gguf"
directory.mkdir(parents=True, exist_ok=True)
filepath = directory / "models.json"
if not filepath.exists():
filepath.write_text("{}")
return filepath
def _ensure_embed_models_file():
directory = llm.user_dir() / "gguf"
directory.mkdir(parents=True, exist_ok=True)
filepath = directory / "embed-models.json"
if not filepath.exists():
filepath.write_text("{}")
return filepath
@llm.hookimpl
def register_models(register):
models_file = _ensure_models_file()
models = json.loads(models_file.read_text())
for model_id, info in models.items():
model_path = info["path"]
aliases = info.get("aliases", [])
clip_model_path = info.get("clip_model_path")
chat_handler_class = info.get("chat_handler_class")
model_id = f"gguf/{model_id}"
model = GgufChatModel(
model_id,
model_path,
clip_model_path=clip_model_path,
chat_handler_class=chat_handler_class,
n_ctx=info.get("n_ctx", 0),
)
register(model, aliases=aliases)
@llm.hookimpl
def register_embedding_models(register):
models_file = _ensure_embed_models_file()
models = json.loads(models_file.read_text())
for model_id, info in models.items():
model_path = info["path"]
aliases = info.get("aliases", [])
model_id = f"gguf/{model_id}"
model = GgufEmbeddingModel(model_id, model_path)
register(model, aliases=aliases)
@llm.hookimpl
def register_commands(cli):
@cli.group()
def gguf():
"Commands for working with GGUF models"
@gguf.command()
def models_file():
"Display the path to the gguf/models.json file"
directory = llm.user_dir() / "gguf"
directory.mkdir(parents=True, exist_ok=True)
models_file = directory / "models.json"
click.echo(models_file)
@gguf.command()
def embed_models_file():
"Display the path to the gguf/embed-models.json file"
directory = llm.user_dir() / "gguf"
directory.mkdir(parents=True, exist_ok=True)
models_file = directory / "embed-models.json"
click.echo(models_file)
@gguf.command()
def models_dir():
"Display the path to the directory holding downloaded GGUF models"
click.echo(_ensure_models_dir())
@gguf.command()
@click.argument("url")
@click.option(
"aliases",
"-a",
"--alias",
multiple=True,
help="Alias(es) to register the model under",
)
def download_model(url, aliases):
"Download and register a GGUF model from a URL"
download_gguf_model(url, _ensure_models_file, aliases)
@gguf.command()
@click.argument("url")
@click.option(
"aliases",
"-a",
"--alias",
multiple=True,
help="Alias(es) to register the model under",
)
def download_embed_model(url, aliases):
"Download and register a GGUF embedding model from a URL"
download_gguf_model(url, _ensure_embed_models_file, aliases)
@gguf.command()
@click.argument("model_id")
@click.argument(
"filepath", type=click.Path(exists=True, dir_okay=False, resolve_path=True)
)
@click.option(
"clip_model_path",
"--clip-model-path",
type=click.Path(exists=True, dir_okay=False, resolve_path=True),
)
@click.option("chat_handler_class", "--chat-handler-class", type=str)
@click.option("n_ctx", "--n-ctx", type=int, default=0)
@click.option(
"aliases",
"-a",
"--alias",
multiple=True,
help="Alias(es) to register the model under",
)
def register_model(
model_id, filepath, clip_model_path, chat_handler_class, n_ctx, aliases
):
"Register a GGUF model that you have already downloaded with LLM"
models_file = _ensure_models_file()
models = json.loads(models_file.read_text())
path = pathlib.Path(filepath)
info = {
"path": str(path.resolve()),
"aliases": aliases,
}
if clip_model_path:
info["clip_model_path"] = clip_model_path
if chat_handler_class:
if not hasattr(llama_chat_format, chat_handler_class):
raise click.ClickException(
f"Invalid chat handler class: {chat_handler_class}"
)
info["chat_handler_class"] = chat_handler_class
if n_ctx:
info["n_ctx"] = n_ctx
models[model_id] = info
models_file.write_text(json.dumps(models, indent=2))
@gguf.command()
@click.argument("model_id")
@click.argument(
"filepath", type=click.Path(exists=True, dir_okay=False, resolve_path=True)
)
@click.option(
"aliases",
"-a",
"--alias",
multiple=True,
help="Alias(es) to register the model under",
)
def register_embed_model(model_id, filepath, aliases):
"Register a GGUF embedding model that you have already downloaded"
models_file = _ensure_embed_models_file()
models = json.loads(models_file.read_text())
path = pathlib.Path(filepath)
info = {
"path": str(path.resolve()),
"aliases": aliases,
}
models[model_id] = info
models_file.write_text(json.dumps(models, indent=2))
@gguf.command()
def models():
"List registered GGUF models"
models_file = _ensure_models_file()
models = json.loads(models_file.read_text())
for model, info in models.items():
try:
info["size"] = human_size(pathlib.Path(info["path"]).stat().st_size)
except FileNotFoundError:
info["size"] = None
click.echo(json.dumps(models, indent=2))
@gguf.command()
def embed_models():
"List registered GGUF embedding models"
models_file = _ensure_embed_models_file()
models = json.loads(models_file.read_text())
for model, info in models.items():
try:
info["size"] = human_size(pathlib.Path(info["path"]).stat().st_size)
except FileNotFoundError:
info["size"] = None
click.echo(json.dumps(models, indent=2))
class GgufChatModel(llm.Model):
can_stream = True
def __init__(
self,
model_id,
model_path,
n_ctx=0,
clip_model_path=None,
chat_handler_class=None,
):
self.model_id = model_id
self.model_path = model_path
self.clip_model_path = clip_model_path
self.chat_handler_class = chat_handler_class
self.n_ctx = n_ctx # "0 = from model"
self._model = None
def get_model(self):
if self._model is None:
if self.chat_handler_class is None:
self._model = Llama(
model_path=self.model_path,
verbose=False,
n_ctx=self.n_ctx,
chat_format="chatml-function-calling",
)
else:
chat_handler_class = getattr(llama_chat_format, self.chat_handler_class)
self._model = Llama(
model_path=self.model_path,
verbose=False,
n_ctx=self.n_ctx,
chat_handler_class=chat_handler_class(
clip_model_path=self.clip_model_path
),
)
return self._model
def execute(self, prompt, stream, response, conversation):
messages = []
current_system = None
if conversation is not None:
for prev_response in conversation.responses:
if (
prev_response.prompt.system
and prev_response.prompt.system != current_system
):
messages.append(
{"role": "system", "content": prev_response.prompt.system}
)
current_system = prev_response.prompt.system
messages.append(
{"role": "user", "content": prev_response.prompt.prompt}
)
messages.append({"role": "assistant", "content": prev_response.text()})
if prompt.system and prompt.system != current_system:
messages.append({"role": "system", "content": prompt.system})
messages.append({"role": "user", "content": prompt.prompt})
if not stream:
model = self.get_model()
completion = model.create_chat_completion(
messages=messages,
tools=[
{
"type": "function",
"function": {
"name": "search_blog",
"description": "Search for posts on the blog.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query, keywords only",
}
},
"required": ["query"],
"additionalProperties": False,
},
},
}
],
tool_choice="auto",
)
breakpoint()
return [completion["choices"][0]["text"]]
# Streaming
model = self.get_model()
completion = model.create_chat_completion(messages=messages, stream=True)
for chunk in completion:
choice = chunk["choices"][0]
delta_content = choice.get("delta", {}).get("content")
if delta_content is not None:
yield delta_content
class GgufEmbeddingModel(llm.EmbeddingModel):
def __init__(self, model_id, model_path):
self.model_id = model_id
self.model_path = model_path
self._model = None
def embed_batch(self, texts):
if self._model is None:
self._model = Llama(
model_path=self.model_path, embedding=True, verbose=False
)
results = self._model.create_embedding(list(texts))
return [result["embedding"] for result in results["data"]]
def download_gguf_model(url, models_file_func, aliases):
"""Download a GGUF model and register it in the specified models file"""
with httpx.stream("GET", url, follow_redirects=True) as response:
total_size = response.headers.get("content-length")
filename = url.split("/")[-1]
download_path = _ensure_models_dir() / filename
if download_path.exists():
raise click.ClickException(f"File already exists at {download_path}")
with open(download_path, "wb") as fp:
if total_size is not None:
total_size = int(total_size)
with click.progressbar(
length=total_size,
label="Downloading {}".format(human_size(total_size)),
) as bar:
for data in response.iter_bytes(1024):
fp.write(data)
bar.update(len(data))
else:
for data in response.iter_bytes(1024):
fp.write(data)
click.echo(f"Downloaded model to {download_path}", err=True)
models_file = models_file_func()
models = json.loads(models_file.read_text())
model_id = download_path.stem
info = {
"path": str(download_path.resolve()),
"aliases": aliases,
}
models[model_id] = info
models_file.write_text(json.dumps(models, indent=2))
def human_size(num_bytes):
"""Return a human readable byte size."""
for unit in ["B", "KB", "MB", "GB", "TB", "PB"]:
if num_bytes < 1024.0:
break
num_bytes /= 1024.0
return f"{num_bytes:.2f} {unit}"