docs/cuda_e_vulkan_stessa_scheda.md (nuova): con CUDA e Vulkan nella stessa cartella una scheda NVIDIA è
CUDA0 e Vulkan0. Dice come si presenta nel log (l'elenco dei dispositivi e il piano con `same GPU as CUDA0`),
cosa succede se qualcuno nomina Vulkan0 e cosa dicono i due avvisi nuovi (backend fissato sul gemello, pesi
che restano su disco e vengono riletti a ogni passo), i tempi misurati su un portatile con le avvertenze (la
RAM quasi piena conta, la differenza non è tutta del backend), cosa fare a mano e da un altro programma, la
prova rapida che nasconde ggml-vulkan.dll, un controllo della RAM in PowerShell, e cosa è verificato e cosa
no.
docs/backend.md: nel punto sulla scheda elencata da due backend, che un `--backend` sul gemello passa da quel
backend e il log lo dice; un punto nuovo sui pesi su disco. docs/convivenza_applicazioni.md: il rimando, e la
corrispondenza degli indirizzi PCI su una macchina reale esce dall'elenco del non verificato (la riga
`same GPU as CUDA0` compare nel log di un portatile con RTX 3060). docs/integrazione_progetti.md (2.9) e README:
il rimando.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
check_plan_warnings() in backend_fit_plan_test.cpp, with simulated devices:
- --backend vulkan0 on a card CUDA lists as CUDA0: one warning naming both
listings and what to pass instead; still one when several modules run on it;
none when the modules run on CUDA0; none when the listings report no PCI id;
- two cards each listed twice: none for the CUDA pair, one per card for the
Vulkan pair;
- two Vulkan listings of one card: the owner is named, the other backend is
not called slower;
- Pony-sized weights on a 5 GiB card with 3 GiB of RAM budget: the warning
names the diffusion model and its size, says it is read at every sampling
step and gives the free RAM and the budget; none for an unknown amount of
RAM or for weights that wait in RAM; a module other than the diffusion model
is not said to be read at every step.
Three variants of the code were also tried (no deduplication of the listings,
the slower-backend remark on equal ranks, a warning for unknown RAM): each one
makes a check fail. The row of test/README.md is extended.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Two things that made a generation take many times longer were visible in the
plan only as a device line or a "params disk" label, with nothing saying what
they cost.
- A GPU that several backends list (an NVIDIA card is both CUDA0 and Vulkan0)
is left out of the automatic choice when another backend already provides
it, but the user, or a program that starts the engine, can still name it.
With --backend vulkan0 the run goes through Vulkan, measured 12 to 22 times
slower than CUDA on the same card, and the log did not say so. Each shadowed
listing a module runs on now gets one warning that names the listing that
the automatic choice uses. The remark about generic graphics APIs is added
only when the owner's backend ranks above the shadowed one, so two Vulkan
listings of one card are not called slower than each other.
- Weights that fit neither the compute device nor the RAM budget stay in the
model file and are read again every time their module runs, the diffusion
model at every sampling step. One warning names the modules, their size, the
free RAM and the budget, and says what helps (closing programs, --type, a
quantized file). Nothing is said when the amount of free RAM is unknown, or
with --cpu-only plans, which print their own note.
The plan itself does not change: both warnings are only log lines after it.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Section 2.9 of docs/integrazione_progetti.md says what the new release file
holds, why the Vulkan zip must not be unpacked over the CUDA one, which script
assembles it and when that script stops. docs/convivenza_applicazioni.md
points to it from the paragraph about CUDA and Vulkan in the same folder.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The test builds small fake zips with the file names of the release zips and
runs scripts/package_windows_cuda_vulkan.sh on them; it needs zip and unzip,
and no build, GPU or model. Checks:
- the package has one folder named like the zip, 26 entries, the programs and
stable-diffusion.dll from the CUDA zip, only ggml-vulkan.dll from the Vulkan
zip, the CUDA runtime DLLs and a LEGGIMI.txt that names the commit;
- no warning when the DLLs shared by the two builds have the same size, a
warning when ggml-base.dll differs;
- the script can run twice in the same directory;
- it refuses a missing or doubled zip, zips of different commits, a Vulkan
zip without ggml-vulkan.dll, a CUDA zip without ggml-cuda.dll, a runtime
zip without cublas, a LEGGIMI.txt that a zip already has, and a file held by
two zips, and it leaves no zip behind.
Each guard of the script was also taken out one at a time (11 variants): a
check fails for ten of them. The eleventh, the final comparison of the file
count, is a last-resort invariant that none of the fake inputs reaches.
The file is added to the allow-list of test/ in .gitignore and to
test/README.md.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The CUDA and Vulkan zips of a release hold the same file names built
differently: stable-diffusion.dll has the CUDA code only in the CUDA zip, so
unpacking one zip over the other leaves a mixture of two builds. A new step of
the release job assembles a third package from the zips of the same run: the
CUDA zip, the CUDA runtime zip and ggml-vulkan.dll from the Vulkan zip, in one
folder with a LEGGIMI.txt. The backends are separate modules loaded side by
side, so nothing else of the Vulkan zip is needed.
scripts/package_windows_cuda_vulkan.sh stops, and the release with it, when a
zip is missing or there are two of a kind, when the CUDA and Vulkan zips come
from different commits, when two zips hold a file with the same name, when a
required file is missing from the package, or when the file count of the
result does not match the inputs. It warns when ggml-base.dll or ggml.dll have
a different size in the two zips, which means two different ggml builds.
The release notes list the new file first and tell people not to unpack the
Vulkan zip over the CUDA one.
Run on the three zips of master-1025-2ab1ed6: 26 files, 878 MiB, every file
has the size and CRC-32 of its source file. The step itself runs only in the
release job (push to master or a manual run with create_release), so a pull
request does not exercise it.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
backend.md (several GPUs): a card that CUDA and Vulkan both list counts once,
the vendor's backend keeps it and the other listing is shown in the plan as
not used automatically; an integrated GPU is the main device only when no
graphics card has memory left and never holds parked weights.
convivenza_applicazioni.md: the same for the case of CUDA and Vulkan in one
folder on a laptop, with the note that it adds no speed because a module is
not divided between backends. The match of the PCI ids on a real machine is
listed among the things that are not verified yet: the logic is only tested
with simulated devices.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Simulated devices, so no GPU and no model are needed. New checks:
- the main device is a graphics card even when an integrated GPU reports more
memory, an integrated GPU only when no card has a budget, and the largest
budget still wins among cards;
- a card listed by CUDA and by Vulkan is one GPU whatever the order of the
listing: the vendor's backend keeps it, three listings of one card reduce to
one, listings without a PCI id are never matched;
- a laptop with a card, an integrated GPU and both backends plans like the
CUDA-only machine: nothing is parked in the integrated GPU's shared memory,
the diffusion weights wait on disk, and the planner has nothing to say about
"different backends";
- weights still wait in the memory of a second graphics card, and not in that
of the card the module computes on under another backend;
- two cards each listed twice, with Vulkan reporting a little more memory,
still split the diffusion model across the two CUDA devices;
- 12000 random plans with twin listings, integrated GPUs and shuffled order:
the main device is never an integrated GPU while a card has a budget or a
shadowed listing, the multi-GPU group holds only cards listed once, no
module lands on a shadowed listing, and parked weights go only to another
card.
Each rule was also put back to its old form one at a time (9 variants) to
check that at least one of the new checks fails for it.
The existing block "an integrated GPU keeps the modules it hosts" started from
the old choice of the integrated GPU as the main device; it now puts the
modules there explicitly and checks the same things.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
--offload-to-cpu, like any explicit --params-backend, turns the automatic
placement off, and nothing in the log said so: the run showed no "auto-fit"
line at all and the placement looked unexplained. One line now gives the
reason and the --backend that applies together with it. It is printed only
when auto-fit was enabled and an explicit params backend switched it off.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The planner chose the main device by the largest budget alone. With the CUDA
and the Vulkan backends installed side by side on a laptop, the integrated GPU
won: it reports the shared system RAM as its memory, which is more than the
graphics card has free. The whole model then ran on it. In a measured
1024x1024 SDXL run (25 steps) that took 745 s, against 167 s with the same
model on the card. The card was also listed twice, as CUDA0 and as Vulkan0,
so the planner counted two discrete GPUs of different backends and the same
memory twice.
- select_main_device prefers a graphics card. An integrated GPU is chosen only
when no card has a budget, and the second listing of a card never is.
- Listings that share a PCI bus id (ggml_backend_dev_props.device_id) are one
GPU. The listing of the vendor's backend keeps it; the one through Vulkan or
OpenCL is marked as shadowed. It stays in the list, so it can still be named
with --backend, but it is not chosen automatically, does not join the
multi-GPU group and receives no weights. Devices that report no id cannot be
matched and are left as they are.
- Weights that fit neither the GPU nor the RAM budget wait in the memory of
another GPU only if that GPU has memory of its own. The "memory" of an
integrated GPU is the RAM that was just found too small, and the card a
module computes on, seen through another backend, is not another GPU.
- The device list printed with the plan says which listing is not used and
why.
A machine with one backend and no integrated GPU plans exactly as before.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The test writes a small safetensors file and loads it into host tensors
through ModelLoader::load_tensors, which is internal to the library, so it is
linked against the compiled library; no GPU and no model are needed.
It checks that the fastest of ten loads of 16 tensors (and of 3) returns in
under 100 ms, that the data read is exact, and that a tensor refused by the
callback fails the load at once. Before the previous change a load of more
than four tensors took 200 ms at least; after it, about a millisecond.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
ModelLoader::load_tensors polled for the end of the workers with a sleep of
200 ms (10 ms for at most four tensors) and printed the progress line at
every wake-up. The sleep was also the polling interval, so every load of more
than four tensors took at least 200 ms, even when the tensors were already in
the page cache or on the device and the workers had finished after a few
milliseconds.
The cost is invisible when a model is loaded once, but streamed weights are
loaded segment by segment at every sampling step. In a 25-step SDXL run with
the diffusion weights on disk, about 300 of the 460 loads of the sampling
phase took one full tick (0.20-0.23 s) with almost nothing to read and about
100 took two ticks, roughly 4 of the 6.4 s of each step. The same floor is
paid by the --offload-to-cpu path.
Completion is now polled every millisecond. The progress line keeps its
cadence (the first line immediately, then no more often than every 200 ms,
10 ms for at most four tensors), and the loop, the join of the workers and the
failure handling are unchanged. A load of 16 small tensors goes from 200 ms
to about 1 ms.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
README.md lists the two new pieces next to the other additions of the
fork: scripts/diagnostica_termica/ and docs/agenti_indipendenti.md.
docs/convivenza_applicazioni.md points to termico.py in the section where
the reader tries the engine next to another application (its guided
session already has the phases of that test and writes a JSON file to
attach to a report), says in the list of what is not checked that the
behavior over many minutes is still to be measured, and points to the
agents guide from the contract for programs that start the engine.
docs/integrazione_progetti.md points to the agents guide from section 3.6
(the engine as a tool of an AI assistant) and adds changelog entries 22
(thermal diagnostics) and 23 (independent agents), each with what was
checked and what was not, and the next steps now include trying termico.py
on a real NVIDIA GPU and on Windows and the guardian with a real GPU under
load.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
test/agenti_guardiano_test.py extracts the Python code from section 9 of
docs/agenti_indipendenti.md and runs it, so the document and the test
cannot drift apart.
Without options (about 10 seconds, no network, model or GPU) it uses a
fake clock and a fake engine: 66 checks on a missing, broken, stale or
non-object status file, the four levels, the wait before restarting (also
with a reading that flickers around the threshold and after a gap in the
data), the hourly cap, the stop file, the decision log, 429 and 503 with
Retry-After, the API key, an engine that is off, deadlines, a stop that the
engine ignores, and a job the engine has already dropped. The fake clock
gives up after five minutes of fake time, so a guardian that never stops
fails quickly instead of hanging the test.
With --server and --model (about 2 minutes with a small model, any
backend, CPU included) it adds 25 checks on the real chain: a real
sd-server, termico.py watching the fake GPU of test/termico_test.py, and
the guardian. A critical GPU stops the job with cancel (/health counts one
more cancelled and no profile step-down); after the wait the guardian
starts again and the job completes; a job of another program is left
alone; with the observer stopped nothing starts; a job in progress without
data goes on until its own deadline and is then stopped; the stop file
stops and blocks; the usage example of the document runs.
The file is added to the .gitignore allowlist and to test/README.md, and
it does not leave __pycache__ behind.
While writing it, 26 deliberate faults were put in the guardian code (a
wrong threshold, a guard removed, an API key not sent, a wait that does
not restart, ...) and the test caught all of them; the script that does
this is not part of the repository.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
docs/agenti_indipendenti.md is for whoever builds, outside this
repository, an AI, a language model, a neural network, an agent or a main
node that uses the engine and the data of termico.py, and wants it to be
independent: to decide with its own judgment, stay faithful to commands
without being a slave to them, and not overload the machine or itself.
The engine is not the brain and not a real-time control: it samples about
once a second and a stop arrives at the next step of the computation. The
guide says so first, then writes the character the requester described
(independent, faithful but not rigid, honest, caring, fair, picky, able
to say no) as requirements with a way to check each one. "Odioso" is read
as picky even when it is inconvenient, not hostile, and the guide neither
affirms nor excludes that a program could be sentient.
Contents: three levels (machine, a small deterministic guardian, the
agent) where a higher level may ask but never override a lower one;
faithfulness as a table by kind of command; "independent does not mean
unstoppable" (a stop that does not go through the agent, closing its own
jobs on exit, a guardian in its own process); fairness (only its own
jobs, the same rule for the same cases, the minimal measure, an
explanation, contestable); how to combine the GPU and engine data and how
old data counts as unknown, not normal; a table of rules against overload
(one observer and many readers, intervals, deadlines, retries with growing
waits, a circuit breaker, a fixed rhythm, caps on reasoning, a small
context, clean-up on exit, back-pressure); a 137-line standard-library
guardian that stops its own job when the GPU is critical and restarts only
after 60 seconds of normal readings; and a ten-row checklist to test a
real agent, including a way to do it without heating anything by starting
termico.py with lowered thresholds.
The character requirements are design requirements, not demonstrated
behavior: no real agent was tried. Also not checked: a real GPU, Windows,
more than one machine, reaction times under a real load. The test that
runs the guardian code is added in the next commit.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
test/termico_test.py runs scripts/diagnostica_termica/termico.py and
carico_motore.py without a GPU, a driver or a model. A stand-in for
nvidia-smi (a Python file the test writes, with state files it can change
while the program runs) answers the field queries, the throttling
reasons and the slowdown limits, and small HTTP servers answer like
sd-server for /health, /resources and the job routes.
127 checks, about 80 seconds (--veloce skips the ones that start the
program): temperature bands from the driver limits and the generic ones,
judgments and when they are withheld, trend, CSV reading and writing
including truncated rows, summary and status files, comparing runs, the
exit codes of `stato`, `osserva` read continuously without ever finding
the status file half written, a run interrupted by SIGTERM and by Ctrl+C,
the guided session driven like a person (including a stray Enter during an
automatic phase), engine off, engine that stops in the middle, right and
wrong API key, a GPU that answers intermittently or not at all, and the
API key never appearing in the output or in the files. For
carico_motore.py: Retry-After, 401, a server that is off, absurd values,
and the stop of its own job at the end.
The test never leaves __pycache__ next to the scripts it loads. The file
is added to the .gitignore allowlist and to test/README.md.
During development 42 deliberate faults were put in the two programs (a
wrong threshold, a forgotten throttling bit, an API key not sent, ...) and
the test caught all of them; the script that does this is not part of the
repository.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
scripts/diagnostica_termica/ lets someone who wants to run the engine on
their own hardware see how hot it gets and why, without installing
anything beyond Python and the NVIDIA driver.
termico.py samples nvidia-smi (temperature, power, clocks, utilization,
memory and the throttling reasons) during a guided session in phases
(idle, engine, chat, both together), or continuously with `osserva`.
With --motore it adds, on the same timeline, what sd-server reports in
/sdcpp/v1/health and /resources (busy, queue, jobs succeeded, failed and
cancelled, profile step-downs, free memory). It writes a CSV, a JSON
summary (termico-riepilogo/1) and a text report, and `confronta` puts
several runs side by side (termico-confronto/1).
For other programs, `osserva --file-stato` keeps a file with the latest
reading (termico-stato/1, replaced atomically so a reader never sees half
of it) and `stato` prints one reading with exit codes 0, 1, 2 and 3.
Temperature bands start from the limits the driver declares (attention
10 C below the slowdown limit, critical 3 C below) or from 80 and 87 C
when it does not say. Bands and judgments are labeled as indicative, and
a judgment is given only for phases that involve the engine or the chat
and for observations of at least 180 seconds.
carico_motore.py makes sd-server generate continuously with always the
same job, so a run has a repeatable load. It honors Retry-After, sends the
API key only when asked, and stops its own job on Ctrl+C.
The README is a step-by-step guide in Italian: first run in two minutes,
the full run, reading the results, observing without phases, comparing,
what the files contain, what the program does on the PC, common problems
and how to share a run.
Checked with a fake nvidia-smi and fake engines (test/termico_test.py,
next commit) and against a real sd-server built for CPU with the
synthetic model. Not checked: a real NVIDIA GPU and driver output,
Windows, laptops with more than one GPU, sessions of many hours.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
POST /sdcpp/v1/jobs/{id}/cancel now stops a job that has started, not only
one in the queue, and the documents still said it answered 409.
api.md describes the route as a table by state of the job (queued,
generating, finished, unknown), the wait parameter (0 to 60 seconds,
default 10), the 200 and 202 answers with examples, cancel_requested on
the job, the cancelled counter of /health and the cancel_queued and
cancel_generating capabilities. It says what to expect: the stop arrives
at the end of the sampling step in progress, a stopped job returns no
images, a stop is not a failure, and the synchronous endpoints are not
jobs and cannot be stopped.
integrazione_progetti.md (in Italian) gets curl examples that can be
copied, how to read 200 and 202, how long a stop takes and why, the
reference to the capability for older servers, an update of the retry
tool that now stops a job that is generating, and a numbered entry in the
list of changes with what was tested and what was not (a real GPU, a video
model). convivenza_applicazioni.md and the README mention the new
behaviour where they described the old limit.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Python clients add Content-Length: 0 to a POST without a body, so they
never met the 5-second wait of the HTTP library; `curl -X POST` does. The
end-to-end test of the cancel route now also sends the request the way
curl does, written on a socket, once with ?wait=0 to a job that is
generating and once to a job that has completed, and requires the answer
in less than 2 seconds.
Against the previous route the answer took 5.10 s, so the new checks fail
on the code they are meant to guard. Against the fixed route all 32 checks
pass on a CPU build with a synthetic model.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
A plain cpp-httplib handler runs only after the library has read the body
of the request. For a POST with neither Content-Length nor chunked
encoding, which is what `curl -X POST <url>` sends, the library cannot know
that there is no body and waits for its read timeout of 5 seconds first.
The cancel route has no body, so stopping a job from the command line took
5 seconds longer than it should (15 s with the default wait, 5 s with
?wait=0).
The route now takes the body through a content reader, which is called
without reading anything first, and drains the body only when the request
announces one with Content-Length or Transfer-Encoding. The API key check
still runs before the route, as for every other route.
Measured on a real sd-server: `curl -X POST .../cancel` went from 5.1 s to
under a millisecond; a JSON body, a chunked body and a 2 MB body are still
accepted and ignored. The other POST routes of the server all need a JSON
body, so none of them is affected.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
server_cancel_e2e.py starts a real sd-server with any model the user has (or
talks to one that is already running) and checks the cancel route as a
client sees it: a job that is generating is stopped and ends as cancelled,
asking again is harmless, a queued job is cancelled without ever starting,
?wait=0 answers at once and the pending stop shows as cancel_requested, a
synchronous request that was waiting behind the cancelled job completes
normally, a finished job is left alone, an unknown id is 404, an invalid
wait is 400, /health counts the stopped jobs without a failure or a step
down, and stopping jobs writes no error line to the server log.
It uses 64x64 images and jobs that never run to the end, so its duration
does not depend on the number of steps; it starts with a warm-up job
because the first generation can read the weights from a slow disk. Only
the standard library is needed. It passed against a CPU build with a
synthetic model (31 checks, 182 s, almost all of it the warm-up).
The file is added to the allowlist in .gitignore and to test/README.md.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
server_recovery_test.cpp gains test_cancel() and test_cancel_threads(),
which need no model: the library and the clock are scripted as in the other
tests of the file.
test_cancel() checks that a stop reaches the context of the job that asked
for it and no other, that a repeated stop reaches the library each time
(the library forgets a request when a generation begins), that a job
cancelled before it starts, or while the model is loaded again, generates
nothing, that a cancelled run is counted on its own and never makes the
server step down, reload the model or record an error, and that the next
job runs on the same context.
test_cancel_threads() sends stops from another thread while jobs run, fail
and make the keeper rebuild its context. The hook that stands for the
library writes into the context it is given, so a stop that reached a
released context is reported by the address sanitizer.
All 149 checks pass plainly, with ASan+UBSan and with TSan, repeated 20, 8
and 8 times. Seven deliberate faults in recovery.cpp (a stop reaching any
running job, a context left registered after the run, no check before the
first attempt or after a reload, a cancellation counted as a failure, no
early stop on a recoverable failure, a cancellation that steps down) are
each reported by at least one check.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
A generation stopped on purpose with sd_cancel_generation() wrote several
[E] lines: "cancelling generation", "sampling for image 1/1 failed" and
"Diffusion model sampling failed". In a server log that looks like a fault,
and a client that cancels jobs would fill the log with them.
When the cancel flag is SD_CANCEL_ALL these messages are now INFO, and the
two that said "failed" say "cancelled". Failures that are not a cancellation
keep their ERROR level. Return values, error codes and the cancel flag
handling are unchanged.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
POST /sdcpp/v1/jobs/{id}/cancel used to answer 409 for a job that had
started. It now tells the library to stop and waits for the job to end:
200 with the cancelled job as soon as it has ended, or 202 with the job and
"cancel_requested": true when it is still stopping after ?wait= seconds
(0 to 60, default 10; 0 answers at once). Repeating the call is harmless,
and GET /sdcpp/v1/jobs/{id} shows the pending request. /capabilities now
reports cancel_generating as true.
The request belongs to the job: ContextKeeper::run() takes a CancelToken
and registers it, with the context, only while that job's attempt is
executing. A stop for one job can therefore never reach another request
(including a synchronous /sdapi one), a job cancelled before it reaches the
context generates nothing, and the context can be released or rebuilt
without cancel() ever touching a context that is gone.
The library forgets a stop request when a generation begins, so a request
that arrives a moment earlier would be lost. The route repeats it every
100 ms until the job ends.
A cancelled run is neither a failure nor a reason to step down: it does not
reload the model, does not touch last_error, and has its own counter,
counters.cancelled in /health. When a stop and a recoverable failure meet,
the stop wins and the model is not reloaded for a request nobody waits for.
Checked on a real sd-server with a CPU build and a synthetic model: stop of
a running job, repeated stop, queued job, job already finished, unknown id,
wait=0, invalid wait, and the next job on the same context. Tests and
documentation follow in separate commits.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The engine is a separate process and shares only physical resources with
whatever else runs on the machine: video memory, GPU time, RAM, CPU cores,
disk and a TCP port. docs/convivenza_applicazioni.md describes that for any
program, a local chat, another generator or an editor alike, without tying it
to one application.
It covers what the engine already does (--profile auto once at startup,
--auto-fit, --memory-guard, the server's step-down ladder) and what it does
not (no release of memory while idle, no cap on GPU compute, --profile auto
looking at the freest GPU even when --backend pins another), three recipes
(separate devices, taking turns, sharing one GPU under a budget), a minimal
contract for a program that starts the engine (port, child process lifetime,
503/429/409/401 handling) and the scenarios to run on a real PC.
Two behaviors found while checking the commands are documented and not
changed: on Linux two sd-server processes can listen on the same port without
an error because the bundled HTTP library sets SO_REUSEPORT, and with a
hand-written --backend the lite profile does not move the text encoder to the
CPU. Everything was checked on CPU only; the guide lists what a GPU run still
has to confirm.
Link the guide from the README and from docs/integrazione_progetti.md
(section 1 table, section 4 and changelog item 20).
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Section 3.6 of the Italian guide shows how a chat or a browser-controlling
agent calls the engine through sd-server: how to start it with no GPU, one GPU
or several (one server per GPU for throughput), presets expressed relative to
the defaults and limits the server reports, the JSON schema of two tools, a
reference implementation in the Python standard library, and the safety rules
for the host application. The implementation was run against a real server on
the CPU: success, invalid arguments, a wrong key, a stopped server, a timeout
with the job queued or already running, and the choice between two servers.
Running it showed server behavior that the guide documents and does not change:
the limits of /capabilities are not enforced (only 8 images and 1 to 100 steps
are), a <sd_cpp_extra_args> block in the prompt changes the parameters on the
OpenAI routes but not on /sdcpp/v1, and a job that has started cannot be
cancelled.
Also add the multi-GPU row and bullet to sections 1 and 4, two changelog
entries and the README bullets, and docs/studio_testo_a_diffusione.md, a study
of generating text with a diffusion language model. The study writes no engine
code: nothing about it can be verified without the model.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Add a section on several GPUs to the backend guide: what auto, on and off do,
what they never touch, and why a layer split does not make one image faster
(for throughput, run one server per GPU with its own --backend).
Correct two statements that did not match the code. The layer split fills the
devices in order, each up to its free memory less the compute reserve; it does
not size the ranges in proportion to the free memory. And auto-fit does now
choose multi-GPU placement itself, unless the module is assigned explicitly.
The performance guide says that --profile auto adds up the free memory of the
GPUs that auto-fit may use together, and shows the log lines.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
backend_fit_plan_test.cpp runs the auto-fit planner on simulated devices, so
it needs neither a GPU nor a model. It checks which module goes to which GPU
for --multi-gpu auto, on and off, when the diffusion model or the text encoder
is split, that integrated GPUs and other backends are left out, and that a
module the user assigned never moves. Eight more checks run over 18000
random machines: no device is given more weights than its budget less the
compute reserve, the shares of a split add up to the weights, and a module
that moved ends up with its weights resident.
profile_test.cpp gets the checks for the memory that --profile auto adds up
over several GPUs. Add the new test to the allowlist in .gitignore and to
test/README.md.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
--profile auto compared the model with the free memory of the single GPU with
the most. When --auto-fit may spread the model over several GPUs of one backend
(--multi-gpu is not off and neither --backend nor --params-backend is given),
add up their free memory, less 2 GiB of working memory for every GPU after the
first, so that a model that fits across two GPUs is not sent to the lite
profile. The log line says how many GPUs were added up.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
With more than one discrete GPU of the same backend, auto-fit used only the
one with the most free memory. A model that did not fit there was streamed
from RAM or disk while the other GPUs stayed idle.
--multi-gpu auto (the default) moves a module that does not fit next to the
modules placed before it to another GPU: first the text encoder or the VAE,
and when the diffusion model or the text encoder fits on no single GPU, it is
split across the fewest GPUs that can hold it, as --backend
"diffusion=cuda0&cuda1" does. on also moves the text encoder and the VAE away
from the GPU of the diffusion model when everything would fit on one, and off
keeps the previous single-GPU behavior.
Modules named in --backend, or split by rows, are never moved or split, and
only discrete GPUs of one backend are combined. The planner requires the free
memory of the GPUs, less the compute reserve of each, to exceed the weights by
10% plus 256 MiB per boundary, because blocks cannot be cut exactly where the
memory ends. A split saves memory but does not make one image faster.
The new field multi_gpu is appended to sd_ctx_params_t and sd_ctx_params_init()
sets it to the default.
Not run on real GPUs; the planner is covered by a test with simulated devices
in the next commits.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
fail-fast is on by default, so the failed CPU image cancelled the five other
images of the same run. The images do not depend on each other; let each one
finish.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
A bare --parallel makes CMake run make with an unlimited number of jobs. In
the CI the CPU image started about 400 compile jobs within a minute and the
builder was lost, while the other Dockerfiles already use -j$(nproc). Use the
same limit.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The guide told people to run ghcr.io/leejet/stable-diffusion.cpp:master,
which contains the original project and not the changes of this fork. Point
the examples at the images published by the CI of this repository, list the
available tags and show how to check that an NVIDIA GPU is visible.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The container job published the CUDA, Vulkan, MUSA and SYCL images but never
the CPU one, although docker/Dockerfile exists and the Docker guide starts
from it. Add a cpu variant, published as master-cpu next to the others.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The Quick Start still sent people to the releases page of the original
project, and the build guide cloned the original repository, so following
either one gave binaries and code without the changes of this fork. Use the
releases page and the repository of the fork instead.
The credits to the original author in the README are left unchanged.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The release was created with an empty description. Say which Windows zip
fits which GPU, that the CUDA build needs the cudart zip in the same folder,
and that the Visual C++ Redistributable 14.44 or newer is required.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The Windows packages are built with MSVC 14.44. When the runtime is missing
or older, Windows cannot load the DLLs and the program ends at once without
any output (exit code 0xC0000135), which looks like a silent failure of
--list-devices and shows up in host applications as code 3221225781.
State the minimum version, the link to the latest installer and how to check
the installed version in the README, the Italian guide (packages, common
problems, table of the Windows start-up exit codes), build.md,
troubleshooting.md and the LEGGIMI.txt written by package_portable.sh.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
stable-diffusion.dll linked the driver import library only to read the
compute capability of the device, so it imported nvcuda.dll at load time. On a
machine without an NVIDIA driver, such as the CI runner, sd-cli.exe could not
start at all (status 127 in Git Bash): the smoke test of the cuda12 portable
package failed, and the package would not have run on a CPU-only PC either.
The three driver functions are now looked up with LoadLibraryEx/dlopen the
first time a CUDA device is queried, and the library no longer links the driver.
The smoke test of the portable workflow now lists the DLLs a Windows
executable imports, and the ones that cannot be found, when it fails to start.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
package_portable.sh builds the zip from a temporary directory, so a relative
output directory such as the "dist" that the release-portable workflow passes
pointed to a place that does not exist and zip failed. Make the build and
output directories absolute before changing directory.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
recovery.cpp included recovery.h first, which reaches <windows.h> through
common/log.h. windows.h pulls in winsock.h, and the winsock2.h included by
httplib.h then redefines its declarations, so both Windows builds stopped
with hundreds of errors in the Windows SDK headers. Include httplib.h first,
as the other server sources do, and include <exception> in recovery.h for the
type it uses.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
A request that ran the machine out of memory ended in a 500 and left the
server on the configuration that had just failed, so every later request
of that size failed the same way. The context now belongs to a
ContextKeeper (examples/server/recovery.*) and every generation of the
OpenAI, sdapi and sdcpp endpoints goes through ContextKeeper::run().
On out_of_memory or backend (the codes of sd_get_last_error()) it frees
the model, loads it again with the next lighter profile of
max > balanced > lite > lite-disk > lite-cpu and runs the same request
again. Steps that would load the same configuration are skipped, a
device failure jumps to lite-cpu, and from lite on the VAE is decoded in
tiles whatever the request asked. --profile sets the top of the ladder.
After --degradation-cooldown seconds (300; 0 = never) the server climbs
back one profile at the start of the next request. A climb that fails
on its first use is undone and doubles the wait, up to an hour. If the
model cannot be loaded again, requests get 503 "unavailable" and the
load is retried no more than every 15 seconds. --disable-degradation
keeps the old behavior of answering with the error.
Failures are answered with 503 and Retry-After (out of memory, no
context), 400 (invalid_argument) or 500, with a body of
{"error", "code", "retry_after_seconds"}. Async jobs report the same
code in error.code, 429 carries Retry-After, and std::bad_alloc in a
handler becomes a 503. New endpoints: GET /sdcpp/v1/health (status,
profile, counters, last error, queue; it never waits for a running
generation) and GET /sdcpp/v1/resources (system memory and devices).
sd-server now exits with code 1 and a message when it cannot listen or
create its HTTP threads; the second used to end in std::terminate and
the first in a silent exit 0. The lite-disk profile clears --eager-load,
which read every weight into memory and so saved nothing.
test/server_recovery_test.cpp checks the ladder, the step downs, the
climb back, the reload after a failure, the HTTP answers and use from
several threads with a scripted library and clock (114 checks, also
under ASan/UBSan and TSan). Checked with a synthetic SD 1.5 model on
the CPU under address-space limits: a 384x384 request at 2400 MiB steps
down to lite-disk and succeeds, below 2200 MiB it answers 503 and the
server stays up, the climb back and a failed climb behave as described,
and nine parallel requests of the three kinds are all served. The server
and the whole engine built with ASan/UBSan went through the ladder, the
CPU memory-guard scenarios and injected read errors without a report.
Not checked: Windows, GPUs, real models.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
SDGenerationParams::resolved_hires_upscaler was assigned only when hires
was enabled, but to_sd_img_gen_params_t() and to_sd_vid_gen_params_t()
copy it into params.hires.upscaler on every request. With hires off that
copied an indeterminate enum value, which UBSan reports as "load of value
..., which is not a valid value for type 'sd_hires_upscaler_t'". The
library does not look at the field while hires is disabled, so nothing
changes in behavior; the member now starts as SD_HIRES_UPSCALER_NONE.
Found by running sd-server under UBSan.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
--profile max|balanced|lite|auto sets, in one option, what a small
machine needs: balanced turns the memory guard on at 90; lite also
puts the text encoder on the CPU, tiles the VAE, runs CFG unbatched
and lowers the guard to 85. An option given on the command line always
wins over the profile, including --memory-guard 0. A profile does not
touch --params-backend or --backend, so --auto-fit keeps deciding
where the weights live, and it never changes the size or the steps of
an image.
auto compares the size of the model files plus a working-memory
reserve with the free memory of the discrete GPU with the most, or
with the available RAM without one, and logs the figures it used. It
leaves the defaults alone when the sizes or the memory are unknown.
parse_options() now records which options were given, through
option_was_given(). The levels below lite (weights streamed from disk,
everything on the CPU) cannot be chosen from the command line; they
are the steps a server takes when a request runs out of memory.
The thresholds of auto are heuristics and have not been tuned on a real
model or a GPU. Checked with the synthetic SD 1.5 model on the CPU: the
three profiles give the same image, and with 3.3 GiB held by another
process auto picks balanced.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC