Skip to content

Commit ea53d85

Browse files
authored
Add an ordered progress recorder that needs no callback (#14)
* Add a clearable progress callback and a silent progress sink Upstream keeps the progress callback in an unsynchronized global that the loading or generating thread reads on every step, so a caller cannot tell when a replaced callback has stopped running. A Dart NativeCallable invoked after its VM shut down aborts with "GetFfiCallbackMetadata called after shutdown". src/sd_dart_wrapper.h adds two exports, compiled into the same library by a top-level CMakeLists.txt that wraps the upstream project: - sd_dart_set_progress_callback(callback, data) registers one forwarder with upstream and routes progress to `callback`; NULL discards progress without printing progress bars. - sd_dart_clear_progress_callback(void*) stops routing to that callback and takes one pointer, so it can be a Dart NativeFinalizer callback. The callback is swapped behind a lock held while it runs: when either function returns, the replaced callback is not running on another thread and is never called again. The export allowlist, shipped headers, XCFramework module map and SwiftPM consumer probe cover the new header. Refs #10 * Keep the upstream build directory short for Windows Building upstream under build/<target>/third_party/stable-diffusion.cpp put the nested Vulkan shader generator's compiler checks past the 260-character Windows path limit, so windows-x64-vulkan failed to configure it. Refs #10 * Move the Vulkan shader generator build to a short path The previous commit was not enough for windows-x64-vulkan: MSBuild's file tracker failed on a 260-character tlog path in the generator's nested configure (FTK1011). The same path is 257 characters when upstream is the top-level project, so any extra directory level breaks it. An inherited EP_PREFIX puts ggml's ExternalProject under build/<target>/ep, which shortens that path to 213 characters. Refs #10 * Record progress natively instead of calling back An independent audit of the callback design found that it cannot be made safe for a Dart callback: - sd_dart_clear_progress_callback held a mutex across the callback and took the same mutex. As a NativeFinalizer it runs at isolate shutdown while the thread is not at a safepoint; a NativeCallable.listener called on the reporting thread blocks on a pending safepoint operation. The finalizer waits for the mutex, its holder waits for the garbage collection, and the collection waits for the finalizer: the process never exits. - When the callback belongs to a background isolate and the main isolate dies, the VM stops accepting callbacks before that isolate's finalizer runs, so the original abort comes back. Both reproduced. The library now takes no callback at all: - sd_dart_progress_enable() registers a recorder with upstream, once. It only stores the report in atomics, and silences the stdout progress bars, loads included. - sd_dart_progress_read() copies the latest whole report, with a sequence number, into a caller-provided struct. It takes no lock and never waits for the reporting thread, so it is a Dart leaf call. sd_dart_set_progress_callback and sd_dart_clear_progress_callback are gone. Nothing has to be undone when the caller goes away, and the recorder has no destructor, so it stays valid while exit() runs. tests/test_progress_stress.py drives a Dart VM that dies while a worker isolate reports progress from a native call, with allocating isolates, for three owner layouts. The two replaced designs are kept there as controls. CI runs it on Linux and macOS. Refs #10 * Check DLL exports and smoke-test macOS in CI validate_artifacts.py returned before the export check on Windows, so nothing compared a DLL's export table with the allowlist. It now reads the export name table itself, which needs no Windows SDK tool. macos-arm64 gets the smoke step the Linux and Windows targets have, so the progress recorder is checked against the built macOS library too. Refs #10 * Keep a history of progress reports A second audit found that recording only the latest report loses progress for every batch of more than one image. stable-diffusion.cpp samples all images before it decodes any, so one image's steps/steps report is followed within a millisecond by the next image's 0/steps. A caller that polls sees only the latter, and llamadart's tracker, which counts images by the former, never advances the image index or emits its decoding event. Reproduced with SD-Turbo (4 steps x 3 images, Metal) and SDXS (1 step x 2, CPU) at a 50 ms poll. The recorder is now a ring of 4096 reports, and sd_dart_progress_read() returns them in order: size_t sd_dart_progress_read(uint64_t after, sd_dart_progress_t* reports, size_t capacity, uint64_t* latest); - It copies the reports with a sequence greater than `after`, oldest first, and reports the newest sequence through `latest`. - The 4095 most recent reports are kept. The fastest source measured, convert, makes 47 reports in 50 ms. A caller that falls further behind gets the newest ones and sees the jump in sequence. - A report is accepted only if the published sequence shows that its slot cannot have been rewritten during the copy. Readers still take no lock and never wait for a reporter; a read copies at most capacity + 4 reports. sd_dart_progress_enable() now returns only once the recorder is registered, also when another thread is the one registering it. The Dart VM harness checks every report it reads against its sequence, has a configuration in which no report may be missing, and gains progress_images.dart: a stand-in emits upstream's report pattern for a batch and a polling consumer must see all of it, while a control that looks only at the newest report must not. Refs #10 * Pin the Dart SDK of the dart vm jobs The harness's control expects the aborts of this VM when native code calls a Dart callback during shutdown. An unpinned SDK could turn the job red for a VM change that is not a defect here. Refs #10
1 parent 68b29da commit ea53d85

23 files changed

Lines changed: 1687 additions & 49 deletions

‎.github/workflows/native_release.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ jobs:
2222
fail-fast: true
2323
matrix:
2424
include:
25-
- { target: macos-arm64, runs_on: macos-latest }
25+
- { target: macos-arm64, runs_on: macos-latest, smoke: "--expect-device CPU" }
2626
- { target: macos-x64, runs_on: macos-latest }
2727
- { target: ios-arm64, runs_on: macos-latest }
2828
- { target: ios-arm64-sim, runs_on: macos-latest }

‎.github/workflows/validate.yml‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,40 @@ jobs:
1919
os: [ubuntu-latest, macos-latest]
2020
steps:
2121
- uses: actions/checkout@v4
22+
with:
23+
# The wrapper tests compile against upstream's header.
24+
submodules: true
2225
- run: python3 -m unittest discover -s tests -v
2326

27+
dart-vm:
28+
name: dart vm (${{ matrix.os }})
29+
runs-on: ${{ matrix.os }}
30+
strategy:
31+
fail-fast: false
32+
matrix:
33+
os: [ubuntu-latest, macos-latest]
34+
steps:
35+
- uses: actions/checkout@v4
36+
with:
37+
submodules: true
38+
- uses: dart-lang/setup-dart@v1
39+
with:
40+
# Pinned: the harness expects this VM's aborts in its controls.
41+
sdk: 3.13.5
42+
- name: Report progress while the Dart VM shuts down
43+
run: python3 -m unittest discover -s tests -p test_progress_stress.py -v
44+
env:
45+
SD_REQUIRE_DART: "1"
46+
SD_PROGRESS_STRESS_RUNS: "25"
47+
2448
build:
2549
name: build (${{ matrix.target }})
2650
runs-on: ${{ matrix.runs_on }}
2751
strategy:
2852
fail-fast: false
2953
matrix:
3054
include:
31-
- { target: macos-arm64, runs_on: macos-latest }
55+
- { target: macos-arm64, runs_on: macos-latest, smoke: "--expect-device CPU" }
3256
- { target: macos-x64, runs_on: macos-latest }
3357
- { target: ios-arm64, runs_on: macos-latest }
3458
- { target: ios-arm64-sim, runs_on: macos-latest }

‎AGENTS.md‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,17 @@ Guidance for coding agents working in `stable-diffusion-native`.
99
- Upstream is the `third_party/stable-diffusion.cpp` submodule. Update the
1010
submodule pin instead of patching vendored sources; report upstream bugs
1111
there.
12+
- What upstream's C API lacks goes in `src/`, which the top-level
13+
`CMakeLists.txt` compiles into the same library. A wrapper export is an
14+
`sd_dart_*` function declared with `SD_API` in `src/sd_dart_wrapper.h`, with
15+
a test under `tests/` and a README entry.
16+
- A wrapper export never takes a callback that stable-diffusion.cpp's threads
17+
would call, and never waits for such a thread: a Dart callback there aborts
18+
or deadlocks VM shutdown. Record state natively and let the caller poll.
19+
Wrapper state has no destructor; threads still use it while `exit()` runs.
20+
- Whatever a caller polls must keep its history. Consumers derive state from
21+
the order of progress reports, such as which image of a batch is being
22+
sampled, so a "latest value" export loses what happened between two polls.
1223

1324
## Commands
1425

@@ -19,10 +30,14 @@ python3 tools/build.py build --target <target>
1930
python3 tools/validate_artifacts.py <target>
2031
```
2132

33+
- `tests/test_progress_stress.py` needs a Dart SDK on `PATH` and skips without
34+
one; CI runs it with 25 runs per configuration. Run it after any change to
35+
`src/`.
2236
- Every shipped library must pass `validate_artifacts.py`: it exports exactly
23-
the `SD_API` symbols in `stable-diffusion.h` and links only allowlisted
24-
system libraries. Never widen the export list to fix a consumer; a leaked
25-
ggml symbol can collide with llama.cpp's ggml in the same process.
37+
the `SD_API` symbols in `stable-diffusion.h` and `src/sd_dart_wrapper.h`, and
38+
links only allowlisted system libraries. Never export an upstream-internal
39+
or ggml symbol to fix a consumer; a leaked ggml symbol can collide with
40+
llama.cpp's ggml in the same process.
2641
- The Apple XCFramework must pass `apple_xcframework.py validate` and
2742
`consumer`. Its Info.plist minimum OS is read from each binary's
2843
`LC_BUILD_VERSION`; never hard-code it, since a mismatch fails App Store
@@ -44,5 +59,5 @@ python3 tools/validate_artifacts.py <target>
4459

4560
After a release, update the `llamadart` runtime pin and archive checksums, the
4661
Apple companion `Package.swift` tag and XCFramework checksum, and regenerate
47-
its bindings from the released `stable-diffusion.h`, in the same `llamadart`
48-
PR.
62+
its bindings from the released `stable-diffusion.h` and `sd_dart_wrapper.h`,
63+
in the same `llamadart` PR.

‎CMakeLists.txt‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
cmake_minimum_required(VERSION 3.13)
2+
project(stable_diffusion_native LANGUAGES C CXX)
3+
4+
set(SD_NATIVE_UPSTREAM_DIR "${CMAKE_CURRENT_SOURCE_DIR}/third_party/stable-diffusion.cpp")
5+
if(NOT EXISTS "${SD_NATIVE_UPSTREAM_DIR}/CMakeLists.txt")
6+
message(FATAL_ERROR
7+
"Missing submodule: third_party/stable-diffusion.cpp. "
8+
"Run: git submodule update --init --recursive")
9+
endif()
10+
11+
# Windows builds run close to the 260-character path limit. Keep the upstream
12+
# build directory short, and move ggml's nested Vulkan shader generator build
13+
# from ggml/src/ggml-vulkan/vulkan-shaders-gen-prefix to ep.
14+
define_property(DIRECTORY PROPERTY EP_PREFIX INHERITED
15+
BRIEF_DOCS "ExternalProject prefix"
16+
FULL_DOCS "ExternalProject prefix, inherited by the upstream directories")
17+
set_property(DIRECTORY PROPERTY EP_PREFIX "${CMAKE_BINARY_DIR}/ep")
18+
add_subdirectory("${SD_NATIVE_UPSTREAM_DIR}" sd)
19+
20+
# Wrapper exports are compiled into the upstream library target, so they share
21+
# its SD_API export macro and reach upstream without patching it.
22+
target_sources(stable-diffusion PRIVATE
23+
"${CMAKE_CURRENT_SOURCE_DIR}/src/sd_dart_wrapper.cpp"
24+
"${CMAKE_CURRENT_SOURCE_DIR}/src/sd_dart_wrapper.h")

‎README.md‎

Lines changed: 99 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ elsewhere.
1414
- Pin an upstream stable-diffusion.cpp commit as a submodule.
1515
- Build one shared library per platform with upstream's C API
1616
(`stable-diffusion.h`) as the FFI boundary.
17-
- Export only that API. stable-diffusion.cpp embeds its own patched ggml;
18-
hiding it lets the library share a process with another ggml, such as
19-
llama.cpp's.
17+
- Export only that API and the [wrapper API](#wrapper-api) this repository
18+
adds. stable-diffusion.cpp embeds its own patched ggml; hiding it lets the
19+
library share a process with another ggml, such as llama.cpp's.
2020
- Publish runtime archives, unstripped symbol archives, an Apple SwiftPM
2121
XCFramework, `manifest.json` and `SHA256SUMS`.
2222

@@ -52,6 +52,100 @@ Android GPU backends are not shipped. On tested devices, Vulkan crashed in
5252
the Adreno 750 driver's shader compiler and on a null `vkGetBufferDeviceAddress`
5353
on Mali-G68, and OpenCL on Adreno 750 was slower than the CPU.
5454

55+
## Wrapper API
56+
57+
`src/sd_dart_wrapper.h` declares the exports this repository adds to
58+
upstream's. It is compiled into the same library and ships next to
59+
`stable-diffusion.h` in every archive and XCFramework slice.
60+
61+
```c
62+
typedef struct {
63+
uint64_t sequence; // reports are numbered from 1 in the order recorded
64+
int32_t step; // the arguments of upstream's progress callback
65+
int32_t steps;
66+
float time;
67+
} sd_dart_progress_t;
68+
69+
void sd_dart_progress_enable(void);
70+
size_t sd_dart_progress_read(uint64_t after, sd_dart_progress_t* reports,
71+
size_t capacity, uint64_t* latest);
72+
```
73+
74+
| Function | Behavior |
75+
| --- | --- |
76+
| `sd_dart_progress_enable` | Records progress in the library instead of printing progress bars to stdout, for every later call in the process, model loads included. Idempotent; when it returns the recorder is registered. |
77+
| `sd_dart_progress_read` | Copies the reports with a sequence greater than `after` into `reports`, oldest first, at most `capacity`, and returns how many. `latest`, if not `NULL`, receives the sequence of the newest report (0 if none); a `capacity` of 0 only asks for that. |
78+
79+
Upstream's `sd_set_progress_callback` calls back on the thread that is loading
80+
or generating, for as long as that call runs. A callback into a managed
81+
runtime cannot be made safe there. A Dart `NativeCallable` is called after
82+
its isolate or the VM has shut down, which aborts the process, and a wrapper
83+
that waits for a call in flight before dropping the callback can deadlock VM
84+
shutdown. So the library takes no callback: it records the reports itself,
85+
and the caller reads them in order whenever it likes.
86+
87+
What is guaranteed:
88+
89+
- **Every report, in order.** The sequences of one call's reports are
90+
consecutive, and each report is whole: the three values of one upstream
91+
call, never a mix of two.
92+
- **History.** The library keeps the 4095 most recent reports. A caller that
93+
reads before more than that were recorded since its last read misses none.
94+
The fastest sources measured on an M4 Max are `convert` (746 reports a
95+
second, 47 in 50 ms) and a tiled VAE decode with 64-pixel tiles (195 a
96+
second, 10 in 50 ms); sampling a batch of one-step images reports 16 times
97+
a second. So a 50 ms poll uses about 1% of the history, and a caller may
98+
stall for more than five seconds before a report is lost.
99+
- **Overflow is visible.** If more than 4095 reports were recorded since
100+
`after`, the older ones are gone and the first report returned is not
101+
`after + 1`.
102+
- **Never blocks.** `sd_dart_progress_read` takes no lock, makes no system
103+
call, never waits for a reporting thread and copies at most `capacity` + 4
104+
reports; a reporting thread never waits for a reader. It is safe as a Dart
105+
leaf call. A call may return fewer reports than there are; the caller has
106+
them all once the last sequence it holds equals `latest`.
107+
- **Nothing to undo.** No call is needed when the caller goes away, and the
108+
state is never destroyed, so reporting and reading stay valid while
109+
`exit()` runs.
110+
111+
What is not:
112+
113+
- **Which call a report belongs to.** Reports are process-wide, as upstream's
114+
callback is. Every context's loads and generations go into the one
115+
sequence, so two contexts working at once see each other's reports, load
116+
reports included, and each takes up part of the other's history.
117+
- **A registration that survives `sd_set_progress_callback`.** The first
118+
`sd_dart_progress_enable` call registers the recorder there. That function
119+
is not synchronized, so make the call before another thread starts a load
120+
or generation. A later `sd_set_progress_callback` call replaces the
121+
recorder, `latest` stops advancing, and `sd_dart_progress_enable` does not
122+
register it again. A caller that wants a C callback uses upstream's
123+
function instead of this API.
124+
- **A shorter exit.** A process whose caller died still waits for a native
125+
call that is in flight: the Dart VM, for one, exits only after the isolate
126+
inside `new_sd_ctx` or `generate_image` returns.
127+
128+
To follow one call, ask for `latest` before starting it, read from there on a
129+
timer, and read once more when the call has returned:
130+
131+
```c
132+
uint64_t after;
133+
sd_dart_progress_read(0, NULL, 0, &after);
134+
/* start the call on another thread; then, on each tick and once at the end: */
135+
uint64_t latest;
136+
do {
137+
size_t count = sd_dart_progress_read(after, reports, capacity, &latest);
138+
for (size_t i = 0; i < count; i++) {
139+
/* reports[i].sequence == after + 1 unless reports were lost */
140+
after = reports[i].sequence;
141+
}
142+
} while (after < latest);
143+
```
144+
145+
`tests/test_progress_stress.py` runs this against a real Dart VM: one that
146+
dies while a native call is reporting progress, and one that polls a batch of
147+
images; see its docstring.
148+
55149
## Build
56150

57151
```bash
@@ -72,7 +166,8 @@ Outputs:
72166

73167
- `bin/<target>/lib/`: stripped runtime library.
74168
- `bin/<target>/symbols/`: unstripped library for crash symbolication.
75-
- `bin/<target>/include/stable-diffusion.h` and `build-info.json`.
169+
- `bin/<target>/include/`: `stable-diffusion.h` and `sd_dart_wrapper.h`.
170+
- `bin/<target>/build-info.json`.
76171
- `dist/`: release archives, `manifest.json`, `SHA256SUMS`.
77172

78173
## Apple XCFramework

‎src/sd_dart_wrapper.cpp‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
#include "sd_dart_wrapper.h"
2+
3+
#include <atomic>
4+
#include <thread>
5+
#include <type_traits>
6+
7+
namespace {
8+
9+
// A power of two. Report n lives in reports[n % kSlots] until report
10+
// n + kSlots replaces it.
11+
constexpr uint64_t kSlots = 4096;
12+
// Report n is safe to copy while the newest report is at most n + kKept - 1:
13+
// the reporter starts on report n + kSlots only after publishing the one
14+
// before it.
15+
constexpr uint64_t kKept = kSlots - 1;
16+
// How often one read starts over because the reporter overtook it.
17+
constexpr int kRestarts = 4;
18+
19+
enum Registration : int { kUnregistered, kRegistering, kRegistered };
20+
21+
struct Report {
22+
std::atomic<int32_t> step{0};
23+
std::atomic<int32_t> steps{0};
24+
std::atomic<float> time{0.0f};
25+
};
26+
27+
struct Recorder {
28+
// The newest report whose slot is completely written.
29+
std::atomic<uint64_t> sequence{0};
30+
Report reports[kSlots];
31+
std::atomic_flag writing = ATOMIC_FLAG_INIT;
32+
std::atomic<int> registration{kUnregistered};
33+
};
34+
35+
// Never destroyed: a thread can still report progress after exit() has run
36+
// static destructors.
37+
static_assert(std::is_trivially_destructible<Recorder>::value, "Recorder must outlive exit()");
38+
static_assert(std::atomic<uint64_t>::is_always_lock_free, "reading must not take a lock");
39+
Recorder recorder;
40+
41+
void record_progress(int step, int steps, float time, void*) {
42+
// Reporting threads exclude each other; readers never take this flag.
43+
while (recorder.writing.test_and_set()) {
44+
std::this_thread::yield();
45+
}
46+
const uint64_t next = recorder.sequence.load() + 1;
47+
Report& report = recorder.reports[next % kSlots];
48+
report.step.store(step);
49+
report.steps.store(steps);
50+
report.time.store(time);
51+
recorder.sequence.store(next);
52+
recorder.writing.clear();
53+
}
54+
55+
} // namespace
56+
57+
void sd_dart_progress_enable(void) {
58+
// Upstream keeps its callback in an unsynchronized global, so it is
59+
// written once rather than on every call.
60+
int expected = kUnregistered;
61+
if (recorder.registration.compare_exchange_strong(expected, kRegistering)) {
62+
sd_set_progress_callback(record_progress, nullptr);
63+
recorder.registration.store(kRegistered);
64+
return;
65+
}
66+
while (recorder.registration.load() != kRegistered) {
67+
std::this_thread::yield();
68+
}
69+
}
70+
71+
size_t sd_dart_progress_read(uint64_t after,
72+
sd_dart_progress_t* reports,
73+
size_t capacity,
74+
uint64_t* latest) {
75+
uint64_t newest = recorder.sequence.load();
76+
uint64_t next = after + 1;
77+
size_t count = 0;
78+
int restarts = 0;
79+
while (after < newest && count < capacity && next <= newest && restarts < kRestarts) {
80+
if (count == 0) {
81+
const uint64_t oldest = newest < kKept ? 1 : newest - kKept + 1;
82+
if (next < oldest) {
83+
next = oldest;
84+
}
85+
}
86+
sd_dart_progress_t& copy = reports[count];
87+
const Report& report = recorder.reports[next % kSlots];
88+
copy.sequence = next;
89+
copy.step = report.step.load();
90+
copy.steps = report.steps.load();
91+
copy.time = report.time.load();
92+
newest = recorder.sequence.load();
93+
if (newest - next >= kKept) {
94+
// The slot may have been rewritten during the copy. Reports
95+
// already copied stay; a read that has none starts over.
96+
if (count > 0) {
97+
break;
98+
}
99+
restarts++;
100+
continue;
101+
}
102+
count++;
103+
next++;
104+
}
105+
if (latest != nullptr) {
106+
*latest = newest;
107+
}
108+
return count;
109+
}

0 commit comments

Comments
 (0)