Skip to content

Commit 0d02086

Browse files
camchiswcandillon
andauthored
feat(⚡️): keep Dawn's compiled pipelines across launches (#594)
* feat(⚡️): keep Dawn's compiled pipelines across launches * fix(⚡️): leave a cache write another process may still finish, and recreate a cleared cache directory * chore(🐙): unit test the Dawn blob cache on the host * chore(🐙): use POSIX calls in the blob cache test, as cpplint asks * chore(📚): say what the pipeline cache keeps on each backend, and when its size is checked * fix(⚡️): recreate the cache directory's parents, and keep the cache off when the JVM can't copy its path * chore(🐙): test the cache's parent directories, and require the CMake its options need * fix(⚡️): clear only the cache's own files, stay off without a usable directory, and let a failed JNI copy throw * chore(🐙): test that the cache leaves other files alone and stays off without a directory * fix(⚡️): trim the oldest cache entries to fit the limit, and check it as a session stores * chore(🐙): test that the cache is trimmed rather than cleared, at setup and while storing * fix(⚡️): keep one entry from taking the cache, and count replacements as no growth An entry larger than half the limit is not stored, so one blob cannot take more than half the cache from the others. A replacement counts only the bytes it adds towards the next tidy, and the counter is reset with a compare-exchange so growth that lands during a reset is kept. Tidy checks the inode as well as the time and size before removing a file, so it does not remove one a store has just replaced. The statics a flush on another thread may still use at exit are never destroyed, and chain() says whether it chained the cache. * fix(⚡️): persist Dawn's monolithic Vulkan pipeline cache With vulkan_monolithic_pipeline_cache Dawn writes its one VkPipelineCache to the blob cache only inside PerformIdleTasks(), which nothing called, so on Android the Vulkan pipeline data never reached the disk. An IdleFlusher now calls it about a second after the last pipeline was created (about ten seconds into a long run of creations) and once on device.destroy(), for devices that have the blob cache, run on Vulkan, and have the toggle applied. A device without implicit synchronization is flushed only on destroy(). Cancelled on device loss, and never waited for when the device is released, since that can happen inside a Dawn callback. Messages Dawn logs during a flush stay native. * chore(📚): say when the pipeline cache is written and how its size is kept * refactor(⚡️): write blob cache entries on a thread of their own, and clear a cache past its limit Dawn stores from the thread that compiles, a JS thread included, and holds the device's lock while it stores its pipeline cache. A store now copies the bytes and returns; one writer thread does the disk work, in order. Tidying runs on that thread too, and is simpler: a cache found past 64 MB at setup is cleared, since which of its entries the app still uses cannot be told, and a session that would take the cache past the limit stops adding to it (a replacement no larger than the entry it replaces is never dropped). Only names shaped exactly like the cache's own are counted or removed. * refactor(⚡️): flush the Vulkan pipeline cache on destroy and when the app pauses Dawn writes its monolithic Vulkan pipeline cache only when the embedder says the device is idle. Rather than guess at idleness with a thread of our own (IdleFlusher), use the moments the platform gives: device.destroy(), and the app going to the background, which Android reports through onHostPause. Each device flushes on the thread of the runtime it was created on, so Dawn's callbacks keep running where they always did. There is nothing to flush on Metal, where Dawn stores its blobs as it compiles. * fix(⚡️): flush the Vulkan pipeline cache every ten seconds, from any runtime, and never for an imported device An app killed in the foreground lost every pipeline built since launch: nothing flushed between onHostPause and destroy. GPUQueue::submit now asks its device to flush when ten seconds have passed since the last one. That is cheap: Dawn only serializes when a pipeline compiled since, and skips the store when the cache's size did not change. The pause flush posted to each device's runtime, but a worklet runtime of the Mailbox kind delivers a post only with its next operation, so a device created there never flushed. Devices with ImplicitDeviceSynchronization, the default, now flush on the calling thread; PerformIdleTasks takes the device's lock itself. Only devices without it are posted to their runtime. A device from importDevice() belongs to someone else: it keeps its origin and is never flushed, on destroy included. * fix(⚡️): keep the writer thread alive through a failing store, and measure the cache again before dropping one A job that threw took the writer thread down with it, and when no thread could be started the jobs ran inline on Dawn's thread, under the device's lock. Jobs now run under try/catch, and are dropped without a thread. The byte count the writer keeps went stale when the OS purged the files but kept the directory, so stores were dropped from an empty cache. A store that would be dropped measures the directory first. Replacements no larger than the entry they replace stay exempt, as the header promises. Temporary names match exactly the one shape the cache writes; the test pins the older `<hash>.<pid>.<seq>.tmp` shape as a file the cache leaves alone. The test helpers that create and age files return whether they did, and every call asserts it. * chore(🐙): run the C++ unit tests in a job of their own, with the googletest download cached The tests ran inside the Android build job, where a failure read as an Android failure and a cold googletest fetch added to the slowest job. They now run on ubuntu in under a minute, and actions/cache keeps the FetchContent checkout under node_modules/.cache/cpp-tests/_deps, keyed on the CMake file. * fix(⚡️): serialize the pipeline cache off the frame thread, hold no device wrapper on the UI thread, and measure the cache again only when it changed The periodic flush of a device that synchronizes itself goes to the blob cache's thread (DawnBlobCache::post), holding the device by its Dawn handle and a shared flag rather than its wrapper, which must only go on its runtime's thread. flushPipelineCaches() copies what it needs out of each wrapper under the registry's mutex (the registry now holds plain pointers and asks weak_from_this()), so the pause-time flush never takes a strong reference on the UI thread. A store the cache refuses as too large is counted on the calling thread, and a flush that sees the count move marks the device's pipeline cache as outgrown and stops having Dawn serialize it. In the cache, the directory is published before its tidying is posted, and a store finding its directory untidied (the tidying dropped for want of a thread, or the store bound for another directory) tidies it first. Before a store is dropped the directory is measured again only when its modification time changed since the last measure, or that measure is ten seconds old. Also: GPUQueue's members in initializer order, the docs on when the Vulkan cache data is written (a submit ten seconds after the last write), and the googletest cache in CI limited to the download and its sub-build. --------- Co-authored-by: William Candillon <wcandillon@gmail.com>
1 parent 939a94c commit 0d02086

18 files changed

Lines changed: 1497 additions & 23 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,38 @@ jobs:
310310
exit 1
311311
}
312312
313+
# The C++ unit tests, built for the host (yarn test:cpp). A job of their
314+
# own, so that a failing test is reported in a minute or two rather than
315+
# after the Android job's setup, and so that a googletest download that
316+
# fails does not fail the Android e2e run.
317+
cpp-tests:
318+
runs-on: ubuntu-latest
319+
timeout-minutes: 10
320+
steps:
321+
- name: Checkout
322+
uses: actions/checkout@v4
323+
324+
- name: Setup
325+
uses: ./.github/actions/setup
326+
with:
327+
github_token: ${{ secrets.GITHUB_TOKEN }}
328+
329+
# FetchContent downloads googletest into the build directory; with the
330+
# download, its stamps and the extracted source in place, a configure
331+
# skips the download. Those only: the objects built from them belong to
332+
# the runner image's compiler, which the key does not name.
333+
- name: Cache googletest
334+
uses: actions/cache@v4
335+
with:
336+
path: |
337+
packages/webgpu/node_modules/.cache/cpp-tests/_deps/googletest-src
338+
packages/webgpu/node_modules/.cache/cpp-tests/_deps/googletest-subbuild
339+
key: ${{ runner.os }}-cpp-tests-googletest-${{ hashFiles('packages/webgpu/tests/cpp/CMakeLists.txt') }}
340+
341+
- name: Run the C++ unit tests
342+
working-directory: packages/webgpu
343+
run: yarn test:cpp
344+
313345
# Android e2e on a GitHub-hosted emulator. The runner has no GPU, so the guest
314346
# sees a SwiftShader (software) Vulkan 1.3 device through gfxstream, which Dawn
315347
# exposes as a fallback adapter. Specs that need hardware-only paths (hardware

