File size: 26,479 Bytes
5073823
 
 
 
 
fbde839
 
 
 
 
 
 
 
5073823
 
 
 
 
 
5352590
5073823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbde839
5073823
 
fbde839
 
 
 
5073823
 
 
 
 
 
 
 
 
 
 
 
 
fbde839
5073823
 
 
 
 
 
 
 
fbde839
 
 
 
 
 
 
5073823
 
 
 
 
 
fbde839
5073823
 
 
 
 
fbde839
5073823
 
 
 
 
fbde839
 
 
 
 
 
 
 
 
 
 
 
 
5073823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbde839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5073823
 
 
 
 
 
 
 
 
 
fbde839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5073823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbde839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5073823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbde839
 
 
 
 
 
 
 
 
5073823
fbde839
5073823
 
 
5352590
5073823
 
 
 
fbde839
5073823
 
 
 
 
 
 
fbde839
5073823
 
 
 
 
 
 
 
 
 
 
 
 
 
fbde839
 
 
5073823
 
 
fbde839
 
 
 
5073823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbde839
5073823
 
 
 
 
 
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
"""Five chat-role LoRAs borrowing the existing single Q4 model allocation.

Import is stdlib-only. Two causal contexts are pooled; all nine role adapters
stay resident. This changes quantization composition from old merged Q4 models.
It is source/mock validated until explicitly constructed by the owned service.

Speed changes (each keeps every output token identical; see the notes at each):
- greedy grammar decoding checks the highest-scoring token first (_bind_greedy_grammar_first);
- a context keeps its adapter between requests (llama.cpp rebuilds its scheduler and compute
  buffers whenever a context's adapter set changes), and the roles in role_contexts get their own
  context, so the planner and writer no longer switch one context back and forth;
- a role's own context saves the state after the prompt prefix its prompts share and restores it
  for later prompts (_PrefixState), on a batch boundary so the rest is evaluated in the same batches.
"""
from __future__ import annotations

from contextlib import ExitStack, contextmanager
import hashlib
import json
import os
from pathlib import Path
import queue
import threading


CHAT_ROLES = ("router", "router_legacy_v8", "prose_v6", "sections_v9", "writer_v10")
PRECISION = "one shared Q4_K_M base plus resident F16 runtime LoRA adapters"
_BORROW_INIT_LOCK = threading.Lock()


def _sha(path):
    h = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for block in iter(lambda: stream.read(8 * 1024 * 1024), b""):
            h.update(block)
    return h.hexdigest()


def validate_chat_manifest(shared, manifest):
    base = manifest["base"]
    if base["original_hf_identity"] != shared.manifest["base"]["original_hf_identity"]:
        raise ValueError("Chat and decision adapters require the exact same common base")
    if set(manifest["roles"]) != set(CHAT_ROLES):
        raise ValueError("Exactly the five separately named chat roles are required")
    if manifest.get("source_common_base_verified") is not True:
        raise ValueError("Chat source common-base provenance is required")
    for name, digest in base["tokenizer_sha256"].items():
        if Path(name).name != name or _sha(Path(base["tokenizer_dir"]) / name) != digest:
            raise ValueError("Chat tokenizer/template hash mismatch")
    if not {"tokenizer.json", "tokenizer_config.json", "chat_template.jinja"} <= set(base["tokenizer_sha256"]):
        raise ValueError("Exact tokenizer and chat template hashes required")
    for role, row in manifest["roles"].items():
        if row["common_base_identity"] != base["original_hf_identity"] or not row.get("original_adapter_provenance"):
            raise ValueError("Chat adapter provenance mismatch: " + role)
        if _sha(row["adapter_gguf_path"]) != row["adapter_gguf_sha256"]:
            raise ValueError("Chat adapter GGUF hash mismatch: " + role)
    return manifest


class SharedChatRuntime:
    """Server-agnostic chat endpoints using a pool of borrowed-model contexts.

    `shared` owns the one base and four decision adapters. This owner keeps five
    more adapters resident, borrows the base for two causal chat contexts, and
    registers teardown before shared frees its base. There is no cross-request
    KV reuse, and each request explicitly supplies all nine adapter scales.
    """
    def __init__(self, shared, manifest, backend=None, *, validate=True, pool_size=2,
                 context_limit=8192, output_limit=1536, role_contexts=(), role_context_limit=16384):
        if type(pool_size) is not int or not 1 <= pool_size <= 2:
            raise ValueError("Use one or two shared chat contexts")
        if any(role not in CHAT_ROLES for role in role_contexts) or len(set(role_contexts)) != len(role_contexts):
            raise ValueError("Own contexts can only be given to distinct chat roles")
        if type(role_context_limit) is not int or not output_limit < role_context_limit <= context_limit:
            raise ValueError("Invalid own-context limit")
        if (type(context_limit) is not int or type(output_limit) is not int
                or context_limit <= output_limit or output_limit <= 0):
            raise ValueError("Invalid context/output limits")
        self.shared = shared
        self.manifest = validate_chat_manifest(shared, manifest) if validate else manifest
        self.backend = backend or BorrowedLlamaChatBackend(shared, manifest)
        self.context_limit, self.output_limit = context_limit, output_limit
        self._condition = threading.Condition()
        self._closing = self._closed = False
        self._active = 0
        self._pool = queue.Queue()
        self.contexts = []
        self.adapters = {}
        self.role_contexts = {}
        self._poisoned = set()
        try:
            for role in CHAT_ROLES:
                self.adapters[role] = self.backend.load_adapter(shared.model, manifest["roles"][role]["adapter_gguf_path"])
            for i in range(pool_size):
                context = self.backend.create_context(shared.model, context_limit=context_limit, slot=i)
                self.contexts.append(context)
                self._pool.put(context)
            # A role's own context: its adapter is set once and never changes, and its prompt-prefix state is kept.
            # n_ctx only sizes the cache (attention runs over the cells in use), so a prompt computes the same here as in
            # a pooled context; a prompt that does not fit, or arrives while the own context is busy, uses the pool.
            for i, role in enumerate(role_contexts):
                context = self.backend.create_context(shared.model, context_limit=role_context_limit, slot=pool_size + i)
                self.contexts.append(context)
                self.role_contexts[role] = _RoleContext(context, role_context_limit)
            shared.register_dependent(self.close)
        except BaseException:
            self.close()
            raise

    @contextmanager
    def _active_request(self):
        with self._condition:
            if self._closing or self._closed:
                raise RuntimeError("Chat runtime is closing")
            self._active += 1
        try:
            yield
        finally:
            with self._condition:
                self._active -= 1
                self._condition.notify_all()

    @contextmanager
    def _slot(self):
        with self._active_request():
            context = None
            try:
                context = self._pool.get()
                if id(context) in self._poisoned:
                    raise RuntimeError("Chat context cleanup failed; restart required")
                yield context
            finally:
                if context is not None:
                    self._pool.put(context)

    def _role(self, role):
        if role not in CHAT_ROLES:
            raise ValueError("Unknown chat role")

    def _render(self, body):
        messages = body.get("messages")
        if not isinstance(messages, list) or not messages:
            raise ValueError("Nonempty messages required")
        for m in messages:
            if (not isinstance(m, dict) or m.get("role") not in {"system", "user", "assistant"}
                    or not isinstance(m.get("content"), str)):
                raise ValueError("Text system/user/assistant messages required")
        kwargs = body.get("chat_template_kwargs", {})
        if kwargs not in ({}, {"enable_thinking": False}):
            raise ValueError("Only thinking-disabled rendering is supported")
        if body.get("add_generation_prompt", True) is not True:
            raise ValueError("Generation prompt is required")
        return self.backend.render(messages)

    def apply_template(self, role, body):
        self._role(role)
        return {"prompt": self._render(body)}

    def tokenize(self, role, body):
        self._role(role)
        if (not isinstance(body.get("content"), str) or body.get("add_special", False) is not False
                or body.get("parse_special", True) is not True):
            raise ValueError("Exact tokenization requires text, add_special=false, parse_special=true")
        with self._slot() as context:
            tokens = self.backend.tokenize(context, body["content"])
        return {"tokens": tokens}

    def complete(self, role, body):
        self._role(role)
        if body.get("stream", False) is not False or body.get("temperature", 0) != 0:
            raise ValueError("Only nonstreaming deterministic greedy chat is supported")
        maximum = body.get("max_tokens", self.output_limit)
        if type(maximum) is not int or not 0 < maximum <= self.output_limit:
            raise ValueError("Output budget out of bounds")
        if "tools" in body or "tool_choice" in body:
            raise ValueError("Tool calling is not supported")
        if body.get("grammar") is not None and body.get("response_format") is not None:
            raise ValueError("Choose explicit grammar or response_format")
        prompt = self._render(body)
        response = tokens = None
        own = self.role_contexts.get(role)
        if own is not None:
            with self._active_request():
                if own.lock.acquire(blocking=False):
                    try:
                        if id(own.context) in self._poisoned:
                            raise RuntimeError("Chat context cleanup failed; restart required")
                        tokens = self.backend.tokenize(own.context, prompt)
                        if tokens and len(tokens) + maximum <= own.limit:
                            response = self._generate_in(own.context, role, tokens, maximum, body, own.prefix)
                    finally:
                        own.lock.release()
        if response is None:
            with self._slot() as context:
                tokens = self.backend.tokenize(context, prompt)
                response = self._generate_in(context, role, tokens, maximum, body, None)
        model_id = self.manifest["roles"][role].get("model_id", "shared-base-" + role)
        usage = response.get("usage")
        if not isinstance(usage, dict) or usage.get("prompt_tokens") != len(tokens):
            raise RuntimeError("Native completion input token accounting mismatch")
        return {"id": response.get("id"), "object": "chat.completion", "created": response.get("created"),
                "model": model_id, "precision": PRECISION,
                "choices": [{"index": 0, "message": {"role": "assistant", "content": response["choices"][0]["text"]},
                             "finish_reason": response["choices"][0]["finish_reason"]}],
                "usage": usage}

    def _generate_in(self, context, role, tokens, maximum, body, prefix):
        if (not tokens or any(type(t) is not int or t < 0 for t in tokens)
                or len(tokens) + maximum > self.context_limit):
            raise ValueError("Prompt/output exceeds exact context budget; no truncation")
        all_adapters = {**self.shared.adapters, **self.adapters}
        if len(all_adapters) != 9:
            raise ValueError("Expected four decision plus five chat adapter identities")
        scales = {name: float(name == role) for name in all_adapters}
        try:
            self.backend.clear(context)
            # Unchanged adapter set: llama.cpp keeps the context as it is (no scheduler rebuild).
            self.backend.set_adapters(context, all_adapters, scales)
            self.backend.assert_causal(context)
            if prefix is not None:
                prefix.position(self.backend.L, context, tokens)
            return self.backend.generate(context, tokens, maximum,
                                         grammar=body.get("grammar"),
                                         response_format=body.get("response_format"))
        finally:
            try:
                self.backend.clear(context)
            except BaseException:
                self._poisoned.add(id(context))
                raise

    def dispatch(self, role, path, body):
        if path == "/apply-template":
            return self.apply_template(role, body)
        if path == "/tokenize":
            return self.tokenize(role, body)
        if path == "/v1/chat/completions":
            return self.complete(role, body)
        raise ValueError("Unknown chat endpoint")

    def close(self):
        with self._condition:
            if self._closed:
                return
            self._closing = True
            while self._active:
                self._condition.wait()
            self._closed = True
        # All borrowers must disappear before their adapters and the common base.
        errors = []
        for context in reversed(self.contexts):
            try:
                self.backend.free_context(context)
            except BaseException as e:
                errors.append(e)
        self.contexts.clear()
        for adapter in reversed(list(self.adapters.values())):
            try:
                self.backend.free_adapter(adapter)
            except BaseException as e:
                errors.append(e)
        self.adapters.clear()
        if errors:
            raise RuntimeError("Chat teardown failed") from errors[0]


