diff --git a/packages/webgpu/android/cpp/cpp-adapter.cpp b/packages/webgpu/android/cpp/cpp-adapter.cpp index 93a93042b6..35eed74d29 100644 --- a/packages/webgpu/android/cpp/cpp-adapter.cpp +++ b/packages/webgpu/android/cpp/cpp-adapter.cpp @@ -70,6 +70,16 @@ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */, rnwgpu::GPUDevice::flushPipelineCaches(); } +// WebGPUModule.reduceMemoryUsage (UI thread): the system asked the app to +// give back memory, its UI hidden or memory low (see +// GPUDevice::reduceMemoryUsage). True when a call after a short delay would +// free more. +extern "C" JNIEXPORT jboolean JNICALL +Java_com_webgpu_WebGPUModule_reduceMemoryUsageNative(JNIEnv * /* env */, + jclass /* clazz */) { + return rnwgpu::GPUDevice::reduceMemoryUsage() ? JNI_TRUE : JNI_FALSE; +} + // 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..d484ebd99b 100644 --- a/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java +++ b/packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java @@ -1,8 +1,12 @@ package com.webgpu; +import android.content.ComponentCallbacks2; +import android.content.res.Configuration; import android.graphics.Bitmap; import android.hardware.HardwareBuffer; import android.os.Build; +import android.os.Handler; +import android.os.Looper; import android.util.Log; import android.view.View; @@ -41,11 +45,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(memoryCallbacks); } @Override public void invalidate() { getReactApplicationContext().removeLifecycleEventListener(this); + getReactApplicationContext().getApplicationContext().unregisterComponentCallbacks(memoryCallbacks); + mainHandler.removeCallbacksAndMessages(null); + reducingMemoryUsage = false; super.invalidate(); } @@ -72,6 +80,63 @@ public void onHostDestroy() {} @DoNotStrip private native void flushPipelineCaches(); + private static final int MEMORY_PASSES = 4; + private static final long MEMORY_PASS_DELAY_MS = 250; + + private final Handler mainHandler = new Handler(Looper.getMainLooper()); + // Main thread only. + private boolean reducingMemoryUsage = false; + + /** + * The system asks the app to give back memory (see + * GPUDevice::reduceMemoryUsage): once its UI is hidden, which is the app + * going to the background (not a pause that a dialog or a focus change in + * multi-window also brings, after which the app is straight back), and + * when memory runs low. The levels below UI_HIDDEN come while the app is + * in the foreground, rendering: what a trim gave back would only be + * allocated again. + */ + private final ComponentCallbacks2 memoryCallbacks = new ComponentCallbacks2() { + @Override + public void onTrimMemory(int level) { + if (level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { + reduceMemoryUsage(); + } + } + + @Override + public void onLowMemory() { + reduceMemoryUsage(); + } + + @Override + public void onConfigurationChanged(Configuration configuration) {} + }; + + /** + * Has Dawn free the memory it keeps but does not need, then again while + * some of it waits on GPU work in flight, as Chrome does, a few times at + * most (see GPUDevice::reduceMemoryUsage). Main thread. + */ + private void reduceMemoryUsage() { + if (reducingMemoryUsage) { + return; + } + reducingMemoryUsage = true; + reduceMemoryUsagePass(MEMORY_PASSES); + } + + private void reduceMemoryUsagePass(int passesLeft) { + if (reduceMemoryUsageNative() && passesLeft > 1) { + mainHandler.postDelayed(() -> reduceMemoryUsagePass(passesLeft - 1), MEMORY_PASS_DELAY_MS); + return; + } + reducingMemoryUsage = false; + } + + @DoNotStrip + private static native boolean reduceMemoryUsageNative(); + /** * 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..1a4c5a9fab 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" +#include "GPUDevice.h" #import "RNWGUIKit.h" #import @@ -22,6 +23,53 @@ @interface RCTBridge (JSIRuntime) - (void *)runtime; @end +#if !TARGET_OS_OSX +// Has Dawn free the memory it keeps but does not need (see +// GPUDevice::reduceMemoryUsage), then again while some of it waits on GPU work +// in flight, as Chrome does, a few times at most. Main thread. +static bool reducingDawnMemoryUsage = false; + +static void reduceDawnMemoryUsagePass(int passesLeft) { + if (rnwgpu::GPUDevice::reduceMemoryUsage() && passesLeft > 1) { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 250 * NSEC_PER_MSEC), + dispatch_get_main_queue(), ^{ + reduceDawnMemoryUsagePass(passesLeft - 1); + }); + return; + } + reducingDawnMemoryUsage = false; +} + +static void reduceDawnMemoryUsage() { + if (reducingDawnMemoryUsage) { + return; + } + reducingDawnMemoryUsage = true; + reduceDawnMemoryUsagePass(4); +} + +// A memory warning, and the move to the background, where iOS kills the apps +// that hold the most memory first: the moments Flutter and Chrome give back +// the GPU memory they can. +static void observeMemoryPressure() { + static dispatch_once_t once; + dispatch_once(&once, ^{ + NSNotificationCenter *center = NSNotificationCenter.defaultCenter; + for (NSNotificationName name in @[ + UIApplicationDidReceiveMemoryWarningNotification, + UIApplicationDidEnterBackgroundNotification + ]) { + [center addObserverForName:name + object:nil + queue:NSOperationQueue.mainQueue + usingBlock:^(NSNotification *) { + reduceDawnMemoryUsage(); + }]; + } + }); +} +#endif + @implementation WebGPUModule RCT_EXPORT_MODULE(WebGPUModule) @@ -151,6 +199,9 @@ - (void)invalidate { } webgpuManager = std::make_shared(runtime, jsInvoker, platformContext); +#if !TARGET_OS_OSX + observeMemoryPressure(); +#endif return @true; } diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp index f4464b1182..1c1218fe4f 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp @@ -118,42 +118,58 @@ 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; + // A wrapper on its way out (its last reference gone, its destructor about + // to unregister it) has nothing left to do; an imported device is its + // owner's to look after. + if (device->_origin == Origin::Imported || + device->weak_from_this().expired()) { + continue; + } + devices.push_back({device->_instance, device->_pipelineCacheOutgrown, + device->_async, device->weak_from_this()}); + } + return devices; +} + +bool GPUDevice::reduceMemoryUsage() { + bool pending = false; + for (const auto &live : liveDevices()) { + // As in flushPipelineCaches: Dawn's wrapper takes the lock of a device + // that synchronizes itself, so this thread trims it at once. + if (live.device.HasFeature( + wgpu::FeatureName::ImplicitDeviceSynchronization)) { + pending |= dawn::native::ReduceMemoryUsage(live.device.Get()); + continue; + } + if (!live.async) { + continue; } + // Held weakly, as in flushPipelineCaches: a runtime that polls its + // mailbox may hold the job a long time, and the job must not keep the + // device alive meanwhile. + live.async->post([weak = live.wrapper](jsi::Runtime &) { + if (auto device = weak.lock()) { + dawn::native::ReduceMemoryUsage(device->_instance.Get()); + } + }); } - for (const auto &flush : flushes) { + return pending; +} + +void GPUDevice::flushPipelineCaches() { + for (const auto &flush : 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); + flushDawnPipelineCache(flush.device, *flush.pipelineCacheOutgrown); continue; } if (!flush.async) { diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h index 734f15adbf..cce2232b78 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h +++ b/packages/webgpu/cpp/rnwgpu/api/GPUDevice.h @@ -323,9 +323,37 @@ class GPUDevice : public NativeObject { // the last moment to write before the process may be killed. static void flushPipelineCaches(); + // Has Dawn free, on every live device, the memory it keeps but does not need + // (dawn::native::ReduceMemoryUsage): its staging ring buffers, scratch and + // temporary uniform buffers and trimmed caches, and on Vulkan the device + // memory it recycles and its framebuffer cache. Like flushPipelineCaches(), + // here when the device synchronizes itself, else on the thread of its + // runtime. Any thread: the platform modules call it when the system warns of + // low memory and when the app goes to the background. Returns true when a + // device trimmed here still has memory that waits on GPU work in flight, + // which a call after a short delay frees; a device trimmed on its runtime's + // thread is not counted. On Vulkan the answer stays true: to free what + // waits, Dawn submits, and that submit leaves something of its own to wait + // on. Callers repeat a few times at most. + static bool reduceMemoryUsage(); + private: friend class GPUAdapter; + // What a pass over the live devices 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) could be its last, and a wrapper, with its JSI members, must + // only go on its runtime's thread. Imported devices, whose owner looks + // after them, are left out, as are wrappers on their way out. + struct LiveDevice { + wgpu::Device device; + std::shared_ptr> pipelineCacheOutgrown; + std::shared_ptr async; + std::weak_ptr wrapper; + }; + static std::vector liveDevices(); + // Runs the uncapturederror listeners on the creation runtime's JS thread. // Invoked from notifyUncapturedError through the runtime's context. void deliverUncapturedError(wgpu::ErrorType type, std::string message); diff --git a/packages/webgpu/src/__tests__/MemoryTrim.spec.ts b/packages/webgpu/src/__tests__/MemoryTrim.spec.ts new file mode 100644 index 0000000000..4dec13ccfe --- /dev/null +++ b/packages/webgpu/src/__tests__/MemoryTrim.spec.ts @@ -0,0 +1,99 @@ +import { execFile } from "child_process"; + +import { client } from "./setup"; + +// The example app's package and activity (apps/example/app.json). +const ANDROID_ACTIVITY = + "com.reactnativewebgpu.example/com.microsoft.reacttestapp.MainActivity"; + +const adb = (...args: string[]) => + new Promise((resolve, reject) => { + execFile("adb", args, (error) => (error ? reject(error) : resolve())); + }); + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +// Sends the example app to the background and brings it back. Hiding its UI +// has Android ask it to give back memory (TRIM_MEMORY_UI_HIDDEN), and +// WebGPUModule then has Dawn trim every live device (see +// GPUDevice::reduceMemoryUsage) on the UI thread, in passes 250ms apart. +// `am send-trim-memory` would be more direct, but Android refuses a +// background level for a process in the foreground, which the app under test +// is. +const hideAndShowApp = async () => { + await adb("shell", "input", "keyevent", "KEYCODE_HOME"); + await wait(1500); + await adb("shell", "am", "start", "-n", ANDROID_ACTIVITY); +}; + +// Uploads through Dawn's staging ring buffers (writeBuffer) and reads the last +// upload back, for durationMs. Run while the UI thread trims the same device, +// it has the trim free those ring buffers under uploads still in flight. +const uploadAndReadBack = (durationMs: number) => + client.eval< + { durationMs: number }, + { rounds: number; mismatches: number; last: number[] } + >( + ({ device, durationMs: duration }) => { + const size = 1024 * 1024; + const target = device.createBuffer({ + size, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC, + }); + const readback = device.createBuffer({ + size: 16, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + }); + const data = new Uint32Array(size / 4); + const end = Date.now() + duration; + let rounds = 0; + let mismatches = 0; + let last: number[] = []; + const round = (): Promise => { + rounds++; + data.fill(rounds); + device.queue.writeBuffer(target, 0, data); + const encoder = device.createCommandEncoder(); + encoder.copyBufferToBuffer(target, size - 16, readback, 0, 16); + device.queue.submit([encoder.finish()]); + return readback.mapAsync(GPUMapMode.READ).then(() => { + last = Array.from(new Uint32Array(readback.getMappedRange())); + readback.unmap(); + if (last.some((value) => value !== rounds)) { + mismatches++; + } + return Date.now() < end ? round() : undefined; + }); + }; + return round().then(() => { + target.destroy(); + readback.destroy(); + return { rounds, mismatches, last }; + }); + }, + { durationMs }, + ); + +describe("Memory trim", () => { + it("keeps a device in use working while Android trims memory", async () => { + if (client.OS !== "android") { + return; + } + // Uploads before, during and after the trim's passes (about one second). + const uploads = uploadAndReadBack(3000); + await hideAndShowApp(); + const during = await uploads; + expect(during.rounds).toBeGreaterThan(1); + expect(during.mismatches).toBe(0); + expect(during.last).toEqual([ + during.rounds, + during.rounds, + during.rounds, + during.rounds, + ]); + + // Once the trim is over, the device still uploads and reads back. + const after = await uploadAndReadBack(0); + expect(after).toEqual({ rounds: 1, mismatches: 0, last: [1, 1, 1, 1] }); + }); +});