captchakraken 5.2.1-beta.59 → 5.3.0-beta.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "captchakraken",
3
- "version": "5.2.1-beta.59",
3
+ "version": "5.3.0-beta.68",
4
4
  "description": "Captcha solver for Playwright and Puppeteer. Finds the captcha, reads it with the v2 pointer model, and clicks, drags, slides or types through to a token — reCAPTCHA, GeeTest, NetEase Yidun, Tencent, Lemin, Prosopo, Turnstile and distorted text. Hosted API or self-hosted.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "captchakraken"
7
- version = "5.2.1b59"
7
+ version = "5.3.0b68"
8
8
  description = "Captcha-solving engine and CLI: a v2 pointer model for image grids, click and drag puzzles, sliders, distorted text and animated challenges. Hosted API or self-hosted on vLLM."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -87,6 +87,18 @@ serve = [
87
87
  "accelerate==1.15.0",
88
88
  "huggingface_hub==1.30.0",
89
89
  ]
90
+ # Self-hosting on a GPU older than compute capability 7.5, which the vLLM build has no
91
+ # kernels for: llama.cpp (the pointer_states binary) runs the model there, and this
92
+ # prepares the board and runs the pointer heads. `fetch` first installs torch and
93
+ # torchvision from PyTorch's CPU index, so these pins skip the CUDA libraries.
94
+ serve-llamacpp = [
95
+ "torch==2.13.0",
96
+ "torchvision==0.28.0",
97
+ "transformers==5.17.0",
98
+ "gguf==0.19.0",
99
+ "safetensors==0.8.0",
100
+ "huggingface_hub==1.30.0",
101
+ ]
90
102
  dev = [
91
103
  # The licensed-model fetch tests raise the Hub's own refusal types.
92
104
  "huggingface_hub==1.30.0",
@@ -47,6 +47,7 @@ try:
47
47
  from .page_solver import CaptchaSolveError, PageSolver, PageSolverConfig, SolveResult, solve_captcha_on_page
48
48
  from .selectors import DEFAULT_CONFIG_PATH, SelectorConfigError, VendorSelectors, load_config
49
49
  from .watcher import CaptchaWatcher
50
+ from .async_page_solver import AsyncCaptchaWatcher, AsyncPageSolver, solve_captcha_on_page_async
50
51
  except ModuleNotFoundError:
51
52
  CaptchaSolver = None
52
53
  solve_captcha = None
@@ -60,6 +61,9 @@ except ModuleNotFoundError:
60
61
  SelectorConfigError = None
61
62
  load_config = None
62
63
  CaptchaWatcher = None
64
+ AsyncPageSolver = None
65
+ AsyncCaptchaWatcher = None
66
+ solve_captcha_on_page_async = None
63
67
 
64
68
  __all__ = [
65
69
  # Solving a page
@@ -69,6 +73,9 @@ __all__ = [
69
73
  "CaptchaSolveError",
70
74
  "solve_captcha_on_page",
71
75
  "CaptchaWatcher",
76
+ "AsyncPageSolver",
77
+ "AsyncCaptchaWatcher",
78
+ "solve_captcha_on_page_async",
72
79
  # Solving an image
73
80
  "CaptchaSolver",
74
81
  "solve_captcha",
@@ -104,4 +111,4 @@ __all__ = [
104
111
  "PauseKind",
105
112
  ]
106
113
 
107
- __version__ = "5.2.1b59"
114
+ __version__ = "5.3.0b68"
@@ -0,0 +1,297 @@
1
+ """The async driver: `PageSolver` for an `async_playwright` (or async Camoufox / patchright) page.
2
+
3
+ async with async_playwright() as p:
4
+ page = await (await p.chromium.launch()).new_page()
5
+ await page.goto(url)
6
+ result = await AsyncPageSolver().solve(page)
7
+
8
+ WHY IT IS A BRIDGE AND NOT A SECOND DRIVER
9
+ The solve is ~3,000 lines of timing-sensitive decisions, and the two Python copies would drift the way the two
10
+ ports did where only one had a guard. So there is one driver. It runs on a worker thread, and the page it drives
11
+ is a proxy that hands every Playwright call back to the caller's event loop and blocks the worker, never the loop,
12
+ until the call returns. The caller's other tasks keep running for the whole solve, waits included: a wait is a
13
+ sleep on the worker thread, not on the loop.
14
+
15
+ Every call goes through the loop, sync-shaped ones too (`page.locator`, `page.on`), so the async objects are only
16
+ ever touched from the thread that owns them. Event callbacks run the other way: the loop gets an async handler
17
+ that runs the driver's sync callback on a worker thread, so a callback that reads a response body can block on
18
+ the loop without deadlocking it.
19
+
20
+ WHAT CANCELLATION DOES
21
+ Cancelling the awaiting task stops the solve at its next page call, which raises `SolveCancelled` on the worker.
22
+ Nothing is left running against the page once that call returns.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import asyncio
28
+ import inspect
29
+ import threading
30
+ from typing import Any, Callable, Dict, Optional
31
+
32
+ from .page_solver import PageSolver, SolveResult
33
+ from .watcher import CaptchaWatcher
34
+
35
+ __all__ = ["AsyncPageSolver", "AsyncCaptchaWatcher", "solve_captcha_on_page_async"]
36
+
37
+ # Members that are coroutine functions on an async Playwright object, one or more per class the driver reaches.
38
+ _ASYNC_PROBES = ("evaluate", "click", "move", "press", "bounding_box", "screenshot", "body", "cookies", "new_page")
39
+ _PASSTHROUGH = (str, bytes, bytearray, int, float, bool, type(None), dict)
40
+
41
+
42
+ class SolveCancelled(RuntimeError):
43
+ """Raised on the worker thread when the task awaiting the solve was cancelled."""
44
+
45
+
46
+ def is_async_page(page: Any) -> bool:
47
+ return inspect.iscoroutinefunction(getattr(page, "evaluate", None))
48
+
49
+
50
+ def _is_async_handle(value: Any) -> bool:
51
+ if isinstance(value, _PASSTHROUGH) or isinstance(value, _Proxy):
52
+ return False
53
+ if "async_api" in type(value).__module__:
54
+ return True
55
+ return any(inspect.iscoroutinefunction(getattr(type(value), name, None)) for name in _ASYNC_PROBES)
56
+
57
+
58
+ def _positional_arity(fn: Callable[..., Any]) -> Optional[int]:
59
+ """How many positional arguments `fn` takes; None when it takes any number, or cannot be inspected."""
60
+ try:
61
+ params = inspect.signature(fn).parameters.values()
62
+ except (TypeError, ValueError):
63
+ return None
64
+ if any(p.kind is p.VAR_POSITIONAL for p in params):
65
+ return None
66
+ return sum(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in params)
67
+
68
+
69
+ class _Bridge:
70
+ """Carries calls from the worker thread to the loop that owns the page."""
71
+
72
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
73
+ self.loop = loop
74
+ # Built on the loop's own thread, by _on_worker.
75
+ self.loop_thread = threading.current_thread()
76
+ self.cancelled = threading.Event()
77
+ self._handlers: Dict[Any, Callable[..., Any]] = {}
78
+
79
+ def call(self, fn: Callable[..., Any], args: tuple, kwargs: dict) -> Any:
80
+ if self.cancelled.is_set():
81
+ raise SolveCancelled("the solve was cancelled")
82
+ if threading.current_thread() is self.loop_thread:
83
+ raise RuntimeError("a bridged page was called from its own event loop; that would deadlock")
84
+ args = tuple(self.unwrap(a, register=fn) for a in args)
85
+ kwargs = {k: self.unwrap(v, register=fn) for k, v in kwargs.items()}
86
+
87
+ async def on_loop() -> Any:
88
+ result = fn(*args, **kwargs)
89
+ if inspect.isawaitable(result):
90
+ result = await result
91
+ return result
92
+
93
+ future = asyncio.run_coroutine_threadsafe(on_loop(), self.loop)
94
+ while True:
95
+ try:
96
+ return self.wrap(future.result(timeout=0.25))
97
+ except TimeoutError:
98
+ if self.cancelled.is_set():
99
+ future.cancel()
100
+ raise SolveCancelled("the solve was cancelled") from None
101
+
102
+ def wrap(self, value: Any) -> Any:
103
+ if isinstance(value, list):
104
+ return [self.wrap(v) for v in value]
105
+ if isinstance(value, tuple):
106
+ return tuple(self.wrap(v) for v in value)
107
+ return _Proxy(value, self) if _is_async_handle(value) else value
108
+
109
+ def unwrap(self, value: Any, register: Any = None) -> Any:
110
+ if isinstance(value, _Proxy):
111
+ return object.__getattribute__(value, "_target")
112
+ if isinstance(value, list):
113
+ return [self.unwrap(v) for v in value]
114
+ if callable(value) and not isinstance(value, type):
115
+ return self._handler_for(value)
116
+ return value
117
+
118
+ def _handler_for(self, callback: Callable[..., Any]) -> Callable[..., Any]:
119
+ """The loop-side twin of a sync callback; the same callback always maps to the same handler, so that
120
+ `remove_listener` finds the one `on` registered."""
121
+ try:
122
+ return self._handlers[callback]
123
+ except (KeyError, TypeError):
124
+ pass
125
+
126
+ # Playwright passes a handler as many arguments as its signature takes (a route handler gets the request
127
+ # too when it asks), so the twin forwards only what the callback accepts.
128
+ accepts = _positional_arity(callback)
129
+
130
+ async def handler(*args: Any) -> Any:
131
+ if self.cancelled.is_set():
132
+ return None
133
+ wrapped = [self.wrap(a) for a in (args if accepts is None else args[:accepts])]
134
+ return await self.loop.run_in_executor(None, lambda: callback(*wrapped))
135
+
136
+ try:
137
+ self._handlers[callback] = handler
138
+ except TypeError:
139
+ pass
140
+ return handler
141
+
142
+
143
+ class _Proxy:
144
+ """A sync-looking stand-in for one async Playwright object."""
145
+
146
+ __slots__ = ("_target", "_bridge")
147
+
148
+ def __init__(self, target: Any, bridge: _Bridge) -> None:
149
+ object.__setattr__(self, "_target", target)
150
+ object.__setattr__(self, "_bridge", bridge)
151
+
152
+ def __getattr__(self, name: str) -> Any:
153
+ target = object.__getattribute__(self, "_target")
154
+ bridge = object.__getattribute__(self, "_bridge")
155
+ value = getattr(target, name)
156
+ if inspect.ismethod(value) or inspect.isfunction(value) or inspect.iscoroutinefunction(value):
157
+ return lambda *args, **kwargs: bridge.call(value, args, kwargs)
158
+ return bridge.wrap(value)
159
+
160
+ def __setattr__(self, name: str, value: Any) -> None:
161
+ setattr(object.__getattribute__(self, "_target"), name, value)
162
+
163
+ def __eq__(self, other: Any) -> bool:
164
+ mine = object.__getattribute__(self, "_target")
165
+ theirs = object.__getattribute__(other, "_target") if isinstance(other, _Proxy) else other
166
+ return mine == theirs
167
+
168
+ def __hash__(self) -> int:
169
+ return hash(object.__getattribute__(self, "_target"))
170
+
171
+ def __repr__(self) -> str:
172
+ return f"<sync view of {object.__getattribute__(self, '_target')!r}>"
173
+
174
+
175
+ async def _on_worker(fn: Callable[..., Any], page: Any, *args: Any, **kwargs: Any) -> Any:
176
+ if not is_async_page(page):
177
+ raise TypeError(
178
+ "AsyncPageSolver drives an async page and was given a synchronous one; use PageSolver for "
179
+ "playwright.sync_api pages."
180
+ )
181
+ loop = asyncio.get_running_loop()
182
+ bridge = _Bridge(loop)
183
+ task = loop.run_in_executor(None, lambda: fn(bridge.wrap(page), *args, **kwargs))
184
+ try:
185
+ return await asyncio.shield(task)
186
+ except asyncio.CancelledError:
187
+ bridge.cancelled.set()
188
+ try:
189
+ await task
190
+ except BaseException:
191
+ pass
192
+ raise
193
+
194
+
195
+ class AsyncPageSolver:
196
+ """`PageSolver`, awaited. Takes the same arguments; each method takes an async page."""
197
+
198
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
199
+ self._solver = PageSolver(*args, **kwargs)
200
+ # One solve at a time per solver, as with PageSolver: its per-solve state lives on the instance.
201
+ self._lock = asyncio.Lock()
202
+
203
+ @property
204
+ def config(self) -> Any:
205
+ return self._solver.config
206
+
207
+ async def _run(self, method: str, page: Any, *args: Any, **kwargs: Any) -> Any:
208
+ async with self._lock:
209
+ return await _on_worker(getattr(self._solver, method), page, *args, **kwargs)
210
+
211
+ async def solve(self, page: Any) -> SolveResult:
212
+ return await self._run("solve", page)
213
+
214
+ async def capture(self, page: Any, *args: Any, **kwargs: Any) -> Any:
215
+ return await self._run("capture", page, *args, **kwargs)
216
+
217
+ async def detect_captcha(self, page: Any) -> Any:
218
+ return await self._run("detect_captcha", page)
219
+
220
+ async def is_captcha_solved(self, page: Any, *args: Any, **kwargs: Any) -> bool:
221
+ return await self._run("is_captcha_solved", page, *args, **kwargs)
222
+
223
+ async def has_interactive_widget_in_dom(self, page: Any) -> bool:
224
+ return await self._run("has_interactive_widget_in_dom", page)
225
+
226
+ async def vendors_on_the_wire(self, page: Any) -> Any:
227
+ return await self._run("vendors_on_the_wire", page)
228
+
229
+ def watch(self, page: Any, **options: Any) -> "AsyncCaptchaWatcher":
230
+ """A watcher over `page`; `await .run()` polls until stopped, `await .poll_once()` checks once."""
231
+ return AsyncCaptchaWatcher(self, page, **options)
232
+
233
+
234
+ class AsyncCaptchaWatcher:
235
+ """`CaptchaWatcher` for an async page. `on_solved` / `on_error` may be plain functions or coroutine functions;
236
+ either way they run on the caller's loop."""
237
+
238
+ def __init__(self, solver: AsyncPageSolver, page: Any, on_solved: Optional[Callable[[Any], Any]] = None,
239
+ on_error: Optional[Callable[[BaseException], Any]] = None, **options: Any) -> None:
240
+ self._solver = solver
241
+ self._page = page
242
+ self._options = options
243
+ self._on_solved = on_solved
244
+ self._on_error = on_error
245
+ self._watcher: Optional[CaptchaWatcher] = None
246
+ self._stopped = False
247
+ self._solves = 0
248
+
249
+ @property
250
+ def solves(self) -> int:
251
+ return self._watcher.solves if self._watcher is not None else self._solves
252
+
253
+ def stop(self) -> None:
254
+ self._stopped = True
255
+ if self._watcher is not None:
256
+ self._watcher.stop()
257
+
258
+ def _report_on_loop(self, loop: asyncio.AbstractEventLoop, callback: Optional[Callable[[Any], Any]]):
259
+ if callback is None:
260
+ return None
261
+
262
+ def report(value: Any) -> None:
263
+ async def on_loop() -> None:
264
+ out = callback(value)
265
+ if inspect.isawaitable(out):
266
+ await out
267
+
268
+ asyncio.run_coroutine_threadsafe(on_loop(), loop).result()
269
+
270
+ return report
271
+
272
+ async def _drive(self, method: str, *args: Any) -> Any:
273
+ loop = asyncio.get_running_loop()
274
+
275
+ def on_worker(page: Any) -> Any:
276
+ if self._watcher is None:
277
+ self._watcher = CaptchaWatcher(
278
+ solver=self._solver._solver, page=page, on_solved=self._report_on_loop(loop, self._on_solved),
279
+ on_error=self._report_on_loop(loop, self._on_error), **self._options)
280
+ else:
281
+ self._watcher.page = page
282
+ if self._stopped:
283
+ self._watcher.stop()
284
+ return getattr(self._watcher, method)(*args)
285
+
286
+ async with self._solver._lock:
287
+ return await _on_worker(on_worker, self._page)
288
+
289
+ async def run(self, timeout_ms: Optional[int] = None) -> int:
290
+ return await self._drive("run", timeout_ms)
291
+
292
+ async def poll_once(self) -> Optional[Any]:
293
+ return await self._drive("poll_once")
294
+
295
+
296
+ async def solve_captcha_on_page_async(page: Any, **kwargs: Any) -> SolveResult:
297
+ return await AsyncPageSolver(**kwargs).solve(page)
@@ -346,7 +346,7 @@ def _fetch_setup(args):
346
346
  from . import selfhost
347
347
 
348
348
  parser = argparse.ArgumentParser(prog="captchakraken fetch",
349
- description="Choose a model, a GPU and a startup mode, then install and start it.")
349
+ description="Choose a model, a GPU, an engine and a startup mode, then install and start it.")
350
350
  parser.add_argument("name", nargs="?", default=None,
351
351
  help="set up this model with the defaults, e.g. `abyss` (needs an Abyss Licence)")
352
352
  parser.add_argument("--yes", "-y", action="store_true", help="ask nothing: previous choices, then the defaults")
@@ -355,14 +355,18 @@ def _fetch_setup(args):
355
355
  parser.add_argument("--gpu", type=int, default=None, help="with --yes: the nvidia-smi GPU index")
356
356
  parser.add_argument("--startup", default=None, choices=[selfhost.ALWAYS_ON, selfhost.FIRST_SOLVE],
357
357
  help="with --yes: always on, or start on the first solve")
358
+ parser.add_argument("--engine", default=None, choices=list(selfhost.ENGINES),
359
+ help="with --yes: vllm (the default where the card has kernels for it) or llamacpp "
360
+ "(any GPU with Vulkan, a smaller install)")
358
361
  opts = parser.parse_args(args)
359
362
  if opts.name:
360
363
  if opts.model:
361
364
  parser.error("name the model once: as a word or with --model")
362
365
  opts.model = opts.name
363
- if not opts.yes and (opts.model or opts.gpu is not None or opts.startup):
366
+ if not opts.yes and (opts.model or opts.gpu is not None or opts.startup or opts.engine):
364
367
  opts.yes = True
365
- sys.exit(selfhost.fetch(yes=opts.yes, model=opts.model, gpu=opts.gpu, startup=opts.startup))
368
+ sys.exit(selfhost.fetch(yes=opts.yes, model=opts.model, gpu=opts.gpu, startup=opts.startup,
369
+ engine=opts.engine))
366
370
 
367
371
 
368
372
  def _fetch(args):
@@ -2,7 +2,7 @@ import json
2
2
  import os
3
3
  from functools import lru_cache
4
4
  from pathlib import Path
5
- from typing import Any, Dict, Optional
5
+ from typing import Any, Dict, List, Optional
6
6
 
7
7
  _PINNED_MODEL_PATH = Path(__file__).with_name("pinned_model.json")
8
8
 
@@ -241,6 +241,20 @@ def max_cudagraph_capture_size() -> Optional[int]:
241
241
  return int(value) if value else None
242
242
 
243
243
 
244
+ def engine() -> str:
245
+ """What runs the pointer model: "vllm", or "llamacpp" on a card vLLM's build has no kernels for."""
246
+ return os.getenv("CAPTCHA_POINTER_ENGINE") or selfhost_active().get("engine") or "vllm"
247
+
248
+
249
+ def llamacpp_args() -> List[str]:
250
+ """The llamacpp engine's server flags, from what `fetch` installed."""
251
+ active = selfhost_active()
252
+ return ["--processor", str(active.get("processor_path", "")),
253
+ "--pointer-states", os.getenv("CAPTCHA_POINTER_STATES") or str(active.get("pointer_states", "")),
254
+ "--quant", str(active.get("quant") or "Q4_K_M"),
255
+ *(["--device", str(active["gpu_pci"])] if active.get("gpu_pci") else [])]
256
+
257
+
244
258
  def serve_model() -> str:
245
259
  """What the server loads: `fetch`'s download directory, which needs no Hub, or the repo id."""
246
260
  return os.getenv("CAPTCHA_BASE_MODEL") or selfhost_active().get("model_path") or base_model()
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import hashlib
6
+ import inspect
6
7
  import io
7
8
  import json
8
9
  import math
@@ -630,6 +631,16 @@ def _stalled(before: Tuple[Any, Sequence[float]], now: Tuple[Any, Sequence[float
630
631
  return math.hypot(bx - ax, by - ay) > SLIDE_PROBE_PX / 2 * k and moved < SLIDE_STALL_PX * k
631
632
 
632
633
 
634
+ def _require_sync_page(page: Any) -> None:
635
+ """Refuse an async page up front: driven anyway, every call returns an unawaited coroutine and the solve dies far
636
+ away. AsyncPageSolver hands this class a sync view of one instead."""
637
+ if inspect.iscoroutinefunction(getattr(page, "evaluate", None)):
638
+ raise TypeError(
639
+ "PageSolver drives a synchronous page and was given an async one; for async_playwright, AsyncCamoufox "
640
+ "or patchright's async API use AsyncPageSolver (`await AsyncPageSolver().solve(page)`)."
641
+ )
642
+
643
+
633
644
  class PageSolver:
634
645
  """Drives one Playwright-compatible `page` through a captcha. Reusable across solves."""
635
646
 
@@ -1280,6 +1291,7 @@ class PageSolver:
1280
1291
  the whole board, is checkable on a live page at no inference cost. A checkbox widget is returned with its own
1281
1292
  element; it is clicked, not photographed.
1282
1293
  """
1294
+ _require_sync_page(page)
1283
1295
  self._page = page
1284
1296
  widget = self.detect_captcha(page)
1285
1297
  if widget is None:
@@ -1571,6 +1583,7 @@ class PageSolver:
1571
1583
 
1572
1584
  The inline vendors count: without them the JS port failed fast in under a second on every GeeTest/Yidun page.
1573
1585
  """
1586
+ _require_sync_page(page)
1574
1587
  def count(selector: str) -> int:
1575
1588
  try:
1576
1589
  return page.locator(selector).count()
@@ -1581,6 +1594,7 @@ class PageSolver:
1581
1594
 
1582
1595
  def detect_captcha(self, page: Any) -> Optional[Widget]:
1583
1596
  """Open challenges first, then unsolved checkboxes, then the inline vendors."""
1597
+ _require_sync_page(page)
1584
1598
  scopes = _host_scopes(page, self._sel)
1585
1599
  for probe in self._sel.widget_probes:
1586
1600
  at = next(iter(_visible_in(scopes, (probe.selector,))), None)
@@ -1599,6 +1613,7 @@ class PageSolver:
1599
1613
 
1600
1614
  def vendors_on_the_wire(self, page: Any) -> List[Vendor]:
1601
1615
  """Which vendors' code the page loaded. Resource timing, because a request listener would have to have been attached before navigation."""
1616
+ _require_sync_page(page)
1602
1617
  try:
1603
1618
  names = page.evaluate(_RESOURCES_JS)
1604
1619
  except Exception:
@@ -1660,6 +1675,7 @@ class PageSolver:
1660
1675
 
1661
1676
  def is_captcha_solved(self, page: Any) -> bool:
1662
1677
  """The vendor's own done signal: a response token, a painted success state, or a checked box."""
1678
+ _require_sync_page(page)
1663
1679
  try:
1664
1680
  scopes = _host_scopes(page, self._sel)
1665
1681
  if any(self._has_value(scopes, s) for s in self._sel.response) or _visible_in(scopes, self._sel.accepted):
@@ -2825,11 +2841,13 @@ class PageSolver:
2825
2841
 
2826
2842
  def watch(self, page: Any, **options: Any) -> "CaptchaWatcher":
2827
2843
  """A watcher over `page`; `.run()` blocks, `.poll_once()` is cooperative."""
2844
+ _require_sync_page(page)
2828
2845
  from .watcher import CaptchaWatcher
2829
2846
 
2830
2847
  return CaptchaWatcher(solver=self, page=page, **options)
2831
2848
 
2832
2849
  def solve(self, page: Any) -> SolveResult:
2850
+ _require_sync_page(page)
2833
2851
  # Loading a model takes as long as the whole solve budget, so a cold server must not spend it.
2834
2852
  if config.selfhost_active():
2835
2853
  ensure_server(config.base_url())
@@ -0,0 +1,209 @@
1
+ """The pointer model on llama.cpp: GGUF weights, any GPU with a Vulkan driver, or the CPU.
2
+
3
+ svc = LlamaCppPointerService("/models/TwilightV2-2B-GGUF", binary="/opt/pointer_states",
4
+ processor="/models/TwilightV2-2B", device="0000:01:00.0")
5
+ svc.solve(image=PIL.Image)
6
+
7
+ The board is prepared and the answer read exactly as `PointerService` does. The
8
+ transformers processor gives the token ids the model was trained on; llama.cpp
9
+ (`native/pointer_states` in the repository) runs the language model over that same prompt and
10
+ returns the hidden state of every token, and the heads read them on the CPU. Every
11
+ request checks llama.cpp's token layout against the processor's, so a prompt that
12
+ tokenizes differently fails instead of pointing at the wrong place.
13
+
14
+ Needs the `serve-llamacpp` extra and the `pointer_states` binary. `processor` is the
15
+ folder with the tokenizer and processor files, which the GGUF repositories leave out.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import subprocess
21
+ import tempfile
22
+ import threading
23
+ from pathlib import Path
24
+ from typing import Dict, List, Optional, Sequence, Union
25
+
26
+ import numpy as np
27
+
28
+ from .. import clipvideo as CV
29
+ from . import layout as L
30
+ from .service import PointerService
31
+
32
+ HEADS_FILE = "pointer_heads.safetensors"
33
+ MARKER = "<__media__>"
34
+ _PIXELS = {"min_pixels": 64 * 64, "max_pixels": L.MAX_PIXELS}
35
+ # A video's pixel budget covers all its frames, so the still's cap would shrink every one.
36
+ _VIDEO_SIZE = {"shortest_edge": 64 * 64, "longest_edge": L.MAX_PIXELS * CV.MAX_FRAMES}
37
+
38
+
39
+ def _one(folder: Path, pattern: str) -> Path:
40
+ found = sorted(folder.glob(pattern))
41
+ if len(found) != 1:
42
+ raise FileNotFoundError(f"{folder} has {len(found)} files matching {pattern}, expected one")
43
+ return found[0]
44
+
45
+
46
+ def lm_head(gguf_path: Path):
47
+ """The output matrix [vocab, d] as float16. These models tie it to the token embeddings."""
48
+ import gguf
49
+ import torch
50
+ reader = gguf.GGUFReader(str(gguf_path))
51
+ by_name = {t.name: t for t in reader.tensors}
52
+ t = by_name.get("output.weight", by_name["token_embd.weight"])
53
+ w = gguf.quants.dequantize(t.data, t.tensor_type)
54
+ return torch.from_numpy(w.reshape(int(t.shape[1]), int(t.shape[0])).astype(np.float16))
55
+
56
+
57
+ class LlamaCppPointerService(PointerService):
58
+ """`PointerService` with llama.cpp as the engine. Its `__init__` is not called: that builds vLLM.
59
+
60
+ `folder` holds one language-model GGUF, its `mmproj-*.gguf` vision encoder, the
61
+ pointer heads and the processor files (or `processor` names their folder); `quant` picks
62
+ the GGUF when there are several. `device` is the PCI address of the GPU to run on;
63
+ without it llama.cpp spreads the model over every GPU it finds."""
64
+
65
+ def __init__(self, folder: Union[str, Path], binary: Union[str, Path], quant: str = "Q4_K_M",
66
+ gpu: bool = True, threads: int = 4, processor: Optional[Union[str, Path]] = None,
67
+ device: str = ""):
68
+ import torch
69
+ from safetensors.torch import load_file
70
+ from transformers import AutoProcessor
71
+
72
+ from . import heads as Hd
73
+
74
+ folder = Path(folder)
75
+ self.model_file = _one(folder, f"*-{quant}.gguf")
76
+ mmproj = _one(folder, "mmproj-*.gguf")
77
+ self.processor = AutoProcessor.from_pretrained(str(processor or folder), **_PIXELS)
78
+ tok = self.processor.tokenizer
79
+ self.stop_id = tok.convert_tokens_to_ids("<|im_end|>")
80
+ self.token_ids = Hd.token_ids(tok)
81
+ self._special = {k: tok.convert_tokens_to_ids(k) for k in ("<|vision_start|>", "<|vision_end|>")}
82
+ self.lm_weight = lm_head(self.model_file).float()
83
+ state = {k.removeprefix("pointer_heads."): v for k, v in load_file(str(folder / HEADS_FILE)).items()}
84
+ self.heads = Hd.Heads(self.lm_weight.shape[1]).float()
85
+ self.heads.load_state_dict(state)
86
+ self.heads.eval()
87
+ self._torch, self._hd = torch, Hd
88
+ self._tmp = tempfile.TemporaryDirectory(prefix="pointer-llama-")
89
+ self._lock = threading.Lock()
90
+ self._cmd = [str(binary), str(self.model_file), str(mmproj), "--threads", str(threads)] + (
91
+ ["--cpu"] if not gpu else ["--device", device] if device else [])
92
+ self._start()
93
+
94
+ def _start(self) -> None:
95
+ self._proc = subprocess.Popen(self._cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1)
96
+ ready = self._reply()
97
+ if ready.get("n_embd") != self.lm_weight.shape[1] or ready.get("marker") != MARKER:
98
+ raise RuntimeError(f"pointer_states started as {ready}, expected n_embd {self.lm_weight.shape[1]}")
99
+
100
+ def _ask(self, req: Dict) -> Dict:
101
+ """One request. A GPU reset (a driver timeout, "device lost") kills the process: start it
102
+ again and retry once, so one bad moment on the card is one slow board, not a dead server."""
103
+ for attempt in (0, 1):
104
+ if self._proc.poll() is not None:
105
+ self._start()
106
+ try:
107
+ self._proc.stdin.write(json.dumps(req) + "\n")
108
+ self._proc.stdin.flush()
109
+ reply = self._reply()
110
+ except (BrokenPipeError, RuntimeError):
111
+ if attempt:
112
+ raise
113
+ continue
114
+ if reply["ok"]:
115
+ return reply
116
+ try:
117
+ self._proc.wait(timeout=5) # an error it survives leaves it running
118
+ except subprocess.TimeoutExpired:
119
+ raise RuntimeError(f"pointer_states: {reply['error']}") from None
120
+ if attempt:
121
+ raise RuntimeError(f"pointer_states: {reply['error']}")
122
+ raise AssertionError("unreachable")
123
+
124
+ def _reply(self) -> Dict:
125
+ line = self._proc.stdout.readline()
126
+ if not line:
127
+ raise RuntimeError(f"pointer_states exited with {self._proc.wait()}; its log is on stderr")
128
+ return json.loads(line)
129
+
130
+ def close(self) -> None:
131
+ self._proc.stdin.close()
132
+ self._proc.wait()
133
+ self._tmp.cleanup()
134
+
135
+ def _inputs(self, request: Dict):
136
+ """The processor's ids for the prompt `prepare` built, and the pixels behind each vision span."""
137
+ mm = request["multi_modal_data"]
138
+ if "video" in mm:
139
+ frames, _meta = mm["video"]
140
+ n = len(frames)
141
+ x = self.processor(text=[L.chat(self.processor, True)], videos=[list(frames)],
142
+ video_metadata=[{"fps": CV.FPS, "frames_indices": list(range(n)), "total_num_frames": n}],
143
+ do_sample_frames=False, cap_pixels_per_frame=False, videos_kwargs={"size": _VIDEO_SIZE},
144
+ return_tensors="np")
145
+ # Qwen pairs frames into one temporal patch and repeats the last of an odd count.
146
+ frames = [np.asarray(f) for f in frames] + ([np.asarray(frames[-1])] if n % 2 else [])
147
+ return x["input_ids"][0].tolist(), [(f, True) for f in frames]
148
+ images = mm["image"] if isinstance(mm["image"], list) else [mm["image"]]
149
+ x = self.processor(text=[L.chat(self.processor, False, history=len(images) - 1)], images=images,
150
+ return_tensors="np")
151
+ return x["input_ids"][0].tolist(), [(np.asarray(i.convert("RGB")), False) for i in images]
152
+
153
+ def _prompt(self, ids: Sequence[int], n_media: int) -> str:
154
+ """`ids` as text, each vision span a media marker: llama.cpp writes the span's tokens itself.
155
+ A video's span is a frame pair, two frames that llama.cpp merges back into one."""
156
+ pads = {self.token_ids[L.IMAGE_PAD]: 1, self.token_ids[L.VIDEO_PAD]: 2}
157
+ start, end = self._special["<|vision_start|>"], self._special["<|vision_end|>"]
158
+ parts, text, i = [], [], 0
159
+ while i < len(ids):
160
+ if ids[i] == start and i + 1 < len(ids) and ids[i + 1] in pads:
161
+ j = ids.index(end, i)
162
+ parts += [self.processor.tokenizer.decode(text, skip_special_tokens=False)] if text else []
163
+ parts.append(MARKER * pads[ids[i + 1]])
164
+ text, i = [], j + 1
165
+ else:
166
+ text.append(ids[i])
167
+ i += 1
168
+ parts += [self.processor.tokenizer.decode(text, skip_special_tokens=False)] if text else []
169
+ prompt = "".join(parts)
170
+ if prompt.count(MARKER) != n_media:
171
+ raise ValueError(f"the prompt has {prompt.count(MARKER)} vision slots for {n_media} pictures")
172
+ return prompt
173
+
174
+ def states(self, request: Dict):
175
+ """(token ids, final hidden states [n_tokens, d]) for one prepared request."""
176
+ ids, media = self._inputs(request)
177
+ files = []
178
+ for k, (px, video) in enumerate(media):
179
+ f = Path(self._tmp.name) / f"{k}.rgb"
180
+ f.write_bytes(np.ascontiguousarray(px, dtype=np.uint8).tobytes())
181
+ files.append({"rgb": str(f), "w": int(px.shape[1]), "h": int(px.shape[0]), "video": video})
182
+ out = Path(self._tmp.name) / "states.f32"
183
+ req = {"prompt": self._prompt(ids, len(media)), "media": files, "out": str(out)}
184
+ with self._lock:
185
+ reply = self._ask(req)
186
+ h = np.fromfile(out, dtype=np.float32).reshape(-1, reply["n_embd"])
187
+ pad = self.token_ids[L.VIDEO_PAD if media and media[0][1] else L.IMAGE_PAD]
188
+ seen = [t for c in reply["chunks"] for t in (c["text"] if "text" in c else [pad] * c["media"])]
189
+ if seen != ids:
190
+ raise RuntimeError("llama.cpp tokenized the prompt differently from the model's processor "
191
+ f"({len(seen)} tokens against {len(ids)}); the heads would read the wrong states")
192
+ return ids, h
193
+
194
+ def vector(self, request: Dict) -> List[float]:
195
+ """The packed decision vector and the two trailing counts, as vLLM's pooler returns them."""
196
+ ids, h = self.states(request)
197
+ torch = self._torch
198
+ with torch.inference_mode():
199
+ pos = self._hd.Positions(torch.tensor(ids), self.token_ids)
200
+ v = self.heads.decide(torch.from_numpy(h), pos, self.lm_weight)
201
+ return [float(t) for t in v] + [float(pos.per_moment), float(pos.n_moments)]
202
+
203
+ def solve_many(self, boards: List[Dict], top: int = 3) -> List[Dict]:
204
+ results = []
205
+ for b in boards:
206
+ p = self.prepare(b.get("image"), b.get("frames"), b.get("history", ()))
207
+ answers = self.decode_answers(p, self.vector(p["request"]), b.get("avoid", ()), top)
208
+ results.append({"answer": answers[0], "answers": answers, "shown": p["shown"], "size": p["size"]})
209
+ return results
@@ -131,14 +131,24 @@ def main():
131
131
  ap.add_argument("--letters", default=None, help=argparse.SUPPRESS)
132
132
  ap.add_argument("--host", default="127.0.0.1")
133
133
  ap.add_argument("--port", type=int, default=8001)
134
+ ap.add_argument("--engine", choices=("vllm", "llamacpp"), default="vllm",
135
+ help="llamacpp runs a GGUF build on any GPU with a Vulkan driver, for cards vLLM has no kernels for")
136
+ ap.add_argument("--processor", default=None, help="llamacpp: the folder with the tokenizer and processor files")
137
+ ap.add_argument("--pointer-states", default=None, help="llamacpp: the pointer_states binary")
138
+ ap.add_argument("--quant", default="Q4_K_M", help="llamacpp: which GGUF in --model to load")
139
+ ap.add_argument("--device", default="", help="llamacpp: the GPU's PCI address, as 0000:01:00.0")
134
140
  ap.add_argument("--gpu-memory-utilization", type=float, default=0.45)
135
141
  ap.add_argument("--max-cudagraph-capture-size", type=int, default=None,
136
142
  help="largest batch vLLM compiles a graph for; each one holds GPU memory (small cards need this)")
137
143
  a = ap.parse_args()
138
- from .service import PointerService
139
- capture = a.max_cudagraph_capture_size
140
- svc = PointerService(a.model, gpu_memory_utilization=a.gpu_memory_utilization,
141
- **({"compilation_config": {"max_cudagraph_capture_size": capture}} if capture else {}))
144
+ if a.engine == "llamacpp":
145
+ from .llamacpp_engine import LlamaCppPointerService
146
+ svc = LlamaCppPointerService(a.model, a.pointer_states, quant=a.quant, processor=a.processor, device=a.device)
147
+ else:
148
+ from .service import PointerService
149
+ capture = a.max_cudagraph_capture_size
150
+ svc = PointerService(a.model, gpu_memory_utilization=a.gpu_memory_utilization,
151
+ **({"compilation_config": {"max_cudagraph_capture_size": capture}} if capture else {}))
142
152
  ThreadingHTTPServer((a.host, a.port), make_handler(svc)).serve_forever()
143
153
 
144
154
 
@@ -36,6 +36,25 @@ RUNTIME_GB = 8.0
36
36
  SMALL_CARD_MIB = 12_000
37
37
  SMALL_CARD_CAPTURE_SIZE = 16
38
38
 
39
+ VLLM = "vllm"
40
+ LLAMACPP = "llamacpp"
41
+ # The serving stack's torch is built for compute capability 7.5 and up (RTX 20 series, GTX 16 series, T4).
42
+ VLLM_MIN_COMPUTE = 7.5
43
+ # Older cards run a GGUF build on llama.cpp's Vulkan backend, which the NVIDIA driver serves on any card
44
+ # since Kepler. Torch there only prepares the board and runs the small heads, so it is the CPU build: the
45
+ # same versions as the `serve-llamacpp` extra (a test checks), from PyTorch's index, without CUDA.
46
+ TORCH_CPU = ("torch==2.13.0", "torchvision==0.28.0")
47
+ TORCH_CPU_INDEX = "https://download.pytorch.org/whl/cpu"
48
+ # pointer_states (native/pointer_states): llama.cpp's language model and vision encoder returning every
49
+ # token's hidden state, one static binary built per llama.cpp release.
50
+ POINTER_STATES_RELEASE = "b12819"
51
+ POINTER_STATES_URL = ("https://github.com/CaptchaKraken/CaptchaKraken/releases/download/"
52
+ f"pointer-states-{POINTER_STATES_RELEASE}/pointer_states-linux-x86_64")
53
+ POINTER_STATES_SHA256 = "70fd71385e92f567daadaaf1827beb30e2f08419c5b454acfb68bbf55e5133b9"
54
+ # The files of a full-precision repo the GGUF builds leave out: what turns a board into token ids.
55
+ PROCESSOR_FILES = ("tokenizer.json", "tokenizer_config.json", "processor_config.json", "chat_template.jinja",
56
+ "config.json", "preprocessor_config.json", "video_preprocessor_config.json")
57
+
39
58
 
40
59
  @dataclass(frozen=True)
41
60
  class Model:
@@ -55,6 +74,11 @@ class Model:
55
74
  access: str = ""
56
75
  # The folder of the repo that is served, when the repo holds several builds; empty means the whole repo.
57
76
  subfolder: str = ""
77
+ # Its llama.cpp build, for a card older than VLLM_MIN_COMPUTE: a GGUF repo and which of its files to load.
78
+ # The tokenizer and processor files come from `processor_repo`, or `repo` when that is empty.
79
+ gguf: str = ""
80
+ gguf_quant: str = "Q4_K_M"
81
+ processor_repo: str = ""
58
82
 
59
83
  @property
60
84
  def licensed(self) -> bool:
@@ -68,9 +92,11 @@ class Model:
68
92
  # Sunlight is absent on purpose: its published heads predate this client's layout and refuse to load.
69
93
  MODELS = (
70
94
  Model("CaptchaKraken/MidnightV2-4B-q4", "Midnight V2 4B Q4", "the default: best balance of speed and accuracy",
71
- 3.8, 8),
72
- Model("CaptchaKraken/TwilightV2-2B", "Twilight V2 2B", "smaller model, full precision", 4.5, 8, 0.80),
73
- Model("CaptchaKraken/MidnightV2-4B", "Midnight V2 4B", "the same model at full precision", 9.1, 16),
95
+ 3.8, 8, gguf="CaptchaKraken/MidnightV2-4B-GGUF"),
96
+ Model("CaptchaKraken/TwilightV2-2B", "Twilight V2 2B", "smaller model, full precision", 4.5, 8, 0.80,
97
+ gguf="CaptchaKraken/TwilightV2-2B-GGUF"),
98
+ Model("CaptchaKraken/MidnightV2-4B", "Midnight V2 4B", "the same model at full precision", 9.1, 16,
99
+ gguf="CaptchaKraken/MidnightV2-4B-GGUF", gguf_quant="BF16"),
74
100
  Model("CaptchaKraken/AbyssV2-q4", "Abyss V2 Q4", "our most accurate model, needs an Abyss Licence",
75
101
  3.8, 8, aliases=("abyss",)),
76
102
  Model("CaptchaKraken/AbyssV2", "Abyss V2", "Abyss at full precision, needs an Abyss Licence", 9.1, 16),
@@ -90,25 +116,60 @@ class Gpu(NamedTuple):
90
116
  name: str
91
117
  total_mib: int
92
118
  free_mib: int
119
+ compute: float
120
+ # As Vulkan writes it, 0000:01:00.0: the only number nvidia-smi and llama.cpp agree on.
121
+ pci: str = ""
93
122
 
94
123
  @property
95
124
  def label(self) -> str:
96
125
  return f"{self.name} ({self.total_mib / 1024:.0f} GB, {self.free_mib / 1024:.1f} GB free)"
97
126
 
127
+ @property
128
+ def engine(self) -> str:
129
+ return VLLM if self.compute >= VLLM_MIN_COMPUTE else LLAMACPP
130
+
98
131
 
99
132
  class Choice(NamedTuple):
100
133
  model: Model
101
134
  gpu: Gpu
102
135
  startup: str
136
+ # "" is the card's own default: vLLM where it has kernels, else llama.cpp.
137
+ engine: str = ""
138
+
139
+ @property
140
+ def runs_on(self) -> str:
141
+ return self.engine or self.gpu.engine
142
+
143
+
144
+ ENGINES = (VLLM, LLAMACPP)
103
145
 
104
146
 
105
147
  class Cancelled(Exception):
106
148
  pass
107
149
 
108
150
 
109
- def _fits(model: Model, gpu: Gpu) -> bool:
151
+ def _unfit(model: Model, gpu: Gpu, engine: str = "") -> str:
152
+ """Why `model` cannot run on `gpu` with `engine` (the card's default when empty), or "" when it can."""
153
+ engine = engine or gpu.engine
154
+ if engine == VLLM and gpu.compute < VLLM_MIN_COMPUTE:
155
+ return f"vLLM runs on compute capability {VLLM_MIN_COMPUTE}+ and the {gpu.name} has {gpu.compute}"
156
+ if engine == LLAMACPP and not model.gguf:
157
+ return "it has no llama.cpp build yet" + (
158
+ f", which the {gpu.name} needs: vLLM runs on compute capability {VLLM_MIN_COMPUTE}+ and it has "
159
+ f"{gpu.compute}" if gpu.engine == LLAMACPP else "")
110
160
  # Cards are sold in GB and report a little under it: an "8 GB" 5060 reports 8151 MiB, a 7.96.
111
- return gpu.total_mib >= model.min_vram_gb * 1024 * 0.95
161
+ if gpu.total_mib < model.min_vram_gb * 1024 * 0.95:
162
+ return f"needs {model.min_vram_gb} GB of VRAM, the {gpu.name} has {gpu.total_mib / 1024:.0f} GB"
163
+ return ""
164
+
165
+
166
+ def _fits(model: Model, gpu: Gpu, engine: str = "") -> bool:
167
+ return not _unfit(model, gpu, engine)
168
+
169
+
170
+ def _engines(model: Model, gpu: Gpu) -> List[str]:
171
+ """The engines that run `model` on `gpu`, the default first."""
172
+ return [e for e in ENGINES if _fits(model, gpu, e)]
112
173
 
113
174
 
114
175
  def _busy_note(model: Model, gpu: Gpu) -> str:
@@ -116,20 +177,35 @@ def _busy_note(model: Model, gpu: Gpu) -> str:
116
177
  return "" if gpu.free_mib >= model.min_vram_gb * 1024 * 0.7 else "too full right now unless you free it up"
117
178
 
118
179
 
180
+ def _pci(bus_id: str) -> str:
181
+ """nvidia-smi's 00000000:01:00.0 as Vulkan writes it, 0000:01:00.0."""
182
+ domain, _, rest = bus_id.strip().lower().partition(":")
183
+ try:
184
+ return f"{int(domain, 16):04x}:{rest}" if rest else ""
185
+ except ValueError:
186
+ return ""
187
+
188
+
119
189
  def detect_gpus(run: Callable = subprocess.run) -> List[Gpu]:
120
190
  """Numbered as nvidia-smi numbers them, which is PCI order, so the server is pinned with that same order."""
121
191
  try:
122
- out = run(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free", "--format=csv,noheader,nounits"],
192
+ out = run(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free,compute_cap,pci.bus_id",
193
+ "--format=csv,noheader,nounits"],
123
194
  capture_output=True, text=True, timeout=30)
124
195
  except (OSError, subprocess.SubprocessError):
125
196
  return []
126
197
  if out.returncode != 0:
198
+ # A driver too old to report compute_cap is also too old for any CUDA 12 build.
199
+ if "compute_cap" in (out.stderr or "") + (out.stdout or ""):
200
+ raise RuntimeError("This NVIDIA driver is too old to self-host: update it (any driver from 2022 on "
201
+ "reports compute capability), or use the hosted API.")
127
202
  return []
128
203
  gpus = []
129
204
  for line in out.stdout.splitlines():
130
205
  fields = [f.strip() for f in line.split(",")]
131
- if len(fields) == 4 and fields[0].isdigit() and fields[2].isdigit() and fields[3].isdigit():
132
- gpus.append(Gpu(int(fields[0]), fields[1], int(fields[2]), int(fields[3])))
206
+ if len(fields) == 6 and fields[0].isdigit() and fields[2].isdigit() and fields[3].isdigit():
207
+ gpus.append(Gpu(int(fields[0]), fields[1], int(fields[2]), int(fields[3]), float(fields[4]),
208
+ _pci(fields[5])))
133
209
  return gpus
134
210
 
135
211
 
@@ -141,6 +217,13 @@ class Option(NamedTuple):
141
217
  disabled: str = ""
142
218
 
143
219
 
220
+ ENGINE_OPTIONS = {
221
+ VLLM: Option("vLLM", "the default: serves several solves at once; about 8 GB of serving stack, "
222
+ f"NVIDIA compute capability {VLLM_MIN_COMPUTE}+"),
223
+ LLAMACPP: Option("llama.cpp", "about 1 GB of serving stack, through Vulkan; one solve at a time"),
224
+ }
225
+
226
+
144
227
  def _read_key() -> str:
145
228
  ch = os.read(sys.stdin.fileno(), 1).decode(errors="ignore")
146
229
  if ch != "\x1b":
@@ -203,29 +286,38 @@ def choose(title: str, options: Sequence[Option], default: int = 0) -> int:
203
286
 
204
287
  def ask(gpus: Sequence[Gpu], saved: dict) -> Choice:
205
288
  """Model, then GPU, then startup. A previous choice is where the cursor starts."""
206
- biggest = max(gpus, key=lambda g: g.total_mib)
207
289
  menu = listed_models()
208
- default_model = next((i for i, m in enumerate(menu) if m.repo == saved.get("model")), 0)
290
+ runnable = [any(_fits(m, g) for g in gpus) for m in menu]
291
+ if not any(runnable):
292
+ raise RuntimeError(_no_model_fits(gpus))
293
+ default_model = next((i for i, m in enumerate(menu) if m.repo == saved.get("model") and runnable[i]),
294
+ runnable.index(True))
209
295
  picked = menu[choose("Which model do you want to run?", [
210
296
  Option(m.title, f"{m.blurb}, {m.download_gb:.1f} GB download, needs {m.min_vram_gb} GB of VRAM",
211
- "" if _fits(m, biggest) else f"needs {m.min_vram_gb} GB of VRAM, your largest has "
212
- f"{biggest.total_mib / 1024:.0f} GB")
213
- for m in menu], default_model)]
297
+ "" if ok else _unfit(m, max(gpus, key=lambda g: g.total_mib)))
298
+ for m, ok in zip(menu, runnable)], default_model)]
214
299
 
215
300
  fitting = [g for g in gpus if _fits(picked, g)]
216
301
  default_gpu = next((i for i, g in enumerate(gpus) if g.index == saved.get("gpu")), None)
217
302
  if default_gpu is None or gpus[default_gpu] not in fitting:
218
303
  default_gpu = gpus.index(max(fitting, key=lambda g: g.free_mib))
219
304
  gpu = gpus[choose("Which GPU should the server run on?", [
220
- Option(f"GPU {g.index}: {g.label}", _busy_note(picked, g), "" if g in fitting else f"too small for {picked.title}")
305
+ Option(f"GPU {g.index}: {g.label}", _busy_note(picked, g), _unfit(picked, g))
221
306
  for g in gpus], default_gpu)]
222
307
 
308
+ # Asked only where there is a choice: a card vLLM has no kernels for, or a model with no GGUF, has one engine.
309
+ engines = _engines(picked, gpu)
310
+ engine = engines[0]
311
+ if len(engines) > 1:
312
+ engine = engines[choose("Which engine should serve it?", [ENGINE_OPTIONS[e] for e in engines],
313
+ engines.index(saved["engine"]) if saved.get("engine") in engines else 0)]
314
+
223
315
  modes = [ALWAYS_ON, FIRST_SOLVE]
224
316
  startup = modes[choose("When should the server run?", [
225
317
  Option("Always on", "starts with this machine and restarts if it crashes"),
226
318
  Option("Warm start", "starts now and after a reboot on the first solve, then stays loaded"),
227
319
  ], modes.index(saved["startup"]) if saved.get("startup") in modes else 0)]
228
- return Choice(picked, gpu, startup)
320
+ return Choice(picked, gpu, startup, engine)
229
321
 
230
322
 
231
323
  # ── a licensed model's Hugging Face access ───────────────────────────────────
@@ -351,6 +443,10 @@ def make_venv(where: Path) -> Path:
351
443
  def install_client(python: Path, extra: str = "") -> None:
352
444
  """This same version from PyPI, or from the source beside this file when that version is not on PyPI."""
353
445
  subprocess.run([str(python), "-m", "pip", "install", "--quiet", "--upgrade", "pip"], check=True)
446
+ if extra == "[serve-llamacpp]":
447
+ # Before the client, so its torch pins are met by the CPU build and pip skips the 3 GB of CUDA libraries.
448
+ subprocess.run([str(python), "-m", "pip", "install", "--quiet", *TORCH_CPU, "--index-url", TORCH_CPU_INDEX],
449
+ check=True)
354
450
  wanted = f"captchakraken{extra}=={__version__}"
355
451
  if subprocess.run([str(python), "-m", "pip", "install", "--quiet", wanted]).returncode == 0:
356
452
  return
@@ -363,18 +459,73 @@ def install_client(python: Path, extra: str = "") -> None:
363
459
  _DOWNLOAD = """
364
460
  import os, sys
365
461
  from huggingface_hub import snapshot_download
366
- repo, sub = sys.argv[1], sys.argv[2]
367
- path = snapshot_download(repo, allow_patterns=[sub + "/*"] if sub else None)
462
+ repo, sub, patterns = sys.argv[1], sys.argv[2], sys.argv[3:]
463
+ path = snapshot_download(repo, allow_patterns=patterns or ([sub + "/*"] if sub else None))
368
464
  print(os.path.join(path, sub) if sub else path)
369
465
  """
370
466
 
371
467
 
372
- def download(python: Path, repo: str, subfolder: str = "") -> str:
373
- """The model directory. Stored as a path so a server never asks the Hub again. Only `subfolder` is fetched when one is given."""
374
- out = subprocess.run([str(python), "-c", _DOWNLOAD, repo, subfolder], stdout=subprocess.PIPE, text=True, check=True)
468
+ def download(python: Path, repo: str, subfolder: str = "", patterns: Sequence[str] = ()) -> str:
469
+ """The model directory. Stored as a path so a server never asks the Hub again. Only `subfolder`, or the
470
+ files matching `patterns`, are fetched when given."""
471
+ out = subprocess.run([str(python), "-c", _DOWNLOAD, repo, subfolder, *patterns], stdout=subprocess.PIPE,
472
+ text=True, check=True)
375
473
  return out.stdout.strip().splitlines()[-1]
376
474
 
377
475
 
476
+ def gguf_patterns(model: Model) -> Tuple[str, ...]:
477
+ """One language model of the GGUF repo, its vision encoder and the pointer heads."""
478
+ return (f"*-{model.gguf_quant}.gguf", "mmproj-*.gguf", "pointer_heads.safetensors")
479
+
480
+
481
+ def pointer_states_path() -> Path:
482
+ return config.state_dir() / "bin" / f"pointer_states-{POINTER_STATES_RELEASE}"
483
+
484
+
485
+ def fetch_pointer_states(http=requests) -> Path:
486
+ """The release binary, checked against its pinned digest. CAPTCHA_POINTER_STATES names a local build instead."""
487
+ import hashlib
488
+ local = os.getenv("CAPTCHA_POINTER_STATES")
489
+ if local:
490
+ return Path(local)
491
+ path = pointer_states_path()
492
+ if path.is_file():
493
+ return path
494
+ path.parent.mkdir(parents=True, exist_ok=True)
495
+ response = http.get(POINTER_STATES_URL, timeout=600)
496
+ response.raise_for_status()
497
+ digest = hashlib.sha256(response.content).hexdigest()
498
+ if digest != POINTER_STATES_SHA256:
499
+ raise RuntimeError(f"{POINTER_STATES_URL} has sha256 {digest}, not the {POINTER_STATES_SHA256} this "
500
+ "release pins. Nothing was installed.")
501
+ temporary = path.with_suffix(".tmp")
502
+ temporary.write_bytes(response.content)
503
+ temporary.chmod(0o755)
504
+ os.replace(temporary, path)
505
+ return path
506
+
507
+
508
+ NO_VULKAN = ("llama.cpp runs the {gpu} through Vulkan, and this machine has no Vulkan loader. "
509
+ "On Debian or Ubuntu: sudo apt install libvulkan1")
510
+ NO_VULKAN_GPU = ("Vulkan does not see the {gpu} (PCI {pci}); it sees {seen}. The NVIDIA driver's Vulkan part "
511
+ "may be missing: on Ubuntu it is in libnvidia-gl-<driver version>, and `vulkaninfo --summary` "
512
+ "(apt install vulkan-tools) lists what Vulkan sees.")
513
+
514
+
515
+ def check_vulkan(binary: Path, gpu: Gpu, run: Callable = subprocess.run) -> None:
516
+ """That llama.cpp can reach `gpu`, before gigabytes of weights download for it."""
517
+ out = run([str(binary), "--list-devices"], capture_output=True, text=True, timeout=60)
518
+ if out.returncode != 0:
519
+ if "libvulkan" in (out.stderr or ""):
520
+ raise RuntimeError(NO_VULKAN.format(gpu=gpu.name))
521
+ raise RuntimeError(f"{binary} --list-devices failed: {(out.stderr or '').strip()[-500:]}")
522
+ lines = [line for line in out.stdout.splitlines() if line.startswith("{")]
523
+ seen = json.loads(lines[-1])["gpus"] if lines else []
524
+ if not any(d.get("pci", "").lower() == gpu.pci for d in seen):
525
+ raise RuntimeError(NO_VULKAN_GPU.format(gpu=gpu.name, pci=gpu.pci,
526
+ seen=", ".join(d["name"] for d in seen) or "no GPU"))
527
+
528
+
378
529
  def free_port(start: int = 8000) -> int:
379
530
  for port in range(start, start + 100):
380
531
  with socket.socket() as s:
@@ -395,6 +546,8 @@ def settings(choice: Choice, model_path: str, saved: dict) -> dict:
395
546
  "model_path": model_path,
396
547
  "gpu": choice.gpu.index,
397
548
  "gpu_name": choice.gpu.name,
549
+ "engine": choice.runs_on,
550
+ "gpu_pci": choice.gpu.pci,
398
551
  "startup": choice.startup,
399
552
  "port": saved.get("port") or free_port(),
400
553
  # The client and the server both read it from this file, which only its owner can open.
@@ -447,14 +600,31 @@ def install(choice: Choice, saved: dict) -> dict:
447
600
  _disk_check(choice.model)
448
601
  server_manager.stop()
449
602
 
450
- _step("Installing the serving stack (torch and vLLM)")
603
+ engine = choice.runs_on
604
+ llama: dict = {}
605
+ if engine == LLAMACPP:
606
+ _step(f"Checking that llama.cpp can reach the {choice.gpu.name}"
607
+ + (" (vLLM has no kernels for it)" if choice.gpu.engine == LLAMACPP else ""))
608
+ binary = fetch_pointer_states()
609
+ check_vulkan(binary, choice.gpu)
610
+ llama = {"pointer_states": str(binary), "quant": choice.model.gguf_quant}
611
+ # The two engines need different torch builds of one version, and pip calls either one installed already.
612
+ if (saved.get("engine") or VLLM) != engine:
613
+ shutil.rmtree(config.runtime_dir(), ignore_errors=True)
614
+ _step("Installing the serving stack (torch and vLLM)" if engine == VLLM
615
+ else "Installing the serving stack (llama.cpp's helpers, on CPU torch)")
451
616
  python = make_venv(config.runtime_dir())
452
- install_client(python, "[serve]")
617
+ install_client(python, "[serve]" if engine == VLLM else "[serve-llamacpp]")
453
618
 
454
619
  _step(f"Downloading {choice.model.title}")
455
- model_path = download(python, choice.model.repo, choice.model.subfolder)
620
+ if engine == LLAMACPP:
621
+ model_path = download(python, choice.model.gguf, patterns=gguf_patterns(choice.model))
622
+ llama["processor_path"] = download(python, choice.model.processor_repo or choice.model.repo,
623
+ choice.model.subfolder, PROCESSOR_FILES)
624
+ else:
625
+ model_path = download(python, choice.model.repo, choice.model.subfolder)
456
626
 
457
- values = settings(choice, model_path, saved)
627
+ values = {**settings(choice, model_path, saved), **llama}
458
628
  write_settings(values)
459
629
  config.selfhost.cache_clear()
460
630
 
@@ -477,7 +647,8 @@ def _summary(values: dict) -> None:
477
647
  command = link_command()
478
648
  bare = bool(command) and _on_path(command)
479
649
  name = "captchakraken" if bare else str(command or config.runtime_dir() / "bin" / "captchakraken")
480
- _ok(f"{values['title']} is running on GPU {values['gpu']} at http://127.0.0.1:{values['port']}")
650
+ engine = ENGINE_OPTIONS.get(values.get("engine") or VLLM, ENGINE_OPTIONS[VLLM]).label
651
+ _ok(f"{values['title']} is running on GPU {values['gpu']} with {engine} at http://127.0.0.1:{values['port']}")
481
652
  print(f"\nTry it:\n {name} demo\n")
482
653
  print(f"Start and stop the server:\n {name} start\n {name} stop\n")
483
654
  if command and not bare:
@@ -486,24 +657,48 @@ def _summary(values: dict) -> None:
486
657
  print(f"VLLM_BASE_URL is set in this shell, and it wins over this install: {os.environ['VLLM_BASE_URL']}\n")
487
658
 
488
659
 
660
+ def _no_model_fits(gpus: Sequence[Gpu]) -> str:
661
+ return ("No model runs on " + ", ".join(g.name for g in gpus) + ": "
662
+ + "; ".join(sorted({_unfit(m, g) for m in listed_models() for g in gpus})) + ".\n"
663
+ "The hosted API needs no GPU: https://github.com/CaptchaKraken/CaptchaKraken/blob/main/docs/hosted-api.md")
664
+
665
+
489
666
  def _from_flags(gpus: Sequence[Gpu], saved: dict, model: Optional[str], gpu: Optional[int],
490
- startup: Optional[str]) -> Choice:
491
- wanted = model or saved.get("model") or MODELS[0].repo
667
+ startup: Optional[str], engine: Optional[str] = None) -> Choice:
668
+ wanted = model or saved.get("model") or next((m.repo for m in listed_models() if any(_fits(m, g) for g in gpus)),
669
+ MODELS[0].repo)
492
670
  found = next((m for m in MODELS if m.named(wanted)), None)
