From 62dc6196cf06a5e6d25cb74a06afb4bf570d5d9f Mon Sep 17 00:00:00 2001 From: William Candillon Date: Tue, 24 Nov 2026 17:02:55 +0100 Subject: [PATCH 1/5] =?UTF-8?q?feat(=F0=9F=A7=B9):=20add=20purgeGpuResourc?= =?UTF-8?q?es(),=20and=20purge=20when=20the=20system=20is=20short=20of=20m?= =?UTF-8?q?emory?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dawn keeps the memory of destroyed textures and buffers for reuse, and in an idle app the deletions wait for a tick nothing asks for. purgeGpuResources() hands that memory back to the system from a background thread, for every device created here. It also runs on iOS memory warnings, and on Android onLowMemory and onTrimMemory from TRIM_MEMORY_BACKGROUND. --- .../docs/getting-started/native-api.mdx | 19 ++++ packages/webgpu/android/cpp/cpp-adapter.cpp | 8 ++ .../main/java/com/webgpu/WebGPUModule.java | 31 ++++++ packages/webgpu/apple/WebGPUModule.mm | 22 ++++ packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp | 100 ++++++++++++++++++ packages/webgpu/cpp/rnwgpu/api/GPUDevice.h | 24 ++++- packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h | 5 + .../src/__tests__/PurgeGpuResources.spec.ts | 76 +++++++++++++ packages/webgpu/src/index.tsx | 1 + packages/webgpu/src/main/index.tsx | 1 + packages/webgpu/src/main/index.web.tsx | 1 + packages/webgpu/src/mock.ts | 2 + packages/webgpu/src/purgeGpuResources.ts | 18 ++++ 13 files changed, 304 insertions(+), 4 deletions(-) create mode 100644 packages/webgpu/src/__tests__/PurgeGpuResources.spec.ts create mode 100644 packages/webgpu/src/purgeGpuResources.ts diff --git a/apps/docs/content/docs/getting-started/native-api.mdx b/apps/docs/content/docs/getting-started/native-api.mdx index eb651233d5..89265dae5a 100644 --- a/apps/docs/content/docs/getting-started/native-api.mdx +++ b/apps/docs/content/docs/getting-started/native-api.mdx @@ -110,6 +110,25 @@ const device = await adapter.requestDevice({ A device wrapped with [`importDevice()`](#importing-an-external-device) is created by its own library and does not use this cache. +## Purging GPU memory + +Destroying a texture or a buffer frees it inside Dawn, which keeps its memory for reuse rather than returning it to the system. +`purgeGpuResources()` hands that memory back, for instance once an export or a heavy screen is done: + +```tsx twoslash +import { purgeGpuResources } from "react-native-webgpu"; +declare const texture: GPUTexture; +// ---cut--- +texture.destroy(); +purgeGpuResources(); +``` + +It covers every device created through React Native WebGPU, does not affect what is alive, and returns right away: the work happens in the background, over about a second at most while the GPU finishes what was submitted. +It is called for you on an iOS memory warning, and on Android on `onLowMemory()` and on `onTrimMemory()` from `TRIM_MEMORY_BACKGROUND`. +There is no need to call it every frame: the next allocations have to ask the system for memory again. + +A device requested with `implicitDeviceSynchronization: false` is purged on the thread of its runtime, when that thread gets to it. An [imported device](#importing-an-external-device) is purged by its owner: use `Skia.purgeGpuResources()` for Skia's, in the React Native Skia versions that have it. + ## Importing an external device `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. diff --git a/packages/webgpu/android/cpp/cpp-adapter.cpp b/packages/webgpu/android/cpp/cpp-adapter.cpp index adeee9664a..5fe2aac7c3 100644 --- a/packages/webgpu/android/cpp/cpp-adapter.cpp +++ b/packages/webgpu/android/cpp/cpp-adapter.cpp @@ -70,6 +70,14 @@ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */, rnwgpu::GPUDevice::flushPipelineCaches(); } +// The system is short of memory (UI thread), see +// GPUDevice::purgeGpuResources. +extern "C" JNIEXPORT void JNICALL +Java_com_webgpu_WebGPUModule_purgeGpuResourcesNative(JNIEnv * /* env */, + jclass /* clazz */) { + rnwgpu::GPUDevice::purgeGpuResources(); +} + // WebGPUModule.onHostResume and onHostPause (UI thread): animation frames // follow the host activity, resumed or not. extern "C" JNIEXPORT void JNICALL diff --git a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java index a4a8557c7f..28099c7684 100644 --- a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java +++ b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java @@ -1,5 +1,7 @@ package com.webgpu; +import android.content.ComponentCallbacks2; +import android.content.res.Configuration; import android.graphics.Bitmap; import android.hardware.HardwareBuffer; import android.os.Build; @@ -34,6 +36,28 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve System.loadLibrary("react-native-webgpu"); // Load the C++ library } + // The GPU memory nothing uses goes back to the system when it is short of + // memory (see GPUDevice::purgeGpuResources). + private final ComponentCallbacks2 mComponentCallbacks = + new ComponentCallbacks2() { + @Override + public void onConfigurationChanged(Configuration newConfig) {} + + @Override + public void onLowMemory() { + purgeGpuResourcesNative(); + } + + @Override + public void onTrimMemory(int level) { + // Android 14 and later never call onLowMemory(), and of the trim + // levels only send UI_HIDDEN (any app switch) and BACKGROUND. + if (level >= TRIM_MEMORY_BACKGROUND) { + purgeGpuResourcesNative(); + } + } + }; + public WebGPUModule(ReactApplicationContext reactContext) { super(reactContext); // Initialize the C++ module @@ -41,11 +65,15 @@ public WebGPUModule(ReactApplicationContext reactContext) { // Animation frames follow the host activity: resumed, or not. setForegroundNative(reactContext.getLifecycleState() == LifecycleState.RESUMED); reactContext.addLifecycleEventListener(this); + reactContext.getApplicationContext().registerComponentCallbacks(mComponentCallbacks); } @Override public void invalidate() { getReactApplicationContext().removeLifecycleEventListener(this); + getReactApplicationContext() + .getApplicationContext() + .unregisterComponentCallbacks(mComponentCallbacks); super.invalidate(); } @@ -72,6 +100,9 @@ public void onHostDestroy() {} @DoNotStrip private native void flushPipelineCaches(); + @DoNotStrip + private static native void purgeGpuResourcesNative(); + /** * Whether the app is in the foreground: the host activity is resumed (see * AnimationFrameDispatcher::setForeground). An AChoreographer sends its diff --git a/packages/webgpu/apple/WebGPUModule.mm b/packages/webgpu/apple/WebGPUModule.mm index 4f75772294..5ed8bd7c04 100644 --- a/packages/webgpu/apple/WebGPUModule.mm +++ b/packages/webgpu/apple/WebGPUModule.mm @@ -2,6 +2,7 @@ #include "ApplePlatformContext.h" #include "DawnBlobCache.h" #import "GPUCanvasContext.h" +#import "GPUDevice.h" #import "RNWGUIKit.h" #import @@ -22,6 +23,24 @@ @interface RCTBridge (JSIRuntime) - (void *)runtime; @end +#if !TARGET_OS_OSX +// The GPU memory nothing uses goes back to the system when it is short of +// memory (see GPUDevice::purgeGpuResources). Once for the process: devices +// outlive a React reload. +static void observeMemoryWarnings() { + static dispatch_once_t once; + dispatch_once(&once, ^{ + [[NSNotificationCenter defaultCenter] + addObserverForName:UIApplicationDidReceiveMemoryWarningNotification + object:nil + queue:nil + usingBlock:^(NSNotification *) { + rnwgpu::GPUDevice::purgeGpuResources(); + }]; + }); +} +#endif + @implementation WebGPUModule RCT_EXPORT_MODULE(WebGPUModule) @@ -149,6 +168,9 @@ - (void)invalidate { rnwgpu::DawnBlobCache::setDirectory( [caches stringByAppendingPathComponent:@"webgpu-dawn"].UTF8String); } +#if !TARGET_OS_OSX + observeMemoryWarnings(); +#endif webgpuManager = std::make_shared(runtime, jsInvoker, platformContext); return @true; diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp index f4464b1182..511df357c3 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp @@ -5,7 +5,10 @@ #include #include #include +#include #include +#include +#include #include #include #include @@ -170,6 +173,103 @@ void GPUDevice::flushPipelineCaches() { } } +bool GPUDevice::reduceMemoryUsage(int pass) { + // Copied out of the wrappers, as in flushPipelineCaches(). Collected anew + // for each pass, so that a device is not kept alive between passes. + struct Purge { + wgpu::Device device; + std::shared_ptr async; + std::weak_ptr wrapper; + }; + std::vector purges; + { + std::lock_guard lock(getRegistryMutex()); + for (const auto &entry : getRegistry()) { + GPUDevice *device = entry.second; + if (device->_origin == Origin::Imported || + device->weak_from_this().expired()) { + continue; + } + purges.push_back( + {device->_instance, device->_async, device->weak_from_this()}); + } + } + bool pending = false; + for (const auto &purge : purges) { + // Dawn does nothing for a device that is lost or destroyed, which it + // checks with the device locked. + if (purge.device.HasFeature( + wgpu::FeatureName::ImplicitDeviceSynchronization)) { + // Not redundant with what ReduceMemoryUsage() does: it learns which work + // has completed but leaves what waits for that work to a tick, and an + // idle app does not tick. + purge.device.Tick(); + pending |= dawn::native::ReduceMemoryUsage(purge.device.Get()); + continue; + } + // A device used from its runtime's thread only: what Dawn answers there is + // not waited for, so it gets a fixed number of passes. The first lets the + // pending deletions go through, the next free what they leave. + constexpr int kUnsynchronizedPasses = 3; + if (pass >= kUnsynchronizedPasses || !purge.async) { + continue; + } + pending = true; + purge.async->post([weak = purge.wrapper](jsi::Runtime &) { + if (auto device = weak.lock()) { + device->_instance.Tick(); + dawn::native::ReduceMemoryUsage(device->_instance.Get()); + } + }); + } + return pending; +} + +void GPUDevice::purgeGpuResources() noexcept { + struct State { + std::mutex mutex; + bool running = false; + bool requested = false; + }; + // Never destroyed: the purge thread may still use it while the process + // exits. + static auto *state = new State(); + { + std::lock_guard lock(state->mutex); + state->requested = true; + if (state->running) { + return; + } + state->running = true; + } + try { + std::thread([] { + constexpr int kMaxPasses = 10; + constexpr auto kPassInterval = std::chrono::milliseconds(100); + for (;;) { + { + std::lock_guard lock(state->mutex); + if (!state->requested) { + state->running = false; + return; + } + state->requested = false; + } + for (int pass = 0; pass < kMaxPasses; pass++) { + if (!reduceMemoryUsage(pass)) { + break; + } + std::this_thread::sleep_for(kPassInterval); + } + } + }).detach(); + } catch (const std::system_error &) { + // No thread to be had: nothing is purged. + std::lock_guard lock(state->mutex); + state->running = false; + } +} + void GPUDevice::notifyDeviceLost(wgpu::DeviceLostReason reason, std::string message) { std::vector toResolve; diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h index 734f15adbf..ea92ed5a37 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h @@ -109,15 +109,21 @@ class GPUDevice : public NativeObject { private: static std::unordered_map &getRegistry() { - static std::unordered_map registry; - return registry; + // Never destroyed: the purge thread (see purgeGpuResources) may still read + // it while the process exits. + static auto *registry = new std::unordered_map(); + return *registry; } static std::mutex &getRegistryMutex() { - static std::mutex mutex; - return mutex; + static auto *mutex = new std::mutex(); + return *mutex; } + // One round of purgeGpuResources() over the live devices. Returns whether + // Dawn still has deletions waiting for submitted work to complete. + static bool reduceMemoryUsage(int pass); + public: std::string getBrand() { return CLASS_NAME; } @@ -323,6 +329,16 @@ class GPUDevice : public NativeObject { // the last moment to write before the process may be killed. static void flushPipelineCaches(); + // Has Dawn give the GPU memory it keeps for reuse (the memory of destroyed + // textures and buffers, staging memory) back to the system, for every live + // device. Nothing alive is affected. Returns at once: a background thread + // does it, and again for up to about a second while deletions still wait for + // submitted work. Requests made meanwhile are served by the same thread. A + // device that does not synchronize itself is asked a few times, on the + // thread of its runtime. An imported device is its owner's to purge. Any + // thread: the platform modules call it when the system is short of memory. + static void purgeGpuResources() noexcept; + private: friend class GPUAdapter; diff --git a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h index 29428235d6..ebe01d8e07 100644 --- a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h +++ b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h @@ -558,6 +558,9 @@ class RNWebGPU : public NativeObject { registry.removeSurfaceInfoIfDetached(contextId); } + // See GPUDevice::purgeGpuResources. + void purgeGpuResources() { GPUDevice::purgeGpuResources(); } + static void definePrototype(jsi::Runtime &runtime, jsi::Object &prototype) { installGetter(runtime, prototype, "fabric", &RNWebGPU::getFabric); installGetter(runtime, prototype, "gpu", &RNWebGPU::getGPU); @@ -581,6 +584,8 @@ class RNWebGPU : public NativeObject { &RNWebGPU::createNativeBufferFromPointer); installMethodWithRuntime(runtime, prototype, "importDevice", &RNWebGPU::importDevice); + installMethod(runtime, prototype, "purgeGpuResources", + &RNWebGPU::purgeGpuResources); installMethod(runtime, prototype, "adoptTexture", &RNWebGPU::adoptTexture); installMethod(runtime, prototype, "createTestVideoPlayer", &RNWebGPU::createTestVideoPlayer); diff --git a/packages/webgpu/src/__tests__/PurgeGpuResources.spec.ts b/packages/webgpu/src/__tests__/PurgeGpuResources.spec.ts new file mode 100644 index 0000000000..e9af36e98d --- /dev/null +++ b/packages/webgpu/src/__tests__/PurgeGpuResources.spec.ts @@ -0,0 +1,76 @@ +import { client } from "./setup"; + +// Native only: the web has nothing to purge. +describe("purgeGpuResources", () => { + it("keeps what is alive, with destroyed resources and submitted work around", async () => { + if (client.OS === "web") { + return; + } + const result = await client.eval(({ device }) => { + const alive = device.createBuffer({ + size: 16, + usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST, + }); + device.queue.writeBuffer(alive, 0, new Uint32Array([1, 2, 3, 4])); + for (let i = 0; i < 20; i++) { + const texture = device.createTexture({ + size: [256, 256], + format: "rgba8unorm", + usage: GPUTextureUsage.RENDER_ATTACHMENT, + }); + const encoder = device.createCommandEncoder(); + encoder + .beginRenderPass({ + colorAttachments: [ + { + view: texture.createView(), + clearValue: [1, 0, 0, 1], + loadOp: "clear", + storeOp: "store", + }, + ], + }) + .end(); + device.queue.submit([encoder.finish()]); + texture.destroy(); + RNWebGPU.purgeGpuResources(); + } + const readback = device.createBuffer({ + size: 16, + usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST, + }); + const encoder = device.createCommandEncoder(); + encoder.copyBufferToBuffer(alive, 0, readback, 0, 16); + device.queue.submit([encoder.finish()]); + return readback + .mapAsync(GPUMapMode.READ) + .then(() => Array.from(new Uint32Array(readback.getMappedRange()))); + }); + expect(result).toEqual([1, 2, 3, 4]); + }); + + it("accepts a destroyed device and one its runtime's thread owns", async () => { + if (client.OS === "web") { + return; + } + const result = await client.eval(({ gpu }) => { + const request = (implicitDeviceSynchronization: boolean) => + gpu + .requestAdapter() + .then((adapter) => + adapter!.requestDevice({ implicitDeviceSynchronization }), + ); + return Promise.all([request(true), request(false)]).then( + ([destroyed, unsynchronized]) => { + destroyed.destroy(); + RNWebGPU.purgeGpuResources(); + return unsynchronized.queue.onSubmittedWorkDone().then(() => { + unsynchronized.destroy(); + return true; + }); + }, + ); + }); + expect(result).toBe(true); + }); +}); diff --git a/packages/webgpu/src/index.tsx b/packages/webgpu/src/index.tsx index 64dcc568ae..8b07bf8f1f 100644 --- a/packages/webgpu/src/index.tsx +++ b/packages/webgpu/src/index.tsx @@ -113,6 +113,7 @@ declare global { // device from Skia.getNativeDevice()) into a GPUDevice. Requires the // exporter to link this process's single Dawn copy. importDevice: (pointer: bigint) => GPUDevice; + purgeGpuResources: () => void; // Wrap an externally created WGPUTexture pointer into a GPUTexture, // taking ownership of one reference (pair with producers that return a // +1 pointer, e.g. Skia.Image.MakeGPUTextureFromImage()). diff --git a/packages/webgpu/src/main/index.tsx b/packages/webgpu/src/main/index.tsx index 15ae1f65e1..742513df60 100644 --- a/packages/webgpu/src/main/index.tsx +++ b/packages/webgpu/src/main/index.tsx @@ -62,6 +62,7 @@ export * from "../WebGPUViewNativeComponent"; export * from "../hooks"; export * from "../GPUDeviceProvider"; export * from "../importDevice"; +export * from "../purgeGpuResources"; export * from "../video"; export * from "../formats"; diff --git a/packages/webgpu/src/main/index.web.tsx b/packages/webgpu/src/main/index.web.tsx index 243681f3d8..f4cf24d1f3 100644 --- a/packages/webgpu/src/main/index.web.tsx +++ b/packages/webgpu/src/main/index.web.tsx @@ -6,6 +6,7 @@ export * from "../WebGPUViewNativeComponent"; export * from "../hooks"; export * from "../GPUDeviceProvider"; export * from "../formats"; +export * from "../purgeGpuResources"; export * from "../video"; // We don't need to set all global properties on web, webgpu is already available globally diff --git a/packages/webgpu/src/mock.ts b/packages/webgpu/src/mock.ts index fba07def07..72e9662f57 100644 --- a/packages/webgpu/src/mock.ts +++ b/packages/webgpu/src/mock.ts @@ -147,6 +147,8 @@ export const useMainDevice = (): never => { throw new Error(`useMainDevice() ${NOT_AVAILABLE_UNDER_JEST}`); }; +export const purgeGpuResources = () => undefined; + export const importDevice = (_pointer: bigint): GPUDevice => { throw new Error(`importDevice() ${NOT_AVAILABLE_UNDER_JEST}`); }; diff --git a/packages/webgpu/src/purgeGpuResources.ts b/packages/webgpu/src/purgeGpuResources.ts new file mode 100644 index 0000000000..5e74ad1882 --- /dev/null +++ b/packages/webgpu/src/purgeGpuResources.ts @@ -0,0 +1,18 @@ +/** + * Hands the GPU memory nothing uses back to the system: Dawn keeps the memory + * of destroyed textures and buffers for reuse otherwise. Call `destroy()` on + * what you are done with first; what is alive is not affected. + * + * It covers every device created through react-native-webgpu and returns right + * away: the work happens in the background, over about a second at most. An + * imported device is purged by its owner (`Skia.purgeGpuResources()` for + * Skia's). The system being short of memory triggers it as well. + * + * Nothing happens where react-native-webgpu is not installed natively (Web). + */ +export const purgeGpuResources = (): void => { + if (typeof RNWebGPU === "undefined") { + return; + } + RNWebGPU.purgeGpuResources(); +}; From 4507e5a4ea4b4dabcdcde962715428af7dc44414 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Tue, 24 Nov 2026 17:26:33 +0100 Subject: [PATCH 2/5] =?UTF-8?q?docs(=F0=9F=A7=B9):=20say=20when=20purgeGpu?= =?UTF-8?q?Resources()=20is=20worth=20calling,=20and=20why=20the=20spec=20?= =?UTF-8?q?has=20none?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/getting-started/native-api.mdx | 28 +++++++++++++------ packages/webgpu/src/purgeGpuResources.ts | 18 ++++++------ 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/apps/docs/content/docs/getting-started/native-api.mdx b/apps/docs/content/docs/getting-started/native-api.mdx index 89265dae5a..513a3a1c49 100644 --- a/apps/docs/content/docs/getting-started/native-api.mdx +++ b/apps/docs/content/docs/getting-started/native-api.mdx @@ -112,22 +112,34 @@ A device wrapped with [`importDevice()`](#importing-an-external-device) is creat ## Purging GPU memory -Destroying a texture or a buffer frees it inside Dawn, which keeps its memory for reuse rather than returning it to the system. -`purgeGpuResources()` hands that memory back, for instance once an export or a heavy screen is done: +**Most apps should never call `purgeGpuResources()`.** Call `destroy()` on the textures and buffers you are done with, and Dawn reuses their memory for the next ones. When the system runs short of memory, React Native WebGPU purges on its own: on an iOS memory warning, and on Android on `onLowMemory()` and on `onTrimMemory()` from `TRIM_MEMORY_BACKGROUND`. + +The one case for calling it is a one-off peak followed by a long stretch that needs far less GPU memory, while the app stays in the foreground. For example, a video export that allocated hundreds of megabytes just finished, and the app is back to a light screen: ```tsx twoslash import { purgeGpuResources } from "react-native-webgpu"; -declare const texture: GPUTexture; +declare const exportTextures: GPUTexture[]; // ---cut--- -texture.destroy(); +// The export is over, and no other one follows +exportTextures.forEach((texture) => texture.destroy()); purgeGpuResources(); ``` -It covers every device created through React Native WebGPU, does not affect what is alive, and returns right away: the work happens in the background, over about a second at most while the GPU finishes what was submitted. -It is called for you on an iOS memory warning, and on Android on `onLowMemory()` and on `onTrimMemory()` from `TRIM_MEMORY_BACKGROUND`. -There is no need to call it every frame: the next allocations have to ask the system for memory again. +Do not call it: + +- in a render loop, or after each `destroy()`; +- when a component unmounts or on navigation: the next screen usually wants that memory back; +- to fix a leak or an out-of-memory error: it only returns memory that nothing uses, so a texture you have not destroyed stays. + +Purging too often makes an app slower: memory that Dawn would have reused has to be requested from the system again. + +It returns right away and works in the background for up to about a second. It covers every device created through React Native WebGPU; an [imported device](#importing-an-external-device) is purged by its owner. + +### Why it is not in the WebGPU spec + +The spec lets you say when you are done with a resource, through `destroy()`. What happens to the memory afterwards (kept for reuse or returned to the system) is left to the implementation. On the web, that is the browser's job: it manages GPU memory for all its pages, and a page has no reason to know about it. -A device requested with `implicitDeviceSynchronization: false` is purged on the thread of its runtime, when that thread gets to it. An [imported device](#importing-an-external-device) is purged by its owner: use `Skia.purgeGpuResources()` for Skia's, in the React Native Skia versions that have it. +In a native app there is no browser to do it: Dawn runs in your own process, its memory counts towards your app's, and the system can end the app for using too much of it. React Native WebGPU therefore takes on that role with the automatic purges above, and `purgeGpuResources()` covers what it cannot know: that your app has just finished a peak. It does nothing on the Web. ## Importing an external device diff --git a/packages/webgpu/src/purgeGpuResources.ts b/packages/webgpu/src/purgeGpuResources.ts index 5e74ad1882..6febddfdf1 100644 --- a/packages/webgpu/src/purgeGpuResources.ts +++ b/packages/webgpu/src/purgeGpuResources.ts @@ -1,14 +1,16 @@ /** - * Hands the GPU memory nothing uses back to the system: Dawn keeps the memory - * of destroyed textures and buffers for reuse otherwise. Call `destroy()` on - * what you are done with first; what is alive is not affected. + * Returns the GPU memory nothing uses to the system. Most apps should never + * call it: `destroy()` lets Dawn reuse the memory, and react-native-webgpu + * purges on its own when the system is short of memory. * - * It covers every device created through react-native-webgpu and returns right - * away: the work happens in the background, over about a second at most. An - * imported device is purged by its owner (`Skia.purgeGpuResources()` for - * Skia's). The system being short of memory triggers it as well. + * It is meant for a one-off peak (a video export) followed by a long stretch + * that needs far less GPU memory. Not for a render loop, not after each + * `destroy()`, not on unmount: memory Dawn would have reused has to be + * requested from the system again. It does not free what was not destroyed. * - * Nothing happens where react-native-webgpu is not installed natively (Web). + * It returns right away and works in the background. It covers every device + * created through react-native-webgpu; an imported device is purged by its + * owner. Not part of the WebGPU spec, and does nothing on the Web. */ export const purgeGpuResources = (): void => { if (typeof RNWebGPU === "undefined") { From 0f87b5969313c15de6f423e2b01aa433ac1685ca Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 09:19:51 +0100 Subject: [PATCH 3/5] =?UTF-8?q?refactor(=F0=9F=A7=B9):=20move=20the=20purg?= =?UTF-8?q?e=20out=20of=20GPUDevice=20into=20GpuPurge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GPUDevice is the wrapper of one device, and held the purge thread, its state and its pass timing as statics. They move to a class of their own, GpuPurge, as in react-native-skia (RNSkGpuPurge): - GpuPurge::request() is purgeGpuResources() from JS. The platform modules report what the system said (onMemoryWarning, onLowMemory, onTrimMemory) and GpuPurge decides what calls for a purge, so the threshold is no longer in Java. - GPUDevice keeps one pass, without the loop counter: reduceMemoryUsage() for the devices that synchronize themselves and reduceMemoryUsageOnRuntimeThreads() for the others. - liveDevices() is the registry walk that flushPipelineCaches() and the passes share (from #653). - The pass count, the pass interval and the trim level are named in one place. No change in behavior. Co-authored-by: Andrei Alecu --- packages/webgpu/android/CMakeLists.txt | 1 + packages/webgpu/android/cpp/cpp-adapter.cpp | 18 +- .../main/java/com/webgpu/WebGPUModule.java | 18 +- packages/webgpu/apple/WebGPUModule.mm | 10 +- packages/webgpu/cpp/rnwgpu/GpuPurge.cpp | 86 +++++++++ packages/webgpu/cpp/rnwgpu/GpuPurge.h | 62 +++++++ packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp | 167 +++++------------- packages/webgpu/cpp/rnwgpu/api/GPUDevice.h | 57 ++++-- packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h | 5 +- 9 files changed, 269 insertions(+), 155 deletions(-) create mode 100644 packages/webgpu/cpp/rnwgpu/GpuPurge.cpp create mode 100644 packages/webgpu/cpp/rnwgpu/GpuPurge.h diff --git a/packages/webgpu/android/CMakeLists.txt b/packages/webgpu/android/CMakeLists.txt index 758586514a..4bc2869df5 100644 --- a/packages/webgpu/android/CMakeLists.txt +++ b/packages/webgpu/android/CMakeLists.txt @@ -56,6 +56,7 @@ add_library(${PACKAGE_NAME} SHARED ../cpp/rnwgpu/api/GPUComputePipeline.cpp ../cpp/rnwgpu/api/GPUCanvasContext.cpp ../cpp/rnwgpu/DawnBlobCache.cpp + ../cpp/rnwgpu/GpuPurge.cpp ../cpp/rnwgpu/NativeBufferViewRegistry.cpp ../cpp/rnwgpu/AnimationFrames.cpp ../cpp/rnwgpu/RNWebGPUManager.cpp diff --git a/packages/webgpu/android/cpp/cpp-adapter.cpp b/packages/webgpu/android/cpp/cpp-adapter.cpp index 5fe2aac7c3..f8ed720939 100644 --- a/packages/webgpu/android/cpp/cpp-adapter.cpp +++ b/packages/webgpu/android/cpp/cpp-adapter.cpp @@ -25,6 +25,7 @@ #include "DawnBlobCache.h" #include "GPUCanvasContext.h" #include "GPUDevice.h" +#include "GpuPurge.h" #include "NativeBufferViewRegistry.h" #include "RNWebGPUManager.h" #include "WebGPURuntime.h" @@ -70,12 +71,19 @@ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */, rnwgpu::GPUDevice::flushPipelineCaches(); } -// The system is short of memory (UI thread), see -// GPUDevice::purgeGpuResources. +// WebGPUModule's ComponentCallbacks2 (UI thread): what the system says about +// memory, as it says it. GpuPurge decides what calls for a purge. extern "C" JNIEXPORT void JNICALL -Java_com_webgpu_WebGPUModule_purgeGpuResourcesNative(JNIEnv * /* env */, - jclass /* clazz */) { - rnwgpu::GPUDevice::purgeGpuResources(); +Java_com_webgpu_WebGPUModule_onLowMemoryNative(JNIEnv * /* env */, + jclass /* clazz */) { + rnwgpu::GpuPurge::onLowMemory(); +} + +extern "C" JNIEXPORT void JNICALL +Java_com_webgpu_WebGPUModule_onTrimMemoryNative(JNIEnv * /* env */, + jclass /* clazz */, + jint level) { + rnwgpu::GpuPurge::onTrimMemory(level); } // WebGPUModule.onHostResume and onHostPause (UI thread): animation frames diff --git a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java index 28099c7684..e5d0c55f5d 100644 --- a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java +++ b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java @@ -36,8 +36,9 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve System.loadLibrary("react-native-webgpu"); // Load the C++ library } - // The GPU memory nothing uses goes back to the system when it is short of - // memory (see GPUDevice::purgeGpuResources). + // What the system says about memory goes to the native side as it comes, + // which decides when the GPU memory nothing uses goes back to the system + // (see GpuPurge). private final ComponentCallbacks2 mComponentCallbacks = new ComponentCallbacks2() { @Override @@ -45,16 +46,12 @@ public void onConfigurationChanged(Configuration newConfig) {} @Override public void onLowMemory() { - purgeGpuResourcesNative(); + onLowMemoryNative(); } @Override public void onTrimMemory(int level) { - // Android 14 and later never call onLowMemory(), and of the trim - // levels only send UI_HIDDEN (any app switch) and BACKGROUND. - if (level >= TRIM_MEMORY_BACKGROUND) { - purgeGpuResourcesNative(); - } + onTrimMemoryNative(level); } }; @@ -101,7 +98,10 @@ public void onHostDestroy() {} private native void flushPipelineCaches(); @DoNotStrip - private static native void purgeGpuResourcesNative(); + private static native void onLowMemoryNative(); + + @DoNotStrip + private static native void onTrimMemoryNative(int level); /** * Whether the app is in the foreground: the host activity is resumed (see diff --git a/packages/webgpu/apple/WebGPUModule.mm b/packages/webgpu/apple/WebGPUModule.mm index 5ed8bd7c04..2f7a3dfaf1 100644 --- a/packages/webgpu/apple/WebGPUModule.mm +++ b/packages/webgpu/apple/WebGPUModule.mm @@ -2,7 +2,7 @@ #include "ApplePlatformContext.h" #include "DawnBlobCache.h" #import "GPUCanvasContext.h" -#import "GPUDevice.h" +#include "GpuPurge.h" #import "RNWGUIKit.h" #import @@ -24,9 +24,9 @@ - (void *)runtime; @end #if !TARGET_OS_OSX -// The GPU memory nothing uses goes back to the system when it is short of -// memory (see GPUDevice::purgeGpuResources). Once for the process: devices -// outlive a React reload. +// A memory warning goes to the native side as it comes, which decides when the +// GPU memory nothing uses goes back to the system (see GpuPurge). Once for the +// process: devices outlive a React reload. static void observeMemoryWarnings() { static dispatch_once_t once; dispatch_once(&once, ^{ @@ -35,7 +35,7 @@ static void observeMemoryWarnings() { object:nil queue:nil usingBlock:^(NSNotification *) { - rnwgpu::GPUDevice::purgeGpuResources(); + rnwgpu::GpuPurge::onMemoryWarning(); }]; }); } diff --git a/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp b/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp new file mode 100644 index 0000000000..c7e4f3a4b2 --- /dev/null +++ b/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp @@ -0,0 +1,86 @@ +#include "GpuPurge.h" + +#include +#include +#include + +#include "GPUDevice.h" + +namespace rnwgpu { + +namespace { + +struct State { + std::mutex mutex; + // Whether the purge thread is alive. + bool running = false; + // Whether a request came in since the thread last started a run. + bool requested = false; +}; + +// Never destroyed: the purge thread may still use it while the process exits. +State &getState() noexcept { + static auto *state = new State(); + return *state; +} + +} // namespace + +void GpuPurge::request() noexcept { + auto &state = getState(); + { + std::lock_guard lock(state.mutex); + state.requested = true; + if (state.running) { + return; + } + state.running = true; + } + try { + std::thread([] { runRequests(); }).detach(); + } catch (const std::system_error &) { + // No thread to be had: nothing is purged. + std::lock_guard lock(state.mutex); + state.running = false; + } +} + +void GpuPurge::onMemoryWarning() noexcept { request(); } + +void GpuPurge::onLowMemory() noexcept { request(); } + +void GpuPurge::onTrimMemory(int level) noexcept { + if (level >= kTrimMemoryBackground) { + request(); + } +} + +void GpuPurge::runRequests() noexcept { + auto &state = getState(); + for (;;) { + { + std::lock_guard lock(state.mutex); + if (!state.requested) { + state.running = false; + return; + } + state.requested = false; + } + run(); + } +} + +void GpuPurge::run() { + for (int pass = 0; pass < kMaxPasses; pass++) { + bool pending = GPUDevice::reduceMemoryUsage(); + if (pass < kRuntimeThreadPasses) { + pending |= GPUDevice::reduceMemoryUsageOnRuntimeThreads(); + } + if (!pending) { + return; + } + std::this_thread::sleep_for(kPassInterval); + } +} + +} // namespace rnwgpu diff --git a/packages/webgpu/cpp/rnwgpu/GpuPurge.h b/packages/webgpu/cpp/rnwgpu/GpuPurge.h new file mode 100644 index 0000000000..736408f889 --- /dev/null +++ b/packages/webgpu/cpp/rnwgpu/GpuPurge.h @@ -0,0 +1,62 @@ +#pragma once + +#include + +namespace rnwgpu { + +// purgeGpuResources(), which the system also brings about when it wants memory +// back: Dawn gives the GPU memory it keeps for reuse (the memory of destroyed +// textures and buffers, staging memory) back to the system, for every live +// device (see GPUDevice::reduceMemoryUsage). Nothing alive is affected. +// +// The platform modules only report what the system said (onMemoryWarning, +// onLowMemory, onTrimMemory): whether it calls for a purge is decided here. +// +// request() returns at once. The work runs on a thread of its own, started by +// a request and gone once done; a request made while it runs is served by one +// more run of the same thread, however many came in. +class GpuPurge { +public: + // purgeGpuResources() from JS. Any thread. + static void request() noexcept; + + // iOS, UIApplicationDidReceiveMemoryWarningNotification: the system is short + // of memory, and ends the apps that hold the most of it first. Any thread. + static void onMemoryWarning() noexcept; + + // Android, ComponentCallbacks.onLowMemory(): the whole system is short of + // memory. Any thread. + static void onLowMemory() noexcept; + + // Android, ComponentCallbacks2.onTrimMemory(): purges from + // kTrimMemoryBackground. Any thread. + static void onTrimMemory(int level) noexcept; + +private: + // One run asks Dawn again for as long as it says deletions wait for + // submitted work to complete, this many times at most and this far apart: + // about a second in all. + static constexpr int kMaxPasses = 10; + static constexpr std::chrono::milliseconds kPassInterval{100}; + + // The passes of a run that also ask the devices only the thread of their + // runtime may use (see GPUDevice::reduceMemoryUsageOnRuntimeThreads). What + // Dawn answers there is not waited for, hence a fixed number: the first lets + // the pending deletions go through, the next free what they leave. + static constexpr int kRuntimeThreadPasses = 3; + + // ComponentCallbacks2.TRIM_MEMORY_BACKGROUND: the process is in the + // background, among those the system ends for their memory. The level below, + // TRIM_MEMORY_UI_HIDDEN, comes with every app switch, where the app is often + // back at once and wants that memory again. Since Android 14 these two are + // the only levels sent. + static constexpr int kTrimMemoryBackground = 40; + + // The purge thread: runs until no request is left. + static void runRequests() noexcept; + + // One run: the passes over the live devices. + static void run(); +}; + +} // namespace rnwgpu diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp index 511df357c3..c35ced5389 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp @@ -7,8 +7,6 @@ #include #include #include -#include -#include #include #include #include @@ -76,6 +74,18 @@ void flushDawnPipelineCache(const wgpu::Device &device, } } +// Has Dawn give the memory it keeps for reuse on a device back to the system. +// Returns whether deletions still wait for submitted work to complete. Dawn +// does nothing for a device that is lost or destroyed, which it checks with +// the device locked. Any thread that may use the device. +bool reduceDawnMemoryUsage(const wgpu::Device &device) { + // Not redundant with what ReduceMemoryUsage() does: it learns which work has + // completed but leaves what waits for that work to a tick, and an idle app + // does not tick. + device.Tick(); + return dawn::native::ReduceMemoryUsage(device.Get()); +} + } // namespace void GPUDevice::flushPipelineCache() { @@ -121,51 +131,38 @@ void GPUDevice::flushPipelineCacheIfDue() { flushPipelineCache(); } -void GPUDevice::flushPipelineCaches() { - // What flushing a device takes, copied out of its wrapper under the - // registry's mutex, rather than the wrapper itself: a strong reference to - // the wrapper released on this thread (the platform's UI thread) could be - // its last, and a wrapper, with its JSI members, must only go on its - // runtime's thread. - struct Flush { - wgpu::Device device; - std::shared_ptr> outgrown; - std::shared_ptr async; - std::weak_ptr wrapper; - }; - std::vector flushes; - { - std::lock_guard lock(getRegistryMutex()); - for (const auto &entry : getRegistry()) { - GPUDevice *device = entry.second; - // A wrapper on its way out (its last reference gone, its destructor - // about to unregister it) has nothing left to flush; nor has an - // imported device, whose owner keeps its cache. - if (device->_origin == Origin::Imported || - device->weak_from_this().expired()) { - continue; - } - flushes.push_back({device->_instance, device->_pipelineCacheOutgrown, - device->_async, device->weak_from_this()}); +std::vector GPUDevice::liveDevices() { + std::vector devices; + std::lock_guard lock(getRegistryMutex()); + for (const auto &entry : getRegistry()) { + GPUDevice *device = entry.second; + if (device->_origin == Origin::Imported || + device->weak_from_this().expired()) { + continue; } + devices.push_back({device->_instance, device->_pipelineCacheOutgrown, + device->_async, device->weak_from_this()}); } - for (const auto &flush : flushes) { + return devices; +} + +void GPUDevice::flushPipelineCaches() { + for (const auto &live : liveDevices()) { // Dawn locks a device that synchronizes itself around the flush, so this // thread can do it, and does: the runtime's thread may be busy, and a // runtime that polls its mailbox would hold the job until its next // operation, which may never come before the process is killed. - if (flush.device.HasFeature( - wgpu::FeatureName::ImplicitDeviceSynchronization)) { - flushDawnPipelineCache(flush.device, *flush.outgrown); + if (live.synchronizesItself()) { + flushDawnPipelineCache(live.device, *live.pipelineCacheOutgrown); continue; } - if (!flush.async) { + if (!live.async) { continue; } // A device used from its runtime's thread only is flushed there. Held // weakly: a device collected before its runtime gets to the job has // nothing left to flush, and the job must not keep it alive. - flush.async->post([weak = flush.wrapper](jsi::Runtime &) { + live.async->post([weak = live.wrapper](jsi::Runtime &) { if (auto device = weak.lock()) { device->flushPipelineCache(); } @@ -173,101 +170,31 @@ void GPUDevice::flushPipelineCaches() { } } -bool GPUDevice::reduceMemoryUsage(int pass) { - // Copied out of the wrappers, as in flushPipelineCaches(). Collected anew - // for each pass, so that a device is not kept alive between passes. - struct Purge { - wgpu::Device device; - std::shared_ptr async; - std::weak_ptr wrapper; - }; - std::vector purges; - { - std::lock_guard lock(getRegistryMutex()); - for (const auto &entry : getRegistry()) { - GPUDevice *device = entry.second; - if (device->_origin == Origin::Imported || - device->weak_from_this().expired()) { - continue; - } - purges.push_back( - {device->_instance, device->_async, device->weak_from_this()}); - } - } +bool GPUDevice::reduceMemoryUsage() { bool pending = false; - for (const auto &purge : purges) { - // Dawn does nothing for a device that is lost or destroyed, which it - // checks with the device locked. - if (purge.device.HasFeature( - wgpu::FeatureName::ImplicitDeviceSynchronization)) { - // Not redundant with what ReduceMemoryUsage() does: it learns which work - // has completed but leaves what waits for that work to a tick, and an - // idle app does not tick. - purge.device.Tick(); - pending |= dawn::native::ReduceMemoryUsage(purge.device.Get()); - continue; + for (const auto &live : liveDevices()) { + if (live.synchronizesItself()) { + pending |= reduceDawnMemoryUsage(live.device); } - // A device used from its runtime's thread only: what Dawn answers there is - // not waited for, so it gets a fixed number of passes. The first lets the - // pending deletions go through, the next free what they leave. - constexpr int kUnsynchronizedPasses = 3; - if (pass >= kUnsynchronizedPasses || !purge.async) { - continue; - } - pending = true; - purge.async->post([weak = purge.wrapper](jsi::Runtime &) { - if (auto device = weak.lock()) { - device->_instance.Tick(); - dawn::native::ReduceMemoryUsage(device->_instance.Get()); - } - }); } return pending; } -void GPUDevice::purgeGpuResources() noexcept { - struct State { - std::mutex mutex; - bool running = false; - bool requested = false; - }; - // Never destroyed: the purge thread may still use it while the process - // exits. - static auto *state = new State(); - { - std::lock_guard lock(state->mutex); - state->requested = true; - if (state->running) { - return; +bool GPUDevice::reduceMemoryUsageOnRuntimeThreads() { + bool asked = false; + for (const auto &live : liveDevices()) { + if (live.synchronizesItself() || !live.async) { + continue; } - state->running = true; - } - try { - std::thread([] { - constexpr int kMaxPasses = 10; - constexpr auto kPassInterval = std::chrono::milliseconds(100); - for (;;) { - { - std::lock_guard lock(state->mutex); - if (!state->requested) { - state->running = false; - return; - } - state->requested = false; - } - for (int pass = 0; pass < kMaxPasses; pass++) { - if (!reduceMemoryUsage(pass)) { - break; - } - std::this_thread::sleep_for(kPassInterval); - } + asked = true; + // Held weakly, as in flushPipelineCaches(). + live.async->post([weak = live.wrapper](jsi::Runtime &) { + if (auto device = weak.lock()) { + reduceDawnMemoryUsage(device->_instance); } - }).detach(); - } catch (const std::system_error &) { - // No thread to be had: nothing is purged. - std::lock_guard lock(state->mutex); - state->running = false; + }); } + return asked; } void GPUDevice::notifyDeviceLost(wgpu::DeviceLostReason reason, diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h index ea92ed5a37..bf3b268c10 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h @@ -109,8 +109,8 @@ class GPUDevice : public NativeObject { private: static std::unordered_map &getRegistry() { - // Never destroyed: the purge thread (see purgeGpuResources) may still read - // it while the process exits. + // Never destroyed: the purge thread (see GpuPurge) may still read it while + // the process exits. static auto *registry = new std::unordered_map(); return *registry; } @@ -120,9 +120,32 @@ class GPUDevice : public NativeObject { return *mutex; } - // One round of purgeGpuResources() over the live devices. Returns whether - // Dawn still has deletions waiting for submitted work to complete. - static bool reduceMemoryUsage(int pass); + // What a pass over the live devices (flushPipelineCaches, + // reduceMemoryUsage) takes from each wrapper, copied out under the + // registry's mutex rather than the wrapper itself: a strong reference to the + // wrapper released on the calling thread (the platform's UI thread, the + // purge thread) could be its last, and a wrapper, with its JSI members, must + // only go on its runtime's thread. + struct LiveDevice { + wgpu::Device device; + std::shared_ptr> pipelineCacheOutgrown; + std::shared_ptr async; + std::weak_ptr wrapper; + + // Whether Dawn locks the device around each call, so that any thread may + // use it (ImplicitDeviceSynchronization, the default). Only the thread of + // its runtime may otherwise. + bool synchronizesItself() const { + return device.HasFeature( + wgpu::FeatureName::ImplicitDeviceSynchronization); + } + }; + + // The devices made here that are still in use: not a wrapper on its way out + // (its last reference gone, its destructor about to unregister it), nor an + // imported device, which is its owner's to look after. Collected anew by + // each pass, so that no pass keeps a device alive for the next. Any thread. + static std::vector liveDevices(); public: std::string getBrand() { return CLASS_NAME; } @@ -329,15 +352,21 @@ class GPUDevice : public NativeObject { // the last moment to write before the process may be killed. static void flushPipelineCaches(); - // Has Dawn give the GPU memory it keeps for reuse (the memory of destroyed - // textures and buffers, staging memory) back to the system, for every live - // device. Nothing alive is affected. Returns at once: a background thread - // does it, and again for up to about a second while deletions still wait for - // submitted work. Requests made meanwhile are served by the same thread. A - // device that does not synchronize itself is asked a few times, on the - // thread of its runtime. An imported device is its owner's to purge. Any - // thread: the platform modules call it when the system is short of memory. - static void purgeGpuResources() noexcept; + // One pass of Dawn's ReduceMemoryUsage() over the live devices that + // synchronize themselves (the default), on the calling thread: Dawn gives + // the GPU memory it keeps for reuse (the memory of destroyed textures and + // buffers, staging memory) back to the system. Nothing alive is affected. + // Returns whether Dawn still has deletions waiting for submitted work to + // complete, in which case another pass shortly frees more. An imported + // device is its owner's to purge. Any thread; GpuPurge decides when, and + // how many times. + static bool reduceMemoryUsage(); + + // The same pass for the live devices only the thread of their runtime may + // use: a job on that thread for each, which a runtime that polls its + // mailbox reaches with its next operation. Returns whether any was asked; + // what Dawn answers there is not waited for. Any thread. + static bool reduceMemoryUsageOnRuntimeThreads(); private: friend class GPUAdapter; diff --git a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h index ebe01d8e07..94a2fa2c93 100644 --- a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h +++ b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h @@ -19,6 +19,7 @@ #include "GPUDevice.h" #include "GPUSharedFenceState.h" #include "GPUTexture.h" +#include "GpuPurge.h" #include "ImageBitmap.h" #include "NativeBufferViewRegistry.h" #include "NativeFrameImport.h" @@ -558,8 +559,8 @@ class RNWebGPU : public NativeObject { registry.removeSurfaceInfoIfDetached(contextId); } - // See GPUDevice::purgeGpuResources. - void purgeGpuResources() { GPUDevice::purgeGpuResources(); } + // See GpuPurge. + void purgeGpuResources() { GpuPurge::request(); } static void definePrototype(jsi::Runtime &runtime, jsi::Object &prototype) { installGetter(runtime, prototype, "fabric", &RNWebGPU::getFabric); From 33be520b434cf85b8ae269388da086969acbadd8 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 09:19:52 +0100 Subject: [PATCH 4/5] =?UTF-8?q?feat(=F0=9F=A7=B9):=20purge=20when=20the=20?= =?UTF-8?q?app=20goes=20to=20the=20background=20on=20Android?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a Galaxy S25 Edge (Android 17) the system only sends TRIM_MEMORY_UI_HIDDEN when the app leaves the foreground. TRIM_MEMORY_BACKGROUND never came, with the app cached and frozen for a minute, so the purge never ran on its own and about 440 MB of destroyed textures stayed held. From TRIM_MEMORY_UI_HIDDEN, going home gives them back within 3 s. Chrome, Flutter on iOS and Android's own renderer also free their GPU caches when the app is hidden. --- .../docs/getting-started/native-api.mdx | 2 +- packages/webgpu/cpp/rnwgpu/GpuPurge.cpp | 2 +- packages/webgpu/cpp/rnwgpu/GpuPurge.h | 26 +++++++++++-------- packages/webgpu/src/purgeGpuResources.ts | 3 ++- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/apps/docs/content/docs/getting-started/native-api.mdx b/apps/docs/content/docs/getting-started/native-api.mdx index 513a3a1c49..e71e8679d1 100644 --- a/apps/docs/content/docs/getting-started/native-api.mdx +++ b/apps/docs/content/docs/getting-started/native-api.mdx @@ -112,7 +112,7 @@ A device wrapped with [`importDevice()`](#importing-an-external-device) is creat ## Purging GPU memory -**Most apps should never call `purgeGpuResources()`.** Call `destroy()` on the textures and buffers you are done with, and Dawn reuses their memory for the next ones. When the system runs short of memory, React Native WebGPU purges on its own: on an iOS memory warning, and on Android on `onLowMemory()` and on `onTrimMemory()` from `TRIM_MEMORY_BACKGROUND`. +**Most apps should never call `purgeGpuResources()`.** Call `destroy()` on the textures and buffers you are done with, and Dawn reuses their memory for the next ones. React Native WebGPU purges on its own: on iOS on a memory warning, and on Android each time the app goes to the background (`onTrimMemory()` from `TRIM_MEMORY_UI_HIDDEN`) and on `onLowMemory()`. The one case for calling it is a one-off peak followed by a long stretch that needs far less GPU memory, while the app stays in the foreground. For example, a video export that allocated hundreds of megabytes just finished, and the app is back to a light screen: diff --git a/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp b/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp index c7e4f3a4b2..d041a7e9b8 100644 --- a/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp +++ b/packages/webgpu/cpp/rnwgpu/GpuPurge.cpp @@ -50,7 +50,7 @@ void GpuPurge::onMemoryWarning() noexcept { request(); } void GpuPurge::onLowMemory() noexcept { request(); } void GpuPurge::onTrimMemory(int level) noexcept { - if (level >= kTrimMemoryBackground) { + if (level >= kTrimMemoryUiHidden) { request(); } } diff --git a/packages/webgpu/cpp/rnwgpu/GpuPurge.h b/packages/webgpu/cpp/rnwgpu/GpuPurge.h index 736408f889..4dc80050ef 100644 --- a/packages/webgpu/cpp/rnwgpu/GpuPurge.h +++ b/packages/webgpu/cpp/rnwgpu/GpuPurge.h @@ -4,10 +4,11 @@ namespace rnwgpu { -// purgeGpuResources(), which the system also brings about when it wants memory -// back: Dawn gives the GPU memory it keeps for reuse (the memory of destroyed -// textures and buffers, staging memory) back to the system, for every live -// device (see GPUDevice::reduceMemoryUsage). Nothing alive is affected. +// purgeGpuResources(), which the system also brings about when it is short of +// memory and, on Android, when the app goes to the background: Dawn gives the +// GPU memory it keeps for reuse (the memory of destroyed textures and buffers, +// staging memory) back to the system, for every live device (see +// GPUDevice::reduceMemoryUsage). Nothing alive is affected. // // The platform modules only report what the system said (onMemoryWarning, // onLowMemory, onTrimMemory): whether it calls for a purge is decided here. @@ -29,7 +30,8 @@ class GpuPurge { static void onLowMemory() noexcept; // Android, ComponentCallbacks2.onTrimMemory(): purges from - // kTrimMemoryBackground. Any thread. + // kTrimMemoryUiHidden, which is each time the app goes to the background. + // Any thread. static void onTrimMemory(int level) noexcept; private: @@ -45,12 +47,14 @@ class GpuPurge { // the pending deletions go through, the next free what they leave. static constexpr int kRuntimeThreadPasses = 3; - // ComponentCallbacks2.TRIM_MEMORY_BACKGROUND: the process is in the - // background, among those the system ends for their memory. The level below, - // TRIM_MEMORY_UI_HIDDEN, comes with every app switch, where the app is often - // back at once and wants that memory again. Since Android 14 these two are - // the only levels sent. - static constexpr int kTrimMemoryBackground = 40; + // ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN: the app is no longer visible. It + // renders nothing there, and the system ends the processes in the background + // that hold the most memory first. The system sends it each time the app + // leaves the foreground, and it may be all it sends: TRIM_MEMORY_BACKGROUND + // did not come to an app left in the background until it was cached and + // frozen (a Samsung on Android 17). The levels below this one are for an app + // in the foreground, and are no longer sent since Android 14. + static constexpr int kTrimMemoryUiHidden = 20; // The purge thread: runs until no request is left. static void runRequests() noexcept; diff --git a/packages/webgpu/src/purgeGpuResources.ts b/packages/webgpu/src/purgeGpuResources.ts index 6febddfdf1..aec63ca37b 100644 --- a/packages/webgpu/src/purgeGpuResources.ts +++ b/packages/webgpu/src/purgeGpuResources.ts @@ -1,7 +1,8 @@ /** * Returns the GPU memory nothing uses to the system. Most apps should never * call it: `destroy()` lets Dawn reuse the memory, and react-native-webgpu - * purges on its own when the system is short of memory. + * purges on its own when the system is short of memory and, on Android, each + * time the app goes to the background. * * It is meant for a one-off peak (a video export) followed by a long stretch * that needs far less GPU memory. Not for a render loop, not after each From f56a60b788655a31b6c10b35bb88bb00e5daaa15 Mon Sep 17 00:00:00 2001 From: William Candillon Date: Wed, 25 Nov 2026 10:22:02 +0100 Subject: [PATCH 5/5] =?UTF-8?q?docs(=F0=9F=A7=B9):=20do=20not=20document?= =?UTF-8?q?=20purgeGpuResources()=20on=20the=20docs=20site?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It is meant for one rare case, and the purge now runs on its own when the app is hidden or the system is short of memory. The function stays exported, and its doc comment says when to call it and when not to. --- .../docs/getting-started/native-api.mdx | 31 ------------------- 1 file changed, 31 deletions(-) diff --git a/apps/docs/content/docs/getting-started/native-api.mdx b/apps/docs/content/docs/getting-started/native-api.mdx index e71e8679d1..eb651233d5 100644 --- a/apps/docs/content/docs/getting-started/native-api.mdx +++ b/apps/docs/content/docs/getting-started/native-api.mdx @@ -110,37 +110,6 @@ const device = await adapter.requestDevice({ A device wrapped with [`importDevice()`](#importing-an-external-device) is created by its own library and does not use this cache. -## Purging GPU memory - -**Most apps should never call `purgeGpuResources()`.** Call `destroy()` on the textures and buffers you are done with, and Dawn reuses their memory for the next ones. React Native WebGPU purges on its own: on iOS on a memory warning, and on Android each time the app goes to the background (`onTrimMemory()` from `TRIM_MEMORY_UI_HIDDEN`) and on `onLowMemory()`. - -The one case for calling it is a one-off peak followed by a long stretch that needs far less GPU memory, while the app stays in the foreground. For example, a video export that allocated hundreds of megabytes just finished, and the app is back to a light screen: - -```tsx twoslash -import { purgeGpuResources } from "react-native-webgpu"; -declare const exportTextures: GPUTexture[]; -// ---cut--- -// The export is over, and no other one follows -exportTextures.forEach((texture) => texture.destroy()); -purgeGpuResources(); -``` - -Do not call it: - -- in a render loop, or after each `destroy()`; -- when a component unmounts or on navigation: the next screen usually wants that memory back; -- to fix a leak or an out-of-memory error: it only returns memory that nothing uses, so a texture you have not destroyed stays. - -Purging too often makes an app slower: memory that Dawn would have reused has to be requested from the system again. - -It returns right away and works in the background for up to about a second. It covers every device created through React Native WebGPU; an [imported device](#importing-an-external-device) is purged by its owner. - -### Why it is not in the WebGPU spec - -The spec lets you say when you are done with a resource, through `destroy()`. What happens to the memory afterwards (kept for reuse or returned to the system) is left to the implementation. On the web, that is the browser's job: it manages GPU memory for all its pages, and a page has no reason to know about it. - -In a native app there is no browser to do it: Dawn runs in your own process, its memory counts towards your app's, and the system can end the app for using too much of it. React Native WebGPU therefore takes on that role with the automatic purges above, and `purgeGpuResources()` covers what it cannot know: that your app has just finished a peak. It does nothing on the Web. - ## Importing an external device `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.