-
Notifications
You must be signed in to change notification settings - Fork 653
Expand file tree
/
Copy pathserver.py
More file actions
1965 lines (1717 loc) · 68.6 KB
/
server.py
File metadata and controls
1965 lines (1717 loc) · 68.6 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright © 2023-2024 Apple Inc.
import argparse
import copy
import json
import logging
import pickle
import platform
import socket
import time
import uuid
import warnings
from collections import deque
from dataclasses import dataclass, field
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from queue import Empty as QueueEmpty
from queue import Queue
from threading import Thread
from typing import (
Any,
Callable,
Dict,
List,
Literal,
NamedTuple,
Optional,
Sequence,
Tuple,
Union,
)
import mlx.core as mx
from huggingface_hub import scan_cache_dir
from ._version import __version__
from .generate import BatchGenerator, generation_stream, stream_generate
from .models.cache import (
can_trim_prompt_cache,
make_prompt_cache,
trim_prompt_cache,
)
from .sample_utils import make_logits_processors, make_sampler
from .utils import load, sharded_load
def get_system_fingerprint():
gpu_arch = mx.device_info()["architecture"]
return f"{__version__}-{mx.__version__}-{platform.platform()}-{gpu_arch}"
def parse_size(x):
sizes = {"M": 1e6, "G": 1e9, "MB": 1e6, "GB": 1e9, "": 1}
split = 0
for xi in x:
if not (xi.isdigit() or xi == "."):
break
split += 1
digits = float(x[:split])
size = (x[split:]).strip().upper()
return int(digits * sizes[size])
class StopCondition(NamedTuple):
stop_met: bool
trim_length: int
trim_text_length: int
def stopping_criteria(
tokens: List[int],
eos_token_ids: set,
stop_id_sequences: List[List[int]],
stop_words: List[str],
) -> StopCondition:
"""
Determines whether the token generation should stop based on predefined
conditions.
Args:
tokens (List[int]): The current sequence of generated tokens.
eos_token_ids (set): The token IDs that represents the
end-of-sequence. If the last token in ``tokens`` is in the set,
the generation should stop.
stop_id_sequences (List[List[[int]]): A list of integer lists, each
representing a sequence of token IDs. If the end of the `tokens`
list matches any of these sequences, the generation should stop.
stop_words (List[str]): The stop words that correspond to the
``stop_id_sequences``.
Returns:
StopCondition: A named tuple indicating whether the stop condition has
been met (`stop_met`) and how many tokens should be trimmed from the
end if it has (`trim_length`) as well as the text that should be
trimmed.
"""
if tokens and tokens[-1] in eos_token_ids:
return StopCondition(stop_met=True, trim_length=0, trim_text_length=0)
for stop_ids, stop_word in zip(stop_id_sequences, stop_words):
if len(tokens) >= len(stop_ids):
if tokens[-len(stop_ids) :] == stop_ids:
return StopCondition(
stop_met=True,
trim_length=len(stop_ids),
trim_text_length=len(stop_word),
)
return StopCondition(stop_met=False, trim_length=0, trim_text_length=0)
def sequence_overlap(s1: Sequence, s2: Sequence) -> bool:
"""
Checks if a suffix of s1 has overlap with a prefix of s2
Args:
s1 (Sequence): The first sequence
s2 (Sequence): The second sequence
Returns:
bool: If the two sequences have overlap
"""
max_overlap = min(len(s1), len(s2))
return any(s1[-i:] == s2[:i] for i in range(1, max_overlap + 1))
def convert_chat(messages: List[dict], role_mapping: Optional[dict] = None):
default_role_mapping = {
"system_prompt": (
"A chat between a curious user and an artificial intelligence "
"assistant. The assistant follows the given rules no matter what."
),
"system": "ASSISTANT's RULE: ",
"user": "USER: ",
"assistant": "ASSISTANT: ",
"stop": "\n",
}
role_mapping = role_mapping if role_mapping is not None else default_role_mapping
prompt = ""
for line in messages:
role_prefix = role_mapping.get(line["role"], "")
stop = role_mapping.get("stop", "")
content = line.get("content", "")
prompt += f"{role_prefix}{content}{stop}"
prompt += role_mapping.get("assistant", "")
return prompt.rstrip()
def process_message_content(messages):
"""
Convert message content to a format suitable for `apply_chat_template`.
The function operates on messages in place. It converts the 'content' field
to a string instead of a list of text fragments.
Args:
message_list (list): A list of dictionaries, where each dictionary may
have a 'content' key containing a list of dictionaries with 'type' and
'text' keys.
Raises:
ValueError: If the 'content' type is not supported or if 'text' is missing.
"""
for message in messages:
content = message.get("content", None)
if isinstance(content, list):
text_fragments = [
fragment["text"] for fragment in content if fragment["type"] == "text"
]
if len(text_fragments) != len(content):
raise ValueError("Only 'text' content type is supported.")
message["content"] = "".join(text_fragments)
elif content is None:
message["content"] = ""
if tool_calls := message.get("tool_calls", False):
for tool_call in tool_calls:
if func := tool_call.get("function", False):
if args := func.get("arguments", False):
func["arguments"] = json.loads(args)
class LRUPromptCache:
@dataclass
class CacheEntry:
prompt_cache: List[Any]
count: int
nbytes: int
@dataclass
class SearchResult:
model: Any
exact: List[int]
shorter: List[int]
longer: List[int]
common_prefix: int
def __init__(self, max_size: int = 10, max_bytes: int = 1 << 63):
self.max_size = max_size
self.max_bytes = max_bytes
self._cache = {}
self._lru = deque()
self._n_bytes = 0
def __len__(self):
return len(self._lru)
@property
def nbytes(self):
return self._n_bytes
def _search(self, model, tokens):
"""Search the cache for a prompt cache. Return exact or close match."""
if model not in self._cache:
return self.SearchResult(model, None, None, None, 0)
current = self._cache[model]
last_cache_index = -1
index = 0
while index < len(tokens) and tokens[index] in current:
current = current[tokens[index]]
if "cache" in current:
last_cache_index = index
index += 1
# Exact match no need to search for longer or shorter caches
if last_cache_index == len(tokens) - 1:
return self.SearchResult(model, tokens, None, None, 0)
# Find the shorter cache
shorter = None
if last_cache_index > 0:
shorter = tokens[: last_cache_index + 1]
# Check for caches that are longer
longer = None
common_prefix = index
if index > 0 and last_cache_index <= 0:
best = None
stack = [(current, [])]
while stack:
current, extra = stack.pop()
if "cache" in current:
if best is None or len(extra) < len(best):
best = extra
else:
for tok in current:
stack.append((current[tok], extra + [tok]))
longer = tokens[:index] + best
return self.SearchResult(model, None, shorter, longer, common_prefix)
def _get(self, model, tokens):
current = self._cache[model]
for tok in tokens:
current = current[tok]
return current["cache"]
def _delete(self, model, tokens):
path = [self._cache[model]]
for tok in tokens:
path.append(path[-1][tok])
cache_bytes = path[-1]["cache"].nbytes
self._n_bytes -= cache_bytes
del path[-1]["cache"]
for i in reversed(range(len(tokens))):
d_prev, d, t = path[i], path[i + 1], tokens[i]
if len(d) > 0:
break
del d_prev[t]
logging.debug(f"[LRUPromptCache] Removed {cache_bytes} bytes from the cache")
def _extract(self, model, tokens):
cache_entry = self._get(model, tokens)
if cache_entry.count == 1:
self._delete(model, tokens)
self._lru.remove((model, tokens))
return cache_entry
cache_entry.count -= 1
return self.CacheEntry(
copy.deepcopy(cache_entry.prompt_cache), 1, cache_entry.nbytes
)
def fetch_nearest_cache(self, model, tokens):
result = self._search(model, tokens)
if result.exact is not None:
cache_entry = self._extract(result.model, result.exact)
return cache_entry.prompt_cache, []
if result.shorter is not None:
cache_entry = self._extract(result.model, result.shorter)
prefix_len = len(result.shorter)
return cache_entry.prompt_cache, tokens[prefix_len:]
if result.longer is not None:
cache_entry = self._get(result.model, result.longer)
if can_trim_prompt_cache(cache_entry.prompt_cache):
cache = copy.deepcopy(cache_entry.prompt_cache)
prefix = min(len(tokens) - 1, result.common_prefix)
num_to_trim = len(result.longer) - prefix
trim_prompt_cache(cache, num_to_trim)
return cache, tokens[prefix:]
return None, tokens
def insert_cache(self, model, tokens, prompt_cache):
if model not in self._cache:
self._cache[model] = {}
current = self._cache[model]
for tok in tokens:
if tok not in current:
current[tok] = {}
current = current[tok]
if "cache" in current:
current["cache"].count += 1
self._lru.remove((model, tokens))
else:
cache_bytes = sum(c.nbytes for c in prompt_cache)
current["cache"] = self.CacheEntry(prompt_cache, 1, cache_bytes)
self._n_bytes += cache_bytes
logging.debug(f"[LRUPromptCache] Adding {cache_bytes} to the cache")
self._lru.append((model, tokens))
if len(self._lru) > self.max_size:
model, tokens = self._lru.popleft()
self._delete(model, tokens)
while self._n_bytes > self.max_bytes and len(self._lru) > 1:
model, tokens = self._lru.popleft()
self._delete(model, tokens)
def trim_to(
self, *, n_sequences: Optional[int] = None, n_bytes: Optional[int] = None
):
n_sequences = max(0, n_sequences) if n_sequences is not None else 1 << 63
n_bytes = max(0, n_bytes) if n_bytes is not None else 1 << 63
while len(self._lru) > n_sequences:
model, tokens = self._lru.popleft()
self._delete(model, tokens)
while self._n_bytes > n_bytes:
model, tokens = self._lru.popleft()
self._delete(model, tokens)
@dataclass
class ModelDescription:
model: str
draft: str
adapter: str
@dataclass
class SamplingArguments:
temperature: float
top_p: float
top_k: int
min_p: float
xtc_probability: float
xtc_threshold: float
@dataclass
class LogitsProcessorArguments:
logit_bias: Optional[Dict[int, float]]
repetition_penalty: float
repetition_context_size: int
@dataclass
class GenerationArguments:
model: ModelDescription
sampling: SamplingArguments
logits: LogitsProcessorArguments
stop_words: List[str]
max_tokens: int
num_draft_tokens: int
logprobs: bool
top_logprobs: int
seed: Optional[int]
chat_template_kwargs: Optional[Dict[str, Any]]
@dataclass
class CompletionRequest:
request_type: Literal["chat", "text"]
prompt: str
messages: List[Any]
tools: Optional[List[Any]]
role_mapping: Optional[Dict[str, Any]]
@dataclass
class GenerationContext:
has_tool_calling: bool
tool_call_start: str
tool_call_end: str
tool_parser: Callable[[str, Any], Dict]
has_thinking: bool
think_start_id: int
think_end_id: int
think_end: str
eos_token_ids: set
stop_token_sequences: List[List[int]]
prompt: List[int]
prompt_cache_count: int = -1
_should_stop: bool = False
def stop(self):
self._should_stop = True
@dataclass
class Response:
text: str
token: int
logprob: float
finish_reason: Optional[str]
top_tokens: Tuple[Dict[str, Any]]
class TimeBudget:
def __init__(self, budget=0.5, iterations=25, sync_frequency=10):
self._is_distributed = mx.distributed.init().size() > 1
self._budget = budget
self._iterations = iterations
self._sync_frequency = sync_frequency
self._start = None
self._current_iterations = None
self._loops = 0
self._time_spent = 0
def __iter__(self):
self._start = time.time()
self._current_iterations = 0
return self
def __next__(self):
if not self._is_distributed:
if time.time() - self._start > self._budget:
raise StopIteration()
return None
self._current_iterations += 1
if self._current_iterations > self._iterations:
self._loops += 1
self._time_spent += time.time() - self._start
if self._loops % self._sync_frequency == 0:
with mx.stream(generation_stream):
loop_time = mx.distributed.all_sum(self._time_spent).item()
avg_loop_time = loop_time / (
mx.distributed.init().size() * self._sync_frequency
)
factor = self._budget / avg_loop_time
self._iterations = max(round(self._iterations * factor), 1)
self._loops = 0
self._time_spent = 0
raise StopIteration()
class ModelProvider:
def __init__(self, cli_args: argparse.Namespace):
"""Load models on demand and persist them across the whole process."""
self.cli_args = cli_args
self.model_key = None
self.model = None
self.tokenizer = None
self.draft_model = None
self.is_batchable = False
group = mx.distributed.init()
self.pipeline_group = group if group.size() > 1 and cli_args.pipeline else None
self.tensor_group = (
group if group.size() > 1 and not cli_args.pipeline else None
)
self.is_distributed = group.size() > 1
# Preload the default model if it is provided
self.default_model_map = {}
if self.cli_args.model is not None:
self.default_model_map[self.cli_args.model] = "default_model"
self.load(self.cli_args.model, draft_model_path="default_model")
# Added in adapter_path to load dynamically
def load(self, model_path, adapter_path=None, draft_model_path=None):
model_path = self.default_model_map.get(model_path, model_path)
if self.model_key == (model_path, adapter_path, draft_model_path):
return self.model, self.tokenizer
# Remove the old model if it exists.
self.model = None
self.tokenizer = None
self.model_key = None
self.draft_model = None
# Building tokenizer_config
tokenizer_config = {
"trust_remote_code": True if self.cli_args.trust_remote_code else None
}
if self.cli_args.chat_template:
tokenizer_config["chat_template"] = self.cli_args.chat_template
if model_path == "default_model":
if self.cli_args.model is None:
raise ValueError(
"A model path has to be given as a CLI "
"argument or in the HTTP request"
)
adapter_path = adapter_path or self.cli_args.adapter_path
# TODO: Generalize distributed load
if self.is_distributed:
model, tokenizer = sharded_load(
self.cli_args.model, self.pipeline_group, self.tensor_group
)
else:
model, tokenizer = load(
self.cli_args.model,
adapter_path=adapter_path,
tokenizer_config=tokenizer_config,
)
else:
# TODO: Generalize distributed load
if self.is_distributed:
model, tokenizer = sharded_load(
model_path, self.pipeline_group, self.tensor_group
)
else:
model, tokenizer = load(
model_path,
adapter_path=adapter_path,
tokenizer_config=tokenizer_config,
)
if self.cli_args.use_default_chat_template:
if tokenizer.chat_template is None:
tokenizer.chat_template = tokenizer.default_chat_template
self.model_key = (model_path, adapter_path, draft_model_path)
self.model = model
self.tokenizer = tokenizer
def validate_draft_tokenizer(draft_tokenizer):
# Check if tokenizers are compatible
if draft_tokenizer.vocab_size != tokenizer.vocab_size:
logging.warning(
"Draft model tokenizer does not match model tokenizer. "
"Speculative decoding may not work as expected."
)
# Load draft model if specified
if (
draft_model_path == "default_model"
and self.cli_args.draft_model is not None
):
self.draft_model, draft_tokenizer = load(self.cli_args.draft_model)
validate_draft_tokenizer(draft_tokenizer)
elif draft_model_path is not None and draft_model_path != "default_model":
self.draft_model, draft_tokenizer = load(draft_model_path)
validate_draft_tokenizer(draft_tokenizer)
if self.draft_model is None:
self.is_batchable = all(
hasattr(c, "merge") for c in make_prompt_cache(self.model)
)
return self.model, self.tokenizer
def _make_sampler(args, tokenizer):
return make_sampler(
args.sampling.temperature,
top_p=args.sampling.top_p,
top_k=args.sampling.top_k,
min_p=args.sampling.min_p,
xtc_probability=args.sampling.xtc_probability,
xtc_threshold=args.sampling.xtc_threshold,
xtc_special_tokens=[
tokenizer.eos_token_id,
tokenizer.encode("\n"),
],
)
def _make_logits_processors(args):
return make_logits_processors(
args.logits.logit_bias,
args.logits.repetition_penalty,
args.logits.repetition_context_size,
)
def _format_top_logprobs(logprobs, top_logprobs, tokenizer) -> Tuple[Dict[str, Any]]:
"""Returns info dicts for the top `top_logprobs` tokens from `logprobs`"""
if top_logprobs <= 0:
return ()
sorted_indices = mx.argpartition(-logprobs, kth=top_logprobs - 1)
top_indices = sorted_indices[:top_logprobs].tolist()
top_logprobs = logprobs[top_indices].tolist()
txts = tokenizer.convert_ids_to_tokens(top_indices)
return tuple(
{"id": i, "token": s, "logprob": g}
for i, s, g in zip(top_indices, txts, top_logprobs)
)
class ResponseGenerator:
def __init__(self, model_provider: ModelProvider, prompt_cache: LRUPromptCache):
self.model_provider = model_provider
self.prompt_cache = prompt_cache
self.requests = Queue()
self._time_budget = TimeBudget()
self._is_distributed = mx.distributed.init().size() > 1
self._rank = mx.distributed.init().rank()
self._stop = False
self._generation_thread = Thread(target=self._generate)
self._generation_thread.start()
def stop_and_join(self):
self._stop = True
self._generation_thread.join()
def join(self):
self._generation_thread.join()
def _next_request(self, timeout=None):
request = None
if not self._is_distributed or self._rank == 0:
try:
if timeout is not None:
request = self.requests.get(timeout=timeout)
else:
request = self.requests.get_nowait()
except QueueEmpty:
pass
return self._share_request(request)
def _share_object(self, obj):
if not self._is_distributed:
return obj
with mx.stream(generation_stream):
if self._rank == 0:
if obj is None:
mx.eval(mx.distributed.all_sum(0))
return None
else:
data = mx.array(pickle.dumps(obj))
mx.eval(mx.distributed.all_sum(data.size))
mx.eval(mx.distributed.all_sum(data))
return obj
else:
size = mx.distributed.all_sum(0).item()
if size == 0:
return None
else:
data = mx.zeros(size, dtype=mx.uint8)
data = mx.distributed.all_sum(data)
return pickle.loads(data)
def _share_request(self, request):
if not self._is_distributed:
return request
shareable = request[1:] if request is not None else None
shareable = self._share_object(shareable)
if shareable is None:
return None
rq = request[0] if request is not None else Queue()
return rq, *shareable
def _tokenize(self, tokenizer, request, args):
if request.request_type == "chat":
messages = request.messages
tools = request.tools
role_mapping = request.role_mapping
if tokenizer.has_chat_template:
process_message_content(messages)
if tools and not tokenizer.has_tool_calling:
logging.warning(
"Received tools but model does not support tool calling. "
"If you think this is an error, file an issue here: "
"https://github.com/ml-explore/mlx-lm/issues"
)
chat_template_args = self.model_provider.cli_args.chat_template_args
if args.chat_template_kwargs:
chat_template_args = chat_template_args.copy()
chat_template_args.update(args.chat_template_kwargs)
return tokenizer.apply_chat_template(
messages,
tools=tools,
add_generation_prompt=True,
tokenize=True,
**chat_template_args,
)
else:
return tokenizer.encode(convert_chat(messages, role_mapping))
else:
return tokenizer.encode(request.prompt)
def _is_batchable(self, args):
if not self.model_provider.is_batchable:
return False
if args.seed is not None:
return False
return True
def _generate(self):
current_model = None
current_sampling = None
current_tokenizer = None
current_model_key = None
batch_generator = None
drain_batch = False
batch_results = {}
unprocessed_requests = []
def get_next_request(timeout=None):
if unprocessed_requests:
return unprocessed_requests.pop()
else:
return self._next_request(timeout)
def progress_callback(info):
for uid, processed, total in info:
if uid in batch_results:
batch_results[uid]["rqueue"].put((min(processed, total), total))
if self._is_distributed:
seed = mx.distributed.all_sum(mx.random.state[0]).view(mx.uint64).item()
mx.random.seed(seed)
while not self._stop:
request = None
if not drain_batch:
timeout = (
None
if (batch_generator is not None and len(batch_results) > 0)
else 0.1
)
request = get_next_request(timeout=timeout)
# We got a request
if request is not None:
rqueue, request, args = request
# Can it be added to the current batch?
if (
batch_generator is not None
and current_model == args.model
and self._is_batchable(args)
):
try:
prompt = self._tokenize(current_tokenizer, request, args)
except Exception as e:
rqueue.put(e)
continue
ctx = GenerationContext(
has_tool_calling=tokenizer.has_tool_calling,
tool_call_start=tokenizer.tool_call_start,
tool_call_end=tokenizer.tool_call_end,
tool_parser=tokenizer.tool_parser,
has_thinking=tokenizer.has_thinking,
think_start_id=tokenizer.think_start_id,
think_end=tokenizer.think_end,
think_end_id=tokenizer.think_end_id,
eos_token_ids=tokenizer.eos_token_ids,
stop_token_sequences=[
tokenizer.encode(stop_word, add_special_tokens=False)
for stop_word in args.stop_words
],
prompt=prompt,
)
rqueue.put(ctx)
cache, rest = self.prompt_cache.fetch_nearest_cache(
current_model_key, prompt
)
ctx.prompt_cache_count = len(prompt) - len(rest)
if cache is None:
cache = make_prompt_cache(self.model_provider.model)
ncaches, nbytes = len(self.prompt_cache), self.prompt_cache.nbytes
logging.info(
f"We have {ncaches} kv caches that take {nbytes/1e9:.2f} GB"
)
(uid,) = batch_generator.insert(
[rest],
args.max_tokens,
caches=[cache],
samplers=[_make_sampler(args, tokenizer)],
logits_processors=[_make_logits_processors(args)],
)
batch_results[uid] = {
"ctx": ctx,
"cache_key": prompt[:],
"rqueue": rqueue,
"detokenizer": tokenizer.detokenizer,
}
# just making sure we don't leave a reference around
del cache
if self.model_provider.cli_args.prompt_cache_bytes is not None:
total = self.model_provider.cli_args.prompt_cache_bytes
active = batch_generator.prompt_cache_nbytes
self.prompt_cache.trim_to(n_bytes=total - active)
continue
# No batch generator. Load the model and if it's not
# batchable serve sequential, o/w make a batch generaotr and
# serve batched
elif batch_generator is None:
try:
model, tokenizer = self.model_provider.load(
args.model.model, args.model.adapter, args.model.draft
)
except Exception as e:
rqueue.put(e)
continue
if not self._is_batchable(args):
self._serve_single((rqueue, request, args))
continue
current_model = args.model
current_tokenizer = tokenizer
current_model_key = self.model_provider.model_key
batch_results = {}
batch_generator = BatchGenerator(
model,
stop_tokens=tokenizer.eos_token_ids,
completion_batch_size=self.cli_args.decode_concurrency,
prefill_batch_size=self.cli_args.prompt_concurrency,
prompt_progress_callback=progress_callback,
)
unprocessed_requests.append((rqueue, request, args))
continue
# We have a batch but this request cannot be added to the
# batch so drain it to process the request.
else:
drain_batch = True
unprocessed_requests.append((rqueue, request, args))
continue
# No request so serve from the current batch
elif batch_generator is not None:
if len(batch_results) == 0:
if drain_batch:
current_model = None
current_sampling = None
current_tokenizer = None
current_model_key = None
batch_generator.close()
batch_generator = None
drain_batch = False
continue
uids_to_remove = []
for _ in self._time_budget:
responses = batch_generator.next()
if not responses:
break
for r in responses:
result = batch_results[r.uid]
result["cache_key"].append(r.token)
if r.finish_reason != "stop":
result["detokenizer"].add_token(r.token)
result["rqueue"].put(
Response(
result["detokenizer"].last_segment,
r.token,
r.logprobs[r.token].item(),
r.finish_reason,
_format_top_logprobs(
r.logprobs, args.top_logprobs, current_tokenizer
),
)
)
if r.finish_reason is not None:
result["rqueue"].put(None)
self.prompt_cache.insert_cache(
current_model_key, result["cache_key"], r.prompt_cache
)
del batch_results[r.uid]
if result["ctx"]._should_stop:
uids_to_remove.append(r.uid)
uids_to_remove = self._share_object(uids_to_remove)
if uids_to_remove:
with mx.stream(generation_stream):
caches = batch_generator.remove(
uids_to_remove, return_prompt_caches=True
)
for uid, prompt_cache in caches.items():
if uid not in batch_results:
continue
result = batch_results[uid]
self.prompt_cache.insert_cache(
current_model_key, result["cache_key"], prompt_cache
)
del batch_results[uid]
def _serve_single(self, request):
rqueue, request, args = request
# Define the progress callback
def progress(tokens_processed, tokens_total):
rqueue.put((tokens_processed, tokens_total))
try:
# Load the model and tokenizer
model = self.model_provider.model
tokenizer = self.model_provider.tokenizer
draft_model = self.model_provider.draft_model
# Prepare the prompt
prompt = self._tokenize(tokenizer, request, args)
# Start the generation context
ctx = GenerationContext(
has_tool_calling=tokenizer.has_tool_calling,
tool_call_start=tokenizer.tool_call_start,
tool_call_end=tokenizer.tool_call_end,
tool_parser=tokenizer.tool_parser,
has_thinking=tokenizer.has_thinking,
think_start_id=tokenizer.think_start_id,
think_end=tokenizer.think_end,
think_end_id=tokenizer.think_end_id,
eos_token_ids=tokenizer.eos_token_ids,
stop_token_sequences=[
tokenizer.encode(stop_word, add_special_tokens=False)
for stop_word in args.stop_words
],
prompt=prompt,
)
rqueue.put(ctx)
# Seed if requested
if args.seed is not None:
mx.random.seed(args.seed)
# Make the sampler and logit processor
sampler = _make_sampler(args, tokenizer)
logits_processors = _make_logits_processors(args)
# Load the KV cache
cache, rest = self.prompt_cache.fetch_nearest_cache(
self.model_provider.model_key, prompt
)
ctx.prompt_cache_count = len(prompt) - len(rest)
cache_key = prompt[:]
if cache is None:
cache = make_prompt_cache(self.model_provider.model)
if self.model_provider.draft_model is not None:
cache += make_prompt_cache(self.model_provider.draft_model)
ncaches, nbytes = len(self.prompt_cache), self.prompt_cache.nbytes
logging.info(f"We have {ncaches} kv caches that take {nbytes/1e9:.2f} GB")
# Process the prompt and generate tokens
kv_kwargs = {}
if self.cli_args.kv_bits is not None:
kv_kwargs["kv_bits"] = self.cli_args.kv_bits
kv_kwargs["kv_group_size"] = self.cli_args.kv_group_size
kv_kwargs["quantized_kv_start"] = self.cli_args.quantized_kv_start
for gen in stream_generate(
model=model,
tokenizer=tokenizer,
prompt=rest,
max_tokens=args.max_tokens,
sampler=sampler,
logits_processors=logits_processors,
prompt_cache=cache,
draft_model=draft_model,
num_draft_tokens=args.num_draft_tokens,