493
671
  if found is None:
494
672
  raise RuntimeError(f"Unknown model {wanted!r}. Choose from: abyss, "
495
673
  + ", ".join(m.repo.split("/")[-1] for m in listed_models()))
674
+ if engine and engine not in ENGINES:
675
+ raise RuntimeError(f"Unknown engine {engine!r}. Choose from: {', '.join(ENGINES)}")
676
+ asked = engine or ""
496
677
  index = gpu if gpu is not None else saved.get("gpu")
497
678
  if index is None:
498
- fitting = [g for g in gpus if _fits(found, g)]
679
+ fitting = [g for g in gpus if _fits(found, g, asked)]
499
680
  if not fitting:
500
- raise RuntimeError(f"{found.title} needs {found.min_vram_gb} GB of VRAM.")
681
+ biggest = max(gpus, key=lambda g: g.total_mib)
682
+ raise RuntimeError(f"{found.title} cannot run here: {_unfit(found, biggest, asked)}."
683
+ + _runs_here_hint(gpus))
501
684
  chosen = max(fitting, key=lambda g: g.free_mib)
502
685
  else:
503
686
  chosen = next((g for g in gpus if g.index == index), None)
504
687
  if chosen is None:
505
688
  raise RuntimeError(f"There is no GPU {index}. Found: {[g.index for g in gpus]}")
