feat: make the values of device health configurable

The values of device health decided on 25 November (3 levels of strain,
15% of the capacity and 25% of the CPU threads per level, a quiet period
of 300 s, and 10 s under which two engine events count once) can now be
read and changed. Without the new option nothing changes.

- C API, additions only: sd_device_health_settings_t,
  sd_get_device_health_settings() and sd_set_device_health_settings().
- sd-cli and sd-server: --device-health with any of the keys levels,
  step, cpu-step, quiet and spacing, e.g. --device-health quiet=600. It
  applies as soon as the options are read, in the DGL mode of sd-cli too;
  values against the rules stop the program at start and say the rules,
  and the log names the values used.
- The registry refuses waits longer than a day and steps whose product
  with the levels would not fit in an int. When the values change, every
  component keeps its state: before, fewer levels could turn a level of
  strain into an exclusion, and more levels could bring an excluded
  device back under strain. The same values written again no longer
  change the revision, which makes the next generation place its models
  again.
- termico.py --segnala reads the levels of its device from
  /sdcpp/v1/health and from the answers to its reports, and never sends
  more than the last level of strain: with two levels the critical band
  is level 2, not an exclusion.

Docs: a "Device health" section in docs/guides/backend.md,
examples/server/api.md and the server README, the README of
scripts/diagnostica_termica, test/README.md and the fork history.

