okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
13.6 KiB303 linesraw
1"""DeepSeek models that this Strata no longer runs: how a saved config, a folder, a file or a typed name is recognised, and the words
2a person sees.
3
4Strata ran DeepSeek-V4.1-Flash up to 0.2.13 on an engine of its own (strata-dsv41).  This version does not: a DeepSeek config is
5refused before anything starts and before any file of it is written, its model files are never touched, and the words name where
6they are and how large, so the person can decide.  Every check here is local and bounded (config fields, a file name, the first
7bytes of one GGUF, the sizes of the files directly in one or two folders): it answers at once, also offline, and never raises.
8"""
9from __future__ import annotations
10
11import json
12import os
13import re
14import struct
15from pathlib import Path
16from typing import Any, Iterable, Mapping
17
18#: the family and arch names setup and the server used for DeepSeek-V4.1-Flash
19FAMILY = "deepseek41"
20ENGINE_NAMES = ("strata-dsv41", "strata-dsv41.exe")
21#: the model sizes setup and `strata launch` offered under --family deepseek41 (lower case); "UD-IQ1_M" and "UD-IQ1_S" are not here: they are also
22#: Unsloth Qwen names
23MODEL_NAMES = frozenset({"ist-das-2.00bpw", "ist-das-2.25bpw", "ist-das-1.75bpw", "ista-das-coder", "ud-q8_k_xl",
24                         "deepseek-v4.1-flash", "deepseek41", "deepseek"})
25#: the config file stem setup wrote (strata-deepseek-v4.1-flash-<size>.json) and the model_name in it
26TAG = "deepseek-v4.1-flash"
27#: the published file names of the DeepSeek sets (unsloth, ISTA-DAS, the Engram table, the DSpark drafter)
28_FILE = re.compile(r"^(?:dspark-)?DeepSeek-V4[._]?1-Flash[-_].*\.gguf$", re.I)
29_DIR_ENTRIES = 200            # entries looked at in one folder: a bounded look, never a walk
30_GGUF_HEAD = 1 << 20          # bytes of a GGUF read to find general.architecture
31
32
33# Every sentence below is the owner's approved wording of 11-11 (par/OWNER-WORDING-1111.md): change none without him.
34#: D1: a start of a saved DeepSeek model (the app, `strata start`, a saved launch)
35REFUSED = "{name} is a DeepSeek model. This version of Strata no longer runs DeepSeek models, so it was not started."
36FILES_STAY = "Its files are still on this computer: {size} in {folder}. Nothing was changed or deleted."
37NEXT = ("Choose a Qwen model to run instead. If you no longer need the DeepSeek files, you can delete that folder "
38        "to free the space.")
39#: D2: the model list's line for a DeepSeek row
40ROW = "DeepSeek - no longer supported."
41ROW_FILES = "DeepSeek - no longer supported. {size} in {folder}."
42#: D3: DeepSeek asked for by name (`strata launch --model`, `--family deepseek41`, setup, a DeepSeek-only flag)
43NOT_OFFERED = "Strata no longer offers DeepSeek models. Run `strata launch` to choose one of the Qwen models."
44#: D4: the person's own DeepSeek files (`strata launch --model-path`, the own-files screen, `strata models import`)
45OWN_FILES = ("These are DeepSeek model files ({size} in {folder}). This version of Strata no longer runs DeepSeek models; "
46             "nothing in the folder was changed. Choose a Qwen model instead.")
47OWN_FILES_NOSIZE = ("These are DeepSeek model files (in {folder}). This version of Strata no longer runs DeepSeek models; "
48                    "nothing in the folder was changed. Choose a Qwen model instead.")
49#: D5: the server started directly with a DeepSeek config or tokenizer
50SERVER = ("[strata] this config runs a DeepSeek model ({why}). This version of Strata no longer runs DeepSeek models, so the "
51          "server stops here. The model files were not changed.")
52#: D6: setup's update and its list of installed models
53LEFT_AS_IS = "{name}: a DeepSeek model, left as it is (this version of Strata no longer runs DeepSeek models)."
54
55WHY = {"arch": "arch deepseek41", "engine": "engine strata-dsv41", "tokenizer": "DeepSeek tokenizer", "gguf": "DeepSeek model file",
56       "name": "DeepSeek model name"}
57
58
59# ----------------------------------------------------------------------------------------------------------- recognising
60def is_name(word: Any) -> bool:
61    """A model, size or family name typed or saved for DeepSeek (`--model IST-DAS-2.00bpw`, `--family deepseek41`, a saved choice)."""
62    if not isinstance(word, str) or not word.strip():
63        return False
64    w = word.strip().lower()
65    return w in MODEL_NAMES or w.startswith(TAG) or w.startswith("deepseek-v4")
66
67
68def is_file_name(name: Any) -> bool:
69    """A published DeepSeek-V4.1-Flash file name (a shard, the Engram table, the DSpark drafter)."""
70    return isinstance(name, str) and bool(_FILE.match(Path(name).name))
71
72
73def gguf_arch(path: Any) -> str | None:
74    """general.architecture of a GGUF file, read from its first megabyte (None: not a GGUF, unreadable, or not found early)."""
75    try:
76        with open(path, "rb") as f:
77            head = f.read(_GGUF_HEAD)
78    except (OSError, TypeError, ValueError):
79        return None
80    if len(head) < 24 or head[:4] != b"GGUF":
81        return None
82    try:
83        pos = 8 + 8                                    # magic, version, tensor count
84        (n_kv,) = struct.unpack_from("<Q", head, pos)
85        pos += 8
86        sizes = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
87        for _ in range(min(n_kv, 64)):
88            (klen,) = struct.unpack_from("<Q", head, pos)
89            pos += 8
90            key = head[pos:pos + klen].decode("utf-8", "replace")
91            pos += klen
92            (vtype,) = struct.unpack_from("<I", head, pos)
93            pos += 4
94            if vtype == 8:                             # a string
95                (slen,) = struct.unpack_from("<Q", head, pos)
96                pos += 8
97                value = head[pos:pos + slen].decode("utf-8", "replace")
98                pos += slen
99                if key == "general.architecture":
100                    return value
101            elif vtype in sizes:
102                pos += sizes[vtype]
103            else:                                      # an array before the architecture: stop looking
104                return None
105            if pos > len(head):
106                return None
107    except (struct.error, ValueError):
108        return None
109    return None
110
111
112def _tokenizer_pre(cfg: Mapping) -> str | None:
113    tok = cfg.get("tokenizer")
114    if not isinstance(tok, str) or not tok:
115        return None
116    try:
117        with open(Path(tok) / "tokenizer.json", "rb") as f:
118            data = f.read(_GGUF_HEAD)
119        pre = json.loads(data.decode("utf-8")).get("pre")
120    except (OSError, ValueError, AttributeError, TypeError):
121        return None
122    return pre if isinstance(pre, str) else None
123
124
125def config_reason(cfg: Any) -> str | None:
126    """Why a run config is a DeepSeek one ("arch", "engine", "tokenizer", "name"), or None.  Reads the config's fields and, only when it
127    names no arch, the first megabyte of its tokenizer.json."""
128    if not isinstance(cfg, Mapping):
129        return None
130    arch = cfg.get("arch")
131    if isinstance(arch, str) and arch.strip().lower().startswith("deepseek"):
132        return "arch"
133    exe = cfg.get("exe")
134    if isinstance(exe, str) and re.split(r"[\\/]", exe)[-1].lower() in ENGINE_NAMES:
135        return "engine"
136    if isinstance(cfg.get("model_name"), str) and is_name(cfg["model_name"]):
137        return "name"
138    if not arch:
139        pre = _tokenizer_pre(cfg)
140        if pre and pre.lower().startswith("deepseek"):
141            return "tokenizer"
142    return None
143
144
145def read_config(path: Any) -> dict | None:
146    try:
147        data = json.loads(Path(path).read_text(encoding="utf-8-sig"))
148    except (OSError, ValueError, TypeError):
149        return None
150    return data if isinstance(data, dict) else None
151
152
153def config_file_reason(path: Any) -> str | None:
154    """config_reason of a run config file (an unreadable file is not DeepSeek's: the usual errors say what is wrong with it)."""
155    stem = Path(str(path)).stem.lower() if path else ""
156    if stem.startswith("strata-" + TAG):
157        return "name"
158    return config_reason(read_config(path))
159
160
161def folder_reason(path: Any) -> str | None:
162    """Why a folder or file the person points at holds a DeepSeek model ("name": a published file name, "gguf": a GGUF whose architecture
163    is DeepSeek's), or None.  Looks at most at _DIR_ENTRIES names and reads the head of at most one GGUF."""
164    try:
165        p = Path(path)
166        if p.is_file():
167            if is_file_name(p.name):
168                return "name"
169            arch = gguf_arch(p)
170            return "gguf" if arch and arch.lower().startswith("deepseek") else None
171        if not p.is_dir():
172            return None
173        first = None
174        with os.scandir(p) as it:
175            for i, entry in enumerate(it):
176                if i >= _DIR_ENTRIES:
177                    break
178                if is_file_name(entry.name):
179                    return "name"
180                if first is None and entry.name.lower().endswith(".gguf") and entry.is_file():
181                    first = entry.path
182        if first:
183            arch = gguf_arch(first)
184            return "gguf" if arch and arch.lower().startswith("deepseek") else None
185    except OSError:
186        return None
187    return None
188
189
190# ------------------------------------------------------------------------------------------------------ where and how large
191def _top_files(folder: Path) -> tuple[int, int]:
192    """(bytes, files) of the files directly in `folder` (at most _DIR_ENTRIES entries; symlinks followed, folders not entered)."""
193    total = count = 0
194    try:
195        with os.scandir(folder) as it:
196            for i, entry in enumerate(it):
197                if i >= _DIR_ENTRIES:
198                    break
199                try:
200                    if entry.is_file():
201                        total += entry.stat().st_size
202                        count += 1
203                except OSError:
204                    continue
205    except OSError:
206        pass
207    return total, count
208
209
210def _pack_model_dir(pack: Path) -> Path | None:
211    """The model folder a DeepSeek pack names (its ds4.txt line `model_dir <folder>`)."""
212    try:
213        with open(pack / "ds4.txt", "r", encoding="utf-8", errors="replace") as f:
214            for i, line in enumerate(f):
215                if i > 400:
216                    break
217                if line.startswith("model_dir "):
218                    return Path(line[len("model_dir "):].strip())
219    except OSError:
220        return None
221    return None
222
223
224def config_folders(cfg: Mapping) -> list[Path]:
225    """The folders that hold a DeepSeek config's model: the model folder its pack names, then the pack itself (existing ones only)."""
226    args = [str(x) for x in (cfg.get("args") or []) if isinstance(x, (str, int, float))]
227    out: list[Path] = []
228    for flag in ("--pack", "--model"):
229        if flag in args and args.index(flag) + 1 < len(args):
230            p = Path(args[args.index(flag) + 1])
231            model_dir = _pack_model_dir(p) if flag == "--pack" else None
232            for q in (model_dir, p if p.is_dir() else p.parent if p.is_file() else None):
233                if q is not None and q.is_dir() and q not in out:
234                    out.append(q)
235    return out
236
237
238def where(folders: Iterable[Path]) -> tuple[str, int] | None:
239    """("<folder>[ and <folder>]", bytes) of the files directly in these folders, or None when none is there."""
240    folders = list(folders)
241    total, names = 0, []
242    for f in folders:
243        size, count = _top_files(f)
244        if count:
245            total += size
246            names.append(str(f))
247    return (" and ".join(names), total) if names else None
248
249
250def size_words(n: int) -> str:
251    gb = max(n, 0) / 1e9
252    return f"{gb:.0f} GB" if gb >= 10 else f"{gb:.1f} GB"
253
254
255# ----------------------------------------------------------------------------------------------------------------- words
256_LABELS = {"ist-das-2.00bpw": "ISTA-DAS 2.00 bpw", "ist-das-2.25bpw": "ISTA-DAS 2.25 bpw", "ist-das-1.75bpw": "ISTA-DAS 1.75 bpw",
257           "ista-das-coder": "ISTA-DAS Coder", "ud-q8_k_xl": "Unsloth UD-Q8_K_XL", "ud-iq1_s": "Unsloth UD-IQ1_S", "ud-iq1_m": "Unsloth UD-IQ1_M"}
258
259
260def title(cfg: Mapping | None = None, path: Any = None) -> str:
261    """The model's name as setup showed it ("DeepSeek-V4.1-Flash ISTA-DAS 2.00 bpw"), from the config file's name when it has setup's form."""
262    stem = Path(str(path)).stem.lower() if path else ""
263    head = "strata-" + TAG + "-"
264    if stem.startswith(head):
265        size = stem[len(head):]
266        return "DeepSeek-V4.1-Flash " + _LABELS.get(size, size.upper())
267    return "DeepSeek-V4.1-Flash"
268
269
270def refusal(cfg: Mapping | None, name: str | None = None) -> str:
271    """D1: the whole refusal for a saved DeepSeek model: what happened, where its files are and how large (when that can be read), the
272    next step."""
273    title = name or (cfg or {}).get("model_name") or "This model"
274    lines = [REFUSED.format(name=title)]
275    found = where(config_folders(cfg)) if isinstance(cfg, Mapping) else None
276    if found:
277        lines.append(FILES_STAY.format(size=size_words(found[1]), folder=found[0]))
278    lines.append(NEXT)
279    return " ".join(lines)
280
281
282def row_line(cfg: Mapping | None) -> str:
283    """D2: the model list's line for a DeepSeek row."""
284    found = where(config_folders(cfg)) if isinstance(cfg, Mapping) else None
285    return ROW_FILES.format(size=size_words(found[1]), folder=found[0]) if found else ROW
286
287
288def own_files(path: Any) -> str:
289    """D4: the person pointed at DeepSeek files."""
290    p = Path(path)
291    folder = p if p.is_dir() else p.parent
292    found = where([folder])
293    return OWN_FILES.format(size=size_words(found[1]), folder=found[0]) if found else OWN_FILES_NOSIZE.format(folder=folder)
294
295
296def server_line(reason: str) -> str:
297    """D5."""
298    return SERVER.format(why=WHY.get(reason, reason))
299
300
301def left_as_is(name: str) -> str:
302    """D6."""
303    return LEFT_AS_IS.format(name=name)