okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main dbb2d168c (picture-reader fix, GGML_NO_BACKTRACE) into f-own-int2503b206b

main
6.9 KiB127 linesraw
1"""The picture reader and a graphics card that has no room for it: what its output says, and the words.
2
3The GPU picture reader (strata-vision, llama.cpp's mtmd) asks the card for its weights and work buffers when it starts.  A card that another program
4has filled answers "cudaMalloc failed: out of memory" (the same text on AMD cards, whose runtime ggml names the same way) and ggml aborts: the reader cannot
5print an answer of its own.  Its lines end up in the engine log (its stderr is the log):
6
7    ggml_backend_cuda_buffer_type_alloc_buffer: allocating 865.48 MiB on device 0: cudaMalloc failed: out of memory
8    alloc_tensor_range: failed to allocate CUDA0 buffer of size 907524736
9    ggml-backend.cpp:188: GGML_ASSERT(buffer) failed
10
11`find` reads them (card number inside the reader's own numbering, and how much it asked for); the two sentences below are what the person reads, in the
12Terminal's launch summary (the reader moved to the processor) and in the error (the launch ended because of it).  One wording for the server and the
13Terminal.  Pure functions, no I/O.
14"""
15from __future__ import annotations
16
17import re
18from dataclasses import dataclass
19
20_ALLOC = re.compile(r"allocating (\d+(?:\.\d+)?) MiB on device (\d+): (?:cuda|hip)Malloc failed: out of memory", re.I)
21_BUFFER = re.compile(r"failed to allocate (?:CUDA|ROCm|HIP|MUSA)(\d+) buffer of size (\d+)", re.I)
22_GENERIC = re.compile(r"(?:cuda|hip)Malloc failed: out of memory", re.I)
23
24
25#: What the GPU picture reader takes from the card in all, at the default image limit of 1,024 tokens: 1,342 MiB measured on an RTX A6000 and an R9700, 1,536 the
26#: figure the server plans with (serve/server.py READER_NEEDS_MIB).  Above 1,024 tokens the picture is bigger and so are the reader's work buffers: at 16,384
27#: tokens the largest peak measured for mtmd's GPU reader was 3,674 MiB (P100, Qwen3.8), 3,264-3,656 MiB on the other cards; between the two the need is taken to
28#: grow in a straight line with the limit (an estimate, said as "about").  A limit of 0 means no limit: the largest the Terminal offers, 16,384.
29READER_NEEDS_MIB = 1536
30READER_NEEDS_AT_LIMIT_MIB = 3674
31READER_LIMIT_DEFAULT = 1024
32READER_LIMIT_LARGEST = 16384
33
34
35def reader_needs_mib(max_tokens: int | None = None) -> float:
36    """The reader's whole need of the card, in MiB, at an image limit of max_tokens tokens (None: the default limit; 0: no limit)."""
37    limit = READER_LIMIT_DEFAULT if max_tokens is None else int(max_tokens)
38    if limit == 0:
39        limit = READER_LIMIT_LARGEST
40    limit = min(max(limit, READER_LIMIT_DEFAULT), READER_LIMIT_LARGEST)
41    return READER_NEEDS_MIB + (limit - READER_LIMIT_DEFAULT) * (READER_NEEDS_AT_LIMIT_MIB - READER_NEEDS_MIB) / (READER_LIMIT_LARGEST - READER_LIMIT_DEFAULT)
42
43
44def whole_need_mib(failed_mib: float | None, max_tokens: int | None = None) -> float:
45    """What to tell the person the reader needs: the larger of the one allocation that failed (the line says it) and the reader's known need at its limit.  The
46    failed allocation alone is not the need: a person who frees that much and nothing more still fails on the next one."""
47    return max(float(failed_mib or 0.0), reader_needs_mib(max_tokens))
48
49
50@dataclass(frozen=True)
51class NoRoom:
52    """`device`: the card's number as the reader counts (the cards its environment shows it), None when the lines do not say; `need_mib`: what it asked for."""
53    device: int | None = None
54    need_mib: float | None = None
55
56
57def find(text_or_lines) -> NoRoom | None:
58    """The reader's out-of-memory lines in `text_or_lines` (a string, or a list of lines), or None.  The last allocation that failed is the one reported."""
59    lines = text_or_lines.splitlines() if isinstance(text_or_lines, str) else [str(x) for x in text_or_lines or []]
60    alloc = buffer = None
61    generic = False
62    for line in lines:
63        m = _ALLOC.search(line)
64        if m:
65            alloc = NoRoom(int(m.group(2)), float(m.group(1)))
66            continue
67        m = _BUFFER.search(line)
68        if m:
69            buffer = NoRoom(int(m.group(1)), int(m.group(2)) / 1048576.0)
70            continue
71        if _GENERIC.search(line):
72            generic = True
73    return alloc or buffer or (NoRoom() if generic else None)
74
75
76def physical_card(device: int | None, visible) -> int | None:
77    """The card's number as nvidia-smi counts, from the reader's number and the list of cards its environment shows it (CUDA_VISIBLE_DEVICES, the engine's
78    card order); the reader's own number when it sees them all.  None when it cannot be said."""
79    if device is None:
80        return None
81    if isinstance(visible, str):
82        visible = [x for x in re.split(r"[,\s]+", visible.strip()) if x]
83    if visible:
84        try:
85            return int(str(visible[device]).strip())
86        except (IndexError, ValueError):
87            return None
88    return device
89
90
91def _gb(mib: float) -> str:
92    gb = mib / 1024.0
93    return f"{gb:.1f} GB" if gb >= 0.05 else "less than 0.1 GB"
94
95
96def _facts(need_mib: float | None, free_mib: float | None) -> str:
97    """The figures in brackets: what the reader needs and what the card has; only what is known, nothing when neither is."""
98    parts = []
99    if need_mib:
100        parts.append(f"it needs about {_gb(need_mib)}")
101    if free_mib is not None:
102        parts.append(f"{_gb(free_mib)} are free")
103    return " (" + "; ".join(parts) + ")" if parts else ""
104
105
106def _card(card: int | None) -> str:
107    return f"graphics card {card}" if card is not None else "the graphics card"
108
109
110def on_processor(card: int | None = None, need_mib: float | None = None, free_mib: float | None = None) -> str:
111    """The launch goes on and the pictures are read on the processor (the Terminal's summary line)."""
112    return (f"Pictures are read on the processor, which is slower: {_card(card)} has no room for the picture reader{_facts(need_mib, free_mib)}. "
113            "To read them on the card, close the other programs that use it and start again.")
114
115
116def not_started_on_processor(card: int | None = None, log_path: str | None = None) -> str:
117    """The launch goes on and the pictures are read on the processor because the GPU reader did not start for a reason that is not a full card (the summary
118    line; the reason is in the engine log, which is the reader's stderr).  Without the card's number, or the log's path, those words are left out."""
119    where = f" on graphics card {card}" if card is not None else ""
120    why = f" The reason is in the engine's log: {log_path}." if log_path else ""
121    return f"Pictures are read on the processor, which is slower: the picture reader could not start{where}.{why}"
122
123
124def could_not_start(card: int | None = None, need_mib: float | None = None, free_mib: float | None = None) -> tuple[str, str]:
125    """(what happened, the next step) when the launch ends because the reader could not start."""
126    return (f"The picture reader could not start: {_card(card)} has no room for it{_facts(need_mib, free_mib)}.",
127            "Close the other programs that use the card and start again, or add --vision off to start without pictures.")