506
- return Choice(found, chosen, startup or saved.get("startup") or ALWAYS_ON)
689
+ if _unfit(found, chosen, asked):
690
+ raise RuntimeError(f"{found.title} cannot run on GPU {index}: {_unfit(found, chosen, asked)}."
691
+ + _runs_here_hint(gpus))
692
+ if not engine:
693
+ # The last engine, while it still runs this model on this card; else the card's default.
694
+ engines = _engines(found, chosen)
695
+ engine = saved.get("engine") if saved.get("engine") in engines else engines[0]
696
+ return Choice(found, chosen, startup or saved.get("startup") or ALWAYS_ON, engine)
697
+
698
+
699
+ def _runs_here_hint(gpus: Sequence[Gpu]) -> str:
700
+ here = [m.repo.split("/")[-1] for m in listed_models() if any(_fits(m, g) for g in gpus)]
701
+ return f" These run here: --model {', '.join(here)}" if here else ""
507
702
 
508
703
 
509
704
  NO_GPU = ("No NVIDIA GPU was found, and self-hosting needs one on Linux.\n"
@@ -511,11 +706,15 @@ NO_GPU = ("No NVIDIA GPU was found, and self-hosting needs one on Linux.\n"
511
706
 
512
707
 
513
708
  def fetch(*, yes: bool = False, model: Optional[str] = None, gpu: Optional[int] = None,
514
- startup: Optional[str] = None) -> int:
709
+ startup: Optional[str] = None, engine: Optional[str] = None) -> int:
515
710
  if sys.platform != "linux":
516
711
  print(NO_GPU, file=sys.stderr)
517
712
  return 1
518
- gpus = detect_gpus()
713
+ try:
714
+ gpus = detect_gpus()
715
+ except RuntimeError as e:
716
+ print(f"\033[1;31m✗\033[0m {e}", file=sys.stderr)
717
+ return 1
519
718
  if not gpus:
520
719
  print(NO_GPU, file=sys.stderr)
521
720
  return 1
@@ -523,11 +722,11 @@ def fetch(*, yes: bool = False, model: Optional[str] = None, gpu: Optional[int]
523
722
  interactive = sys.stdin.isatty() and sys.stdout.isatty()
524
723
  if not yes and not interactive:
525
724
  print("`captchakraken fetch` asks its questions in a terminal. Without one, pass --yes, "
526
- "plus --model, --gpu and --startup to choose other than the defaults.", file=sys.stderr)
725
+ "plus --model, --gpu, --engine and --startup to choose other than the defaults.", file=sys.stderr)
527
726
  return 2
528
727
  try:
529
728
  if yes:
530
- choice = _from_flags(gpus, saved, model, gpu, startup)
729
+ choice = _from_flags(gpus, saved, model, gpu, startup, engine)
531
730
  else:
532
731
  print("\n\033[1mCaptchaKraken self-hosted setup\033[0m\n")
533
732
  choice = ask(gpus, saved)
@@ -88,12 +88,17 @@ def build_serve_command() -> "list[str]":
88
88
  from . import prompts
89
89
 
90
90
  if prompts.resolve(config.lora_adapter()).pointer:
91
- capture = config.max_cudagraph_capture_size()
92
- return [
91
+ server = [
93
92
  _serve_python(), "-m", "captchakraken.pointer.server",
94
93
  "--model", config.serve_model(),
95
94
  "--host", os.getenv("CAPTCHA_POINTER_HOST", "127.0.0.1"),
96
95
  "--port", str(config.port()),
96
+ ]
97
+ if config.engine() == "llamacpp":
98
+ return [*server, "--engine", "llamacpp", *config.llamacpp_args()]
99
+ capture = config.max_cudagraph_capture_size()
100
+ return [
101
+ *server,
97
102
  "--gpu-memory-utilization", str(config.gpu_memory_utilization()),
98
103
  *(["--max-cudagraph-capture-size", str(capture)] if capture else []),
99
104
  ]