From abbec1a7f3ce3cfbeebde0bdc69a132de917c597 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 13:16:02 +0100 Subject: [PATCH] feat: track device health and halt the server when nothing can run The engine keeps, for the whole process, a record of how each device, the RAM and the disk are doing (src/core/device_health.*). A component under strain offers less of its capacity, one step per level (85%, 70%, 55%); an excluded one offers nothing and is never computed on. A level rises by one for a compute that fails, a backend that does not start, the memory guard that cannot reach its threshold or a read of the weights that fails (events less than 10 s apart count once), and comes down one step after each quiet period of 300 s. Outside watchers report signals with a source and a duration; a signal reaches the other listings of the same card, a failure of one backend does not. - C API, additions only: sd_device_health_t, sd_get_device_health(), sd_report_device_pressure() and sd_resume_device_health(). - The layer split gives each device its share of capacity, the run plan and the multi-GPU planner their share of memory, and an excluded device is never the default one. When the record changes, the next generation releases the cached models and places them again. - The engine refuses to compute on an excluded device (a backend error at the start of the segment), computes on the CPU with 25% fewer threads per level and does not fall back to an excluded CPU. The RAM is never cut below the share of level 3; with the disk excluded, weights that would be read from it during the run are refused as out of memory. - sd-server: the context keeper skips excluded devices and does not climb back to them. A guardian (examples/server/guardian.*) stops all work when a component is reported critical or every compute device is excluded: the generation in progress ends with the code halted, new work is refused with 503 halted and Retry-After, queued jobs wait, and /sdcpp/v1/health reports the guardian and every component. It resumes when the cause ends, or with POST /sdcpp/v1/guardian/resume; while it is halted the keeper neither loads the model again nor steps down. --guardian on|off, on by default. - POST /sdcpp/v1/devices/{device}/pressure takes the reports of outside watchers, and termico.py osserva --segnala sends the temperature band of an NVIDIA GPU as the level of its device. The values are provisional. This is a layer of the software, not a safety system, and the docs say so: examples/server/api.md (Device health and the guardian), the server README, the README of scripts/diagnostica_termica, docs/agenti_indipendenti.md (section 9) and the fork history. test: device_health_test and server_guardian_test are new, and the recovery, layer split, planner and termico tests cover the new rules. server_guardian_e2e.py runs the guardian against a real sd-server: 59 checks, three runs in a row, with a synthetic SD 1.5 model. Every program of test/ passes, the server tests under ThreadSanitizer too, and broken versions of the registry, guardian, keeper and termico code make them fail. Not tried: real GPUs, a layer split between two devices, Windows. Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC --- .gitignore | 3 + docs/agenti_indipendenti.md | 25 ++ docs/integrazione_progetti.md | 86 +++- examples/server/CMakeLists.txt | 1 + examples/server/README.md | 20 + examples/server/api.md | 134 +++++- examples/server/async_jobs.cpp | 55 ++- examples/server/async_jobs.h | 6 + examples/server/guardian.cpp | 269 ++++++++++++ examples/server/guardian.h | 110 +++++ examples/server/main.cpp | 13 + examples/server/recovery.cpp | 96 ++++- examples/server/recovery.h | 17 + examples/server/routes_dgl.cpp | 4 + examples/server/routes_models.cpp | 12 + examples/server/routes_sdcpp.cpp | 84 +++- examples/server/runtime.cpp | 14 + examples/server/runtime.h | 3 + include/stable-diffusion.h | 34 ++ scripts/diagnostica_termica/README.md | 49 ++- scripts/diagnostica_termica/termico.py | 200 ++++++++- src/api/generation_program.cpp | 6 +- src/core/backend_fit.cpp | 23 +- src/core/device_health.cpp | 565 +++++++++++++++++++++++++ src/core/device_health.h | 165 ++++++++ src/core/execution_engine.cpp | 31 ++ src/core/ggml_extend_backend.cpp | 18 +- src/core/layer_split_partition.cpp | 30 +- src/core/layer_split_partition.h | 7 + src/dgl/context.cpp | 16 + src/dgl/context.h | 4 + src/dgl/executor.cpp | 1 + src/dgl/models/model_runtime.cpp | 6 + src/dgl/run_plan.cpp | 9 +- src/model_loader.cpp | 3 + src/model_manager.cpp | 5 + test/README.md | 7 +- test/backend_fit_plan_test.cpp | 32 ++ test/device_health_test.cpp | 467 ++++++++++++++++++++ test/layer_split_fill_test.cpp | 29 ++ test/server_guardian_e2e.py | 477 +++++++++++++++++++++ test/server_guardian_test.cpp | 342 +++++++++++++++ test/server_recovery_test.cpp | 179 ++++++++ test/termico_test.py | 188 +++++++- 44 files changed, 3804 insertions(+), 41 deletions(-) create mode 100644 examples/server/guardian.cpp create mode 100644 examples/server/guardian.h create mode 100644 src/core/device_health.cpp create mode 100644 src/core/device_health.h create mode 100644 test/device_health_test.cpp create mode 100644 test/server_guardian_e2e.py create mode 100644 test/server_guardian_test.cpp diff --git a/.gitignore b/.gitignore index 733a1228..128e8ce9 100644 --- a/.gitignore +++ b/.gitignore @@ -13,9 +13,12 @@ test/* !test/backend_fit_plan_test.cpp !test/memory_guard_engine_test.cpp !test/layer_split_fill_test.cpp +!test/device_health_test.cpp !test/package_windows_cuda_vulkan_test.sh !test/server_recovery_test.cpp !test/server_cancel_e2e.py +!test/server_guardian_test.cpp +!test/server_guardian_e2e.py !test/termico_test.py !test/agenti_guardiano_test.py !test/fuzz_model_loader.py diff --git a/docs/agenti_indipendenti.md b/docs/agenti_indipendenti.md index c1ef0eaf..158e0b25 100644 --- a/docs/agenti_indipendenti.md +++ b/docs/agenti_indipendenti.md @@ -457,6 +457,31 @@ Con lo strumento di riferimento di [integrazione_progetti.md](./integrazione_pro sostituisce l'invio della richiesta e `segui_lavoro` il ciclo di attesa; il resto (preset, dimensioni dai `limits`, percorso del file) non cambia. +**Insieme alla salute dei device del motore.** Il motore tiene da sé un registro della salute di ogni device e toglie +lavoro, un gradino alla volta, a quello sotto sforzo ([Device health and the guardian](../examples/server/api.md#device-health-and-the-guardian)). +Lo stesso osservatore glielo può dire: con `--segnala` manda a ogni campione la fascia della GPU come livello del suo +device ([sezione 7.1 del README di termico](../scripts/diagnostica_termica/README.md#71-segnalare-la-fascia-al-motore---segnala)), +e il guardiano continua a decidere dei propri lavori come sopra. + +```shell +python scripts/diagnostica_termica/termico.py osserva --file-stato stato.json --motore http://127.0.0.1:1234 --segnala +``` + +Le due cose fanno lavori diversi. Il motore sposta il lavoro di **tutti** fra i device, in modo uguale per tutti; il +guardiano decide se **il suo** lavoro può partire e lo ferma, senza toccare quello degli altri programmi (sezione +[6](#6-giustizia-nessun-torto-né-alle-persone-né-agli-altri-programmi)). Per questo l'esempio non manda mai il +segnale `critical`: quel segnale ferma il server intero, con i lavori di tutti, finché scade o finché qualcuno dice di +aver controllato la macchina. È l'interruttore di chi gestisce la macchina, non di un agente: + +```shell +curl -X POST http://127.0.0.1:1234/sdcpp/v1/devices/CUDA0/pressure -H "Content-Type: application/json" \ + -d '{"level": "critical", "reason": "controllo del raffreddamento", "duration_seconds": 600, "source": "operatore"}' +curl -X POST http://127.0.0.1:1234/sdcpp/v1/guardian/resume +``` + +Mentre il server è fermo, `avvia_lavoro` riceve `503` con `Retry-After` e aspetta, come per il `429`; un lavoro che +era in corso finisce `failed` con il codice `halted`, e `segui_lavoro` lo restituisce così com'è. + ## 10. Come collaudare un agente Si prova sul proprio PC senza scaldare niente: `termico.py` non cambia nulla nella GPU, e se si avvia con soglie più diff --git a/docs/integrazione_progetti.md b/docs/integrazione_progetti.md index 0aa6bee8..fca3dce0 100644 --- a/docs/integrazione_progetti.md +++ b/docs/integrazione_progetti.md @@ -1905,6 +1905,87 @@ sincronizzazioni future. reale, più GPU (la scelta dei device di `planned_backend_spec()` non è coperta da nessun test: servono almeno due GPU; il pianificatore in sé ha i suoi test con GPU simulate), Windows. +26. **Salute dei device, watchdog e watchGuardian** — il motore tiene un + registro della salute di ogni componente e sposta il lavoro prima che un + componente ceda; il server si ferma del tutto solo quando la macchina non + regge più. Il piano, fase per fase, è nel documento «Piano del watchdog e + del watchGuardian». + + Fase 1, il registro: `src/core/device_health.{h,cpp}` (`sd::DeviceHealth`, + uno per processo). Componenti: i device di ggml, `RAM` e `disk`; livelli 0, + da 1 a 3 sotto sforzo (85%, 70%, 55% della capacità), 4 escluso. Eventi del + motore, un gradino ciascuno e una volta sola se a meno di 10 secondi l'uno + dall'altro: un calcolo fallito (`execution_engine.cpp`), un backend che non + parte (`ggml_extend_backend.cpp`), il memory guard che non scende sotto la + soglia (`model_manager.cpp`), una lettura dei pesi fallita + (`model_loader.cpp`). Segnali esterni con fonte e durata (da 1 secondo a un + giorno, al più 8 fonti per componente; il critico esclude e chiede la + fermata); la stessa scheda vista da due backend riceve i segnali esterni + ma non i guasti dell'altro backend. Un livello scende di un gradino dopo + ogni periodo tranquillo di 300 secondi. API C, solo aggiunte e in forma + provvisoria: `sd_device_health_t`, `sd_get_device_health()`, + `sd_report_device_pressure()`, `sd_resume_device_health()`. + + Fase 2, lo split a gradini: `layer_split_apply_shares()` + (`src/core/layer_split_partition.*`); quando il registro cambia, la + generazione successiva rilascia i modelli in cache e rifà il piano + (`Context::follow_device_health()` in `dgl::run`). + + Fase 3: i budget del piano di esecuzione e del pianificatore multi-GPU + valgono la quota del device (`backend_fit.cpp`, `run_plan.cpp`; la chiave + della cache dei piani comprende la revisione del registro in + `generation_program.cpp`); un device escluso non è mai il predefinito e il + motore non calcola su di lui (errore `backend` all'inizio del segmento, + con una riga di log sola); thread della CPU -25% per livello; il ripiego + sulla CPU è rifiutato se la CPU è esclusa (`model_runtime.cpp`); la RAM non + scende sotto la quota del livello 3; con il disco escluso i pesi da leggere + durante il calcolo sono rifiutati (`out_of_memory`). + + Fase 4, il guardiano del server: `examples/server/guardian.{h,cpp}`. Si + ferma con un componente critico o senza più device di calcolo. Un + sorvegliante (un thread: ogni secondo e subito dopo una segnalazione) + ferma la generazione in corso: un job finisce `failed` con il codice + `halted`, una richiesta sincrona riceve `503` `halted`. Le richieste nuove + (img_gen, vid_gen, A1111, OpenAI, script DGL, caricamento del modello) + ricevono `503` `halted` con `Retry-After`; i job in coda aspettano; + `/sdcpp/v1/health` mostra `guardian`, `devices` e lo stato `halted`. Riparte + da solo quando la causa finisce, o con `POST /sdcpp/v1/guardian/resume`. + `--guardian on|off`, acceso per default. Il custode salta i device esclusi, + non risale verso di loro e, con il server fermo, non ricarica il modello né + scende di profilo (hook `halted`). + + Fase 5, i segnali dall'esterno: `POST /sdcpp/v1/devices/{device}/pressure`; + `termico.py osserva --segnala [DEVICE]` manda la fascia della GPU come + livello (attenzione 1, con throttling termico 2, critica 3, critica con + throttling hardware esclusa; in fascia normale il throttling termico vale + 1). Nella guida sugli agenti (sezione 9) il guardiano d'esempio si affianca + a `--segnala` e non manda mai il segnale critico, che ferma il lavoro di + tutti (sezione 6). Documentato in `examples/server/api.md` («Device health + and the guardian» e i due endpoint), `examples/server/README.md`, + `scripts/diagnostica_termica/README.md` (7.1) e + [agenti_indipendenti.md](./agenti_indipendenti.md) (9). I valori sono + provvisori. + + Anche: `test/agenti_guardiano_test.py` con il server vero falliva dalla + voce 25, perché chiedeva 500 passi e il server ne accetta al massimo 100: + ora ne chiede 100. + + Test, su una build per CPU: gli undici programmi di `test/` passano, con i + nuovi `device_health_test` e `server_guardian_test`; + `server_recovery_test` e `server_guardian_test` anche con + ThreadSanitizer, senza avvisi. Versioni rotte del codice che i test devono + scoprire: registro 10, guardiano 24, custode 9, `termico.py --segnala` 10, + tutte scoperte; delle 3 del collegamento nel server vero, 2 le scopre + `test/server_guardian_e2e.py` e la terza (il custode che non sa della + fermata) solo `server_recovery_test`, perché sul server vero lo stop del + sorvegliante arriva sempre prima. Con il modello SD 1.5 sintetico: + `test/server_guardian_e2e.py` passa i suoi 59 controlli tre volte di fila + contro un vero `sd-server`; `server_cancel_e2e.py` 35; `termico_test.py` + 153; `agenti_guardiano_test.py` 66 senza server e 91 con il server vero; + `security_smoke.sh`; `dgl-check-builtins`; una prova d'integrazione del + registro nel motore (12 controlli, non nel repository). **Non provato**: + GPU vere, uno split a livelli fra due device, `termico.py --segnala` con una + NVIDIA reale, Windows. Passaggi previsti e non ancora svolti: collaudo del workflow di release sui runner GitHub, prova di `--multi-gpu` su una macchina con due GPU, generazione @@ -1915,7 +1996,10 @@ stessa GPU (scenari in [convivenza_applicazioni.md](./convivenza_applicazioni.md sezione 5), prova di `termico.py` su una GPU NVIDIA reale e su Windows e del guardiano della guida sugli agenti con una GPU vera sotto carico, test su CUDA/Vulkan e su Windows (il ramo Windows della -memoria di sistema è stato solo controllato nella sintassi), taratura delle +memoria di sistema è stato solo controllato nella sintassi), prova della salute +dei device (voce 26) su GPU vere, con uno split a livelli fra la scheda +discreta e la GPU integrata e `termico.py --segnala` su una NVIDIA reale, +taratura dei valori della salute dei device, taratura delle soglie di `--profile auto` e dei preset della sezione 3.6, e il livello di astrazione `ImageRuntime` nell'applicazione ospite (fuori da questo repository). diff --git a/examples/server/CMakeLists.txt b/examples/server/CMakeLists.txt index ec5b92b8..60d2fbd9 100644 --- a/examples/server/CMakeLists.txt +++ b/examples/server/CMakeLists.txt @@ -71,6 +71,7 @@ add_executable(${TARGET} main.cpp runtime.cpp recovery.cpp + guardian.cpp model_catalog.cpp routes_models.cpp async_jobs.cpp diff --git a/examples/server/README.md b/examples/server/README.md index fb5a31ed..2a093605 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -510,6 +510,26 @@ If the model does not fit at startup, the server starts on the first profile and the model cannot be loaded at all, or the address cannot be used, `sd-server` exits with a non-zero code and says why. See [Failures and recovery](api.md#failures-and-recovery) for the answers a client gets. +## When a device is under strain + +The engine keeps a record of how each device, the RAM and the disk are doing, and gives a component under strain less +work, one step at a time: 85%, 70%, 55% of its capacity; an excluded device is never computed on, and its work goes to the +others. Compute failures raise the level by themselves; outside watchers report with +`POST /sdcpp/v1/devices/{device}/pressure`, for example `termico.py osserva --segnala` of +[`scripts/diagnostica_termica/`](../../scripts/diagnostica_termica/README.md), which sends the temperature band of an +NVIDIA GPU. + +When a component is reported critical, or every compute device is excluded, the guardian stops all work: the +generation in progress ends with the code `halted`, new requests get `503` with `Retry-After`, and the queued jobs wait. +The server resumes by itself when the cause ends, or when an operator calls `POST /sdcpp/v1/guardian/resume`. See +[Device health and the guardian](api.md#device-health-and-the-guardian). + +* `--guardian on|off` (default `on`): with `off` the server never stops all work by itself; device health still moves + the work between devices + +This is a layer of the software, not a safety system: a stop that protects people or equipment belongs to independent, +certified hardware. + ## Frontend development ### Build with frontend diff --git a/examples/server/api.md b/examples/server/api.md index 6eb292a7..b7fc87b4 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -63,6 +63,8 @@ Current endpoints include: - `GET /sdcpp/v1/capabilities` - `GET /sdcpp/v1/health` - `GET /sdcpp/v1/resources` +- `POST /sdcpp/v1/devices/{device}/pressure` +- `POST /sdcpp/v1/guardian/resume` - `POST /sdcpp/v1/img_gen` - `GET /sdcpp/v1/jobs/{id}` - `POST /sdcpp/v1/jobs/{id}/cancel` @@ -78,6 +80,7 @@ A generation that cannot be served is answered the same way by all three API fam | `503 Service Unavailable` | `out_of_memory` | The machine ran out of memory, even after the server tried the lighter configurations described below. Retry later, or send a smaller request. | | `503 Service Unavailable` | `unavailable` | The server has no usable model at this moment, for example because loading it again after a failure did not succeed yet. `cause` holds the reason. | | `503 Service Unavailable` | `busy` | The model was in use. | +| `503 Service Unavailable` | `halted` | The guardian has stopped all work: a component is reported critical, or device health excludes every compute device (see [Device health and the guardian](#device-health-and-the-guardian)). A generation that was running when the server halted ends the same way. | | `400 Bad Request` | `invalid_argument` | The request cannot be generated as it is (for example a size the model cannot handle). Retrying it unchanged will not help. | | `500 Internal Server Error` | `model_file`, `backend`, `generation_failed` | A model file could not be read, a compute device failed, or the generation failed without a more specific reason. | @@ -179,6 +182,51 @@ wait doubles. From the CPU, after a device failure, the climb goes straight back device failed and offers every device again, so the best one that works is found even if the preferred one does not; when the CPU was reached through memory failures, the climb is one profile up, as usual. +### Device health and the guardian + +The engine keeps, for the whole process, a record of how each component is doing: every device the engine lists +(`CUDA0`, `Vulkan1`, `CPU`, ...), the `RAM` and the `disk`. Each one is healthy (level 0), under strain (levels 1 to 3) +or excluded (level 4). + +| Level | What the component offers | +| --- | --- | +| 0 | all of its capacity | +| 1, 2, 3 | 85%, 70%, 55%: the planner gives it that share of its memory, the layer split that share of its capacity, and the CPU computes with 25% fewer threads per level (at least one) | +| 4, excluded | nothing: the engine never computes on it, the planner gives it no module, the server does not load the model on it nor climb back to it, and an excluded CPU takes no work handed over from the GPUs. The RAM is never cut below the share of level 3; an excluded disk is not read during a generation, and a model that would need it fails with `out_of_memory` | + +What raises a level, one step at a time: a compute that fails on a device (not for lack of memory: the profiles deal +with that), a backend that does not start, the memory guard that cannot bring the memory below its threshold (it +counts for the device, or for the `RAM` when it guards the CPU), a read of the weights that fails (the `disk`). Events of +one device less than 10 seconds apart count once. Outside watchers report too, with +[`POST /sdcpp/v1/devices/{device}/pressure`](#post-sdcppv1devicesdevicepressure): such a signal holds its level for the time it +lasts, and reaches the other listings of the same card (`CUDA0` and `Vulkan0` of one GPU), which a failure of one backend +does not. A level comes down one step after each quiet period of 300 seconds, counted from the last event and from the +end of the signals that held it; withdrawing a signal does not make the component healthy at once. When the record +changes, the next generation places the model again with the new shares, which costs loading the weights again. The +values are provisional. + +The guardian stops all the work of the server when the machine cannot take it: a component is reported `critical`, or +every compute device is excluded (the GPUs and the CPU; the `RAM` and the `disk` do not count). While it is halted: + +- the generation in progress stops: a job ends `failed` with the code `halted`, a synchronous request is answered `503` + with the code `halted`; a generation that finishes before the stop reaches it keeps its result; +- new generations, DGL scripts and model loads are refused with `503`, the code `halted` and a `Retry-After` header: the + time left to the critical signal, or until the first excluded device comes back, and never less than 10 seconds; +- the queued jobs wait, and run after the resume; +- the server does not load the model again, step down or climb back: a failure that comes with the halt is a stop; +- [`GET /sdcpp/v1/health`](#get-sdcppv1health) answers `503` with `status: "halted"`, the reason and every component; polling + jobs, cancelling them, unloading the model and the reports still work. + +The server resumes by itself when the cause ends (the critical signal runs out or is withdrawn, an excluded device comes +back after its quiet periods), or when an operator says the machine was checked with +[`POST /sdcpp/v1/guardian/resume`](#post-sdcppv1guardianresume). `--guardian off` disables the guardian: device health still +moves the work between devices, but the server never stops all work by itself. + +This is a layer of the software, inside the process it watches: a driver that hangs or a crash stop it with everything +else, and lowering the work does not cool a device by itself. A stop that protects people or equipment belongs to +independent, certified hardware, never to this server. A signal that is not repeated runs out, and the server resumes +then: a watcher that stops reporting does not keep the server halted. + ## Model management All three API families share the server's execution context and its component @@ -1203,13 +1251,44 @@ Example response: "pending": 0, "waiting": 0, "max": 64 - } + }, + "guardian": { + "enabled": true, + "halted": false, + "reason": "", + "since": 0, + "retry_after_seconds": 0 + }, + "devices": [ + { + "name": "CUDA0", + "level": 2, + "strain_levels": 3, + "share_percent": 70, + "excluded": false, + "critical": false, + "reason": "termico: GPU a 86 C, fascia attenzione, throttling termico", + "held_ms": 4200, + "next_step_ms": 0 + }, + { + "name": "CPU", + "level": 0, + "strain_levels": 3, + "share_percent": 100, + "excluded": false, + "critical": false, + "reason": "", + "held_ms": 0, + "next_step_ms": 0 + } + ] } ``` | Field | Type | Notes | | --- | --- | --- | -| `status` | `string` | `ok`, `degraded` (running on a lighter profile than the one it was started with, or on another device than the first one), `recovering` (the model is being loaded), `unavailable` (no usable model at the moment), or `no_model` (no model is loaded: the server was started without one, or it was unloaded) | +| `status` | `string` | `ok`, `degraded` (running on a lighter profile than the one it was started with, or on another device than the first one), `recovering` (the model is being loaded), `unavailable` (no usable model at the moment), `no_model` (no model is loaded: the server was started without one, or it was unloaded), or `halted` (the guardian has stopped all work; `guardian` says why) | | `model_loaded` | `boolean` | | | `profile` | `string \| null` | Profile in use: `max`, `balanced`, `lite`, `lite-disk`, `lite-hybrid` or `lite-cpu`; `null` without a model | | `base_profile` | `string` | Profile the server was started with | @@ -1224,11 +1303,14 @@ Example response: | `uptime_seconds` | `integer` | | | `version` | `string` | | | `queue` | `object` | Jobs of the async API: `pending` (queued or generating), `waiting` (queued) and `max` (limit before `429`) | +| `guardian` | `object` | `enabled` (`false` with `--guardian off`), `halted`, `reason` (empty when it is not halted), `since` (Unix time of the start of the halt; 0 when it is not halted) and `retry_after_seconds` (0 when it is not halted) | +| `devices` | `array` | The components of [device health](#device-health-and-the-guardian): `name`; `level` (0 healthy, 1 to `strain_levels` under strain, `strain_levels + 1` excluded); `strain_levels`; `share_percent`, what it offers of its capacity; `excluded`; `critical`; `reason`, the `source: reason` of the signal, or the event, that set the level (empty when it is healthy); `held_ms`, how long the signals that hold the level still last; `next_step_ms`, until the level comes down one step if nothing else happens | Typical status codes: - `200 OK` -- `503 Service Unavailable` only when `status` is `unavailable`; the body is the same +- `503 Service Unavailable` when `status` is `unavailable` or `halted`; the body is the same, and with `halted` a + `Retry-After` header says when to ask again #### `GET /sdcpp/v1/resources` @@ -1262,6 +1344,52 @@ Example response: | `devices` | `array` | The compute devices, as listed by `--list-devices` | | `devices[].type` | `string` | `cpu`, `gpu`, `igpu`, `accel` or `unknown` | +#### `POST /sdcpp/v1/devices/{device}/pressure` + +An outside watcher (a thermal monitor such as `termico.py osserva --segnala` of +[`scripts/diagnostica_termica/`](../../scripts/diagnostica_termica/README.md), a supervisor, an operator) reports how a +component is doing. `{device}` is a name that [`GET /sdcpp/v1/health`](#get-sdcppv1health) lists under `devices`, in any +case. It needs the API key when one is set, and it answers while the server is halted, so that a watcher can withdraw +its signal. + +Request body: + +```json +{"level": 2, "reason": "GPU at 86 C with thermal throttling", "duration_seconds": 60, "source": "termico"} +``` + +| Field | Type | Notes | +| --- | --- | --- | +| `level` | `integer \| string` | `0` withdraws the signal of this source; `1` to `3` put the component under strain; `4` or `"excluded"` exclude it; `"critical"` excludes it and asks the guardian to stop all work while the signal lasts | +| `reason` | `string` | Optional, one line. The health shows it as `source: reason` | +| `duration_seconds` | `integer` | Optional, 1 to 86400, default 60. The signal ends by itself after this time, so a watcher repeats it while the condition lasts | +| `source` | `string` | Optional, default `http`: 1 to 32 letters, digits, `.`, `_` or `-`. Each source holds one signal per component, and a new one replaces the old one; name it when more than one watcher reports | + +Other fields are refused. The answer is the component and the guardian, as the health shows them; when the report +halts the server, the generation in progress is stopped at once. + +```json +{ + "device": {"name": "CUDA0", "level": 2, "strain_levels": 3, "share_percent": 70, "excluded": false, "critical": false, + "reason": "termico: GPU at 86 C with thermal throttling", "held_ms": 60000, "next_step_ms": 0}, + "guardian": {"enabled": true, "halted": false, "reason": "", "since": 0, "retry_after_seconds": 0} +} +``` + +Typical status codes: + +- `200 OK` +- `400 Bad Request` with the code `invalid_report`: the body is not valid; `error` says why +- `404 Not Found` with the code `unknown_device`: the server has no such component +- `409 Conflict` with the code `report_refused`: the component holds the signals of 8 sources already + +#### `POST /sdcpp/v1/guardian/resume` + +An operator says the machine was checked: the critical signals end, the excluded components come back to the last level +of strain (the signals that exclude are lowered to it), and the server resumes unless something else still holds the +halt; the queued jobs run. It needs the API key when one is set, and answers `200` with `guardian` and `devices` as +[`GET /sdcpp/v1/health`](#get-sdcppv1health) shows them. Without a halt it only lowers what excludes. + #### `POST /sdcpp/v1/img_gen` Submits an async image generation job. diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index cd429099..dd6e4fcf 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -14,6 +14,7 @@ #include "common/log.h" #include "common/media_io.h" #include "common/resource_owners.hpp" +#include "guardian.h" #include "model_catalog.h" class JobCancellationMonitor { @@ -269,6 +270,34 @@ bool cancel_generating_job(ServerRuntime& runtime, } } +void stop_work_for_guardian(ServerRuntime& runtime, const std::string& reason) { + std::shared_ptr running; + { + std::lock_guard lock(runtime.async_job_manager->mutex); + for (const auto& entry : runtime.async_job_manager->jobs) { + if (entry.second->status == AsyncJobStatus::Generating) { + entry.second->halted_reason = reason; + running = entry.second; + break; + } + } + } + if (running != nullptr) { + cancel_generating_job(runtime, running, std::chrono::milliseconds(2000)); + } + // A synchronous request has no job: whatever still runs on the context is stopped, again and again for a + // moment, because the library forgets a stop that arrives before a generation pass begins. + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + bool told = false; + while (runtime.keeper->cancel_running() && std::chrono::steady_clock::now() < deadline) { + if (!told) { + LOG_WARN("guardian: stopping the generation in progress"); + told = true; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } +} + json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJob& job) { json result; result["id"] = job.id; @@ -803,7 +832,16 @@ static void wait_for_job(ServerRuntime& runtime, std::unique_lock& l auto& manager = *runtime.async_job_manager; using Clock = std::chrono::steady_clock; const auto disabled = Clock::time_point::max(); - while (!manager.stop && manager.queue.empty()) { + while (!manager.stop) { + if (!manager.queue.empty()) { + // While the guardian has halted the server the queued jobs wait. Its state is read again every second, + // so the work resumes when the cause ends even without new requests. + if (runtime.guardian == nullptr || !runtime.guardian->evaluate().halted) { + return; + } + manager.cv.wait_for(lock, std::chrono::seconds(1)); + continue; + } const auto deadline = std::min(manager.staging_deadline, manager.residency_deadline); if (deadline == disabled || manager.synchronous_jobs != 0) { manager.cv.wait(lock); @@ -914,7 +952,20 @@ void async_job_worker(ServerRuntime& runtime) { job->completed_at = unix_timestamp_now_ms(); finish_job_progress(*job); - if (job->cancel.requested.load()) { + // The guardian marks the job it stops. A cancellation that no client asked for is the keeper stopping the + // run for the halt before the mark reached the job. A job that finished anyway keeps its result. + const bool halted = !ok && (!job->halted_reason.empty() || + (failure.code == SD_ERROR_CANCELLED && !job->cancel.requested.load())); + if (halted) { + std::string reason = job->halted_reason; + if (reason.empty() && runtime.guardian != nullptr) { + reason = runtime.guardian->evaluate().reason; + } + job->status = AsyncJobStatus::Failed; + job->error_code = "halted"; + job->error_message = "the server stopped all work" + (reason.empty() ? std::string() : ": " + reason); + LOG_WARN("job %s stopped by the guardian", job->id.c_str()); + } else if (job->cancel.requested.load() && job->halted_reason.empty()) { job->status = AsyncJobStatus::Cancelled; job->error_code = "cancelled"; job->error_message = "job cancelled by client"; diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h index 90d4607b..7741bda2 100644 --- a/examples/server/async_jobs.h +++ b/examples/server/async_jobs.h @@ -69,6 +69,8 @@ struct AsyncGenerationJob { // the request to the library (see JobCancellationMonitor), because the library forgets a stop that arrives // before a generation pass begins. CancelToken cancel; + // Set, with the manager's mutex held, when the guardian stopped the job: it ends with the code halted. + std::string halted_reason; mutable std::mutex progress_mutex; AsyncJobProgress progress; mutable std::mutex preview_mutex; @@ -109,6 +111,10 @@ bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job); bool cancel_generating_job(ServerRuntime& runtime, const std::shared_ptr& job, std::chrono::milliseconds wait); +// The guardian has halted the server: the job that is generating stops and ends with the code halted, a synchronous +// request (A1111, OpenAI) is stopped too, and the queued jobs wait for the resume. Waits a few seconds at most. Call +// it without holding manager.mutex. +void stop_work_for_guardian(ServerRuntime& runtime, const std::string& reason); json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJob& job); int64_t dgl_image_frame_count(const sd_tensor_t* tensor); bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message); diff --git a/examples/server/guardian.cpp b/examples/server/guardian.cpp new file mode 100644 index 00000000..ca031d8a --- /dev/null +++ b/examples/server/guardian.cpp @@ -0,0 +1,269 @@ +// httplib.h must come before any header that reaches (common/log.h does): windows.h pulls in winsock.h, +// which clashes with the winsock2.h included by httplib.h. +#include "httplib.h" + +#include "guardian.h" + +#include +#include +#include +#include +#include +#include + +#include "common/log.h" + +static bool is_compute_device(const sd_device_health_t& component) { + std::string name = component.name; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + return name != "ram" && name != "disk"; +} + +std::vector read_device_health() { + std::vector components(sd_get_device_health(nullptr, 0)); + const size_t count = sd_get_device_health(components.data(), components.size()); + components.resize(std::min(count, components.size())); + return components; +} + +nlohmann::json device_health_json(const sd_device_health_t& component) { + return {{"name", component.name}, + {"level", component.level}, + {"strain_levels", component.strain_levels}, + {"share_percent", component.share_percent}, + {"excluded", component.excluded}, + {"critical", component.critical}, + {"reason", component.reason}, + {"held_ms", component.held_ms}, + {"next_step_ms", component.next_step_ms}}; +} + +static std::string json_text(const nlohmann::json& value) { + return value.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace); +} + +Guardian::Guardian(bool enabled, const Hooks& hooks) + : enabled_(enabled), hooks_(hooks) {} + +Guardian::~Guardian() { + stop_watching(); +} + +void Guardian::watch(std::function on_halt, std::chrono::milliseconds period) { + if (!enabled_ || watcher_.joinable()) { + return; + } + watcher_ = std::thread([this, on_halt = std::move(on_halt), period]() { + std::unique_lock lock(watch_mutex_); + while (!watch_stop_) { + lock.unlock(); + // An exception must not end the thread that stops the work, nor the server with it. + try { + bool started = false; + const State state = evaluate(&started); + if (started && on_halt) { + on_halt(state); + } + } catch (const std::exception& error) { + LOG_ERROR("guardian: %s", error.what()); + } + lock.lock(); + watch_wake_.wait_for(lock, period, [this] { return watch_stop_ || watch_check_; }); + watch_check_ = false; + } + }); +} + +void Guardian::stop_watching() { + { + std::lock_guard lock(watch_mutex_); + watch_stop_ = true; + } + watch_wake_.notify_all(); + if (watcher_.joinable()) { + watcher_.join(); + } +} + +void Guardian::check_now() { + { + std::lock_guard lock(watch_mutex_); + watch_check_ = true; + } + watch_wake_.notify_all(); +} + +Guardian::State Guardian::evaluate(bool* started_halt) { + if (started_halt != nullptr) { + *started_halt = false; + } + std::vector components = hooks_.read_health ? hooks_.read_health() : read_device_health(); + + std::string reason; + int64_t wait_ms = 0; + for (const auto& component : components) { + if (component.critical) { + reason += (reason.empty() ? "" : "; ") + std::string(component.name) + " is critical" + + (component.reason[0] != '\0' ? ": " + std::string(component.reason) : std::string()); + wait_ms = std::max(wait_ms, component.held_ms); + } + } + if (reason.empty()) { + bool any_compute = false; + bool all_excluded = true; + int64_t soonest = std::numeric_limits::max(); + for (const auto& component : components) { + if (!is_compute_device(component)) { + continue; + } + any_compute = true; + if (!component.excluded) { + all_excluded = false; + break; + } + soonest = std::min(soonest, component.held_ms > 0 ? component.held_ms : component.next_step_ms); + } + if (any_compute && all_excluded) { + reason = "no compute device left: device health excludes every GPU and the CPU"; + wait_ms = soonest == std::numeric_limits::max() ? 0 : soonest; + } + } + + std::lock_guard lock(mutex_); + components_ = std::move(components); + const bool halted = enabled_ && !reason.empty(); + if (halted && !halted_) { + since_ = static_cast(std::time(nullptr)); + stop_pending_ = true; + LOG_WARN("guardian: the server stops all work: %s", reason.c_str()); + } else if (!halted && halted_) { + stop_pending_ = false; + LOG_INFO("guardian: the cause has ended, the server resumes work"); + } + if (started_halt != nullptr && stop_pending_) { + *started_halt = true; + stop_pending_ = false; + } + halted_ = halted; + reason_ = halted ? reason : std::string(); + since_ = halted ? since_ : 0; + retry_after_ = halted ? std::max(10, static_cast((wait_ms + 999) / 1000)) : 0; + + State state; + state.halted = halted_; + state.reason = reason_; + state.retry_after_seconds = retry_after_; + return state; +} + +Guardian::State Guardian::resume() { + if (hooks_.resume_health) { + hooks_.resume_health(); + } else { + sd_resume_device_health(); + } + LOG_INFO("guardian: an operator says the machine was checked"); + return evaluate(); +} + +nlohmann::json Guardian::health_json() { + evaluate(); + std::lock_guard lock(mutex_); + nlohmann::json devices = nlohmann::json::array(); + for (const auto& component : components_) { + devices.push_back(device_health_json(component)); + } + nlohmann::json guardian = {{"enabled", enabled_}, + {"halted", halted_}, + {"reason", reason_}, + {"since", since_}, + {"retry_after_seconds", retry_after_}}; + return {{"guardian", std::move(guardian)}, {"devices", std::move(devices)}}; +} + +static bool valid_source_name(const std::string& name) { + return !name.empty() && name.size() <= 32 && std::all_of(name.begin(), name.end(), [](unsigned char c) { + return std::isalnum(c) != 0 || c == '.' || c == '_' || c == '-'; + }); +} + +bool parse_pressure_report(const nlohmann::json& body, int strain_levels, PressureReport& report, std::string& error) { + report = PressureReport(); + if (!body.is_object()) { + error = "the body must be a JSON object"; + return false; + } + for (const auto& field : body.items()) { + if (field.key() != "level" && field.key() != "source" && field.key() != "reason" && field.key() != "duration_seconds") { + error = "unknown field '" + field.key() + "': the fields are level, source, reason and duration_seconds"; + return false; + } + } + + const int top = strain_levels + 1; + const std::string level_rule = "level must be 0 (withdraw the signal of this source) to " + std::to_string(top) + + ", \"excluded\" or \"critical\""; + const auto level = body.find("level"); + if (level == body.end()) { + error = level_rule; + return false; + } + if (level->is_number_integer()) { + const int64_t value = level->get(); + if (value < 0 || value > top) { + error = level_rule; + return false; + } + report.level = static_cast(value); + } else if (level->is_string() && *level == "excluded") { + report.level = top; + } else if (level->is_string() && *level == "critical") { + report.level = top; + report.critical = true; + } else { + error = level_rule; + return false; + } + + if (const auto source = body.find("source"); source != body.end()) { + if (!source->is_string() || !valid_source_name(source->get())) { + error = "source must be 1 to 32 letters, digits, '.', '_' or '-'"; + return false; + } + report.source = source->get(); + } + if (const auto reason = body.find("reason"); reason != body.end()) { + const bool one_line = reason->is_string() && std::none_of(reason->get_ref().begin(), + reason->get_ref().end(), + [](unsigned char c) { return c < 0x20 || c == 0x7f; }); + if (!one_line) { + error = "reason must be one line of text"; + return false; + } + report.reason = reason->get(); + } + if (const auto duration = body.find("duration_seconds"); duration != body.end()) { + if (!duration->is_number_integer() || duration->get() < 1 || duration->get() > 86400) { + error = "duration_seconds must be a whole number of seconds from 1 to 86400"; + return false; + } + report.duration_seconds = static_cast(duration->get()); + } + return true; +} + +bool refuse_while_halted(Guardian* guardian, httplib::Response& res) { + if (guardian == nullptr) { + return false; + } + const auto state = guardian->evaluate(); + if (!state.halted) { + return false; + } + res.status = 503; + nlohmann::json body = {{"error", "the server has stopped all work: " + state.reason}, {"code", "halted"}}; + body["retry_after_seconds"] = state.retry_after_seconds; + res.set_header("Retry-After", std::to_string(state.retry_after_seconds)); + res.set_content(json_text(body), "application/json"); + return true; +} diff --git a/examples/server/guardian.h b/examples/server/guardian.h new file mode 100644 index 00000000..be0f96ab --- /dev/null +++ b/examples/server/guardian.h @@ -0,0 +1,110 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "stable-diffusion.h" + +namespace httplib { + struct Response; +} + +// Stops all the work of the server when the machine cannot take it: a watcher reports a component as critical, or +// no compute device is left because device health excludes every GPU and the CPU. While it is halted, the +// generation in progress is stopped, new requests are refused with 503 and the queued jobs wait; it resumes on its +// own when the cause ends, or when an operator says the machine was checked. It only reads the registry of device +// health, so asking it never waits for a compute device. +// +// It is a layer on top of the software, not a safety system: a stop that protects people or plants belongs to +// independent, certified hardware. +class Guardian { +public: + using Clock = std::chrono::steady_clock; + + // Replaceable so that the logic can be tested without a registry. An empty function selects the real one. + struct Hooks { + // The components and how they are doing. Default: sd_get_device_health(). + std::function()> read_health; + // Default: sd_resume_device_health(). + std::function resume_health; + }; + + struct State { + bool halted = false; + std::string reason; + // How long a client should wait before trying again; 0 when the server is not halted. + int retry_after_seconds = 0; + }; + + explicit Guardian(bool enabled, const Hooks& hooks = Hooks()); + Guardian(const Guardian&) = delete; + Guardian& operator=(const Guardian&) = delete; + ~Guardian(); + + // Reads the registry every period on a thread of its own and calls on_halt there, once per halt, so that the + // work in progress stops even when no request comes. The thread ends with the guardian. Nothing happens when + // the guardian is off or already watches. + void watch(std::function on_halt, std::chrono::milliseconds period = std::chrono::seconds(1)); + // Makes the watcher read the registry now, for example right after a report. + void check_now(); + // Ends the watcher and waits for it; call it before what on_halt uses goes away. The destructor calls it too. + void stop_watching(); + + // Reads the registry and updates the state. started_halt is set, once per halt, for the first caller that passes + // it, so that this caller stops the generation in progress once; a refused request reads the registry too but + // passes nothing, so it does not use up the start of the halt. + State evaluate(bool* started_halt = nullptr); + // An operator says the machine was checked; returns the state after it. + State resume(); + bool enabled() const { + return enabled_; + } + // {"guardian": {...}, "devices": [...]}, fresh, for /sdcpp/v1/health. + nlohmann::json health_json(); + +private: + const bool enabled_; + const Hooks hooks_; + std::mutex mutex_; + bool halted_ = false; + bool stop_pending_ = false; // the start of the halt has not reached a caller that stops the work yet + int64_t since_ = 0; // unix seconds of the start of the halt + int retry_after_ = 0; + std::string reason_; + std::vector components_; // as the last evaluation read them + + std::mutex watch_mutex_; + std::condition_variable watch_wake_; + bool watch_stop_ = false; + bool watch_check_ = false; + std::thread watcher_; +}; + +// Answers 503 with the code halted, the reason and Retry-After when the guardian has halted the server; false, and +// res untouched, otherwise or without a guardian. +bool refuse_while_halted(Guardian* guardian, httplib::Response& res); + +// The components of device health as the registry lists them now, and one of them as /sdcpp/v1/health shows it. +std::vector read_device_health(); +nlohmann::json device_health_json(const sd_device_health_t& component); + +// What an outside watcher reports with POST /sdcpp/v1/devices/{device}/pressure, ready for +// sd_report_device_pressure(). +struct PressureReport { + std::string source = "http"; + int level = 0; + bool critical = false; + std::string reason; + int duration_seconds = 60; +}; + +// Reads the body of that request for a device with strain_levels levels of strain; false, with the reason in +// error, when it is not valid. +bool parse_pressure_report(const nlohmann::json& body, int strain_levels, PressureReport& report, std::string& error); diff --git a/examples/server/main.cpp b/examples/server/main.cpp index 790f3066..2856df93 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -11,6 +11,7 @@ #include "common/common.h" #include "common/profile.h" #include "common/resource_owners.hpp" +#include "guardian.h" #include "model_catalog.h" #include "recovery.h" #include "routes.h" @@ -148,10 +149,18 @@ int main(int argc, const char** argv) { return 1; } + Guardian guardian(svr_params.guardian); + if (svr_params.guardian) { + LOG_INFO("the guardian stops all work when a component is reported critical or device health excludes every GPU and the CPU (--guardian off to disable)"); + } else { + LOG_INFO("the guardian is off: the server never stops all work by itself (device health still moves work between devices)"); + } + ContextKeeper::Settings keeper_settings; keeper_settings.degradation = !svr_params.disable_degradation; keeper_settings.cooldown_seconds = svr_params.degradation_cooldown; ContextKeeper::Hooks keeper_hooks; + keeper_hooks.halted = [&guardian] { return guardian.evaluate().halted; }; // Every context the keeper creates, after a step down too, reads files only where the server allows it. keeper_hooks.create_context = [&models](const SDContextParams& params, GenerationFailure& failure) { SDCtxPtr ctx = create_context_from_params(params, failure); @@ -224,6 +233,7 @@ int main(int argc, const char** argv) { &async_job_manager, &models, }; + runtime.guardian = &guardian; try { initialize_server_models(runtime); @@ -233,6 +243,7 @@ int main(int argc, const char** argv) { } std::thread async_worker(async_job_worker, std::ref(runtime)); + guardian.watch([&runtime](const Guardian::State& state) { stop_work_for_guardian(runtime, state.reason); }); httplib::Server svr; @@ -294,5 +305,7 @@ int main(int argc, const char** argv) { } async_job_manager.cv.notify_all(); async_worker.join(); + // The guardian outlives the runtime its watcher stops the work of. + guardian.stop_watching(); return exit_code; } diff --git a/examples/server/recovery.cpp b/examples/server/recovery.cpp index 4567a62c..01f142da 100644 --- a/examples/server/recovery.cpp +++ b/examples/server/recovery.cpp @@ -64,6 +64,18 @@ namespace { return text; } + bool device_health_excludes(const std::string& name) { + std::vector components(sd_get_device_health(nullptr, 0)); + const size_t count = std::min(sd_get_device_health(components.data(), components.size()), components.size()); + const std::string wanted = lowercase(name); + for (size_t i = 0; i < count; ++i) { + if (lowercase(components[i].name) == wanted) { + return components[i].excluded; + } + } + return false; + } + GenerationFailure capture_failure() { GenerationFailure failure; char message[1024]; @@ -179,6 +191,12 @@ static ContextKeeper::Hooks with_defaults(ContextKeeper::Hooks hooks) { if (!hooks.list_devices) { hooks.list_devices = list_devices; } + if (!hooks.device_excluded) { + hooks.device_excluded = device_health_excludes; + } + if (!hooks.halted) { + hooks.halted = [] { return false; }; + } if (!hooks.now) { hooks.now = [] { return ContextKeeper::Clock::now(); }; } @@ -329,6 +347,44 @@ std::vector ContextKeeper::make_devices() const { } ContextKeeper::Rung ContextKeeper::next_rung(size_t index, size_t slot, const GenerationFailure& failure, bool retry_available) const { + Rung next = next_rung_ignoring_health(index, slot, failure, retry_available); + GenerationFailure excluded = failure; + excluded.code = SD_ERROR_BACKEND; + while (next.valid && !rung_excluded_device(next.index, next.slot).empty()) { + next = next_rung_ignoring_health(next.index, next.slot, excluded, false); + } + return next; +} + +std::string ContextKeeper::slot_device(size_t slot) const { + if (slot > 0) { + return slot <= devices_.size() ? devices_[slot - 1] : std::string(); + } + const std::string pinned = base_params_.backend.value_or(""); + if (pinned.empty() || pinned.find_first_of("=&,") != std::string::npos) { + return std::string(); + } + return lowercase(pinned) == "cpu" ? std::string("CPU") : pinned; +} + +std::string ContextKeeper::rung_excluded_device(size_t index, size_t slot) const { + const sd_profile::Level level = ladder_[index]; + const bool hands_work_to_cpu = + !accelerator_ || level == sd_profile::Level::LITE_CPU || level == sd_profile::Level::LITE_HYBRID; + if (hands_work_to_cpu && hooks_.device_excluded("CPU")) { + return "CPU"; + } + const std::string device = slot_device(slot); + if (level != sd_profile::Level::LITE_CPU && !device.empty() && hooks_.device_excluded(device)) { + return device; + } + return std::string(); +} + +ContextKeeper::Rung ContextKeeper::next_rung_ignoring_health(size_t index, + size_t slot, + const GenerationFailure& failure, + bool retry_available) const { Rung next; const size_t last = ladder_.size() - 1; if (failure.code != SD_ERROR_BACKEND) { @@ -540,7 +596,15 @@ bool ContextKeeper::build_from(size_t index, size_t slot, GenerationFailure& fai } done{*this}; while (index < ladder_.size()) { - if (try_build(index, slot, failure)) { + const std::string excluded = rung_excluded_device(index, slot); + if (!excluded.empty()) { + failure = GenerationFailure(); + failure.code = SD_ERROR_BACKEND; + failure.message = rung_text(index, slot) + " needs " + excluded + ", which device health excludes"; + LOG_WARN("%s: not loading it", failure.message.c_str()); + // An excluded device is no passing failure: loading the same configuration again would not help. + retry_used = true; + } else if (try_build(index, slot, failure)) { return true; } if (only_this || !settings_.degradation || !failure_is_recoverable(failure.code)) { @@ -692,6 +756,18 @@ void ContextKeeper::promote_if_due() { } else if (slot == 0) { target = index - 1; } + // No climb towards devices that device health excludes: the devices better than the one in use (all of them, + // from the cpu profile) or the one the climb would load on. The check comes back after the cooldown. + const size_t better = from_cpu ? devices_.size() : (slot > 0 ? slot - 1 : 0); + bool better_all_excluded = better > 0; + for (size_t i = 0; i < better && better_all_excluded; ++i) { + better_all_excluded = hooks_.device_excluded(devices_[i]); + } + if (better_all_excluded || !rung_excluded_device(target, 0).empty()) { + std::lock_guard state(state_mutex_); + next_promotion_ = hooks_.now() + std::chrono::seconds(cooldown_seconds_); + return; + } LOG_INFO("trying %s again", rung_text(target, 0).c_str()); release_context(); GenerationFailure failure; @@ -728,6 +804,15 @@ bool ContextKeeper::cancel(CancelToken& token) { return true; } +bool ContextKeeper::cancel_running() { + std::lock_guard state(state_mutex_); + if (running_ctx_ == nullptr) { + return false; + } + hooks_.cancel_context(running_ctx_); + return true; +} + bool ContextKeeper::run(const Attempt& attempt, GenerationFailure& failure, const CancelToken* token) { std::lock_guard lock(mutex_); failure = GenerationFailure(); @@ -753,12 +838,13 @@ bool ContextKeeper::run(const Attempt& attempt, GenerationFailure& failure, cons }; auto wanted_stop = [&]() { - return token != nullptr && token->requested.load(); + return (token != nullptr && token->requested.load()) || hooks_.halted(); }; auto stop = [&]() { - failure = GenerationFailure(); - failure.code = SD_ERROR_CANCELLED; - failure.message = "the generation was cancelled"; + const bool halted = hooks_.halted(); + failure = GenerationFailure(); + failure.code = SD_ERROR_CANCELLED; + failure.message = halted ? "the server stopped all work" : "the generation was cancelled"; std::lock_guard state(state_mutex_); ++counters_.cancelled; return false; diff --git a/examples/server/recovery.h b/examples/server/recovery.h index 24621c86..96b0a4a4 100644 --- a/examples/server/recovery.h +++ b/examples/server/recovery.h @@ -93,6 +93,11 @@ public: std::function has_accelerator; // The devices of the machine, in the order the library lists them. Default: sd_get_device_info(). std::function()> list_devices; + // Whether device health excludes a device ("CPU" included). Default: sd_get_device_health(). + std::function device_excluded; + // Whether the guardian has halted the server. A run then stops as if its token had been requested: before + // it reaches the context, and instead of loading the model again after a failure. Default: never. + std::function halted; std::function now; // Asks the library to stop the generation running on a context. Default: sd_cancel_generation(SD_CANCEL_ALL). std::function cancel_context; @@ -172,6 +177,10 @@ public: // was told. The library forgets a stop request when a generation begins, so a caller that cannot tell // whether the generation has begun yet repeats the call until the job ends (see the cancel route). bool cancel(CancelToken& token); + // Tells the library to stop whatever generation runs on the context now, whoever started it: the guardian + // halting the server, for requests that have no job and no token it could reach. Returns whether something was + // running; like cancel(), a caller repeats it for a moment, because the library forgets an early stop. + bool cancel_running(); // The settings the context in use was created with; for the upscale endpoint, which loads its own model. struct BackendChoice { @@ -237,7 +246,15 @@ private: std::vector make_devices() const; // Where to try next after failure at (index, slot); not valid when nothing is left. The same rung again is // offered once (retry_available) for a backend failure, then the other devices, then the lightest profile. + // Rungs that device health makes unusable are passed over as if their device had failed. Rung next_rung(size_t index, size_t slot, const GenerationFailure& failure, bool retry_available) const; + Rung next_rung_ignoring_health(size_t index, size_t slot, const GenerationFailure& failure, bool retry_available) const; + // The device a slot names: the alternative of slots 1, 2, ..., or for slot 0 the one device the host named; empty + // when the engine chooses. + std::string slot_device(size_t slot) const; + // The device that device health excludes and the rung would load on or hand work to ("CPU" included); empty + // when the rung can be used. + std::string rung_excluded_device(size_t index, size_t slot) const; std::string rung_text(size_t index, size_t slot) const; bool load_locked(GenerationFailure& failure); diff --git a/examples/server/routes_dgl.cpp b/examples/server/routes_dgl.cpp index 72905129..1cc2e7cb 100644 --- a/examples/server/routes_dgl.cpp +++ b/examples/server/routes_dgl.cpp @@ -9,6 +9,7 @@ #include "async_jobs.h" #include "common/media_io.h" +#include "guardian.h" namespace { namespace fs = std::filesystem; @@ -228,6 +229,9 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { })); svr.Post("/sdcpp/v1/dgl/jobs", local_dgl_route([&runtime](const Request& req, Response& res) { + if (refuse_while_halted(runtime.guardian, res)) { + return; + } auto source = json::parse(req.body).at("source").get(); if (source.empty() || !valid_source(source)) { send_error(res, 400, "Expected non-empty UTF-8 source"); diff --git a/examples/server/routes_models.cpp b/examples/server/routes_models.cpp index 56570eda..6ecf8a1f 100644 --- a/examples/server/routes_models.cpp +++ b/examples/server/routes_models.cpp @@ -1,6 +1,7 @@ #include "routes.h" #include "async_jobs.h" +#include "guardian.h" #include "model_catalog.h" class SynchronousContextJob { @@ -38,6 +39,9 @@ httplib::Server::Handler RuntimeRoutes::protect(httplib::Server::Handler handler const bool generation = req.path == "/sdapi/v1/txt2img" || req.path == "/sdapi/v1/img2img" || req.path == "/v1/images/generations" || req.path == "/v1/images/edits"; if (generation) { + if (refuse_while_halted(runtime->guardian, res)) { + return; + } SynchronousContextJob job(*runtime); std::lock_guard lock(*runtime->sd_ctx_mutex); if (!runtime->keeper->has_model()) { @@ -45,6 +49,10 @@ httplib::Server::Handler RuntimeRoutes::protect(httplib::Server::Handler handler return; } handler(req, res); + // A generation that the guardian stopped is answered with the halt while it lasts. + if (res.status >= 400) { + refuse_while_halted(runtime->guardian, res); + } } else { handler(req, res); } @@ -70,6 +78,10 @@ void RuntimeRoutes::post(const std::string& pattern, httplib::Server::Handler ha // Loads the model of a recipe ahead of the requests that use it, or unloads the current one. Generation jobs // pick their model themselves; these routes are for programs that want the model ready, or the memory back. static void change_model(ServerRuntime& runtime, const httplib::Request& req, httplib::Response& res, bool unload) { + // Unloading gives memory back, which a halted machine may need; loading is work. + if (!unload && refuse_while_halted(runtime.guardian, res)) { + return; + } auto& models = *runtime.models; { std::lock_guard jobs_lock(runtime.async_job_manager->mutex); diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index b13f39db..3ab4760b 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -13,6 +13,7 @@ #include "async_jobs.h" #include "common/common.h" #include "common/resource_owners.hpp" +#include "guardian.h" #include "model_catalog.h" namespace fs = std::filesystem; @@ -462,6 +463,9 @@ bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGen } static void submit_generation_job(ServerRuntime& runtime, const httplib::Request& req, httplib::Response& res, SDMode mode) { + if (refuse_while_halted(runtime.guardian, res)) { + return; + } try { if (req.body.empty()) { res.status = 400; @@ -549,6 +553,55 @@ static void submit_generation_job(ServerRuntime& runtime, const httplib::Request } } +static bool same_device_name(const std::string& a, const std::string& b) { + return a.size() == b.size() && + std::equal(a.begin(), a.end(), b.begin(), [](unsigned char x, unsigned char y) { return std::tolower(x) == std::tolower(y); }); +} + +static void answer_report_error(httplib::Response& res, int status, const std::string& code, const std::string& message) { + res.status = status; + res.set_content(safe_json_dump(json({{"error", message}, {"code", code}})), "application/json"); +} + +// A watcher outside the server (a thermal monitor, a supervisor, an operator) reports how a device is doing. The +// reports go through while the server is halted: a watcher must be able to withdraw its signal. +static void report_pressure(ServerRuntime& runtime, const std::string& name, const httplib::Request& req, httplib::Response& res) { + const std::vector components = read_device_health(); + const auto found = std::find_if(components.begin(), components.end(), [&](const sd_device_health_t& component) { + return same_device_name(component.name, name); + }); + if (found == components.end()) { + answer_report_error(res, 404, "unknown_device", "no device is named '" + name + "': GET /sdcpp/v1/health lists them"); + return; + } + const json body = json::parse(req.body, nullptr, false); + PressureReport report; + std::string error = "the body is not valid JSON"; + if (body.is_discarded() || !parse_pressure_report(body, found->strain_levels, report, error)) { + answer_report_error(res, 400, "invalid_report", error); + return; + } + const std::string device = found->name; + if (!sd_report_device_pressure(device.c_str(), report.source.c_str(), report.level, report.critical, report.reason.c_str(), report.duration_seconds)) { + answer_report_error(res, 409, "report_refused", "device health did not take the report: a device holds the signals of 8 sources at most"); + return; + } + + json out = {{"device", nullptr}, {"guardian", nullptr}}; + if (runtime.guardian != nullptr) { + // The watcher stops the work in progress at once when this report halts the server. + runtime.guardian->check_now(); + out["guardian"] = runtime.guardian->health_json()["guardian"]; + } + for (const auto& component : read_device_health()) { + if (same_device_name(component.name, device)) { + out["device"] = device_health_json(component); + } + } + res.status = 200; + res.set_content(safe_json_dump(out), "application/json"); +} + void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { ServerRuntime* runtime = &rt; RuntimeRoutes routes(svr, rt); @@ -571,7 +624,36 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { {"max", manager.max_pending_jobs}, }; } - res.status = body.value("status", std::string()) == "unavailable" ? 503 : 200; + if (runtime->guardian != nullptr) { + json guarded = runtime->guardian->health_json(); + body["guardian"] = std::move(guarded["guardian"]); + body["devices"] = std::move(guarded["devices"]); + if (body["guardian"].value("halted", false)) { + body["status"] = "halted"; + res.set_header("Retry-After", std::to_string(body["guardian"].value("retry_after_seconds", 10))); + } + } + const std::string status = body.value("status", std::string()); + res.status = status == "unavailable" || status == "halted" ? 503 : 200; + res.set_content(safe_json_dump(body), "application/json"); + }); + + svr.Post(R"(/sdcpp/v1/devices/([^/]+)/pressure)", [runtime](const httplib::Request& req, httplib::Response& res) { + report_pressure(*runtime, req.matches[1], req, res); + }); + + // An operator says the machine was checked: the critical signals end, the excluded devices come back at the last + // level of strain, and the queued jobs run again if nothing else holds the halt. + svr.Post("/sdcpp/v1/guardian/resume", [runtime](const httplib::Request&, httplib::Response& res) { + json body = json::object(); + if (runtime->guardian != nullptr) { + runtime->guardian->resume(); + body = runtime->guardian->health_json(); + } else { + sd_resume_device_health(); + } + runtime->async_job_manager->cv.notify_all(); + res.status = 200; res.set_content(safe_json_dump(body), "application/json"); }); diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index 7e88e319..55574b76 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -357,6 +357,19 @@ ArgOptions SDSvrParams::get_options() { model_dirs.push_back(argv_to_utf8(index, argv)); return 1; }}, + {"", "--guardian", + "on|off: stop all work, answering 503 until the cause ends, when a component is reported critical or device health excludes every GPU and the CPU (default: on)", + [this](int argc, const char** argv, int index) { + if (++index < argc) { + const std::string value = argv[index]; + if (value == "on" || value == "off") { + guardian = value == "on"; + return 1; + } + } + LOG_ERROR("--guardian expects on or off"); + return -1; + }}, }; add_log_options(options, log_level); return options; @@ -421,6 +434,7 @@ std::string SDSvrParams::to_string() const { << " cors_origins: \"" << cors_origins << "\",\n" << " disable_degradation: " << (disable_degradation ? "true" : "false") << ",\n" << " degradation_cooldown: " << degradation_cooldown << ",\n" + << " guardian: " << (guardian ? "on" : "off") << ",\n" << " dgl_dir: \"" << dgl_dir << "\",\n" << "}"; return oss.str(); diff --git a/examples/server/runtime.h b/examples/server/runtime.h index d26db8bd..0bbcdf3a 100644 --- a/examples/server/runtime.h +++ b/examples/server/runtime.h @@ -18,6 +18,7 @@ struct ArgOptions; struct SDContextParams; struct AsyncJobManager; class ContextKeeper; +class Guardian; struct ServerModels; struct SDSvrParams { @@ -32,6 +33,7 @@ struct SDSvrParams { std::string cors_origins; // comma-separated allowlist; empty = reflect any origin bool disable_degradation = false; int degradation_cooldown = 300; // seconds before the server tries a heavier profile again; 0 = never + bool guardian = true; // stop all work when device health leaves nothing to run on (--guardian) std::string dgl_dir = "dgl"; std::vector model_dirs; bool normal_exit = false; @@ -75,6 +77,7 @@ struct ServerRuntime { std::mutex* upscaler_mutex; AsyncJobManager* async_job_manager; ServerModels* models; + Guardian* guardian = nullptr; }; struct ServerADetailerPass { diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index 73473c02..2bc3ace8 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -593,6 +593,40 @@ typedef struct { // Returns false when none of them can be determined on this platform. SD_API bool sd_get_system_memory(sd_system_memory_t* info); +// Device health. The engine and outside watchers report how the devices, the RAM and the disk are doing: a +// component under strain offers less of its capacity, one step per level, and the work it gives up goes to the +// others; an excluded device is never computed on. A level comes back one step after each quiet period. The +// components are the devices sd_get_device_info() lists, "RAM" and "disk". +typedef struct { + char name[64]; + int level; // 0 healthy, 1..strain_levels under strain, strain_levels + 1 excluded + int strain_levels; // levels of strain before exclusion + int share_percent; // what the component offers of its capacity + bool excluded; // never computed on + bool critical; // a watcher asks to stop all work + char reason[200]; // why it is not healthy; empty when it is + int64_t held_ms; // how long the signals that hold this level still last; 0 when none does + int64_t next_step_ms; // until the level comes down one step if nothing else happens; 0 when none is due +} sd_device_health_t; + +// Fills up to capacity entries and returns the number of components; with health NULL or capacity 0 it only +// counts them. +SD_API size_t sd_get_device_health(sd_device_health_t* health, size_t capacity); +// Reports the signal of an outside watcher, named by source; each source holds one signal per component. Level 0 +// withdraws the signal of that source, 1..strain_levels puts the component under strain, strain_levels + 1 excludes +// it; critical asks to stop all work while the signal lasts, and excludes the component too. A signal reaches the +// listings of the same card through other backends and ends after duration_seconds, so a watcher repeats it while +// the condition lasts. Returns false, and changes nothing, when the component is unknown or the signal not valid. +SD_API bool sd_report_device_pressure(const char* component, + const char* source, + int level, + bool critical, + const char* reason, + int duration_seconds); +// An operator says the machine was checked: the critical signals are withdrawn and the excluded components come +// back to the last level of strain. +SD_API void sd_resume_device_health(void); + // Why a call failed, in finer terms than sd_status_t: a lack of memory, which a lighter configuration may get // around, is told apart from a compute backend that failed. sd_ctx_create, sd_ctx_set_model_options*, // sd_generate_image and sd_generate_video record the reason on the calling thread when they fail; a call that diff --git a/scripts/diagnostica_termica/README.md b/scripts/diagnostica_termica/README.md index ea550438..2641747a 100644 --- a/scripts/diagnostica_termica/README.md +++ b/scripts/diagnostica_termica/README.md @@ -11,9 +11,10 @@ frenando. Si usa a riposo, con il motore acceso, con una chat accanto, con tutto ## In breve -- **Solo lettura.** `termico.py` non cambia nessuna impostazione della GPU, non avvia carichi, non ferma programmi. - Esegue `nvidia-smi` con interrogazioni di sola lettura e, se glielo chiedi, fa richieste `GET` al motore - (sezione [10](#10-cosa-fa-sul-tuo-pc-esattamente)). +- **Solo lettura, salvo `--segnala`.** `termico.py` non cambia nessuna impostazione della GPU, non avvia carichi, non + ferma programmi. Esegue `nvidia-smi` con interrogazioni di sola lettura e, se glielo chiedi, fa richieste `GET` al + motore (sezione [10](#10-cosa-fa-sul-tuo-pc-esattamente)). Solo con `osserva --segnala` manda anche al motore la fascia + della GPU, e il motore le toglie lavoro (sezione [7.1](#71-segnalare-la-fascia-al-motore---segnala)). - **Non è un test di velocità né uno stress test.** Il carico lo generi tu, con il motore vero; lo strumento guarda cosa succede mentre lavora. - **Le fasce di temperatura sono indicative**, non garanzie del produttore: partono dai limiti che il driver dice @@ -373,6 +374,42 @@ Una cautela: interrogare la GPU ogni secondo con `nvidia-smi` è leggero, ma su può impedire alla GPU di spegnersi quando non serve. Non lasciare `osserva` acceso per ore a batteria se non ti serve. +### 7.1 Segnalare la fascia al motore (`--segnala`) + +Con `--segnala` il programma non si limita a guardare: a ogni campione manda a `sd-server` la fascia della GPU come +livello di salute del suo device, e il motore le toglie lavoro un gradino alla volta (85%, 70%, 55% di quello che può +tenere) e lo passa agli altri device; una GPU esclusa non calcola più niente finché non si riprende. + +```shell +python scripts/diagnostica_termica/termico.py osserva --motore http://127.0.0.1:1234 --segnala +``` + +| Cosa vede `termico.py` | Livello mandato | +|---|---| +| fascia normale | nessuno (un segnale mandato prima si ritira) | +| fascia normale, ma il driver rallenta la GPU per il caldo | 1 | +| fascia di attenzione | 1 | +| attenzione con throttling termico | 2 | +| fascia critica | 3 | +| critica con throttling termico hardware | escluso | + +- **Quale device.** Senza nome, il programma cerca la GPU fra i device del motore (`GET /sdcpp/v1/resources`) dal nome + che dà `nvidia-smi`; la stessa scheda vista da CUDA e da Vulkan va bene con l'uno o l'altro nome, perché il motore + riconosce la scheda e passa il segnale anche all'altro. Con due schede uguali, o se il nome non si trova, indica il + device: `--segnala CUDA0` (i nomi li elenca `GET /sdcpp/v1/health`, sotto `devices`). +- **Quanto dura.** Il segnale vale qualche campione (5 secondi con `--ogni 1`) e si ripete finché la fascia resta. + Tornata la GPU normale, e quando il programma si ferma, il segnale si ritira; il livello poi scende di un gradino + ogni 5 minuti di calma, non di colpo. Se il programma cade, il segnale scade da solo dopo pochi secondi. +- **Cosa non fa.** Non ferma mai il motore da solo: manda al massimo "escluso", e il motore si ferma del tutto solo se + non gli resta nessun device su cui calcolare (sezione "Device health and the guardian" della + [guida dell'API](../../examples/server/api.md#device-health-and-the-guardian)). +- **Errori.** Un motore che non risponde, la chiave API mancante o un device sconosciuto si dicono una volta sola, e + la misura va avanti; un motore lento non rallenta i campioni. La chiave è la stessa di `--motore` (`--chiave-api` + o `TERMICO_CHIAVE_API`). + +Le fasce restano indicative (sezione [6.4](#64-le-fasce-di-temperatura)): se sul tuo portatile il driver rallenta la GPU +prima della fascia di attenzione, il programma lo segnala lo stesso con il livello 1. + ## 8. Confrontare più prove (`confronta`) ```shell @@ -549,8 +586,9 @@ nvidia-smi --query-gpu=temperature.gpu,power.draw,clocks.sm,utilization.gpu,memo ``` (`-i 0` è la GPU scelta con `--gpu`.) Rete: **solo** se passi `--motore`, richieste `GET` a -`/sdcpp/v1/health` e `/sdcpp/v1/resources` dell'indirizzo che indichi, senza passare da proxy; niente -altro, niente telemetria. File: scrive `.csv`, `.json`, `.txt` e l'eventuale file di stato soltanto nella cartella di +`/sdcpp/v1/health` e `/sdcpp/v1/resources` dell'indirizzo che indichi, senza passare da proxy; con +`osserva --segnala` anche `POST /sdcpp/v1/devices/{device}/pressure` a ogni campione (sezione +[7.1](#71-segnalare-la-fascia-al-motore---segnala)); niente altro, niente telemetria. File: scrive `.csv`, `.json`, `.txt` e l'eventuale file di stato soltanto nella cartella di uscita (il nome della prova viene ripulito: non può far uscire i file dalla cartella). Non modifica né legge altro. `carico_motore.py` parla solo con il server che gli indichi: `POST /sdcpp/v1/img_gen`, `GET /sdcpp/v1/jobs/{id}` e @@ -630,6 +668,7 @@ della prima versione funzionano ancora). | `--auto-secondi S` | guidata | Durata delle fasi automatiche (default 120). | | `--durata S` | osserva | Secondi da registrare (default: fino a Ctrl+C). | | `--file-stato FILE` | osserva | File JSON con l'ultima lettura, riscritto a ogni campione. | +| `--segnala [DEVICE]` | osserva | Manda al motore (serve `--motore`) la fascia della GPU come livello di salute del device; senza `DEVICE` lo cerca dal nome della GPU (sezione 7.1). | | `--json FILE` | riepilogo, confronta | Scrive anche il risultato in JSON. | `carico_motore.py`: `--url` (default `http://127.0.0.1:1234`), `--chiave-api`, `--durata` (default 180), diff --git a/scripts/diagnostica_termica/termico.py b/scripts/diagnostica_termica/termico.py index c2bc721c..b989ab4c 100644 --- a/scripts/diagnostica_termica/termico.py +++ b/scripts/diagnostica_termica/termico.py @@ -4,8 +4,10 @@ Misura temperatura, potenza, frequenza e motivi di throttling con nvidia-smi, a fasi, e può affiancare alla stessa linea del tempo lo stato del motore (sd-server: /sdcpp/v1/health e /sdcpp/v1/resources). -Solo lettura: non cambia nessuna impostazione della GPU, non avvia nessun carico e scrive soltanto nella -cartella di uscita. Serve Python 3.8 o più recente; nessun pacchetto da installare. +Non cambia nessuna impostazione della GPU, non avvia nessun carico e scrive soltanto nella cartella di uscita. +Al motore chiede soltanto il suo stato, salvo con osserva --segnala: allora gli manda anche la fascia della GPU +come livello di salute del device (POST /sdcpp/v1/devices/{device}/pressure), e il motore sposta il lavoro. +Serve Python 3.8 o più recente; nessun pacchetto da installare. Comandi (guida completa: README.md di questa cartella): guidata sessione a fasi (riposo, motore, chat, insieme, raffreddamento); è il comando predefinito @@ -18,6 +20,7 @@ import argparse import csv import datetime as dt import json +import math import os import re import shutil @@ -298,7 +301,7 @@ def fascia_di(temp, fasce): # ---------------------------------------------------------------------------------------------------------- -# Motore (sd-server): solo richieste GET +# Motore (sd-server): letture con GET; le segnalazioni di --segnala sono le sole POST # ---------------------------------------------------------------------------------------------------------- def normalizza_url(testo): @@ -316,8 +319,8 @@ def url_senza_credenziali(url): return f"{parti.scheme}://{host}" + (f":{parti.port}" if parti.port else "") -def chiedi_json(url, chiave, percorso, timeout): - richiesta = urllib.request.Request(url + percorso, headers={"Accept": "application/json"}) +def apri_json(richiesta, chiave, timeout): + """(codice HTTP, corpo JSON); (None, None) se il motore non risponde.""" if chiave: richiesta.add_header("Authorization", "Bearer " + chiave) # Il motore è di solito su questo stesso PC: niente proxy di sistema. @@ -334,6 +337,16 @@ def chiedi_json(url, chiave, percorso, timeout): return None, None +def chiedi_json(url, chiave, percorso, timeout): + return apri_json(urllib.request.Request(url + percorso, headers={"Accept": "application/json"}), chiave, timeout) + + +def manda_json(url, chiave, percorso, corpo, timeout): + richiesta = urllib.request.Request(url + percorso, data=json.dumps(corpo).encode("utf-8"), method="POST", + headers={"Accept": "application/json", "Content-Type": "application/json"}) + return apri_json(richiesta, chiave, timeout) + + def leggi_salute(url, chiave, timeout=3.0): codice, salute = chiedi_json(url, chiave, "/sdcpp/v1/health", timeout) if codice is None: @@ -417,6 +430,161 @@ class OsservatoreMotore: return dict(ultimo[1]) +# ---------------------------------------------------------------------------------------------------------- +# Segnalazioni al motore (osserva --segnala): la fascia della GPU diventa il livello di salute del suo device. +# Il motore toglie lavoro al device un gradino alla volta e, se lo esclude, lo sposta altrove; il segnale dura +# qualche campione e si ripete finché la condizione resta, così scade da solo se questo programma si ferma. +# ---------------------------------------------------------------------------------------------------------- + +FONTE_SEGNALE = "termico" +LIVELLO_ESCLUSO = 4 # il livello dopo i tre di sforzo del motore +BIT_TERMICO_HW = 0x40 + + +def livello_segnale(fascia, mask): + """Il livello che fascia e motivi di throttling valgono per il motore; None se la temperatura non si legge.""" + if fascia is None: + return None + termico = (mask or 0) & BIT_TERMICI + if fascia == "critica": + return LIVELLO_ESCLUSO if (mask or 0) & BIT_TERMICO_HW else 3 + if fascia == "attenzione": + return 2 if termico else 1 + # Il driver che rallenta la GPU per il caldo sotto la fascia di attenzione: le fasce sono più alte del suo limite. + return 1 if termico else 0 + + +def motivo_segnale(c, fascia): + mask = c.get("mask") or 0 + motivo = f"GPU a {c['temp']:.0f} C, fascia {fascia}" + if mask & BIT_TERMICO_HW: + motivo += ", throttling termico hardware" + elif mask & BIT_TERMICI: + motivo += ", throttling termico" + return motivo + + +def durata_segnale(ogni): + """Qualche campione, mai meno di 5 secondi.""" + return max(5, int(math.ceil(3 * ogni))) + + +def dispositivo_del_motore(dispositivi, nome_gpu): + """Il device del motore per la GPU, dal nome che il motore ne dà (/sdcpp/v1/resources); None se non c'è o se + due schede uguali non si distinguono. La stessa scheda vista da CUDA e da Vulkan va bene con l'uno o l'altro + nome: il motore riconosce la scheda e passa il segnale anche all'altro.""" + voluto = (nome_gpu or "").strip().lower() + trovati = [d.get("name") for d in dispositivi or [] if isinstance(d, dict) and d.get("name") and + d.get("type") in ("gpu", "igpu") and str(d.get("description") or "").strip().lower() == voluto] + if not voluto or not trovati: + return None + backend = [re.sub(r"\d+$", "", nome) for nome in trovati] + if len(set(backend)) != len(backend): + return None + return trovati[0] + + +class SegnalatoreMotore: + """Manda al motore il livello della GPU in un thread a parte, così un motore lento non rallenta le letture. + Un livello sopra 0 si ripete a ogni campione; tornato 0 il segnale si ritira una volta, e così alla fine.""" + + def __init__(self, url, chiave, dispositivo, nome_gpu, durata): + self.url = url + self.chiave = chiave + self.dispositivo = dispositivo # None: si cerca dal nome della GPU + self.nome_gpu = nome_gpu + self.durata = durata + self._voluto = None # (livello, motivo) dell'ultimo campione, non ancora mandato + self._attivo = False # il motore tiene un segnale di questa fonte + self._fermo = False + self._annunciato = False + self._avvisi = set() + self._ultima_ricerca = None + self._condizione = threading.Condition() + self._thread = threading.Thread(target=self._ciclo, daemon=True) + + def avvia(self): + self._thread.start() + + def aggiorna(self, livello, motivo): + with self._condizione: + self._voluto = (livello, motivo) + self._condizione.notify() + + def ferma(self): + with self._condizione: + self._fermo = True + self._condizione.notify() + self._thread.join(timeout=10) + + def _avvisa(self, chiave, testo): + if chiave not in self._avvisi: + self._avvisi.add(chiave) + print(" " + testo, flush=True) + + def _ciclo(self): + self._trova_dispositivo() + while True: + with self._condizione: + while self._voluto is None and not self._fermo: + self._condizione.wait() + voluto, self._voluto = self._voluto, None + fermo = self._fermo + if fermo: + if self._attivo: + self._invia(0, "") + return + self._invia(*voluto) + + def _trova_dispositivo(self): + if self.dispositivo is None and (self._ultima_ricerca is None or time.monotonic() - self._ultima_ricerca >= 10): + self._ultima_ricerca = time.monotonic() + codice, risorse = chiedi_json(self.url, self.chiave, "/sdcpp/v1/resources", 3.0) + if codice == 200 and isinstance(risorse, dict): + dispositivi = risorse.get("devices") or [] + self.dispositivo = dispositivo_del_motore(dispositivi, self.nome_gpu) + if self.dispositivo is None: + nomi = ", ".join(str(d.get("name")) for d in dispositivi if isinstance(d, dict)) or "nessuno" + self._avvisa("gpu_ignota", f"Nel motore non trovo la GPU {self.nome_gpu} fra i device ({nomi}): " + "indica il suo nome con --segnala NOME.") + else: + self._avvisa_errore(codice, risorse) + if self.dispositivo is not None and not self._annunciato: + self._annunciato = True + print(f" Segnalo al motore la GPU come device {self.dispositivo}.", flush=True) + return self.dispositivo + + def _avvisa_errore(self, codice, risposta): + if codice is None: + self._avvisa("irraggiungibile", "Segnalazione al motore non riuscita: il motore non risponde. Riprovo al prossimo campione.") + elif codice == 401: + self._avvisa("401", "Segnalazione al motore rifiutata: chiave API mancante o errata (--chiave-api o TERMICO_CHIAVE_API).") + elif codice == 404: + self._avvisa("404", f"Il motore non conosce il device {self.dispositivo}: i nomi sono quelli di " + "/sdcpp/v1/health (CPU, CUDA0, Vulkan0...).") + else: + errore = risposta.get("error") if isinstance(risposta, dict) else None + self._avvisa(f"http{codice}", f"Segnalazione al motore rifiutata (HTTP {codice})" + (f": {errore}" if errore else ".")) + + def _invia(self, livello, motivo): + if livello == 0 and not self._attivo: + return + dispositivo = self._trova_dispositivo() + if dispositivo is None: + return + if livello == 0: + corpo = {"level": 0, "source": FONTE_SEGNALE} + else: + corpo = {"level": "excluded" if livello == LIVELLO_ESCLUSO else livello, "source": FONTE_SEGNALE, + "reason": motivo, "duration_seconds": self.durata} + percorso = "/sdcpp/v1/devices/" + urllib.parse.quote(dispositivo, safe="") + "/pressure" + codice, risposta = manda_json(self.url, self.chiave, percorso, corpo, 3.0) + if codice == 200: + self._attivo = livello != 0 + else: + self._avvisa_errore(codice, risposta) + + # ---------------------------------------------------------------------------------------------------------- # Riepilogo # ---------------------------------------------------------------------------------------------------------- @@ -1003,12 +1171,22 @@ def comando_guidata(args): def comando_osserva(args): + if args.segnala is not None and not args.motore: + sys.exit("--segnala manda la fascia della GPU al motore: indica anche --motore URL.") nvsmi, info, campo_motivi, osservatore = prepara(args) sessione = crea_sessione(args, nvsmi, info, campo_motivi, osservatore, ["OSSERVAZIONE"]) print(f"GPU: {info['nome']}, driver {info['driver']}") print(f"Fasce di temperatura (indicative): attenzione da {sessione.fasce['attenzione_da_c']:.0f} C, " f"critica da {sessione.fasce['critica_da_c']:.0f} C. Origine: {sessione.fasce['origine']}.") sessione.descrivi_motore() + segnalatore = None + if args.segnala is not None: + segnalatore = SegnalatoreMotore(normalizza_url(args.motore), args.chiave_api, args.segnala or None, info["nome"], + durata_segnale(args.ogni)) + print(f"Segnalazioni al motore: la fascia diventa il livello di salute del device (attenzione 1, con throttling " + f"termico 2, critica 3, critica con throttling hardware esclusa), ripetuta a ogni campione con una durata " + f"di {segnalatore.durata} s; tornata normale, e alla fine, il segnale si ritira.") + segnalatore.avvia() if args.file_stato: print(f"Stato aggiornato a ogni campione in {args.file_stato} (un file più vecchio di qualche secondo non vale).") print("Ctrl+C per fermare: il riepilogo viene scritto lo stesso." if not args.durata @@ -1022,6 +1200,11 @@ def comando_osserva(args): stato_non_scritto = [False] def dopo_campione(t, c, campioni): + if segnalatore is not None: + fascia = fascia_di(c["temp"], sessione.fasce) + livello = livello_segnale(fascia, c["mask"]) + if livello is not None: + segnalatore.aggiorna(livello, motivo_segnale(c, fascia)) if args.file_stato: try: scrivi_json(args.file_stato, costruisci_quadro(info, sessione.fasce, c, campioni[-70:])) @@ -1042,6 +1225,9 @@ def comando_osserva(args): except (RuntimeError, OSError) as errore: print(f"\nErrore: {errore}.") esito = 1 + finally: + if segnalatore is not None: + segnalatore.ferma() return chiudi_e_riferisci(sessione, esito == 1) @@ -1261,6 +1447,10 @@ def crea_parser(): osserva = sotto.add_parser("osserva", parents=[gpu, motore, registrazione], help="registra senza fasi") osserva.add_argument("--durata", type=int, default=0, metavar="S", help="secondi da registrare (default: fino a Ctrl+C)") + osserva.add_argument("--segnala", nargs="?", const="", default=None, metavar="DEVICE", + help="manda al motore (--motore) la fascia della GPU come livello di salute del suo device: " + "attenzione 1, con throttling termico 2, critica 3, critica con throttling hardware " + "esclusa; DEVICE è il nome nel motore (CUDA0, Vulkan0...), senza si trova dal nome della GPU") osserva.add_argument("--file-stato", dest="file_stato", metavar="FILE", help="file JSON riscritto a ogni campione con l'ultima lettura (per altri programmi)") osserva.set_defaults(esegui=comando_osserva) diff --git a/src/api/generation_program.cpp b/src/api/generation_program.cpp index 5217421f..90ec39fe 100644 --- a/src/api/generation_program.cpp +++ b/src/api/generation_program.cpp @@ -7,6 +7,7 @@ #include "conditioning/prompt_input.h" #include "core/backend_fit.h" +#include "core/device_health.h" #include "core/image_geometry.h" #include "model/vae/geometry.hpp" #include "name_conversion.h" @@ -76,7 +77,7 @@ namespace sd::api { {settings.vae_path, "vae."}, }; std::string key = text(settings.multi_gpu) + "|" + options.split_mode_spec + "|" + text(settings.max_vram) + "|" + - std::to_string(int(settings.wtype)); + std::to_string(int(settings.wtype)) + "|" + std::to_string(sd::device_health().revision()); for (const auto& [path, prefix] : sources) key += "|" + text(path); static std::mutex mutex; @@ -101,6 +102,9 @@ namespace sd::api { runtime_spec.clear(); LOG_WARN("auto-fit: no multi-GPU plan for this model%s%s; the run plan picks one device", error.empty() ? "" : ": ", error.c_str()); } + // The key changes with every change of device health, so old plans are dropped now and then. + if (plans.size() >= 64) + plans.clear(); plans.emplace(key, runtime_spec); return runtime_spec; } diff --git a/src/core/backend_fit.cpp b/src/core/backend_fit.cpp index 81d101fe..fcac5d77 100644 --- a/src/core/backend_fit.cpp +++ b/src/core/backend_fit.cpp @@ -1,5 +1,6 @@ #include "backend_fit.h" #include "config.h" +#include "core/device_health.h" #include "core/layer_split_partition.h" #include @@ -177,6 +178,18 @@ namespace sd::backend_fit { } } + // What each device offers after the registry of device health: a device under strain is chosen last, and an + // excluded one has no budget, so no module goes to it. + static void apply_device_health(std::vector& devices) { + for (Device& device : devices) { + const double share = sd::device_health().share(device.name); + if (share < 1.0) { + device.free_bytes = (int64_t)((double)device.free_bytes * share); + device.budget_bytes = (int64_t)((double)device.budget_bytes * share); + } + } + } + static std::vector enumerate_gpu_devices(const sd::ggml_graph_cut::MaxVramAssignment& budgets, bool include_other_devices, const AvailableVRAM& available_vram) { @@ -220,6 +233,7 @@ namespace sd::backend_fit { } out.push_back(std::move(device)); } + apply_device_health(out); mark_shadowed_devices(out); return out; } @@ -1068,7 +1082,14 @@ namespace sd::backend_fit { const auto fallback = sd_backend_resolve_name(""); const auto devices = enumerate_gpu_devices(budgets, false, available_vram); const auto selected = select_main_device(devices); - return selected == SIZE_MAX ? fallback : devices[selected].name; + if (selected != SIZE_MAX) { + return devices[selected].name; + } + if (sd::device_health().excluded(fallback) && !sd::device_health().excluded("CPU")) { + LOG_WARN("auto-fit: %s is excluded by device health; the models run on the CPU", fallback.c_str()); + return "CPU"; + } + return fallback; } bool derive_backend_specs(ModelLoader& loader, diff --git a/src/core/device_health.cpp b/src/core/device_health.cpp new file mode 100644 index 00000000..b5f1f4cd --- /dev/null +++ b/src/core/device_health.cpp @@ -0,0 +1,565 @@ +#include "core/device_health.h" + +#include +#include +#include +#include +#include + +#include "core/ggml_extend_backend.h" +#include "core/util.h" +#include "stable-diffusion.h" + +namespace sd { + + // Limits on what an outside watcher can make the registry keep: signals are data from another program. + static constexpr size_t max_signal_sources = 8; + static constexpr size_t max_source_length = 32; + static constexpr size_t max_reason_length = 160; + static constexpr std::chrono::seconds max_signal_duration{24 * 60 * 60}; + + static std::string lowercase(std::string text) { + std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + return text; + } + + static bool same_name(const std::string& a, const std::string& b) { + return a.size() == b.size() && lowercase(a) == lowercase(b); + } + + // Cuts text to at most limit bytes without splitting a UTF-8 sequence. + static std::string clipped(const std::string& text, size_t limit) { + if (text.size() <= limit) { + return text; + } + size_t end = limit; + while (end > 0 && (static_cast(text[end]) & 0xC0) == 0x80) { + end--; + } + return text.substr(0, end); + } + + static std::vector machine_components() { + sd_backend_resolve_name(""); + std::vector components; + for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + DeviceHealth::Component component; + component.name = ggml_backend_dev_name(dev); + ggml_backend_dev_props props{}; + ggml_backend_dev_get_props(dev, &props); + if (props.device_id != nullptr) { + component.hardware_id = props.device_id; + } + components.push_back(std::move(component)); + } + components.push_back({"RAM", ""}); + components.push_back({"disk", ""}); + return components; + } + + DeviceHealth::DeviceHealth() + : lister_(machine_components), clock_([] { return Clock::now(); }) {} + + void DeviceHealth::set_component_lister(std::function()> lister) { + std::lock_guard lock(mutex_); + lister_ = lister ? std::move(lister) : machine_components; + listed_ = false; + } + + void DeviceHealth::set_clock(std::function now) { + std::lock_guard lock(mutex_); + if (now) { + clock_ = std::move(now); + } else { + clock_ = [] { return Clock::now(); }; + } + } + + bool DeviceHealth::set_settings(const Settings& settings) { + const bool valid = settings.strain_levels >= 1 && settings.strain_levels <= 10 && + settings.step_percent >= 1 && settings.step_percent * settings.strain_levels < 100 && + settings.cpu_thread_step_percent >= 0 && + settings.cpu_thread_step_percent * settings.strain_levels < 100 && + settings.quiet_period >= std::chrono::seconds(1) && + settings.event_spacing >= std::chrono::seconds(0); + if (!valid) { + return false; + } + std::lock_guard lock(mutex_); + settings_ = settings; + if (!settings_.enabled) { + entries_.clear(); + listed_ = false; + } + const int top = top_locked(); + for (auto& entry : entries_) { + entry.level = std::min(entry.level, top); + for (auto& held : entry.signals) { + held.level = std::min(held.level, top); + } + } + revision_++; + return true; + } + + DeviceHealth::Settings DeviceHealth::settings() const { + std::lock_guard lock(mutex_); + return settings_; + } + + void DeviceHealth::reset() { + std::lock_guard lock(mutex_); + entries_.clear(); + listed_ = false; + revision_++; + } + + DeviceHealth::Clock::time_point DeviceHealth::now_locked() const { + return clock_(); + } + + int DeviceHealth::top_locked() const { + return settings_.strain_levels + 1; + } + + int DeviceHealth::effective(const Held& held) const { + return held.critical ? top_locked() : held.level; + } + + void DeviceHealth::list_locked(bool refresh) { + if (listed_ && !refresh) { + return; + } + const auto now = now_locked(); + for (const auto& component : lister_()) { + if (component.name.empty()) { + continue; + } + if (Entry* entry = find_locked(component.name)) { + entry->name = component.name; + entry->hardware_id = component.hardware_id; + continue; + } + Entry entry; + entry.name = component.name; + entry.hardware_id = component.hardware_id; + entry.since = now; + entry.quiet_from = now; + entries_.push_back(std::move(entry)); + } + listed_ = true; + } + + DeviceHealth::Entry* DeviceHealth::find_locked(const std::string& name) { + for (auto& entry : entries_) { + if (same_name(entry.name, name)) { + return &entry; + } + } + return nullptr; + } + + DeviceHealth::Entry& DeviceHealth::entry_locked(const std::string& name) { + list_locked(false); + if (Entry* entry = find_locked(name)) { + return *entry; + } + // An event of the engine names a device it is using, even one the lister did not know (an RPC server + // added later). + Entry entry; + entry.name = name; + entry.since = now_locked(); + entry.quiet_from = entry.since; + entries_.push_back(std::move(entry)); + return entries_.back(); + } + + void DeviceHealth::set_level_locked(Entry& entry, int level, const std::string& reason, Clock::time_point when) { + const int previous = entry.level; + entry.reason = reason; + if (level == previous) { + return; + } + entry.level = level; + entry.since = when; + revision_++; + const int top = top_locked(); + if (level == top) { + LOG_WARN("device health: %s excluded (%s)", entry.name.c_str(), reason.c_str()); + } else if (level > previous) { + LOG_WARN("device health: %s under strain, level %d of %d (%s); it offers %d%% of its capacity", + entry.name.c_str(), level, settings_.strain_levels, reason.c_str(), share_percent_locked(level)); + } else if (level == 0) { + LOG_INFO("device health: %s is healthy again", entry.name.c_str()); + } else { + LOG_INFO("device health: %s back to level %d of %d; it offers %d%% of its capacity", + entry.name.c_str(), level, settings_.strain_levels, share_percent_locked(level)); + } + } + + void DeviceHealth::refresh_locked(Entry& entry, Clock::time_point now) { + while (entry.level > 0) { + // The quiet period runs from the last event, or from the end of the latest signal at this level or + // above when that comes later; a signal that still holds puts the start in the future. + Clock::time_point start = entry.quiet_from; + for (const auto& held : entry.signals) { + if (effective(held) >= entry.level) { + start = std::max(start, held.expires); + } + } + if (now - start < settings_.quiet_period) { + break; + } + const auto when = start + settings_.quiet_period; + entry.quiet_from = when; + set_level_locked(entry, entry.level - 1, entry.level - 1 == 0 ? std::string() : entry.reason, when); + } + // A signal that ended before the quiet period started can no longer hold anything. + entry.signals.erase(std::remove_if(entry.signals.begin(), entry.signals.end(), [&](const Held& held) { + return held.expires <= now && (entry.level == 0 || held.expires <= entry.quiet_from); + }), + entry.signals.end()); + } + + void DeviceHealth::refresh_all_locked(Clock::time_point now) { + for (auto& entry : entries_) { + refresh_locked(entry, now); + } + } + + int DeviceHealth::share_percent_locked(int level) const { + if (level <= 0) { + return 100; + } + if (level >= top_locked()) { + return 0; + } + return 100 - settings_.step_percent * level; + } + + std::chrono::seconds DeviceHealth::next_step_in_locked(const Entry& entry, Clock::time_point now) const { + if (entry.level == 0) { + return std::chrono::seconds(0); + } + Clock::time_point start = entry.quiet_from; + for (const auto& held : entry.signals) { + if (effective(held) >= entry.level) { + if (held.expires > now) { + return std::chrono::seconds(0); + } + start = std::max(start, held.expires); + } + } + const auto remaining = start + settings_.quiet_period - now; + return std::chrono::ceil(std::max(remaining, Clock::duration::zero())); + } + + void DeviceHealth::note_strain(const std::string& component, const std::string& reason) { + std::lock_guard lock(mutex_); + if (!settings_.enabled || component.empty()) { + return; + } + const auto now = now_locked(); + Entry& entry = entry_locked(component); + refresh_locked(entry, now); + entry.quiet_from = std::max(entry.quiet_from, now); + if (entry.counted_event && now - entry.last_event < settings_.event_spacing) { + return; + } + entry.counted_event = true; + entry.last_event = now; + set_level_locked(entry, std::min(entry.level + 1, top_locked()), clipped(reason, max_reason_length), now); + } + + bool DeviceHealth::report(const std::string& component, const Signal& signal) { + std::lock_guard lock(mutex_); + const int top = top_locked(); + if (!settings_.enabled || signal.source.empty() || signal.level < 0 || signal.level > top || + signal.duration < std::chrono::seconds(1)) { + return false; + } + list_locked(false); + Entry* named = find_locked(component); + if (named == nullptr) { + list_locked(true); + named = find_locked(component); + } + if (named == nullptr) { + return false; + } + std::vector targets; + for (auto& entry : entries_) { + if (&entry == named || (!named->hardware_id.empty() && entry.hardware_id == named->hardware_id)) { + targets.push_back(&entry); + } + } + const std::string source = clipped(signal.source, max_source_length); + const bool withdraw = signal.level == 0 && !signal.critical; + auto from_source = [&](const Held& held) { return held.source == source; }; + for (Entry* entry : targets) { + const bool known = std::any_of(entry->signals.begin(), entry->signals.end(), from_source); + if (!withdraw && !known && entry->signals.size() >= max_signal_sources) { + return false; + } + } + + const auto now = now_locked(); + const auto duration = std::min(signal.duration, max_signal_duration); + const std::string reason = + source + ": " + clipped(signal.reason.empty() ? std::string(signal.critical ? "critical" : "pressure") : signal.reason, max_reason_length); + for (Entry* entry : targets) { + refresh_locked(*entry, now); + auto old = std::find_if(entry->signals.begin(), entry->signals.end(), from_source); + const bool old_holds = old != entry->signals.end() && old->expires > now && effective(*old) >= entry->level; + if (withdraw) { + if (old != entry->signals.end()) { + entry->signals.erase(old); + } + if (old_holds) { + entry->quiet_from = std::max(entry->quiet_from, now); + } + continue; + } + Held held; + held.source = source; + held.level = signal.level; + held.critical = signal.critical; + held.reason = reason; + held.expires = now + duration; + if (old != entry->signals.end()) { + *old = held; + } else { + entry->signals.push_back(held); + } + const int level = effective(held); + if (level >= entry->level || old_holds) { + entry->quiet_from = std::max(entry->quiet_from, now); + } + if (level >= entry->level) { + set_level_locked(*entry, level, reason, now); + } + } + return true; + } + + void DeviceHealth::resume() { + std::lock_guard lock(mutex_); + if (!settings_.enabled) { + return; + } + const auto now = now_locked(); + const int top = top_locked(); + for (auto& entry : entries_) { + refresh_locked(entry, now); + for (auto it = entry.signals.begin(); it != entry.signals.end();) { + if (it->critical) { + it = entry.signals.erase(it); + continue; + } + it->level = std::min(it->level, settings_.strain_levels); + ++it; + } + if (entry.level == top) { + entry.quiet_from = std::max(entry.quiet_from, now); + set_level_locked(entry, settings_.strain_levels, "resumed by an operator", now); + } + } + } + + int DeviceHealth::level(const std::string& component) { + std::lock_guard lock(mutex_); + if (!settings_.enabled) { + return 0; + } + list_locked(false); + Entry* entry = find_locked(component); + if (entry == nullptr) { + return 0; + } + refresh_locked(*entry, now_locked()); + return entry->level; + } + + bool DeviceHealth::excluded(const std::string& component) { + const int current = level(component); + std::lock_guard lock(mutex_); + return settings_.enabled && current >= top_locked(); + } + + bool DeviceHealth::excluded(ggml_backend_t backend) { + return backend != nullptr && excluded(device_health_name(backend)); + } + + double DeviceHealth::share(const std::string& component) { + const int current = level(component); + std::lock_guard lock(mutex_); + return share_percent_locked(current) / 100.0; + } + + double DeviceHealth::ram_share() { + const int current = level("RAM"); + std::lock_guard lock(mutex_); + return share_percent_locked(std::min(current, settings_.strain_levels)) / 100.0; + } + + int DeviceHealth::cpu_threads(int requested) { + if (requested <= 1) { + return requested; + } + const int current = level("CPU"); + std::lock_guard lock(mutex_); + const int steps = std::min(current, settings_.strain_levels); + if (steps <= 0) { + return requested; + } + const int percent = 100 - settings_.cpu_thread_step_percent * steps; + return std::max(1, (requested * percent + 50) / 100); + } + + bool DeviceHealth::any_critical() { + std::lock_guard lock(mutex_); + if (!settings_.enabled) { + return false; + } + const auto now = now_locked(); + refresh_all_locked(now); + for (const auto& entry : entries_) { + for (const auto& held : entry.signals) { + if (held.critical && held.expires > now) { + return true; + } + } + } + return false; + } + + uint64_t DeviceHealth::revision() { + std::lock_guard lock(mutex_); + if (settings_.enabled) { + refresh_all_locked(now_locked()); + } + return revision_; + } + + std::vector DeviceHealth::snapshot() { + std::lock_guard lock(mutex_); + list_locked(false); + const auto now = now_locked(); + const int top = top_locked(); + refresh_all_locked(now); + std::vector states; + states.reserve(entries_.size()); + for (const auto& entry : entries_) { + State state; + state.name = entry.name; + state.level = entry.level; + state.share_percent = share_percent_locked(entry.level); + state.excluded = entry.level >= top; + state.critical = std::any_of(entry.signals.begin(), entry.signals.end(), [&](const Held& held) { + return held.critical && held.expires > now; + }); + state.reason = entry.reason; + state.since = entry.since; + state.next_step_in = next_step_in_locked(entry, now); + for (const auto& held : entry.signals) { + if (entry.level > 0 && effective(held) >= entry.level && held.expires > now) { + state.held_for = std::max(state.held_for, std::chrono::ceil(held.expires - now)); + } + } + states.push_back(std::move(state)); + } + return states; + } + + DeviceHealth& device_health() { + static DeviceHealth health; + return health; + } + + std::string device_health_name(ggml_backend_t backend) { + if (backend == nullptr) { + return ""; + } + ggml_backend_dev_t dev = ggml_backend_get_device(backend); + const char* name = dev != nullptr ? ggml_backend_dev_name(dev) : ggml_backend_name(backend); + return name != nullptr ? name : ""; + } + + size_t health_scaled_bytes(ggml_backend_t backend, size_t bytes) { + if (backend == nullptr) { + return bytes; + } + const double share = device_health().share(device_health_name(backend)); + return share >= 1.0 ? bytes : static_cast(static_cast(bytes) * share); + } + + void note_compute_status(ggml_backend_t backend, ggml_status status) { + if (backend != nullptr && status == GGML_STATUS_FAILED) { + device_health().note_strain(device_health_name(backend), "compute failed"); + } + } + + void note_backend_start_failure(ggml_backend_dev_t device) { + if (device != nullptr) { + device_health().note_strain(ggml_backend_dev_name(device), "the backend did not start"); + } + } + + void note_memory_guard_unreachable(ggml_backend_t backend, int threshold_percent) { + if (backend == nullptr) { + return; + } + const std::string component = sd_backend_is_cpu(backend) ? std::string("RAM") : device_health_name(backend); + device_health().note_strain(component, "the memory guard cannot get usage under " + std::to_string(threshold_percent) + "%"); + } + + void note_disk_read_failure(const std::string& path) { + // The file name only: the reason is shown by the server's health endpoint. + device_health().note_strain("disk", "a read of " + std::filesystem::u8path(path).filename().u8string() + " failed"); + } + +} // namespace sd + +size_t sd_get_device_health(sd_device_health_t* health, size_t capacity) { + auto& registry = sd::device_health(); + const auto states = registry.snapshot(); + const auto settings = registry.settings(); + for (size_t i = 0; health != nullptr && i < states.size() && i < capacity; ++i) { + const auto& state = states[i]; + sd_device_health_t& out = health[i]; + out = sd_device_health_t{}; + snprintf(out.name, sizeof(out.name), "%s", state.name.c_str()); + out.level = state.level; + out.strain_levels = settings.strain_levels; + out.share_percent = state.share_percent; + out.excluded = state.excluded; + out.critical = state.critical; + snprintf(out.reason, sizeof(out.reason), "%s", state.reason.c_str()); + out.held_ms = std::chrono::duration_cast(state.held_for).count(); + out.next_step_ms = std::chrono::duration_cast(state.next_step_in).count(); + } + return states.size(); +} + +bool sd_report_device_pressure(const char* component, + const char* source, + int level, + bool critical, + const char* reason, + int duration_seconds) { + if (component == nullptr || source == nullptr) { + return false; + } + sd::DeviceHealth::Signal signal; + signal.source = source; + signal.level = level; + signal.critical = critical; + signal.reason = reason != nullptr ? reason : ""; + signal.duration = std::chrono::seconds(duration_seconds); + return sd::device_health().report(component, signal); +} + +void sd_resume_device_health(void) { + sd::device_health().resume(); +} diff --git a/src/core/device_health.h b/src/core/device_health.h new file mode 100644 index 00000000..6c20c904 --- /dev/null +++ b/src/core/device_health.h @@ -0,0 +1,165 @@ +#ifndef __SD_CORE_DEVICE_HEALTH_H__ +#define __SD_CORE_DEVICE_HEALTH_H__ + +#include +#include +#include +#include +#include +#include + +#include "ggml-backend.h" + +namespace sd { + + // How the compute devices, the RAM and the disk of the process are doing, from what the engine sees and what + // outside watchers report. A component under strain offers less of its capacity, one step per level, and the + // work it gives up goes to the others; an excluded device offers nothing and the engine never computes on it. + // A level rises at once, one step per event, and comes back one step after each quiet period, never below a + // signal that still holds. There is no thread: the clock is read whenever the registry is asked. + class DeviceHealth { + public: + using Clock = std::chrono::steady_clock; + + struct Settings { + bool enabled = true; + int strain_levels = 3; // levels of strain before exclusion + int step_percent = 15; // capacity a component gives up at each level + int cpu_thread_step_percent = 25; // compute threads the CPU gives up at each level + std::chrono::seconds quiet_period{300}; + // Events of the engine on one component closer than this count once: a failure shows up in more + // than one place. + std::chrono::seconds event_spacing{10}; + }; + + // A device as the backends list it, "RAM" or "disk". The listings of one card through two backends (CUDA0 + // and Vulkan0) share a non-empty hardware id. + struct Component { + std::string name; + std::string hardware_id; + }; + + // What an outside watcher reports. Each source holds at most one signal per component; a new one replaces + // it, and level 0 withdraws it. A signal reaches every listing of the same hardware. + struct Signal { + std::string source; + int level = 0; // 1..strain_levels, or strain_levels + 1 to exclude + bool critical = false; // asks to stop all work; excludes the component while it holds + std::string reason; + std::chrono::seconds duration{60}; + }; + + struct State { + std::string name; + int level = 0; // 0 healthy, 1..strain_levels under strain, strain_levels + 1 excluded + int share_percent = 100; + bool excluded = false; + bool critical = false; + std::string reason; + Clock::time_point since; // when the level last changed + // Until the level comes down one step when nothing else happens; zero when it is healthy or held by + // a signal that has not ended yet. + std::chrono::seconds next_step_in{0}; + // How long the signals that hold this level still last; zero when none does. + std::chrono::seconds held_for{0}; + }; + + DeviceHealth(); + + // Replaceable so that the rules can be tested without devices and without waiting. Defaults: the devices + // of the ggml backends with RAM and disk, and the steady clock. + void set_component_lister(std::function()> lister); + void set_clock(std::function now); + // False, and nothing changes, when the values make no sense. + bool set_settings(const Settings& settings); + Settings settings() const; + // Forgets every level and every signal. + void reset(); + + // An event of the engine on one component: a compute that failed, a backend that did not start, the + // memory guard that cannot get under its threshold, a read of the disk that failed. One level up. + void note_strain(const std::string& component, const std::string& reason); + // False when the component is unknown or the signal is not valid; the registry is then unchanged. + bool report(const std::string& component, const Signal& signal); + // An operator says the machine was checked: the critical signals are withdrawn and the excluded components + // come back to the last level of strain. + void resume(); + + int level(const std::string& component); + bool excluded(const std::string& component); + bool excluded(ggml_backend_t backend); + // What the component offers of its capacity: 1 when healthy, 0 when excluded. + double share(const std::string& component); + // What the RAM offers: as share("RAM"), but never less than at the last level of strain, because nothing + // runs without RAM. + double ram_share(); + // The compute threads the CPU takes out of requested, at least 1. + int cpu_threads(int requested); + bool any_critical(); + // Changes whenever a level changes, so that a placement made before knows it is out of date. + uint64_t revision(); + std::vector snapshot(); + + private: + struct Held { + std::string source; + int level = 0; + bool critical = false; + std::string reason; + Clock::time_point expires; + }; + + struct Entry { + std::string name; + std::string hardware_id; + int level = 0; + std::string reason; + Clock::time_point since; + // The quiet period that brings the level down runs from here, unless a signal holds the level longer. + Clock::time_point quiet_from; + bool counted_event = false; + Clock::time_point last_event; + std::vector signals; + }; + + Clock::time_point now_locked() const; + int top_locked() const; + int effective(const Held& held) const; + void list_locked(bool refresh); + Entry* find_locked(const std::string& name); + Entry& entry_locked(const std::string& name); + void refresh_locked(Entry& entry, Clock::time_point now); + void refresh_all_locked(Clock::time_point now); + void set_level_locked(Entry& entry, int level, const std::string& reason, Clock::time_point now); + int share_percent_locked(int level) const; + std::chrono::seconds next_step_in_locked(const Entry& entry, Clock::time_point now) const; + + mutable std::mutex mutex_; + Settings settings_; + std::function()> lister_; + std::function clock_; + std::vector entries_; + bool listed_ = false; + uint64_t revision_ = 0; + }; + + // The registry of the process: the devices are shared by every context. + DeviceHealth& device_health(); + + // The name the registry uses for the device a backend runs on. + std::string device_health_name(ggml_backend_t backend); + // A budget of memory on the device of a backend, scaled by the share the device offers. + size_t health_scaled_bytes(ggml_backend_t backend, size_t bytes); + + // The events of the engine, as the registry of the process counts them. A compute that failed counts; one that + // ran out of memory or was stopped on request does not: the profile ladder and the memory guard deal with + // memory, and a stop is not a fault. + void note_compute_status(ggml_backend_t backend, ggml_status status); + void note_backend_start_failure(ggml_backend_dev_t device); + // The guard of the CPU watches the system RAM, so its pressure is the RAM's. + void note_memory_guard_unreachable(ggml_backend_t backend, int threshold_percent); + void note_disk_read_failure(const std::string& path); + +} // namespace sd + +#endif // __SD_CORE_DEVICE_HEALTH_H__ diff --git a/src/core/execution_engine.cpp b/src/core/execution_engine.cpp index a974a436..c564989a 100644 --- a/src/core/execution_engine.cpp +++ b/src/core/execution_engine.cpp @@ -6,6 +6,7 @@ #include #include +#include "core/device_health.h" #include "core/ggml_extend_backend.h" #include "core/ggml_tensor_utils.h" #include "core/last_error.h" @@ -48,6 +49,9 @@ namespace sd { bool fits(const std::vector& requests, const std::vector& params, bool allow_reclamation = false) const; bool execute_segment(ggml_cgraph* graph, int n_threads, const std::function& on_before_compute); bool execute_graph(ggml_cgraph* graph, int n_threads, bool no_return, const std::function& read_outputs); + // The device of this run that device health excludes, if any: the main one, or one the layer split gave + // nodes to before it was excluded. + ggml_backend_t excluded_backend() const; bool is_multi_device() const { return !session_.extra_backends_.empty(); } size_t retained_runtime_buffer_bytes(ggml_backend_t backend) const { return session_.resident_bytes(backend); } void sync_runtime_residency() { engine_.sync_residency(session_); } @@ -453,7 +457,26 @@ namespace sd { return true; } + ggml_backend_t GraphExecution::excluded_backend() const { + auto& health = sd::device_health(); + if (health.excluded(session_.backend_)) { + return session_.backend_; + } + for (ggml_backend_t backend : session_.extra_backends_) { + if (!health.excluded(backend)) { + continue; + } + for (const auto& entry : session_.node_assignments_) { + if (entry.second == backend) { + return backend; + } + } + } + return nullptr; + } + bool GraphExecution::execute_segment(ggml_cgraph* graph, int n_threads, const std::function& on_before_compute) { + n_threads = sd::device_health().cpu_threads(n_threads); if (sd_backend_is_cpu(session_.backend_)) { sd_backend_cpu_set_n_threads(session_.backend_, n_threads); } @@ -489,6 +512,7 @@ namespace sd { last_compute_status_ = status; LOG_ERROR_CODE(status == GGML_STATUS_ALLOC_FAILED ? SD_ERROR_OUT_OF_MEMORY : SD_ERROR_BACKEND, "%s compute failed: %s", task_.description.c_str(), ggml_status_to_string(status)); + sd::note_compute_status(session_.backend_, status); return false; } const std::string description = task_.description; @@ -610,6 +634,13 @@ namespace sd { index + 1, plan.segments.size(), segment.group_name.c_str(), phase); return false; }; + // A device excluded while the graph runs is refused at the next segment; the line says why on its own. + if (ggml_backend_t excluded = excluded_backend()) { + last_compute_status_ = GGML_STATUS_FAILED; + LOG_ERROR_CODE(SD_ERROR_BACKEND, "%s: %s is excluded by device health; the engine does not compute on it", + task_.description.c_str(), sd::layer_split_backend_device_display_name(excluded).c_str()); + return false; + } session_.cut_cache_.prune(segment.live_cut_names); bindings.reset(segment); if (!bindings.bind_cached_inputs(segment, task_.description.c_str())) { diff --git a/src/core/ggml_extend_backend.cpp b/src/core/ggml_extend_backend.cpp index f26df75f..ac58b758 100644 --- a/src/core/ggml_extend_backend.cpp +++ b/src/core/ggml_extend_backend.cpp @@ -1,4 +1,6 @@ #include "core/ggml_extend_backend.h" + +#include "core/device_health.h" #include "core/ggml_extensions.h" #include @@ -419,6 +421,14 @@ static bool backend_name_exists(const std::string& name) { return !sd_backend_resolve_name(name).empty(); } +static ggml_backend_t init_device_backend(ggml_backend_dev_t dev) { + ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr); + if (backend == nullptr) { + sd::note_backend_start_failure(dev); + } + return backend; +} + static ggml_backend_t init_named_backend(const std::string& name) { ggml_backend_load_all_once(); LOG_VERBOSE("Initializing backend: %s", name.c_str()); @@ -427,18 +437,18 @@ static ggml_backend_t init_named_backend(const std::string& name) { } if (ggml_backend_dev_t dev = resolve_device_by_name(name)) { - return ggml_backend_dev_init(dev, nullptr); + return init_device_backend(dev); } if (ggml_backend_dev_t dev = resolve_first_device_by_registry_name(name)) { - return ggml_backend_dev_init(dev, nullptr); + return init_device_backend(dev); } std::string resolved = sd_backend_resolve_name(name); if (ggml_backend_dev_t dev = resolve_device_by_name(resolved)) { - return ggml_backend_dev_init(dev, nullptr); + return init_device_backend(dev); } if (ggml_backend_dev_t dev = resolve_first_device_by_registry_name(resolved)) { - return ggml_backend_dev_init(dev, nullptr); + return init_device_backend(dev); } if (resolved.empty()) { return nullptr; diff --git a/src/core/layer_split_partition.cpp b/src/core/layer_split_partition.cpp index 30b5e3d9..b74f26b6 100644 --- a/src/core/layer_split_partition.cpp +++ b/src/core/layer_split_partition.cpp @@ -9,6 +9,7 @@ #include #include +#include "core/device_health.h" #include "core/util.h" namespace sd { @@ -75,13 +76,10 @@ namespace sd { return backend_index == 0 ? primary_backend_vram_limit : 0; } - // Capacity of a device that reports no free memory and has no VRAM limit. - static constexpr int64_t graph_cut_layer_split_unknown_capacity = std::numeric_limits::max() / 4; - static std::vector graph_cut_layer_split_backend_capacities(const std::vector& backends, const std::vector& backend_vram_limits, size_t primary_backend_vram_limit) { - std::vector capacities(backends.size(), graph_cut_layer_split_unknown_capacity); + std::vector capacities(backends.size(), layer_split_unknown_capacity); constexpr int64_t compute_headroom_bytes = 2ll * 1024 * 1024 * 1024; for (size_t i = 0; i < backends.size(); i++) { ggml_backend_dev_t dev = ggml_backend_get_device(backends[i]); @@ -130,7 +128,7 @@ namespace sd { static std::vector graph_cut_layer_split_proportional_limits(const std::vector& segment_bytes, const std::vector& capacities) { const bool capacities_known = std::all_of(capacities.begin(), capacities.end(), [](int64_t capacity) { - return capacity < graph_cut_layer_split_unknown_capacity; + return capacity < layer_split_unknown_capacity; }); if (!capacities_known || !graph_cut_layer_split_fits(segment_bytes, capacities, 1.0)) { return capacities; @@ -207,6 +205,19 @@ namespace sd { return graph_cut_layer_split_proportional_limits(segment_bytes, capacities); } + std::vector layer_split_apply_shares(const std::vector& capacities, const std::vector& shares) { + std::vector result = capacities; + for (size_t i = 0; i < result.size() && i < shares.size(); i++) { + const double share = std::min(std::max(shares[i], 0.0), 1.0); + if (share <= 0.0) { + result[i] = 0; + } else if (result[i] < layer_split_unknown_capacity) { + result[i] = (int64_t)((double)result[i] * share); + } + } + return result; + } + bool layer_split_place(const std::vector& segment_bytes, const std::vector& limits, std::vector& bytes_by_device) { @@ -292,6 +303,15 @@ namespace sd { const LayerSplitFill fill = resolve_layer_split_fill(layer_split_fill(), device_types); if (!reuse_assignments) { LOG_INFO("%s layer split fill: %s", desc, layer_split_fill_name(fill)); + std::vector shares; + for (ggml_backend_t backend : split_backends) { + shares.push_back(device_health().share(device_health_name(backend))); + if (shares.back() < 1.0) { + LOG_INFO("%s layer split: %s offers %.0f%% of its capacity (device health)", + desc, layer_split_backend_device_display_name(backend).c_str(), shares.back() * 100.0); + } + } + backend_capacities = layer_split_apply_shares(backend_capacities, shares); } // Move to the next device at the fill limit; the capacity stays the hard limit. const std::vector backend_limits = reuse_assignments diff --git a/src/core/layer_split_partition.h b/src/core/layer_split_partition.h index 2990600e..865c2612 100644 --- a/src/core/layer_split_partition.h +++ b/src/core/layer_split_partition.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -53,6 +54,12 @@ namespace sd { bool layer_split_place(const std::vector& segment_bytes, const std::vector& limits, std::vector& bytes_by_device); + // The capacity of a device that reports no free memory and has no VRAM limit. + constexpr int64_t layer_split_unknown_capacity = std::numeric_limits::max() / 4; + // The capacities after the registry of device health (src/core/device_health.h): each device offers its share, + // given in split order, and an excluded one (share 0) nothing. What a device gives up goes to the others by the + // fill in use. A capacity that is not known stays unknown unless the device is excluded. + std::vector layer_split_apply_shares(const std::vector& capacities, const std::vector& shares); std::string layer_split_backend_device_display_name(ggml_backend_t backend); int layer_split_tensor_block_index(const std::string& name); diff --git a/src/dgl/context.cpp b/src/dgl/context.cpp index 20912138..416ccb0a 100644 --- a/src/dgl/context.cpp +++ b/src/dgl/context.cpp @@ -7,6 +7,7 @@ #include #include +#include "core/device_health.h" #include "core/ggml_graph_cut.h" #include "core/probe/backend_probe.h" #include "core/util.h" @@ -19,6 +20,7 @@ namespace sd::dgl { Context::Context(bool keep_resources) : keep_resources(keep_resources), + device_health_revision_(sd::device_health().revision()), model_execution_{std::make_shared(sd_get_num_physical_cores())}, conditioning_cache_size_(4) { model_execution_.backend_probes = std::make_shared(); @@ -63,6 +65,20 @@ namespace sd::dgl { LOG_VERBOSE("DGL unloaded %zu cached model components", unloaded); } + void Context::follow_device_health() { + const auto revision = sd::device_health().revision(); + if (revision == device_health_revision_) + return; + device_health_revision_ = revision; + const bool loaded = std::any_of(resources.begin(), resources.end(), [](const auto& entry) { + return is_model_kind(entry.second.value.type().kind); + }); + if (!loaded) + return; + LOG_INFO("device health changed: the loaded models are released and placed again for this run"); + unload_models(); + } + static size_t parse_max_ram(const std::string& value) { constexpr long double gib_bytes = 1024.0L * 1024 * 1024; size_t end = 0; diff --git a/src/dgl/context.h b/src/dgl/context.h index db57d305..9f067a7e 100644 --- a/src/dgl/context.h +++ b/src/dgl/context.h @@ -52,6 +52,9 @@ namespace sd::dgl { bool evict_idle_resource(); void prune_expired_resources(); void unload_models(); + // A model is placed on the devices when it is loaded, so a change of device health (src/core/device_health.h) + // since the last run releases the loaded models: the next run places them again with the new shares. + void follow_device_health(); sd::ParallelExecutor* tensor_executor() const { return model_execution_.tensor_executor.get(); } bool auto_fit() const { return auto_fit_; } @@ -68,6 +71,7 @@ namespace sd::dgl { std::optional find_resource(const ResourceKey& identity, const std::string& revision, const std::string& lora_revision, uint64_t last_use); Value cache_resource(ResourceKey identity, std::string revision, std::string lora_revision, ModelLoader::Dependencies dependencies, Value value, uint64_t last_use); bool auto_fit_ = true; + uint64_t device_health_revision_; models::ModelExecutionOptions model_execution_; size_t conditioning_cache_size_; void set_model_execution_option(const std::string& key, const std::string& value); diff --git a/src/dgl/executor.cpp b/src/dgl/executor.cpp index 920f776b..e98459db 100644 --- a/src/dgl/executor.cpp +++ b/src/dgl/executor.cpp @@ -284,6 +284,7 @@ namespace sd::dgl { Value run(const Graph& graph, RunState& state, Values inputs) { state.metadata = state.context.embed_metadata ? graph.source : ""; state.context.prune_expired_resources(); + state.context.follow_device_health(); sd::ParallelScope tensor_scope(state.context.tensor_executor()); RunPlan plan(graph, state); state.plan = &plan; diff --git a/src/dgl/models/model_runtime.cpp b/src/dgl/models/model_runtime.cpp index 60797fd0..8d06be1a 100644 --- a/src/dgl/models/model_runtime.cpp +++ b/src/dgl/models/model_runtime.cpp @@ -5,6 +5,7 @@ #include #include "conditioning/conditioner.hpp" +#include "core/device_health.h" #include "core/ggml_runner.h" #include "core/ggml_tensor_utils.h" #include "core/last_error.h" @@ -348,6 +349,11 @@ namespace sd::dgl::models { LOG_ERROR_CODE(SD_ERROR_BACKEND, "%s backend config failed: %s", model_component_name(component), error.c_str()); return false; } + if (sd::device_health().excluded("CPU")) { + LOG_ERROR_CODE(SD_ERROR_BACKEND, "%s backend config failed (%s), and the CPU is excluded by device health", + model_component_name(component), error.c_str()); + return false; + } LOG_WARN("%s backend config failed (%s); falling back to the cpu backend (use --disable-backend-fallback to fail instead)", model_component_name(component), error.c_str()); backend_spec_ = "cpu"; diff --git a/src/dgl/run_plan.cpp b/src/dgl/run_plan.cpp index 48e3edf0..96e997c4 100644 --- a/src/dgl/run_plan.cpp +++ b/src/dgl/run_plan.cpp @@ -5,6 +5,7 @@ #include "context.h" #include "core/backend_fit.h" +#include "core/device_health.h" #include "core/util.h" #include "executor.h" #include "model_value.h" @@ -63,7 +64,7 @@ namespace sd::dgl { auto available = state.context.models->available_vram_for_fit(backend, free, total); if (!state.context.models->max_vram_bytes(backend)) available -= std::min(available, 512 * MiB); - budgets_[backend] = available; + budgets_[backend] = sd::health_scaled_bytes(backend, available); } const auto ram = state.context.models->available_ram_for_fit(); ram_budget_ = ram.weights; @@ -212,6 +213,10 @@ namespace sd::dgl { } memory.params_backend = target; disk = peak_bytes(target, index, false) > ram_budget_ || peak_bytes(target, index) > host_budget_; + if (disk && sd::device_health().excluded("disk")) + throw Error(SD_STATUS_OUT_OF_MEMORY, "the weights of " + entry.name + + " do not fit in memory and would be read from the disk during the run, " + "which device health excludes"); if (disk) { target = memory.compute_backends.front(); memory.params_backend = target; @@ -279,7 +284,7 @@ namespace sd::dgl { auto available = state_.context.models->available_vram_for_fit(backend, free, total); if (!state_.context.models->max_vram_bytes(backend)) available -= std::min(available, 512 * MiB); - budgets_[backend] = available; + budgets_[backend] = sd::health_scaled_bytes(backend, available); } const auto ram = state_.context.models->available_ram_for_fit(); ram_budget_ = ram.weights; diff --git a/src/model_loader.cpp b/src/model_loader.cpp index 78862c71..b187b2f6 100644 --- a/src/model_loader.cpp +++ b/src/model_loader.cpp @@ -30,6 +30,7 @@ #include "runtime/imatrix.h" #include "stable-diffusion.h" +#include "core/device_health.h" #include "core/ggml_extend_backend.h" #include "ggml-alloc.h" #include "ggml-backend.h" @@ -1333,6 +1334,7 @@ bool ModelLoader::load_tensors(on_new_tensor_cb_t on_new_tensor_cb, } else if (mmapped) { if (!mmapped->copy_data(buf, n, tensor_storage.offset)) { LOG_ERROR("read tensor data failed: '%s'", file_path.c_str()); + sd::note_disk_read_failure(file_path); return false; } } else { @@ -1345,6 +1347,7 @@ bool ModelLoader::load_tensors(on_new_tensor_cb_t on_new_tensor_cb, // A stream kept open for a long time can go bad (removable or // network storage); try once more on a newly opened one. LOG_WARN("read from '%s' failed; reopening the file and trying again", file_path.c_str()); + sd::note_disk_read_failure(file_path); file.discard(); file = file_pool_.acquire(file_path, true); if (!file || !read_from_file()) { diff --git a/src/model_manager.cpp b/src/model_manager.cpp index ca2a4027..0e6a9d6d 100644 --- a/src/model_manager.cpp +++ b/src/model_manager.cpp @@ -10,6 +10,7 @@ #include #include "core/backend_fit.h" +#include "core/device_health.h" #include "core/ggml_extend_backend.h" #include "core/last_error.h" #include "core/util.h" @@ -2145,6 +2146,9 @@ ModelManager::RAMBudget ModelManager::available_ram_for_fit() const { constexpr size_t reserve = 1024ULL * 1024 * 1024; size_t available = free < 0 ? 0 : size_t(std::max(free - reserve, 0)); available += std::min(reclaimable, SIZE_MAX - available); + const double share = sd::device_health().ram_share(); + if (share < 1.0) + available = static_cast(static_cast(available) * share); const auto weights = max_ram_bytes_ ? std::min(available, max_ram_bytes_ > fixed ? max_ram_bytes_ - fixed : 0) : available; return {weights, available}; } @@ -2637,6 +2641,7 @@ void ModelManager::memory_guard_unreachable(const DeviceMemoryRequest& request, if (memory_watchdog_.should_log_unreachable(request.compute_backend)) { LOG_WARN("memory guard: cannot reduce %s below %d%% usage, continuing under pressure", ggml_backend_name(request.compute_backend), memory_watchdog_.threshold_percent()); + sd::note_memory_guard_unreachable(request.compute_backend, memory_watchdog_.threshold_percent()); } } diff --git a/test/README.md b/test/README.md index e5a8a276..d79087f4 100644 --- a/test/README.md +++ b/test/README.md @@ -16,10 +16,13 @@ sezione "Sicurezza". | `backend_fit_plan_test.cpp` | pianificatore multi-GPU dell'auto-fit (`--multi-gpu auto\|on\|off`) con GPU simulate: quale modulo va su quale GPU, quando il modello si divide per blocchi, nessun device riceve più pesi del suo budget, i moduli assegnati dall'utente non si muovono. Con più backend installati insieme (CUDA e Vulkan): la stessa scheda vista da due backend conta una volta sola, una GPU integrata non diventa la scheda principale finché una scheda ha memoria libera e la sua memoria condivisa (la RAM) non ospita pesi; gli avvisi dopo il piano: `--backend vulkan0` su una scheda che CUDA elenca come CUDA0, e pesi lasciati su disco che vengono riletti a ogni passo (include `src/core/backend_fit.cpp`, quindi serve la libreria compilata; nessuna GPU né modello) | vedi intestazione del file | | `memory_guard_engine_test.cpp` | memory guard (`--memory-guard`, profili `balanced` e successivi) dentro il motore di esecuzione: libera blocchi di pesi finché la richiesta ci sta *e* l'uso scende sotto la soglia, e se la soglia è irraggiungibile esegue comunque una richiesta che ci sta, avvisando una volta (gestore della memoria simulato, nessun modello) | vedi intestazione del file | | `layer_split_fill_test.cpp` | come lo split a livelli riempie i dispositivi (`--layer-split-fill auto\|proportional\|fill-first`): ripartizione proporzionale alla capacità, prima scheda riempita per prima, scelta di `auto` per GPU discrete, integrate e CPU, piazzamento condiviso con il pianificatore | vedi intestazione del file | +| `device_health_test.cpp` | registro della salute dei device (`src/core/device_health.*`): i livelli salgono di un gradino per evento (eventi del motore troppo ravvicinati contano una volta) e scendono di uno dopo ogni periodo tranquillo; i segnali esterni tengono il livello finché durano (fonte, durata, ritiro, sostituzione) e il periodo tranquillo parte dalla loro fine; un segnale critico esclude il componente; la stessa scheda vista da due backend riceve i segnali esterni ma non i guasti dell'altro backend; quote e thread della CPU per livello, segnali non validi rifiutati, ripresa chiesta dall'operatore. Eventi del motore: un calcolo fallito conta, la memoria esaurita e uno stop chiesto no, il memory guard della CPU parla per la RAM, una lettura fallita alza il disco. Orologio finto: nessuna GPU né modello | vedi intestazione del file | | `package_windows_cuda_vulkan_test.sh` | script che assembla lo zip Windows con CUDA e Vulkan insieme (`scripts/package_windows_cuda_vulkan.sh`, passo del job `release` di `build.yml`) con zip finti che hanno i nomi di quelli veri: pacchetto in una cartella sola con tutti i file (programmi e `stable-diffusion.dll` dallo zip CUDA, solo `ggml-vulkan.dll` dallo zip Vulkan, DLL di CUDA, `LEGGIMI.txt`), avviso se `ggml-base.dll` o `ggml.dll` hanno dimensioni diverse, rifiuto di uno zip mancante o doppio, di zip di commit diversi, di moduli o DLL mancanti, di file con lo stesso nome in due zip e di un `LEGGIMI.txt` già presente, due esecuzioni nella stessa cartella. Servono `zip` e `unzip`; nessuna build, GPU o modello | `./test/package_windows_cuda_vulkan_test.sh` (meno di un secondo) | -| `server_recovery_test.cpp` | custode del contesto del server (`examples/server/recovery.*`): scala dei profili, discesa su memoria insufficiente, risalita dopo una pausa, ricarica dopo un errore, risposte HTTP 503/400/500 con `Retry-After`, uso da più thread. Annullamento di una generazione in corso: lo stop raggiunge solo il job che lo ha chiesto, un job annullato prima di partire non genera nulla, non costa nessuna ricarica del modello e non conta come errore. Caricamento e scaricamento del modello chiesti dal catalogo del server (`load`/`unload`): il vecchio contesto viene liberato prima di crearne uno nuovo, la scala dei profili si ricostruisce dalle opzioni del modello nuovo, un caricamento fallito lascia il server senza modello (richieste rifiutate) e si può ripetere, scaricare due volte è innocuo, salute e stato si possono leggere mentre il modello cambia. Contesto condiviso con gli script DGL e con il rilascio dei pesi inattivi: uno script usa il contesto del modello caricato, senza modello riceve un contesto temporaneo che dura solo per quella chiamata, e il rilascio dei pesi inattivi non aspetta una generazione in corso. Non serve nessun modello: libreria e orologio sono simulati (con ASan/UBSan e TSan) | vedi intestazione del file | +| `server_recovery_test.cpp` | custode del contesto del server (`examples/server/recovery.*`): scala dei profili, discesa su memoria insufficiente, risalita dopo una pausa, ricarica dopo un errore, risposte HTTP 503/400/500 con `Retry-After`, uso da più thread. Annullamento di una generazione in corso: lo stop raggiunge solo il job che lo ha chiesto, un job annullato prima di partire non genera nulla, non costa nessuna ricarica del modello e non conta come errore. Caricamento e scaricamento del modello chiesti dal catalogo del server (`load`/`unload`): il vecchio contesto viene liberato prima di crearne uno nuovo, la scala dei profili si ricostruisce dalle opzioni del modello nuovo, un caricamento fallito lascia il server senza modello (richieste rifiutate) e si può ripetere, scaricare due volte è innocuo, salute e stato si possono leggere mentre il modello cambia. Contesto condiviso con gli script DGL e con il rilascio dei pesi inattivi: uno script usa il contesto del modello caricato, senza modello riceve un contesto temporaneo che dura solo per quella chiamata, e il rilascio dei pesi inattivi non aspetta una generazione in corso. Salute dei device: un device escluso non viene caricato né raggiunto risalendo, i profili che passano lavoro a una CPU esclusa vengono saltati. Server fermato dal guardiano: una richiesta non genera nulla, anche senza token, e un errore che arriva mentre il server si ferma non fa ricaricare il modello né scendere di profilo. Non serve nessun modello: libreria e orologio sono simulati (con ASan/UBSan e TSan) | vedi intestazione del file | +| `server_guardian_test.cpp` | guardiano del server (`examples/server/guardian.*`): quando ferma tutto il lavoro (un componente segnalato critico, oppure nessun device di calcolo rimasto perché la salute dei device esclude ogni GPU e la CPU), quando riparte, quanto dice di aspettare (`Retry-After`, mai meno di 10 secondi), l'inizio dell'arresto consegnato una volta sola anche se una richiesta rifiutata lo ha visto per prima, la ripresa chiesta dall'operatore, cosa mostra `/sdcpp/v1/health`, il corpo di `POST /sdcpp/v1/devices/{device}/pressure` (livelli, `excluded`, `critical`, fonte, motivo, durata, campi sconosciuti rifiutati) e il sorvegliante che ferma il lavoro senza aspettare una richiesta. Componenti simulati: nessun modello né GPU (anche con TSan) | vedi intestazione del file | +| `server_guardian_e2e.py` | guardiano e segnalazioni degli osservatori esterni su un vero `sd-server` (serve un modello qualsiasi, su qualunque backend): segnalazioni non valide (`400`), device sconosciuto (`404`), chiave API richiesta, livello di sforzo che lascia lavorare, RAM critica durante un job (job finito con codice `halted`, job in coda che aspetta, `503` con `Retry-After` su img_gen, txt2img, OpenAI, DGL e caricamento del modello, salute `halted`, ripartenza da sola alla fine del segnale), lo stesso con una richiesta sincrona, ogni device di calcolo critico mentre un job calcola (il modello non viene ricaricato altrove, il server resta fermo finché l'operatore non chiama `POST /sdcpp/v1/guardian/resume`), un secondo server con `--guardian off`, `termico.py osserva --segnala` con la GPU finta di `termico_test.py` che arriva al server, contatori e log | `python3 test/server_guardian_e2e.py --server build/bin/sd-server --model ` (circa un minuto con un modello piccolo) | | `server_cancel_e2e.py` | annullamento di un job in corso su un vero `sd-server` (serve un modello qualsiasi, su qualunque backend): job fermato (senza `?wait=` la risposta torna subito con il job ancora in generazione), richiesta ripetuta, job in coda, `?wait=0`, `?wait=30` (`200` appena il job finisce), POST senza corpo né `Content-Length` (come `curl -X POST`: risposta subito, non dopo 5 secondi), richiesta sincrona in attesa che poi completa, job già finito, id sconosciuto, `wait` non valido, contatori di `/sdcpp/v1/health` e log senza righe di errore | `python3 test/server_cancel_e2e.py --server build/bin/sd-server --model ` | -| `termico_test.py` | programma di diagnostica termica [`scripts/diagnostica_termica/`](../scripts/diagnostica_termica/README.md) (`termico.py` e `carico_motore.py`) con una GPU finta (un `nvidia-smi` scritto dentro il test) e un motore finto: lettura dei campi e dei motivi di throttling, fasce di temperatura, giudizi, riepilogo e file di stato, confronto fra prove, codici di uscita, interruzione con Ctrl+C e SIGTERM, motore che non risponde, chiave API. Non serve nessuna GPU, driver o modello | `python3 test/termico_test.py` (1-2 minuti; `--veloce` salta le prove che lanciano il programma) | +| `termico_test.py` | programma di diagnostica termica [`scripts/diagnostica_termica/`](../scripts/diagnostica_termica/README.md) (`termico.py` e `carico_motore.py`) con una GPU finta (un `nvidia-smi` scritto dentro il test) e un motore finto: lettura dei campi e dei motivi di throttling, fasce di temperatura, giudizi, riepilogo e file di stato, confronto fra prove, codici di uscita, interruzione con Ctrl+C e SIGTERM, motore che non risponde, chiave API. Segnalazioni al motore con `osserva --segnala`: livello per fascia e throttling (attenzione 1, con throttling termico 2, critica 3, con throttling hardware escluso), device trovato dal nome della GPU o indicato, segnale ripetuto e ritirato alla fine, chiave API, GPU o device che il motore non conosce detti una volta, motore lento che non rallenta i campioni. Non serve nessuna GPU, driver o modello | `python3 test/termico_test.py` (1-2 minuti; `--veloce` salta le prove che lanciano il programma) | | `agenti_guardiano_test.py` | guardiano d'esempio di [docs/agenti_indipendenti.md](../docs/agenti_indipendenti.md) (sezione 9): il test estrae il codice dalla guida e lo fa girare. Senza opzioni usa un orologio e un motore finti (nessun modello né GPU): lettura dello stato e dato vecchio, livelli, attesa prima di ripartire, tetto orario, file `stop`, registro, `429`/`503` con `Retry-After`, scadenze, stop ignorato dal motore. Con `--server` e `--model` prova la catena vera: `sd-server` (anche su CPU), `termico.py` con la GPU finta di `termico_test.py`, GPU critica = job fermato con `cancel` senza discesa di profilo, job di un altro programma non toccato | `python3 test/agenti_guardiano_test.py` (10 secondi); con il server vero aggiungi `--server build/bin/sd-server --model MODELLO` (circa 2 minuti con un modello piccolo) | | `fuzz_model_loader.py` | fuzzing a mutazione del caricamento modelli (safetensors/GGUF) | `python3 test/fuzz_model_loader.py --seconds 300` | diff --git a/test/backend_fit_plan_test.cpp b/test/backend_fit_plan_test.cpp index e0ec7021..c462a229 100644 --- a/test/backend_fit_plan_test.cpp +++ b/test/backend_fit_plan_test.cpp @@ -618,6 +618,38 @@ int main() { const std::vector one_gpu = {make_gpu("CUDA0", "CUDA", 12)}; const std::vector two_gpus = {make_gpu("CUDA0", "CUDA", 12), make_gpu("CUDA1", "CUDA", 12)}; + { + sd::DeviceHealth& health = sd::device_health(); + health.set_component_lister([] { + return std::vector{{"CUDA0", ""}, {"CUDA1", ""}, {"CPU", ""}, {"RAM", ""}, {"disk", ""}}; + }); + health.reset(); + sd::DeviceHealth::Signal hot; + hot.source = "test"; + hot.level = 3; + hot.reason = "too hot"; + hot.duration = std::chrono::seconds(600); + health.report("CUDA0", hot); + std::vector devices = two_gpus; + apply_device_health(devices); + CHECK(devices[0].budget_bytes == (int64_t)((double)two_gpus[0].budget_bytes * 0.55) && + devices[1].budget_bytes == two_gpus[1].budget_bytes, + "device health: a GPU under strain offers its share of its budget"); + CHECK(select_main_device(devices) == 1, "device health: a GPU under strain is no longer the main device"); + hot.level = 4; + health.report("CUDA0", hot); + devices = two_gpus; + apply_device_health(devices); + const Outcome out = run(make_components(6, 2, 0.3), devices, MultiGpuMode::ON); + bool on_excluded = false; + for (const Runtime& runtime : out.runtimes) { + on_excluded = on_excluded || runtime.name.find("CUDA0") != std::string::npos; + } + CHECK(devices[0].budget_bytes == 0 && !on_excluded, "device health: an excluded GPU gets no module, even with --multi-gpu on"); + health.set_component_lister(nullptr); + health.reset(); + } + { const std::vector on_cuda0(3, Runtime{"CUDA0", {0}}); const Plan fits = compute_plan(make_components(6, 2, 0.3), one_gpu, 0, on_cuda0); diff --git a/test/device_health_test.cpp b/test/device_health_test.cpp new file mode 100644 index 00000000..98e1f966 --- /dev/null +++ b/test/device_health_test.cpp @@ -0,0 +1,467 @@ +// Test of the registry of device health (src/core/device_health.*): levels that rise one step per event, events +// of the engine that come too close together, the way back after each quiet period, the signals of outside +// watchers (sources, durations, critical), the same card seen by two backends, and what the levels offer: the +// share of a device and the threads of the CPU. A fake clock replaces waiting; no GPU and no model are needed. +// Build (from the repository root, after building the static library into build/): +// c++ -std=c++17 -DGGML_MAX_NAME=160 -Isrc -Isrc/core -Iinclude -Ithirdparty -Iggml/include \ +// test/device_health_test.cpp build/libstable-diffusion.a build/ggml/src/libggml.a \ +// build/ggml/src/libggml-cpu.a build/ggml/src/libggml-base.a -ldl -lm -fopenmp -pthread \ +// -o device_health_test +// Run: ./device_health_test ; exit code 0 = all checks passed. +#include +#include +#include +#include + +#include "core/device_health.h" +#include "stable-diffusion.h" + +using sd::DeviceHealth; + +static int failures = 0; + +static void check(bool condition, const char* what) { + std::printf("%s %s\n", condition ? "ok: " : "FAIL:", what); + failures += condition ? 0 : 1; +} + +static DeviceHealth::Clock::time_point fake_now = DeviceHealth::Clock::time_point(std::chrono::hours(100)); + +static void advance(int seconds) { + fake_now += std::chrono::seconds(seconds); +} + +// An NVIDIA card seen by CUDA and by Vulkan, an integrated GPU, the CPU, the RAM and the disk. +static std::vector machine() { + return {{"CUDA0", "0000:01:00.0"}, {"Vulkan0", "0000:01:00.0"}, {"Vulkan1", "0000:05:00.0"}, {"CPU", ""}, {"RAM", ""}, {"disk", ""}}; +} + +static void prepare(DeviceHealth& health, DeviceHealth::Settings settings = DeviceHealth::Settings()) { + health.set_clock([] { return fake_now; }); + health.set_component_lister(machine); + health.set_settings(settings); + health.reset(); +} + +static DeviceHealth::Signal signal(const char* source, int level, int seconds, const char* reason = "too hot") { + DeviceHealth::Signal result; + result.source = source; + result.level = level; + result.reason = reason; + result.duration = std::chrono::seconds(seconds); + return result; +} + +static DeviceHealth::Signal critical_signal(const char* source, int seconds) { + DeviceHealth::Signal result = signal(source, 0, seconds, "emergency stop"); + result.critical = true; + return result; +} + +static const DeviceHealth::State* find(const std::vector& states, const char* name) { + for (const auto& state : states) { + if (state.name == name) { + return &state; + } + } + return nullptr; +} + +static bool same(double a, double b) { + return std::fabs(a - b) < 1e-9; +} + +static void test_starts_healthy() { + DeviceHealth health; + prepare(health); + check(health.level("CUDA0") == 0 && same(health.share("CUDA0"), 1.0) && !health.excluded("CUDA0"), + "a device starts healthy and offers all of its capacity"); + check(health.cpu_threads(8) == 8, "the CPU starts with all of its threads"); + check(!health.any_critical(), "nothing asks to stop"); + const auto states = health.snapshot(); + check(states.size() == 6, "the snapshot lists every component of the machine"); + const auto* ram = find(states, "RAM"); + check(ram != nullptr && ram->level == 0 && ram->share_percent == 100 && !ram->excluded && ram->reason.empty(), + "a healthy component has level 0, all of its share and no reason"); +} + +static void test_engine_events_rise_one_step_each() { + DeviceHealth health; + prepare(health); + const auto start = health.revision(); + health.note_strain("CUDA0", "compute failed"); + check(health.level("CUDA0") == 1 && same(health.share("CUDA0"), 0.85), "an event of the engine raises its device one level, to 85%"); + check(health.revision() != start, "a new level changes the revision"); + advance(5); + health.note_strain("CUDA0", "compute failed"); + check(health.level("CUDA0") == 1, "an event closer than the spacing to the previous one counts once"); + advance(10); + health.note_strain("CUDA0", "compute failed"); + check(health.level("CUDA0") == 2 && same(health.share("CUDA0"), 0.70), "a later event raises it again, to 70%"); + advance(10); + health.note_strain("CUDA0", "compute failed"); + check(health.level("CUDA0") == 3 && same(health.share("CUDA0"), 0.55), "the third level offers 55%"); + advance(10); + health.note_strain("CUDA0", "compute failed"); + check(health.level("CUDA0") == 4 && health.excluded("CUDA0") && same(health.share("CUDA0"), 0.0), + "the event after the last level of strain excludes the device"); + advance(10); + health.note_strain("CUDA0", "compute failed"); + check(health.level("CUDA0") == 4, "an excluded device stays excluded"); + check(health.level("Vulkan0") == 0, "an event of the engine stays with its backend, even on the same card"); +} + +static void test_quiet_periods_bring_the_levels_back() { + DeviceHealth health; + prepare(health); + health.note_strain("Vulkan1", "compute failed"); + advance(10); + health.note_strain("Vulkan1", "compute failed"); + advance(299); + check(health.level("Vulkan1") == 2, "the level holds during the quiet period"); + const auto before = health.revision(); + advance(1); + check(health.level("Vulkan1") == 1, "after 300 quiet seconds it comes down one level"); + check(health.revision() != before, "coming down changes the revision"); + advance(300); + check(health.level("Vulkan1") == 0, "and one more after the next quiet period"); + + health.note_strain("Vulkan1", "compute failed"); + advance(10); + health.note_strain("Vulkan1", "compute failed"); + advance(600); + check(health.level("Vulkan1") == 0, "two quiet periods bring it down two levels even when nobody asked in between"); + + health.note_strain("Vulkan1", "compute failed"); + advance(10); + health.note_strain("Vulkan1", "compute failed"); + advance(200); + health.note_strain("Vulkan1", "memory guard cannot get under its threshold"); + advance(200); + check(health.level("Vulkan1") == 3, "an event restarts the quiet period"); + advance(100); + check(health.level("Vulkan1") == 2, "which then runs from that event"); + + DeviceHealth other; + prepare(other); + other.note_strain("CUDA0", "compute failed"); + advance(5); + other.note_strain("CUDA0", "compute failed"); + advance(296); + check(other.level("CUDA0") == 1, "an event that counts once still restarts the quiet period"); + advance(4); + check(other.level("CUDA0") == 0, "from its own time"); +} + +static void test_signals_hold_a_level_while_they_last() { + DeviceHealth health; + prepare(health); + check(health.report("Vulkan1", signal("termico", 2, 60)), "a signal on a known device is accepted"); + check(health.level("Vulkan1") == 2, "a signal sets its level at once"); + for (int i = 0; i < 3; ++i) { + advance(30); + health.report("Vulkan1", signal("termico", 2, 60)); + } + check(health.level("Vulkan1") == 2, "a watcher that repeats its signal keeps the level"); + advance(60); + check(health.level("Vulkan1") == 2, "when the signal expires the level does not drop at once"); + advance(299); + check(health.level("Vulkan1") == 2, "the quiet period counts from the end of the signal"); + advance(1); + check(health.level("Vulkan1") == 1, "and then the level comes down one step"); + advance(300); + check(health.level("Vulkan1") == 0, "and one more"); + + check(health.report("Vulkan1", signal("termico", 2, 1000)), "a long signal is accepted"); + advance(600); + check(health.level("Vulkan1") == 2, "a signal holds its level for as long as it lasts"); + advance(400); + check(health.level("Vulkan1") == 2, "even right after it expires"); + advance(300); + check(health.level("Vulkan1") == 1, "the way back starts when it ends"); + + DeviceHealth other; + prepare(other); + for (int i = 0; i < 3; ++i) { + other.note_strain("Vulkan1", "compute failed"); + advance(10); + } + other.report("Vulkan1", signal("termico", 1, 60)); + check(other.level("Vulkan1") == 3, "a signal lower than the current level does not lower it"); +} + +static void test_each_source_holds_one_signal() { + DeviceHealth health; + prepare(health); + health.report("Vulkan1", signal("termico", 3, 600)); + health.report("Vulkan1", signal("agente", 1, 3600)); + check(health.level("Vulkan1") == 3, "two sources: the higher signal sets the level"); + advance(400); + health.report("Vulkan1", signal("termico", 0, 60)); + check(health.level("Vulkan1") == 3, "a withdrawn signal leaves the level where it is"); + advance(299); + check(health.level("Vulkan1") == 3, "the way back counts from the withdrawal"); + advance(1); + check(health.level("Vulkan1") == 2, "and then comes down one step"); + advance(300); + check(health.level("Vulkan1") == 1, "down to the level the other source still holds"); + advance(1200); + check(health.level("Vulkan1") == 1, "which it keeps while that signal lasts"); + health.report("Vulkan1", signal("agente", 0, 60)); + advance(300); + check(health.level("Vulkan1") == 0, "when it is withdrawn too, the device comes back"); + + health.report("Vulkan1", signal("termico", 2, 600)); + advance(400); + health.report("Vulkan1", signal("termico", 1, 600)); + check(health.level("Vulkan1") == 2, "a new signal of the same source replaces the old one without dropping the level at once"); + advance(299); + check(health.level("Vulkan1") == 2, "the way back counts from the replacement"); + advance(1); + check(health.level("Vulkan1") == 1, "down to the level of the new signal"); +} + +static void test_critical_signals() { + DeviceHealth health; + prepare(health); + check(health.report("CPU", critical_signal("guardiano", 30)), "a critical signal is accepted"); + check(health.any_critical() && health.excluded("CPU"), "a critical signal asks to stop and excludes its component"); + const auto states = health.snapshot(); + const auto* cpu = find(states, "CPU"); + check(cpu != nullptr && cpu->critical && cpu->reason.find("emergency stop") != std::string::npos, + "the snapshot shows the critical component and why"); + advance(30); + check(!health.any_critical(), "the critical signal ends when it expires"); + check(health.excluded("CPU"), "its component stays excluded for a quiet period"); + advance(300); + check(health.level("CPU") == 3, "and then comes back one level at a time"); +} + +static void test_signals_reach_the_same_card() { + DeviceHealth health; + prepare(health); + health.report("CUDA0", signal("termico", 2, 60)); + check(health.level("Vulkan0") == 2, "a signal reaches the same card seen by another backend"); + check(health.level("Vulkan1") == 0, "but not another card"); + check(health.report("vulkan1", signal("termico", 1, 60)) && health.level("Vulkan1") == 1, "device names are matched in any case"); +} + +static void test_invalid_signals_are_refused() { + DeviceHealth health; + prepare(health); + check(!health.report("GPU9", signal("termico", 1, 60)), "a device the machine does not have is refused"); + check(!health.report("CUDA0", signal("termico", -1, 60)), "a negative level is refused"); + check(!health.report("CUDA0", signal("termico", 5, 60)), "a level above exclusion is refused"); + check(!health.report("CUDA0", signal("termico", 1, 0)), "a signal without a duration is refused"); + check(!health.report("CUDA0", signal("", 1, 60)), "a signal without a source is refused"); + check(health.level("CUDA0") == 0, "refused signals change nothing"); + for (int i = 0; i < 8; ++i) { + health.report("RAM", signal(("watcher" + std::to_string(i)).c_str(), 1, 60)); + } + check(!health.report("RAM", signal("one-too-many", 1, 60)), "a component keeps at most eight sources"); + check(health.report("RAM", signal("watcher0", 2, 60)), "a known source can still update its signal"); + health.report("disk", signal("termico", 1, 60, std::string(1000, 'x').c_str())); + const auto states = health.snapshot(); + const auto* disk = find(states, "disk"); + check(disk != nullptr && disk->reason.size() <= 200, "a long reason is cut"); +} + +static void test_resume() { + DeviceHealth health; + prepare(health); + health.report("CUDA0", critical_signal("guardiano", 3600)); + for (int i = 0; i < 4; ++i) { + health.note_strain("Vulkan1", "compute failed"); + advance(10); + } + const auto before = health.revision(); + health.resume(); + check(!health.any_critical(), "resume withdraws the critical signals"); + check(health.level("CUDA0") == 3 && health.level("Vulkan1") == 3, "and brings the excluded devices back to the last level of strain"); + check(health.revision() != before, "which changes the revision"); +} + +static void test_cpu_threads() { + DeviceHealth health; + prepare(health); + health.note_strain("CPU", "too hot"); + check(health.cpu_threads(8) == 6, "a CPU under strain gives up a quarter of its threads per level: 8 to 6"); + advance(10); + health.note_strain("CPU", "too hot"); + check(health.cpu_threads(8) == 4, "then 4"); + advance(10); + health.note_strain("CPU", "too hot"); + check(health.cpu_threads(8) == 2, "then 2"); + check(health.cpu_threads(1) == 1 && health.cpu_threads(3) == 1, "never fewer than one thread"); + advance(10); + health.note_strain("CPU", "too hot"); + check(health.cpu_threads(8) == 2, "an excluded CPU keeps the threads of the last level"); +} + +static void test_settings() { + DeviceHealth health; + prepare(health); + DeviceHealth::Settings settings; + settings.strain_levels = 0; + check(!health.set_settings(settings), "at least one level of strain"); + settings = DeviceHealth::Settings(); + settings.step_percent = 40; + check(!health.set_settings(settings), "steps that would leave nothing before exclusion are refused"); + settings = DeviceHealth::Settings(); + settings.quiet_period = std::chrono::seconds(0); + check(!health.set_settings(settings), "a quiet period of zero is refused"); + settings = DeviceHealth::Settings(); + settings.step_percent = 20; + check(health.set_settings(settings), "sensible settings are accepted"); + health.note_strain("CUDA0", "compute failed"); + check(same(health.share("CUDA0"), 0.80), "the step applies to the share"); + + DeviceHealth off; + DeviceHealth::Settings disabled; + disabled.enabled = false; + prepare(off, disabled); + const auto revision = off.revision(); + off.note_strain("CUDA0", "compute failed"); + check(!off.report("CUDA0", signal("termico", 2, 60)), "a disabled registry refuses signals"); + check(off.level("CUDA0") == 0 && same(off.share("CUDA0"), 1.0) && off.revision() == revision, + "and changes nothing for the events of the engine"); +} + +static void test_snapshot_and_revision() { + DeviceHealth health; + prepare(health); + health.note_strain("RPC0[host:50052]", "compute failed"); + auto states = health.snapshot(); + const auto* rpc = find(states, "RPC0[host:50052]"); + check(rpc != nullptr && rpc->level == 1, "an event on a device the lister does not know is kept"); + health.note_strain("CUDA0", "compute failed"); + advance(100); + states = health.snapshot(); + const auto* cuda = find(states, "CUDA0"); + check(cuda != nullptr && cuda->level == 1 && cuda->share_percent == 85 && cuda->reason == "compute failed", + "the snapshot gives the level, the share and the reason"); + check(cuda != nullptr && cuda->next_step_in == std::chrono::seconds(200), "and how long until the next step down"); + + health.report("Vulkan1", signal("termico", 2, 60)); + const auto revision = health.revision(); + advance(10); + health.report("Vulkan1", signal("termico", 2, 60)); + check(health.revision() == revision, "a repeated signal at the same level leaves the revision as it is"); + advance(20); + states = health.snapshot(); + const auto* vulkan1 = find(states, "Vulkan1"); + check(vulkan1 != nullptr && vulkan1->held_for == std::chrono::seconds(40) && vulkan1->next_step_in == std::chrono::seconds(0), + "a level held by a signal tells how long the signal still lasts, and no step down is due"); +} + +// The C functions a host (the server) reads and resumes the registry with. +static void test_c_api() { + DeviceHealth& health = sd::device_health(); + prepare(health); + check(sd_report_device_pressure("Vulkan1", "termico", 2, false, "86 C", 60), "the C API reports a signal"); + check(sd_report_device_pressure("CPU", "guardiano", 0, true, "emergency stop", 30), "and a critical one"); + check(!sd_report_device_pressure(nullptr, "termico", 1, false, "x", 60) && !sd_report_device_pressure("CPU", nullptr, 1, false, "x", 60) && + !sd_report_device_pressure("GPU9", "termico", 1, false, "x", 60) && !sd_report_device_pressure("CPU", "termico", 1, false, nullptr, 0), + "and refuses a missing component or source, an unknown device and a signal without a duration"); + const size_t count = sd_get_device_health(nullptr, 0); + check(count == 6, "the C API counts the components"); + std::vector entries(count + 2); + check(sd_get_device_health(entries.data(), 2) == count, "and returns the count even when the array is shorter"); + sd_get_device_health(entries.data(), entries.size()); + const sd_device_health_t* vulkan1 = nullptr; + const sd_device_health_t* cpu = nullptr; + for (size_t i = 0; i < count; ++i) { + if (std::string(entries[i].name) == "Vulkan1") { + vulkan1 = &entries[i]; + } else if (std::string(entries[i].name) == "CPU") { + cpu = &entries[i]; + } + } + check(vulkan1 != nullptr && vulkan1->level == 2 && vulkan1->strain_levels == 3 && vulkan1->share_percent == 70 && + !vulkan1->excluded && !vulkan1->critical && std::string(vulkan1->reason) == "termico: 86 C" && vulkan1->held_ms == 60000, + "an entry carries the level, the share, the reason and how long its signal holds"); + check(cpu != nullptr && cpu->excluded && cpu->critical && cpu->share_percent == 0, "a critical component is excluded"); + sd_resume_device_health(); + check(!health.any_critical() && health.level("CPU") == 3, "the C API resumes the registry"); + health.set_clock(nullptr); + health.set_component_lister(nullptr); + health.reset(); +} + +static void test_backend_names() { + ggml_backend_t cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr); + check(cpu != nullptr && sd::device_health_name(cpu) == "CPU", "a backend is named by its device"); + DeviceHealth health; + prepare(health); + for (int i = 0; i < 4; ++i) { + health.note_strain(sd::device_health_name(cpu), "compute failed"); + advance(10); + } + check(health.excluded(cpu), "and its device can be asked about through the backend"); + if (cpu != nullptr) { + ggml_backend_free(cpu); + } + check(&sd::device_health() == &sd::device_health(), "the process has one registry"); +} + +// What the engine reports, through the registry of the process. +static void test_engine_hooks() { + DeviceHealth& health = sd::device_health(); + prepare(health); + ggml_backend_t cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr); + sd::note_compute_status(cpu, GGML_STATUS_ALLOC_FAILED); + check(health.level("CPU") == 0, "running out of memory is not a matter of health: the ladder and the guard handle it"); + sd::note_compute_status(cpu, GGML_STATUS_ABORTED); + sd::note_compute_status(cpu, GGML_STATUS_SUCCESS); + check(health.level("CPU") == 0, "nor is a compute that was stopped on request, or one that worked"); + sd::note_compute_status(cpu, GGML_STATUS_FAILED); + check(health.level("CPU") == 1, "a compute that failed raises its device"); + advance(10); + sd::note_backend_start_failure(ggml_backend_get_device(cpu)); + check(health.level("CPU") == 2, "so does a backend that does not start"); + auto states = health.snapshot(); + const auto* dev = find(states, "CPU"); + check(dev != nullptr && dev->reason.find("did not start") != std::string::npos, "with the reason of the latest event"); + sd::note_memory_guard_unreachable(cpu, 90); + check(health.level("RAM") == 1 && health.level("CPU") == 2, "the memory guard of the CPU speaks for the RAM"); + check(sd::health_scaled_bytes(cpu, 1000) == 700, "a budget on a device is scaled by its share"); + check(same(health.ram_share(), 0.85), "the RAM offers its share"); + for (int i = 0; i < 3; ++i) { + advance(10); + sd::note_memory_guard_unreachable(cpu, 90); + } + check(health.level("RAM") == 4 && same(health.ram_share(), 0.55), + "but nothing runs without RAM: past the last level of strain it keeps the smallest share"); + sd::note_disk_read_failure("model.safetensors"); + states = health.snapshot(); + const auto* disk = find(states, "disk"); + check(disk != nullptr && disk->level == 1 && disk->reason.find("model.safetensors") != std::string::npos, + "a failed read raises the disk and names the file"); + if (cpu != nullptr) { + ggml_backend_free(cpu); + } + health.set_clock(nullptr); + health.set_component_lister(nullptr); + health.reset(); +} + +int main() { + test_starts_healthy(); + test_engine_events_rise_one_step_each(); + test_quiet_periods_bring_the_levels_back(); + test_signals_hold_a_level_while_they_last(); + test_each_source_holds_one_signal(); + test_critical_signals(); + test_signals_reach_the_same_card(); + test_invalid_signals_are_refused(); + test_resume(); + test_cpu_threads(); + test_settings(); + test_snapshot_and_revision(); + test_backend_names(); + test_engine_hooks(); + test_c_api(); + + std::printf("\n%s (%d failures)\n", failures == 0 ? "ALL TESTS PASSED" : "TESTS FAILED", failures); + return failures == 0 ? 0 : 1; +} diff --git a/test/layer_split_fill_test.cpp b/test/layer_split_fill_test.cpp index 25dc7d9e..0b9882a6 100644 --- a/test/layer_split_fill_test.cpp +++ b/test/layer_split_fill_test.cpp @@ -84,6 +84,35 @@ int main() { "every byte is placed and no device gets more than its capacity"); } + { + const std::vector capacities = {10 * GiB, 10 * GiB}; + check(sd::layer_split_apply_shares(capacities, {1.0, 1.0}) == capacities, "healthy devices offer all of their capacity"); + const auto strained = sd::layer_split_apply_shares(capacities, {0.70, 1.0}); + check(strained[0] == 7 * GiB && strained[1] == 10 * GiB, "a device under strain at 70% offers 70% of its capacity"); + + const auto fill_first = place(LayerSplitFill::FILL_FIRST, segments, strained); + check(fill_first.size() == 2 && near(fill_first[0], 7 * GiB, segments[0]) && near(fill_first[1], GiB, segments[0]), + "fill-first: the next device takes what the device under strain gives up"); + const auto healthy = place(LayerSplitFill::PROPORTIONAL, segments, capacities); + const auto proportional = place(LayerSplitFill::PROPORTIONAL, segments, strained); + check(proportional.size() == 2 && near(proportional[0], 8 * GiB * 7 / 17, segments[0]) && + near(proportional[1], 8 * GiB * 10 / 17, segments[0]), + "proportional: what it gives up is spread in proportion to the capacities"); + check(!healthy.empty() && !proportional.empty() && proportional[0] < healthy[0], + "so the device under strain holds less than when it was healthy"); + + const auto excluded = place(LayerSplitFill::PROPORTIONAL, segments, sd::layer_split_apply_shares(capacities, {0.0, 1.0})); + check(excluded.size() == 2 && excluded[0] == 0 && excluded[1] == 8 * GiB, "an excluded device takes nothing"); + check(place(LayerSplitFill::FILL_FIRST, segments, sd::layer_split_apply_shares({10 * GiB, 5 * GiB}, {0.0, 1.0})).empty(), + "when the others cannot hold what an excluded device leaves, nothing is placed"); + check(place(LayerSplitFill::PROPORTIONAL, segments, sd::layer_split_apply_shares(capacities, {1.0, 1.0})) == healthy, + "when the device recovers, its share comes back"); + + const auto unknown = sd::layer_split_apply_shares({sd::layer_split_unknown_capacity, 10 * GiB}, {0.85, 1.0}); + check(unknown[0] == sd::layer_split_unknown_capacity, "a capacity the device does not report stays unknown"); + check(sd::layer_split_apply_shares({sd::layer_split_unknown_capacity}, {0.0})[0] == 0, "unless the device is excluded"); + } + const auto gpu = GGML_BACKEND_DEVICE_TYPE_GPU; const auto igpu = GGML_BACKEND_DEVICE_TYPE_IGPU; const auto cpu = GGML_BACKEND_DEVICE_TYPE_CPU; diff --git a/test/server_guardian_e2e.py b/test/server_guardian_e2e.py new file mode 100644 index 00000000..7227b1b1 --- /dev/null +++ b/test/server_guardian_e2e.py @@ -0,0 +1,477 @@ +#!/usr/bin/env python3 +"""End-to-end test of the guardian of sd-server and of the reports of outside watchers, on a real server. + +It needs a real model, any model the server can load, on any backend; the jobs are small (64x64). The standard +library is enough. + + python3 test/server_guardian_e2e.py --server build/bin/sd-server --model /path/to/model.safetensors + +Through POST /sdcpp/v1/devices/{device}/pressure it checks that: + - a report that is not valid is refused, and one for a device the server does not have is 404; + - a level of strain on the RAM leaves the server working; + - the RAM reported critical while a job generates halts the server: the job ends with the code halted, the queued + job waits, new work is refused with 503 and Retry-After, and the server resumes by itself when the signal ends; + - the same while a synchronous request generates: the request is answered 503 with the code halted; + - every compute device reported critical while a job computes on it: the job stops, the model is not loaded + anywhere else, and the server stays halted after the signals until an operator resumes it + (POST /sdcpp/v1/guardian/resume); + - a second server with --guardian off never halts: a critical report only changes device health; + - termico.py osserva --segnala, with the fake GPU of test/termico_test.py, reports to that server. + +The test starts its servers with an API key of its own, to check that the reports need it. Extra options for the +servers (a backend, ...) go after --extra, one each, for example --extra=--backend --extra=cpu. To use a server that +is already running: --url http://127.0.0.1:1234 (add --api-key if it asks for one); the scenario with --guardian off +and the checks of the server log are then skipped, and the server is left with signals of the source "e2e" that end +within two minutes. Exit code 0 = all checks passed. +""" +import argparse +import importlib.util +import json +import os +import re +import secrets +import shutil +import socket +import subprocess +import sys +import tempfile +import threading +import time +import urllib.error +import urllib.parse +import urllib.request + +failures = 0 +FINAL = ("completed", "failed", "cancelled") + + +def check(condition, message): + global failures + if condition: + print("ok: " + message, flush=True) + else: + print("FAIL: " + message, flush=True) + failures += 1 + return condition + + +class Abort(Exception): + """The test cannot go on: what comes next depends on what just failed.""" + + +def wait_until(condition, timeout, interval=0.2): + started = time.time() + while time.time() - started < timeout: + if condition(): + return True + time.sleep(interval) + return condition() + + +class Client: + def __init__(self, base_url, api_key): + self.base_url = base_url.rstrip("/") + self.api_key = api_key + + def call(self, method, path, body=None, timeout=120, raw=None): + """Returns the status, the JSON body (or the text when it is not JSON) and the headers.""" + data = raw if raw is not None else (None if body is None else json.dumps(body).encode()) + headers = {"Content-Type": "application/json"} + if self.api_key: + headers["Authorization"] = "Bearer " + self.api_key + request = urllib.request.Request(self.base_url + path, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + status, payload, answer_headers = response.status, response.read(), response.headers + except urllib.error.HTTPError as error: + status, payload, answer_headers = error.code, error.read(), error.headers + try: + parsed = json.loads(payload) if payload else None + except ValueError: + parsed = payload.decode(errors="replace") + return status, parsed, answer_headers + + def health(self): + return self.call("GET", "/sdcpp/v1/health") + + def pressure(self, device, body): + return self.call("POST", "/sdcpp/v1/devices/%s/pressure" % urllib.parse.quote(device, safe=""), body) + + def submit(self, steps, seed, size): + status, job, _ = self.call("POST", "/sdcpp/v1/img_gen", generation_body(steps, seed, size)) + if status != 202: + raise Abort("the server did not accept a job: %s %s" % (status, job)) + return job["id"] + + def job(self, job_id): + return self.call("GET", "/sdcpp/v1/jobs/" + job_id)[1] + + def wait_for(self, job_id, wanted, timeout): + started = time.time() + while time.time() - started < timeout: + job = self.job(job_id) + if job["status"] in wanted: + return job + if job["status"] in FINAL: + raise Abort("job %s ended as %s, expected %s: %s" % (job_id, job["status"], wanted, job.get("error"))) + time.sleep(0.1) + raise Abort("job %s did not become %s within %d s" % (job_id, wanted, timeout)) + + +def generation_body(steps, seed, size): + return {"prompt": "a test", "width": size, "height": size, "seed": seed, "sample_params": {"sample_steps": steps}} + + +def is_halted_refusal(status, body, headers): + try: + retry_after = int(headers.get("Retry-After", "0")) + except ValueError: + retry_after = 0 + return status == 503 and isinstance(body, dict) and body.get("code") == "halted" and retry_after >= 10 + + +def free_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def start_server(args, log, extra=()): + port = free_port() + command = [args.server, "-m", args.model, "--listen-ip", "127.0.0.1", "--listen-port", str(port)] + command += ["--api-key", args.api_key] + args.extra + list(extra) + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + return process, "http://127.0.0.1:%d" % port + + +def wait_ready(client, process, timeout): + started = time.time() + while time.time() - started < timeout: + if process is not None and process.poll() is not None: + raise Abort("the server stopped at start-up (exit code %s)" % process.returncode) + try: + status, health, _ = client.call("GET", "/sdcpp/v1/health", timeout=5) + if status == 200 and health.get("status") in ("ok", "degraded"): + return health + except (urllib.error.URLError, OSError): + pass + time.sleep(0.5) + raise Abort("the server was not ready after %d s" % timeout) + + +def stop_server(process): + if process is None: + return + process.terminate() + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + process.kill() + + +def device(answer, name): + for entry in answer.get("devices", []) if isinstance(answer, dict) else []: + if entry["name"].lower() == name.lower(): + return entry + return {} + + +def run_scenarios(client, args): + size = args.size + print("warming up (the first generation may read the weights from disk)...", flush=True) + warm = client.wait_for(client.submit(2, 1, size), ("completed",), args.warmup_timeout) + check(warm["status"] == "completed", "warm-up job completed") + + # 1. The health shows the guardian and every component of device health. + status, health, _ = client.health() + guardian = health.get("guardian", {}) if isinstance(health, dict) else {} + check(status == 200 and guardian.get("enabled") is True and guardian.get("halted") is False, + "the health reports the guardian, on and not halted") + names = [entry["name"] for entry in health.get("devices", [])] + check({"CPU", "RAM", "disk"} <= set(names), "and the components of device health: %s" % ", ".join(names)) + check(names and all(entry["level"] == 0 and entry["share_percent"] == 100 and not entry["excluded"] for entry in health["devices"]), + "all of them healthy at the start") + compute = [name for name in names if name.lower() not in ("ram", "disk")] + before = health.get("counters", {}) + start_status = health.get("status") + if not compute: + raise Abort("the health lists no compute device") + + # 2. Reports that are not valid. + status, body, _ = client.pressure("NoSuchDevice0", {"level": 1}) + check(status == 404 and isinstance(body, dict) and body.get("code") == "unknown_device", "a report for a device the server does not have is 404") + for wrong in ({"level": 9}, {"level": "hot"}, {"level": 1, "duration_seconds": 0}, {"level": 1, "source": "two words"}, {"lvl": 1}): + status, body, _ = client.pressure("RAM", wrong) + check(status == 400 and isinstance(body, dict) and body.get("code") == "invalid_report" and body.get("error"), + "a report that is not valid is 400 with the reason: %s" % json.dumps(wrong)) + status, body, _ = client.call("POST", "/sdcpp/v1/devices/RAM/pressure", raw=b"not json") + check(status == 400, "a body that is not JSON is 400") + if client.api_key: + anonymous = Client(client.base_url, None) + check(anonymous.pressure("RAM", {"level": 1})[0] == 401, "a report without the API key is refused") + check(anonymous.call("POST", "/sdcpp/v1/guardian/resume")[0] == 401, "and so is a resume") + check(device(client.health()[1], "RAM").get("level") == 0, "none of them changed device health") + + # 3. A level of strain: the server keeps working. + status, body, _ = client.pressure("ram", {"level": 2, "source": "e2e", "reason": "test strain", "duration_seconds": 30}) + ram = body.get("device", {}) if isinstance(body, dict) else {} + check(status == 200 and ram.get("name") == "RAM" and ram.get("level") == 2 and ram.get("share_percent") == 70, + "the RAM reported at level 2 (its name in any case) offers 70%% of its capacity (got %s %s)" % (status, body)) + check("e2e: test strain" in ram.get("reason", "") and ram.get("held_ms", 0) > 25000, + "the reason names the source, and the signal is held for the time given") + check(isinstance(body, dict) and body.get("guardian", {}).get("halted") is False, "strain does not halt the server") + done = client.wait_for(client.submit(2, 2, size), ("completed",), args.warmup_timeout) + check(done["status"] == "completed", "a job completes with the RAM under strain") + status, body, _ = client.pressure("RAM", {"level": 0, "source": "e2e"}) + ram = body.get("device", {}) if isinstance(body, dict) else {} + check(status == 200 and ram.get("held_ms") == 0 and ram.get("level") == 2 and ram.get("next_step_ms", 0) > 0, + "withdrawing the signal leaves the level, which comes down one step after each quiet period") + + # 4. The RAM reported critical while a job generates. + running = client.submit(args.steps, 3, size) + client.wait_for(running, ("generating",), 60) + queued = client.submit(2, 4, size) + time.sleep(1.0) + status, body, _ = client.pressure("RAM", {"level": "critical", "source": "e2e", "reason": "test overheat", "duration_seconds": args.critical_seconds}) + halted_at = time.time() + state = body.get("guardian", {}) if isinstance(body, dict) else {} + check(status == 200 and state.get("halted") is True and "RAM is critical" in state.get("reason", ""), + "a critical report halts the server at once (got %s %s)" % (status, body)) + job = {} + if wait_until(lambda: client.job(running)["status"] in FINAL, 30): + job = client.job(running) + error = job.get("error") or {} + check(job.get("status") == "failed" and error.get("code") == "halted" and "test overheat" in error.get("message", ""), + "the job that was generating ends with the code halted and the reason (%s)" % json.dumps(error)) + check(time.time() - halted_at < 15, "within seconds of the report (%.1f s)" % (time.time() - halted_at)) + check(client.job(queued)["status"] == "queued", "the queued job waits") + refused = [ + ("POST", "/sdcpp/v1/img_gen", generation_body(2, 5, size)), + ("POST", "/sdapi/v1/txt2img", {"prompt": "a test", "width": size, "height": size, "steps": 2}), + ("POST", "/v1/images/generations", {"prompt": "a test", "size": "%dx%d" % (size, size)}), + ("POST", "/sdcpp/v1/dgl/jobs", {"source": "x"}), + ("POST", "/sdcpp/v1/models/load", {}), + ] + for method, path, request_body in refused: + status, answer, headers = client.call(method, path, request_body) + check(is_halted_refusal(status, answer, headers), + "%s %s is refused with 503, the code halted and Retry-After (got %s %s)" % (method, path, status, answer)) + status, health, headers = client.health() + check(is_halted_refusal(status, {"code": "halted"} if health.get("status") == "halted" else {}, headers) and + health.get("guardian", {}).get("halted") is True, "the health says halted, with 503 and Retry-After") + check(device(health, "RAM").get("critical") is True, "and shows the RAM critical") + check(client.call("GET", "/sdcpp/v1/jobs/" + queued)[0] == 200, "polling a job still works") + check(client.pressure("disk", {"level": 1, "source": "e2e", "duration_seconds": 5})[0] == 200, "and so do reports") + check(wait_until(lambda: client.health()[0] == 200, args.critical_seconds + 20), + "the server resumes by itself when the critical signal ends") + status, health, _ = client.health() + ram = device(health, "RAM") + check(health.get("guardian", {}).get("halted") is False and ram.get("excluded") is True and ram.get("critical") is False, + "the RAM stays excluded for a while, which does not halt the server: it is not a compute device") + done = client.wait_for(queued, ("completed",), args.warmup_timeout) + check(done["status"] == "completed", "the job that waited runs and completes") + + # 5. The same while a synchronous request generates. + outcome = {} + + def synchronous_request(): + outcome["result"] = client.call("POST", "/sdapi/v1/txt2img", { + "prompt": "a sync test", "width": size, "height": size, "steps": args.steps, "seed": 7, + }, timeout=args.warmup_timeout) + + thread = threading.Thread(target=synchronous_request) + thread.start() + check(wait_until(lambda: client.health()[1].get("busy") is True, 60), "a synchronous request generates") + time.sleep(1.0) + client.pressure("RAM", {"level": "critical", "source": "e2e", "reason": "test overheat again", "duration_seconds": args.critical_seconds}) + thread.join(60) + status, answer, headers = outcome.get("result", (None, None, {})) + check(is_halted_refusal(status, answer, headers), + "the synchronous request is stopped and answered 503 with the code halted (got %s %s)" % (status, answer)) + check(wait_until(lambda: client.health()[0] == 200, args.critical_seconds + 20), "the server resumes by itself again") + + # 6. Every compute device reported critical while a job generates on it, as a thermal watcher does: the engine + # refuses the excluded device, and the server must stop rather than load the model somewhere else. When the + # signals end the devices are still excluded, so the server stays halted until an operator resumes it. + running = client.submit(args.steps, 6, size) + client.wait_for(running, ("generating",), 60) + time.sleep(1.0) + for name in compute: + client.pressure(name, {"level": "critical", "source": "e2e", "reason": "test overheat of " + name, "duration_seconds": args.critical_seconds}) + job = {} + if wait_until(lambda: client.job(running)["status"] in FINAL, 30): + job = client.job(running) + error = job.get("error") or {} + check(job.get("status") == "failed" and error.get("code") == "halted", + "with every compute device (%s) critical, the job that computes on them ends with the code halted (%s)" % (", ".join(compute), json.dumps(error))) + state = {} + + def no_compute_device_left(): + state.update(client.health()[1].get("guardian", {})) + return "no compute device" in state.get("reason", "") + + check(wait_until(no_compute_device_left, args.critical_seconds + 20) and state.get("halted") is True, + "when the critical signals end the devices are still excluded: the server stays halted (%s)" % state.get("reason")) + status, answer, headers = client.call("POST", "/sdcpp/v1/img_gen", generation_body(2, 7, size)) + check(is_halted_refusal(status, answer, headers), "and refuses work") + status, body, _ = client.call("POST", "/sdcpp/v1/guardian/resume") + check(status == 200 and isinstance(body, dict) and body.get("guardian", {}).get("halted") is False, + "an operator who has checked the machine resumes the server") + check(all(device(body, name).get("level") == device(body, name).get("strain_levels") and device(body, name).get("excluded") is False + for name in compute), + "the excluded devices come back at the last level of strain") + done = client.wait_for(client.submit(2, 8, size), ("completed",), args.warmup_timeout) + check(done["status"] == "completed", "and the server works again, with the model where it was") + for name in compute: + client.pressure(name, {"level": 0, "source": "e2e"}) + + # 7. The keeper is where it was. + status, health, _ = client.health() + now = health.get("counters", {}) + check(status == 200 and health.get("status") == start_status, "the halts did not move the model: the status is %s as at the start" % health.get("status")) + check(now.get("step_downs") == before.get("step_downs") and now.get("failed") == before.get("failed") and + now.get("device_switches") == before.get("device_switches") and now.get("retries") == before.get("retries"), + "no step down, no device switch, no failure: the work the guardian stopped counts as stopped") + check(now.get("cancelled", 0) - before.get("cancelled", 0) == 3, "the two jobs and the request that the guardian stopped count as cancelled") + + +def run_termico(client, args): + """termico.py osserva --segnala with the fake GPU of test/termico_test.py, at 82 C (the attention band): its + report reaches the server as level 1 of the CPU, named explicitly so that the scenario does not depend on the + GPUs of the machine, and is withdrawn when termico.py ends.""" + here = os.path.dirname(os.path.abspath(__file__)) + termico = os.path.join(here, "..", "scripts", "diagnostica_termica", "termico.py") + spec = importlib.util.spec_from_file_location("termico_test", os.path.join(here, "termico_test.py")) + fakes = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fakes) + folder = tempfile.mkdtemp(prefix="termico-e2e-") + try: + fake_gpu = os.path.join(folder, "nvidia-smi-finto.py") + with open(fake_gpu, "w") as handle: + handle.write(fakes.GPU_FINTA) + for name, value in (("temp", "82"), ("mask", "0000000000000004")): + with open(os.path.join(folder, name), "w") as handle: + handle.write(value) + environment = dict(os.environ, FAKE_DIR=folder) + environment.pop("TERMICO_CHIAVE_API", None) + command = [sys.executable, "-I", termico, "osserva", "--nvidia-smi", fake_gpu, "--motore", client.base_url, + "--chiave-api", args.api_key, "--segnala", "CPU", "--durata", "5", "--ogni", "0.5", + "--uscita", os.path.join(folder, "uscita")] + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", + env=environment, stdin=subprocess.DEVNULL) + cpu = {} + + def reported(): + cpu.update(device(client.health()[1], "CPU")) + return cpu.get("level") == 1 and cpu.get("held_ms", 0) > 0 + + seen = wait_until(reported, 10) + output, _ = process.communicate(timeout=60) + check(seen and "termico: GPU a 82 C, fascia attenzione" in cpu.get("reason", ""), + "termico.py --segnala: the attention band reaches the server as level 1, with the reason (%s)" % cpu.get("reason")) + after = device(client.health()[1], "CPU") + check(process.returncode == 0 and after.get("held_ms") == 0 and after.get("level") == 1, + "termico.py --segnala: when it ends its signal is withdrawn, and the level comes down with the quiet periods") + check(args.api_key not in output, "termico.py --segnala: the API key does not appear in its output") + finally: + shutil.rmtree(folder, ignore_errors=True) + + +def run_guardian_off(args, log_path): + with open(log_path, "wb") as log: + process, base_url = start_server(args, log, ["--guardian", "off"]) + client = Client(base_url, args.api_key) + try: + health = wait_ready(client, process, args.start_timeout) + check(health.get("guardian", {}).get("enabled") is False, "--guardian off: the health says the guardian is off") + status, body, _ = client.pressure("RAM", {"level": "critical", "source": "e2e", "reason": "test overheat", "duration_seconds": 30}) + check(status == 200 and device({"devices": [body.get("device", {})]}, "RAM").get("critical") is True and + body.get("guardian", {}).get("halted") is False, + "--guardian off: a critical report reaches device health but does not halt the server") + done = client.wait_for(client.submit(2, 8, args.size), ("completed",), args.warmup_timeout) + check(done["status"] == "completed", "--guardian off: the server keeps working") + run_termico(client, args) + finally: + stop_server(process) + + +def log_lines(path, offset=0): + with open(path, "rb") as handle: + handle.seek(offset) + return handle.read().decode(errors="replace") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--server", default="build/bin/sd-server", help="path to sd-server") + parser.add_argument("--model", help="model for the servers to load") + parser.add_argument("--url", help="use a server that is already running instead of starting one") + parser.add_argument("--api-key", help="API key of the server (default: one of the test's own for the servers it starts)") + parser.add_argument("--extra", action="append", default=[], help="an extra option for sd-server (repeatable)") + parser.add_argument("--size", type=int, default=64, help="width and height of the images (default 64, the minimum)") + parser.add_argument("--steps", type=int, default=100, help="steps of the generations that get stopped, at most 100") + parser.add_argument("--critical-seconds", type=int, default=6, help="how long the critical reports last (default 6)") + parser.add_argument("--start-timeout", type=int, default=300, help="seconds to wait for a server to load the model") + parser.add_argument("--warmup-timeout", type=int, default=900, help="seconds for any job that must complete") + args = parser.parse_args() + if not args.url and not args.model: + parser.error("give --model (and --server), or --url of a running server") + if not args.url and not args.api_key: + args.api_key = "e2e-" + secrets.token_hex(8) + + process = None + log = None + log_path = None + if args.url: + base_url = args.url + else: + handle, log_path = tempfile.mkstemp(prefix="sd-server-guardian-", suffix=".log") + os.close(handle) + log = open(log_path, "wb") + process, base_url = start_server(args, log) + + client = Client(base_url, args.api_key) + try: + wait_ready(client, process, args.start_timeout) + run_scenarios(client, args) + except Abort as error: + check(False, str(error)) + finally: + stop_server(process) + if log is not None: + log.close() + + off_log_path = None + if not args.url: + handle, off_log_path = tempfile.mkstemp(prefix="sd-server-guardian-off-", suffix=".log") + os.close(handle) + try: + run_guardian_off(args, off_log_path) + except Abort as error: + check(False, "--guardian off: " + str(error)) + + if log_path is not None: + text = log_lines(log_path) + check("guardian: the server stops all work: RAM is critical: e2e: test overheat" in text, + "the server log says when and why the server stopped all work") + check(re.search(r"job \S+ stopped by the guardian", text) is not None, "it names the job that the guardian stopped") + check("guardian: the cause has ended, the server resumes work" in text, "it says when the server resumed by itself") + check("guardian: an operator says the machine was checked" in text, "and when an operator resumed it") + # The engine may meet a device that has just been excluded before the stop reaches it, and says so. + refused = "the engine does not compute on it" + for path in (log_path, off_log_path): + errors = [line for line in re.findall(r"\[E\][^\r\n]*", log_lines(path)) if refused not in line] if path else [] + check(not errors, "the server writes no other error line to its log" + (": " + errors[0] if errors else "")) + if failures: + print("server logs kept at " + log_path + (" and " + off_log_path if off_log_path else "")) + else: + os.remove(log_path) + if off_log_path: + os.remove(off_log_path) + + print("\n%s (%d failures)" % ("TEST FAILED" if failures else "ALL TESTS PASSED", failures)) + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test/server_guardian_test.cpp b/test/server_guardian_test.cpp new file mode 100644 index 00000000..cbc22bf9 --- /dev/null +++ b/test/server_guardian_test.cpp @@ -0,0 +1,342 @@ +// Test of the guardian of the server (examples/server/guardian.*): when it stops all work (a component reported as +// critical, or no compute device left because every GPU and the CPU are excluded by device health), when it +// resumes, how long it tells clients to wait, that the halt starts once, the operator's resume, what +// /sdcpp/v1/health shows, and the watcher that stops the work when no request comes. The registry of device health +// is replaced by scripted components, so no model or device is needed. +// Build (from the repository root, after building the library into build/); the sources go in one command: +// c++ -std=c++17 -Iexamples -Iexamples/server -Iinclude -Ithirdparty -Isrc test/server_guardian_test.cpp +// examples/server/guardian.cpp examples/common/log.cpp +// -Lbuild/bin -lstable-diffusion -Wl,-rpath,build/bin -pthread -o server_guardian_test +// Run: ./server_guardian_test ; exit code 0 = all checks passed. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "httplib.h" + +#include "guardian.h" + +static int failures = 0; + +static void check(bool condition, const char* what) { + std::printf("%s %s\n", condition ? "ok: " : "FAIL:", what); + failures += condition ? 0 : 1; +} + +static sd_device_health_t component(const char* name, int level, const char* reason = "") { + sd_device_health_t entry{}; + std::snprintf(entry.name, sizeof(entry.name), "%s", name); + std::snprintf(entry.reason, sizeof(entry.reason), "%s", reason); + entry.level = level; + entry.strain_levels = 3; + entry.excluded = level > 3; + entry.share_percent = level > 3 ? 0 : 100 - 15 * level; + return entry; +} + +struct Machine { + std::vector components = {component("Vulkan0", 0), component("CPU", 0), component("RAM", 0), component("disk", 0)}; + int resumes = 0; + + Guardian::Hooks hooks() { + Guardian::Hooks hooks; + hooks.read_health = [this] { return components; }; + hooks.resume_health = [this] { ++resumes; }; + return hooks; + } + sd_device_health_t& find(const char* name) { + for (auto& entry : components) { + if (std::strcmp(entry.name, name) == 0) { + return entry; + } + } + return components.front(); + } +}; + +static void test_healthy_and_disabled() { + Machine machine; + Guardian guardian(true, machine.hooks()); + check(!guardian.evaluate().halted, "a healthy machine is not halted"); + machine.find("Vulkan0") = component("Vulkan0", 2, "termico: 84 C"); + check(!guardian.evaluate().halted, "a device under strain does not halt the server: it only gives up work"); + + Machine other; + other.find("CPU") = component("CPU", 4, "guardiano: stop"); + other.find("CPU").critical = true; + Guardian off(false, other.hooks()); + check(!off.enabled() && !off.evaluate().halted, "a guardian that is off never halts the server"); +} + +static void test_critical_signal() { + Machine machine; + Guardian guardian(true, machine.hooks()); + machine.find("Vulkan0") = component("Vulkan0", 4, "termico: 95 C"); + machine.find("Vulkan0").critical = true; + machine.find("Vulkan0").held_ms = 42500; + bool started = false; + const auto state = guardian.evaluate(&started); + check(state.halted && started, "a critical component halts the server, and this evaluation is the one that starts the halt"); + check(state.reason.find("Vulkan0") != std::string::npos && state.reason.find("95 C") != std::string::npos, + "the reason names the component and why"); + check(state.retry_after_seconds == 43, "clients are told to come back when the critical signal ends"); + bool again = true; + check(guardian.evaluate(&again).halted && !again, "the halt starts once"); + machine.find("Vulkan0").held_ms = 2000; + check(guardian.evaluate().retry_after_seconds == 10, "and never sooner than ten seconds"); + machine.find("Vulkan0").critical = false; + machine.find("Vulkan0").held_ms = 0; + check(!guardian.evaluate().halted, "when the critical signal ends, the server resumes, even if the device is still excluded"); +} + +// A refused request reads the registry too, so it may be the first to see a halt; the start of the halt must still +// reach whoever stops the work, once. +static void test_halt_seen_first_by_a_request() { + Machine machine; + Guardian guardian(true, machine.hooks()); + machine.find("Vulkan0") = component("Vulkan0", 4, "termico: 95 C"); + machine.find("Vulkan0").critical = true; + httplib::Response res; + check(refuse_while_halted(&guardian, res), "a request is the first to see the halt"); + bool started = false; + check(guardian.evaluate(&started).halted && started, "the start of the halt still reaches the first caller that asks for it"); + bool again = true; + check(guardian.evaluate(&again).halted && !again, "only once"); + + machine.find("Vulkan0").critical = false; + check(!guardian.evaluate().halted, "the cause ends"); + machine.find("Vulkan0").critical = true; + check(guardian.evaluate().halted, "a second halt, seen by a request"); + machine.find("Vulkan0").critical = false; + check(!guardian.evaluate().halted, "ends before anyone asked for its start"); + bool stale = true; + guardian.evaluate(&stale); + check(!stale, "a halt that has ended leaves nothing to stop"); +} + +static void test_no_compute_device_left() { + Machine machine; + Guardian guardian(true, machine.hooks()); + machine.find("Vulkan0") = component("Vulkan0", 4, "compute failed"); + check(!guardian.evaluate().halted, "with the GPU excluded the CPU is still there"); + machine.find("RAM") = component("RAM", 4, "memory guard"); + machine.find("disk") = component("disk", 4, "read failed"); + check(!guardian.evaluate().halted, "the RAM and the disk are not compute devices"); + machine.find("CPU") = component("CPU", 4, "compute failed"); + machine.find("Vulkan0").next_step_ms = 120000; + machine.find("CPU").next_step_ms = 60000; + bool started = false; + const auto state = guardian.evaluate(&started); + check(state.halted && started && state.reason.find("no compute device") != std::string::npos, + "with every GPU and the CPU excluded the server halts"); + check(state.retry_after_seconds == 60, "and tells clients to come back when the first device returns"); + machine.find("CPU") = component("CPU", 3, "compute failed"); + check(!guardian.evaluate().halted, "it resumes as soon as one compute device is back"); +} + +static void test_resume_and_json() { + Machine machine; + Guardian guardian(true, machine.hooks()); + machine.find("CPU") = component("CPU", 4, "guardiano: stop"); + machine.find("CPU").critical = true; + check(guardian.evaluate().halted, "halted by a critical CPU"); + auto health = guardian.health_json(); + check(health["guardian"]["halted"] == true && health["guardian"]["enabled"] == true && + health["guardian"]["reason"].get().find("CPU") != std::string::npos && health["guardian"]["since"].get() > 0, + "the health shows the halt, why and since when"); + check(health["devices"].is_array() && health["devices"].size() == 4 && health["devices"][1]["name"] == "CPU" && + health["devices"][1]["excluded"] == true && health["devices"][1]["critical"] == true && health["devices"][1]["share_percent"] == 0, + "and every component with its level and share"); + machine.find("CPU") = component("CPU", 3, "resumed by an operator"); + const auto state = guardian.resume(); + check(machine.resumes == 1 && !state.halted, "the operator's resume reaches the registry and the server resumes"); + health = guardian.health_json(); + check(health["guardian"]["halted"] == false && health["guardian"]["reason"] == "", "and the health shows it"); +} + +static void test_refusal() { + Machine machine; + Guardian guardian(true, machine.hooks()); + httplib::Response res; + check(!refuse_while_halted(&guardian, res), "a request goes through while the server is not halted"); + check(!refuse_while_halted(nullptr, res), "and when there is no guardian"); + machine.find("Vulkan0") = component("Vulkan0", 4, "termico: 95 C"); + machine.find("Vulkan0").critical = true; + machine.find("Vulkan0").held_ms = 30000; + check(refuse_while_halted(&guardian, res), "a request is refused while the server is halted"); + const auto body = nlohmann::json::parse(res.body, nullptr, false); + check(res.status == 503 && res.get_header_value("Retry-After") == "30" && body.is_object() && body["code"] == "halted" && + body["error"].get().find("95 C") != std::string::npos, + "with 503, the code halted, the reason and Retry-After"); +} + +// The body of POST /sdcpp/v1/devices/{device}/pressure. +static void test_pressure_report() { + auto parse = [](const char* text, PressureReport& report, std::string& error) { + report = PressureReport(); + error.clear(); + return parse_pressure_report(nlohmann::json::parse(text), 3, report, error); + }; + PressureReport report; + std::string error; + check(parse(R"({"level": 2})", report, error) && report.level == 2 && !report.critical && report.source == "http" && + report.duration_seconds == 60 && report.reason.empty(), + "a level of strain, with the defaults: source http, one minute, no reason"); + check(parse(R"({"level": 0, "source": "termico"})", report, error) && report.level == 0 && report.source == "termico", + "level 0 withdraws the signal of a source"); + check(parse(R"({"level": "excluded"})", report, error) && report.level == 4 && !report.critical, "excluded is the level after the last strain"); + check(parse(R"({"level": 4})", report, error) && report.level == 4 && !report.critical, "and so is that number"); + check(parse(R"({"level": "critical", "reason": "95 C", "duration_seconds": 30, "source": "termico.cpu-1"})", report, error) && + report.level == 4 && report.critical && report.reason == "95 C" && report.duration_seconds == 30 && report.source == "termico.cpu-1", + "critical excludes the device and asks to stop all work, for the time given"); + check(parse(R"({"level": 1, "duration_seconds": 86400})", report, error) && report.duration_seconds == 86400, "a signal lasts a day at most"); + + const char* invalid[] = { + R"([])", + R"({})", + R"({"level": 5})", + R"({"level": -1})", + R"({"level": 2.5})", + R"({"level": "hot"})", + R"({"level": true})", + R"({"level": 1, "duration_seconds": 0})", + R"({"level": 1, "duration_seconds": 86401})", + R"({"level": 1, "duration_seconds": "60"})", + R"({"level": 1, "source": ""})", + R"({"level": 1, "source": "a b"})", + R"({"level": 1, "source": "123456789012345678901234567890123"})", + R"({"level": 1, "reason": 5})", + R"({"level": 1, "reason": "two\nlines"})", + R"({"level": 1, "duration": 30})", + }; + for (const char* text : invalid) { + const bool accepted = parse(text, report, error); + check(!accepted && !error.empty(), (std::string("refused, with the reason: ") + text + (error.empty() ? "" : " -> " + error)).c_str()); + } +} + +static bool wait_until(const std::function& condition, std::chrono::milliseconds limit) { + const auto deadline = std::chrono::steady_clock::now() + limit; + while (!condition()) { + if (std::chrono::steady_clock::now() >= deadline) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + return true; +} + +// The work must stop even when no request comes: the watcher reads the registry on a thread of its own. +static void test_watcher() { + std::mutex mutex; + bool critical = false; + std::atomic reads{0}; + Guardian::Hooks hooks; + hooks.read_health = [&] { + std::lock_guard lock(mutex); + ++reads; + std::vector components = {component("Vulkan0", critical ? 4 : 0, critical ? "termico: 95 C" : ""), component("CPU", 0)}; + components[0].critical = critical; + return components; + }; + auto set_critical = [&](bool value) { + std::lock_guard lock(mutex); + critical = value; + }; + std::atomic halts{0}; + std::string reason; + auto on_halt = [&](const Guardian::State& state) { + std::lock_guard lock(mutex); + reason = state.reason; + ++halts; + }; + + { + Guardian guardian(true, hooks); + guardian.watch(on_halt, std::chrono::milliseconds(20)); + set_critical(true); + check(wait_until([&] { return halts == 1; }, std::chrono::seconds(5)), "the watcher sees a halt by itself and stops the work"); + { + std::lock_guard lock(mutex); + check(reason.find("95 C") != std::string::npos, "it knows why the server halted"); + } + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + check(halts == 1, "it stops the work once per halt"); + set_critical(false); + check(wait_until([&] { return !guardian.evaluate().halted; }, std::chrono::seconds(5)), "the cause ends"); + set_critical(true); + check(wait_until([&] { return halts == 2; }, std::chrono::seconds(5)), "a second halt stops the work again"); + } + + set_critical(false); + const int before = halts; + { + auto guardian = std::make_unique(true, hooks); + reads = 0; + guardian->watch(on_halt, std::chrono::hours(1)); + check(wait_until([&] { return reads >= 1; }, std::chrono::seconds(5)), "the watcher reads the registry when it starts"); + set_critical(true); + guardian->check_now(); + check(wait_until([&] { return halts == before + 1; }, std::chrono::seconds(5)), + "check_now makes it read the registry at once, without waiting for the period"); + const auto start = std::chrono::steady_clock::now(); + guardian.reset(); + check(std::chrono::steady_clock::now() - start < std::chrono::seconds(2), "the guardian ends its watcher at once when it ends"); + } + + { + Guardian off(false, hooks); + const int reads_before = reads; + off.watch(on_halt, std::chrono::milliseconds(20)); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + check(halts == before + 1 && reads == reads_before, "a guardian that is off does not watch"); + } + + { + std::atomic thrown{false}; + Guardian::Hooks failing = hooks; + failing.read_health = [&] { + if (!thrown.exchange(true)) { + throw std::runtime_error("the registry cannot be read"); + } + return hooks.read_health(); + }; + Guardian guardian(true, failing); + guardian.watch(on_halt, std::chrono::milliseconds(20)); + check(wait_until([&] { return halts == before + 2; }, std::chrono::seconds(5)) && thrown, + "a failure to read the registry does not end the watcher"); + } + + { + set_critical(false); + Guardian guardian(true, hooks); + guardian.watch(on_halt, std::chrono::milliseconds(20)); + const int handled = halts; + guardian.stop_watching(); + set_critical(true); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + check(halts == handled, "after stop_watching the watcher handles no halt, so the server can end it before what on_halt uses"); + guardian.stop_watching(); + } +} + +int main() { + test_healthy_and_disabled(); + test_critical_signal(); + test_halt_seen_first_by_a_request(); + test_no_compute_device_left(); + test_resume_and_json(); + test_refusal(); + test_pressure_report(); + test_watcher(); + std::printf("\n%s (%d failures)\n", failures == 0 ? "ALL TESTS PASSED" : "TESTS FAILED", failures); + return failures == 0 ? 0 : 1; +} diff --git a/test/server_recovery_test.cpp b/test/server_recovery_test.cpp index e5626c66..d2b2f09d 100644 --- a/test/server_recovery_test.cpp +++ b/test/server_recovery_test.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -104,6 +105,10 @@ struct Env { bool accelerator = true; // The devices the library lists besides the cpu; empty means that the engine's own choice is all there is. std::vector devices; + // The devices device health excludes, the CPU included. + std::set excluded; + // The guardian has halted the server. + bool halted = false; // The contexts the keeper asked the library to stop, in order. on_cancel runs on the thread that called cancel(). std::mutex cancel_mutex; @@ -139,6 +144,8 @@ struct Env { hooks.read_failure = [this] { return next_failure; }; hooks.has_accelerator = [this] { return accelerator; }; hooks.list_devices = [this] { return devices; }; + hooks.device_excluded = [this](const std::string& name) { return excluded.count(name) != 0; }; + hooks.halted = [this] { return halted; }; hooks.now = [this] { return now; }; hooks.cancel_context = [this](sd_ctx_t* ctx) { // Reading the memory of a context the keeper no longer owns is what the address sanitizer reports. @@ -1012,6 +1019,25 @@ static void start_generation(ContextKeeper& keeper, Env& env, const CancelToken* } static void test_cancel() { + // The guardian stops a generation that has no token for it to reach (a synchronous A1111 or OpenAI request). + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + CHECK(!keeper.cancel_running() && env.cancel_calls.empty(), "cancel_running() reaches nobody while nothing runs"); + + Generation gen; + env.on_cancel = [&gen](sd_ctx_t*) { gen.told_to_stop = true; }; + start_generation(keeper, env, nullptr, gen); + CHECK(wait_for(gen.entered), "a generation without a token is running"); + const bool told = keeper.cancel_running(); + gen.thread.join(); + CHECK(told && env.cancel_calls.size() == 1 && env.cancel_calls[0] == gen.ctx, + "cancel_running() tells the library to stop the context in use"); + CHECK(!gen.ok && gen.failure.code == SD_ERROR_CANCELLED, "and the run reports a cancellation"); + CHECK(!keeper.cancel_running() && env.cancel_calls.size() == 1, "once the run has ended, cancel_running() reaches nobody"); + } // A job that is generating is stopped through its token. { Env env; @@ -1343,6 +1369,157 @@ static Script runs_only_on(const std::string& device) { }; } +// Device health (src/core/device_health.h): the keeper never moves the model to a device it excludes, the CPU +// included, and does not load the same configuration again on a device that has just been excluded. +static void test_excluded_devices() { + { + Env env; + env.devices = laptop_devices(); + env.excluded = {"Vulkan0"}; + env.load_result = only_the_cpu_works; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && backends_of(env) == Names({"", "", "CUDA0", "Vulkan1", "cpu"}), + "device health: an excluded device is not tried"); + } + { + Env env; + env.devices = laptop_devices(); + env.excluded = {"CPU"}; + env.load_result = only_the_cpu_works; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(!keeper.start(failure) && backends_of(env) == Names({"", "", "CUDA0", "Vulkan0", "Vulkan1"}), + "device health: with the CPU excluded, nothing falls back to it"); + } + { + Env env; + env.devices = laptop_devices(); + env.excluded = {"CPU"}; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + CHECK(!run_with(keeper, env, seen, [](const ContextKeeper::ContextView&) { return oom(); }, failure), "device health: a request that runs out of memory on every profile fails"); + CHECK(!seen.levels.empty() && seen.levels.back() == Level::LITE_DISK, + "device health: the profiles that hand work to an excluded CPU are skipped"); + } + { + Env env; + env.devices = laptop_devices(); + env.load_result = [](const Load& load) { return load.backend == "Vulkan1" ? ok_result : backend_failure(); }; + SDContextParams named = base_params(); + named.backend = "Vulkan0"; + ContextKeeper keeper(named, Level::MAX, settings(), env.hooks()); + env.excluded = {"Vulkan0"}; + GenerationFailure failure; + CHECK(keeper.start(failure) && backends_of(env) == Names({"CUDA0", "Vulkan1"}), + "device health: the device the host named is not loaded while it is excluded, and the others follow"); + } + { + Env env; + env.devices = laptop_devices(); + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + CHECK(run_with(keeper, env, seen, runs_only_on("Vulkan1"), failure), "a request served by the integrated GPU"); + const size_t loads = env.loads.size(); + env.excluded = {"CUDA0", "Vulkan0"}; + env.advance(10); + CHECK(run_with(keeper, env, seen, runs_only_on("Vulkan1"), failure) && env.loads.size() == loads, + "device health: the climb back does not leave a working device for an excluded one"); + } + { + Env env; + env.devices = laptop_devices(); + SDContextParams named = base_params(); + named.backend = "Vulkan0"; + ContextKeeper keeper(named, Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure), "a model loaded on the device the host named"); + env.excluded = {"Vulkan0"}; + Seen seen; + CHECK(run_with(keeper, env, seen, runs_only_on("CUDA0"), failure), + "a request that fails there because the device has just been excluded is served by the next device"); + CHECK(counter(keeper.health_json(), "retries") == 0, "device health: no retry is announced or counted for an excluded device"); + } +} + +// The guardian has halted the server (examples/server/guardian.h): a run stops as if its token had been requested, +// whatever token it has, so that no work goes on, and loading the model again elsewhere is work too. +static void test_halted() { + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + env.halted = true; + Seen seen; + const bool ok = run_with(keeper, env, seen, succeed, failure); + const json health = keeper.health_json(); + CHECK(!ok && failure.code == SD_ERROR_CANCELLED && seen.levels.empty(), + "halted: a run generates nothing, even one without a token"); + CHECK(failure.message.find("stopped all work") != std::string::npos, "halted: the run says that the server stopped all work"); + CHECK(counter(health, "cancelled") == 1 && counter(health, "failed") == 0 && health["last_error"].is_null(), + "halted: the run counts as stopped, not as a failure"); + env.halted = false; + CHECK(run_with(keeper, env, seen, succeed, failure) && seen.levels.size() == 1, "after the resume, runs generate again"); + } + { + Env env; + env.devices = laptop_devices(); + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + const size_t loads = env.loads.size(); + Seen seen; + // The device the run computes on has just been reported critical: the engine refuses it and the server halts. + const Script halt_then_fail = [&](const ContextKeeper::ContextView&) { + env.halted = true; + env.excluded = {"CUDA0", "Vulkan0"}; + return backend_failure(); + }; + const bool ok = run_with(keeper, env, seen, halt_then_fail, failure); + const json health = keeper.health_json(); + CHECK(!ok && failure.code == SD_ERROR_CANCELLED && seen.levels.size() == 1, "halted: a run that fails as the server halts is stopped"); + CHECK(env.loads.size() == loads && counter(health, "retries") == 0 && counter(health, "device_switches") == 0, + "halted: the model is not loaded again, neither in the same configuration nor on another device"); + CHECK(counter(health, "failed") == 0 && counter(health, "cancelled") == 1 && health["status"] == "ok", + "halted: the run counts as stopped and the server stays where it was"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + const Script halt_then_oom = [&](const ContextKeeper::ContextView&) { + env.halted = true; + return oom(); + }; + run_with(keeper, env, seen, halt_then_oom, failure); + CHECK(failure.code == SD_ERROR_CANCELLED && env.loads.size() == 1 && counter(keeper.health_json(), "step_downs") == 0, + "halted: running out of memory as the server halts does not make it step down"); + } + { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen first; + run_with(keeper, env, first, [](const ContextKeeper::ContextView& view) { return view.level < Level::LITE ? oom() : ok_result; }, failure); + const size_t loads = env.loads.size(); + env.advance(100); + env.halted = true; + Seen seen; + run_with(keeper, env, seen, succeed, failure); + CHECK(env.loads.size() == loads && counter(keeper.health_json(), "promotions") == 0, + "halted: the server does not climb back to a heavier profile"); + } +} + // A device that fails is not the end of the GPUs: the same configuration is tried once more, then every other device, // and the cpu only when none of them works. The server goes back to the preferred device when it works again. static void test_devices() { @@ -1720,6 +1897,8 @@ int main() { test_start(); test_step_down(); test_devices(); + test_excluded_devices(); + test_halted(); test_promotion(); test_unavailable(); test_reporting(); diff --git a/test/termico_test.py b/test/termico_test.py index f6155da9..40696b4c 100644 --- a/test/termico_test.py +++ b/test/termico_test.py @@ -25,6 +25,7 @@ import sys import tempfile import threading import time +import urllib.parse sys.dont_write_bytecode = True # provare gli script non deve lasciare __pycache__ accanto a loro @@ -182,15 +183,24 @@ class Gpu: self.imposta("t0", None) +NOME_GPU_FINTA = "NVIDIA GeForce RTX 3060 Laptop GPU" + + # --------------------------------------------------------------------------------------------------------- -# Motore finto: risponde come sd-server a /sdcpp/v1/health e /sdcpp/v1/resources, e ricorda ogni richiesta. +# Motore finto: risponde come sd-server a /sdcpp/v1/health, /sdcpp/v1/resources e alle segnalazioni +# (POST /sdcpp/v1/devices/{device}/pressure), e ricorda ogni richiesta. # --------------------------------------------------------------------------------------------------------- class MotoreFinto: - def __init__(self, chiave=None, stato="ok", profilo="max"): + DISPOSITIVI = ("CPU", "CUDA0", "Vulkan0", "RAM", "disk") + + def __init__(self, chiave=None, stato="ok", profilo="max", descrizione_gpu="gpu", ritardo_segnali=0.0): self.chiave = chiave self.stato = stato self.profilo = profilo + self.descrizione_gpu = descrizione_gpu + self.ritardo_segnali = ritardo_segnali self.richieste = [] + self.segnali = [] # (device, corpo) di ogni segnalazione accettata, in ordine self.avvio = time.time() motore = self @@ -230,7 +240,9 @@ class MotoreFinto: "process_bytes": 3221225472}, "devices": [{"name": "CPU", "description": "cpu", "type": "cpu", "free_memory_bytes": 8000000000, "total_memory_bytes": 17179869184}, - {"name": "CUDA0", "description": "gpu", "type": "gpu", + {"name": "CUDA0", "description": motore.descrizione_gpu, "type": "gpu", + "free_memory_bytes": 3758096384, "total_memory_bytes": 6442450944}, + {"name": "Vulkan0", "description": motore.descrizione_gpu, "type": "gpu", "free_memory_bytes": 3758096384, "total_memory_bytes": 6442450944}]}) self.rispondi(404, {"error": "not found"}) @@ -238,7 +250,22 @@ class MotoreFinto: motore.richieste.append((self.command, self.path)) self.rispondi(405, {"error": "method not allowed"}) - do_POST = do_PUT = do_DELETE = do_PATCH = altro + def do_POST(self): + parti = self.path.split("/") + if len(parti) != 6 or parti[1:4] != ["sdcpp", "v1", "devices"] or parti[5] != "pressure": + return self.altro() + motore.richieste.append(("POST", self.path)) + if self.senza_diritto(): + return self.rispondi(401, {"error": "unauthorized"}) + corpo = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"null") + time.sleep(motore.ritardo_segnali) + dispositivo = urllib.parse.unquote(parti[4]) + if dispositivo not in MotoreFinto.DISPOSITIVI: + return self.rispondi(404, {"error": "no device is named " + dispositivo, "code": "unknown_device"}) + motore.segnali.append((dispositivo, corpo)) + self.rispondi(200, {"device": {"name": dispositivo, "level": 0}, "guardian": {"enabled": True, "halted": False}}) + + do_PUT = do_DELETE = do_PATCH = altro self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Gestore) self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) @@ -477,6 +504,38 @@ def prove_funzioni(tm): controlla("GPU o driver diversi" in testo and "differenza" not in testo, "testo_confronto: GPU diverse = avviso; tre prove = niente colonna di differenza") +def prove_funzioni_segnala(tm): + print("\n-- funzioni di --segnala --") + L = tm.livello_segnale + controlla(L("normale", 0x1) == 0 and L("normale", None) == 0, "livello_segnale: fascia normale = nessun segnale (il bit 0x1 non è un motivo)") + controlla(L("normale", 0x20) == 1 and L("normale", 0x40) == 1, + "livello_segnale: il driver che rallenta la GPU per il caldo vale un gradino anche in fascia normale") + controlla(L("attenzione", 0x4) == 1 and L("attenzione", 0x20) == 2 and L("attenzione", 0x40) == 2, + "livello_segnale: attenzione = 1, con throttling termico = 2") + controlla(L("critica", 0x1) == 3 and L("critica", 0x20) == 3 and L("critica", 0x40) == 4, + "livello_segnale: critica = 3, con throttling termico hardware = escluso (4)") + controlla(L(None, 0x40) is None, "livello_segnale: temperatura illeggibile = nessuna segnalazione") + motivo = tm.motivo_segnale({"temp": 86.0, "mask": 0x20}, "attenzione") + controlla("86 C" in motivo and "attenzione" in motivo and "throttling termico" in motivo and "\n" not in motivo, + "motivo_segnale: temperatura, fascia e throttling in una riga (%s)" % motivo) + + D = tm.dispositivo_del_motore + portatile = [{"name": "CPU", "description": "cpu", "type": "cpu"}, + {"name": "CUDA0", "description": NOME_GPU_FINTA, "type": "gpu"}, + {"name": "Vulkan0", "description": NOME_GPU_FINTA, "type": "gpu"}, + {"name": "Vulkan1", "description": "AMD Radeon(TM) Graphics", "type": "igpu"}] + controlla(D(portatile, NOME_GPU_FINTA) == "CUDA0", + "dispositivo_del_motore: la GPU si riconosce dal nome; vista da CUDA e da Vulkan va bene la prima (il motore passa il segnale all'altra)") + controlla(D(portatile[:1] + portatile[2:], NOME_GPU_FINTA.lower()) == "Vulkan0", + "dispositivo_del_motore: senza CUDA va bene Vulkan, e le maiuscole non contano") + controlla(D(portatile, "NVIDIA RTX A2000") is None, "dispositivo_del_motore: una GPU che il motore non vede = nessun device") + gemelle = [{"name": "CUDA0", "description": NOME_GPU_FINTA, "type": "gpu"}, {"name": "CUDA1", "description": NOME_GPU_FINTA, "type": "gpu"}] + controlla(D(gemelle, NOME_GPU_FINTA) is None, "dispositivo_del_motore: due schede uguali non si distinguono dal nome: il device va indicato") + controlla(D([], NOME_GPU_FINTA) is None and D(None, NOME_GPU_FINTA) is None, "dispositivo_del_motore: nessun elenco = nessun device") + controlla(tm.durata_segnale(1.0) == 5 and tm.durata_segnale(0.3) == 5 and tm.durata_segnale(4.0) == 12, + "durata_segnale: qualche campione, mai meno di 5 secondi") + + # --------------------------------------------------------------------------------------------------------- # Prove del programma, lanciato come lo lancerebbe una persona (o un altro programma) # --------------------------------------------------------------------------------------------------------- @@ -752,6 +811,125 @@ def prove_osserva_guasti(gpu, base): protetto.ferma() +def osserva_con_passi(gpu, argomenti, passi, durata_passo, env=None, timeout=90): + """Lancia osserva e intanto cambia la GPU finta: passi è una lista di (temperatura, maschera esadecimale).""" + fermo = threading.Event() + + def cambia(): + for temp, mask in passi: + gpu.imposta("temp", temp) + gpu.imposta("mask", mask.zfill(16)) + if fermo.wait(durata_passo): + return + + temp, mask = passi[0] + gpu.imposta("temp", temp) + gpu.imposta("mask", mask.zfill(16)) + gpu.riparti() + comando = [sys.executable, "-I", TERMICO, "osserva", "--nvidia-smi", gpu.file] + argomenti + p = subprocess.Popen(comando, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", + env=env or gpu.ambiente(), stdin=subprocess.DEVNULL) + cambiatore = threading.Thread(target=cambia, daemon=True) + cambiatore.start() + try: + uscita, errori_uscita = p.communicate(timeout=timeout) + finally: + fermo.set() + cambiatore.join(5) + gpu.imposta("mask", None) + gpu.imposta("temp", None) + return p.returncode, uscita, errori_uscita + + +def livelli_di(segnali): + """I livelli ricevuti, senza ripetizioni di fila.""" + livelli = [] + for _, corpo in segnali: + if not livelli or livelli[-1] != corpo["level"]: + livelli.append(corpo["level"]) + return livelli + + +def prove_segnala(gpu, base): + print("\n-- osserva --segnala --") + r = lancia(gpu, con_gpu(gpu, ["osserva", "--segnala", "--durata", "1", "--uscita", os.path.join(base, "segnala-0")])) + controlla(r.returncode != 0 and "--motore" in r.stderr, "--segnala senza --motore viene rifiutato") + + # Tutte le fasce, una dopo l'altra, e di nuovo normale. La GPU finta legge temperatura e maschera da due file: + # ogni passo cambia solo ciò che fra due passi vicini non dà un livello diverso a metà scrittura. + motore = MotoreFinto(descrizione_gpu=NOME_GPU_FINTA) + try: + passi = [(60, "1"), (82, "4"), (82, "20"), (88, "1"), (88, "40"), (88, "1"), (60, "1")] + codice, uscita, _ = osserva_con_passi(gpu, ["--segnala", "--motore", motore.url, "--ogni", "0.3", "--durata", "12", + "--uscita", os.path.join(base, "segnala-1")], passi, 1.5) + segnali = list(motore.segnali) + finally: + motore.ferma() + livelli = livelli_di(segnali) + controlla(codice == 0 and livelli == [1, 2, 3, "excluded", 3, 0], + "--segnala: attenzione 1, con throttling termico 2, critica 3, con throttling hardware escluso, di nuovo 3, poi il ritiro (%s)" % livelli) + controlla(segnali and all(d == "CUDA0" for d, _ in segnali), "--segnala: il device si trova dal nome della GPU fra quelli del motore") + attivi = [corpo for _, corpo in segnali if corpo["level"] != 0] + controlla(attivi and all(corpo["source"] == "termico" and corpo["duration_seconds"] == 5 for corpo in attivi), + "--segnala: fonte termico, durata di qualche campione (5 s)") + controlla(sum(1 for corpo in attivi if corpo["level"] == 1) >= 2, "--segnala: il segnale si ripete a ogni campione finché la fascia resta") + doppio = next((corpo for corpo in attivi if corpo["level"] == 2), {}) + controlla("82 C" in doppio.get("reason", "") and "throttling termico" in doppio.get("reason", ""), + "--segnala: il motivo dice temperatura e throttling (%s)" % doppio.get("reason")) + controlla(segnali and segnali[-1][1] == {"level": 0, "source": "termico"} and sum(1 for _, c in segnali if c["level"] == 0) == 1, + "--segnala: tornata normale, il segnale si ritira una volta sola") + controlla("CUDA0" in uscita and "segnal" in uscita.lower(), "--segnala: all'inizio dice a quale device del motore segnala") + + # Device indicato, chiave API, ritiro alla fine. + protetto = MotoreFinto(chiave="k-77", descrizione_gpu=NOME_GPU_FINTA) + try: + codice, uscita, errori_uscita = osserva_con_passi( + gpu, ["--segnala", "Vulkan0", "--motore", protetto.url, "--chiave-api", "k-77", "--ogni", "0.3", "--durata", "3", + "--uscita", os.path.join(base, "segnala-2")], [(82, "4")], 3) + segnali = list(protetto.segnali) + finally: + protetto.ferma() + controlla(codice == 0 and segnali and all(d == "Vulkan0" for d, _ in segnali) and livelli_di(segnali) == [1, 0], + "--segnala Vulkan0: si usa il device indicato, e alla fine il segnale si ritira (%s)" % livelli_di(segnali)) + controlla("k-77" not in uscita + errori_uscita, "--segnala: la chiave API passa e non compare nell'uscita") + + protetto = MotoreFinto(chiave="k-77", descrizione_gpu=NOME_GPU_FINTA) + try: + codice, uscita, _ = osserva_con_passi(gpu, ["--segnala", "--motore", protetto.url, "--ogni", "0.3", "--durata", "3", + "--uscita", os.path.join(base, "segnala-3")], [(82, "4")], 3) + finally: + protetto.ferma() + controlla(codice == 0 and uscita.count("Segnalazione al motore rifiutata: chiave API mancante o errata") == 1, + "--segnala senza la chiave: il programma lo dice, una volta, e continua a misurare") + + # Il motore non conosce la GPU, o il device indicato. + estraneo = MotoreFinto() + try: + codice, uscita, _ = osserva_con_passi(gpu, ["--segnala", "--motore", estraneo.url, "--ogni", "0.3", "--durata", "3", + "--uscita", os.path.join(base, "segnala-4")], [(82, "4")], 3) + nessuno = list(estraneo.segnali) + codice_ignoto, uscita_ignoto, _ = osserva_con_passi( + gpu, ["--segnala", "Nessuno9", "--motore", estraneo.url, "--ogni", "0.3", "--durata", "3", + "--uscita", os.path.join(base, "segnala-5")], [(82, "4")], 3) + finally: + estraneo.ferma() + controlla(codice == 0 and not nessuno and "--segnala NOME" in uscita and NOME_GPU_FINTA in uscita, + "--segnala: una GPU che il motore non elenca = nessun segnale, e il programma dice come indicarla") + controlla(codice_ignoto == 0 and uscita_ignoto.count("Nessuno9") >= 1 and uscita_ignoto.count("non conosce") == 1, + "--segnala Nessuno9: il motore non lo conosce, il programma lo dice una volta e continua") + + # Un motore lento non rallenta le letture della GPU. + lento = MotoreFinto(descrizione_gpu=NOME_GPU_FINTA, ritardo_segnali=2.0) + cartella = os.path.join(base, "segnala-6") + try: + codice, _, _ = osserva_con_passi(gpu, ["--segnala", "--motore", lento.url, "--ogni", "0.3", "--durata", "4", + "--uscita", cartella], [(88, "1")], 4) + finally: + lento.ferma() + righe = leggi_csv(file_con(cartella, ".csv")[0]) + controlla(codice == 0 and len(righe) >= 10, "--segnala con un motore lento: i campioni della GPU non rallentano (%d righe in 4 s)" % len(righe)) + + def prove_segnali(gpu, base): if os.name == "nt": print("\n-- segnali: saltate su Windows --") @@ -1065,6 +1243,7 @@ def prove_programma(base): prove_stato_motore(gpu, base) prove_osserva(gpu, base) prove_osserva_guasti(gpu, base) + prove_segnala(gpu, base) prove_segnali(gpu, base) prova_guidata(gpu, base) prove_confronto(gpu, base) @@ -1077,6 +1256,7 @@ def main(): args = parser.parse_args() tm = carica_modulo() prove_funzioni(tm) + prove_funzioni_segnala(tm) if not args.veloce: base = tempfile.mkdtemp(prefix="termico-test-") try: