Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/webgpu/android/cpp/cpp-adapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
65 changes: 65 additions & 0 deletions packages/webgpu/android/src/main/java/com/webgpu/WebGPUModule.java
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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();
}

Expand All @@ -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
Expand Down
51 changes: 51 additions & 0 deletions packages/webgpu/apple/WebGPUModule.mm
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "ApplePlatformContext.h"
#include "DawnBlobCache.h"
#import "GPUCanvasContext.h"
#include "GPUDevice.h"
#import "RNWGUIKit.h"

#import <React/RCTBridge+Private.h>
Expand All @@ -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)
Expand Down Expand Up @@ -151,6 +199,9 @@ - (void)invalidate {
}
webgpuManager = std::make_shared<rnwgpu::RNWebGPUManager>(runtime, jsInvoker,
platformContext);
#if !TARGET_OS_OSX
observeMemoryPressure();
#endif
return @true;
}

Expand Down
72 changes: 44 additions & 28 deletions packages/webgpu/cpp/rnwgpu/api/GPUDevice.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::atomic<bool>> outgrown;
std::shared_ptr<async::RuntimeContext> async;
std::weak_ptr<GPUDevice> wrapper;
};
std::vector<Flush> flushes;
{
std::lock_guard<std::mutex> 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::LiveDevice> GPUDevice::liveDevices() {
std::vector<LiveDevice> devices;
std::lock_guard<std::mutex> 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) {
Expand Down
28 changes: 28 additions & 0 deletions packages/webgpu/cpp/rnwgpu/api/GPUDevice.h
Original file line number Diff line number Diff line change
Expand Up @@ -323,9 +323,37 @@ class GPUDevice : public NativeObject<GPUDevice> {
// 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<std::atomic<bool>> pipelineCacheOutgrown;
std::shared_ptr<async::RuntimeContext> async;
std::weak_ptr<GPUDevice> wrapper;
};
static std::vector<LiveDevice> 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);
Expand Down
Loading