okami.mom/strata

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

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

main
17.5 KiB312 linesraw
1#!/bin/sh
2# Entry point of the Strata container: `strata launch --no-tui` with the settings the TUI asks for, read from environment
3# variables, then stay up and stop cleanly on SIGTERM (`docker stop`).
4#
5#   docker run ... strata              start the server (default)
6#   docker run ... strata strata ...   run any strata command instead (e.g. `strata launch --plan --model q2_0`)
7#   docker run ... strata sh           a shell
8#
9# Settings (all optional; names match the screens of `strata launch`):
10#   MODEL         model size, e.g. IQ3_XXS, Q2_0 (empty: Strata picks one for this card and says so)
11#   FAMILY        model family when a size is offered by several (qwen, swift, coder, ...)
12#   MODEL_PATH    GGUF files you already have, a folder or one .gguf, inside the container (mount it read-only)
13#   ALLOW_DOWNLOAD  1: go on and download the model although model files of the older layout (/data/models) were left unread (default: stop)
14#   CONTEXT       32k, 64k, 128k, 256k or a number of tokens
15#   PARALLEL      requests answered at the same time, 1 to 8 (empty: fit to the card)
16#   VISION        off | on | gpu | cpu  (pictures; the picture reader file is downloaded with the model)
17#   KV            int8 | q4_0 | k8v4 | fp16  (conversation memory format)
18#   GPU / GPUS    card numbers, e.g. 0 or 0,1 (empty or "all": the engine's choice)
19#   GPU_ROLES     a role for each card, e.g. 1=main,0=helper (main, helper or off; cards you do not name are off; not together with GPU / GPUS)
20#   TUNE          quick | thorough | skip   (done once; RETUNE=1 tunes again)
21#   PORT          port inside the container (default 8080)
22#   API_KEY / API_KEY_FILE   the key clients must send. The server listens on every address inside the container, and Strata does
23#                 not serve beyond loopback without a key, so one is always on: yours, or one made on the first start and kept in /data.
24#   PRESET        preset name in /data (default "docker"). Settings above are saved into it; with no settings given a saved preset is reused.
25#   STRATA_SET    advanced engine settings, space separated KEY=VALUE (like `strata launch --set`)
26set -u
27
28APP=/opt/strata
29STRATA="$APP/terminal/bin/strata"
30PYBIN="$APP/terminal/python/bin/python3"; [ -x "$PYBIN" ] || PYBIN=$(command -v python3 || echo python3)
31STATE_DIR="${XDG_STATE_HOME:-/data/state}/strata"
32KEY_FILE="${STRATA_KEY_FILE:-/data/state/api-key}"
33PHASE_FILE=/run/strata-phase
34PRESET="${PRESET:-docker}"
35PORT="${PORT:-8080}"
36
37say()  { printf '%s\n' "$*"; }
38warn() { printf '[!] %s\n' "$*" >&2; }
39die()  { printf '[X] %s\n' "$*" >&2; exit "${2:-1}"; }
40phase() { printf '%s\n' "$1" > "$PHASE_FILE" 2>/dev/null || true; }
41
42# Model files of the older layout that this image did not move (a folder you mounted at /data/models, or a move that failed) are not read here, and
43# the start would download the model again. Say so and stop instead (#3421); ALLOW_DOWNLOAD=1 goes on, with the same text as a warning.
44# $1: MODEL_PATH (when it is set the files are named and nothing is lost), $2: the older models folder.
45legacy_models_guard() {
46  [ -n "$1" ] && return 0
47  stuck=$(find "$2" -maxdepth 3 -name '*.gguf' 2>/dev/null | head -1)
48  [ -n "$stuck" ] || return 0
49  msg="There are model files in ${stuck%/*} (the older image's place). This image keeps its models in /data/Strata-data/models and does not read them there, so it would download the model again (tens of GB). To use them: mount that folder read-only and set MODEL_PATH to the folder that holds the shards (docs/DOCKER.md, \"Files you already have\"), or put them in /data/Strata-data/models/<model folder>/. To download anyway: set ALLOW_DOWNLOAD=1. Nothing was downloaded."
50  if [ "${ALLOW_DOWNLOAD:-0}" = "1" ]; then warn "$msg Going on, because ALLOW_DOWNLOAD=1."; else die "$msg" 2; fi
51}
52
53# ---- other commands: `docker run image strata ...`, `docker run image sh`
54if [ "$#" -gt 0 ] && [ "$1" != "run" ] && [ "$1" != "serve" ]; then
55  case "$1" in strata) shift; exec "$STRATA" "$@" ;; *) exec "$@" ;; esac
56fi
57
58mkdir -p /data/state /data/home /data/install /data/Strata-data /run 2>/dev/null || die "/data is not writable. Mount a volume there: -v strata-data:/data"
59if ! grep -q " /data " /proc/self/mountinfo 2>/dev/null; then
60  warn "/data is not a volume, so the model and your settings are lost when this container is removed. Add: -v strata-data:/data"
61fi
62
63# ---- plain warnings (never refusals)
64cpuinfo="${STRATA_CPUINFO:-/proc/cpuinfo}"
65if [ -r "$cpuinfo" ] && grep -q '^flags' "$cpuinfo" && ! grep -m1 '^flags' "$cpuinfo" | grep -qw avx2; then
66  warn "This computer's CPU has no AVX2. The engine is built for CPUs with AVX2 and may stop with 'illegal instruction'."
67fi
68limit=$(cat /sys/fs/cgroup/memory.max 2>/dev/null || echo max)
69case "$limit" in max|"") ;; *[!0-9]*) ;; *)
70  gb=$((limit / 1073741824))
71  warn "This container has a memory limit of ${gb} GB. Strata plans from the host's RAM (/proc/meminfo) and loads tens of GB, so a low limit can end in the container being killed. Raise or remove the limit."
72esac
73if [ -n "${API_KEY:-}" ] && [ "${#API_KEY}" -lt 16 ]; then
74  warn "API_KEY is short (${#API_KEY} characters). Use 16 or more; 'openssl rand -hex 24' makes a good one."
75fi
76for legacy in HOST LOW_RAM REINSTALL RESIDENT_BUDGET_GIB KV_STREAMING LAYER_SPLIT CONFIG; do
77  eval "v=\${$legacy:-}"
78  [ -n "$v" ] && warn "$legacy is from the older image and is ignored here. See docs/DOCKER.md (\"From the older image\")."
79done
80
81# ---- a volume from the older (0.1.x) image: its models, packs and draft layer are in /data/models, /data/packs and /data/mtp.
82# This image keeps them in /data/Strata-data. Move them over (a rename inside one volume: instant, no copy, no download).
83# A folder that is its own mount (a bind mount of yours) is never touched.
84legacy_moved=""
85for d in models packs mtp; do
86  [ -d "/data/$d" ] || continue
87  grep -q " /data/$d " /proc/self/mountinfo 2>/dev/null && continue
88  [ -n "$(ls -A "/data/$d" 2>/dev/null)" ] || continue
89  mkdir -p "/data/Strata-data/$d" 2>/dev/null || continue
90  for item in "/data/$d"/* "/data/$d"/.[!.]*; do
91    [ -e "$item" ] || continue
92    name=${item##*/}
93    [ -e "/data/Strata-data/$d/$name" ] && continue
94    if mv "$item" "/data/Strata-data/$d/$name" 2>/dev/null; then legacy_moved="$legacy_moved $d/$name"
95    else warn "Could not move $item into /data/Strata-data/$d (the model is downloaded again unless you set MODEL_PATH=/data/$d/...)."; fi
96  done
97  rmdir "/data/$d" 2>/dev/null || true
98done
99[ -n "$legacy_moved" ] && say "Found model files from the older image in the volume and moved them into /data/Strata-data (no copy, nothing is downloaded again):$legacy_moved"
100
101# ---- run settings made by an image for another card or another engine version name that image's engine folder
102# (/opt/strata/components/engine/<package>/...): in this image that folder is not there, so the server would stop at the start. Drop
103# them; the next step writes them again from the model files, which are kept.
104for c in /data/install/strata-*.json; do
105  [ -f "$c" ] || continue
106  gone=$("$PYBIN" -c '
107import json, os, sys
108def walk(v):
109    if isinstance(v, str):
110        yield v
111    elif isinstance(v, dict):
112        for x in v.values():
113            yield from walk(x)
114    elif isinstance(v, list):
115        for x in v:
116            yield from walk(x)
117try:
118    cfg = json.load(open(sys.argv[1], encoding="utf-8-sig"))
119except (OSError, ValueError):
120    sys.exit(0)
121for s in walk(cfg):
122    if s.startswith("/opt/strata/components/") and not os.path.exists(s):
123        print(s)
124        break
125' "$c" 2>/dev/null)
126  if [ -n "$gone" ]; then
127    say "The saved run settings $(basename "$c") name $gone, which this image does not have (made by an image for another card or engine version): making them again. The model files are kept."
128    rm -f "$c"
129  fi
130done
131
132# ---- is there an engine for this card?
133phase checking
134engine_json=$("$STRATA" components engine --output json 2>/dev/null || true)
135if ! printf '%s' "$engine_json" | grep -q '"usable": *true'; then
136  echo "[X] The engine in this image does not match this computer's graphics card, or the card is not visible to the container." >&2
137  "$STRATA" components engine 2>&1 | sed 's/^/    /' >&2 || true
138  cat >&2 <<'MSG'
139    Check, in this order:
140      NVIDIA  docker run --gpus all ... (needs nvidia-container-toolkit on the host; driver 580+ for the cuda13 image, 575+ for cuda12)
141      AMD     docker run --device /dev/kfd --device /dev/dri --group-add video --group-add render ...
142      Intel   docker run --device /dev/dri ... (add --group-add for the host's render group)
143    Then pick the image for your card: docs/DOCKER.md.
144MSG
145  exit 3
146fi
147
148# the card is found through sysfs even when no device file was passed in: say so now instead of failing when the engine starts
149# (before the model is prepared; /dev/dxg is the GPU of Docker Desktop on WSL2)
150backend=$(printf '%s' "$engine_json" | sed -n 's/.*"backend": *"\([a-z0-9]*\)".*/\1/p' | head -1)
151dev="${STRATA_DEV_DIR:-/dev}"
152case "$backend" in
153  cuda) ls "$dev"/nvidia[0-9]* >/dev/null 2>&1 || [ -e "$dev/dxg" ] || { echo "[X] This computer has an NVIDIA card, but the container cannot use it, so nothing would run (and the model would be prepared for nothing). Start the container with: --gpus all (needs the NVIDIA Container Toolkit on the host; docs/DOCKER.md, Troubleshooting)." >&2; exit 3; } ;;
154  hip)  [ -e "$dev/kfd" ] || { echo "[X] This is an AMD card, but /dev/kfd is not in the container. Add: --device /dev/kfd --device /dev/dri --group-add video --group-add <render group number> (docs/DOCKER.md)" >&2; exit 3; } ;;
155  sycl) ls "$dev"/dri/renderD* >/dev/null 2>&1 || { echo "[X] This is an Intel card, but /dev/dri is not in the container. Add: --device /dev/dri --group-add <render group number> (docs/DOCKER.md)" >&2; exit 3; } ;;
156esac
157
158# ---- the API key
159key="${API_KEY:-}"
160if [ -z "$key" ] && [ -n "${API_KEY_FILE:-}" ]; then
161  [ -r "$API_KEY_FILE" ] || die "API_KEY_FILE=$API_KEY_FILE cannot be read."
162  key=$(tr -d '\r\n' < "$API_KEY_FILE")
163fi
164
165# ---- settings -> `strata launch` flags
166set -- launch --no-tui --access lan --port "$PORT" --data-dir /data/Strata-data
167have=""
168
169preset_exists=""
170if "$STRATA" launch --list-presets --output json 2>/dev/null | grep -q "\"name\": *\"$PRESET\""; then preset_exists=1; fi
171
172model_path="${MODEL_PATH:-${GGUF_DIR:-}}"
173if [ -n "$model_path" ]; then
174  # a folder that is not mounted (or a typo) must not end as "missing /xxx.gguf" after a minute of setup, and must never turn into a download
175  if [ ! -e "$model_path" ]; then
176    die "MODEL_PATH=$model_path is not in the container, so no model file can be found there. Mount your folder at that place, for example: -v /srv/gguf/IQ3_XXS:$model_path:ro (docs/DOCKER.md, \"Files you already have\"). Nothing was downloaded." 2
177  elif [ -d "$model_path" ] && ! ls "$model_path"/*.gguf >/dev/null 2>&1; then
178    sub=$(find "$model_path" -maxdepth 2 -name '*.gguf' 2>/dev/null | head -1)
179    if [ -n "$sub" ]; then
180      die "MODEL_PATH=$model_path has no .gguf files directly in it, but there are some in ${sub%/*}. Set MODEL_PATH=${sub%/*} (the folder that holds the shards of one model). Nothing was downloaded." 2
181    fi
182    die "MODEL_PATH=$model_path holds no .gguf files. Mount the folder with the model's shards (the -0000N-of-0000M.gguf files). Nothing was downloaded." 2
183  fi
184fi
185legacy_models_guard "$model_path" "${STRATA_LEGACY_MODELS:-/data/models}"
186[ -n "${MODEL:-}" ]       && { set -- "$@" --model "$MODEL"; have=1; }
187[ -n "${FAMILY:-}" ]      && { set -- "$@" --family "$FAMILY"; have=1; }
188[ -n "$model_path" ]      && { set -- "$@" --model-path "$model_path"; have=1; }
189[ -n "${CONTEXT:-}" ]     && { set -- "$@" --context "$CONTEXT"; have=1; }
190[ -n "${PARALLEL:-}" ] && [ "${PARALLEL}" != "auto" ] && { set -- "$@" --parallel "$PARALLEL"; have=1; }
191[ -n "${KV:-}" ]          && { set -- "$@" --kv "$KV"; have=1; }
192if [ -n "${VISION:-}" ]; then
193  case "$(printf '%s' "$VISION" | tr 'A-Z' 'a-z')" in
194    off|no|false|0) v=off ;; on|yes|true|1) v=on ;; gpu) v=gpu ;; cpu) v=cpu ;;
195    *) die "VISION=$VISION is not one of off, on, gpu, cpu." 2 ;;
196  esac
197  set -- "$@" --vision "$v"; have=1
198fi
199gpus="${GPUS:-${GPU:-}}"
200case "$gpus" in ""|all|ALL) ;; *)
201  set -- "$@" --gpu "$gpus"; have=1
202  # `launch --gpu` is applied when a model is first set up; a model that is already set up keeps its card. So that GPU / GPUS take effect on
203  # a volume that already has the model, run settings that name another card are dropped: setup writes them again from the files that are there.
204  want=$(printf '%s' "$gpus" | tr -d ' ')
205  for c in /data/install/strata-*.json; do
206    [ -f "$c" ] || continue
207    cur=$("$PYBIN" -c 'import json, sys; g = json.load(open(sys.argv[1])).get("gpu"); print(",".join(map(str, g)) if isinstance(g, list) else ("" if g is None else g))' "$c" 2>/dev/null)
208    if [ "$cur" != "$want" ]; then
209      say "The saved run settings use graphics card '${cur:-default}', GPU/GPUS asks for '$want': making them again (model files are kept)."
210      rm -f "$c"
211    fi
212  done ;;
213esac
214# GPU_ROLES=1=main,0=helper: a role for each card (main, helper or off; cards you do not name are off). `launch --gpu-roles` writes them into the
215# run settings at every start, so nothing saved has to be dropped.
216roles=$(printf '%s' "${GPU_ROLES:-}" | tr -d ' ')
217if [ -n "$roles" ]; then
218  case "$gpus" in ""|all|ALL) ;; *) die "Set GPU_ROLES or GPU / GPUS, not both." 2 ;; esac
219  set -- "$@" --gpu-roles "$roles"; have=1
220fi
221[ -n "${STRATA_SET:-}" ] && { for kv in $STRATA_SET; do set -- "$@" --set "$kv"; done; have=1; }
222[ -n "$key" ] && { set -- "$@" --api-key-env STRATA_LAUNCH_KEY; }
223
224# tune once: ask only when this preset has not been tuned yet (a restart must not tune again for 20 minutes)
225tune_mode=$(printf '%s' "${TUNE:-}" | tr 'A-Z' 'a-z')
226if [ -n "$tune_mode" ] && [ "$tune_mode" != "skip" ]; then
227  tuned=""
228  if [ -n "$preset_exists" ] && "$STRATA" launch --list-presets 2>/dev/null | grep -E "^$PRESET[[:space:]]" | grep -qv "not tuned"; then tuned=1; fi
229  if [ -n "$tuned" ] && [ "${RETUNE:-0}" != "1" ]; then
230    say "This preset is already tuned; keeping the tuned settings (set RETUNE=1 to tune again)."
231  else
232    set -- "$@" --tune "$tune_mode"; have=1
233    [ "${RETUNE:-0}" = "1" ] && set -- "$@" --retune     # without it the launcher sees a tuned preset and measures nothing (#4779)
234    say "Tuning is on (TUNE=$tune_mode): the first start takes longer (up to about $([ "$tune_mode" = quick ] && echo 20 || echo 120) minutes), once."
235  fi
236fi
237[ "${TUNE_ALLOW_SMALL:-0}" = "1" ] && set -- "$@" --tune-allow-small
238
239if [ -n "$preset_exists" ]; then
240  set -- "$@" --preset "$PRESET"
241  [ -n "$have" ] && set -- "$@" --save-preset "$PRESET"
242elif [ -n "$have" ]; then
243  set -- "$@" --save-preset "$PRESET"
244else
245  warn "No MODEL was set, so Strata picks the model it recommends for this card. Set MODEL (for example MODEL=IQ3_XXS) to choose."
246  set -- "$@" --save-preset "$PRESET"
247fi
248
249# ---- start; `docker stop` during the download or the load ends it cleanly, after serving it drains and stops the model
250stopping=""
251launch_pid=""
252on_term() {
253  stopping=1
254  phase stopping
255  say "Stop requested: shutting down."
256  if [ -n "$launch_pid" ] && kill -0 "$launch_pid" 2>/dev/null; then
257    kill -INT "$launch_pid" 2>/dev/null     # the launch is still downloading or loading: it stops what it started
258    i=0; while kill -0 "$launch_pid" 2>/dev/null && [ "$i" -lt 30 ]; do sleep 1; i=$((i+1)); done
259    kill -TERM "$launch_pid" 2>/dev/null || true
260  fi
261  "$STRATA" launch --stop --preset "$PRESET" || true
262  exit 0
263}
264trap on_term TERM INT
265
266# A command started with & by a non-interactive sh ignores SIGINT, so `kill -INT` would do nothing. The launch must see it (it is how it
267# stops a download or a load cleanly), so it is started through a one-line Python that puts SIGINT back before it runs the Terminal.
268RESET_INT='import os, signal, sys; signal.signal(signal.SIGINT, signal.SIG_DFL); os.execv(sys.argv[1], sys.argv[1:])'
269
270phase preparing
271if [ -n "${MODEL:-}" ]; then what="$MODEL${model_path:+ from $model_path}"
272elif [ -n "$model_path" ]; then what="the model files in $model_path"
273else what="the recommended model"; fi
274say "Starting Strata: $what (preset '$PRESET')."
275if [ -n "$key" ]; then
276  STRATA_LAUNCH_KEY="$key" "$PYBIN" -c "$RESET_INT" "$STRATA" "$@" &
277else
278  "$PYBIN" -c "$RESET_INT" "$STRATA" "$@" &
279fi
280launch_pid=$!
281wait "$launch_pid"
282rc=$?
283launch_pid=""
284[ -n "$stopping" ] && exit 0
285if [ "$rc" -ne 0 ]; then
286  phase failed
287  die "strata launch stopped with code $rc (the lines above say why). The container ends. Fix that and start it again: finished steps are not repeated, and an interrupted download continues where it stopped." "$rc"
288fi
289
290# keep the key where `docker exec ... strata monitor` and the health check can read it (private file on the volume)
291( umask 077; "$STRATA" launch --show-key --preset "$PRESET" > "$KEY_FILE" 2>/dev/null ) || true
292[ -s "$KEY_FILE" ] || rm -f "$KEY_FILE"
293if [ -z "$key" ]; then
294  warn "No API_KEY was set, so Strata made one (the server listens on all addresses in the container and will not run without a key)."
295  warn "Show it with: docker exec <container> strata launch --show-key --preset $PRESET   Set your own with -e API_KEY=..."
296fi
297phase serving
298say "Serving on port $PORT. Watch it: docker exec -it <container> strata monitor    Stop: docker stop <container>"
299
300# ---- stay up; leave (so a restart policy can act) if the server is gone
301bad=0
302while [ -z "$stopping" ]; do
303  sleep 10 &
304  wait $!
305  [ -n "$stopping" ] && break
306  if "$STRATA" launch --status --output json 2>/dev/null | grep -q '"state": *"ready"'; then bad=0; else bad=$((bad+1)); fi
307  if [ "$bad" -ge 3 ]; then
308    phase failed
309    die "The server is no longer running. Last lines of its log are in /data/install and 'docker logs'." 1
310  fi
311done
312exit 0