| 274 | } |
| 275 | |
| 276 | Status Invoke(TfLiteContext* context) { |
| 277 | const EGLContext egl_context_at_delegate_init = env_->context().context(); |
| 278 | const EGLContext egl_context_at_delegate_invoke = eglGetCurrentContext(); |
| 279 | if (egl_context_at_delegate_init != egl_context_at_delegate_invoke) { |
| 280 | return FailedPreconditionError( |
| 281 | "Delegate should run on the same thread where it was initialized."); |
| 282 | } |
| 283 | |
| 284 | // Push input data from a tensor to GPU. |
| 285 | for (ValueId id : inputs_) { |
| 286 | const ValueRef& ref = tensors_[id]; |
| 287 | auto external_object = bhwc_objects_.FindBuffer(ref.tensor_index); |
| 288 | if (external_object) { |
| 289 | // Use input from GPU. |
| 290 | // Conversion is needed only when external object is not phwc4. |
| 291 | if (!IsPHWC4(tensors_[id].shape)) { |
| 292 | RETURN_IF_ERROR(bhwc_to_phwc4_.Convert( |
| 293 | ref.shape, *external_object, command_queue_.get(), |
| 294 | phwc4_objects_.FindBuffer(id))); |
| 295 | } |
| 296 | } else { |
| 297 | // Copy from CPU to GPU |
| 298 | TfLiteTensor& tensor = context->tensors[ref.tensor_index]; |
| 299 | RETURN_IF_ERROR(CopyToBufferHandle(id, &tensor)); |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | // Run inference. |
| 304 | RETURN_IF_ERROR(inference_context_->Reset()); |
| 305 | RETURN_IF_ERROR(inference_context_->Execute()); |
| 306 | |
| 307 | // Push output data from GPU to a tensor. |
| 308 | bool finished_gpu_processing = false; |
| 309 | for (ValueId id : outputs_) { |
| 310 | const ValueRef& ref = tensors_[id]; |
| 311 | auto external_object = bhwc_objects_.FindBuffer(ref.tensor_index); |
| 312 | if (external_object) { |
| 313 | // Convert data from PHWC4 to BHWC and leave it in GPU object. |
| 314 | // Conversion is needed only when external object is not phwc4. |
| 315 | if (!IsPHWC4(tensors_[id].shape)) { |
| 316 | RETURN_IF_ERROR( |
| 317 | phwc4_to_bhwc_.Convert(ref.shape, *phwc4_objects_.FindBuffer(id), |
| 318 | command_queue_.get(), external_object)); |
| 319 | } |
| 320 | } else { |
| 321 | // Wait until all GPU command are completed. This call leads to a lower |
| 322 | // processing latency because a buffer reading below will not stall if |
| 323 | // data is not yet ready. |
| 324 | if (!finished_gpu_processing) { |
| 325 | RETURN_IF_ERROR(command_queue_->WaitForCompletion()); |
| 326 | finished_gpu_processing = true; |
| 327 | } |
| 328 | // Copy from GPU to CPU. |
| 329 | TfLiteTensor& tensor = context->tensors[ref.tensor_index]; |
| 330 | RETURN_IF_ERROR(CopyFromBufferHandle(id, &tensor)); |
| 331 | } |
| 332 | } |
| 333 | return OkStatus(); |
no test coverage detected