test: device_health_test covers the new rules and the C API (135
checks), device_health_option_test is new (30), termico_test covers
engines with two levels, one level and none declared (161), and
server_guardian_e2e.py starts its second server with
--device-health levels=2,step=20,quiet=5 and checks the option in sd-cli
(70 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
29 broken versions of the new code (registry and C API 12, option 9,
termico.py 6, the calls in sd-server and sd-cli 2) all make the tests
fail. Not tried: real GPUs, Windows.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
This commit is contained in:
Claude 2026-11-25 20:26:55 +01:00
parent abbec1a7f3
commit 84cf73f5cd
No known key found for this signature in database
18 changed files with 705 additions and 47 deletions

1
.gitignore vendored
View file

@ -14,6 +14,7 @@ test/*
!test/memory_guard_engine_test.cpp
!test/layer_split_fill_test.cpp
!test/device_health_test.cpp
!test/device_health_option_test.cpp
!test/package_windows_cuda_vulkan_test.sh
!test/server_recovery_test.cpp
!test/server_cancel_e2e.py

View file

@ -360,6 +360,46 @@ What it does and does not do:
- `--profile auto` counts the free memory of the GPUs together (less 2 GiB of
working memory for each GPU after the first) when `--multi-gpu` is not `off`.
## Device health (`--device-health`)
The engine keeps, for the whole process, a record of how each device, 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: the planner gives it that
share of its memory, the layer split that share of its capacity, and the CPU computes
with fewer threads. An excluded device is never computed on.
A level rises when a compute fails, a backend does not start, the memory guard cannot
get under its threshold or a read of the weights fails, and when an outside watcher
reports a signal: `sd-server` takes them on `POST /sdcpp/v1/devices/{device}/pressure`
(see [Device health and the guardian](../../examples/server/api.md#device-health-and-the-guardian)),
a host application calls `sd_report_device_pressure()`. Without failures and without
signals nothing changes. A level comes back one step after each quiet period.
`--device-health` sets the values for the run, in `sd-cli` and in `sd-server`, as a
list of any of these keys:
| Key | Default | Meaning |
| --- | --- | --- |
| `levels` | 3 | levels of strain before exclusion, 1 to 10; the level after the last one excludes |
| `step` | 15 | percent of its capacity a component gives up at each level: 85%, 70%, 55% |
| `cpu-step` | 25 | percent of its compute threads the CPU gives up at each level |
| `quiet` | 300 | seconds without events before a level comes back one step, 1 to 86400 |
| `spacing` | 10 | seconds under which two events of the engine on one component count once, 0 to 86400 |
`step` and `cpu-step` times `levels` stay under 100, so the last level of strain still
offers something. The values are checked at start: a list that breaks the rules stops
the program and says them, and the log names the values used.
```shell
sd-server -m model.safetensors --device-health quiet=600
sd-cli -m model.safetensors -p "a cat" --device-health levels=2,step=20
```
Host applications read and change the same values with
`sd_get_device_health_settings()` and `sd_set_device_health_settings()`. When they
change, every component keeps its state: an excluded one stays excluded, and a level of
strain above the new last one comes down to it.
## Direct convolution (`--conv-direct on|off|auto`)
`--conv-direct` defaults to `auto` and accepts module assignments for

View file

@ -1986,6 +1986,42 @@ sincronizzazioni future.
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.
27. **I valori della salute dei device** — i valori della voce 26, decisi il
25 novembre (tre livelli, 15% della capacità e 25% dei thread della CPU per
livello, 300 secondi di calma, 10 secondi fra due eventi del motore), ora
si leggono e si cambiano. API C, solo aggiunte:
`sd_device_health_settings_t`, `sd_get_device_health_settings()`,
`sd_set_device_health_settings()`. Opzione `--device-health` di `sd-cli` e
`sd-server` con le chiavi `levels`, `step`, `cpu-step`, `quiet` e `spacing`,
anche solo alcune (`examples/common/common.cpp`): vale appena lette le
opzioni, anche nel modo DGL, e un valore fuori regola ferma il programma
con le regole. Documentata nella sezione «Device health» di
[backend.md](./guides/backend.md), in `examples/server/api.md` e nel README
del server.
Il registro rifiuta ora attese oltre un giorno e passi che, moltiplicati
per i livelli, non stanno in un `int`; quando i valori cambiano, ogni
componente resta nel suo stato (prima, con meno livelli, un livello di
sforzo poteva diventare un'esclusione e, con più livelli, un escluso
tornare sotto sforzo); gli stessi valori riscritti non cambiano la
revisione, che farebbe ripiazzare i modelli. `termico.py --segnala` legge
i livelli del device da `/sdcpp/v1/health` e dalle risposte e non manda mai
più dell'ultimo: con due livelli la fascia critica vale 2, non
l'esclusione.
Test, su una build per CPU: i dodici programmi di `test/` passano, con
`device_health_test` (135 controlli) e il nuovo
`device_health_option_test` (30); `server_recovery_test` e
`server_guardian_test` anche con ThreadSanitizer. Versioni rotte del codice
nuovo che i test devono scoprire: registro e API C 12, opzione 9,
`termico.py` 6, collegamento in `sd-server` e `sd-cli` 2, tutte scoperte.
Con il modello SD 1.5 sintetico: `test/server_guardian_e2e.py` passa i suoi
70 controlli tre volte di fila (il secondo server con
`--device-health levels=2,step=20,quiet=5`, e `sd-cli` nel modo DGL);
`termico_test.py` 161; `server_cancel_e2e.py` 35; `agenti_guardiano_test.py`
66 senza server e 91 con il server vero; `security_smoke.sh`;
`dgl-check-builtins`; la prova d'integrazione del registro nel motore (12
controlli, non nel repository). **Non provato**: GPU vere, 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

View file

@ -550,6 +550,9 @@ int main(int argc, const char* argv[]) {
sd_set_log_callback(sd_log_cb, (void*)&cli_params);
parse_args(argc, argv, cli_params, ctx_params, gen_params);
if (!ctx_params.apply_device_health_option()) {
return 1;
}
if (cli_params.mode == DGL) {
return cli_params.dgl.run(ctx_params, gen_params.embed_image_metadata);

View file

@ -2,6 +2,7 @@
#include <algorithm>
#include <cctype>
#include <charconv>
#include <cstdio>
#include <cstdlib>
#include <ctime>
@ -559,6 +560,15 @@ ArgOptions SDContextParams::get_options() {
"computing on each) or fill-first (the first device takes as many layers as it can, the next ones the rest)",
0,
&layer_split_fill},
{"",
"--device-health",
"values of device health, for the whole process, as a key=value list with any of the keys: levels (levels of strain "
"before a device is excluded, 1 to 10, default 3), step (percent of its capacity a device gives up at each level, "
"default 15), cpu-step (percent of its compute threads the CPU gives up at each level, default 25), quiet (seconds "
"without events before a level comes back one step, default 300) and spacing (seconds under which two events of the "
"engine on one device count once, default 10), e.g. quiet=600",
(int)',',
&device_health},
{"",
"--rpc-servers",
"comma-separated list of RPC servers to connect to for offloading, in the format host:port, e.g. localhost:50052,192.168.1.3:50052",
@ -820,6 +830,93 @@ bool SDContextParams::register_rpc_devices() const {
return !rpc_servers || sd_add_rpc_servers(rpc_servers->c_str());
}
static std::string trimmed(const std::string& text) {
const size_t first = text.find_first_not_of(" \t");
if (first == std::string::npos) {
return "";
}
return text.substr(first, text.find_last_not_of(" \t") - first + 1);
}
bool parse_device_health_settings(const std::string& list, sd_device_health_settings_t& settings, std::string& error) {
static const char* keys = "the keys are levels, step, cpu-step, quiet and spacing";
sd_device_health_settings_t parsed = settings;
std::set<std::string> seen;
size_t start = 0;
while (true) {
const size_t comma = list.find(',', start);
const std::string item = trimmed(list.substr(start, comma == std::string::npos ? std::string::npos : comma - start));
const size_t equals = item.find('=');
if (equals == std::string::npos) {
error = "--device-health: '" + item + "' is not key=value; " + keys;
return false;
}
const std::string key = trimmed(item.substr(0, equals));
const std::string value = trimmed(item.substr(equals + 1));
int* target = key == "levels" ? &parsed.strain_levels
: key == "step" ? &parsed.step_percent
: key == "cpu-step" ? &parsed.cpu_thread_step_percent
: key == "quiet" ? &parsed.quiet_period_seconds
: key == "spacing" ? &parsed.event_spacing_seconds
: nullptr;
if (target == nullptr) {
error = "--device-health: unknown key '" + key + "'; " + keys;
return false;
}
if (!seen.insert(key).second) {
error = "--device-health: " + key + " is given twice";
return false;
}
int number = 0;
const char* end = value.data() + value.size();
const auto result = std::from_chars(value.data(), end, number);
if (value.empty() || result.ec != std::errc() || result.ptr != end) {
error = "--device-health: " + key + " needs a whole number, not '" + value + "'";
return false;
}
*target = number;
if (comma == std::string::npos) {
break;
}
start = comma + 1;
}
settings = parsed;
return true;
}
bool SDContextParams::apply_device_health_option() const {
if (device_health.empty()) {
return true;
}
sd_device_health_settings_t settings = {};
sd_get_device_health_settings(&settings);
std::string error;
if (!parse_device_health_settings(device_health, settings, error)) {
LOG_ERROR("error: %s", error.c_str());
return false;
}
if (!sd_set_device_health_settings(&settings)) {
LOG_ERROR(
"error: --device-health: levels=%d, step=%d, cpu-step=%d, quiet=%d, spacing=%d break the rules: levels from 1 to 10, "
"step at least 1, step and cpu-step times levels under 100, quiet from 1 to 86400 seconds, spacing from 0 to 86400",
settings.strain_levels,
settings.step_percent,
settings.cpu_thread_step_percent,
settings.quiet_period_seconds,
settings.event_spacing_seconds);
return false;
}
LOG_INFO(
"device health: %d levels of strain, %d%% of the capacity and %d%% of the CPU threads per level, "
"a quiet period of %d s, events of the engine closer than %d s count once",
settings.strain_levels,
settings.step_percent,
settings.cpu_thread_step_percent,
settings.quiet_period_seconds,
settings.event_spacing_seconds);
return true;
}
bool SDContextParams::print_devices() const {
if (!register_rpc_devices()) {
return false;
@ -1023,6 +1120,7 @@ std::string SDContextParams::to_string() const {
<< " split_mode: \"" << split_mode << "\",\n"
<< " multi_gpu: \"" << multi_gpu << "\",\n"
<< " layer_split_fill: \"" << layer_split_fill << "\",\n"
<< " device_health: \"" << device_health << "\",\n"
<< " model_args: \"" << model_args << "\",\n"
<< " auto_fit: " << auto_fit << ",\n"
<< " enable_mmap: " << enable_mmap << ",\n"

View file

@ -175,6 +175,7 @@ struct SDContextParams {
std::optional<std::string> split_mode;
std::string multi_gpu;
std::string layer_split_fill;
std::string device_health;
std::optional<std::string> model_args;
std::optional<bool> auto_fit;
std::optional<std::string> rpc_servers;
@ -210,8 +211,14 @@ struct SDContextParams {
SDOptPtr to_context_opt();
bool configure_dgl(sd_dgl_ctx_t* ctx) const;
bool register_rpc_devices() const;
// For the whole process. False, with the reason logged, when the list cannot be read or breaks the rules.
bool apply_device_health_option() const;
};
// settings changes only when the whole list can be read; the rules are checked when the values are written, by
// sd_set_device_health_settings().
bool parse_device_health_settings(const std::string& list, sd_device_health_settings_t& settings, std::string& error);
struct SDGenerationParams {
// User-facing input fields.
std::string prompt;

View file

@ -513,8 +513,8 @@ See [Failures and recovery](api.md#failures-and-recovery) for the answers a clie
## 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
work, one step at a time: 85%, 70%, 55% of its capacity with the default values; 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.
@ -526,6 +526,9 @@ The server resumes by itself when the cause ends, or when an operator calls `POS
* `--guardian on|off` (default `on`): with `off` the server never stops all work by itself; device health still moves
the work between devices
* `--device-health levels=3,step=15,cpu-step=25,quiet=300,spacing=10` (any of the keys; these are the defaults): the
values of device health, as in `sd-cli`; see
[Backend selection](../../docs/guides/backend.md#device-health---device-health)
This is a layer of the software, not a safety system: a stop that protects people or equipment belongs to independent,
certified hardware.

View file

@ -186,13 +186,13 @@ when the CPU was reached through memory failures, the climb is one profile up, a
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).
or excluded (level 4). These are the default values; `--device-health` changes them (see below).
| 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` |
| 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 the last level of strain; 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
@ -202,8 +202,13 @@ one device less than 10 seconds apart count once. Outside watchers report too, w
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.
changes, the next generation places the model again with the new shares, which costs loading the weights again.
`--device-health` changes the values when the server starts, with any of the keys of
`levels=3,step=15,cpu-step=25,quiet=300,spacing=10` (the defaults): the levels of strain, the share and the CPU
threads given up at each level, the quiet period and the spacing of the events, in seconds. The level after the last
level of strain excludes; each component in `/sdcpp/v1/health` gives its `strain_levels`, so a watcher knows which
level that is. See [Backend selection](../../docs/guides/backend.md#device-health---device-health) for the rules.
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:
@ -1360,7 +1365,7 @@ Request body:
| 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 |
| `level` | `integer \| string` | `0` withdraws the signal of this source; `1` to `strain_levels` (3 by default) put the component under strain; `strain_levels + 1` 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 |

View file

@ -135,6 +135,9 @@ int main(int argc, const char** argv) {
LOG_DEBUG("%s", ctx_params.to_string().c_str());
LOG_DEBUG("%s", default_gen_params.to_string().c_str());
if (!ctx_params.apply_device_health_option()) {
return 1;
}
if (!ctx_params.register_rpc_devices()) {
return 1;
}

View file

@ -627,6 +627,23 @@ SD_API bool sd_report_device_pressure(const char* component,
// back to the last level of strain.
SD_API void sd_resume_device_health(void);
// The values of device health, for the whole process: read them, change some and write them back. The defaults are
// 3 levels of strain, 15% of the capacity and 25% of the CPU threads per level, a quiet period of 300 s, and 10 s
// under which two events of the engine on one component count once.
typedef struct {
int strain_levels; // levels of strain before exclusion, 1..10
int step_percent; // capacity a component gives up at each level, at least 1
int cpu_thread_step_percent; // compute threads the CPU gives up at each level, at least 0
int quiet_period_seconds; // a level comes back one step after this long without events, 1..86400
int event_spacing_seconds; // events of the engine on one component closer than this count once, 0..86400
} sd_device_health_settings_t;
SD_API void sd_get_device_health_settings(sd_device_health_settings_t* settings);
// Returns false, and changes nothing, when a value is out of its range or a step times strain_levels reaches 100.
// Every component keeps its state: an excluded one stays excluded, and a level of strain above the new last one
// comes down to it. Writing the same values again changes nothing.
SD_API bool sd_set_device_health_settings(const sd_device_health_settings_t* settings);
// 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

View file

@ -378,7 +378,8 @@ serve.
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.
tenere, con i valori di partenza) 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
@ -397,9 +398,13 @@ python scripts/diagnostica_termica/termico.py osserva --motore http://127.0.0.1:
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`).
- **Un motore con altri livelli.** Il motore può avere più o meno di tre livelli di sforzo (`--device-health levels=N`):
il programma li legge da `GET /sdcpp/v1/health` e non va mai oltre l'ultimo, perché il livello dopo è l'esclusione.
Con due livelli la fascia critica vale 2, e lo dice all'inizio; l'esclusione arriva solo con il throttling hardware.
- **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.
ogni 5 minuti di calma (con i valori di partenza), 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)).
@ -596,14 +601,16 @@ uscita (il nome della prova viene ripulito: non può far uscire i file dalla car
## 11. Cosa è verificato e cosa no
**Verificato**, con 127 controlli automatici in [`test/termico_test.py`](../../test/termico_test.py) (circa 80
secondi; una GPU finta che risponde come `nvidia-smi`, un motore finto, e il programma lanciato davvero): calcolo di
**Verificato**, con 161 controlli automatici in [`test/termico_test.py`](../../test/termico_test.py) (due minuti e
mezzo; una GPU finta che risponde come `nvidia-smi`, un motore finto, e il programma lanciato davvero): calcolo di
fasce, giudizi, pendenze e riepiloghi; lettura e scrittura del CSV (anche con righe troncate); `stato` con tutti i
codici di uscita; `osserva` con file di stato letto in continuazione senza mai trovarlo a metà; `riepilogo` di una
prova interrotta con un segnale di terminazione; la sessione guidata pilotata come da una persona (compreso l'Invio
premuto per sbaglio durante una fase automatica); `confronta`; motore spento, motore che si spegne a metà, chiave API
giusta e sbagliata, GPU che risponde a intermittenza o per niente; la chiave non compare mai nell'uscita né nei file.
Inoltre `termico.py` e `carico_motore.py` sono stati provati contro un vero `sd-server` (build per CPU, modello
giusta e sbagliata, GPU che risponde a intermittenza o per niente; la chiave non compare mai nell'uscita né nei file;
`osserva --segnala` con motori finti a tre, due e un livello di sforzo, e contro un vero `sd-server` in
[`test/server_guardian_e2e.py`](../../test/server_guardian_e2e.py), anche con `--device-health levels=2`. Inoltre
`termico.py` e `carico_motore.py` sono stati provati contro un vero `sd-server` (build per CPU, modello
sintetico, GPU simulata) mentre generava, con uno script di prova che non fa parte del repository: sei job completati
e uno fermato con `cancel`, i contatori letti da `termico.py` uguali a quelli di `/health`, nessuna discesa di
profilo. Per vedere che i controlli servano a qualcosa, durante lo sviluppo sono stati inseriti di proposito 42 errori

View file

@ -438,6 +438,7 @@ class OsservatoreMotore:
FONTE_SEGNALE = "termico"
LIVELLO_ESCLUSO = 4 # il livello dopo i tre di sforzo del motore
LIVELLI_PREDEFINITI = 3 # i livelli di sforzo di un motore che non li dice (--device-health levels li cambia)
BIT_TERMICO_HW = 0x40
@ -454,6 +455,14 @@ def livello_segnale(fascia, mask):
return 1 if termico else 0
def livello_per_il_motore(livello, livelli):
"""Il "level" da mandare a un motore con quei livelli di sforzo (None se non li dice: tre). Una fascia si ferma
all'ultimo livello di sforzo, perché il livello dopo è l'esclusione; l'esclusione si manda per nome."""
if livello == LIVELLO_ESCLUSO:
return "excluded"
return min(livello, livelli or LIVELLI_PREDEFINITI)
def motivo_segnale(c, fascia):
mask = c.get("mask") or 0
motivo = f"GPU a {c['temp']:.0f} C, fascia {fascia}"
@ -494,6 +503,9 @@ class SegnalatoreMotore:
self.dispositivo = dispositivo # None: si cerca dal nome della GPU
self.nome_gpu = nome_gpu
self.durata = durata
self.livelli = None # i livelli di sforzo del device nel motore, da /sdcpp/v1/health e dalle risposte
self._livelli_chiesti = False
self._ultima_richiesta_livelli = None
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
@ -552,8 +564,33 @@ class SegnalatoreMotore:
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)
if self.dispositivo is not None:
self._chiedi_livelli()
return self.dispositivo
def _chiedi_livelli(self):
if self._livelli_chiesti or (self._ultima_richiesta_livelli is not None and
time.monotonic() - self._ultima_richiesta_livelli < 10):
return
self._ultima_richiesta_livelli = time.monotonic()
codice, salute = chiedi_json(self.url, self.chiave, "/sdcpp/v1/health", 3.0)
if codice not in (200, 503) or not isinstance(salute, dict):
return
self._livelli_chiesti = True
voluto = self.dispositivo.lower()
for stato in salute.get("devices") or []:
if isinstance(stato, dict) and str(stato.get("name") or "").lower() == voluto:
self._prendi_livelli(stato.get("strain_levels"))
def _prendi_livelli(self, livelli):
if not isinstance(livelli, int) or isinstance(livelli, bool) or livelli < 1 or livelli == self.livelli:
return
self.livelli = livelli
if livelli < LIVELLI_PREDEFINITI:
parola = "livello" if livelli == 1 else "livelli"
self._avvisa(f"livelli{livelli}", f"Il motore ha {livelli} {parola} di sforzo: le fasce che varrebbero "
f"di più valgono {livelli}, e solo il throttling hardware esclude la GPU.")
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.")
@ -575,12 +612,15 @@ class SegnalatoreMotore:
if livello == 0:
corpo = {"level": 0, "source": FONTE_SEGNALE}
else:
corpo = {"level": "excluded" if livello == LIVELLO_ESCLUSO else livello, "source": FONTE_SEGNALE,
corpo = {"level": livello_per_il_motore(livello, self.livelli), "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
stato = risposta.get("device") if isinstance(risposta, dict) else None
if isinstance(stato, dict):
self._prendi_livelli(stato.get("strain_levels"))
else:
self._avvisa_errore(codice, risposta)
@ -1449,8 +1489,9 @@ def crea_parser():
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")
"attenzione 1, con throttling termico 2, critica 3 (mai oltre l'ultimo livello di sforzo "
"del motore), 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)

View file

@ -17,6 +17,7 @@ namespace sd {
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 constexpr std::chrono::seconds max_settings_wait{24 * 60 * 60};
static std::string lowercase(std::string text) {
std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
@ -77,26 +78,38 @@ namespace sd {
}
bool DeviceHealth::set_settings(const Settings& settings) {
// Each step is checked alone first, so the products below cannot overflow.
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.step_percent >= 1 && settings.step_percent < 100 &&
settings.step_percent * settings.strain_levels < 100 &&
settings.cpu_thread_step_percent >= 0 && settings.cpu_thread_step_percent < 100 &&
settings.cpu_thread_step_percent * settings.strain_levels < 100 &&
settings.quiet_period >= std::chrono::seconds(1) &&
settings.event_spacing >= std::chrono::seconds(0);
settings.quiet_period >= std::chrono::seconds(1) && settings.quiet_period <= max_settings_wait &&
settings.event_spacing >= std::chrono::seconds(0) && settings.event_spacing <= max_settings_wait;
if (!valid) {
return false;
}
std::lock_guard<std::mutex> lock(mutex_);
settings_ = settings;
// A new revision makes the next generation place its models again.
if (settings.enabled == settings_.enabled && settings.strain_levels == settings_.strain_levels &&
settings.step_percent == settings_.step_percent && settings.cpu_thread_step_percent == settings_.cpu_thread_step_percent &&
settings.quiet_period == settings_.quiet_period && settings.event_spacing == settings_.event_spacing) {
return true;
}
const int old_top = top_locked();
settings_ = settings;
if (!settings_.enabled) {
entries_.clear();
listed_ = false;
}
// Every component keeps its state: an excluded one stays excluded, one under strain stays under strain, at
// most on the new last level.
const int top = top_locked();
auto moved = [&](int level) { return level >= old_top ? top : std::min(level, settings_.strain_levels); };
for (auto& entry : entries_) {
entry.level = std::min(entry.level, top);
entry.level = moved(entry.level);
for (auto& held : entry.signals) {
held.level = std::min(held.level, top);
held.level = moved(held.level);
}
}
revision_++;
@ -563,3 +576,28 @@ bool sd_report_device_pressure(const char* component,
void sd_resume_device_health(void) {
sd::device_health().resume();
}
void sd_get_device_health_settings(sd_device_health_settings_t* settings) {
if (settings == nullptr) {
return;
}
const auto current = sd::device_health().settings();
settings->strain_levels = current.strain_levels;
settings->step_percent = current.step_percent;
settings->cpu_thread_step_percent = current.cpu_thread_step_percent;
settings->quiet_period_seconds = static_cast<int>(current.quiet_period.count());
settings->event_spacing_seconds = static_cast<int>(current.event_spacing.count());
}
bool sd_set_device_health_settings(const sd_device_health_settings_t* settings) {
if (settings == nullptr) {
return false;
}
auto next = sd::device_health().settings();
next.strain_levels = settings->strain_levels;
next.step_percent = settings->step_percent;
next.cpu_thread_step_percent = settings->cpu_thread_step_percent;
next.quiet_period = std::chrono::seconds(settings->quiet_period_seconds);
next.event_spacing = std::chrono::seconds(settings->event_spacing_seconds);
return sd::device_health().set_settings(next);
}

View file

@ -16,13 +16,14 @@ 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 |
| `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. I valori: regole (anche attese oltre un giorno e passi che non stanno in un `int`), valori cambiati mentre i componenti sono sotto sforzo o esclusi (ognuno resta nel suo stato), gli stessi valori senza nuova revisione, lettura e scrittura con l'API C. Orologio finto: nessuna GPU né modello | vedi intestazione del file |
| `device_health_option_test.cpp` | opzione `--device-health` di `sd-cli` e `sd-server` (`examples/common`): chiavi `levels`, `step`, `cpu-step`, `quiet`, `spacing` (anche solo alcune, con spazi, l'opzione ripetuta), elenchi rifiutati senza cambiare niente (vuoti, chiavi sconosciute o ripetute, numeri sbagliati o troppo grandi), valori scritti nel registro del processo e valori fuori regola rifiutati. Serve la libreria compilata, 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. 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 <modello>` (circa un minuto con un modello piccolo) |
| `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` e `--device-health levels=2,step=20,quiet=5` (due livelli all'80% e al 60%, il terzo esclude, un gradino in meno ogni 5 secondi), `termico.py osserva --segnala` con la GPU finta di `termico_test.py` che arriva al server (la fascia critica vale 2, l'ultimo dei due livelli), `sd-cli` (accanto al server, o indicato con `--cli`) che applica `--device-health` all'avvio anche nel modo DGL e rifiuta i valori fuori regola, contatori e log | `python3 test/server_guardian_e2e.py --server build/bin/sd-server --model <modello>` (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 <modello>` |
| `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) |
| `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), mai oltre l'ultimo livello di sforzo di un motore a due o a un livello, 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` (2-3 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 <sd-cli> --seconds 300` |

View file

@ -0,0 +1,141 @@
// Test of the --device-health option of sd-cli and sd-server (examples/common): the key=value list, the lists it
// refuses, and the values it writes into the device health of the process through the C API.
// Build (from the repository root, after building the static library into build/):
// cc -c thirdparty/zip.c -o zip.o
// c++ -std=c++17 -Iexamples -Iinclude -Ithirdparty -Isrc test/device_health_option_test.cpp \
// examples/common/common.cpp examples/common/log.cpp examples/common/media_io.cpp \
// examples/common/media_metadata.cpp examples/common/profile.cpp zip.o 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_option_test
// Run: ./device_health_option_test ; exit code 0 = all checks passed.
#include <cstdio>
#include <string>
#include <vector>
#include "common/common.h"
#include "stable-diffusion.h"
static int failures = 0;
static void check(bool condition, const std::string& what) {
std::printf("%s %s\n", condition ? "ok: " : "FAIL:", what.c_str());
failures += condition ? 0 : 1;
}
static sd_device_health_settings_t defaults() {
sd_device_health_settings_t settings = {};
settings.strain_levels = 3;
settings.step_percent = 15;
settings.cpu_thread_step_percent = 25;
settings.quiet_period_seconds = 300;
settings.event_spacing_seconds = 10;
return settings;
}
static bool same_values(const sd_device_health_settings_t& a, const sd_device_health_settings_t& b) {
return a.strain_levels == b.strain_levels && a.step_percent == b.step_percent &&
a.cpu_thread_step_percent == b.cpu_thread_step_percent && a.quiet_period_seconds == b.quiet_period_seconds &&
a.event_spacing_seconds == b.event_spacing_seconds;
}
static void test_parse() {
std::string error;
sd_device_health_settings_t settings = defaults();
check(parse_device_health_settings("levels=2,step=20", settings, error) && settings.strain_levels == 2 &&
settings.step_percent == 20 && settings.cpu_thread_step_percent == 25 && settings.quiet_period_seconds == 300 &&
settings.event_spacing_seconds == 10,
"the keys given change their values, the others stay");
settings = defaults();
check(parse_device_health_settings("quiet=600", settings, error) && settings.quiet_period_seconds == 600 &&
settings.strain_levels == 3 && settings.event_spacing_seconds == 10,
"one key alone changes one value");
settings = defaults();
check(parse_device_health_settings(" cpu-step = 20 , spacing=0 ", settings, error) && settings.cpu_thread_step_percent == 20 &&
settings.event_spacing_seconds == 0,
"spaces around keys and values are allowed");
settings = defaults();
check(parse_device_health_settings("spacing=-1", settings, error) && settings.event_spacing_seconds == -1,
"a negative number is read: the values are judged when they are written");
struct Refused {
const char* list;
const char* what;
};
const Refused refused[] = {
{"", "an empty list"},
{"levels", "a key without a value"},
{"levels=", "an empty value"},
{"=2", "a value without a key"},
{"levels=two", "a value that is not a number"},
{"levels=2x", "a number followed by letters"},
{"levels=2.5", "a number that is not whole"},
{"levels=99999999999", "a number too big for an int"},
{"levels=2,levels=3", "a key given twice"},
{"speed=3", "an unknown key"},
{"Levels=2", "a key in other letters"},
{"levels=2,,step=20", "an empty item"},
{"levels=2,", "a comma at the end"},
};
for (const auto& item : refused) {
settings = defaults();
error.clear();
const bool parsed = parse_device_health_settings(item.list, settings, error);
check(!parsed && !error.empty() && same_values(settings, defaults()),
std::string("refused, with a reason and nothing changed: ") + item.what + " ('" + item.list + "')");
}
settings = defaults();
parse_device_health_settings("speed=3", settings, error);
check(error.find("levels") != std::string::npos && error.find("cpu-step") != std::string::npos &&
error.find("spacing") != std::string::npos,
"an unknown key is answered with the keys there are");
}
static void test_option_and_values() {
sd_device_health_settings_t saved = {};
sd_get_device_health_settings(&saved);
check(same_values(saved, defaults()), "the process starts with the default values");
SDContextParams params;
const std::vector<std::string> words = {"test", "--device-health", "levels=2", "--device-health", "step=20"};
std::vector<const char*> argv;
for (const auto& word : words) {
argv.push_back(word.c_str());
}
const bool parsed = parse_options(static_cast<int>(argv.size()), argv.data(), {params.get_options()});
check(parsed && params.device_health == "levels=2,step=20", "the option is read, and given twice its lists are joined");
check(params.apply_device_health_option(), "the values are written");
sd_device_health_settings_t now = {};
sd_get_device_health_settings(&now);
sd_device_health_settings_t wanted = defaults();
wanted.strain_levels = 2;
wanted.step_percent = 20;
check(same_values(now, wanted), "into the device health of the process, the others unchanged");
SDContextParams wrong;
wrong.device_health = "levels=8";
check(!wrong.apply_device_health_option(), "values against the rules are refused: 8 levels of 20% leave nothing");
wrong.device_health = "spacing=-1";
check(!wrong.apply_device_health_option(), "and so is a negative spacing");
wrong.device_health = "quiet=86401";
check(!wrong.apply_device_health_option(), "and a quiet period longer than a day");
wrong.device_health = "speed=3";
check(!wrong.apply_device_health_option(), "and a list that cannot be read");
sd_get_device_health_settings(&now);
check(same_values(now, wanted), "and they change nothing");
SDContextParams none;
check(none.apply_device_health_option(), "without the option there is nothing to do");
sd_get_device_health_settings(&now);
check(same_values(now, wanted), "and nothing changes");
check(params.to_string().find("device_health: \"levels=2,step=20\"") != std::string::npos,
"the parameters printed at start name the option");
sd_set_device_health_settings(&saved);
}
int main() {
test_parse();
test_option_and_values();
std::printf("\n%s (%d failures)\n", failures == 0 ? "ALL TESTS PASSED" : "TESTS FAILED", failures);
return failures == 0 ? 0 : 1;
}

View file

@ -1,7 +1,8 @@
// 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.
// watchers (sources, durations, critical), the same card seen by two backends, what the levels offer (the share of
// a device and the threads of the CPU) and the values, changed at run time and through the C API. 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 \
@ -307,9 +308,23 @@ static void test_settings() {
settings = DeviceHealth::Settings();
settings.step_percent = 40;
check(!health.set_settings(settings), "steps that would leave nothing before exclusion are refused");
settings.step_percent = 1431655766;
check(!health.set_settings(settings), "even when the step times the levels does not fit in an int");
settings = DeviceHealth::Settings();
settings.cpu_thread_step_percent = 1431655766;
check(!health.set_settings(settings), "and so are such steps for the CPU threads");
settings = DeviceHealth::Settings();
settings.quiet_period = std::chrono::seconds(0);
check(!health.set_settings(settings), "a quiet period of zero is refused");
settings.quiet_period = std::chrono::seconds(24 * 60 * 60 + 1);
check(!health.set_settings(settings), "a quiet period longer than a day is refused");
settings.quiet_period = std::chrono::seconds(24 * 60 * 60);
check(health.set_settings(settings), "a day is accepted");
settings = DeviceHealth::Settings();
settings.event_spacing = std::chrono::seconds(-1);
check(!health.set_settings(settings), "a negative spacing of events is refused");
settings.event_spacing = std::chrono::seconds(24 * 60 * 60 + 1);
check(!health.set_settings(settings), "a spacing of events longer than a day is refused too");
settings = DeviceHealth::Settings();
settings.step_percent = 20;
check(health.set_settings(settings), "sensible settings are accepted");
@ -327,6 +342,50 @@ static void test_settings() {
"and changes nothing for the events of the engine");
}
// New settings while components are under strain or excluded: each one stays in its state, and the same settings
// written again change nothing, so the models are not placed again for nothing.
static void test_settings_change_at_run_time() {
DeviceHealth health;
prepare(health);
for (int i = 0; i < 4; ++i) {
health.note_strain("CUDA0", "compute failed");
advance(10);
}
for (int i = 0; i < 3; ++i) {
health.note_strain("Vulkan1", "compute failed");
advance(10);
}
health.report("CPU", signal("termico", 3, 600));
const auto before = health.revision();
check(health.set_settings(DeviceHealth::Settings()) && health.revision() == before,
"the same settings written again change nothing, not even the revision");
DeviceHealth::Settings two;
two.strain_levels = 2;
check(health.set_settings(two) && health.revision() != before, "fewer levels are accepted and change the revision");
check(health.excluded("CUDA0"), "an excluded device stays excluded with fewer levels");
check(health.level("Vulkan1") == 2 && !health.excluded("Vulkan1"),
"a device on the last level of strain moves to the new last one, not to exclusion");
check(health.level("CPU") == 2 && !health.excluded("CPU"), "and so does the level a signal holds");
DeviceHealth::Settings five;
five.strain_levels = 5;
five.step_percent = 10;
five.cpu_thread_step_percent = 15;
check(health.set_settings(five), "more levels are accepted");
check(health.excluded("CUDA0") && health.level("CUDA0") == 6, "an excluded device stays excluded with more levels");
check(health.level("Vulkan1") == 2 && same(health.share("Vulkan1"), 0.80), "a device under strain keeps its level, with the new step");
advance(400);
check(health.level("CPU") == 2, "a signal keeps holding its level after the change, past a quiet period");
DeviceHealth held;
prepare(held);
held.report("Vulkan1", signal("termico", 4, 3600));
check(held.set_settings(five) && held.excluded("Vulkan1"), "an exclusion held by a signal stays an exclusion with more levels");
advance(400);
check(held.excluded("Vulkan1"), "and the signal keeps holding it past a quiet period");
}
static void test_snapshot_and_revision() {
DeviceHealth health;
prepare(health);
@ -388,6 +447,63 @@ static void test_c_api() {
health.reset();
}
// The C functions a host reads and changes the values with: read them, change some, write them back.
static void test_c_api_settings() {
DeviceHealth& health = sd::device_health();
prepare(health);
sd_device_health_settings_t settings = {};
sd_get_device_health_settings(&settings);
check(settings.strain_levels == 3 && settings.step_percent == 15 && settings.cpu_thread_step_percent == 25 &&
settings.quiet_period_seconds == 300 && settings.event_spacing_seconds == 10,
"the C API reads the values: 3 levels, 15% and 25% per level, 300 s, 10 s");
settings.strain_levels = 2;
settings.step_percent = 20;
settings.cpu_thread_step_percent = 30;
settings.quiet_period_seconds = 60;
settings.event_spacing_seconds = 5;
check(sd_set_device_health_settings(&settings), "and writes new ones");
health.note_strain("CUDA0", "compute failed");
check(same(health.share("CUDA0"), 0.80), "which the registry uses: the step");
advance(59);
check(health.level("CUDA0") == 1, "and the quiet period");
advance(1);
check(health.level("CUDA0") == 0, "to the second");
health.note_strain("CPU", "too hot");
check(health.cpu_threads(10) == 7, "the CPU step: 10 threads to 7");
advance(4);
health.note_strain("CPU", "too hot");
check(health.level("CPU") == 1, "and the spacing: an event 4 s later counts once");
advance(1);
health.note_strain("CPU", "too hot");
check(health.level("CPU") == 2, "one 5 s later counts again");
sd_device_health_settings_t read_back = {};
sd_get_device_health_settings(&read_back);
check(read_back.strain_levels == 2 && read_back.step_percent == 20 && read_back.cpu_thread_step_percent == 30 &&
read_back.quiet_period_seconds == 60 && read_back.event_spacing_seconds == 5,
"the values read back are the ones written");
const size_t count = sd_get_device_health(nullptr, 0);
std::vector<sd_device_health_t> entries(count);
sd_get_device_health(entries.data(), entries.size());
check(count > 0 && entries[0].strain_levels == 2, "the entries carry the new number of levels");
sd_device_health_settings_t wrong = read_back;
wrong.step_percent = 50;
check(!sd_set_device_health_settings(&wrong), "values that make no sense are refused: 2 levels of 50% leave nothing");
wrong = read_back;
wrong.quiet_period_seconds = 24 * 60 * 60 + 1;
check(!sd_set_device_health_settings(&wrong), "as is a quiet period longer than a day");
sd_get_device_health_settings(&read_back);
check(read_back.step_percent == 20 && read_back.quiet_period_seconds == 60, "and change nothing");
check(!sd_set_device_health_settings(nullptr), "a missing pointer is refused");
sd_get_device_health_settings(nullptr);
check(health.settings().strain_levels == 2, "and reading into none changes nothing either");
health.set_settings(DeviceHealth::Settings());
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");
@ -457,10 +573,12 @@ int main() {
test_resume();
test_cpu_threads();
test_settings();
test_settings_change_at_run_time();
test_snapshot_and_revision();
test_backend_names();
test_engine_hooks();
test_c_api();
test_c_api_settings();
std::printf("\n%s (%d failures)\n", failures == 0 ? "ALL TESTS PASSED" : "TESTS FAILED", failures);
return failures == 0 ? 0 : 1;

View file

@ -15,8 +15,13 @@ Through POST /sdcpp/v1/devices/{device}/pressure it checks that:
- 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.
- a second server, with --guardian off and --device-health levels=2,step=20,quiet=5, never halts: a critical report
only changes device health; its components have two levels of strain (80%, 60%, then excluded) and come back one
step every 5 s;
- termico.py osserva --segnala, with the fake GPU of test/termico_test.py, reports to that server: the attention
band as level 1, and the critical band as level 2, the last of the two, not as an exclusion;
- sd-cli, next to the server or given with --cli, applies --device-health at start, in the DGL mode too, and
refuses values against the rules.
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
@ -335,10 +340,10 @@ def run_scenarios(client, args):
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."""
def run_termico(client, args, temperature, mask, band, level):
"""termico.py osserva --segnala with the fake GPU of test/termico_test.py at the given temperature: its report
reaches the server as that level 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; the CPU then comes back with the quiet periods of 5 s."""
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"))
@ -349,7 +354,7 @@ def run_termico(client, args):
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")):
for name, value in (("temp", str(temperature)), ("mask", mask.zfill(16))):
with open(os.path.join(folder, name), "w") as handle:
handle.write(value)
environment = dict(os.environ, FAKE_DIR=folder)
@ -363,38 +368,72 @@ def run_termico(client, args):
def reported():
cpu.update(device(client.health()[1], "CPU"))
return cpu.get("level") == 1 and cpu.get("held_ms", 0) > 0
return cpu.get("level") == level 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"))
check(seen and "termico: GPU a %d C, fascia %s" % (temperature, band) in cpu.get("reason", "") and cpu.get("excluded") is False,
"termico.py --segnala at %d C: the %s band reaches the server as level %d of 2, with the reason (%s)" %
(temperature, band, level, 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(process.returncode == 0 and after.get("held_ms") == 0 and 0 < after.get("level", 0) <= level,
"termico.py --segnala: when it ends its signal is withdrawn, and the level does not drop at once")
check(wait_until(lambda: device(client.health()[1], "CPU").get("level") == 0, 5 * level + 10),
"termico.py --segnala: the CPU comes back one step every 5 s")
check(args.api_key not in output, "termico.py --segnala: the API key does not appear in its output")
return output
finally:
shutil.rmtree(folder, ignore_errors=True)
def run_guardian_off(args, log_path):
"""The second server: --guardian off, and the values of device health changed with --device-health."""
with open(log_path, "wb") as log:
process, base_url = start_server(args, log, ["--guardian", "off"])
process, base_url = start_server(args, log, ["--guardian", "off", "--device-health", "levels=2,step=20,quiet=5"])
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")
check(health.get("devices") and all(entry.get("strain_levels") == 2 for entry in health["devices"]),
"--device-health levels=2: every component has two levels of strain")
shares = []
for level in (1, 2, 3):
status, body, _ = client.pressure("disk", {"level": level, "source": "e2e", "duration_seconds": 60})
disk = body.get("device", {}) if status == 200 else {}
shares.append((disk.get("share_percent"), disk.get("excluded")))
check(shares == [(80, False), (60, False), (0, True)],
"--device-health step=20: the levels offer 80%% and 60%%, and level 3 excludes (%s)" % shares)
client.pressure("disk", {"level": 0, "source": "e2e"})
check(wait_until(lambda: device(client.health()[1], "disk").get("level") == 0, 30),
"--device-health quiet=5: withdrawn, the disk comes back one step every 5 s")
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)
run_termico(client, args, 82, "4", "attenzione", 1)
output = run_termico(client, args, 88, "1", "critica", 2)
check("2 livelli di sforzo" in output, "termico.py --segnala: the critical band stops at the last of the two levels, and it says so")
finally:
stop_server(process)
def run_cli_option(args):
"""--device-health in sd-cli, in the DGL mode that checks a script without loading a model: a value against the
rules stops the program at start, and a valid one is applied and named in the log."""
here = os.path.dirname(os.path.abspath(__file__))
script = os.path.join(here, "..", "docs", "dgl", "sd", "sd1-5-txt2img.dgl")
command = [args.cli, "-M", "dgl", "--script", script, "--check", "--device-health"]
wrong = subprocess.run(command + ["levels=0"], capture_output=True, text=True, timeout=120)
check(wrong.returncode == 1 and "--device-health: levels=0" in wrong.stdout + wrong.stderr,
"sd-cli --device-health levels=0: refused at start, with the rules")
right = subprocess.run(command + ["quiet=600"], capture_output=True, text=True, timeout=120)
check(right.returncode == 0 and "device health: 3 levels of strain" in right.stdout + right.stderr and
"a quiet period of 600 s" in right.stdout + right.stderr,
"sd-cli --device-health quiet=600: applied in the DGL mode too, and named in the log")
def log_lines(path, offset=0):
with open(path, "rb") as handle:
handle.seek(offset)
@ -404,6 +443,7 @@ def log_lines(path, offset=0):
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("--cli", help="path to sd-cli, for its --device-health (default: next to --server; skipped if it is not there)")
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)")
@ -450,6 +490,13 @@ def main():
except Abort as error:
check(False, "--guardian off: " + str(error))
if not args.cli:
args.cli = os.path.join(os.path.dirname(args.server), "sd-cli" + (".exe" if os.name == "nt" else ""))
if os.path.isfile(args.cli):
run_cli_option(args)
else:
print("sd-cli not found at %s: its --device-health is not checked" % args.cli)
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,

View file

@ -4,7 +4,7 @@
Non serve nessuna GPU, nessun driver e nessun modello: la GPU e il motore sono processi e server locali che il
test crea e distrugge. Serve solo Python 3.8 o più recente, senza pacchetti.
python3 test/termico_test.py tutto (circa 1-2 minuti)
python3 test/termico_test.py tutto (circa 2-3 minuti)
python3 test/termico_test.py --veloce solo le prove delle funzioni, senza lanciare il programma
Codice di uscita 0 = tutti i controlli superati. Su Windows la prova della sessione guidata (che usa uno
@ -193,12 +193,15 @@ NOME_GPU_FINTA = "NVIDIA GeForce RTX 3060 Laptop GPU"
class MotoreFinto:
DISPOSITIVI = ("CPU", "CUDA0", "Vulkan0", "RAM", "disk")
def __init__(self, chiave=None, stato="ok", profilo="max", descrizione_gpu="gpu", ritardo_segnali=0.0):
def __init__(self, chiave=None, stato="ok", profilo="max", descrizione_gpu="gpu", ritardo_segnali=0.0, livelli=3,
livelli_in_salute=True):
self.chiave = chiave
self.stato = stato
self.profilo = profilo
self.descrizione_gpu = descrizione_gpu
self.ritardo_segnali = ritardo_segnali
self.livelli = livelli # livelli di sforzo dei device (--device-health); None = un motore che non li dice
self.livelli_in_salute = livelli_in_salute # False: li dicono solo le risposte alle segnalazioni
self.richieste = []
self.segnali = [] # (device, corpo) di ogni segnalazione accettata, in ordine
self.avvio = time.time()
@ -226,14 +229,17 @@ class MotoreFinto:
passato = time.time() - motore.avvio
if self.path == "/sdcpp/v1/health":
riuscite = int(passato / 1.5)
return self.rispondi(503 if motore.stato == "unavailable" else 200, {
corpo = {
"status": motore.stato, "model_loaded": True, "profile": motore.profilo,
"base_profile": "max", "degradation": True, "busy": True,
"counters": {"requests": riuscite + 1, "succeeded": riuscite, "failed": 0, "cancelled": 0,
"recovered": 0, "step_downs": 0, "promotions": 0, "failed_promotions": 0,
"rebuilds": 1},
"last_error": None, "next_promotion_seconds": None, "uptime_seconds": int(passato) + 100,
"version": "stable-diffusion.cpp finto", "queue": {"pending": 1, "waiting": 0, "max": 64}})
"version": "stable-diffusion.cpp finto", "queue": {"pending": 1, "waiting": 0, "max": 64}}
if motore.livelli is not None and motore.livelli_in_salute:
corpo["devices"] = [motore.stato_device(nome) for nome in MotoreFinto.DISPOSITIVI]
return self.rispondi(503 if motore.stato == "unavailable" else 200, corpo)
if self.path == "/sdcpp/v1/resources":
return self.rispondi(200, {
"system_memory": {"total_bytes": 17179869184, "available_bytes": 9126805504,
@ -262,8 +268,12 @@ class MotoreFinto:
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"})
# Come sd-server: un livello oltre l'esclusione è rifiutato.
livello = corpo.get("level") if isinstance(corpo, dict) else None
if isinstance(livello, int) and not 0 <= livello <= (motore.livelli or 3) + 1:
return self.rispondi(400, {"error": "level out of range", "code": "invalid_report"})
motore.segnali.append((dispositivo, corpo))
self.rispondi(200, {"device": {"name": dispositivo, "level": 0}, "guardian": {"enabled": True, "halted": False}})
self.rispondi(200, {"device": motore.stato_device(dispositivo), "guardian": {"enabled": True, "halted": False}})
do_PUT = do_DELETE = do_PATCH = altro
@ -272,6 +282,13 @@ class MotoreFinto:
self.thread.start()
self.url = "http://127.0.0.1:%d" % self.server.server_address[1]
def stato_device(self, nome):
stato = {"name": nome, "level": 0, "share_percent": 100, "excluded": False, "critical": False, "reason": "",
"held_ms": 0, "next_step_ms": 0}
if self.livelli is not None:
stato["strain_levels"] = self.livelli
return stato
def ferma(self):
self.server.shutdown()
self.server.server_close()
@ -515,6 +532,13 @@ def prove_funzioni_segnala(tm):
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")
P = tm.livello_per_il_motore
controlla(P(1, 3) == 1 and P(3, 3) == 3 and P(0, 3) == 0 and P(tm.LIVELLO_ESCLUSO, 3) == "excluded",
"livello_per_il_motore: con tre livelli le fasce passano come sono, l'esclusione si manda per nome")
controlla(P(3, 2) == 2 and P(2, 2) == 2 and P(2, 1) == 1 and P(3, 1) == 1 and P(tm.LIVELLO_ESCLUSO, 1) == "excluded",
"livello_per_il_motore: con meno livelli una fascia si ferma all'ultimo e non diventa un'esclusione")
controlla(P(3, None) == 3 and P(3, 5) == 3 and P(1, 5) == 1,
"livello_per_il_motore: un motore che non dice i livelli ne ha tre; con più livelli le fasce restano 1, 2, 3")
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)
@ -880,6 +904,34 @@ def prove_segnala(gpu, base):
"--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")
# Un motore con meno livelli di sforzo (--device-health levels=2, o 1): le fasce si fermano all'ultimo e nessuna
# diventa un'esclusione; un motore che non dice i livelli ne ha tre.
# La GPU già critica al primo campione: i livelli si chiedono prima del primo segnale. Un motore che li dice solo
# nelle risposte: dalla seconda segnalazione valgono quelli.
casi = ((2, True, [(82, "4"), (82, "20"), (88, "1"), (88, "40"), (60, "1")], [1, 2, "excluded", 0]),
(1, True, [(82, "4"), (88, "1"), (88, "40"), (60, "1")], [1, "excluded", 0]),
(2, True, [(88, "1"), (60, "1")], [2, 0]),
(2, False, [(82, "4"), (88, "1"), (60, "1")], [1, 2, 0]),
(None, True, [(88, "1"), (60, "1")], [3, 0]))
for livelli, in_salute, passi, attesi in casi:
motore = MotoreFinto(descrizione_gpu=NOME_GPU_FINTA, livelli=livelli, livelli_in_salute=in_salute)
try:
codice, uscita, _ = osserva_con_passi(gpu, ["--segnala", "--motore", motore.url, "--ogni", "0.3",
"--durata", str(int(1.5 * len(passi)) + 2),
"--uscita", os.path.join(base, "segnala-livelli-%s-%d" % (livelli, len(passi)))],
passi, 1.5)
segnali = list(motore.segnali)
finally:
motore.ferma()
quale = ("a %d livell%s" % (livelli, "o" if livelli == 1 else "i")) if livelli else "che non dice i livelli"
if not in_salute:
quale += ", detti solo nelle risposte"
elif passi[0][0] >= 87:
quale += ", con la GPU già critica"
controlla(codice == 0 and livelli_di(segnali) == attesi and (livelli is None or "di sforzo" in uscita) and
"rifiutata" not in uscita,
"--segnala con un motore %s: manda %s, e con meno di tre livelli lo dice (%s)" % (quale, attesi, livelli_di(segnali)))
# Device indicato, chiave API, ritiro alla fine.
protetto = MotoreFinto(chiave="k-77", descrizione_gpu=NOME_GPU_FINTA)
try: