Commit graph

1019 commits

Author SHA1 Message Date
Claude
aa6ea2eaa2
fix(model-loader): stop waiting a whole progress tick after the tensors are loaded
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
2026-10-15 15:03:52 +02:00
Francesco Simeoni
c2b5c637ea
Merge pull request #10 from Filve/fix_to_claude
Fix to claude
2026-10-15 09:55:07 +02:00
Claude
bde488059f
docs: link the thermal diagnostics and the agents guide
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
2026-10-14 23:36:44 +02:00
Claude
ec15f601f7
test: run the example guardian of the agents guide
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
2026-10-14 23:36:24 +02:00
Claude
f75d4b9c3c
docs: add a guide for independent agents next to the engine
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
2026-10-14 23:36:14 +02:00
Claude
f2a6bd674b
test: cover the thermal diagnostics with a fake GPU
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
2026-10-14 23:36:05 +02:00
Claude
65ccae284f
feat(scripts): add thermal diagnostics with an Italian guide
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
2026-10-14 23:35:52 +02:00
Claude
c8bb095ba6
docs: explain how to stop a job that is generating
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
2026-10-14 22:15:52 +02:00
Claude
025124e655
test: check that cancel answers a POST without Content-Length at once
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
2026-10-14 22:15:52 +02:00
Claude
8b6acc9316
fix(server): answer a cancel request without waiting for a body
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
2026-10-14 22:15:52 +02:00
Claude
cc8f3c384d
test: add an end-to-end test for stopping a running job
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
2026-10-14 21:59:27 +02:00
Claude
12dbf8f6dd
test: cover stopping a generation that is running
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
2026-10-14 21:54:02 +02:00
Claude
1ce4084e10
fix: log a requested cancellation as information, not as an error
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
2026-10-14 16:36:00 +02:00
Claude
eeec4916a5
feat(server): stop a job that is generating
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
2026-10-14 16:35:58 +02:00
Claude
f85475b6a8
docs: add a guide to running the engine next to other applications
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
2026-10-14 11:22:02 +02:00
Claude
d2ac121945
docs: explain how an AI assistant can use the engine as a tool
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
2026-10-14 01:03:42 +02:00
Claude
7f067f8144
docs: describe --multi-gpu in the backend and performance guides
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
2026-10-14 01:03:42 +02:00
Claude
3843767142
test: cover the multi-GPU placement without GPUs
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
2026-10-14 01:03:42 +02:00
Claude
e458f87349
feat: let --profile auto count the memory of several GPUs
--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
2026-10-14 01:03:42 +02:00
Claude
a873187b6a
feat: let --auto-fit place modules on several GPUs
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
2026-10-14 01:03:42 +02:00
Francesco Simeoni
87fbe03461
Merge pull request #9 from Filve/fix_to_claude
Fix to claude
2026-10-13 14:00:56 +02:00
Francesco Simeoni
bc5fbed7bd
Update README.md 2026-10-13 11:13:44 +02:00
Francesco Simeoni
7123a368e3
Add files via upload 2026-10-13 11:13:19 +02:00
Francesco Simeoni
61673486bd
Merge pull request #8 from Filve/fix_to_claude
Fix to claude
2026-10-12 23:17:59 +02:00
Claude
37cad36dc4
ci: let the other container images finish when one fails
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
2026-10-12 20:09:39 +02:00
Claude
e7bb62b330
fix: bound the parallel build in the CPU Dockerfile
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
2026-10-12 20:09:39 +02:00
Francesco Simeoni
c6baaf0e3c
Merge pull request #7 from Filve/fix_to_claude
Fix to claude
2026-10-12 16:58:30 +02:00
Claude
7a84d9e04d
docs: use the container images of this fork
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
2026-10-12 16:21:57 +02:00
Claude
7b0657df43
ci: build and publish the CPU container image
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
2026-10-12 16:21:57 +02:00
Claude
7000584024
docs: point the download and clone instructions at the fork
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
2026-10-12 16:07:54 +02:00
Claude
cac832a1aa
ci: explain the Windows packages and runtime in the release notes
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
2026-10-12 15:54:33 +02:00
Claude
529185d840
docs: require Visual C++ Redistributable 14.44 or newer on Windows
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
2026-10-12 15:54:33 +02:00
Francesco Simeoni
84f02711c6
Merge pull request #6 from Filve/fix_to_claude
Fix to claude
2026-10-11 13:58:40 +02:00
Claude
6bb3b8de16
fix: load the CUDA driver at run time so the library starts without it
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
2026-10-11 12:51:59 +02:00
Claude
5c51e91ec1
fix: create the portable zip when the output directory is relative
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
2026-10-11 12:00:03 +02:00
Claude
9aeccdf5a8
fix: include httplib.h before windows.h in the server recovery code
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
2026-10-11 12:00:03 +02:00
Claude
6a01873d73
feat: keep sd-server serving when a request runs out of memory
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
2026-10-11 10:40:29 +02:00
Claude
ebfe8784bb
fix: give the resolved hires upscaler a default value
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
2026-10-11 09:52:16 +02:00
Claude
071a12b378
feat: add --profile to choose a resource footprint
--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
2026-10-11 07:19:14 +02:00
Claude
51845ffb58
feat: report why a call failed and expose system memory
new_sd_ctx(), generate_image() and generate_video() now record the
reason of a failure, and sd_get_last_error() returns it with a code:
out of memory, model file, backend, invalid argument, busy or
cancelled. An application can tell "try again with less memory" from
"the file is damaged" instead of reading the log. The state belongs to
the calling thread; errors logged by the model loader threads reach the
thread that reports the failure. C++ exceptions, std::bad_alloc
included, no longer cross the C API.

A test with a limited address space showed the process ending with
std::terminate when a loader thread could not be created while others
were already running. The loader now uses fewer threads, or the
calling thread when none could be started, and the loader threads
report exceptions as a failed load.

sd_get_system_memory() returns total, available and process RAM. The
free memory of the CPU device in sd_get_device_info() is the available
RAM, because ggml reports the total on Linux and macOS.

Checked with a synthetic 2.1 GB SD 1.5 model under a limited address
space: the standard configuration fails with out_of_memory, the same
context generates once the limit is lifted, and weights on disk let
the same request succeed. The Windows branch of system_memory.cpp was
only syntax-checked; macOS was not built.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-11 07:09:28 +02:00
Claude
0d84e104ee
feat: run CPU graphs in segments when weights stream from disk
Without a GPU, auto-fit now compares the available RAM with the size of
each component and leaves the ones that do not fit on disk. When it does,
it turns the memory guard on at 90% unless --memory-guard is set.

On CPU backends the memory guard now counts the weights a graph still has
to read from disk before they are loaded. When that total would pass the
threshold and some weights can be released, the graph runs in segments, as
it already does on a GPU, so the peak stays well below the size of the
model. Splitting is skipped when the guard is off or when every weight is
resident, because it could not lower the peak.

Checked with a synthetic SD 1.5 model (128x128, 3 steps, 2 threads, Linux):
with 3.3 GiB of RAM held by another process and a 60% guard, the UNet runs
in 22 segments with a 732 MiB peak instead of 1722 MiB and the image is
identical pixel for pixel. Resident weights and runs without pressure or
without the guard behave as before. Not tested on Windows or with real
models.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-11 06:39:34 +02:00
Claude
7ed90dace3
fix: keep model file handles open between tensor loads
The loader opened the model file again for every batch of tensors, in every
worker thread: once per component at startup (text encoder, UNet, VAE) and
then again each time weights are loaded back from disk (per segment, per
residency swap, per request). Each open is a chance to fail, and on Windows
it can fail exactly when the system is short of memory or handles
("failed to open '...safetensors'" at VAE decode, after RAM hit 100%).

A new FileHandlePool keeps the read streams open and hands them out to the
workers one at a time. ModelLoader owns one; copies and the per-file readers
used for LoRA tensors share it. A stream is dropped when the file's size or
modification time changes, when it is in an error state, or when its source
is removed. If a read fails the worker reopens the file once and repeats the
read, so a stream that went bad while idle (removable or network storage)
no longer fails the whole generation. The open retry with errno/doserrno
logging moves into the pool and now also covers .ckpt (zip) files.

Measured with a synthetic SD 1.5 checkpoint on CPU: the file is opened 5
times for three server requests instead of 9 per request; an injected EIO is
absorbed and the image is pixel-identical; persistent read errors end in a
clean error. test/file_handle_pool_test.cpp covers reuse, changed and
replaced files, failed streams, limits and concurrent use, and passes under
ASan/UBSan and ThreadSanitizer.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-11 06:09:49 +02:00
Claude
54038f6290
feat: log why a GPU backend module could not be used
With dynamic backends ggml loads the GPU modules silently in Release
builds, and on Windows its dl_error() returns an empty string, so a GPU
module that is on disk but fails to load (missing driver, missing
cudart/cublas DLL, wrong version) just made the GPU disappear: "only the
CPU is detected" with no hint why.

After the one-time module load, look for each known GPU module next to the
executable and in the working directory (the places ggml searches). For
every module that is present but provides no device, load it the way ggml
does and log the real reason with a hint: the dlopen error on Linux and
macOS; on Windows the error code and message plus the DLLs the module
imports that the loader cannot find, read from the import table of the
file (new bounds-checked PE reader, tested with truncated and corrupted
images). When no GPU module exists at all, say where it looked.

