1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
|
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/ml/webnn/ml_tensor.h"
#include "base/metrics/histogram_functions.h"
#include "base/types/expected.h"
#include "base/types/expected_macros.h"
#include "services/webnn/public/cpp/ml_tensor_usage.h"
#include "services/webnn/public/cpp/operand_descriptor.h"
#include "services/webnn/public/mojom/webnn_tensor.mojom-blink.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_tensor_descriptor.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/modules/ml/ml_context.h"
#include "third_party/blink/renderer/modules/ml/webnn/ml_error.h"
#include "third_party/blink/renderer/modules/ml/webnn/ml_graph_utils.h"
namespace blink {
namespace {
void RecordReadTensorTime(base::ElapsedTimer read_tensor_timer) {
base::UmaHistogramMediumTimes("WebNN.MLTensor.TimingMs.Read",
read_tensor_timer.Elapsed());
}
} // namespace
MLTensor::MLTensor(
ExecutionContext* execution_context,
MLContext* context,
webnn::OperandDescriptor descriptor,
webnn::MLTensorUsage usage,
webnn::mojom::blink::CreateTensorSuccessPtr create_tensor_success,
base::PassKey<MLContext> /*pass_key*/)
: ml_context_(context),
descriptor_(std::move(descriptor)),
usage_(usage),
webnn_handle_(std::move(create_tensor_success->tensor_handle)),
remote_tensor_(execution_context) {
remote_tensor_.Bind(
std::move(create_tensor_success->tensor_remote),
execution_context->GetTaskRunner(TaskType::kMachineLearning));
remote_tensor_.set_disconnect_handler(
WTF::BindOnce(&MLTensor::OnConnectionError, WrapWeakPersistent(this)));
}
MLTensor::~MLTensor() = default;
void MLTensor::Trace(Visitor* visitor) const {
visitor->Trace(ml_context_);
visitor->Trace(remote_tensor_);
visitor->Trace(pending_resolvers_);
visitor->Trace(pending_byob_resolvers_);
ScriptWrappable::Trace(visitor);
}
V8MLOperandDataType MLTensor::dataType() const {
return ToBlinkDataType(descriptor_.data_type());
}
Vector<uint32_t> MLTensor::shape() const {
return Vector<uint32_t>(descriptor_.shape());
}
bool MLTensor::exportableToGPU() const {
return usage_.Has(webnn::MLTensorUsageFlags::kWebGpuInterop);
}
bool MLTensor::readable() const {
return usage_.Has(webnn::MLTensorUsageFlags::kRead);
}
bool MLTensor::writable() const {
return usage_.Has(webnn::MLTensorUsageFlags::kWrite);
}
bool MLTensor::constant() const {
return usage_.Has(webnn::MLTensorUsageFlags::kGraphConstant);
}
void MLTensor::destroy() {
// Calling OnConnectionError() will disconnect and destroy the tensor in
// the service. The remote tensor must remain unbound after calling
// OnConnectionError() because it is valid to call destroy() multiple times.
OnConnectionError();
}
const webnn::OperandDescriptor& MLTensor::Descriptor() const {
return descriptor_;
}
webnn::OperandDataType MLTensor::DataType() const {
return descriptor_.data_type();
}
const std::vector<uint32_t>& MLTensor::Shape() const {
return descriptor_.shape();
}
const webnn::MLTensorUsage& MLTensor::Usage() const {
return usage_;
}
uint64_t MLTensor::PackedByteLength() const {
return descriptor_.PackedByteLength();
}
ScriptPromise<DOMArrayBuffer> MLTensor::ReadTensorImpl(
webnn::ScopedTrace scoped_trace,
ScriptState* script_state,
ExceptionState& exception_state) {
// Remote context gets automatically unbound when the execution context
// destructs.
if (!remote_tensor_.is_bound()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"Tensor has been destroyed or context is lost.");
return EmptyPromise();
}
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver<DOMArrayBuffer>>(
script_state, exception_state.GetContext());
pending_resolvers_.insert(resolver);
base::ElapsedTimer read_tensor_timer;
remote_tensor_->ReadTensor(WTF::BindOnce(
&MLTensor::OnDidReadTensor, WrapPersistent(this), std::move(scoped_trace),
WrapPersistent(resolver), std::move(read_tensor_timer)));
return resolver->Promise();
}
ScriptPromise<IDLUndefined> MLTensor::ReadTensorImpl(
webnn::ScopedTrace scoped_trace,
ScriptState* script_state,
AllowSharedBufferSource* dst_data,
ExceptionState& exception_state) {
// Remote context gets automatically unbound when the execution context
// destructs.
if (!remote_tensor_.is_bound()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Invalid tensor state");
return EmptyPromise();
}
base::span<uint8_t> bytes = AsByteSpan(*dst_data);
if (bytes.size() < PackedByteLength()) {
exception_state.ThrowTypeError("The destination tensor is too small.");
return EmptyPromise();
}
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver<IDLUndefined>>(
script_state, exception_state.GetContext());
pending_byob_resolvers_.insert(resolver);
base::ElapsedTimer read_tensor_timer;
remote_tensor_->ReadTensor(
WTF::BindOnce(&MLTensor::OnDidReadTensorByob, WrapPersistent(this),
std::move(scoped_trace), WrapPersistent(resolver),
WrapPersistent(dst_data), std::move(read_tensor_timer)));
return resolver->Promise();
}
void MLTensor::OnDidReadTensor(
webnn::ScopedTrace scoped_trace,
ScriptPromiseResolver<DOMArrayBuffer>* resolver,
base::ElapsedTimer read_tensor_timer,
webnn::mojom::blink::ReadTensorResultPtr result) {
pending_resolvers_.erase(resolver);
if (result->is_error()) {
const webnn::mojom::blink::Error& read_tensor_error = *result->get_error();
resolver->RejectWithDOMException(
WebNNErrorCodeToDOMExceptionCode(read_tensor_error.code),
read_tensor_error.message);
return;
}
CHECK_EQ(result->get_buffer().size(), descriptor_.PackedByteLength());
resolver->Resolve(DOMArrayBuffer::Create(result->get_buffer()));
RecordReadTensorTime(std::move(read_tensor_timer));
}
void MLTensor::OnDidReadTensorByob(
webnn::ScopedTrace scoped_trace,
ScriptPromiseResolver<IDLUndefined>* resolver,
AllowSharedBufferSource* dst_data,
base::ElapsedTimer read_tensor_timer,
webnn::mojom::blink::ReadTensorResultPtr result) {
pending_byob_resolvers_.erase(resolver);
if (result->is_error()) {
const webnn::mojom::blink::Error& read_tensor_error = *result->get_error();
resolver->RejectWithDOMException(
WebNNErrorCodeToDOMExceptionCode(read_tensor_error.code),
read_tensor_error.message);
return;
}
base::span<uint8_t> bytes = AsByteSpan(*dst_data);
if (bytes.size() == 0) {
resolver->RejectWithTypeError("Buffer was detached.");
return;
}
CHECK_EQ(result->get_buffer().size(), descriptor_.PackedByteLength());
// It is safe to write into `dst_data` even though it was not transferred
// because this method is called in a task which runs on same thread where
// script executes, so script can't observe a partially written state (unless
// `dst_data` is a SharedArrayBuffer).
bytes.copy_prefix_from(result->get_buffer());
resolver->Resolve();
RecordReadTensorTime(std::move(read_tensor_timer));
}
void MLTensor::WriteTensorImpl(base::span<const uint8_t> src_data,
ExceptionState& exception_state) {
// Remote context gets automatically unbound when the execution context
// destructs.
if (!remote_tensor_.is_bound()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"Tensor has been destroyed or context is lost.");
return;
}
// Return early since empty written data can be ignored with no observable
// effect.
if (src_data.size() == 0) {
return;
}
// Copy src data.
remote_tensor_->WriteTensor(src_data);
}
void MLTensor::OnConnectionError() {
remote_tensor_.reset();
for (const auto& resolver : pending_resolvers_) {
resolver->RejectWithDOMException(
DOMExceptionCode::kInvalidStateError,
"Tensor has been destroyed or context is lost.");
}
pending_resolvers_.clear();
for (const auto& resolver : pending_byob_resolvers_) {
resolver->RejectWithDOMException(
DOMExceptionCode::kInvalidStateError,
"Tensor has been destroyed or context is lost.");
}
pending_byob_resolvers_.clear();
}
} // namespace blink
|