class _RoleContext:
    def __init__(self, context, limit):
        self.context, self.limit = context, limit
        self.lock = threading.Lock()
        self.prefix = _PrefixState()


def _shared_length(a, b):
    n = 0
    for x, y in zip(a, b):
        if x != y:
            break
        n += 1
    return n


class _PrefixState:
    """Exact reuse of the prompt prefix a role's prompts share (attention cache and recurrent state of the hybrid model).

    A saved prefix is a run of first tokens shared by the prompts of one family (the writer and the calculator share a
    role but not a system prompt, so a role keeps a few), cut down to a multiple of the context's batch size (512), with
    at least one prompt token left to evaluate. After the memory clear, position() either restores the saved state of
    exactly those tokens (llama_state_seq_set_data), or evaluates them from position 0 (the same batches as a full
    evaluation) and saves the state. Generation then evaluates only the rest, again in the same 512-token batches as a
    full evaluation, so every logit is bit-identical to evaluating the whole prompt. A new family starts with the whole
    prompt (cut to the batch size); its next prompt shrinks it to the part they share.
    """
    def __init__(self, entries=4):
        self.entries = []               # [tokens tuple, (ctypes buffer, size)], most recently used first
        self.max_entries = entries
        self.restored = self.saved = 0

    def position(self, L, context, tokens):
        batch, limit = context.n_batch, len(tokens) - 1
        best, best_n = None, 0
        for entry in self.entries:
            n = batch * (min(_shared_length(entry[0], tokens), limit) // batch)
            if n > best_n:
                best, best_n = entry, n
        if best is not None:
            self.entries.remove(best)
            if best_n == len(best[0]):
                buffer, size = best[1]
                if L.llama_state_seq_set_data(context._ctx.ctx, buffer, size, 0) != size:
                    raise RuntimeError("Prompt prefix state could not be restored")
                context.input_ids[:best_n] = best[0]
                context.n_tokens = best_n
                self.entries.insert(0, best)
                self.restored += 1
                return
            n = best_n                  # shares only part of that prefix: shrink it to the shared part
        else:
            n = batch * (limit // batch)
        if n == 0:
            return
        prefix = tuple(tokens[:n])
        context.eval(list(prefix))
        import ctypes
        size = L.llama_state_seq_get_size(context._ctx.ctx, 0)
        buffer = (ctypes.c_uint8 * size)()
        if L.llama_state_seq_get_data(context._ctx.ctx, buffer, size, 0) != size:
            raise RuntimeError("Prompt prefix state could not be saved")
        self.entries.insert(0, [prefix, (buffer, size)])
        del self.entries[self.max_entries:]
        self.saved += 1


def _bind_greedy_grammar_first(chat):
    """Greedy decoding under a grammar (planner JSON schema, writer and calculator schemas): check the best token first.

    llama-cpp-python samples a constrained greedy call with the chain [penalties (a no-op at 1.0), grammar, greedy]: the
    grammar is applied to all 248K tokens at every step, then the highest-scoring allowed token is taken (the first maximum
    in token order). If the highest-scoring token is allowed, it is that pick, so: check only that token (np.argmax also
    returns the first maximum), and run the full chain as before only when it is rejected. The grammar and every other
    sampler of the chain then accept the same token, as llama_sampler_sample does. Exact by construction.
    """
    import ctypes
    import types
    import numpy as np
    import llama_cpp
    full_sample = type(chat).sample

    def sample(self, top_k=40, top_p=0.95, min_p=0.05, typical_p=1.0, temp=0.80, repeat_penalty=1.0,
               frequency_penalty=0.0, presence_penalty=0.0, tfs_z=1.0, mirostat_mode=0, mirostat_eta=0.1,
               mirostat_tau=5.0, penalize_nl=True, logits_processor=None, grammar=None, idx=None):
        options = dict(top_k=top_k, top_p=top_p, min_p=min_p, typical_p=typical_p, temp=temp,
                       repeat_penalty=repeat_penalty, frequency_penalty=frequency_penalty,
                       presence_penalty=presence_penalty, tfs_z=tfs_z, mirostat_mode=mirostat_mode,
                       mirostat_eta=mirostat_eta, mirostat_tau=mirostat_tau, penalize_nl=penalize_nl,
                       logits_processor=logits_processor, grammar=grammar, idx=idx)
        sampler = self._sampler
        if (grammar is None or temp != 0.0 or logits_processor is not None or sampler is None or repeat_penalty != 1.0
                or frequency_penalty != 0.0 or presence_penalty != 0.0):
            return full_sample(self, **options)
        chain = sampler.sampler
        if llama_cpp.llama_sampler_chain_n(chain) != 3:
            return full_sample(self, **options)
        check = llama_cpp.llama_sampler_chain_get(chain, 1)
        if llama_cpp.llama_sampler_name(check) != b"grammar":
            return full_sample(self, **options)
        ridx = idx - self.n_tokens if idx is not None else -1
        pointer = llama_cpp.llama_get_logits_ith(self._ctx.ctx, ridx)
        logits = np.ctypeslib.as_array(ctypes.cast(pointer, ctypes.POINTER(ctypes.c_float)), shape=(self._n_vocab,))
        best = int(np.argmax(logits))
        one = (llama_cpp.llama_token_data * 1)()
        one[0].id, one[0].logit, one[0].p = best, float(logits[best]), 0.0
        candidates = llama_cpp.llama_token_data_array(data=ctypes.cast(one, llama_cpp.llama_token_data_p), size=1,
                                                      selected=-1, sorted=False)
        llama_cpp.llama_sampler_apply(check, ctypes.byref(candidates))
        if one[0].logit == float("-inf"):
            return full_sample(self, **options)
        llama_cpp.llama_sampler_accept(chain, best)
        return best

    chat.sample = types.MethodType(sample, chat)


class BorrowedLlamaChatBackend:
    """Reuse installed high-level sampling while preventing any second base load.

    The only constructor interception substitutes a borrowed LlamaModel wrapper
    whose close stack never owns the base handle. Its regular context/batch and
    sampler remain independently owned. Initialization is locked and restored
    immediately. The default HF tokenizer renders the known exact base template;
    native vocab token IDs must match it before generation.
    """
    def __init__(self, shared, manifest):
        self.shared = shared
        self.L = shared.backend.L
        from transformers import AutoTokenizer
        self.tokenizer = AutoTokenizer.from_pretrained(manifest["base"]["tokenizer_dir"],
                                                      local_files_only=True, trust_remote_code=False)

    def load_adapter(self, model, path):
        return self.shared.backend.load_adapter(model, path)

    def create_context(self, model, *, context_limit, slot):
        import llama_cpp
        import llama_cpp._internals as internals
        L = self.L
        # Fetch the original class inside the lock as well: another concurrent
        # constructor must not accidentally subclass a temporary borrower.
        with _BORROW_INIT_LOCK:
            original = internals.LlamaModel
            class BorrowedModel(original):
                def __init__(self, *, path_model, params, verbose=True):
                    self.path_model, self.params, self.verbose = path_model, params, verbose
                    self._exit_stack = ExitStack()
                    self.sampler, self.custom_samplers = None, []
                    self.model = model
                    self.vocab = L.llama_model_get_vocab(model)
                    if not self.vocab:
                        raise RuntimeError("Shared model vocabulary is unavailable")
            original_context = internals.LlamaContext

            class OneOutputContext(original_context):
                # Greedy generation with logits_all off reads one logits row per decode. llama.cpp otherwise reserves
                # compute memory for logits at every position of a batch (512 x 248K floats = 0.5 GB per context) and
                # re-creates it whenever the context's adapter set changes. Memory sizing only: the graph is the same.
                def __init__(self, *, model, params, verbose=True):
                    params.n_outputs_max = 1
                    super().__init__(model=model, params=params, verbose=verbose)
            internals.LlamaModel = BorrowedModel
            internals.LlamaContext = OneOutputContext
            try:
                chat = llama_cpp.Llama(model_path=self.shared.manifest["base"]["gguf_path"],
                                      n_ctx=context_limit, n_batch=512, n_ubatch=512,
                                      n_threads=int(os.environ.get("SEC10K_THREADS", "8") or 8), n_threads_batch=int(os.environ.get("SEC10K_THREADS", "8") or 8), logits_all=False,
                                      attention_type=L.LLAMA_ATTENTION_TYPE_CAUSAL,
                                      seed=0, verbose=False)
            finally:
                internals.LlamaModel = original
                internals.LlamaContext = original_context
        if chat._model.model != model:
            chat.close()
            raise RuntimeError("Chat context does not borrow the one common model")
        if chat.n_ctx() != context_limit:
            chat.close()
            raise RuntimeError("Native chat context capacity differs from requested limit")
        L.llama_set_causal_attn(chat._ctx.ctx, True)
        _bind_greedy_grammar_first(chat)
        return chat

    def render(self, messages):
        return self.tokenizer.apply_chat_template(messages, tokenize=False,
                                                  add_generation_prompt=True, enable_thinking=False)

    def tokenize(self, context, prompt):
        native = context.tokenize(prompt.encode("utf-8"), add_bos=False, special=True)
        hf = self.tokenizer(prompt, add_special_tokens=False, truncation=False)["input_ids"]
        if native != hf:
            raise RuntimeError("Shared native vocab and exact HF tokenizer IDs differ")
        return native

    def clear(self, context):
        # Memory only: the context keeps its adapter. Setting "none" here and the role's adapter again before the next
        # request changed nothing in the computation but made llama.cpp rebuild the scheduler and compute buffers twice
        # per request; set_adapters() still runs for every request, and llama.cpp skips an unchanged adapter set.
        self.L.llama_memory_clear(self.L.llama_get_memory(context._ctx.ctx), True)
        context.reset()

    def clear_adapters(self, context):
        if self.L.llama_set_adapters_lora(context._ctx.ctx, None, 0, None) != 0:
            raise RuntimeError("Failed to clear chat adapters")

    def set_adapters(self, context, adapters, scales):
        import ctypes
        names = list(adapters)
        handles = (self.L.llama_adapter_lora_p_ctypes * len(names))(*(adapters[n] for n in names))
        weights = (ctypes.c_float * len(names))(*(scales[n] for n in names))
        if self.L.llama_set_adapters_lora(context._ctx.ctx, handles, len(names), weights) != 0:
            raise RuntimeError("Failed to bind chat role adapter")

    def assert_causal(self, context):
        if not self.L.llama_get_causal_attn(context._ctx.ctx):
            raise RuntimeError("Chat context is not causal")

    def generate(self, context, tokens, maximum, *, grammar=None, response_format=None):
        from llama_cpp import LlamaGrammar
        if grammar is not None and response_format is not None:
            raise ValueError("Choose explicit grammar or response_format")
        constraint = None
        if grammar is not None:
            if not isinstance(grammar, str) or not grammar.strip():
                raise ValueError("Grammar must be nonempty GBNF")
            constraint = LlamaGrammar.from_string(grammar, verbose=False)
        elif response_format is not None:
            if not isinstance(response_format, dict) or response_format.get("type") != "json_object":
                raise ValueError("Only json_object response_format is supported")
            constraint = LlamaGrammar.from_json_schema(json.dumps(response_format.get("schema", {"type": "object"})), verbose=False)
        return context.create_completion(prompt=tokens, max_tokens=maximum, temperature=0,
                                         top_k=1, top_p=1, repeat_penalty=1, seed=0,
                                         stream=False, grammar=constraint)

    def free_context(self, context):
        # Cleanup failure must not leave a borrowed context alive when its
        # adapter handles and the owning shared model are subsequently freed.
        try:
            self.clear_adapters(context)
            self.clear(context)
        finally:
            context.close()

    def free_adapter(self, adapter):
        self.shared.backend.free_adapter(adapter)