sd_get_device_count() and sd_list_devices() now share the one-time loader
instead of calling ggml_backend_load_all() themselves.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-11 05:52:43 +02:00
Claude
df821e6b5c
ci: build portable packages with GPU backends (Windows CUDA 12 and Vulkan, Linux Vulkan)
The portable workflow only built CPU packages, so a downloaded Windows zip
could never use the GPU ("sd-server detects only the CPU"). Mirror the
configuration already proven by build.yml and add the GPU modules:

- windows-x86_64: CPU + Vulkan (NVIDIA, AMD, Intel)
- windows-x86_64-cuda12: CPU + CUDA 12 with cudart/cublas/cublasLt bundled,
  so only the NVIDIA driver is needed on the target machine
- linux-x86_64: CPU + Vulkan, with an $ORIGIN rpath so the unpacked zip finds
  its shared libraries
- darwin-arm64 unchanged (Metal)

Windows now builds with cl.exe, /bigobj and the shared stable-diffusion
library like build.yml; the server frontend is built as in the main CI.

A manual run can select the packages and the CUDA architectures (a single
architecture shortens the CUDA build a lot). A smoke test runs
"sd-cli --list-devices" on every package, and the release is attached by one
job after all packages succeeded instead of by racing matrix jobs.

package_portable.sh takes PORTABLE_VARIANT (zip name and LEGGIMI wording) and
PORTABLE_REQUIRE_BACKENDS, and refuses to create a GPU package whose backend
module (or, on Windows, CUDA runtime DLLs) is missing.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-11 05:40:43 +02:00
Claude
9b4ff13d52
feat: apply --memory-guard to CPU backends using system RAM
The guard returned an empty sample for CPU backends, so a CPU-only run
could fill system RAM without the guard ever reacting. On the CPU, measure
system RAM instead: total minus the memory available without swapping,
plus the allocation the graph is about to make, against total physical
memory.

Under pressure the guard releases unpinned weights that can be re-read
from the model file (--params-backend disk). It never fails a graph on the
CPU, since system RAM has no managed capacity, and CPU pressure does not
suspend prefetch for GPU backends.

Expose available_ram_bytes() from backend_fit for the probe, and update
the CLI help, the public header comment and the docs.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-11 04:51:58 +02:00
Claude
c487a4b6a2
ci: grant contents write to the release job
The release job creates a release with the default GITHUB_TOKEN but declared
no permissions, so on repositories whose default token is read-only the
"Create release" step fails with "Resource not accessible by integration".

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-11 04:42:16 +02:00
Claude
86fc897098
Merge upstream leejet/stable-diffusion.cpp master into fix_to_claude
Brings in the nine upstream commits since 228c707, including the VAE
decode tile halving on OOM retry and the demotion of resident params to
disk residency when memory reclamation fails.

The only conflict was in ModelManager::ensure_compute_backend_capacity:
both sides added a block before the final capacity report. Keep both,
and apply the memory guard's "never fail a graph that still fits"
fallback before and after the demotion step.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-11 04:26:15 +02:00
Claude
3609c71514
fix: retry weight file open and log the OS error
A loader worker that failed to open the model file gave up with a bare
"failed to open" and no hint of the cause, and later requests kept
failing the same way. Retry the open up to five times with backoff
(not for a missing file) and log errno/doserrno on every failed attempt.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
2026-10-11 02:40:33 +02:00
leejet
2988060a43
feat: add TAEQI2.1 support for Qwen Image 2.1 (#2123)
Some checks failed
CI / ubuntu-latest-cmake (push) Has been cancelled
CI / ubuntu-latest-cmake-vulkan (push) Has been cancelled
CI / Build and push container images (push) Has been cancelled
CI / macOS-latest-cmake (push) Has been cancelled
CI / windows-latest-cmake (cpu, -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_LIBS=ON -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Has been cancelled
CI / windows-latest-cmake (cuda12, -DSD_CUDA=ON -DSD_BUILD_SHARED_LIBS=ON -DCMAKE_CUDA_ARCHITECTURES='61;70;75;80;86;89;90;100;120' -DCMAKE_CUDA_FLAGS='-Xcudafe "--diag_suppress=177" -Xcudafe "--diag_suppress=550"' -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_L… (push) Has been cancelled
CI / windows-latest-cmake (vulkan, -DSD_VULKAN=ON -DSD_BUILD_SHARED_LIBS=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Has been cancelled
CI / windows-latest-rocm (push) Has been cancelled
CI / ubuntu-latest-rocm (10.1.0, x64, gfx900;gfx906;gfx908;gfx90a;gfx90c;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201) (push) Has been cancelled
CI / release (push) Has been cancelled
2026-10-11 00:01:18 +08:00
Daniele
1b0ba10893
feat: run conditional and unconditional CFG in one batched UNet forward (#2085) 2026-10-10 23:35:58 +08:00