Skip to content

Commit d2930e0

Browse files
authored
feat(🧹): add purgeGpuResources(), and purge when the system is short of memory (#649)
1 parent 1136de8 commit d2930e0

15 files changed

Lines changed: 438 additions & 36 deletions

File tree

‎packages/webgpu/android/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ add_library(${PACKAGE_NAME} SHARED
5656
../cpp/rnwgpu/api/GPUComputePipeline.cpp
5757
../cpp/rnwgpu/api/GPUCanvasContext.cpp
5858
../cpp/rnwgpu/DawnBlobCache.cpp
59+
../cpp/rnwgpu/GpuPurge.cpp
5960
../cpp/rnwgpu/NativeBufferViewRegistry.cpp
6061
../cpp/rnwgpu/AnimationFrames.cpp
6162
../cpp/rnwgpu/RNWebGPUManager.cpp

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#include "DawnBlobCache.h"
2626
#include "GPUCanvasContext.h"
2727
#include "GPUDevice.h"
28+
#include "GpuPurge.h"
2829
#include "NativeBufferViewRegistry.h"
2930
#include "RNWebGPUManager.h"
3031
#include "WebGPURuntime.h"
@@ -70,6 +71,21 @@ Java_com_webgpu_WebGPUModule_flushPipelineCaches(JNIEnv * /* env */,
7071
rnwgpu::GPUDevice::flushPipelineCaches();
7172
}
7273

74+
// WebGPUModule's ComponentCallbacks2 (UI thread): what the system says about
75+
// memory, as it says it. GpuPurge decides what calls for a purge.
76+
extern "C" JNIEXPORT void JNICALL
77+
Java_com_webgpu_WebGPUModule_onLowMemoryNative(JNIEnv * /* env */,
78+
jclass /* clazz */) {
79+
rnwgpu::GpuPurge::onLowMemory();
80+
}
81+
82+
extern "C" JNIEXPORT void JNICALL
83+
Java_com_webgpu_WebGPUModule_onTrimMemoryNative(JNIEnv * /* env */,
84+
jclass /* clazz */,
85+
jint level) {
86+
rnwgpu::GpuPurge::onTrimMemory(level);
87+
}
88+
7389
// WebGPUModule.onHostResume and onHostPause (UI thread): animation frames
7490
// follow the host activity, resumed or not.
7591
extern "C" JNIEXPORT void JNICALL

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.webgpu;
22

3+
import android.content.ComponentCallbacks2;
4+
import android.content.res.Configuration;
35
import android.graphics.Bitmap;
46
import android.hardware.HardwareBuffer;
57
import android.os.Build;
@@ -34,18 +36,41 @@ public class WebGPUModule extends NativeWebGPUModuleSpec implements LifecycleEve
3436
System.loadLibrary("react-native-webgpu"); // Load the C++ library
3537
}
3638

39+
// What the system says about memory goes to the native side as it comes,
40+
// which decides when the GPU memory nothing uses goes back to the system
41+
// (see GpuPurge).
42+
private final ComponentCallbacks2 mComponentCallbacks =
43+
new ComponentCallbacks2() {
44+
@Override
45+
public void onConfigurationChanged(Configuration newConfig) {}
46+
47+
@Override
48+
public void onLowMemory() {
49+
onLowMemoryNative();
50+
}
51+
52+
@Override
53+
public void onTrimMemory(int level) {
54+
onTrimMemoryNative(level);
55+
}
56+
};
57+
3758
public WebGPUModule(ReactApplicationContext reactContext) {
3859
super(reactContext);
3960
// Initialize the C++ module
4061
initialize();
4162
// Animation frames follow the host activity: resumed, or not.
4263
setForegroundNative(reactContext.getLifecycleState() == LifecycleState.RESUMED);
4364
reactContext.addLifecycleEventListener(this);
65+
reactContext.getApplicationContext().registerComponentCallbacks(mComponentCallbacks);
4466
}
4567

4668
@Override
4769
public void invalidate() {
4870
getReactApplicationContext().removeLifecycleEventListener(this);
71+
getReactApplicationContext()
72+
.getApplicationContext()
73+
.unregisterComponentCallbacks(mComponentCallbacks);
4974
super.invalidate();
5075
}
5176

@@ -72,6 +97,12 @@ public void onHostDestroy() {}
7297
@DoNotStrip
7398
private native void flushPipelineCaches();
7499

100+
@DoNotStrip
101+
private static native void onLowMemoryNative();
102+
103+
@DoNotStrip
104+
private static native void onTrimMemoryNative(int level);
105+
75106
/**
76107
* Whether the app is in the foreground: the host activity is resumed (see
77108
* AnimationFrameDispatcher::setForeground). An AChoreographer sends its

‎packages/webgpu/apple/WebGPUModule.mm‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include "ApplePlatformContext.h"
33
#include "DawnBlobCache.h"
44
#import "GPUCanvasContext.h"
5+
#include "GpuPurge.h"
56
#import "RNWGUIKit.h"
67

78
#import <React/RCTBridge+Private.h>
@@ -22,6 +23,24 @@ @interface RCTBridge (JSIRuntime)
2223
- (void *)runtime;
2324
@end
2425

26+
#if !TARGET_OS_OSX
27+
// A memory warning goes to the native side as it comes, which decides when the
28+
// GPU memory nothing uses goes back to the system (see GpuPurge). Once for the
29+
// process: devices outlive a React reload.
30+
static void observeMemoryWarnings() {
31+
static dispatch_once_t once;
32+
dispatch_once(&once, ^{
33+
[[NSNotificationCenter defaultCenter]
34+
addObserverForName:UIApplicationDidReceiveMemoryWarningNotification
35+
object:nil
36+
queue:nil
37+
usingBlock:^(NSNotification *) {
38+
rnwgpu::GpuPurge::onMemoryWarning();
39+
}];
40+
});
41+
}
42+
#endif
43+
2544
@implementation WebGPUModule
2645

2746
RCT_EXPORT_MODULE(WebGPUModule)
@@ -149,6 +168,9 @@ - (void)invalidate {
149168
rnwgpu::DawnBlobCache::setDirectory(
150169
[caches stringByAppendingPathComponent:@"webgpu-dawn"].UTF8String);
151170
}
171+
#if !TARGET_OS_OSX
172+
observeMemoryWarnings();
173+
#endif
152174
webgpuManager = std::make_shared<rnwgpu::RNWebGPUManager>(runtime, jsInvoker,
153175
platformContext);
154176
return @true;
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#include "GpuPurge.h"
2+
3+
#include <mutex>
4+
#include <system_error>
5+
#include <thread>
6+
7+
#include "GPUDevice.h"
8+
9+
namespace rnwgpu {
10+
11+
namespace {
12+
13+
struct State {
14+
std::mutex mutex;
15+
// Whether the purge thread is alive.
16+
bool running = false;
17+
// Whether a request came in since the thread last started a run.
18+
bool requested = false;
19+
};
20+
21+
// Never destroyed: the purge thread may still use it while the process exits.
22+
State &getState() noexcept {
23+
static auto *state = new State();
24+
return *state;
25+
}
26+
27+
} // namespace
28+
29+
void GpuPurge::request() noexcept {
30+
auto &state = getState();
31+
{
32+
std::lock_guard<std::mutex> lock(state.mutex);
33+
state.requested = true;
34+
if (state.running) {
35+
return;
36+
}
37+
state.running = true;
38+
}
39+
try {
40+
std::thread([] { runRequests(); }).detach();
41+
} catch (const std::system_error &) {
42+
// No thread to be had: nothing is purged.
43+
std::lock_guard<std::mutex> lock(state.mutex);
44+
state.running = false;
45+
}
46+
}
47+
48+
void GpuPurge::onMemoryWarning() noexcept { request(); }
49+
50+
void GpuPurge::onLowMemory() noexcept { request(); }
51+
52+
void GpuPurge::onTrimMemory(int level) noexcept {
53+
if (level >= kTrimMemoryUiHidden) {
54+
request();
55+
}
56+
}
57+
58+
void GpuPurge::runRequests() noexcept {
59+
auto &state = getState();
60+
for (;;) {
61+
{
62+
std::lock_guard<std::mutex> lock(state.mutex);
63+
if (!state.requested) {
64+
state.running = false;
65+
return;
66+
}
67+
state.requested = false;
68+
}
69+
run();
70+
}
71+
}
72+
73+
void GpuPurge::run() {
74+
for (int pass = 0; pass < kMaxPasses; pass++) {
75+
bool pending = GPUDevice::reduceMemoryUsage();
76+
if (pass < kRuntimeThreadPasses) {
77+
pending |= GPUDevice::reduceMemoryUsageOnRuntimeThreads();
78+
}
79+
if (!pending) {
80+
return;
81+
}
82+
std::this_thread::sleep_for(kPassInterval);
83+
}
84+
}
85+
86+
} // namespace rnwgpu
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#pragma once
2+
3+
#include <chrono>
4+
5+
namespace rnwgpu {
6+
7+
// purgeGpuResources(), which the system also brings about when it is short of
8+
// memory and, on Android, when the app goes to the background: Dawn gives the
9+
// GPU memory it keeps for reuse (the memory of destroyed textures and buffers,
10+
// staging memory) back to the system, for every live device (see
11+
// GPUDevice::reduceMemoryUsage). Nothing alive is affected.
12+
//
13+
// The platform modules only report what the system said (onMemoryWarning,
14+
// onLowMemory, onTrimMemory): whether it calls for a purge is decided here.
15+
//
16+
// request() returns at once. The work runs on a thread of its own, started by
17+
// a request and gone once done; a request made while it runs is served by one
18+
// more run of the same thread, however many came in.
19+
class GpuPurge {
20+
public:
21+
// purgeGpuResources() from JS. Any thread.
22+
static void request() noexcept;
23+
24+
// iOS, UIApplicationDidReceiveMemoryWarningNotification: the system is short
25+
// of memory, and ends the apps that hold the most of it first. Any thread.
26+
static void onMemoryWarning() noexcept;
27+
28+
// Android, ComponentCallbacks.onLowMemory(): the whole system is short of
29+
// memory. Any thread.
30+
static void onLowMemory() noexcept;
31+
32+
// Android, ComponentCallbacks2.onTrimMemory(): purges from
33+
// kTrimMemoryUiHidden, which is each time the app goes to the background.
34+
// Any thread.
35+
static void onTrimMemory(int level) noexcept;
36+
37+
private:
38+
// One run asks Dawn again for as long as it says deletions wait for
39+
// submitted work to complete, this many times at most and this far apart:
40+
// about a second in all.
41+
static constexpr int kMaxPasses = 10;
42+
static constexpr std::chrono::milliseconds kPassInterval{100};
43+
44+
// The passes of a run that also ask the devices only the thread of their
45+
// runtime may use (see GPUDevice::reduceMemoryUsageOnRuntimeThreads). What
46+
// Dawn answers there is not waited for, hence a fixed number: the first lets
47+
// the pending deletions go through, the next free what they leave.
48+
static constexpr int kRuntimeThreadPasses = 3;
49+
50+
// ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN: the app is no longer visible. It
51+
// renders nothing there, and the system ends the processes in the background
52+
// that hold the most memory first. The system sends it each time the app
53+
// leaves the foreground, and it may be all it sends: TRIM_MEMORY_BACKGROUND
54+
// did not come to an app left in the background until it was cached and
55+
// frozen (a Samsung on Android 17). The levels below this one are for an app
56+
// in the foreground, and are no longer sent since Android 14.
57+
static constexpr int kTrimMemoryUiHidden = 20;
58+
59+
// The purge thread: runs until no request is left.
60+
static void runRequests() noexcept;
61+
62+
// One run: the passes over the live devices.
63+
static void run();
64+
};
65+
66+
} // namespace rnwgpu

0 commit comments

Comments
 (0)