‎apps/docs/content/docs/getting-started/native-api.mdx‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,22 @@ A device created by another library and wrapped with [`importDevice()`](#importi
102102

103103
See [Vision Camera](/docs/integrations/vision-camera) for an end-to-end example applying WGSL effects to live camera frames, and [Native Extensions](/api/gpu-device-extensions) for the full API.
104104

105+
## Pipeline cache
106+
107+
Every device `requestDevice()` creates keeps what Dawn produces while it builds shaders and pipelines in a cache on disk, in the app's cache directory, so a relaunch can reuse it instead of redoing the work. On Vulkan (Android) that includes the driver's pipeline cache data, which saves the most, since building pipelines is where Vulkan drivers spend their time. That data is written when `device.destroy()` is called, when the app goes to the background and, while the app submits work to the queue, about every ten seconds: a `queue.submit()` ten seconds or more after the last write triggers the next. An app killed while in the foreground therefore loses at most the last ten seconds of pipeline building, or everything built since its last submit. On Metal (iOS) the cache holds the shaders Dawn translates to MSL; Metal still builds the pipelines, with the help of its own system cache.
108+
109+
The cache is kept to about 64 MB. An app that finds its cache past that size when it starts clears it, and builds everything once more; a session that would take the cache past that size stops adding to it until then. An entry larger than half of that is not stored, so the Vulkan pipeline cache data stops being updated if it ever grows past 32 MB. The system may also clear the cache, as it does any app cache.
110+
111+
To opt a device out, disable it with a Dawn toggle:
112+
113+
```tsx
114+
const device = await adapter.requestDevice({
115+
dawnToggles: { enabledToggles: ["disable_blob_cache"] },
116+
});
117+
```
118+
119+
A device wrapped with [`importDevice()`](#importing-an-external-device) is created by its own library and does not use this cache.
120+
105121
## Importing an external device
106122

107123
`importDevice()` wraps a GPU device created by another native library into a regular `GPUDevice`. The device handle is passed as a `BigInt`, and the original owner keeps its own reference.

‎packages/webgpu/CONTRIBUTING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Example app (from `apps/example/`): `yarn start` · `yarn ios` · `yarn android`
1616

1717
From the repo root: `yarn lint` · `yarn tsc` · `yarn build:docs`
1818

19-
Tests (from `packages/webgpu/`): `yarn test:ref` (Chrome reference) · `yarn test` (E2E) · `yarn test:plugin` (Expo config plugin unit tests)
19+
Tests (from `packages/webgpu/`): `yarn test:ref` (Chrome reference) · `yarn test` (E2E) · `yarn test:plugin` (Expo config plugin unit tests) · `yarn test:cpp` (C++ unit tests of `cpp/rnwgpu/DawnBlobCache.cpp`, built for the host with CMake and a C++20 compiler against Dawn's headers; one test after a build: `ctest --test-dir node_modules/.cache/cpp-tests -R <name>`)
2020

2121
`yarn test` needs the example app open on its "Tests" screen and connected to Metro first: start Metro with `CI=true yarn start` (from `apps/example/`) — `initialRouteName` in `apps/example/src/App.tsx` is `"Tests"` when `process.env.CI === "true"`, inlined at bundle time via the `transform-inline-environment-variables` babel plugin — then launch the app (`yarn ios` / `yarn android`, or install+launch an existing build). The screen shows "Connecting to localhost..." once it's ready; `yarn test` then picks it up automatically. If a run fails mid-suite, reload the app (`curl -X POST http://localhost:8081/reload`) before the next run — a broken `GPUDevice` from the failed run makes unrelated later tests fail too. The app and the test server talk over port 4242 by default; set `E2E_PORT` for both Metro (it is inlined into the bundle, so start Metro with `--reset-cache` after changing it) and `yarn test` to use another one, as CI does to keep clear of the other projects sharing its runner.
2222

‎packages/webgpu/android/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ add_library(${PACKAGE_NAME} SHARED
5555
../cpp/rnwgpu/api/GPUComputePassEncoder.cpp
5656
../cpp/rnwgpu/api/GPUComputePipeline.cpp
5757
../cpp/rnwgpu/api/GPUCanvasContext.cpp
58+
../cpp/rnwgpu/DawnBlobCache.cpp
5859
../cpp/rnwgpu/RNWebGPUManager.cpp
5960
../cpp/rnwgpu/WebGPURuntime.cpp
6061
../cpp/jsi/Promise.cpp

‎packages/webgpu/android/cpp/cpp-adapter.cpp‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121
#include <webgpu/webgpu_cpp.h>
2222

2323
#include "AndroidPlatformContext.h"
24+
#include "DawnBlobCache.h"
2425
#include "GPUCanvasContext.h"
26+
#include "GPUDevice.h"
2527
#include "RNWebGPUManager.h"
2628
#include "WebGPURuntime.h"
2729

@@ -31,8 +33,18 @@ std::shared_ptr<rnwgpu::RNWebGPUManager> manager;
3133

3234
extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUModule_initializeNative(
3335
JNIEnv *env, jobject thiz, jlong jsRuntime, jobject jsCallInvokerHolder,
34-
jobject blobModule) {
36+
jobject blobModule, jstring cacheDirectory) {
3537
auto runtime = reinterpret_cast<facebook::jsi::Runtime *>(jsRuntime);
38+
if (cacheDirectory != nullptr) {
39+
const char *path = env->GetStringUTFChars(cacheDirectory, nullptr);
40+
if (path == nullptr) {
41+
// The JVM could not copy the string, and an OutOfMemoryError is pending:
42+
// no further JNI call is allowed, so let it reach the caller.
43+
return;
44+
}
45+
rnwgpu::DawnBlobCache::setDirectory(path);
46+
env->ReleaseStringUTFChars(cacheDirectory, path);
47+
}
3648
jobject globalBlobModule = env->NewGlobalRef(blobModule);
3749
jobject globalModule = env->NewGlobalRef(thiz);
3850
auto jsCallInvoker{
@@ -45,6 +57,16 @@ extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUModule_initializeNative(
4557
platformContext);
4658
}
4759

60+
// WebGPUModule.onHostPause (UI thread): the app is going to the background,
61+
// the last moment to write what Dawn's pipeline caches hold before the process
62+
// may be killed. Each device flushes here, or on the thread of its own runtime
63+
// when it does not synchronize itself.
64+
extern "C" JNIEXPORT void JNICALL
65+
Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */,
66+
jobject /* this */) {
67+
rnwgpu::GPUDevice::flushPipelineCaches();
68+
}
69+
4870
// Completion of WebGPUModule.snapshotView (UI thread). Reclaims the callbacks
4971
// handed to Java and delivers either the bitmap's pixels or the error.
5072
extern "C" JNIEXPORT void JNICALL Java_com_webgpu_WebGPUModule_onViewSnapshot(

‎packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@
88

99
import androidx.annotation.OptIn;
1010

11+
import java.io.File;
1112
import java.util.HashSet;
1213
import java.util.Set;
1314

1415
import com.facebook.proguard.annotations.DoNotStrip;
1516
import com.facebook.react.bridge.ReactApplicationContext;
1617
import com.facebook.react.bridge.JavaScriptContextHolder;
18+
import com.facebook.react.bridge.LifecycleEventListener;
1719
import com.facebook.react.bridge.ReactMethod;
1820
import com.facebook.react.bridge.UIManager;
1921
import com.facebook.react.bridge.UiThreadUtil;
@@ -26,7 +28,7 @@
2628
import com.facebook.react.turbomodule.core.interfaces.CallInvokerHolder;
2729

2830
@ReactModule(name = WebGPUModule.NAME)
29-
public class WebGPUModule extends NativeWebGPUModuleSpec {
31+
public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEventListener {
3032
static {
3133
System.loadLibrary("react-native-webgpu"); // Load the C++ library
3234
}
@@ -35,8 +37,34 @@ public WebGPUModule(ReactApplicationContext reactContext) {
3537
super(reactContext);
3638
// Initialize the C++ module
3739
initialize();
40+
reactContext.addLifecycleEventListener(this);
3841
}
3942

43+
@Override
44+
public void invalidate() {
45+
getReactApplicationContext().removeLifecycleEventListener(this);
46+
super.invalidate();
47+
}
48+
49+
@Override
50+
public void onHostResume() {}
51+
52+
/**
53+
* The app is going to the background: the last moment to write what Dawn's
54+
* pipeline caches hold before the process may be killed (see
55+
* GPUDevice::flushPipelineCaches).
56+
*/
57+
@Override
58+
public void onHostPause() {
59+
flushPipelineCaches();
60+
}
61+
62+
@Override
63+
public void onHostDestroy() {}
64+
65+
@DoNotStrip
66+
private native void flushPipelineCaches();
67+
4068
@OptIn(markerClass = FrameworkAPI.class)
4169
@ReactMethod(isBlockingSynchronousMethod = true)
4270
public boolean install() {
@@ -47,13 +75,16 @@ public boolean install() {
4775
if (blobModule == null) {
4876
throw new RuntimeException("React Native's BlobModule was not found!");
4977
}
50-
initializeNative(jsContext.get(), (CallInvokerHolderImpl) callInvokerHolder, blobModule);
78+
// Dawn keeps the pipelines it compiles here, so a relaunch does not
79+
// compile them again (see DawnBlobCache).
80+
String cacheDirectory = new File(context.getCacheDir(), "webgpu-dawn").getAbsolutePath();
81+
initializeNative(jsContext.get(), (CallInvokerHolderImpl) callInvokerHolder, blobModule, cacheDirectory);
5182
return true;
5283
}
5384

5485
@OptIn(markerClass = FrameworkAPI.class)
5586
@DoNotStrip
56-
private native void initializeNative(long jsRuntime, CallInvokerHolderImpl jsInvoker, BlobModule blobModule);
87+
private native void initializeNative(long jsRuntime, CallInvokerHolderImpl jsInvoker, BlobModule blobModule, String cacheDirectory);
5788

5889
/**
5990
* Called from C++ (AndroidPlatformContext::snapshotView) on an arbitrary

‎packages/webgpu/apple/WebGPUModule.mm‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#import "WebGPUModule.h"
22
#include "ApplePlatformContext.h"
3+
#include "DawnBlobCache.h"
34
#import "GPUCanvasContext.h"
45
#import "RNWGUIKit.h"
56

@@ -109,6 +110,20 @@ - (void)invalidate {
109110
std::shared_ptr<rnwgpu::PlatformContext> platformContext =
110111
std::make_shared<rnwgpu::ApplePlatformContext>(
111112
std::move(viewLookup), std::move(blobManagerLookup));
113+
// Dawn keeps the pipelines it compiles here, so a relaunch does not compile
114+
// them again (see DawnBlobCache). The caches directory is per app on iOS but
115+
// shared on macOS, hence the bundle identifier.
116+
NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
117+
NSUserDomainMask, YES)
118+
.firstObject;
119+
NSString *bundle = NSBundle.mainBundle.bundleIdentifier;
120+
if (caches != nil) {
121+
if (bundle != nil) {
122+
caches = [caches stringByAppendingPathComponent:bundle];
123+
}
124+
rnwgpu::DawnBlobCache::setDirectory(
125+
[caches stringByAppendingPathComponent:@"webgpu-dawn"].UTF8String);
126+
}
112127
webgpuManager = std::make_shared<rnwgpu::RNWebGPUManager>(runtime, jsInvoker,
113128
platformContext);
114129
return @true;

0 commit comments

Comments
 (0)