diff options
author | Haamed Gheibi <haamed@google.com> | 2022-02-04 13:47:26 -0800 |
---|---|---|
committer | Haamed Gheibi <haamed@google.com> | 2022-02-04 13:55:47 -0800 |
commit | f99b35c293439db0b7436b47b939eb8c7bf21b51 (patch) | |
tree | 6cd9b0719554809447c845616317cca5409b93ae /neuralnetworks | |
parent | a028272dee9220e6810cbdcfb2328c34f8afe4c2 (diff) | |
parent | 332dead340bb196c6ba3f6978e8fb53966c74bf7 (diff) |
Merge TP1A.220120.003
Change-Id: Ie5eba313ee102e452f5f96942ed2f3a7bb4e8f01
Diffstat (limited to 'neuralnetworks')
96 files changed, 4641 insertions, 461 deletions
diff --git a/neuralnetworks/aidl/Android.bp b/neuralnetworks/aidl/Android.bp index cbb6ce5163..47f3b30280 100644 --- a/neuralnetworks/aidl/Android.bp +++ b/neuralnetworks/aidl/Android.bp @@ -38,5 +38,6 @@ aidl_interface { versions: [ "1", "2", + "3", ], } diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/.hash b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/.hash new file mode 100644 index 0000000000..3b9f018381 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/.hash @@ -0,0 +1 @@ +8c2c4ca2327e6f779dad6119c03d832ea4e1def1 diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/BufferDesc.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/BufferDesc.aidl new file mode 100644 index 0000000000..05cec76c88 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/BufferDesc.aidl @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable BufferDesc { + int[] dimensions; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/BufferRole.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/BufferRole.aidl new file mode 100644 index 0000000000..10a6b75ac7 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/BufferRole.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable BufferRole { + int modelIndex; + int ioIndex; + float probability; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Capabilities.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Capabilities.aidl new file mode 100644 index 0000000000..30877c0294 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Capabilities.aidl @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable Capabilities { + android.hardware.neuralnetworks.PerformanceInfo relaxedFloat32toFloat16PerformanceScalar; + android.hardware.neuralnetworks.PerformanceInfo relaxedFloat32toFloat16PerformanceTensor; + android.hardware.neuralnetworks.OperandPerformance[] operandPerformance; + android.hardware.neuralnetworks.PerformanceInfo ifPerformance; + android.hardware.neuralnetworks.PerformanceInfo whilePerformance; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/DataLocation.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/DataLocation.aidl new file mode 100644 index 0000000000..db49a38979 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/DataLocation.aidl @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable DataLocation { + int poolIndex; + long offset; + long length; + long padding; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/DeviceBuffer.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/DeviceBuffer.aidl new file mode 100644 index 0000000000..7cdd6db742 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/DeviceBuffer.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable DeviceBuffer { + android.hardware.neuralnetworks.IBuffer buffer; + int token; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/DeviceType.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/DeviceType.aidl new file mode 100644 index 0000000000..82fe8ae3e7 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/DeviceType.aidl @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@Backing(type="int") @VintfStability +enum DeviceType { + OTHER = 1, + CPU = 2, + GPU = 3, + ACCELERATOR = 4, +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ErrorStatus.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ErrorStatus.aidl new file mode 100644 index 0000000000..57d5d6e4cd --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ErrorStatus.aidl @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@Backing(type="int") @VintfStability +enum ErrorStatus { + NONE = 0, + DEVICE_UNAVAILABLE = 1, + GENERAL_FAILURE = 2, + OUTPUT_INSUFFICIENT_SIZE = 3, + INVALID_ARGUMENT = 4, + MISSED_DEADLINE_TRANSIENT = 5, + MISSED_DEADLINE_PERSISTENT = 6, + RESOURCE_EXHAUSTED_TRANSIENT = 7, + RESOURCE_EXHAUSTED_PERSISTENT = 8, +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExecutionPreference.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExecutionPreference.aidl new file mode 100644 index 0000000000..4352d8f334 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExecutionPreference.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@Backing(type="int") @VintfStability +enum ExecutionPreference { + LOW_POWER = 0, + FAST_SINGLE_ANSWER = 1, + SUSTAINED_SPEED = 2, +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExecutionResult.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExecutionResult.aidl new file mode 100644 index 0000000000..44e9922f52 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExecutionResult.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable ExecutionResult { + boolean outputSufficientSize; + android.hardware.neuralnetworks.OutputShape[] outputShapes; + android.hardware.neuralnetworks.Timing timing; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Extension.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Extension.aidl new file mode 100644 index 0000000000..c47028d99f --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Extension.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable Extension { + String name; + android.hardware.neuralnetworks.ExtensionOperandTypeInformation[] operandTypes; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExtensionNameAndPrefix.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExtensionNameAndPrefix.aidl new file mode 100644 index 0000000000..6c287fd460 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExtensionNameAndPrefix.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable ExtensionNameAndPrefix { + String name; + char prefix; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExtensionOperandTypeInformation.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExtensionOperandTypeInformation.aidl new file mode 100644 index 0000000000..a3680aa9dd --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/ExtensionOperandTypeInformation.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable ExtensionOperandTypeInformation { + char type; + boolean isTensor; + int byteSize; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/FencedExecutionResult.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/FencedExecutionResult.aidl new file mode 100644 index 0000000000..7952b34632 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/FencedExecutionResult.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable FencedExecutionResult { + android.hardware.neuralnetworks.IFencedExecutionCallback callback; + @nullable ParcelFileDescriptor syncFence; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/FusedActivationFunc.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/FusedActivationFunc.aidl new file mode 100644 index 0000000000..7e61bbbdb1 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/FusedActivationFunc.aidl @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@Backing(type="int") @VintfStability +enum FusedActivationFunc { + NONE = 0, + RELU = 1, + RELU1 = 2, + RELU6 = 3, +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IBuffer.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IBuffer.aidl new file mode 100644 index 0000000000..f10e7e24ca --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IBuffer.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +interface IBuffer { + void copyFrom(in android.hardware.neuralnetworks.Memory src, in int[] dimensions); + void copyTo(in android.hardware.neuralnetworks.Memory dst); +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IBurst.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IBurst.aidl new file mode 100644 index 0000000000..eb3d0b004a --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IBurst.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +interface IBurst { + android.hardware.neuralnetworks.ExecutionResult executeSynchronously(in android.hardware.neuralnetworks.Request request, in long[] memoryIdentifierTokens, in boolean measureTiming, in long deadlineNs, in long loopTimeoutDurationNs); + void releaseMemoryResource(in long memoryIdentifierToken); +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IDevice.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IDevice.aidl new file mode 100644 index 0000000000..c9c67f2fcd --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IDevice.aidl @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +interface IDevice { + android.hardware.neuralnetworks.DeviceBuffer allocate(in android.hardware.neuralnetworks.BufferDesc desc, in android.hardware.neuralnetworks.IPreparedModelParcel[] preparedModels, in android.hardware.neuralnetworks.BufferRole[] inputRoles, in android.hardware.neuralnetworks.BufferRole[] outputRoles); + android.hardware.neuralnetworks.Capabilities getCapabilities(); + android.hardware.neuralnetworks.NumberOfCacheFiles getNumberOfCacheFilesNeeded(); + android.hardware.neuralnetworks.Extension[] getSupportedExtensions(); + boolean[] getSupportedOperations(in android.hardware.neuralnetworks.Model model); + android.hardware.neuralnetworks.DeviceType getType(); + String getVersionString(); + void prepareModel(in android.hardware.neuralnetworks.Model model, in android.hardware.neuralnetworks.ExecutionPreference preference, in android.hardware.neuralnetworks.Priority priority, in long deadlineNs, in ParcelFileDescriptor[] modelCache, in ParcelFileDescriptor[] dataCache, in byte[] token, in android.hardware.neuralnetworks.IPreparedModelCallback callback); + void prepareModelFromCache(in long deadlineNs, in ParcelFileDescriptor[] modelCache, in ParcelFileDescriptor[] dataCache, in byte[] token, in android.hardware.neuralnetworks.IPreparedModelCallback callback); + const int BYTE_SIZE_OF_CACHE_TOKEN = 32; + const int MAX_NUMBER_OF_CACHE_FILES = 32; + const int EXTENSION_TYPE_HIGH_BITS_PREFIX = 15; + const int EXTENSION_TYPE_LOW_BITS_TYPE = 16; + const int OPERAND_TYPE_BASE_MAX = 65535; + const int OPERATION_TYPE_BASE_MAX = 65535; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IFencedExecutionCallback.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IFencedExecutionCallback.aidl new file mode 100644 index 0000000000..0bfb80ac78 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IFencedExecutionCallback.aidl @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +interface IFencedExecutionCallback { + android.hardware.neuralnetworks.ErrorStatus getExecutionInfo(out android.hardware.neuralnetworks.Timing timingLaunched, out android.hardware.neuralnetworks.Timing timingFenced); +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IPreparedModel.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IPreparedModel.aidl new file mode 100644 index 0000000000..fccb5dc98e --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IPreparedModel.aidl @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +interface IPreparedModel { + android.hardware.neuralnetworks.ExecutionResult executeSynchronously(in android.hardware.neuralnetworks.Request request, in boolean measureTiming, in long deadlineNs, in long loopTimeoutDurationNs); + android.hardware.neuralnetworks.FencedExecutionResult executeFenced(in android.hardware.neuralnetworks.Request request, in ParcelFileDescriptor[] waitFor, in boolean measureTiming, in long deadlineNs, in long loopTimeoutDurationNs, in long durationNs); + android.hardware.neuralnetworks.IBurst configureExecutionBurst(); + const long DEFAULT_LOOP_TIMEOUT_DURATION_NS = 2000000000; + const long MAXIMUM_LOOP_TIMEOUT_DURATION_NS = 15000000000; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IPreparedModelCallback.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IPreparedModelCallback.aidl new file mode 100644 index 0000000000..e0c763bc2a --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IPreparedModelCallback.aidl @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +interface IPreparedModelCallback { + void notify(in android.hardware.neuralnetworks.ErrorStatus status, in android.hardware.neuralnetworks.IPreparedModel preparedModel); +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IPreparedModelParcel.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IPreparedModelParcel.aidl new file mode 100644 index 0000000000..dbedf12772 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/IPreparedModelParcel.aidl @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable IPreparedModelParcel { + android.hardware.neuralnetworks.IPreparedModel preparedModel; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Memory.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Memory.aidl new file mode 100644 index 0000000000..37fa102cf4 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Memory.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +union Memory { + android.hardware.common.Ashmem ashmem; + android.hardware.common.MappableFile mappableFile; + android.hardware.graphics.common.HardwareBuffer hardwareBuffer; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Model.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Model.aidl new file mode 100644 index 0000000000..30d8dda55d --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Model.aidl @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable Model { + android.hardware.neuralnetworks.Subgraph main; + android.hardware.neuralnetworks.Subgraph[] referenced; + byte[] operandValues; + android.hardware.neuralnetworks.Memory[] pools; + boolean relaxComputationFloat32toFloat16; + android.hardware.neuralnetworks.ExtensionNameAndPrefix[] extensionNameToPrefix; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/NumberOfCacheFiles.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/NumberOfCacheFiles.aidl new file mode 100644 index 0000000000..9314760a43 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/NumberOfCacheFiles.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable NumberOfCacheFiles { + int numModelCache; + int numDataCache; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Operand.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Operand.aidl new file mode 100644 index 0000000000..1d9bdd8446 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Operand.aidl @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable Operand { + android.hardware.neuralnetworks.OperandType type = android.hardware.neuralnetworks.OperandType.FLOAT32; + int[] dimensions; + float scale; + int zeroPoint; + android.hardware.neuralnetworks.OperandLifeTime lifetime = android.hardware.neuralnetworks.OperandLifeTime.TEMPORARY_VARIABLE; + android.hardware.neuralnetworks.DataLocation location; + @nullable android.hardware.neuralnetworks.OperandExtraParams extraParams; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandExtraParams.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandExtraParams.aidl new file mode 100644 index 0000000000..14792cff08 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandExtraParams.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +union OperandExtraParams { + android.hardware.neuralnetworks.SymmPerChannelQuantParams channelQuant; + byte[] extension; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandLifeTime.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandLifeTime.aidl new file mode 100644 index 0000000000..40adfb1dd8 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandLifeTime.aidl @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@Backing(type="int") @VintfStability +enum OperandLifeTime { + TEMPORARY_VARIABLE = 0, + SUBGRAPH_INPUT = 1, + SUBGRAPH_OUTPUT = 2, + CONSTANT_COPY = 3, + CONSTANT_POOL = 4, + NO_VALUE = 5, + SUBGRAPH = 6, +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandPerformance.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandPerformance.aidl new file mode 100644 index 0000000000..ebb361b762 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandPerformance.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable OperandPerformance { + android.hardware.neuralnetworks.OperandType type = android.hardware.neuralnetworks.OperandType.FLOAT32; + android.hardware.neuralnetworks.PerformanceInfo info; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandType.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandType.aidl new file mode 100644 index 0000000000..9f2c759d38 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperandType.aidl @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@Backing(type="int") @VintfStability +enum OperandType { + FLOAT32 = 0, + INT32 = 1, + UINT32 = 2, + TENSOR_FLOAT32 = 3, + TENSOR_INT32 = 4, + TENSOR_QUANT8_ASYMM = 5, + BOOL = 6, + TENSOR_QUANT16_SYMM = 7, + TENSOR_FLOAT16 = 8, + TENSOR_BOOL8 = 9, + FLOAT16 = 10, + TENSOR_QUANT8_SYMM_PER_CHANNEL = 11, + TENSOR_QUANT16_ASYMM = 12, + TENSOR_QUANT8_SYMM = 13, + TENSOR_QUANT8_ASYMM_SIGNED = 14, + SUBGRAPH = 15, +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Operation.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Operation.aidl new file mode 100644 index 0000000000..a4a3fbee60 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Operation.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable Operation { + android.hardware.neuralnetworks.OperationType type = android.hardware.neuralnetworks.OperationType.ADD; + int[] inputs; + int[] outputs; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperationType.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperationType.aidl new file mode 100644 index 0000000000..34506c8860 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OperationType.aidl @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@Backing(type="int") @VintfStability +enum OperationType { + ADD = 0, + AVERAGE_POOL_2D = 1, + CONCATENATION = 2, + CONV_2D = 3, + DEPTHWISE_CONV_2D = 4, + DEPTH_TO_SPACE = 5, + DEQUANTIZE = 6, + EMBEDDING_LOOKUP = 7, + FLOOR = 8, + FULLY_CONNECTED = 9, + HASHTABLE_LOOKUP = 10, + L2_NORMALIZATION = 11, + L2_POOL_2D = 12, + LOCAL_RESPONSE_NORMALIZATION = 13, + LOGISTIC = 14, + LSH_PROJECTION = 15, + LSTM = 16, + MAX_POOL_2D = 17, + MUL = 18, + RELU = 19, + RELU1 = 20, + RELU6 = 21, + RESHAPE = 22, + RESIZE_BILINEAR = 23, + RNN = 24, + SOFTMAX = 25, + SPACE_TO_DEPTH = 26, + SVDF = 27, + TANH = 28, + BATCH_TO_SPACE_ND = 29, + DIV = 30, + MEAN = 31, + PAD = 32, + SPACE_TO_BATCH_ND = 33, + SQUEEZE = 34, + STRIDED_SLICE = 35, + SUB = 36, + TRANSPOSE = 37, + ABS = 38, + ARGMAX = 39, + ARGMIN = 40, + AXIS_ALIGNED_BBOX_TRANSFORM = 41, + BIDIRECTIONAL_SEQUENCE_LSTM = 42, + BIDIRECTIONAL_SEQUENCE_RNN = 43, + BOX_WITH_NMS_LIMIT = 44, + CAST = 45, + CHANNEL_SHUFFLE = 46, + DETECTION_POSTPROCESSING = 47, + EQUAL = 48, + EXP = 49, + EXPAND_DIMS = 50, + GATHER = 51, + GENERATE_PROPOSALS = 52, + GREATER = 53, + GREATER_EQUAL = 54, + GROUPED_CONV_2D = 55, + HEATMAP_MAX_KEYPOINT = 56, + INSTANCE_NORMALIZATION = 57, + LESS = 58, + LESS_EQUAL = 59, + LOG = 60, + LOGICAL_AND = 61, + LOGICAL_NOT = 62, + LOGICAL_OR = 63, + LOG_SOFTMAX = 64, + MAXIMUM = 65, + MINIMUM = 66, + NEG = 67, + NOT_EQUAL = 68, + PAD_V2 = 69, + POW = 70, + PRELU = 71, + QUANTIZE = 72, + QUANTIZED_16BIT_LSTM = 73, + RANDOM_MULTINOMIAL = 74, + REDUCE_ALL = 75, + REDUCE_ANY = 76, + REDUCE_MAX = 77, + REDUCE_MIN = 78, + REDUCE_PROD = 79, + REDUCE_SUM = 80, + ROI_ALIGN = 81, + ROI_POOLING = 82, + RSQRT = 83, + SELECT = 84, + SIN = 85, + SLICE = 86, + SPLIT = 87, + SQRT = 88, + TILE = 89, + TOPK_V2 = 90, + TRANSPOSE_CONV_2D = 91, + UNIDIRECTIONAL_SEQUENCE_LSTM = 92, + UNIDIRECTIONAL_SEQUENCE_RNN = 93, + RESIZE_NEAREST_NEIGHBOR = 94, + QUANTIZED_LSTM = 95, + IF = 96, + WHILE = 97, + ELU = 98, + HARD_SWISH = 99, + FILL = 100, + RANK = 101, + BATCH_MATMUL = 102, + PACK = 103, + MIRROR_PAD = 104, + REVERSE = 105, +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OutputShape.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OutputShape.aidl new file mode 100644 index 0000000000..f7335054cf --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/OutputShape.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable OutputShape { + int[] dimensions; + boolean isSufficient; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/PerformanceInfo.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/PerformanceInfo.aidl new file mode 100644 index 0000000000..04910f5410 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/PerformanceInfo.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable PerformanceInfo { + float execTime; + float powerUsage; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Priority.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Priority.aidl new file mode 100644 index 0000000000..8f357097ab --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Priority.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@Backing(type="int") @VintfStability +enum Priority { + LOW = 0, + MEDIUM = 1, + HIGH = 2, +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Request.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Request.aidl new file mode 100644 index 0000000000..39ec7a9acd --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Request.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable Request { + android.hardware.neuralnetworks.RequestArgument[] inputs; + android.hardware.neuralnetworks.RequestArgument[] outputs; + android.hardware.neuralnetworks.RequestMemoryPool[] pools; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/RequestArgument.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/RequestArgument.aidl new file mode 100644 index 0000000000..e3541c0ece --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/RequestArgument.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable RequestArgument { + boolean hasNoValue; + android.hardware.neuralnetworks.DataLocation location; + int[] dimensions; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/RequestMemoryPool.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/RequestMemoryPool.aidl new file mode 100644 index 0000000000..312f5813bc --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/RequestMemoryPool.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +union RequestMemoryPool { + android.hardware.neuralnetworks.Memory pool; + int token; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Subgraph.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Subgraph.aidl new file mode 100644 index 0000000000..b7d44515f4 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Subgraph.aidl @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable Subgraph { + android.hardware.neuralnetworks.Operand[] operands; + android.hardware.neuralnetworks.Operation[] operations; + int[] inputIndexes; + int[] outputIndexes; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/SymmPerChannelQuantParams.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/SymmPerChannelQuantParams.aidl new file mode 100644 index 0000000000..02d68f9ed1 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/SymmPerChannelQuantParams.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable SymmPerChannelQuantParams { + float[] scales; + int channelDim; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Timing.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Timing.aidl new file mode 100644 index 0000000000..bcc83cfbee --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/3/android/hardware/neuralnetworks/Timing.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +parcelable Timing { + long timeOnDeviceNs; + long timeInDriverNs; +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/current/android/hardware/neuralnetworks/IExecution.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/current/android/hardware/neuralnetworks/IExecution.aidl new file mode 100644 index 0000000000..ab5275e582 --- /dev/null +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/current/android/hardware/neuralnetworks/IExecution.aidl @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/////////////////////////////////////////////////////////////////////////////// +// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. // +/////////////////////////////////////////////////////////////////////////////// + +// This file is a snapshot of an AIDL file. Do not edit it manually. There are +// two cases: +// 1). this is a frozen version file - do not edit this in any case. +// 2). this is a 'current' file. If you make a backwards compatible change to +// the interface (from the latest frozen version), the build system will +// prompt you to update this file with `m <name>-update-api`. +// +// You must not make a backward incompatible change to any AIDL file built +// with the aidl_interface module type with versions property set. The module +// type is used to build AIDL files in a way that they can be used across +// independently updatable components of the system. If a device is shipped +// with such a backward incompatible change, it has a high risk of breaking +// later when a module using the interface is updated, e.g., Mainline modules. + +package android.hardware.neuralnetworks; +@VintfStability +interface IExecution { + android.hardware.neuralnetworks.ExecutionResult executeSynchronously(in long deadlineNs); + android.hardware.neuralnetworks.FencedExecutionResult executeFenced(in ParcelFileDescriptor[] waitFor, in long deadlineNs, in long durationNs); +} diff --git a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/current/android/hardware/neuralnetworks/IPreparedModel.aidl b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/current/android/hardware/neuralnetworks/IPreparedModel.aidl index fccb5dc98e..f89956719e 100644 --- a/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/current/android/hardware/neuralnetworks/IPreparedModel.aidl +++ b/neuralnetworks/aidl/aidl_api/android.hardware.neuralnetworks/current/android/hardware/neuralnetworks/IPreparedModel.aidl @@ -37,6 +37,7 @@ interface IPreparedModel { android.hardware.neuralnetworks.ExecutionResult executeSynchronously(in android.hardware.neuralnetworks.Request request, in boolean measureTiming, in long deadlineNs, in long loopTimeoutDurationNs); android.hardware.neuralnetworks.FencedExecutionResult executeFenced(in android.hardware.neuralnetworks.Request request, in ParcelFileDescriptor[] waitFor, in boolean measureTiming, in long deadlineNs, in long loopTimeoutDurationNs, in long durationNs); android.hardware.neuralnetworks.IBurst configureExecutionBurst(); + android.hardware.neuralnetworks.IExecution createReusableExecution(in android.hardware.neuralnetworks.Request request, in boolean measureTiming, in long loopTimeoutDurationNs); const long DEFAULT_LOOP_TIMEOUT_DURATION_NS = 2000000000; const long MAXIMUM_LOOP_TIMEOUT_DURATION_NS = 15000000000; } diff --git a/neuralnetworks/aidl/android/hardware/neuralnetworks/IBurst.aidl b/neuralnetworks/aidl/android/hardware/neuralnetworks/IBurst.aidl index decdc481f1..b089c499c6 100644 --- a/neuralnetworks/aidl/android/hardware/neuralnetworks/IBurst.aidl +++ b/neuralnetworks/aidl/android/hardware/neuralnetworks/IBurst.aidl @@ -78,10 +78,10 @@ interface IBurst { * runs from the time the driver sees the call to the executeSynchronously * function to the time the driver returns from the function. * @param deadlineNs The time by which the execution is expected to complete. The time is - * measured in nanoseconds since epoch of the steady clock (as from - * std::chrono::steady_clock). If the execution cannot be finished by the - * deadline, the execution may be aborted. Passing -1 means the deadline is - * omitted. Other negative values are invalid. + * measured in nanoseconds since boot (as from clock_gettime(CLOCK_BOOTTIME, + * &ts) or ::android::base::boot_clock). If the execution cannot be finished + * by the deadline, the execution may be aborted. Passing -1 means the + * deadline is omitted. Other negative values are invalid. * @param loopTimeoutDurationNs The maximum amount of time in nanoseconds that should be spent * executing a {@link OperationType::WHILE} operation. If a loop * condition model does not output false within this duration, the diff --git a/neuralnetworks/aidl/android/hardware/neuralnetworks/IExecution.aidl b/neuralnetworks/aidl/android/hardware/neuralnetworks/IExecution.aidl new file mode 100644 index 0000000000..3cb9c1a592 --- /dev/null +++ b/neuralnetworks/aidl/android/hardware/neuralnetworks/IExecution.aidl @@ -0,0 +1,153 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.hardware.neuralnetworks; + +import android.hardware.neuralnetworks.ExecutionResult; +import android.hardware.neuralnetworks.FencedExecutionResult; + +/** + * IExecution represents a reusable execution object with request and most other execution + * properties fixed. It is used to launch executions. + * + * At most one execution may occur on a reusable execution object at any given time, either by + * means of executeSynchronously or executeFenced. + * + * An IExecution object is used to control a set of executions on the same prepared model with + * the same request and properties. IExecution objects enable some optimizations: + * (1) An IExecution object can preserve resources between executions. For example, a driver can + * map a memory object when the IExecution object is created and cache the mapping for reuse in + * subsequent executions. Any cached resource can be released when the IExecution object is + * destroyed. + * (2) Because an IExecution object may be used for at most one execution at a time, any transient + * execution resources such as intermediate tensors can be allocated once when the IExecution + * object is created and freed when the IExecution object is destroyed. + * (3) An IExecution object is created for a fixed request. This enables the implementation to apply + * request-specific optimizations. For example, an implementation can avoid request validation + * and conversions when the IExecution object is reused. An implementation may also choose to + * specialize the dynamic tensor shapes in the IExecution object according to the request. + */ +@VintfStability +interface IExecution { + /** + * Performs a synchronous execution on the reusable execution object. + * + * The execution is performed synchronously with respect to the caller. executeSynchronously + * must verify the inputs to the function are correct, and the usages of memory pools allocated + * by IDevice::allocate are valid. If there is an error, executeSynchronously must immediately + * return a service specific exception with the appropriate ErrorStatus value. If the inputs to + * the function are valid and there is no error, executeSynchronously must perform the + * execution, and must not return until the execution is complete. + * + * The caller must not change the content of any data object referenced by the 'request' + * provided in {@link IPreparedModel::createReusableExecution} (described by the + * {@link DataLocation} of a {@link RequestArgument}) until executeSynchronously returns. + * executeSynchronously must not change the content of any of the data objects corresponding to + * 'request' inputs. + * + * If the execution object was configured from a prepared model wherein all tensor operands have + * fully specified dimensions, and the inputs to the function are valid, and at execution time + * every operation's input operands have legal values, then the execution should complete + * successfully: there must be no failure unless the device itself is in a bad state. + * + * If the execution object was created with measureTiming being true and the execution is + * successful, the driver may report the timing information in the returning + * {@link ExecutionResult}. The duration runs from the time the driver sees the call to the time + * the driver returns from the function. + * + * executeSynchronously may be called with an optional deadline. If the execution is not able to + * be completed before the provided deadline, the execution may be aborted, and either + * {@link ErrorStatus::MISSED_DEADLINE_TRANSIENT} or {@link + * ErrorStatus::MISSED_DEADLINE_PERSISTENT} may be returned. The error due to an abort must be + * sent the same way as other errors, described above. + * + * @param deadlineNs The time by which the execution is expected to complete. The time is + * measured in nanoseconds since boot (as from clock_gettime(CLOCK_BOOTTIME, + * &ts) or ::android::base::boot_clock). If the execution cannot be finished + * by the deadline, the execution may be aborted. Passing -1 means the + * deadline is omitted. Other negative values are invalid. + * @return ExecutionResult parcelable, containing the status of the execution, output shapes + * and timing information. + * @throws ServiceSpecificException with one of the following ErrorStatus values: + * - DEVICE_UNAVAILABLE if driver is offline or busy + * - GENERAL_FAILURE if there is an unspecified error + * - INVALID_ARGUMENT if one of the input arguments is invalid + * - MISSED_DEADLINE_* if the execution is aborted because it cannot be completed by the + * deadline + * - RESOURCE_EXHAUSTED_* if the task was aborted by the driver + */ + ExecutionResult executeSynchronously(in long deadlineNs); + + /** + * Launch a fenced asynchronous execution on the reusable execution object. + * + * The execution is performed asynchronously with respect to the caller. executeFenced must + * verify the inputs to the function are correct, and the usages of memory pools allocated by + * IDevice::allocate are valid. If there is an error, executeFenced must immediately return a + * service specific exception with the corresponding ErrorStatus. If the inputs to the function + * are valid and there is no error, executeFenced must dispatch an asynchronous task to perform + * the execution in the background, and immediately return a {@link FencedExecutionResult} + * containing two fields: a callback (which can be used by the client to query the duration and + * runtime error status) and a sync fence (which will be signaled once the execution is + * completed). If the task has finished before the call returns, syncFence file descriptor may + * be set to -1. The execution must wait for all the sync fences (if any) in waitFor to be + * signaled before starting the actual execution. + * + * When the asynchronous task has finished its execution, it must immediately signal the + * syncFence returned from the executeFenced call. After the syncFence is signaled, the task + * must not modify the content of any data object referenced by the 'request' provided in + * IPreparedModel::createReusableExecution (described by the {@link DataLocation} of a + * {@link RequestArgument}). + * + * executeFenced may be called with an optional deadline and an optional duration. If the + * execution is not able to be completed before the provided deadline or within the timeout + * duration (measured from when all sync fences in waitFor are signaled), whichever comes + * earlier, the execution may be aborted, and either + * {@link ErrorStatus::MISSED_DEADLINE_TRANSIENT} or {@link + * ErrorStatus::MISSED_DEADLINE_PERSISTENT} may be returned. The error due to an abort must be + * sent the same way as other errors, described above. + * + * If any of the sync fences in waitFor changes to error status after the executeFenced call + * succeeds, or the execution is aborted because it cannot finish before the deadline has been + * reached or the duration has elapsed, the driver must immediately set the returned syncFence + * to error status. + * + * @param waitFor A vector of sync fence file descriptors. Execution must not start until all + * sync fences have been signaled. + * @param deadlineNs The time by which the execution is expected to complete. The time is + * measured in nanoseconds since boot (as from clock_gettime(CLOCK_BOOTTIME, + * &ts) or ::android::base::boot_clock). If the execution cannot be finished + * by the deadline, the execution may be aborted. Passing -1 means the + * deadline is omitted. Other negative values are invalid. + * @param durationNs The length of time in nanoseconds within which the execution is expected + * to complete after all sync fences in waitFor are signaled. If the + * execution cannot be finished within the duration, the execution may be + * aborted. Passing -1 means the duration is omitted. Other negative values + * are invalid. + * @return The FencedExecutionResult parcelable, containing IFencedExecutionCallback and the + * sync fence. + * @throws ServiceSpecificException with one of the following ErrorStatus values: + * - DEVICE_UNAVAILABLE if driver is offline or busy + * - GENERAL_FAILURE if there is an unspecified error + * - INVALID_ARGUMENT if one of the input arguments is invalid, including fences in error + * states. + * - MISSED_DEADLINE_* if the execution is aborted because it cannot be completed by the + * deadline + * - RESOURCE_EXHAUSTED_* if the task was aborted by the driver + */ + FencedExecutionResult executeFenced( + in ParcelFileDescriptor[] waitFor, in long deadlineNs, in long durationNs); +} diff --git a/neuralnetworks/aidl/android/hardware/neuralnetworks/IPreparedModel.aidl b/neuralnetworks/aidl/android/hardware/neuralnetworks/IPreparedModel.aidl index 956b626dd9..79053e527f 100644 --- a/neuralnetworks/aidl/android/hardware/neuralnetworks/IPreparedModel.aidl +++ b/neuralnetworks/aidl/android/hardware/neuralnetworks/IPreparedModel.aidl @@ -21,6 +21,7 @@ import android.hardware.neuralnetworks.ErrorStatus; import android.hardware.neuralnetworks.ExecutionResult; import android.hardware.neuralnetworks.FencedExecutionResult; import android.hardware.neuralnetworks.IBurst; +import android.hardware.neuralnetworks.IExecution; import android.hardware.neuralnetworks.Request; /** @@ -105,11 +106,12 @@ interface IPreparedModel { * IDevice::allocate are valid. If there is an error, executeFenced must immediately return a * service specific exception with the corresponding ErrorStatus. If the inputs to the function * are valid and there is no error, executeFenced must dispatch an asynchronous task to perform - * the execution in the background, assign a sync fence that will be signaled once the execution - * is completed and immediately return a callback that can be used by the client to query the - * duration and runtime error status. If the task has finished before the call returns, - * syncFence file descriptor may be set to -1. The execution must wait for all the sync fences - * (if any) in waitFor to be signaled before starting the actual execution. + * the execution in the background, and immediately return a {@link FencedExecutionResult} + * containing two fields: a callback (which can be used by the client to query the duration and + * runtime error status) and a sync fence (which will be signaled once the execution is + * completed). If the task has finished before the call returns, syncFence file descriptor may + * be set to -1. The execution must wait for all the sync fences (if any) in waitFor to be + * signaled before starting the actual execution. * * When the asynchronous task has finished its execution, it must immediately signal the * syncFence returned from the executeFenced call. After the syncFence is signaled, the task @@ -186,4 +188,36 @@ interface IPreparedModel { * - RESOURCE_EXHAUSTED_* if the task was aborted by the driver */ IBurst configureExecutionBurst(); + + /** + * Create a reusable execution object to launch multiple executions with the same request and + * properties. + * + * createReusableExecution must verify the inputs to the function are correct, and the usages of + * memory pools allocated by IDevice::allocate are valid. If there is an error, + * createReusableExecution must immediately return a service specific exception with the + * appropriate ErrorStatus value. If the inputs to the function are valid and there is no error, + * createReusableExecution must construct a reusable execution. + * + * @param request The input and output information on which the prepared model is to be + * executed. + * @param measure Specifies whether or not to measure duration of the execution. + * @param loopTimeoutDurationNs The maximum amount of time in nanoseconds that should be spent + * executing a {@link OperationType::WHILE} operation. If a loop + * condition model does not output false within this duration, the + * computation performed on the returned reusable execution object + * must be aborted. If -1 is provided, the maximum amount + * of time is {@link DEFAULT_LOOP_TIMEOUT_DURATION_NS}. Other + * negative values are invalid. When provided, the duration must + * not exceed {@link MAXIMUM_LOOP_TIMEOUT_DURATION_NS}. + * @return execution An IExecution object representing a reusable execution that has been + * specialized for a fixed request. + * @throws ServiceSpecificException with one of the following ErrorStatus values: + * - DEVICE_UNAVAILABLE if driver is offline or busy + * - GENERAL_FAILURE if there is an unspecified error + * - INVALID_ARGUMENT if one of the input arguments is invalid + * - RESOURCE_EXHAUSTED_* if the task was aborted by the driver + */ + IExecution createReusableExecution( + in Request request, in boolean measureTiming, in long loopTimeoutDurationNs); } diff --git a/neuralnetworks/aidl/android/hardware/neuralnetworks/OperationType.aidl b/neuralnetworks/aidl/android/hardware/neuralnetworks/OperationType.aidl index 0ad254dc4e..5f7810b778 100644 --- a/neuralnetworks/aidl/android/hardware/neuralnetworks/OperationType.aidl +++ b/neuralnetworks/aidl/android/hardware/neuralnetworks/OperationType.aidl @@ -5331,6 +5331,18 @@ enum OperationType { /** * Pads a tensor with mirrored values. * + * This operator specifies one of two padding modes: REFLECT or SYMMETRIC. + * In the case of REFLECT mode, the mirroring excludes the border element + * on the padding side. + * In the case of SYMMETRIC mode, the mirroring includes the border element + * on the padding side. + * + * For example, if the input is the 1-D tensor `[1, 2, 3]` and the padding + * is `[0, 2]` (i.e., pad no elements before the first (and only) dimension, + * and two elements after the first (and only) dimension), then: + * - REFLECT mode produces the output `[1, 2, 3, 2, 1]` + * - SYMMETRIC mode produces the output `[1, 2, 3, 3, 2]` + * * Supported tensor {@link OperandType}: * * {@link OperandType::TENSOR_FLOAT16} * * {@link OperandType::TENSOR_FLOAT32} @@ -5349,6 +5361,11 @@ enum OperationType { * front of dimension i. * padding[i, 1] specifies the number of elements to be padded after the * end of dimension i. + * Each padding value must be nonnegative. + * In the case of REFLECT mode, each padding value must be less than the + * corresponding dimension. + * In the case of SYMMETRIC mode, each padding value must be less than or + * equal to the corresponding dimension. * * 2: An {@link OperandType::INT32} scalar, specifying the mode. * Options are 0:REFLECT and 1:SYMMETRIC. * diff --git a/neuralnetworks/aidl/utils/Android.bp b/neuralnetworks/aidl/utils/Android.bp index e3561042be..3faa613514 100644 --- a/neuralnetworks/aidl/utils/Android.bp +++ b/neuralnetworks/aidl/utils/Android.bp @@ -26,7 +26,14 @@ package { cc_defaults { name: "neuralnetworks_utils_hal_aidl_defaults", defaults: ["neuralnetworks_utils_defaults"], - srcs: ["src/*"], + srcs: [ + // AIDL utils that a driver may depend on. + "src/BufferTracker.cpp", + "src/Conversions.cpp", + "src/HalUtils.cpp", + "src/Utils.cpp", + "src/ValidateHal.cpp", + ], local_include_dirs: ["include/nnapi/hal/aidl/"], export_include_dirs: ["include"], cflags: ["-Wthread-safety"], @@ -47,6 +54,7 @@ cc_defaults { }, } +// Deprecated. Remove once all modules depending on this are migrated away. cc_library_static { name: "neuralnetworks_utils_hal_aidl_v1", defaults: ["neuralnetworks_utils_hal_aidl_defaults"], @@ -56,19 +64,25 @@ cc_library_static { } cc_library_static { - name: "neuralnetworks_utils_hal_aidl_v2", - defaults: ["neuralnetworks_utils_hal_aidl_defaults"], - shared_libs: [ - "android.hardware.neuralnetworks-V2-ndk", - ], -} - -cc_library_static { name: "neuralnetworks_utils_hal_aidl", defaults: ["neuralnetworks_utils_hal_aidl_defaults"], + srcs: [ + // Additional AIDL utils for the runtime. + "src/Assertions.cpp", + "src/Buffer.cpp", + "src/Burst.cpp", + "src/Callbacks.cpp", + "src/Device.cpp", + "src/Execution.cpp", + "src/InvalidDevice.cpp", + "src/PreparedModel.cpp", + "src/ProtectCallback.cpp", + "src/Service.cpp", + ], shared_libs: [ - "android.hardware.neuralnetworks-V3-ndk", + "android.hardware.neuralnetworks-V4-ndk", ], + cflags: ["-DNN_AIDL_V4_OR_ABOVE"], } // A cc_defaults that includes the latest non-experimental AIDL utilities and other AIDL libraries @@ -79,9 +93,10 @@ cc_defaults { static_libs: [ "android.hardware.common-V2-ndk", "android.hardware.graphics.common-V3-ndk", - "android.hardware.neuralnetworks-V3-ndk", + "android.hardware.neuralnetworks-V4-ndk", "neuralnetworks_utils_hal_aidl", ], + cflags: ["-DNN_AIDL_V4_OR_ABOVE"], } cc_test { diff --git a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Callbacks.h b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Callbacks.h index 168264babf..960be2bb54 100644 --- a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Callbacks.h +++ b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Callbacks.h @@ -36,6 +36,8 @@ class PreparedModelCallback final : public BnPreparedModelCallback, public IProt public: using Data = nn::GeneralResult<nn::SharedPreparedModel>; + PreparedModelCallback(nn::Version featureLevel) : kFeatureLevel(featureLevel) {} + ndk::ScopedAStatus notify(ErrorStatus status, const std::shared_ptr<IPreparedModel>& preparedModel) override; @@ -44,6 +46,7 @@ class PreparedModelCallback final : public BnPreparedModelCallback, public IProt Data get(); private: + const nn::Version kFeatureLevel; hal::utils::TransferValue<Data> mData; }; diff --git a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Conversions.h b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Conversions.h index 78433a74e9..477b311598 100644 --- a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Conversions.h +++ b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Conversions.h @@ -112,11 +112,15 @@ GeneralResult<Priority> convert(const aidl_hal::Priority& priority); GeneralResult<Request> convert(const aidl_hal::Request& request); GeneralResult<Timing> convert(const aidl_hal::Timing& timing); GeneralResult<SharedHandle> convert(const ndk::ScopedFileDescriptor& handle); +GeneralResult<BufferDesc> convert(const aidl_hal::BufferDesc& bufferDesc); GeneralResult<std::vector<Extension>> convert(const std::vector<aidl_hal::Extension>& extension); GeneralResult<std::vector<SharedMemory>> convert(const std::vector<aidl_hal::Memory>& memories); GeneralResult<std::vector<OutputShape>> convert( const std::vector<aidl_hal::OutputShape>& outputShapes); +GeneralResult<std::vector<SharedHandle>> convert( + const std::vector<ndk::ScopedFileDescriptor>& handles); +GeneralResult<std::vector<BufferRole>> convert(const std::vector<aidl_hal::BufferRole>& roles); GeneralResult<std::vector<uint32_t>> toUnsigned(const std::vector<int32_t>& vec); @@ -129,6 +133,7 @@ namespace nn = ::android::nn; nn::GeneralResult<std::vector<uint8_t>> unvalidatedConvert(const nn::CacheToken& cacheToken); nn::GeneralResult<BufferDesc> unvalidatedConvert(const nn::BufferDesc& bufferDesc); nn::GeneralResult<BufferRole> unvalidatedConvert(const nn::BufferRole& bufferRole); +nn::GeneralResult<DeviceType> unvalidatedConvert(const nn::DeviceType& deviceType); nn::GeneralResult<bool> unvalidatedConvert(const nn::MeasureTiming& measureTiming); nn::GeneralResult<Memory> unvalidatedConvert(const nn::SharedMemory& memory); nn::GeneralResult<OutputShape> unvalidatedConvert(const nn::OutputShape& outputShape); @@ -154,14 +159,16 @@ nn::GeneralResult<Request> unvalidatedConvert(const nn::Request& request); nn::GeneralResult<RequestArgument> unvalidatedConvert(const nn::Request::Argument& requestArgument); nn::GeneralResult<RequestMemoryPool> unvalidatedConvert(const nn::Request::MemoryPool& memoryPool); nn::GeneralResult<Timing> unvalidatedConvert(const nn::Timing& timing); -nn::GeneralResult<int64_t> unvalidatedConvert(const nn::Duration& duration); nn::GeneralResult<int64_t> unvalidatedConvert(const nn::OptionalDuration& optionalDuration); nn::GeneralResult<int64_t> unvalidatedConvert(const nn::OptionalTimePoint& optionalTimePoint); nn::GeneralResult<ndk::ScopedFileDescriptor> unvalidatedConvert(const nn::SyncFence& syncFence); nn::GeneralResult<ndk::ScopedFileDescriptor> unvalidatedConvert(const nn::SharedHandle& handle); +nn::GeneralResult<Capabilities> unvalidatedConvert(const nn::Capabilities& capabilities); +nn::GeneralResult<Extension> unvalidatedConvert(const nn::Extension& extension); nn::GeneralResult<std::vector<uint8_t>> convert(const nn::CacheToken& cacheToken); nn::GeneralResult<BufferDesc> convert(const nn::BufferDesc& bufferDesc); +nn::GeneralResult<DeviceType> convert(const nn::DeviceType& deviceType); nn::GeneralResult<bool> convert(const nn::MeasureTiming& measureTiming); nn::GeneralResult<Memory> convert(const nn::SharedMemory& memory); nn::GeneralResult<ErrorStatus> convert(const nn::ErrorStatus& errorStatus); @@ -172,6 +179,8 @@ nn::GeneralResult<Request> convert(const nn::Request& request); nn::GeneralResult<Timing> convert(const nn::Timing& timing); nn::GeneralResult<int64_t> convert(const nn::OptionalDuration& optionalDuration); nn::GeneralResult<int64_t> convert(const nn::OptionalTimePoint& optionalTimePoint); +nn::GeneralResult<Capabilities> convert(const nn::Capabilities& capabilities); +nn::GeneralResult<Extension> convert(const nn::Extension& extension); nn::GeneralResult<std::vector<BufferRole>> convert(const std::vector<nn::BufferRole>& bufferRoles); nn::GeneralResult<std::vector<OutputShape>> convert( @@ -180,6 +189,7 @@ nn::GeneralResult<std::vector<ndk::ScopedFileDescriptor>> convert( const std::vector<nn::SharedHandle>& handles); nn::GeneralResult<std::vector<ndk::ScopedFileDescriptor>> convert( const std::vector<nn::SyncFence>& syncFences); +nn::GeneralResult<std::vector<Extension>> convert(const std::vector<nn::Extension>& extensions); nn::GeneralResult<std::vector<int32_t>> toSigned(const std::vector<uint32_t>& vec); diff --git a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Execution.h b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Execution.h index a77ea984b2..14802b98cc 100644 --- a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Execution.h +++ b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Execution.h @@ -17,6 +17,8 @@ #ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_EXECUTION_H #define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_EXECUTION_H +#include <aidl/android/hardware/neuralnetworks/IExecution.h> + #include <nnapi/IExecution.h> #include <nnapi/Result.h> #include <nnapi/Types.h> @@ -33,17 +35,22 @@ namespace aidl::android::hardware::neuralnetworks::utils { -class Execution final : public nn::IExecution, public std::enable_shared_from_this<Execution> { +// A reusable execution implementation with a cached Request, internally it is still passing the +// request to the driver in every computation. +class ExecutionWithCachedRequest final + : public nn::IExecution, + public std::enable_shared_from_this<ExecutionWithCachedRequest> { struct PrivateConstructorTag {}; public: - static nn::GeneralResult<std::shared_ptr<const Execution>> create( + static nn::GeneralResult<std::shared_ptr<const ExecutionWithCachedRequest>> create( std::shared_ptr<const PreparedModel> preparedModel, Request request, hal::utils::RequestRelocation relocation, bool measure, int64_t loopTimeoutDuration); - Execution(PrivateConstructorTag tag, std::shared_ptr<const PreparedModel> preparedModel, - Request request, hal::utils::RequestRelocation relocation, bool measure, - int64_t loopTimeoutDuration); + ExecutionWithCachedRequest(PrivateConstructorTag tag, + std::shared_ptr<const PreparedModel> preparedModel, Request request, + hal::utils::RequestRelocation relocation, bool measure, + int64_t loopTimeoutDuration); nn::ExecutionResult<std::pair<std::vector<nn::OutputShape>, nn::Timing>> compute( const nn::OptionalTimePoint& deadline) const override; @@ -60,6 +67,30 @@ class Execution final : public nn::IExecution, public std::enable_shared_from_th const int64_t kLoopTimeoutDuration; }; +// A reusable execution implementation that is backed by an actual AIDL IExecution object. +class Execution final : public nn::IExecution, public std::enable_shared_from_this<Execution> { + struct PrivateConstructorTag {}; + + public: + static nn::GeneralResult<std::shared_ptr<const Execution>> create( + std::shared_ptr<aidl_hal::IExecution> execution, + hal::utils::RequestRelocation relocation); + + Execution(PrivateConstructorTag tag, std::shared_ptr<aidl_hal::IExecution> execution, + hal::utils::RequestRelocation relocation); + + nn::ExecutionResult<std::pair<std::vector<nn::OutputShape>, nn::Timing>> compute( + const nn::OptionalTimePoint& deadline) const override; + + nn::GeneralResult<std::pair<nn::SyncFence, nn::ExecuteFencedInfoCallback>> computeFenced( + const std::vector<nn::SyncFence>& waitFor, const nn::OptionalTimePoint& deadline, + const nn::OptionalDuration& timeoutDurationAfterFence) const override; + + private: + const std::shared_ptr<aidl_hal::IExecution> kExecution; + const hal::utils::RequestRelocation kRelocation; +}; + } // namespace aidl::android::hardware::neuralnetworks::utils #endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_EXECUTION_H diff --git a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/HalInterfaces.h b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/HalInterfaces.h index 3fb443c388..205d428cf4 100644 --- a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/HalInterfaces.h +++ b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/HalInterfaces.h @@ -61,6 +61,11 @@ #include <aidl/android/hardware/neuralnetworks/SymmPerChannelQuantParams.h> #include <aidl/android/hardware/neuralnetworks/Timing.h> +#ifdef NN_AIDL_V4_OR_ABOVE +#include <aidl/android/hardware/neuralnetworks/BnExecution.h> +#include <aidl/android/hardware/neuralnetworks/IExecution.h> +#endif // NN_AIDL_V4_OR_ABOVE + namespace android::nn { namespace aidl_hal = ::aidl::android::hardware::neuralnetworks; diff --git a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/PreparedModel.h b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/PreparedModel.h index 4035764ea4..24cd681658 100644 --- a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/PreparedModel.h +++ b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/PreparedModel.h @@ -41,10 +41,11 @@ class PreparedModel final : public nn::IPreparedModel, public: static nn::GeneralResult<std::shared_ptr<const PreparedModel>> create( - std::shared_ptr<aidl_hal::IPreparedModel> preparedModel); + std::shared_ptr<aidl_hal::IPreparedModel> preparedModel, nn::Version featureLevel); PreparedModel(PrivateConstructorTag tag, - std::shared_ptr<aidl_hal::IPreparedModel> preparedModel); + std::shared_ptr<aidl_hal::IPreparedModel> preparedModel, + nn::Version featureLevel); nn::ExecutionResult<std::pair<std::vector<nn::OutputShape>, nn::Timing>> execute( const nn::Request& request, nn::MeasureTiming measure, @@ -78,6 +79,7 @@ class PreparedModel final : public nn::IPreparedModel, private: const std::shared_ptr<aidl_hal::IPreparedModel> kPreparedModel; + const nn::Version kFeatureLevel; }; } // namespace aidl::android::hardware::neuralnetworks::utils diff --git a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Utils.h b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Utils.h index a27487e17c..beca38b1ee 100644 --- a/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Utils.h +++ b/neuralnetworks/aidl/utils/include/nnapi/hal/aidl/Utils.h @@ -38,6 +38,8 @@ constexpr std::optional<nn::Version> aidlVersionToCanonicalVersion(int aidlVersi return nn::kVersionFeatureLevel6; case 3: return nn::kVersionFeatureLevel7; + case 4: + return nn::kVersionFeatureLevel8; default: return std::nullopt; } diff --git a/neuralnetworks/aidl/utils/src/Callbacks.cpp b/neuralnetworks/aidl/utils/src/Callbacks.cpp index 8084970690..554f3faa73 100644 --- a/neuralnetworks/aidl/utils/src/Callbacks.cpp +++ b/neuralnetworks/aidl/utils/src/Callbacks.cpp @@ -38,16 +38,17 @@ namespace { // nn::kVersionFeatureLevel5. On failure, this function returns with the appropriate // nn::GeneralError. nn::GeneralResult<nn::SharedPreparedModel> prepareModelCallback( - ErrorStatus status, const std::shared_ptr<IPreparedModel>& preparedModel) { + ErrorStatus status, const std::shared_ptr<IPreparedModel>& preparedModel, + nn::Version featureLevel) { HANDLE_STATUS_AIDL(status) << "model preparation failed with " << toString(status); - return NN_TRY(PreparedModel::create(preparedModel)); + return NN_TRY(PreparedModel::create(preparedModel, featureLevel)); } } // namespace ndk::ScopedAStatus PreparedModelCallback::notify( ErrorStatus status, const std::shared_ptr<IPreparedModel>& preparedModel) { - mData.put(prepareModelCallback(status, preparedModel)); + mData.put(prepareModelCallback(status, preparedModel, kFeatureLevel)); return ndk::ScopedAStatus::ok(); } diff --git a/neuralnetworks/aidl/utils/src/Conversions.cpp b/neuralnetworks/aidl/utils/src/Conversions.cpp index 45628c8e73..113d2da955 100644 --- a/neuralnetworks/aidl/utils/src/Conversions.cpp +++ b/neuralnetworks/aidl/utils/src/Conversions.cpp @@ -551,6 +551,10 @@ GeneralResult<SharedHandle> convert(const ndk::ScopedFileDescriptor& handle) { return validatedConvert(handle); } +GeneralResult<BufferDesc> convert(const aidl_hal::BufferDesc& bufferDesc) { + return validatedConvert(bufferDesc); +} + GeneralResult<std::vector<Extension>> convert(const std::vector<aidl_hal::Extension>& extension) { return validatedConvert(extension); } @@ -564,6 +568,15 @@ GeneralResult<std::vector<OutputShape>> convert( return validatedConvert(outputShapes); } +GeneralResult<std::vector<SharedHandle>> convert( + const std::vector<ndk::ScopedFileDescriptor>& handles) { + return validatedConvert(handles); +} + +GeneralResult<std::vector<BufferRole>> convert(const std::vector<aidl_hal::BufferRole>& roles) { + return validatedConvert(roles); +} + GeneralResult<std::vector<uint32_t>> toUnsigned(const std::vector<int32_t>& vec) { if (!std::all_of(vec.begin(), vec.end(), [](int32_t v) { return v >= 0; })) { return NN_ERROR() << "Negative value passed to conversion from signed to unsigned"; @@ -576,42 +589,7 @@ GeneralResult<std::vector<uint32_t>> toUnsigned(const std::vector<int32_t>& vec) namespace aidl::android::hardware::neuralnetworks::utils { namespace { -template <typename Input> -using UnvalidatedConvertOutput = - std::decay_t<decltype(unvalidatedConvert(std::declval<Input>()).value())>; - -template <typename Type> -nn::GeneralResult<std::vector<UnvalidatedConvertOutput<Type>>> unvalidatedConvertVec( - const std::vector<Type>& arguments) { - std::vector<UnvalidatedConvertOutput<Type>> halObject; - halObject.reserve(arguments.size()); - for (const auto& argument : arguments) { - halObject.push_back(NN_TRY(unvalidatedConvert(argument))); - } - return halObject; -} - -template <typename Type> -nn::GeneralResult<std::vector<UnvalidatedConvertOutput<Type>>> unvalidatedConvert( - const std::vector<Type>& arguments) { - return unvalidatedConvertVec(arguments); -} - -template <typename Type> -nn::GeneralResult<UnvalidatedConvertOutput<Type>> validatedConvert(const Type& canonical) { - NN_TRY(compliantVersion(canonical)); - return utils::unvalidatedConvert(canonical); -} - -template <typename Type> -nn::GeneralResult<std::vector<UnvalidatedConvertOutput<Type>>> validatedConvert( - const std::vector<Type>& arguments) { - std::vector<UnvalidatedConvertOutput<Type>> halObject(arguments.size()); - for (size_t i = 0; i < arguments.size(); ++i) { - halObject[i] = NN_TRY(validatedConvert(arguments[i])); - } - return halObject; -} +using utils::unvalidatedConvert; // Helper template for std::visit template <class... Ts> @@ -721,6 +699,74 @@ nn::GeneralResult<Memory> unvalidatedConvert(const nn::Memory::Unknown& /*memory operator nn::GeneralResult<Memory>(); } +nn::GeneralResult<PerformanceInfo> unvalidatedConvert( + const nn::Capabilities::PerformanceInfo& info) { + return PerformanceInfo{.execTime = info.execTime, .powerUsage = info.powerUsage}; +} + +nn::GeneralResult<OperandPerformance> unvalidatedConvert( + const nn::Capabilities::OperandPerformance& operandPerformance) { + return OperandPerformance{.type = NN_TRY(unvalidatedConvert(operandPerformance.type)), + .info = NN_TRY(unvalidatedConvert(operandPerformance.info))}; +} + +nn::GeneralResult<std::vector<OperandPerformance>> unvalidatedConvert( + const nn::Capabilities::OperandPerformanceTable& table) { + std::vector<OperandPerformance> operandPerformances; + operandPerformances.reserve(table.asVector().size()); + for (const auto& operandPerformance : table.asVector()) { + operandPerformances.push_back(NN_TRY(unvalidatedConvert(operandPerformance))); + } + return operandPerformances; +} + +nn::GeneralResult<ExtensionOperandTypeInformation> unvalidatedConvert( + const nn::Extension::OperandTypeInformation& info) { + return ExtensionOperandTypeInformation{.type = info.type, + .isTensor = info.isTensor, + .byteSize = static_cast<int32_t>(info.byteSize)}; +} + +nn::GeneralResult<int64_t> unvalidatedConvert(const nn::Duration& duration) { + if (duration < nn::Duration::zero()) { + return NN_ERROR() << "Unable to convert invalid (negative) duration"; + } + constexpr std::chrono::nanoseconds::rep kIntMax = std::numeric_limits<int64_t>::max(); + const auto count = duration.count(); + return static_cast<int64_t>(std::min(count, kIntMax)); +} + +template <typename Input> +using UnvalidatedConvertOutput = + std::decay_t<decltype(unvalidatedConvert(std::declval<Input>()).value())>; + +template <typename Type> +nn::GeneralResult<std::vector<UnvalidatedConvertOutput<Type>>> unvalidatedConvert( + const std::vector<Type>& arguments) { + std::vector<UnvalidatedConvertOutput<Type>> halObject; + halObject.reserve(arguments.size()); + for (const auto& argument : arguments) { + halObject.push_back(NN_TRY(unvalidatedConvert(argument))); + } + return halObject; +} + +template <typename Type> +nn::GeneralResult<UnvalidatedConvertOutput<Type>> validatedConvert(const Type& canonical) { + NN_TRY(compliantVersion(canonical)); + return utils::unvalidatedConvert(canonical); +} + +template <typename Type> +nn::GeneralResult<std::vector<UnvalidatedConvertOutput<Type>>> validatedConvert( + const std::vector<Type>& arguments) { + std::vector<UnvalidatedConvertOutput<Type>> halObject(arguments.size()); + for (size_t i = 0; i < arguments.size(); ++i) { + halObject[i] = NN_TRY(validatedConvert(arguments[i])); + } + return halObject; +} + } // namespace nn::GeneralResult<std::vector<uint8_t>> unvalidatedConvert(const nn::CacheToken& cacheToken) { @@ -743,6 +789,19 @@ nn::GeneralResult<BufferRole> unvalidatedConvert(const nn::BufferRole& bufferRol }; } +nn::GeneralResult<DeviceType> unvalidatedConvert(const nn::DeviceType& deviceType) { + switch (deviceType) { + case nn::DeviceType::UNKNOWN: + break; + case nn::DeviceType::OTHER: + case nn::DeviceType::CPU: + case nn::DeviceType::GPU: + case nn::DeviceType::ACCELERATOR: + return static_cast<DeviceType>(deviceType); + } + return NN_ERROR() << "Invalid DeviceType " << deviceType; +} + nn::GeneralResult<bool> unvalidatedConvert(const nn::MeasureTiming& measureTiming) { return measureTiming == nn::MeasureTiming::YES; } @@ -956,15 +1015,6 @@ nn::GeneralResult<Timing> unvalidatedConvert(const nn::Timing& timing) { }; } -nn::GeneralResult<int64_t> unvalidatedConvert(const nn::Duration& duration) { - if (duration < nn::Duration::zero()) { - return NN_ERROR() << "Unable to convert invalid (negative) duration"; - } - constexpr std::chrono::nanoseconds::rep kIntMax = std::numeric_limits<int64_t>::max(); - const auto count = duration.count(); - return static_cast<int64_t>(std::min(count, kIntMax)); -} - nn::GeneralResult<int64_t> unvalidatedConvert(const nn::OptionalDuration& optionalDuration) { if (!optionalDuration.has_value()) { return kNoTiming; @@ -989,6 +1039,23 @@ nn::GeneralResult<ndk::ScopedFileDescriptor> unvalidatedConvert(const nn::Shared return ndk::ScopedFileDescriptor(duplicatedFd.release()); } +nn::GeneralResult<Capabilities> unvalidatedConvert(const nn::Capabilities& capabilities) { + return Capabilities{ + .relaxedFloat32toFloat16PerformanceTensor = NN_TRY( + unvalidatedConvert(capabilities.relaxedFloat32toFloat16PerformanceTensor)), + .relaxedFloat32toFloat16PerformanceScalar = NN_TRY( + unvalidatedConvert(capabilities.relaxedFloat32toFloat16PerformanceScalar)), + .operandPerformance = NN_TRY(unvalidatedConvert(capabilities.operandPerformance)), + .ifPerformance = NN_TRY(unvalidatedConvert(capabilities.ifPerformance)), + .whilePerformance = NN_TRY(unvalidatedConvert(capabilities.whilePerformance)), + }; +} + +nn::GeneralResult<Extension> unvalidatedConvert(const nn::Extension& extension) { + return Extension{.name = extension.name, + .operandTypes = NN_TRY(unvalidatedConvert(extension.operandTypes))}; +} + nn::GeneralResult<std::vector<uint8_t>> convert(const nn::CacheToken& cacheToken) { return validatedConvert(cacheToken); } @@ -997,6 +1064,10 @@ nn::GeneralResult<BufferDesc> convert(const nn::BufferDesc& bufferDesc) { return validatedConvert(bufferDesc); } +nn::GeneralResult<DeviceType> convert(const nn::DeviceType& deviceType) { + return validatedConvert(deviceType); +} + nn::GeneralResult<bool> convert(const nn::MeasureTiming& measureTiming) { return validatedConvert(measureTiming); } @@ -1037,6 +1108,14 @@ nn::GeneralResult<int64_t> convert(const nn::OptionalTimePoint& outputShapes) { return validatedConvert(outputShapes); } +nn::GeneralResult<Capabilities> convert(const nn::Capabilities& capabilities) { + return validatedConvert(capabilities); +} + +nn::GeneralResult<Extension> convert(const nn::Extension& extension) { + return validatedConvert(extension); +} + nn::GeneralResult<std::vector<BufferRole>> convert(const std::vector<nn::BufferRole>& bufferRoles) { return validatedConvert(bufferRoles); } @@ -1056,6 +1135,10 @@ nn::GeneralResult<std::vector<ndk::ScopedFileDescriptor>> convert( return validatedConvert(syncFences); } +nn::GeneralResult<std::vector<Extension>> convert(const std::vector<nn::Extension>& extensions) { + return validatedConvert(extensions); +} + nn::GeneralResult<std::vector<int32_t>> toSigned(const std::vector<uint32_t>& vec) { if (!std::all_of(vec.begin(), vec.end(), [](uint32_t v) { return v <= std::numeric_limits<int32_t>::max(); })) { diff --git a/neuralnetworks/aidl/utils/src/Device.cpp b/neuralnetworks/aidl/utils/src/Device.cpp index 5b7ec4ebd7..bad10ed347 100644 --- a/neuralnetworks/aidl/utils/src/Device.cpp +++ b/neuralnetworks/aidl/utils/src/Device.cpp @@ -229,7 +229,7 @@ nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModel( const auto aidlDataCache = NN_TRY(convert(dataCache)); const auto aidlToken = NN_TRY(convert(token)); - const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>(); + const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>(kFeatureLevel); const auto scoped = kDeathHandler.protectCallback(cb.get()); const auto ret = kDevice->prepareModel(aidlModel, aidlPreference, aidlPriority, aidlDeadline, @@ -247,7 +247,7 @@ nn::GeneralResult<nn::SharedPreparedModel> Device::prepareModelFromCache( const auto aidlDataCache = NN_TRY(convert(dataCache)); const auto aidlToken = NN_TRY(convert(token)); - const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>(); + const auto cb = ndk::SharedRefBase::make<PreparedModelCallback>(kFeatureLevel); const auto scoped = kDeathHandler.protectCallback(cb.get()); const auto ret = kDevice->prepareModelFromCache(aidlDeadline, aidlModelCache, aidlDataCache, diff --git a/neuralnetworks/aidl/utils/src/Execution.cpp b/neuralnetworks/aidl/utils/src/Execution.cpp index 94edd90c89..c4add636e5 100644 --- a/neuralnetworks/aidl/utils/src/Execution.cpp +++ b/neuralnetworks/aidl/utils/src/Execution.cpp @@ -35,36 +35,39 @@ namespace aidl::android::hardware::neuralnetworks::utils { -nn::GeneralResult<std::shared_ptr<const Execution>> Execution::create( - std::shared_ptr<const PreparedModel> preparedModel, Request request, - hal::utils::RequestRelocation relocation, bool measure, int64_t loopTimeoutDuration) { +nn::GeneralResult<std::shared_ptr<const ExecutionWithCachedRequest>> +ExecutionWithCachedRequest::create(std::shared_ptr<const PreparedModel> preparedModel, + Request request, hal::utils::RequestRelocation relocation, + bool measure, int64_t loopTimeoutDuration) { if (preparedModel == nullptr) { - return NN_ERROR() << "aidl::utils::Execution::create must have non-null preparedModel"; + return NN_ERROR() << "aidl::utils::ExecutionWithCachedRequest::create must have non-null " + "preparedModel"; } - return std::make_shared<const Execution>(PrivateConstructorTag{}, std::move(preparedModel), - std::move(request), std::move(relocation), measure, - loopTimeoutDuration); + return std::make_shared<const ExecutionWithCachedRequest>( + PrivateConstructorTag{}, std::move(preparedModel), std::move(request), + std::move(relocation), measure, loopTimeoutDuration); } -Execution::Execution(PrivateConstructorTag /*tag*/, - std::shared_ptr<const PreparedModel> preparedModel, Request request, - hal::utils::RequestRelocation relocation, bool measure, - int64_t loopTimeoutDuration) +ExecutionWithCachedRequest::ExecutionWithCachedRequest( + PrivateConstructorTag /*tag*/, std::shared_ptr<const PreparedModel> preparedModel, + Request request, hal::utils::RequestRelocation relocation, bool measure, + int64_t loopTimeoutDuration) : kPreparedModel(std::move(preparedModel)), kRequest(std::move(request)), kRelocation(std::move(relocation)), kMeasure(measure), kLoopTimeoutDuration(loopTimeoutDuration) {} -nn::ExecutionResult<std::pair<std::vector<nn::OutputShape>, nn::Timing>> Execution::compute( - const nn::OptionalTimePoint& deadline) const { +nn::ExecutionResult<std::pair<std::vector<nn::OutputShape>, nn::Timing>> +ExecutionWithCachedRequest::compute(const nn::OptionalTimePoint& deadline) const { const auto aidlDeadline = NN_TRY(convert(deadline)); return kPreparedModel->executeInternal(kRequest, kMeasure, aidlDeadline, kLoopTimeoutDuration, kRelocation); } -nn::GeneralResult<std::pair<nn::SyncFence, nn::ExecuteFencedInfoCallback>> Execution::computeFenced( +nn::GeneralResult<std::pair<nn::SyncFence, nn::ExecuteFencedInfoCallback>> +ExecutionWithCachedRequest::computeFenced( const std::vector<nn::SyncFence>& waitFor, const nn::OptionalTimePoint& deadline, const nn::OptionalDuration& timeoutDurationAfterFence) const { const auto aidlWaitFor = NN_TRY(convert(waitFor)); @@ -75,4 +78,18 @@ nn::GeneralResult<std::pair<nn::SyncFence, nn::ExecuteFencedInfoCallback>> Execu aidlTimeoutDurationAfterFence, kRelocation); } +nn::GeneralResult<std::shared_ptr<const Execution>> Execution::create( + std::shared_ptr<aidl_hal::IExecution> execution, hal::utils::RequestRelocation relocation) { + if (execution == nullptr) { + return NN_ERROR() << "aidl::utils::Execution::create must have non-null execution"; + } + + return std::make_shared<const Execution>(PrivateConstructorTag{}, std::move(execution), + std::move(relocation)); +} + +Execution::Execution(PrivateConstructorTag /*tag*/, std::shared_ptr<aidl_hal::IExecution> execution, + hal::utils::RequestRelocation relocation) + : kExecution(std::move(execution)), kRelocation(std::move(relocation)) {} + } // namespace aidl::android::hardware::neuralnetworks::utils diff --git a/neuralnetworks/aidl/utils/src/PreparedModel.cpp b/neuralnetworks/aidl/utils/src/PreparedModel.cpp index f25c2c8825..6d1de569d0 100644 --- a/neuralnetworks/aidl/utils/src/PreparedModel.cpp +++ b/neuralnetworks/aidl/utils/src/PreparedModel.cpp @@ -54,21 +54,77 @@ nn::GeneralResult<std::pair<nn::Timing, nn::Timing>> convertFencedExecutionResul return std::make_pair(NN_TRY(nn::convert(timingLaunched)), NN_TRY(nn::convert(timingFenced))); } +nn::ExecutionResult<std::pair<std::vector<nn::OutputShape>, nn::Timing>> handleExecutionResult( + const ExecutionResult& result, const hal::utils::RequestRelocation& relocation) { + if (!result.outputSufficientSize) { + auto canonicalOutputShapes = + nn::convert(result.outputShapes).value_or(std::vector<nn::OutputShape>{}); + return NN_ERROR(nn::ErrorStatus::OUTPUT_INSUFFICIENT_SIZE, std::move(canonicalOutputShapes)) + << "execution failed with " << nn::ErrorStatus::OUTPUT_INSUFFICIENT_SIZE; + } + auto [outputShapes, timing] = + NN_TRY(convertExecutionResults(result.outputShapes, result.timing)); + + if (relocation.output) { + relocation.output->flush(); + } + return std::make_pair(std::move(outputShapes), timing); +} + +nn::GeneralResult<std::pair<nn::SyncFence, nn::ExecuteFencedInfoCallback>> +handleFencedExecutionResult(const FencedExecutionResult& result, + const hal::utils::RequestRelocation& relocation) { + auto resultSyncFence = nn::SyncFence::createAsSignaled(); + if (result.syncFence.get() != -1) { + resultSyncFence = nn::SyncFence::create(NN_TRY(nn::convert(result.syncFence))).value(); + } + + auto callback = result.callback; + if (callback == nullptr) { + return NN_ERROR(nn::ErrorStatus::GENERAL_FAILURE) << "callback is null"; + } + + // If computeFenced required the request memory to be moved into shared memory, block here until + // the fenced execution has completed and flush the memory back. + if (relocation.output) { + const auto state = resultSyncFence.syncWait({}); + if (state != nn::SyncFence::FenceState::SIGNALED) { + return NN_ERROR() << "syncWait failed with " << state; + } + relocation.output->flush(); + } + + // Create callback which can be used to retrieve the execution error status and timings. + nn::ExecuteFencedInfoCallback resultCallback = + [callback]() -> nn::GeneralResult<std::pair<nn::Timing, nn::Timing>> { + ErrorStatus errorStatus; + Timing timingLaunched; + Timing timingFenced; + const auto ret = callback->getExecutionInfo(&timingLaunched, &timingFenced, &errorStatus); + HANDLE_ASTATUS(ret) << "fenced execution callback getExecutionInfo failed"; + return convertFencedExecutionResults(errorStatus, timingLaunched, timingFenced); + }; + + return std::make_pair(std::move(resultSyncFence), std::move(resultCallback)); +} + } // namespace nn::GeneralResult<std::shared_ptr<const PreparedModel>> PreparedModel::create( - std::shared_ptr<aidl_hal::IPreparedModel> preparedModel) { + std::shared_ptr<aidl_hal::IPreparedModel> preparedModel, nn::Version featureLevel) { if (preparedModel == nullptr) { return NN_ERROR() << "aidl_hal::utils::PreparedModel::create must have non-null preparedModel"; } - return std::make_shared<const PreparedModel>(PrivateConstructorTag{}, std::move(preparedModel)); + return std::make_shared<const PreparedModel>(PrivateConstructorTag{}, std::move(preparedModel), + featureLevel); } PreparedModel::PreparedModel(PrivateConstructorTag /*tag*/, - std::shared_ptr<aidl_hal::IPreparedModel> preparedModel) - : kPreparedModel(std::move(preparedModel)) {} + std::shared_ptr<aidl_hal::IPreparedModel> preparedModel, + nn::Version featureLevel) + : kPreparedModel(std::move(preparedModel)), kFeatureLevel(featureLevel) {} nn::ExecutionResult<std::pair<std::vector<nn::OutputShape>, nn::Timing>> PreparedModel::execute( const nn::Request& request, nn::MeasureTiming measure, @@ -101,19 +157,7 @@ PreparedModel::executeInternal(const Request& request, bool measure, int64_t dea const auto ret = kPreparedModel->executeSynchronously(request, measure, deadline, loopTimeoutDuration, &executionResult); HANDLE_ASTATUS(ret) << "executeSynchronously failed"; - if (!executionResult.outputSufficientSize) { - auto canonicalOutputShapes = - nn::convert(executionResult.outputShapes).value_or(std::vector<nn::OutputShape>{}); - return NN_ERROR(nn::ErrorStatus::OUTPUT_INSUFFICIENT_SIZE, std::move(canonicalOutputShapes)) - << "execution failed with " << nn::ErrorStatus::OUTPUT_INSUFFICIENT_SIZE; - } - auto [outputShapes, timing] = - NN_TRY(convertExecutionResults(executionResult.outputShapes, executionResult.timing)); - - if (relocation.output) { - relocation.output->flush(); - } - return std::make_pair(std::move(outputShapes), timing); + return handleExecutionResult(executionResult, relocation); } nn::GeneralResult<std::pair<nn::SyncFence, nn::ExecuteFencedInfoCallback>> @@ -154,39 +198,7 @@ PreparedModel::executeFencedInternal(const Request& request, kPreparedModel->executeFenced(request, waitFor, measure, deadline, loopTimeoutDuration, timeoutDurationAfterFence, &result); HANDLE_ASTATUS(ret) << "executeFenced failed"; - - auto resultSyncFence = nn::SyncFence::createAsSignaled(); - if (result.syncFence.get() != -1) { - resultSyncFence = nn::SyncFence::create(NN_TRY(nn::convert(result.syncFence))).value(); - } - - auto callback = result.callback; - if (callback == nullptr) { - return NN_ERROR(nn::ErrorStatus::GENERAL_FAILURE) << "callback is null"; - } - - // If executeFenced required the request memory to be moved into shared memory, block here until - // the fenced execution has completed and flush the memory back. - if (relocation.output) { - const auto state = resultSyncFence.syncWait({}); - if (state != nn::SyncFence::FenceState::SIGNALED) { - return NN_ERROR() << "syncWait failed with " << state; - } - relocation.output->flush(); - } - - // Create callback which can be used to retrieve the execution error status and timings. - nn::ExecuteFencedInfoCallback resultCallback = - [callback]() -> nn::GeneralResult<std::pair<nn::Timing, nn::Timing>> { - ErrorStatus errorStatus; - Timing timingLaunched; - Timing timingFenced; - const auto ret = callback->getExecutionInfo(&timingLaunched, &timingFenced, &errorStatus); - HANDLE_ASTATUS(ret) << "fenced execution callback getExecutionInfo failed"; - return convertFencedExecutionResults(errorStatus, timingLaunched, timingFenced); - }; - - return std::make_pair(std::move(resultSyncFence), std::move(resultCallback)); + return handleFencedExecutionResult(result, relocation); } nn::GeneralResult<nn::SharedExecution> PreparedModel::createReusableExecution( @@ -202,8 +214,18 @@ nn::GeneralResult<nn::SharedExecution> PreparedModel::createReusableExecution( auto aidlRequest = NN_TRY(convert(requestInShared)); auto aidlMeasure = NN_TRY(convert(measure)); auto aidlLoopTimeoutDuration = NN_TRY(convert(loopTimeoutDuration)); - return Execution::create(shared_from_this(), std::move(aidlRequest), std::move(relocation), - aidlMeasure, aidlLoopTimeoutDuration); + + if (kFeatureLevel.level >= nn::Version::Level::FEATURE_LEVEL_8) { + std::shared_ptr<IExecution> execution; + const auto ret = kPreparedModel->createReusableExecution( + aidlRequest, aidlMeasure, aidlLoopTimeoutDuration, &execution); + HANDLE_ASTATUS(ret) << "createReusableExecution failed"; + return Execution::create(std::move(execution), std::move(relocation)); + } + + return ExecutionWithCachedRequest::create(shared_from_this(), std::move(aidlRequest), + std::move(relocation), aidlMeasure, + aidlLoopTimeoutDuration); } nn::GeneralResult<nn::SharedBurst> PreparedModel::configureExecutionBurst() const { @@ -218,4 +240,36 @@ std::any PreparedModel::getUnderlyingResource() const { return resource; } +nn::ExecutionResult<std::pair<std::vector<nn::OutputShape>, nn::Timing>> Execution::compute( + const nn::OptionalTimePoint& deadline) const { + const auto aidlDeadline = NN_TRY(convert(deadline)); + + if (kRelocation.input) { + kRelocation.input->flush(); + } + + ExecutionResult executionResult; + auto ret = kExecution->executeSynchronously(aidlDeadline, &executionResult); + HANDLE_ASTATUS(ret) << "executeSynchronously failed"; + return handleExecutionResult(executionResult, kRelocation); +} + +nn::GeneralResult<std::pair<nn::SyncFence, nn::ExecuteFencedInfoCallback>> Execution::computeFenced( + const std::vector<nn::SyncFence>& waitFor, const nn::OptionalTimePoint& deadline, + const nn::OptionalDuration& timeoutDurationAfterFence) const { + const auto aidlWaitFor = NN_TRY(convert(waitFor)); + const auto aidlDeadline = NN_TRY(convert(deadline)); + const auto aidlTimeoutDurationAfterFence = NN_TRY(convert(timeoutDurationAfterFence)); + + if (kRelocation.input) { + kRelocation.input->flush(); + } + + FencedExecutionResult result; + const auto ret = kExecution->executeFenced(aidlWaitFor, aidlDeadline, + aidlTimeoutDurationAfterFence, &result); + HANDLE_ASTATUS(ret) << "executeFenced failed"; + return handleFencedExecutionResult(result, kRelocation); +} + } // namespace aidl::android::hardware::neuralnetworks::utils diff --git a/neuralnetworks/aidl/utils/test/DeviceTest.cpp b/neuralnetworks/aidl/utils/test/DeviceTest.cpp index 0366e7dff0..fb13af8d9f 100644 --- a/neuralnetworks/aidl/utils/test/DeviceTest.cpp +++ b/neuralnetworks/aidl/utils/test/DeviceTest.cpp @@ -17,6 +17,7 @@ #include "MockBuffer.h" #include "MockDevice.h" #include "MockPreparedModel.h" +#include "TestUtils.h" #include <aidl/android/hardware/neuralnetworks/BnDevice.h> #include <android/binder_auto_utils.h> @@ -146,26 +147,7 @@ constexpr auto makeDeadObjectFailure = [] { return ndk::ScopedAStatus::fromStatus(STATUS_DEAD_OBJECT); }; -class DeviceTest : public ::testing::TestWithParam<nn::Version> { - protected: - const nn::Version kVersion = GetParam(); -}; - -std::string printDeviceTest(const testing::TestParamInfo<nn::Version>& info) { - const nn::Version version = info.param; - CHECK(!version.runtimeOnlyFeatures); - switch (version.level) { - case nn::Version::Level::FEATURE_LEVEL_5: - return "v1"; - case nn::Version::Level::FEATURE_LEVEL_6: - return "v2"; - case nn::Version::Level::FEATURE_LEVEL_7: - return "v3"; - default: - LOG(FATAL) << "Invalid AIDL version: " << version; - return "invalid"; - } -} +class DeviceTest : public VersionedAidlUtilsTestBase {}; } // namespace @@ -894,9 +876,6 @@ TEST_P(DeviceTest, allocateDeadObject) { EXPECT_EQ(result.error().code, nn::ErrorStatus::DEAD_OBJECT); } -INSTANTIATE_TEST_SUITE_P(TestDevice, DeviceTest, - ::testing::Values(nn::kVersionFeatureLevel5, nn::kVersionFeatureLevel6, - nn::kVersionFeatureLevel7), - printDeviceTest); +INSTANTIATE_VERSIONED_AIDL_UTILS_TEST(DeviceTest, kAllAidlVersions); } // namespace aidl::android::hardware::neuralnetworks::utils diff --git a/neuralnetworks/aidl/utils/test/ExecutionTest.cpp b/neuralnetworks/aidl/utils/test/ExecutionTest.cpp new file mode 100644 index 0000000000..8519290145 --- /dev/null +++ b/neuralnetworks/aidl/utils/test/ExecutionTest.cpp @@ -0,0 +1,254 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "MockExecution.h" +#include "MockFencedExecutionCallback.h" + +#include <aidl/android/hardware/neuralnetworks/IFencedExecutionCallback.h> +#include <gmock/gmock.h> +#include <gtest/gtest.h> +#include <nnapi/IExecution.h> +#include <nnapi/TypeUtils.h> +#include <nnapi/Types.h> +#include <nnapi/hal/aidl/Execution.h> + +#include <functional> +#include <memory> + +namespace aidl::android::hardware::neuralnetworks::utils { +namespace { + +using ::testing::_; +using ::testing::DoAll; +using ::testing::Invoke; +using ::testing::InvokeWithoutArgs; +using ::testing::SetArgPointee; + +const std::shared_ptr<IExecution> kInvalidExecution; +constexpr auto kNoTiming = Timing{.timeOnDeviceNs = -1, .timeInDriverNs = -1}; + +constexpr auto makeStatusOk = [] { return ndk::ScopedAStatus::ok(); }; + +constexpr auto makeGeneralFailure = [] { + return ndk::ScopedAStatus::fromServiceSpecificError( + static_cast<int32_t>(ErrorStatus::GENERAL_FAILURE)); +}; +constexpr auto makeGeneralTransportFailure = [] { + return ndk::ScopedAStatus::fromStatus(STATUS_NO_MEMORY); +}; +constexpr auto makeDeadObjectFailure = [] { + return ndk::ScopedAStatus::fromStatus(STATUS_DEAD_OBJECT); +}; + +auto makeFencedExecutionResult(const std::shared_ptr<MockFencedExecutionCallback>& callback) { + return [callback](const std::vector<ndk::ScopedFileDescriptor>& /*waitFor*/, + int64_t /*deadline*/, int64_t /*duration*/, + FencedExecutionResult* fencedExecutionResult) { + *fencedExecutionResult = FencedExecutionResult{.callback = callback, + .syncFence = ndk::ScopedFileDescriptor(-1)}; + return ndk::ScopedAStatus::ok(); + }; +} + +} // namespace + +TEST(ExecutionTest, invalidExecution) { + // run test + const auto result = Execution::create(kInvalidExecution, {}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); +} + +TEST(ExecutionTest, executeSync) { + // setup call + const auto mockExecution = MockExecution::create(); + const auto execution = Execution::create(mockExecution, {}).value(); + const auto mockExecutionResult = ExecutionResult{ + .outputSufficientSize = true, + .outputShapes = {}, + .timing = kNoTiming, + }; + EXPECT_CALL(*mockExecution, executeSynchronously(_, _)) + .Times(1) + .WillOnce( + DoAll(SetArgPointee<1>(mockExecutionResult), InvokeWithoutArgs(makeStatusOk))); + + // run test + const auto result = execution->compute({}); + + // verify result + EXPECT_TRUE(result.has_value()) + << "Failed with " << result.error().code << ": " << result.error().message; +} + +TEST(ExecutionTest, executeSyncError) { + // setup test + const auto mockExecution = MockExecution::create(); + const auto execution = Execution::create(mockExecution, {}).value(); + EXPECT_CALL(*mockExecution, executeSynchronously(_, _)) + .Times(1) + .WillOnce(Invoke(makeGeneralFailure)); + + // run test + const auto result = execution->compute({}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); +} + +TEST(ExecutionTest, executeSyncTransportFailure) { + // setup test + const auto mockExecution = MockExecution::create(); + const auto execution = Execution::create(mockExecution, {}).value(); + EXPECT_CALL(*mockExecution, executeSynchronously(_, _)) + .Times(1) + .WillOnce(InvokeWithoutArgs(makeGeneralTransportFailure)); + + // run test + const auto result = execution->compute({}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); +} + +TEST(ExecutionTest, executeSyncDeadObject) { + // setup test + const auto mockExecution = MockExecution::create(); + const auto execution = Execution::create(mockExecution, {}).value(); + EXPECT_CALL(*mockExecution, executeSynchronously(_, _)) + .Times(1) + .WillOnce(InvokeWithoutArgs(makeDeadObjectFailure)); + + // run test + const auto result = execution->compute({}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::DEAD_OBJECT); +} + +TEST(ExecutionTest, executeFenced) { + // setup call + const auto mockExecution = MockExecution::create(); + const auto execution = Execution::create(mockExecution, {}).value(); + const auto mockCallback = MockFencedExecutionCallback::create(); + EXPECT_CALL(*mockCallback, getExecutionInfo(_, _, _)) + .Times(1) + .WillOnce(DoAll(SetArgPointee<0>(kNoTiming), SetArgPointee<1>(kNoTiming), + SetArgPointee<2>(ErrorStatus::NONE), Invoke(makeStatusOk))); + EXPECT_CALL(*mockExecution, executeFenced(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(makeFencedExecutionResult(mockCallback))); + + // run test + const auto result = execution->computeFenced({}, {}, {}); + + // verify result + ASSERT_TRUE(result.has_value()) + << "Failed with " << result.error().code << ": " << result.error().message; + const auto& [syncFence, callback] = result.value(); + EXPECT_EQ(syncFence.syncWait({}), nn::SyncFence::FenceState::SIGNALED); + ASSERT_NE(callback, nullptr); + + // get results from callback + const auto callbackResult = callback(); + ASSERT_TRUE(callbackResult.has_value()) << "Failed with " << callbackResult.error().code << ": " + << callbackResult.error().message; +} + +TEST(ExecutionTest, executeFencedCallbackError) { + // setup call + const auto mockExecution = MockExecution::create(); + const auto execution = Execution::create(mockExecution, {}).value(); + const auto mockCallback = MockFencedExecutionCallback::create(); + EXPECT_CALL(*mockCallback, getExecutionInfo(_, _, _)) + .Times(1) + .WillOnce(Invoke(DoAll(SetArgPointee<0>(kNoTiming), SetArgPointee<1>(kNoTiming), + SetArgPointee<2>(ErrorStatus::GENERAL_FAILURE), + Invoke(makeStatusOk)))); + EXPECT_CALL(*mockExecution, executeFenced(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(makeFencedExecutionResult(mockCallback))); + + // run test + const auto result = execution->computeFenced({}, {}, {}); + + // verify result + ASSERT_TRUE(result.has_value()) + << "Failed with " << result.error().code << ": " << result.error().message; + const auto& [syncFence, callback] = result.value(); + EXPECT_NE(syncFence.syncWait({}), nn::SyncFence::FenceState::ACTIVE); + ASSERT_NE(callback, nullptr); + + // verify callback failure + const auto callbackResult = callback(); + ASSERT_FALSE(callbackResult.has_value()); + EXPECT_EQ(callbackResult.error().code, nn::ErrorStatus::GENERAL_FAILURE); +} + +TEST(ExecutionTest, executeFencedError) { + // setup test + const auto mockExecution = MockExecution::create(); + const auto execution = Execution::create(mockExecution, {}).value(); + EXPECT_CALL(*mockExecution, executeFenced(_, _, _, _)) + .Times(1) + .WillOnce(InvokeWithoutArgs(makeGeneralFailure)); + + // run test + const auto result = execution->computeFenced({}, {}, {}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); +} + +TEST(ExecutionTest, executeFencedTransportFailure) { + // setup test + const auto mockExecution = MockExecution::create(); + const auto execution = Execution::create(mockExecution, {}).value(); + EXPECT_CALL(*mockExecution, executeFenced(_, _, _, _)) + .Times(1) + .WillOnce(InvokeWithoutArgs(makeGeneralTransportFailure)); + + // run test + const auto result = execution->computeFenced({}, {}, {}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); +} + +TEST(ExecutionTest, executeFencedDeadObject) { + // setup test + const auto mockExecution = MockExecution::create(); + const auto execution = Execution::create(mockExecution, {}).value(); + EXPECT_CALL(*mockExecution, executeFenced(_, _, _, _)) + .Times(1) + .WillOnce(InvokeWithoutArgs(makeDeadObjectFailure)); + + // run test + const auto result = execution->computeFenced({}, {}, {}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::DEAD_OBJECT); +} + +} // namespace aidl::android::hardware::neuralnetworks::utils diff --git a/neuralnetworks/aidl/utils/test/MockExecution.h b/neuralnetworks/aidl/utils/test/MockExecution.h new file mode 100644 index 0000000000..216f569abc --- /dev/null +++ b/neuralnetworks/aidl/utils/test/MockExecution.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_MOCK_EXECUTION_H +#define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_MOCK_EXECUTION_H + +#include <aidl/android/hardware/neuralnetworks/BnExecution.h> +#include <android/binder_interface_utils.h> +#include <gmock/gmock.h> +#include <gtest/gtest.h> +#include <hidl/HidlSupport.h> +#include <hidl/Status.h> + +namespace aidl::android::hardware::neuralnetworks::utils { + +class MockExecution final : public BnExecution { + public: + static std::shared_ptr<MockExecution> create(); + + MOCK_METHOD(ndk::ScopedAStatus, executeSynchronously, + (int64_t deadline, ExecutionResult* executionResult), (override)); + MOCK_METHOD(ndk::ScopedAStatus, executeFenced, + (const std::vector<ndk::ScopedFileDescriptor>& waitFor, int64_t deadline, + int64_t duration, FencedExecutionResult* fencedExecutionResult), + (override)); +}; + +inline std::shared_ptr<MockExecution> MockExecution::create() { + return ndk::SharedRefBase::make<MockExecution>(); +} + +} // namespace aidl::android::hardware::neuralnetworks::utils + +#endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_MOCK_EXECUTION_H diff --git a/neuralnetworks/aidl/utils/test/MockPreparedModel.h b/neuralnetworks/aidl/utils/test/MockPreparedModel.h index a4ae2b778a..0ed9af9929 100644 --- a/neuralnetworks/aidl/utils/test/MockPreparedModel.h +++ b/neuralnetworks/aidl/utils/test/MockPreparedModel.h @@ -17,6 +17,7 @@ #ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_MOCK_PREPARED_MODEL_H #define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_MOCK_PREPARED_MODEL_H +#include <aidl/android/hardware/neuralnetworks/BnExecution.h> #include <aidl/android/hardware/neuralnetworks/BnPreparedModel.h> #include <android/binder_interface_utils.h> #include <gmock/gmock.h> @@ -41,6 +42,10 @@ class MockPreparedModel final : public BnPreparedModel { (override)); MOCK_METHOD(ndk::ScopedAStatus, configureExecutionBurst, (std::shared_ptr<IBurst> * burst), (override)); + MOCK_METHOD(ndk::ScopedAStatus, createReusableExecution, + (const Request& request, bool measureTiming, int64_t loopTimeoutDuration, + std::shared_ptr<IExecution>* execution), + (override)); }; inline std::shared_ptr<MockPreparedModel> MockPreparedModel::create() { diff --git a/neuralnetworks/aidl/utils/test/PreparedModelTest.cpp b/neuralnetworks/aidl/utils/test/PreparedModelTest.cpp index 8bb5c90d1e..8cfb7c123a 100644 --- a/neuralnetworks/aidl/utils/test/PreparedModelTest.cpp +++ b/neuralnetworks/aidl/utils/test/PreparedModelTest.cpp @@ -15,8 +15,10 @@ */ #include "MockBurst.h" +#include "MockExecution.h" #include "MockFencedExecutionCallback.h" #include "MockPreparedModel.h" +#include "TestUtils.h" #include <aidl/android/hardware/neuralnetworks/IFencedExecutionCallback.h> #include <gmock/gmock.h> @@ -66,21 +68,23 @@ auto makeFencedExecutionResult(const std::shared_ptr<MockFencedExecutionCallback }; } +class PreparedModelTest : public VersionedAidlUtilsTestBase {}; + } // namespace -TEST(PreparedModelTest, invalidPreparedModel) { +TEST_P(PreparedModelTest, invalidPreparedModel) { // run test - const auto result = PreparedModel::create(kInvalidPreparedModel); + const auto result = PreparedModel::create(kInvalidPreparedModel, kVersion); // verify result ASSERT_FALSE(result.has_value()); EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, executeSync) { +TEST_P(PreparedModelTest, executeSync) { // setup call const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); const auto mockExecutionResult = ExecutionResult{ .outputSufficientSize = true, .outputShapes = {}, @@ -99,10 +103,10 @@ TEST(PreparedModelTest, executeSync) { << "Failed with " << result.error().code << ": " << result.error().message; } -TEST(PreparedModelTest, executeSyncError) { +TEST_P(PreparedModelTest, executeSyncError) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeSynchronously(_, _, _, _, _)) .Times(1) .WillOnce(Invoke(makeGeneralFailure)); @@ -115,10 +119,10 @@ TEST(PreparedModelTest, executeSyncError) { EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, executeSyncTransportFailure) { +TEST_P(PreparedModelTest, executeSyncTransportFailure) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeSynchronously(_, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeGeneralTransportFailure)); @@ -131,10 +135,10 @@ TEST(PreparedModelTest, executeSyncTransportFailure) { EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, executeSyncDeadObject) { +TEST_P(PreparedModelTest, executeSyncDeadObject) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeSynchronously(_, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeDeadObjectFailure)); @@ -147,10 +151,10 @@ TEST(PreparedModelTest, executeSyncDeadObject) { EXPECT_EQ(result.error().code, nn::ErrorStatus::DEAD_OBJECT); } -TEST(PreparedModelTest, executeFenced) { +TEST_P(PreparedModelTest, executeFenced) { // setup call const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); const auto mockCallback = MockFencedExecutionCallback::create(); EXPECT_CALL(*mockCallback, getExecutionInfo(_, _, _)) .Times(1) @@ -176,10 +180,10 @@ TEST(PreparedModelTest, executeFenced) { << callbackResult.error().message; } -TEST(PreparedModelTest, executeFencedCallbackError) { +TEST_P(PreparedModelTest, executeFencedCallbackError) { // setup call const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); const auto mockCallback = MockFencedExecutionCallback::create(); EXPECT_CALL(*mockCallback, getExecutionInfo(_, _, _)) .Times(1) @@ -206,10 +210,10 @@ TEST(PreparedModelTest, executeFencedCallbackError) { EXPECT_EQ(callbackResult.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, executeFencedError) { +TEST_P(PreparedModelTest, executeFencedError) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeFenced(_, _, _, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeGeneralFailure)); @@ -222,10 +226,10 @@ TEST(PreparedModelTest, executeFencedError) { EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, executeFencedTransportFailure) { +TEST_P(PreparedModelTest, executeFencedTransportFailure) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeFenced(_, _, _, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeGeneralTransportFailure)); @@ -238,10 +242,10 @@ TEST(PreparedModelTest, executeFencedTransportFailure) { EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, executeFencedDeadObject) { +TEST_P(PreparedModelTest, executeFencedDeadObject) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeFenced(_, _, _, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeDeadObjectFailure)); @@ -254,11 +258,13 @@ TEST(PreparedModelTest, executeFencedDeadObject) { EXPECT_EQ(result.error().code, nn::ErrorStatus::DEAD_OBJECT); } -TEST(PreparedModelTest, reusableExecuteSync) { +TEST_P(PreparedModelTest, reusableExecuteSync) { + if (kVersion.level >= nn::Version::Level::FEATURE_LEVEL_8) return; + // setup call const uint32_t kNumberOfComputations = 2; const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); const auto mockExecutionResult = ExecutionResult{ .outputSufficientSize = true, .outputShapes = {}, @@ -283,10 +289,12 @@ TEST(PreparedModelTest, reusableExecuteSync) { } } -TEST(PreparedModelTest, reusableExecuteSyncError) { +TEST_P(PreparedModelTest, reusableExecuteSyncError) { + if (kVersion.level >= nn::Version::Level::FEATURE_LEVEL_8) return; + // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeSynchronously(_, _, _, _, _)) .Times(1) .WillOnce(Invoke(makeGeneralFailure)); @@ -303,10 +311,12 @@ TEST(PreparedModelTest, reusableExecuteSyncError) { EXPECT_EQ(computeResult.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, reusableExecuteSyncTransportFailure) { +TEST_P(PreparedModelTest, reusableExecuteSyncTransportFailure) { + if (kVersion.level >= nn::Version::Level::FEATURE_LEVEL_8) return; + // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeSynchronously(_, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeGeneralTransportFailure)); @@ -323,10 +333,12 @@ TEST(PreparedModelTest, reusableExecuteSyncTransportFailure) { EXPECT_EQ(computeResult.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, reusableExecuteSyncDeadObject) { +TEST_P(PreparedModelTest, reusableExecuteSyncDeadObject) { + if (kVersion.level >= nn::Version::Level::FEATURE_LEVEL_8) return; + // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeSynchronously(_, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeDeadObjectFailure)); @@ -343,11 +355,13 @@ TEST(PreparedModelTest, reusableExecuteSyncDeadObject) { EXPECT_EQ(computeResult.error().code, nn::ErrorStatus::DEAD_OBJECT); } -TEST(PreparedModelTest, reusableExecuteFenced) { +TEST_P(PreparedModelTest, reusableExecuteFenced) { + if (kVersion.level >= nn::Version::Level::FEATURE_LEVEL_8) return; + // setup call const uint32_t kNumberOfComputations = 2; const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); const auto mockCallback = MockFencedExecutionCallback::create(); EXPECT_CALL(*mockCallback, getExecutionInfo(_, _, _)) .Times(kNumberOfComputations) @@ -379,10 +393,12 @@ TEST(PreparedModelTest, reusableExecuteFenced) { } } -TEST(PreparedModelTest, reusableExecuteFencedCallbackError) { +TEST_P(PreparedModelTest, reusableExecuteFencedCallbackError) { + if (kVersion.level >= nn::Version::Level::FEATURE_LEVEL_8) return; + // setup call const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); const auto mockCallback = MockFencedExecutionCallback::create(); EXPECT_CALL(*mockCallback, getExecutionInfo(_, _, _)) .Times(1) @@ -413,10 +429,12 @@ TEST(PreparedModelTest, reusableExecuteFencedCallbackError) { EXPECT_EQ(callbackResult.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, reusableExecuteFencedError) { +TEST_P(PreparedModelTest, reusableExecuteFencedError) { + if (kVersion.level >= nn::Version::Level::FEATURE_LEVEL_8) return; + // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeFenced(_, _, _, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeGeneralFailure)); @@ -433,10 +451,12 @@ TEST(PreparedModelTest, reusableExecuteFencedError) { EXPECT_EQ(computeResult.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, reusableExecuteFencedTransportFailure) { +TEST_P(PreparedModelTest, reusableExecuteFencedTransportFailure) { + if (kVersion.level >= nn::Version::Level::FEATURE_LEVEL_8) return; + // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeFenced(_, _, _, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeGeneralTransportFailure)); @@ -453,10 +473,12 @@ TEST(PreparedModelTest, reusableExecuteFencedTransportFailure) { EXPECT_EQ(computeResult.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, reusableExecuteFencedDeadObject) { +TEST_P(PreparedModelTest, reusableExecuteFencedDeadObject) { + if (kVersion.level >= nn::Version::Level::FEATURE_LEVEL_8) return; + // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); EXPECT_CALL(*mockPreparedModel, executeFenced(_, _, _, _, _, _, _)) .Times(1) .WillOnce(InvokeWithoutArgs(makeDeadObjectFailure)); @@ -473,14 +495,14 @@ TEST(PreparedModelTest, reusableExecuteFencedDeadObject) { EXPECT_EQ(computeResult.error().code, nn::ErrorStatus::DEAD_OBJECT); } -TEST(PreparedModelTest, configureExecutionBurst) { +TEST_P(PreparedModelTest, configureExecutionBurst) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); const auto mockBurst = ndk::SharedRefBase::make<MockBurst>(); EXPECT_CALL(*mockPreparedModel, configureExecutionBurst(_)) .Times(1) .WillOnce(DoAll(SetArgPointee<0>(mockBurst), Invoke(makeStatusOk))); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); // run test const auto result = preparedModel->configureExecutionBurst(); @@ -491,13 +513,13 @@ TEST(PreparedModelTest, configureExecutionBurst) { EXPECT_NE(result.value(), nullptr); } -TEST(PreparedModelTest, configureExecutionBurstError) { +TEST_P(PreparedModelTest, configureExecutionBurstError) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); EXPECT_CALL(*mockPreparedModel, configureExecutionBurst(_)) .Times(1) .WillOnce(InvokeWithoutArgs(makeGeneralFailure)); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); // run test const auto result = preparedModel->configureExecutionBurst(); @@ -507,13 +529,13 @@ TEST(PreparedModelTest, configureExecutionBurstError) { EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, configureExecutionBurstTransportFailure) { +TEST_P(PreparedModelTest, configureExecutionBurstTransportFailure) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); EXPECT_CALL(*mockPreparedModel, configureExecutionBurst(_)) .Times(1) .WillOnce(InvokeWithoutArgs(makeGeneralTransportFailure)); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); // run test const auto result = preparedModel->configureExecutionBurst(); @@ -523,13 +545,13 @@ TEST(PreparedModelTest, configureExecutionBurstTransportFailure) { EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); } -TEST(PreparedModelTest, configureExecutionBurstDeadObject) { +TEST_P(PreparedModelTest, configureExecutionBurstDeadObject) { // setup test const auto mockPreparedModel = MockPreparedModel::create(); EXPECT_CALL(*mockPreparedModel, configureExecutionBurst(_)) .Times(1) .WillOnce(InvokeWithoutArgs(makeDeadObjectFailure)); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); // run test const auto result = preparedModel->configureExecutionBurst(); @@ -539,10 +561,84 @@ TEST(PreparedModelTest, configureExecutionBurstDeadObject) { EXPECT_EQ(result.error().code, nn::ErrorStatus::DEAD_OBJECT); } -TEST(PreparedModelTest, getUnderlyingResource) { +TEST_P(PreparedModelTest, createReusableExecution) { + if (kVersion.level < nn::Version::Level::FEATURE_LEVEL_8) return; + + // setup test + const auto mockPreparedModel = MockPreparedModel::create(); + const auto mockExecution = ndk::SharedRefBase::make<MockExecution>(); + EXPECT_CALL(*mockPreparedModel, createReusableExecution(_, _, _, _)) + .Times(1) + .WillOnce(DoAll(SetArgPointee<3>(mockExecution), Invoke(makeStatusOk))); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); + + // run test + const auto result = preparedModel->createReusableExecution({}, {}, {}); + + // verify result + ASSERT_TRUE(result.has_value()) + << "Failed with " << result.error().code << ": " << result.error().message; + EXPECT_NE(result.value(), nullptr); +} + +TEST_P(PreparedModelTest, createReusableExecutionError) { + if (kVersion.level < nn::Version::Level::FEATURE_LEVEL_8) return; + // setup test const auto mockPreparedModel = MockPreparedModel::create(); - const auto preparedModel = PreparedModel::create(mockPreparedModel).value(); + EXPECT_CALL(*mockPreparedModel, createReusableExecution(_, _, _, _)) + .Times(1) + .WillOnce(InvokeWithoutArgs(makeGeneralFailure)); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); + + // run test + const auto result = preparedModel->createReusableExecution({}, {}, {}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); +} + +TEST_P(PreparedModelTest, createReusableExecutionTransportFailure) { + if (kVersion.level < nn::Version::Level::FEATURE_LEVEL_8) return; + + // setup test + const auto mockPreparedModel = MockPreparedModel::create(); + EXPECT_CALL(*mockPreparedModel, createReusableExecution(_, _, _, _)) + .Times(1) + .WillOnce(InvokeWithoutArgs(makeGeneralTransportFailure)); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); + + // run test + const auto result = preparedModel->createReusableExecution({}, {}, {}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::GENERAL_FAILURE); +} + +TEST_P(PreparedModelTest, createReusableExecutionDeadObject) { + if (kVersion.level < nn::Version::Level::FEATURE_LEVEL_8) return; + + // setup test + const auto mockPreparedModel = MockPreparedModel::create(); + EXPECT_CALL(*mockPreparedModel, createReusableExecution(_, _, _, _)) + .Times(1) + .WillOnce(InvokeWithoutArgs(makeDeadObjectFailure)); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); + + // run test + const auto result = preparedModel->createReusableExecution({}, {}, {}); + + // verify result + ASSERT_FALSE(result.has_value()); + EXPECT_EQ(result.error().code, nn::ErrorStatus::DEAD_OBJECT); +} + +TEST_P(PreparedModelTest, getUnderlyingResource) { + // setup test + const auto mockPreparedModel = MockPreparedModel::create(); + const auto preparedModel = PreparedModel::create(mockPreparedModel, kVersion).value(); // run test const auto resource = preparedModel->getUnderlyingResource(); @@ -554,4 +650,6 @@ TEST(PreparedModelTest, getUnderlyingResource) { EXPECT_EQ(maybeMock->get(), mockPreparedModel.get()); } +INSTANTIATE_VERSIONED_AIDL_UTILS_TEST(PreparedModelTest, kAllAidlVersions); + } // namespace aidl::android::hardware::neuralnetworks::utils diff --git a/neuralnetworks/aidl/utils/test/TestUtils.cpp b/neuralnetworks/aidl/utils/test/TestUtils.cpp new file mode 100644 index 0000000000..9abec883a6 --- /dev/null +++ b/neuralnetworks/aidl/utils/test/TestUtils.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "TestUtils.h" + +#include <android-base/logging.h> +#include <gtest/gtest.h> +#include <nnapi/TypeUtils.h> +#include <nnapi/Types.h> +#include <nnapi/hal/CommonUtils.h> +#include <string> + +namespace aidl::android::hardware::neuralnetworks::utils { + +std::string printTestVersion(const testing::TestParamInfo<nn::Version>& info) { + switch (info.param.level) { + case nn::Version::Level::FEATURE_LEVEL_5: + return "v1"; + case nn::Version::Level::FEATURE_LEVEL_6: + return "v2"; + case nn::Version::Level::FEATURE_LEVEL_7: + return "v3"; + case nn::Version::Level::FEATURE_LEVEL_8: + return "v4"; + default: + LOG(FATAL) << "Invalid AIDL version: " << info.param; + return "invalid"; + } +} + +} // namespace aidl::android::hardware::neuralnetworks::utils diff --git a/neuralnetworks/aidl/utils/test/TestUtils.h b/neuralnetworks/aidl/utils/test/TestUtils.h new file mode 100644 index 0000000000..23f734a47a --- /dev/null +++ b/neuralnetworks/aidl/utils/test/TestUtils.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_TEST_UTILS_H +#define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_TEST_UTILS_H + +#include <gtest/gtest.h> +#include <nnapi/Types.h> +#include <nnapi/hal/CommonUtils.h> +#include <string> + +namespace aidl::android::hardware::neuralnetworks::utils { + +class VersionedAidlUtilsTestBase : public ::testing::TestWithParam<nn::Version> { + protected: + const nn::Version kVersion = GetParam(); +}; + +std::string printTestVersion(const testing::TestParamInfo<nn::Version>& info); + +inline const auto kAllAidlVersions = + ::testing::Values(nn::kVersionFeatureLevel5, nn::kVersionFeatureLevel6, + nn::kVersionFeatureLevel7, nn::kVersionFeatureLevel8); + +#define INSTANTIATE_VERSIONED_AIDL_UTILS_TEST(TestSuite, versions) \ + INSTANTIATE_TEST_SUITE_P(Versioned, TestSuite, versions, printTestVersion) + +} // namespace aidl::android::hardware::neuralnetworks::utils + +#endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_AIDL_UTILS_TEST_TEST_UTILS_H diff --git a/neuralnetworks/aidl/vts/functional/GeneratedTestHarness.cpp b/neuralnetworks/aidl/vts/functional/GeneratedTestHarness.cpp index f67fd34383..2460fbad86 100644 --- a/neuralnetworks/aidl/vts/functional/GeneratedTestHarness.cpp +++ b/neuralnetworks/aidl/vts/functional/GeneratedTestHarness.cpp @@ -58,25 +58,52 @@ struct TestConfig { bool measureTiming; OutputType outputType; MemoryType memoryType; + bool reusable; // `reportSkipping` indicates if a test should print an info message in case // it is skipped. The field is set to true by default and is set to false in // quantization coupling tests to suppress skipping a test bool reportSkipping; - TestConfig(Executor executor, bool measureTiming, OutputType outputType, MemoryType memoryType) + TestConfig(Executor executor, bool measureTiming, OutputType outputType, MemoryType memoryType, + bool reusable) : executor(executor), measureTiming(measureTiming), outputType(outputType), memoryType(memoryType), + reusable(reusable), reportSkipping(true) {} TestConfig(Executor executor, bool measureTiming, OutputType outputType, MemoryType memoryType, - bool reportSkipping) + bool reusable, bool reportSkipping) : executor(executor), measureTiming(measureTiming), outputType(outputType), memoryType(memoryType), + reusable(reusable), reportSkipping(reportSkipping) {} }; +std::string toString(OutputType type) { + switch (type) { + case OutputType::FULLY_SPECIFIED: + return "FULLY_SPECIFIED"; + case OutputType::UNSPECIFIED: + return "UNSPECIFIED"; + case OutputType::INSUFFICIENT: + return "INSUFFICIENT"; + case OutputType::MISSED_DEADLINE: + return "MISSED_DEADLINE"; + } +} + +std::string toString(const TestConfig& config) { + std::stringstream ss; + ss << "TestConfig{.executor=" << toString(config.executor) + << ", .measureTiming=" << (config.measureTiming ? "true" : "false") + << ", .outputType=" << toString(config.outputType) + << ", .memoryType=" << toString(config.memoryType) + << ", .reusable=" << (config.reusable ? "true" : "false") << "}"; + return ss.str(); +} + enum class IOType { INPUT, OUTPUT }; class DeviceMemoryAllocator { @@ -558,209 +585,241 @@ void EvaluatePreparedModel(const std::shared_ptr<IDevice>& device, loopTimeoutDurationNs = 1 * kMillisecond; } - ErrorStatus executionStatus; - std::vector<OutputShape> outputShapes; - Timing timing = kNoTiming; - switch (testConfig.executor) { - case Executor::SYNC: { - SCOPED_TRACE("synchronous"); - - ExecutionResult executionResult; - // execute - const auto ret = preparedModel->executeSynchronously(request, testConfig.measureTiming, - kNoDeadline, loopTimeoutDurationNs, - &executionResult); - ASSERT_TRUE(ret.isOk() || ret.getExceptionCode() == EX_SERVICE_SPECIFIC) - << ret.getDescription(); - if (ret.isOk()) { - executionStatus = executionResult.outputSufficientSize - ? ErrorStatus::NONE - : ErrorStatus::OUTPUT_INSUFFICIENT_SIZE; - outputShapes = std::move(executionResult.outputShapes); - timing = executionResult.timing; - } else { - executionStatus = static_cast<ErrorStatus>(ret.getServiceSpecificError()); - } - break; - } - case Executor::BURST: { - SCOPED_TRACE("burst"); - - // create burst - std::shared_ptr<IBurst> burst; - auto ret = preparedModel->configureExecutionBurst(&burst); - ASSERT_TRUE(ret.isOk()) << ret.getDescription(); - ASSERT_NE(nullptr, burst.get()); - - // associate a unique slot with each memory pool - int64_t currentSlot = 0; - std::vector<int64_t> slots; - slots.reserve(request.pools.size()); - for (const auto& pool : request.pools) { - if (pool.getTag() == RequestMemoryPool::Tag::pool) { - slots.push_back(currentSlot++); + std::shared_ptr<IExecution> execution; + if (testConfig.reusable) { + const auto ret = preparedModel->createReusableExecution(request, testConfig.measureTiming, + loopTimeoutDurationNs, &execution); + ASSERT_TRUE(ret.isOk()) << static_cast<nn::ErrorStatus>(ret.getServiceSpecificError()); + ASSERT_NE(nullptr, execution.get()); + } + + const auto executeAndCheckResults = [&preparedModel, &execution, &testConfig, &testModel, + &context, &request, loopTimeoutDurationNs, skipped]() { + ErrorStatus executionStatus; + std::vector<OutputShape> outputShapes; + Timing timing = kNoTiming; + switch (testConfig.executor) { + case Executor::SYNC: { + SCOPED_TRACE("synchronous"); + + ExecutionResult executionResult; + // execute + ::ndk::ScopedAStatus ret; + if (testConfig.reusable) { + ret = execution->executeSynchronously(kNoDeadline, &executionResult); } else { - EXPECT_EQ(pool.getTag(), RequestMemoryPool::Tag::token); - slots.push_back(-1); + ret = preparedModel->executeSynchronously(request, testConfig.measureTiming, + kNoDeadline, loopTimeoutDurationNs, + &executionResult); } + ASSERT_TRUE(ret.isOk() || ret.getExceptionCode() == EX_SERVICE_SPECIFIC) + << ret.getDescription(); + if (ret.isOk()) { + executionStatus = executionResult.outputSufficientSize + ? ErrorStatus::NONE + : ErrorStatus::OUTPUT_INSUFFICIENT_SIZE; + outputShapes = std::move(executionResult.outputShapes); + timing = executionResult.timing; + } else { + executionStatus = static_cast<ErrorStatus>(ret.getServiceSpecificError()); + } + break; } + case Executor::BURST: { + SCOPED_TRACE("burst"); - ExecutionResult executionResult; - // execute - ret = burst->executeSynchronously(request, slots, testConfig.measureTiming, kNoDeadline, - loopTimeoutDurationNs, &executionResult); - ASSERT_TRUE(ret.isOk() || ret.getExceptionCode() == EX_SERVICE_SPECIFIC) - << ret.getDescription(); - if (ret.isOk()) { - executionStatus = executionResult.outputSufficientSize - ? ErrorStatus::NONE - : ErrorStatus::OUTPUT_INSUFFICIENT_SIZE; - outputShapes = std::move(executionResult.outputShapes); - timing = executionResult.timing; - } else { - executionStatus = static_cast<ErrorStatus>(ret.getServiceSpecificError()); - } - - // Mark each slot as unused after the execution. This is unnecessary because the burst - // is freed after this scope ends, but this is here to test the functionality. - for (int64_t slot : slots) { - ret = burst->releaseMemoryResource(slot); + // create burst + std::shared_ptr<IBurst> burst; + auto ret = preparedModel->configureExecutionBurst(&burst); ASSERT_TRUE(ret.isOk()) << ret.getDescription(); - } + ASSERT_NE(nullptr, burst.get()); + + // associate a unique slot with each memory pool + int64_t currentSlot = 0; + std::vector<int64_t> slots; + slots.reserve(request.pools.size()); + for (const auto& pool : request.pools) { + if (pool.getTag() == RequestMemoryPool::Tag::pool) { + slots.push_back(currentSlot++); + } else { + EXPECT_EQ(pool.getTag(), RequestMemoryPool::Tag::token); + slots.push_back(-1); + } + } - break; - } - case Executor::FENCED: { - SCOPED_TRACE("fenced"); - ErrorStatus result = ErrorStatus::NONE; - FencedExecutionResult executionResult; - auto ret = preparedModel->executeFenced(request, {}, testConfig.measureTiming, - kNoDeadline, loopTimeoutDurationNs, kNoDuration, - &executionResult); - ASSERT_TRUE(ret.isOk() || ret.getExceptionCode() == EX_SERVICE_SPECIFIC) - << ret.getDescription(); - if (!ret.isOk()) { - result = static_cast<ErrorStatus>(ret.getServiceSpecificError()); - executionStatus = result; - } else if (executionResult.syncFence.get() != -1) { - std::vector<ndk::ScopedFileDescriptor> waitFor; - auto dupFd = dup(executionResult.syncFence.get()); - ASSERT_NE(dupFd, -1); - waitFor.emplace_back(dupFd); - // If a sync fence is returned, try start another run waiting for the sync fence. - ret = preparedModel->executeFenced(request, waitFor, testConfig.measureTiming, - kNoDeadline, loopTimeoutDurationNs, kNoDuration, - &executionResult); - ASSERT_TRUE(ret.isOk()); - waitForSyncFence(executionResult.syncFence.get()); + ExecutionResult executionResult; + // execute + ret = burst->executeSynchronously(request, slots, testConfig.measureTiming, + kNoDeadline, loopTimeoutDurationNs, + &executionResult); + ASSERT_TRUE(ret.isOk() || ret.getExceptionCode() == EX_SERVICE_SPECIFIC) + << ret.getDescription(); + if (ret.isOk()) { + executionStatus = executionResult.outputSufficientSize + ? ErrorStatus::NONE + : ErrorStatus::OUTPUT_INSUFFICIENT_SIZE; + outputShapes = std::move(executionResult.outputShapes); + timing = executionResult.timing; + } else { + executionStatus = static_cast<ErrorStatus>(ret.getServiceSpecificError()); + } + + // Mark each slot as unused after the execution. This is unnecessary because the + // burst is freed after this scope ends, but this is here to test the functionality. + for (int64_t slot : slots) { + ret = burst->releaseMemoryResource(slot); + ASSERT_TRUE(ret.isOk()) << ret.getDescription(); + } + + break; } - if (result == ErrorStatus::NONE) { - ASSERT_NE(executionResult.callback, nullptr); - Timing timingFenced; - auto ret = executionResult.callback->getExecutionInfo(&timing, &timingFenced, - &executionStatus); - ASSERT_TRUE(ret.isOk()); + case Executor::FENCED: { + SCOPED_TRACE("fenced"); + ErrorStatus result = ErrorStatus::NONE; + FencedExecutionResult executionResult; + ::ndk::ScopedAStatus ret; + if (testConfig.reusable) { + ret = execution->executeFenced({}, kNoDeadline, kNoDuration, &executionResult); + } else { + ret = preparedModel->executeFenced(request, {}, testConfig.measureTiming, + kNoDeadline, loopTimeoutDurationNs, + kNoDuration, &executionResult); + } + ASSERT_TRUE(ret.isOk() || ret.getExceptionCode() == EX_SERVICE_SPECIFIC) + << ret.getDescription(); + if (!ret.isOk()) { + result = static_cast<ErrorStatus>(ret.getServiceSpecificError()); + executionStatus = result; + } else if (executionResult.syncFence.get() != -1) { + std::vector<ndk::ScopedFileDescriptor> waitFor; + auto dupFd = dup(executionResult.syncFence.get()); + ASSERT_NE(dupFd, -1); + waitFor.emplace_back(dupFd); + // If a sync fence is returned, try start another run waiting for the sync + // fence. + ret = preparedModel->executeFenced(request, waitFor, testConfig.measureTiming, + kNoDeadline, loopTimeoutDurationNs, + kNoDuration, &executionResult); + ASSERT_TRUE(ret.isOk()); + waitForSyncFence(executionResult.syncFence.get()); + } + if (result == ErrorStatus::NONE) { + ASSERT_NE(executionResult.callback, nullptr); + Timing timingFenced; + auto ret = executionResult.callback->getExecutionInfo(&timing, &timingFenced, + &executionStatus); + ASSERT_TRUE(ret.isOk()); + } + break; + } + default: { + FAIL() << "Unsupported execution mode for AIDL interface."; } - break; - } - default: { - FAIL() << "Unsupported execution mode for AIDL interface."; - } - } - - if (testConfig.outputType != OutputType::FULLY_SPECIFIED && - executionStatus == ErrorStatus::GENERAL_FAILURE) { - if (skipped != nullptr) { - *skipped = true; - } - if (!testConfig.reportSkipping) { - return; - } - LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot " - "execute model that it does not support."; - std::cout << "[ ] Early termination of test because vendor service cannot " - "execute model that it does not support." - << std::endl; - GTEST_SKIP(); - } - if (!testConfig.measureTiming) { - EXPECT_EQ(timing, kNoTiming); - } else { - if (timing.timeOnDeviceNs != -1 && timing.timeInDriverNs != -1) { - EXPECT_LE(timing.timeOnDeviceNs, timing.timeInDriverNs); } - } - switch (testConfig.outputType) { - case OutputType::FULLY_SPECIFIED: - if (testConfig.executor == Executor::FENCED && hasZeroSizedOutput(testModel)) { - // Executor::FENCED does not support zero-sized output. - ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, executionStatus); - return; + if (testConfig.outputType != OutputType::FULLY_SPECIFIED && + executionStatus == ErrorStatus::GENERAL_FAILURE) { + if (skipped != nullptr) { + *skipped = true; } - // If the model output operands are fully specified, outputShapes must be either - // either empty, or have the same number of elements as the number of outputs. - ASSERT_EQ(ErrorStatus::NONE, executionStatus); - ASSERT_TRUE(outputShapes.size() == 0 || - outputShapes.size() == testModel.main.outputIndexes.size()); - break; - case OutputType::UNSPECIFIED: - if (testConfig.executor == Executor::FENCED) { - // For Executor::FENCED, the output shape must be fully specified. - ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, executionStatus); + if (!testConfig.reportSkipping) { return; } - // If the model output operands are not fully specified, outputShapes must have - // the same number of elements as the number of outputs. - ASSERT_EQ(ErrorStatus::NONE, executionStatus); - ASSERT_EQ(outputShapes.size(), testModel.main.outputIndexes.size()); - break; - case OutputType::INSUFFICIENT: - if (testConfig.executor == Executor::FENCED) { - // For Executor::FENCED, the output shape must be fully specified. - ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, executionStatus); - return; + LOG(INFO) << "NN VTS: Early termination of test because vendor service cannot " + "execute model that it does not support."; + std::cout << "[ ] Early termination of test because vendor service cannot " + "execute model that it does not support." + << std::endl; + GTEST_SKIP(); + } + if (!testConfig.measureTiming) { + EXPECT_EQ(timing, kNoTiming); + } else { + if (timing.timeOnDeviceNs != -1 && timing.timeInDriverNs != -1) { + EXPECT_LE(timing.timeOnDeviceNs, timing.timeInDriverNs); } - ASSERT_EQ(ErrorStatus::OUTPUT_INSUFFICIENT_SIZE, executionStatus); - ASSERT_EQ(outputShapes.size(), testModel.main.outputIndexes.size()); - // Check that all returned output dimensions are at least as fully specified as the - // union of the information about the corresponding operand in the model and in the - // request. In this test, all model outputs have known rank with all dimensions - // unspecified, and no dimensional information is provided in the request. - for (uint32_t i = 0; i < outputShapes.size(); i++) { - ASSERT_EQ(outputShapes[i].isSufficient, i != kInsufficientOutputIndex); - const auto& actual = outputShapes[i].dimensions; - const auto& golden = - testModel.main.operands[testModel.main.outputIndexes[i]].dimensions; - ASSERT_EQ(actual.size(), golden.size()); - for (uint32_t j = 0; j < actual.size(); j++) { - if (actual[j] == 0) continue; - EXPECT_EQ(actual[j], golden[j]) << "index: " << j; + } + + switch (testConfig.outputType) { + case OutputType::FULLY_SPECIFIED: + if (testConfig.executor == Executor::FENCED && hasZeroSizedOutput(testModel)) { + // Executor::FENCED does not support zero-sized output. + ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, executionStatus); + return; } - } - return; - case OutputType::MISSED_DEADLINE: - ASSERT_TRUE(executionStatus == ErrorStatus::MISSED_DEADLINE_TRANSIENT || - executionStatus == ErrorStatus::MISSED_DEADLINE_PERSISTENT) - << "executionStatus = " << executionStatus; - return; - } + // If the model output operands are fully specified, outputShapes must be either + // either empty, or have the same number of elements as the number of outputs. + ASSERT_EQ(ErrorStatus::NONE, executionStatus); + ASSERT_TRUE(outputShapes.size() == 0 || + outputShapes.size() == testModel.main.outputIndexes.size()); + break; + case OutputType::UNSPECIFIED: + if (testConfig.executor == Executor::FENCED) { + // For Executor::FENCED, the output shape must be fully specified. + ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, executionStatus); + return; + } + // If the model output operands are not fully specified, outputShapes must have + // the same number of elements as the number of outputs. + ASSERT_EQ(ErrorStatus::NONE, executionStatus); + ASSERT_EQ(outputShapes.size(), testModel.main.outputIndexes.size()); + break; + case OutputType::INSUFFICIENT: + if (testConfig.executor == Executor::FENCED) { + // For Executor::FENCED, the output shape must be fully specified. + ASSERT_EQ(ErrorStatus::INVALID_ARGUMENT, executionStatus); + return; + } + ASSERT_EQ(ErrorStatus::OUTPUT_INSUFFICIENT_SIZE, executionStatus); + ASSERT_EQ(outputShapes.size(), testModel.main.outputIndexes.size()); + // Check that all returned output dimensions are at least as fully specified as the + // union of the information about the corresponding operand in the model and in the + // request. In this test, all model outputs have known rank with all dimensions + // unspecified, and no dimensional information is provided in the request. + for (uint32_t i = 0; i < outputShapes.size(); i++) { + ASSERT_EQ(outputShapes[i].isSufficient, i != kInsufficientOutputIndex); + const auto& actual = outputShapes[i].dimensions; + const auto& golden = + testModel.main.operands[testModel.main.outputIndexes[i]].dimensions; + ASSERT_EQ(actual.size(), golden.size()); + for (uint32_t j = 0; j < actual.size(); j++) { + if (actual[j] == 0) continue; + EXPECT_EQ(actual[j], golden[j]) << "index: " << j; + } + } + return; + case OutputType::MISSED_DEADLINE: + ASSERT_TRUE(executionStatus == ErrorStatus::MISSED_DEADLINE_TRANSIENT || + executionStatus == ErrorStatus::MISSED_DEADLINE_PERSISTENT) + << "executionStatus = " << executionStatus; + return; + } - // Go through all outputs, check returned output shapes. - for (uint32_t i = 0; i < outputShapes.size(); i++) { - EXPECT_TRUE(outputShapes[i].isSufficient); - const auto& expect = testModel.main.operands[testModel.main.outputIndexes[i]].dimensions; - const auto unsignedActual = nn::toUnsigned(outputShapes[i].dimensions); - ASSERT_TRUE(unsignedActual.has_value()); - const std::vector<uint32_t>& actual = unsignedActual.value(); - EXPECT_EQ(expect, actual); - } + // Go through all outputs, check returned output shapes. + for (uint32_t i = 0; i < outputShapes.size(); i++) { + EXPECT_TRUE(outputShapes[i].isSufficient); + const auto& expect = + testModel.main.operands[testModel.main.outputIndexes[i]].dimensions; + const auto unsignedActual = nn::toUnsigned(outputShapes[i].dimensions); + ASSERT_TRUE(unsignedActual.has_value()); + const std::vector<uint32_t>& actual = unsignedActual.value(); + EXPECT_EQ(expect, actual); + } + + // Retrieve execution results. + const std::vector<TestBuffer> outputs = context.getOutputBuffers(testModel, request); - // Retrieve execution results. - const std::vector<TestBuffer> outputs = context.getOutputBuffers(testModel, request); + // We want "close-enough" results. + checkResults(testModel, outputs); + }; - // We want "close-enough" results. - checkResults(testModel, outputs); + executeAndCheckResults(); + + // For reusable execution tests, run the execution twice. + if (testConfig.reusable) { + SCOPED_TRACE("Second execution"); + executeAndCheckResults(); + } } void EvaluatePreparedModel(const std::shared_ptr<IDevice>& device, @@ -770,6 +829,13 @@ void EvaluatePreparedModel(const std::shared_ptr<IDevice>& device, std::vector<bool> measureTimingList; std::vector<Executor> executorList; std::vector<MemoryType> memoryTypeList; + std::vector<bool> reusableList = {false}; + + int deviceVersion; + ASSERT_TRUE(device->getInterfaceVersion(&deviceVersion).isOk()); + if (deviceVersion >= kMinAidlLevelForFL8) { + reusableList.push_back(true); + } switch (testKind) { case TestKind::GENERAL: { @@ -812,8 +878,13 @@ void EvaluatePreparedModel(const std::shared_ptr<IDevice>& device, for (const bool measureTiming : measureTimingList) { for (const Executor executor : executorList) { for (const MemoryType memoryType : memoryTypeList) { - const TestConfig testConfig(executor, measureTiming, outputType, memoryType); - EvaluatePreparedModel(device, preparedModel, testModel, testConfig); + for (const bool reusable : reusableList) { + if (executor == Executor::BURST && reusable) continue; + const TestConfig testConfig(executor, measureTiming, outputType, memoryType, + reusable); + SCOPED_TRACE(toString(testConfig)); + EvaluatePreparedModel(device, preparedModel, testModel, testConfig); + } } } } @@ -833,7 +904,7 @@ void EvaluatePreparedCoupledModels(const std::shared_ptr<IDevice>& device, for (const bool measureTiming : measureTimingList) { for (const Executor executor : executorList) { const TestConfig testConfig(executor, measureTiming, outputType, MemoryType::ASHMEM, - /*reportSkipping=*/false); + /*reusable=*/false, /*reportSkipping=*/false); bool baseSkipped = false; EvaluatePreparedModel(device, preparedModel, testModel, testConfig, &baseSkipped); bool coupledSkipped = false; diff --git a/neuralnetworks/aidl/vts/functional/MemoryDomainTests.cpp b/neuralnetworks/aidl/vts/functional/MemoryDomainTests.cpp index cd5475c0d3..b3e9c633e3 100644 --- a/neuralnetworks/aidl/vts/functional/MemoryDomainTests.cpp +++ b/neuralnetworks/aidl/vts/functional/MemoryDomainTests.cpp @@ -208,6 +208,11 @@ class InvalidPreparedModel : public BnPreparedModel { return ndk::ScopedAStatus::fromServiceSpecificError( static_cast<int32_t>(ErrorStatus::GENERAL_FAILURE)); } + ndk::ScopedAStatus createReusableExecution(const aidl_hal::Request&, bool, int64_t, + std::shared_ptr<aidl_hal::IExecution>*) override { + return ndk::ScopedAStatus::fromServiceSpecificError( + static_cast<int32_t>(ErrorStatus::GENERAL_FAILURE)); + } }; template <typename... Args> diff --git a/neuralnetworks/aidl/vts/functional/Utils.cpp b/neuralnetworks/aidl/vts/functional/Utils.cpp index 325a436f79..efd5bca517 100644 --- a/neuralnetworks/aidl/vts/functional/Utils.cpp +++ b/neuralnetworks/aidl/vts/functional/Utils.cpp @@ -177,6 +177,17 @@ std::string gtestCompliantName(std::string name) { return os << toString(errorStatus); } +std::string toString(MemoryType type) { + switch (type) { + case MemoryType::ASHMEM: + return "ASHMEM"; + case MemoryType::BLOB_AHWB: + return "BLOB_AHWB"; + case MemoryType::DEVICE: + return "DEVICE"; + } +} + Request ExecutionContext::createRequest(const TestModel& testModel, MemoryType memoryType) { CHECK(memoryType == MemoryType::ASHMEM || memoryType == MemoryType::BLOB_AHWB); diff --git a/neuralnetworks/aidl/vts/functional/Utils.h b/neuralnetworks/aidl/vts/functional/Utils.h index ca81418417..0db3f8c7f8 100644 --- a/neuralnetworks/aidl/vts/functional/Utils.h +++ b/neuralnetworks/aidl/vts/functional/Utils.h @@ -111,6 +111,8 @@ class TestBlobAHWB : public TestMemoryBase { enum class MemoryType { ASHMEM, BLOB_AHWB, DEVICE }; +std::string toString(MemoryType type); + // Manages the lifetime of memory resources used in an execution. class ExecutionContext { DISALLOW_COPY_AND_ASSIGN(ExecutionContext); diff --git a/neuralnetworks/aidl/vts/functional/ValidateRequest.cpp b/neuralnetworks/aidl/vts/functional/ValidateRequest.cpp index 29e2471777..e8debf704c 100644 --- a/neuralnetworks/aidl/vts/functional/ValidateRequest.cpp +++ b/neuralnetworks/aidl/vts/functional/ValidateRequest.cpp @@ -36,6 +36,51 @@ using ExecutionMutation = std::function<void(Request*)>; ///////////////////////// UTILITY FUNCTIONS ///////////////////////// +// Test request validation with reusable execution. +static void validateReusableExecution(const std::shared_ptr<IPreparedModel>& preparedModel, + const std::string& message, const Request& request, + bool measure) { + // createReusableExecution + std::shared_ptr<IExecution> execution; + { + SCOPED_TRACE(message + " [createReusableExecution]"); + const auto createStatus = preparedModel->createReusableExecution( + request, measure, kOmittedTimeoutDuration, &execution); + if (!createStatus.isOk()) { + ASSERT_EQ(createStatus.getExceptionCode(), EX_SERVICE_SPECIFIC); + ASSERT_EQ(static_cast<ErrorStatus>(createStatus.getServiceSpecificError()), + ErrorStatus::INVALID_ARGUMENT); + ASSERT_EQ(nullptr, execution); + return; + } else { + ASSERT_NE(nullptr, execution); + } + } + + // synchronous + { + SCOPED_TRACE(message + " [executeSynchronously]"); + ExecutionResult executionResult; + const auto executeStatus = execution->executeSynchronously(kNoDeadline, &executionResult); + ASSERT_FALSE(executeStatus.isOk()); + ASSERT_EQ(executeStatus.getExceptionCode(), EX_SERVICE_SPECIFIC); + ASSERT_EQ(static_cast<ErrorStatus>(executeStatus.getServiceSpecificError()), + ErrorStatus::INVALID_ARGUMENT); + } + + // fenced + { + SCOPED_TRACE(message + " [executeFenced]"); + FencedExecutionResult executionResult; + const auto executeStatus = + execution->executeFenced({}, kNoDeadline, kNoDuration, &executionResult); + ASSERT_FALSE(executeStatus.isOk()); + ASSERT_EQ(executeStatus.getExceptionCode(), EX_SERVICE_SPECIFIC); + ASSERT_EQ(static_cast<ErrorStatus>(executeStatus.getServiceSpecificError()), + ErrorStatus::INVALID_ARGUMENT); + } +} + // Primary validation function. This function will take a valid request, apply a // mutation to it to invalidate the request, then pass it to interface calls // that use the request. @@ -101,6 +146,14 @@ static void validate(const std::shared_ptr<IPreparedModel>& preparedModel, ASSERT_EQ(static_cast<ErrorStatus>(executeStatus.getServiceSpecificError()), ErrorStatus::INVALID_ARGUMENT); } + + int32_t aidlVersion; + ASSERT_TRUE(preparedModel->getInterfaceVersion(&aidlVersion).isOk()); + + // validate reusable execution + if (aidlVersion >= kMinAidlLevelForFL8) { + validateReusableExecution(preparedModel, message, request, measure); + } } std::shared_ptr<IBurst> createBurst(const std::shared_ptr<IPreparedModel>& preparedModel) { diff --git a/neuralnetworks/aidl/vts/functional/VtsHalNeuralnetworks.h b/neuralnetworks/aidl/vts/functional/VtsHalNeuralnetworks.h index 4312d3a4a1..a900590791 100644 --- a/neuralnetworks/aidl/vts/functional/VtsHalNeuralnetworks.h +++ b/neuralnetworks/aidl/vts/functional/VtsHalNeuralnetworks.h @@ -30,6 +30,8 @@ namespace aidl::android::hardware::neuralnetworks::vts::functional { using NamedDevice = Named<std::shared_ptr<IDevice>>; using NeuralNetworksAidlTestParam = NamedDevice; +constexpr int kMinAidlLevelForFL8 = 4; + class NeuralNetworksAidlTest : public testing::TestWithParam<NeuralNetworksAidlTestParam> { protected: void SetUp() override; diff --git a/neuralnetworks/utils/adapter/aidl/Android.bp b/neuralnetworks/utils/adapter/aidl/Android.bp new file mode 100644 index 0000000000..8269a3d4aa --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/Android.bp @@ -0,0 +1,42 @@ +// +// Copyright (C) 2021 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "hardware_interfaces_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["hardware_interfaces_license"], +} + +cc_library_static { + name: "neuralnetworks_utils_hal_adapter_aidl", + defaults: [ + "neuralnetworks_use_latest_utils_hal_aidl", + "neuralnetworks_utils_defaults", + ], + srcs: ["src/*"], + local_include_dirs: ["include/nnapi/hal/aidl/"], + export_include_dirs: ["include"], + static_libs: [ + "neuralnetworks_types", + "neuralnetworks_utils_hal_common", + ], + shared_libs: [ + "libbinder_ndk", + ], +} diff --git a/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Adapter.h b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Adapter.h new file mode 100644 index 0000000000..4c0b3286de --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Adapter.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_ADAPTER_H +#define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_ADAPTER_H + +#include <aidl/android/hardware/neuralnetworks/BnDevice.h> +#include <nnapi/IDevice.h> +#include <nnapi/Types.h> + +#include <functional> +#include <memory> + +// See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface +// lifetimes across processes and for protecting asynchronous calls across AIDL. + +namespace aidl::android::hardware::neuralnetworks::adapter { + +/** + * A self-contained unit of work to be executed. + */ +using Task = std::function<void()>; + +/** + * A type-erased executor which executes a task asynchronously. + * + * This executor is also provided an optional deadline for when the caller expects is the upper + * bound for the amount of time to complete the task. If needed, the Executor can retrieve the + * Application ID (Android User ID) by calling AIBinder_getCallingUid in android/binder_ibinder.h. + */ +using Executor = std::function<void(Task, ::android::nn::OptionalTimePoint)>; + +/** + * Adapt an NNAPI canonical interface object to a AIDL NN HAL interface object. + * + * The IPreparedModel object created from IDevice::prepareModel or IDevice::preparedModelFromCache + * must return "const nn::Model*" from IPreparedModel::getUnderlyingResource(). + * + * @param device NNAPI canonical IDevice interface object to be adapted. + * @param executor Type-erased executor to handle executing tasks asynchronously. + * @return AIDL NN HAL IDevice interface object. + */ +std::shared_ptr<BnDevice> adapt(::android::nn::SharedDevice device, Executor executor); + +/** + * Adapt an NNAPI canonical interface object to a AIDL NN HAL interface object. + * + * The IPreparedModel object created from IDevice::prepareModel or IDevice::preparedModelFromCache + * must return "const nn::Model*" from IPreparedModel::getUnderlyingResource(). + * + * This function uses a default executor, which will execute tasks from a detached thread. + * + * @param device NNAPI canonical IDevice interface object to be adapted. + * @return AIDL NN HAL IDevice interface object. + */ +std::shared_ptr<BnDevice> adapt(::android::nn::SharedDevice device); + +} // namespace aidl::android::hardware::neuralnetworks::adapter + +#endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_ADAPTER_H diff --git a/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Buffer.h b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Buffer.h new file mode 100644 index 0000000000..701e43eb01 --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Buffer.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_BUFFER_H +#define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_BUFFER_H + +#include <aidl/android/hardware/neuralnetworks/BnBuffer.h> +#include <aidl/android/hardware/neuralnetworks/Memory.h> +#include <android/binder_auto_utils.h> +#include <nnapi/IBuffer.h> + +#include <memory> +#include <vector> + +// See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface +// lifetimes across processes and for protecting asynchronous calls across AIDL. + +namespace aidl::android::hardware::neuralnetworks::adapter { + +// Class that adapts nn::IBuffer to BnBuffer. +class Buffer : public BnBuffer { + public: + explicit Buffer(::android::nn::SharedBuffer buffer); + + ndk::ScopedAStatus copyFrom(const Memory& src, const std::vector<int32_t>& dimensions) override; + ndk::ScopedAStatus copyTo(const Memory& dst) override; + + private: + const ::android::nn::SharedBuffer kBuffer; +}; + +} // namespace aidl::android::hardware::neuralnetworks::adapter + +#endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_BUFFER_H diff --git a/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Burst.h b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Burst.h new file mode 100644 index 0000000000..f2687c4a69 --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Burst.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_BURST_H +#define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_BURST_H + +#include <aidl/android/hardware/neuralnetworks/BnBurst.h> +#include <aidl/android/hardware/neuralnetworks/ExecutionResult.h> +#include <aidl/android/hardware/neuralnetworks/Request.h> +#include <android-base/thread_annotations.h> +#include <android/binder_auto_utils.h> +#include <nnapi/IBurst.h> +#include <nnapi/Types.h> + +#include <memory> +#include <mutex> +#include <unordered_map> +#include <vector> + +// See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface +// lifetimes across processes and for protecting asynchronous calls across AIDL. + +namespace aidl::android::hardware::neuralnetworks::adapter { + +// Class that adapts nn::Burst to BnBurst. +class Burst : public BnBurst { + public: + // Precondition: burst != nullptr + explicit Burst(::android::nn::SharedBurst burst); + + ndk::ScopedAStatus executeSynchronously(const Request& request, + const std::vector<int64_t>& memoryIdentifierTokens, + bool measureTiming, int64_t deadlineNs, + int64_t loopTimeoutDurationNs, + ExecutionResult* executionResult) override; + ndk::ScopedAStatus releaseMemoryResource(int64_t memoryIdentifierToken) override; + + class ThreadSafeMemoryCache { + public: + using Value = + std::pair<::android::nn::SharedMemory, ::android::nn::IBurst::OptionalCacheHold>; + + Value add(int64_t token, const ::android::nn::SharedMemory& memory, + const ::android::nn::IBurst& burst) const; + void remove(int64_t token) const; + + private: + mutable std::mutex mMutex; + mutable std::unordered_map<int64_t, Value> mCache GUARDED_BY(mMutex); + }; + + private: + const ::android::nn::SharedBurst kBurst; + const ThreadSafeMemoryCache kMemoryCache; +}; + +} // namespace aidl::android::hardware::neuralnetworks::adapter + +#endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_BURST_H diff --git a/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Device.h b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Device.h new file mode 100644 index 0000000000..aa29d63b6b --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Device.h @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_DEVICE_H +#define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_DEVICE_H + +#include "nnapi/hal/aidl/Adapter.h" + +#include <aidl/android/hardware/neuralnetworks/BnDevice.h> +#include <aidl/android/hardware/neuralnetworks/BufferDesc.h> +#include <aidl/android/hardware/neuralnetworks/BufferRole.h> +#include <aidl/android/hardware/neuralnetworks/Capabilities.h> +#include <aidl/android/hardware/neuralnetworks/DeviceBuffer.h> +#include <aidl/android/hardware/neuralnetworks/DeviceType.h> +#include <aidl/android/hardware/neuralnetworks/ExecutionPreference.h> +#include <aidl/android/hardware/neuralnetworks/Extension.h> +#include <aidl/android/hardware/neuralnetworks/IPreparedModelCallback.h> +#include <aidl/android/hardware/neuralnetworks/IPreparedModelParcel.h> +#include <aidl/android/hardware/neuralnetworks/Model.h> +#include <aidl/android/hardware/neuralnetworks/NumberOfCacheFiles.h> +#include <aidl/android/hardware/neuralnetworks/Priority.h> +#include <android/binder_auto_utils.h> +#include <nnapi/IDevice.h> + +#include <memory> +#include <string> +#include <vector> + +// See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface +// lifetimes across processes and for protecting asynchronous calls across AIDL. + +namespace aidl::android::hardware::neuralnetworks::adapter { + +// Class that adapts nn::IDevice to BnDevice. +class Device : public BnDevice { + public: + Device(::android::nn::SharedDevice device, Executor executor); + + ndk::ScopedAStatus allocate(const BufferDesc& desc, + const std::vector<IPreparedModelParcel>& preparedModels, + const std::vector<BufferRole>& inputRoles, + const std::vector<BufferRole>& outputRoles, + DeviceBuffer* buffer) override; + ndk::ScopedAStatus getCapabilities(Capabilities* capabilities) override; + ndk::ScopedAStatus getNumberOfCacheFilesNeeded(NumberOfCacheFiles* numberOfCacheFiles) override; + ndk::ScopedAStatus getSupportedExtensions(std::vector<Extension>* extensions) override; + ndk::ScopedAStatus getSupportedOperations(const Model& model, + std::vector<bool>* supported) override; + ndk::ScopedAStatus getType(DeviceType* deviceType) override; + ndk::ScopedAStatus getVersionString(std::string* version) override; + ndk::ScopedAStatus prepareModel( + const Model& model, ExecutionPreference preference, Priority priority, + int64_t deadlineNs, const std::vector<ndk::ScopedFileDescriptor>& modelCache, + const std::vector<ndk::ScopedFileDescriptor>& dataCache, + const std::vector<uint8_t>& token, + const std::shared_ptr<IPreparedModelCallback>& callback) override; + ndk::ScopedAStatus prepareModelFromCache( + int64_t deadlineNs, const std::vector<ndk::ScopedFileDescriptor>& modelCache, + const std::vector<ndk::ScopedFileDescriptor>& dataCache, + const std::vector<uint8_t>& token, + const std::shared_ptr<IPreparedModelCallback>& callback) override; + + protected: + const ::android::nn::SharedDevice kDevice; + const Executor kExecutor; +}; + +} // namespace aidl::android::hardware::neuralnetworks::adapter + +#endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_DEVICE_H diff --git a/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Execution.h b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Execution.h new file mode 100644 index 0000000000..6a9ac57fbe --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/Execution.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_EXECUTION_H +#define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_EXECUTION_H + +#include "nnapi/hal/aidl/Adapter.h" + +#include <aidl/android/hardware/neuralnetworks/BnExecution.h> +#include <aidl/android/hardware/neuralnetworks/ExecutionResult.h> +#include <aidl/android/hardware/neuralnetworks/FencedExecutionResult.h> +#include <aidl/android/hardware/neuralnetworks/IExecution.h> +#include <aidl/android/hardware/neuralnetworks/Request.h> +#include <android/binder_auto_utils.h> +#include <nnapi/IExecution.h> +#include <nnapi/Types.h> + +#include <memory> +#include <vector> + +// See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface +// lifetimes across processes and for protecting asynchronous calls across AIDL. + +namespace aidl::android::hardware::neuralnetworks::adapter { + +// Class that adapts nn::IExecution to BnExecution. +class Execution : public BnExecution { + public: + explicit Execution(::android::nn::SharedExecution execution); + + ndk::ScopedAStatus executeSynchronously(int64_t deadlineNs, + ExecutionResult* executionResult) override; + ndk::ScopedAStatus executeFenced(const std::vector<ndk::ScopedFileDescriptor>& waitFor, + int64_t deadlineNs, int64_t durationNs, + FencedExecutionResult* fencedExecutionResult) override; + + protected: + const ::android::nn::SharedExecution kExecution; +}; + +} // namespace aidl::android::hardware::neuralnetworks::adapter + +#endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_EXECUTION_H diff --git a/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/PreparedModel.h b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/PreparedModel.h new file mode 100644 index 0000000000..f92b0bc783 --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/include/nnapi/hal/aidl/PreparedModel.h @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_PREPARED_MDOEL_H +#define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_PREPARED_MDOEL_H + +#include "nnapi/hal/aidl/Adapter.h" + +#include <aidl/android/hardware/neuralnetworks/BnPreparedModel.h> +#include <aidl/android/hardware/neuralnetworks/ExecutionResult.h> +#include <aidl/android/hardware/neuralnetworks/FencedExecutionResult.h> +#include <aidl/android/hardware/neuralnetworks/IBurst.h> +#include <aidl/android/hardware/neuralnetworks/IExecution.h> +#include <aidl/android/hardware/neuralnetworks/Request.h> +#include <android/binder_auto_utils.h> +#include <nnapi/IPreparedModel.h> +#include <nnapi/Types.h> + +#include <memory> +#include <vector> + +// See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface +// lifetimes across processes and for protecting asynchronous calls across AIDL. + +namespace aidl::android::hardware::neuralnetworks::adapter { + +// Class that adapts nn::IPreparedModel to BnPreparedModel. +class PreparedModel : public BnPreparedModel { + public: + explicit PreparedModel(::android::nn::SharedPreparedModel preparedModel); + + ndk::ScopedAStatus executeSynchronously(const Request& request, bool measureTiming, + int64_t deadlineNs, int64_t loopTimeoutDurationNs, + ExecutionResult* executionResult) override; + ndk::ScopedAStatus executeFenced(const Request& request, + const std::vector<ndk::ScopedFileDescriptor>& waitFor, + bool measureTiming, int64_t deadlineNs, + int64_t loopTimeoutDurationNs, int64_t durationNs, + FencedExecutionResult* executionResult) override; + ndk::ScopedAStatus configureExecutionBurst(std::shared_ptr<IBurst>* burst) override; + ndk::ScopedAStatus createReusableExecution(const Request& request, bool measureTiming, + int64_t loopTimeoutDurationNs, + std::shared_ptr<IExecution>* execution) override; + + ::android::nn::SharedPreparedModel getUnderlyingPreparedModel() const; + + protected: + const ::android::nn::SharedPreparedModel kPreparedModel; +}; + +} // namespace aidl::android::hardware::neuralnetworks::adapter + +#endif // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_UTILS_ADAPTER_AIDL_PREPARED_MDOEL_H diff --git a/neuralnetworks/utils/adapter/aidl/src/Adapter.cpp b/neuralnetworks/utils/adapter/aidl/src/Adapter.cpp new file mode 100644 index 0000000000..d0b56e89cc --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/src/Adapter.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Adapter.h" + +#include "Device.h" + +#include <aidl/android/hardware/neuralnetworks/BnDevice.h> +#include <android/binder_interface_utils.h> +#include <nnapi/IDevice.h> +#include <nnapi/Types.h> + +#include <functional> +#include <memory> +#include <thread> + +// See hardware/interfaces/neuralnetworks/utils/README.md for more information on AIDL interface +// lifetimes across processes and for protecting asynchronous calls across AIDL. + +namespace aidl::android::hardware::neuralnetworks::adapter { + +std::shared_ptr<BnDevice> adapt(::android::nn::SharedDevice device, Executor executor) { + return ndk::SharedRefBase::make<Device>(std::move(device), std::move(executor)); +} + +std::shared_ptr<BnDevice> adapt(::android::nn::SharedDevice device) { + Executor defaultExecutor = [](Task task, ::android::nn::OptionalTimePoint /*deadline*/) { + std::thread(std::move(task)).detach(); + }; + return adapt(std::move(device), std::move(defaultExecutor)); +} + +} // namespace aidl::android::hardware::neuralnetworks::adapter diff --git a/neuralnetworks/utils/adapter/aidl/src/Buffer.cpp b/neuralnetworks/utils/adapter/aidl/src/Buffer.cpp new file mode 100644 index 0000000000..c15ab659c5 --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/src/Buffer.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Buffer.h" + +#include <aidl/android/hardware/neuralnetworks/BnBuffer.h> +#include <aidl/android/hardware/neuralnetworks/Memory.h> +#include <android-base/logging.h> +#include <android/binder_auto_utils.h> +#include <nnapi/IBuffer.h> +#include <nnapi/Result.h> +#include <nnapi/Types.h> +#include <nnapi/hal/aidl/Conversions.h> + +namespace aidl::android::hardware::neuralnetworks::adapter { +namespace { + +template <typename Type> +auto convertInput(const Type& object) -> decltype(nn::convert(std::declval<Type>())) { + auto result = nn::convert(object); + if (!result.has_value()) { + result.error().code = nn::ErrorStatus::INVALID_ARGUMENT; + } + return result; +} + +nn::GeneralResult<std::vector<uint32_t>> inputToUnsigned(const std::vector<int32_t>& dims) { + auto result = nn::toUnsigned(dims); + if (!result.has_value()) { + result.error().code = nn::ErrorStatus::INVALID_ARGUMENT; + } + return result; +} + +nn::GeneralResult<void> copyTo(const nn::IBuffer& buffer, const Memory& dst) { + const auto nnDst = NN_TRY(convertInput(dst)); + return buffer.copyTo(nnDst); +} + +nn::GeneralResult<void> copyFrom(const nn::IBuffer& buffer, const Memory& src, + const std::vector<int32_t>& dimensions) { + const auto nnSrc = NN_TRY(convertInput(src)); + const auto nnDims = NN_TRY(inputToUnsigned(dimensions)); + return buffer.copyFrom(nnSrc, nnDims); +} + +} // namespace + +Buffer::Buffer(nn::SharedBuffer buffer) : kBuffer(std::move(buffer)) { + CHECK(kBuffer != nullptr); +} + +ndk::ScopedAStatus Buffer::copyTo(const Memory& dst) { + const auto result = adapter::copyTo(*kBuffer, dst); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Buffer::copyFrom(const Memory& src, const std::vector<int32_t>& dimensions) { + const auto result = adapter::copyFrom(*kBuffer, src, dimensions); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + return ndk::ScopedAStatus::ok(); +} + +} // namespace aidl::android::hardware::neuralnetworks::adapter diff --git a/neuralnetworks/utils/adapter/aidl/src/Burst.cpp b/neuralnetworks/utils/adapter/aidl/src/Burst.cpp new file mode 100644 index 0000000000..4fabb20635 --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/src/Burst.cpp @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Burst.h" + +#include <android-base/logging.h> +#include <android-base/thread_annotations.h> +#include <android/binder_auto_utils.h> +#include <nnapi/IBurst.h> +#include <nnapi/Result.h> +#include <nnapi/Types.h> +#include <nnapi/Validation.h> +#include <nnapi/hal/aidl/Conversions.h> +#include <nnapi/hal/aidl/Utils.h> + +#include <algorithm> +#include <chrono> +#include <memory> +#include <mutex> +#include <unordered_map> +#include <utility> +#include <variant> + +namespace aidl::android::hardware::neuralnetworks::adapter { +namespace { + +using Value = Burst::ThreadSafeMemoryCache::Value; + +template <typename Type> +auto convertInput(const Type& object) -> decltype(nn::convert(std::declval<Type>())) { + auto result = nn::convert(object); + if (!result.has_value()) { + result.error().code = nn::ErrorStatus::INVALID_ARGUMENT; + } + return result; +} + +nn::Duration makeDuration(int64_t durationNs) { + return nn::Duration(std::chrono::nanoseconds(durationNs)); +} + +nn::GeneralResult<nn::OptionalDuration> makeOptionalDuration(int64_t durationNs) { + if (durationNs < -1) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid duration " << durationNs; + } + return durationNs < 0 ? nn::OptionalDuration{} : makeDuration(durationNs); +} + +nn::GeneralResult<nn::OptionalTimePoint> makeOptionalTimePoint(int64_t durationNs) { + if (durationNs < -1) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid time point " << durationNs; + } + return durationNs < 0 ? nn::OptionalTimePoint{} : nn::TimePoint(makeDuration(durationNs)); +} + +std::vector<nn::IBurst::OptionalCacheHold> ensureAllMemoriesAreCached( + nn::Request* request, const std::vector<int64_t>& memoryIdentifierTokens, + const nn::IBurst& burst, const Burst::ThreadSafeMemoryCache& cache) { + std::vector<nn::IBurst::OptionalCacheHold> holds; + holds.reserve(memoryIdentifierTokens.size()); + + for (size_t i = 0; i < memoryIdentifierTokens.size(); ++i) { + const auto& pool = request->pools[i]; + const auto token = memoryIdentifierTokens[i]; + constexpr int64_t kNoToken = -1; + if (token == kNoToken || !std::holds_alternative<nn::SharedMemory>(pool)) { + continue; + } + + const auto& memory = std::get<nn::SharedMemory>(pool); + auto [storedMemory, hold] = cache.add(token, memory, burst); + + request->pools[i] = std::move(storedMemory); + holds.push_back(std::move(hold)); + } + + return holds; +} + +nn::ExecutionResult<ExecutionResult> executeSynchronously( + const nn::IBurst& burst, const Burst::ThreadSafeMemoryCache& cache, const Request& request, + const std::vector<int64_t>& memoryIdentifierTokens, bool measureTiming, int64_t deadlineNs, + int64_t loopTimeoutDurationNs) { + if (request.pools.size() != memoryIdentifierTokens.size()) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) + << "request.pools.size() != memoryIdentifierTokens.size()"; + } + if (!std::all_of(memoryIdentifierTokens.begin(), memoryIdentifierTokens.end(), + [](int64_t token) { return token >= -1; })) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid memoryIdentifierTokens"; + } + + auto nnRequest = NN_TRY(convertInput(request)); + const auto nnMeasureTiming = measureTiming ? nn::MeasureTiming::YES : nn::MeasureTiming::NO; + const auto nnDeadline = NN_TRY(makeOptionalTimePoint(deadlineNs)); + const auto nnLoopTimeoutDuration = NN_TRY(makeOptionalDuration(loopTimeoutDurationNs)); + + const auto hold = ensureAllMemoriesAreCached(&nnRequest, memoryIdentifierTokens, burst, cache); + + const auto result = + burst.execute(nnRequest, nnMeasureTiming, nnDeadline, nnLoopTimeoutDuration); + + if (!result.ok() && result.error().code == nn::ErrorStatus::OUTPUT_INSUFFICIENT_SIZE) { + const auto& [message, code, outputShapes] = result.error(); + return ExecutionResult{.outputSufficientSize = false, + .outputShapes = utils::convert(outputShapes).value(), + .timing = {.timeInDriverNs = -1, .timeOnDeviceNs = -1}}; + } + + const auto& [outputShapes, timing] = NN_TRY(result); + return ExecutionResult{.outputSufficientSize = true, + .outputShapes = utils::convert(outputShapes).value(), + .timing = utils::convert(timing).value()}; +} + +} // namespace + +Value Burst::ThreadSafeMemoryCache::add(int64_t token, const nn::SharedMemory& memory, + const nn::IBurst& burst) const { + std::lock_guard guard(mMutex); + if (const auto it = mCache.find(token); it != mCache.end()) { + return it->second; + } + auto hold = burst.cacheMemory(memory); + auto [it, _] = mCache.emplace(token, std::make_pair(memory, std::move(hold))); + return it->second; +} + +void Burst::ThreadSafeMemoryCache::remove(int64_t token) const { + std::lock_guard guard(mMutex); + mCache.erase(token); +} + +Burst::Burst(nn::SharedBurst burst) : kBurst(std::move(burst)) { + CHECK(kBurst != nullptr); +} + +ndk::ScopedAStatus Burst::executeSynchronously(const Request& request, + const std::vector<int64_t>& memoryIdentifierTokens, + bool measureTiming, int64_t deadlineNs, + int64_t loopTimeoutDurationNs, + ExecutionResult* executionResult) { + auto result = + adapter::executeSynchronously(*kBurst, kMemoryCache, request, memoryIdentifierTokens, + measureTiming, deadlineNs, loopTimeoutDurationNs); + if (!result.has_value()) { + auto [message, code, _] = std::move(result).error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + *executionResult = std::move(result).value(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Burst::releaseMemoryResource(int64_t memoryIdentifierToken) { + if (memoryIdentifierToken < -1) { + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(ErrorStatus::INVALID_ARGUMENT), + "Invalid memoryIdentifierToken"); + } + kMemoryCache.remove(memoryIdentifierToken); + return ndk::ScopedAStatus::ok(); +} + +} // namespace aidl::android::hardware::neuralnetworks::adapter diff --git a/neuralnetworks/utils/adapter/aidl/src/Device.cpp b/neuralnetworks/utils/adapter/aidl/src/Device.cpp new file mode 100644 index 0000000000..763be7f3fa --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/src/Device.cpp @@ -0,0 +1,304 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Device.h" + +#include "Adapter.h" +#include "Buffer.h" +#include "PreparedModel.h" + +#include <aidl/android/hardware/neuralnetworks/BnDevice.h> +#include <aidl/android/hardware/neuralnetworks/BufferDesc.h> +#include <aidl/android/hardware/neuralnetworks/BufferRole.h> +#include <aidl/android/hardware/neuralnetworks/DeviceBuffer.h> +#include <aidl/android/hardware/neuralnetworks/DeviceType.h> +#include <aidl/android/hardware/neuralnetworks/ErrorStatus.h> +#include <aidl/android/hardware/neuralnetworks/ExecutionPreference.h> +#include <aidl/android/hardware/neuralnetworks/Extension.h> +#include <aidl/android/hardware/neuralnetworks/IPreparedModelCallback.h> +#include <aidl/android/hardware/neuralnetworks/IPreparedModelParcel.h> +#include <aidl/android/hardware/neuralnetworks/Model.h> +#include <aidl/android/hardware/neuralnetworks/NumberOfCacheFiles.h> +#include <aidl/android/hardware/neuralnetworks/Priority.h> +#include <android-base/logging.h> +#include <android/binder_auto_utils.h> +#include <android/binder_interface_utils.h> +#include <nnapi/IDevice.h> +#include <nnapi/Result.h> +#include <nnapi/TypeUtils.h> +#include <nnapi/Types.h> +#include <nnapi/hal/aidl/Conversions.h> + +#include <chrono> +#include <memory> +#include <string> +#include <vector> + +namespace aidl::android::hardware::neuralnetworks::adapter { +namespace { + +template <typename Type> +auto convertInput(const Type& object) -> decltype(nn::convert(std::declval<Type>())) { + auto result = nn::convert(object); + if (!result.has_value()) { + result.error().code = nn::ErrorStatus::INVALID_ARGUMENT; + } + return result; +} + +nn::Duration makeDuration(int64_t durationNs) { + return nn::Duration(std::chrono::nanoseconds(durationNs)); +} + +nn::GeneralResult<nn::OptionalTimePoint> makeOptionalTimePoint(int64_t durationNs) { + if (durationNs < -1) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid time point " << durationNs; + } + return durationNs < 0 ? nn::OptionalTimePoint{} : nn::TimePoint(makeDuration(durationNs)); +} + +nn::GeneralResult<nn::CacheToken> convertCacheToken(const std::vector<uint8_t>& token) { + nn::CacheToken nnToken; + if (token.size() != nnToken.size()) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid token"; + } + std::copy(token.begin(), token.end(), nnToken.begin()); + return nnToken; +} + +nn::GeneralResult<nn::SharedPreparedModel> downcast(const IPreparedModelParcel& preparedModel) { + if (preparedModel.preparedModel == nullptr) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "preparedModel is nullptr"; + } + if (preparedModel.preparedModel->isRemote()) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Cannot convert remote models"; + } + + // This static_cast is safe because adapter::PreparedModel is the only class that implements + // the IPreparedModel interface in the adapter service code. + const auto* casted = static_cast<const PreparedModel*>(preparedModel.preparedModel.get()); + return casted->getUnderlyingPreparedModel(); +} + +nn::GeneralResult<std::vector<nn::SharedPreparedModel>> downcastAll( + const std::vector<IPreparedModelParcel>& preparedModels) { + std::vector<nn::SharedPreparedModel> canonical; + canonical.reserve(preparedModels.size()); + for (const auto& preparedModel : preparedModels) { + canonical.push_back(NN_TRY(downcast(preparedModel))); + } + return canonical; +} + +nn::GeneralResult<DeviceBuffer> allocate(const nn::IDevice& device, const BufferDesc& desc, + const std::vector<IPreparedModelParcel>& preparedModels, + const std::vector<BufferRole>& inputRoles, + const std::vector<BufferRole>& outputRoles) { + auto nnDesc = NN_TRY(convertInput(desc)); + auto nnPreparedModels = NN_TRY(downcastAll(preparedModels)); + auto nnInputRoles = NN_TRY(convertInput(inputRoles)); + auto nnOutputRoles = NN_TRY(convertInput(outputRoles)); + + auto buffer = NN_TRY(device.allocate(nnDesc, nnPreparedModels, nnInputRoles, nnOutputRoles)); + CHECK(buffer != nullptr); + + const nn::Request::MemoryDomainToken token = buffer->getToken(); + auto aidlBuffer = ndk::SharedRefBase::make<Buffer>(std::move(buffer)); + return DeviceBuffer{.buffer = std::move(aidlBuffer), .token = static_cast<int32_t>(token)}; +} + +nn::GeneralResult<std::vector<bool>> getSupportedOperations(const nn::IDevice& device, + const Model& model) { + const auto nnModel = NN_TRY(convertInput(model)); + return device.getSupportedOperations(nnModel); +} + +using PrepareModelResult = nn::GeneralResult<nn::SharedPreparedModel>; + +std::shared_ptr<PreparedModel> adaptPreparedModel(nn::SharedPreparedModel preparedModel) { + if (preparedModel == nullptr) { + return nullptr; + } + return ndk::SharedRefBase::make<PreparedModel>(std::move(preparedModel)); +} + +void notify(IPreparedModelCallback* callback, PrepareModelResult result) { + if (!result.has_value()) { + const auto& [message, status] = result.error(); + LOG(ERROR) << message; + const auto aidlCode = utils::convert(status).value_or(ErrorStatus::GENERAL_FAILURE); + callback->notify(aidlCode, nullptr); + } else { + auto preparedModel = std::move(result).value(); + auto aidlPreparedModel = adaptPreparedModel(std::move(preparedModel)); + callback->notify(ErrorStatus::NONE, std::move(aidlPreparedModel)); + } +} + +nn::GeneralResult<void> prepareModel(const nn::SharedDevice& device, const Executor& executor, + const Model& model, ExecutionPreference preference, + Priority priority, int64_t deadlineNs, + const std::vector<ndk::ScopedFileDescriptor>& modelCache, + const std::vector<ndk::ScopedFileDescriptor>& dataCache, + const std::vector<uint8_t>& token, + const std::shared_ptr<IPreparedModelCallback>& callback) { + if (callback.get() == nullptr) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid callback"; + } + + auto nnModel = NN_TRY(convertInput(model)); + const auto nnPreference = NN_TRY(convertInput(preference)); + const auto nnPriority = NN_TRY(convertInput(priority)); + const auto nnDeadline = NN_TRY(makeOptionalTimePoint(deadlineNs)); + auto nnModelCache = NN_TRY(convertInput(modelCache)); + auto nnDataCache = NN_TRY(convertInput(dataCache)); + const auto nnToken = NN_TRY(convertCacheToken(token)); + + Task task = [device, nnModel = std::move(nnModel), nnPreference, nnPriority, nnDeadline, + nnModelCache = std::move(nnModelCache), nnDataCache = std::move(nnDataCache), + nnToken, callback] { + auto result = device->prepareModel(nnModel, nnPreference, nnPriority, nnDeadline, + nnModelCache, nnDataCache, nnToken); + notify(callback.get(), std::move(result)); + }; + executor(std::move(task), nnDeadline); + + return {}; +} + +nn::GeneralResult<void> prepareModelFromCache( + const nn::SharedDevice& device, const Executor& executor, int64_t deadlineNs, + const std::vector<ndk::ScopedFileDescriptor>& modelCache, + const std::vector<ndk::ScopedFileDescriptor>& dataCache, const std::vector<uint8_t>& token, + const std::shared_ptr<IPreparedModelCallback>& callback) { + if (callback.get() == nullptr) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid callback"; + } + + const auto nnDeadline = NN_TRY(makeOptionalTimePoint(deadlineNs)); + auto nnModelCache = NN_TRY(convertInput(modelCache)); + auto nnDataCache = NN_TRY(convertInput(dataCache)); + const auto nnToken = NN_TRY(convertCacheToken(token)); + + auto task = [device, nnDeadline, nnModelCache = std::move(nnModelCache), + nnDataCache = std::move(nnDataCache), nnToken, callback] { + auto result = device->prepareModelFromCache(nnDeadline, nnModelCache, nnDataCache, nnToken); + notify(callback.get(), std::move(result)); + }; + executor(std::move(task), nnDeadline); + + return {}; +} + +} // namespace + +Device::Device(::android::nn::SharedDevice device, Executor executor) + : kDevice(std::move(device)), kExecutor(std::move(executor)) { + CHECK(kDevice != nullptr); + CHECK(kExecutor != nullptr); +} + +ndk::ScopedAStatus Device::allocate(const BufferDesc& desc, + const std::vector<IPreparedModelParcel>& preparedModels, + const std::vector<BufferRole>& inputRoles, + const std::vector<BufferRole>& outputRoles, + DeviceBuffer* buffer) { + auto result = adapter::allocate(*kDevice, desc, preparedModels, inputRoles, outputRoles); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + *buffer = std::move(result).value(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Device::getCapabilities(Capabilities* capabilities) { + *capabilities = utils::convert(kDevice->getCapabilities()).value(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Device::getNumberOfCacheFilesNeeded(NumberOfCacheFiles* numberOfCacheFiles) { + const auto [numModelCache, numDataCache] = kDevice->getNumberOfCacheFilesNeeded(); + *numberOfCacheFiles = NumberOfCacheFiles{.numModelCache = static_cast<int32_t>(numModelCache), + .numDataCache = static_cast<int32_t>(numDataCache)}; + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Device::getSupportedExtensions(std::vector<Extension>* extensions) { + *extensions = utils::convert(kDevice->getSupportedExtensions()).value(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Device::getSupportedOperations(const Model& model, + std::vector<bool>* supported) { + auto result = adapter::getSupportedOperations(*kDevice, model); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + *supported = std::move(result).value(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Device::getType(DeviceType* deviceType) { + *deviceType = utils::convert(kDevice->getType()).value(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Device::getVersionString(std::string* version) { + *version = kDevice->getVersionString(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Device::prepareModel(const Model& model, ExecutionPreference preference, + Priority priority, int64_t deadlineNs, + const std::vector<ndk::ScopedFileDescriptor>& modelCache, + const std::vector<ndk::ScopedFileDescriptor>& dataCache, + const std::vector<uint8_t>& token, + const std::shared_ptr<IPreparedModelCallback>& callback) { + const auto result = adapter::prepareModel(kDevice, kExecutor, model, preference, priority, + deadlineNs, modelCache, dataCache, token, callback); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + callback->notify(aidlCode, nullptr); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Device::prepareModelFromCache( + int64_t deadlineNs, const std::vector<ndk::ScopedFileDescriptor>& modelCache, + const std::vector<ndk::ScopedFileDescriptor>& dataCache, const std::vector<uint8_t>& token, + const std::shared_ptr<IPreparedModelCallback>& callback) { + const auto result = adapter::prepareModelFromCache(kDevice, kExecutor, deadlineNs, modelCache, + dataCache, token, callback); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + callback->notify(aidlCode, nullptr); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + return ndk::ScopedAStatus::ok(); +} + +} // namespace aidl::android::hardware::neuralnetworks::adapter diff --git a/neuralnetworks/utils/adapter/aidl/src/PreparedModel.cpp b/neuralnetworks/utils/adapter/aidl/src/PreparedModel.cpp new file mode 100644 index 0000000000..5cab62c625 --- /dev/null +++ b/neuralnetworks/utils/adapter/aidl/src/PreparedModel.cpp @@ -0,0 +1,324 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "PreparedModel.h" + +#include "Burst.h" +#include "Execution.h" + +#include <aidl/android/hardware/neuralnetworks/BnFencedExecutionCallback.h> +#include <aidl/android/hardware/neuralnetworks/BnPreparedModel.h> +#include <aidl/android/hardware/neuralnetworks/ExecutionResult.h> +#include <aidl/android/hardware/neuralnetworks/FencedExecutionResult.h> +#include <aidl/android/hardware/neuralnetworks/IBurst.h> +#include <aidl/android/hardware/neuralnetworks/Request.h> +#include <android-base/logging.h> +#include <android/binder_auto_utils.h> +#include <nnapi/IExecution.h> +#include <nnapi/IPreparedModel.h> +#include <nnapi/Result.h> +#include <nnapi/SharedMemory.h> +#include <nnapi/Types.h> +#include <nnapi/Validation.h> +#include <nnapi/hal/aidl/Conversions.h> +#include <nnapi/hal/aidl/Utils.h> + +#include <memory> +#include <utility> +#include <vector> + +namespace aidl::android::hardware::neuralnetworks::adapter { +namespace { + +class FencedExecutionCallback : public BnFencedExecutionCallback { + public: + FencedExecutionCallback(nn::ExecuteFencedInfoCallback callback) + : kCallback(std::move(callback)) {} + + ndk::ScopedAStatus getExecutionInfo(Timing* timingLaunched, Timing* timingFenced, + ErrorStatus* errorStatus) override { + const auto result = kCallback(); + if (result.ok()) { + const auto& [nnTimingLaunched, nnTimingFenced] = result.value(); + *timingLaunched = utils::convert(nnTimingLaunched).value(); + *timingFenced = utils::convert(nnTimingFenced).value(); + *errorStatus = ErrorStatus::NONE; + } else { + constexpr auto kNoTiming = Timing{.timeOnDeviceNs = -1, .timeInDriverNs = -1}; + const auto& [message, code] = result.error(); + LOG(ERROR) << "getExecutionInfo failed with " << code << ": " << message; + const auto aidlStatus = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + *timingLaunched = kNoTiming; + *timingFenced = kNoTiming; + *errorStatus = aidlStatus; + } + return ndk::ScopedAStatus::ok(); + } + + private: + const nn::ExecuteFencedInfoCallback kCallback; +}; + +template <typename Type> +auto convertInput(const Type& object) -> decltype(nn::convert(std::declval<Type>())) { + auto result = nn::convert(object); + if (!result.has_value()) { + result.error().code = nn::ErrorStatus::INVALID_ARGUMENT; + } + return result; +} + +nn::GeneralResult<std::vector<nn::SyncFence>> convertSyncFences( + const std::vector<ndk::ScopedFileDescriptor>& waitFor) { + auto handles = NN_TRY(convertInput(waitFor)); + + constexpr auto valid = [](const nn::SharedHandle& handle) { + return handle != nullptr && handle->ok(); + }; + if (!std::all_of(handles.begin(), handles.end(), valid)) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid sync fence"; + } + + std::vector<nn::SyncFence> syncFences; + syncFences.reserve(waitFor.size()); + for (auto& handle : handles) { + syncFences.push_back(nn::SyncFence::create(std::move(handle)).value()); + } + return syncFences; +} + +nn::Duration makeDuration(int64_t durationNs) { + return nn::Duration(std::chrono::nanoseconds(durationNs)); +} + +nn::GeneralResult<nn::OptionalDuration> makeOptionalDuration(int64_t durationNs) { + if (durationNs < -1) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid duration " << durationNs; + } + return durationNs < 0 ? nn::OptionalDuration{} : makeDuration(durationNs); +} + +nn::GeneralResult<nn::OptionalTimePoint> makeOptionalTimePoint(int64_t durationNs) { + if (durationNs < -1) { + return NN_ERROR(nn::ErrorStatus::INVALID_ARGUMENT) << "Invalid time point " << durationNs; + } + return durationNs < 0 ? nn::OptionalTimePoint{} : nn::TimePoint(makeDuration(durationNs)); +} + +nn::ExecutionResult<ExecutionResult> executeSynchronously(const nn::IPreparedModel& preparedModel, + const Request& request, + bool measureTiming, int64_t deadlineNs, + int64_t loopTimeoutDurationNs) { + const auto nnRequest = NN_TRY(convertInput(request)); + const auto nnMeasureTiming = measureTiming ? nn::MeasureTiming::YES : nn::MeasureTiming::NO; + const auto nnDeadline = NN_TRY(makeOptionalTimePoint(deadlineNs)); + const auto nnLoopTimeoutDuration = NN_TRY(makeOptionalDuration(loopTimeoutDurationNs)); + + const auto result = + preparedModel.execute(nnRequest, nnMeasureTiming, nnDeadline, nnLoopTimeoutDuration); + + if (!result.ok() && result.error().code == nn::ErrorStatus::OUTPUT_INSUFFICIENT_SIZE) { + const auto& [message, code, outputShapes] = result.error(); + LOG(ERROR) << "executeSynchronously failed with " << code << ": " << message; + return ExecutionResult{.outputSufficientSize = false, + .outputShapes = utils::convert(outputShapes).value(), + .timing = {.timeInDriverNs = -1, .timeOnDeviceNs = -1}}; + } + + const auto& [outputShapes, timing] = NN_TRY(result); + return ExecutionResult{.outputSufficientSize = true, + .outputShapes = utils::convert(outputShapes).value(), + .timing = utils::convert(timing).value()}; +} + +nn::GeneralResult<FencedExecutionResult> executeFenced( + const nn::IPreparedModel& preparedModel, const Request& request, + const std::vector<ndk::ScopedFileDescriptor>& waitFor, bool measureTiming, + int64_t deadlineNs, int64_t loopTimeoutDurationNs, int64_t durationNs) { + const auto nnRequest = NN_TRY(convertInput(request)); + const auto nnWaitFor = NN_TRY(convertSyncFences(waitFor)); + const auto nnMeasureTiming = measureTiming ? nn::MeasureTiming::YES : nn::MeasureTiming::NO; + const auto nnDeadline = NN_TRY(makeOptionalTimePoint(deadlineNs)); + const auto nnLoopTimeoutDuration = NN_TRY(makeOptionalDuration(loopTimeoutDurationNs)); + const auto nnDuration = NN_TRY(makeOptionalDuration(durationNs)); + + auto [syncFence, executeFencedInfoCallback] = NN_TRY(preparedModel.executeFenced( + nnRequest, nnWaitFor, nnMeasureTiming, nnDeadline, nnLoopTimeoutDuration, nnDuration)); + + ndk::ScopedFileDescriptor fileDescriptor; + if (syncFence.hasFd()) { + auto uniqueFd = NN_TRY(nn::dupFd(syncFence.getFd())); + fileDescriptor = ndk::ScopedFileDescriptor(uniqueFd.release()); + } + + return FencedExecutionResult{.callback = ndk::SharedRefBase::make<FencedExecutionCallback>( + std::move(executeFencedInfoCallback)), + .syncFence = std::move(fileDescriptor)}; +} + +nn::GeneralResult<nn::SharedExecution> createReusableExecution( + const nn::IPreparedModel& preparedModel, const Request& request, bool measureTiming, + int64_t loopTimeoutDurationNs) { + const auto nnRequest = NN_TRY(convertInput(request)); + const auto nnMeasureTiming = measureTiming ? nn::MeasureTiming::YES : nn::MeasureTiming::NO; + const auto nnLoopTimeoutDuration = NN_TRY(makeOptionalDuration(loopTimeoutDurationNs)); + return preparedModel.createReusableExecution(nnRequest, nnMeasureTiming, nnLoopTimeoutDuration); +} + +nn::ExecutionResult<ExecutionResult> executeSynchronously(const nn::IExecution& execution, + int64_t deadlineNs) { + const auto nnDeadline = NN_TRY(makeOptionalTimePoint(deadlineNs)); + + const auto result = execution.compute(nnDeadline); + + if (!result.ok() && result.error().code == nn::ErrorStatus::OUTPUT_INSUFFICIENT_SIZE) { + const auto& [message, code, outputShapes] = result.error(); + LOG(ERROR) << "executeSynchronously failed with " << code << ": " << message; + return ExecutionResult{.outputSufficientSize = false, + .outputShapes = utils::convert(outputShapes).value(), + .timing = {.timeInDriverNs = -1, .timeOnDeviceNs = -1}}; + } + + const auto& [outputShapes, timing] = NN_TRY(result); + return ExecutionResult{.outputSufficientSize = true, + .outputShapes = utils::convert(outputShapes).value(), + .timing = utils::convert(timing).value()}; +} + +nn::GeneralResult<FencedExecutionResult> executeFenced( + const nn::IExecution& execution, const std::vector<ndk::ScopedFileDescriptor>& waitFor, + int64_t deadlineNs, int64_t durationNs) { + const auto nnWaitFor = NN_TRY(convertSyncFences(waitFor)); + const auto nnDeadline = NN_TRY(makeOptionalTimePoint(deadlineNs)); + const auto nnDuration = NN_TRY(makeOptionalDuration(durationNs)); + + auto [syncFence, executeFencedInfoCallback] = + NN_TRY(execution.computeFenced(nnWaitFor, nnDeadline, nnDuration)); + + ndk::ScopedFileDescriptor fileDescriptor; + if (syncFence.hasFd()) { + auto uniqueFd = NN_TRY(nn::dupFd(syncFence.getFd())); + fileDescriptor = ndk::ScopedFileDescriptor(uniqueFd.release()); + } + + return FencedExecutionResult{.callback = ndk::SharedRefBase::make<FencedExecutionCallback>( + std::move(executeFencedInfoCallback)), + .syncFence = std::move(fileDescriptor)}; +} + +} // namespace + +PreparedModel::PreparedModel(nn::SharedPreparedModel preparedModel) + : kPreparedModel(std::move(preparedModel)) { + CHECK(kPreparedModel != nullptr); +} + +ndk::ScopedAStatus PreparedModel::executeSynchronously(const Request& request, bool measureTiming, + int64_t deadlineNs, + int64_t loopTimeoutDurationNs, + ExecutionResult* executionResult) { + auto result = adapter::executeSynchronously(*kPreparedModel, request, measureTiming, deadlineNs, + loopTimeoutDurationNs); + if (!result.has_value()) { + const auto& [message, code, _] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + *executionResult = std::move(result).value(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus PreparedModel::executeFenced( + const Request& request, const std::vector<ndk::ScopedFileDescriptor>& waitFor, + bool measureTiming, int64_t deadlineNs, int64_t loopTimeoutDurationNs, int64_t durationNs, + FencedExecutionResult* executionResult) { + auto result = adapter::executeFenced(*kPreparedModel, request, waitFor, measureTiming, + deadlineNs, loopTimeoutDurationNs, durationNs); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + *executionResult = std::move(result).value(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus PreparedModel::configureExecutionBurst(std::shared_ptr<IBurst>* burst) { + auto result = kPreparedModel->configureExecutionBurst(); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + *burst = ndk::SharedRefBase::make<Burst>(std::move(result).value()); + return ndk::ScopedAStatus::ok(); +} + +nn::SharedPreparedModel PreparedModel::getUnderlyingPreparedModel() const { + return kPreparedModel; +} + +ndk::ScopedAStatus PreparedModel::createReusableExecution(const Request& request, + bool measureTiming, + int64_t loopTimeoutDurationNs, + std::shared_ptr<IExecution>* execution) { + auto result = adapter::createReusableExecution(*kPreparedModel, request, measureTiming, + loopTimeoutDurationNs); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + *execution = ndk::SharedRefBase::make<Execution>(std::move(result).value()); + return ndk::ScopedAStatus::ok(); +} + +Execution::Execution(nn::SharedExecution execution) : kExecution(std::move(execution)) { + CHECK(kExecution != nullptr); +} + +ndk::ScopedAStatus Execution::executeSynchronously(int64_t deadlineNs, + ExecutionResult* executionResult) { + auto result = adapter::executeSynchronously(*kExecution, deadlineNs); + if (!result.has_value()) { + const auto& [message, code, _] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + *executionResult = std::move(result).value(); + return ndk::ScopedAStatus::ok(); +} + +ndk::ScopedAStatus Execution::executeFenced(const std::vector<ndk::ScopedFileDescriptor>& waitFor, + int64_t deadlineNs, int64_t durationNs, + FencedExecutionResult* executionResult) { + auto result = adapter::executeFenced(*kExecution, waitFor, deadlineNs, durationNs); + if (!result.has_value()) { + const auto& [message, code] = result.error(); + const auto aidlCode = utils::convert(code).value_or(ErrorStatus::GENERAL_FAILURE); + return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage( + static_cast<int32_t>(aidlCode), message.c_str()); + } + *executionResult = std::move(result).value(); + return ndk::ScopedAStatus::ok(); +} + +} // namespace aidl::android::hardware::neuralnetworks::adapter diff --git a/neuralnetworks/utils/adapter/Android.bp b/neuralnetworks/utils/adapter/hidl/Android.bp index d073106a5f..d073106a5f 100644 --- a/neuralnetworks/utils/adapter/Android.bp +++ b/neuralnetworks/utils/adapter/hidl/Android.bp diff --git a/neuralnetworks/utils/adapter/include/nnapi/hal/Adapter.h b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/Adapter.h index da00a090ed..6fba4abe7d 100644 --- a/neuralnetworks/utils/adapter/include/nnapi/hal/Adapter.h +++ b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/Adapter.h @@ -20,7 +20,6 @@ #include <android/hardware/neuralnetworks/1.3/IDevice.h> #include <nnapi/IDevice.h> #include <nnapi/Types.h> -#include <sys/types.h> #include <functional> #include <memory> @@ -37,10 +36,12 @@ using Task = std::function<void()>; /** * A type-erased executor which executes a task asynchronously. * - * This executor is also provided with an Application ID (Android User ID) and an optional deadline - * for when the caller expects is the upper bound for the amount of time to complete the task. + * This executor is also provided an optional deadline for when the caller expects is the upper + * bound for the amount of time to complete the task. If needed, the Executor can retrieve the + * Application ID (Android User ID) by calling IPCThreadState::self()->getCallingUid() in + * hwbinder/IPCThreadState.h. */ -using Executor = std::function<void(Task, uid_t, nn::OptionalTimePoint)>; +using Executor = std::function<void(Task, nn::OptionalTimePoint)>; /** * Adapt an NNAPI canonical interface object to a HIDL NN HAL interface object. diff --git a/neuralnetworks/utils/adapter/include/nnapi/hal/Buffer.h b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/Buffer.h index e53c7d4f09..e53c7d4f09 100644 --- a/neuralnetworks/utils/adapter/include/nnapi/hal/Buffer.h +++ b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/Buffer.h diff --git a/neuralnetworks/utils/adapter/include/nnapi/hal/Burst.h b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/Burst.h index a3aa706a0c..a3aa706a0c 100644 --- a/neuralnetworks/utils/adapter/include/nnapi/hal/Burst.h +++ b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/Burst.h diff --git a/neuralnetworks/utils/adapter/include/nnapi/hal/Device.h b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/Device.h index 148d0a0341..148d0a0341 100644 --- a/neuralnetworks/utils/adapter/include/nnapi/hal/Device.h +++ b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/Device.h diff --git a/neuralnetworks/utils/adapter/include/nnapi/hal/PreparedModel.h b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/PreparedModel.h index 65763b8d19..9482b0d512 100644 --- a/neuralnetworks/utils/adapter/include/nnapi/hal/PreparedModel.h +++ b/neuralnetworks/utils/adapter/hidl/include/nnapi/hal/PreparedModel.h @@ -39,7 +39,7 @@ namespace android::hardware::neuralnetworks::adapter { // Class that adapts nn::IPreparedModel to V1_3::IPreparedModel. class PreparedModel final : public V1_3::IPreparedModel { public: - PreparedModel(nn::SharedPreparedModel preparedModel, Executor executor, uid_t userId); + PreparedModel(nn::SharedPreparedModel preparedModel, Executor executor); Return<V1_0::ErrorStatus> execute(const V1_0::Request& request, const sp<V1_0::IExecutionCallback>& callback) override; @@ -71,7 +71,6 @@ class PreparedModel final : public V1_3::IPreparedModel { private: const nn::SharedPreparedModel kPreparedModel; const Executor kExecutor; - const uid_t kUserId; }; } // namespace android::hardware::neuralnetworks::adapter diff --git a/neuralnetworks/utils/adapter/src/Adapter.cpp b/neuralnetworks/utils/adapter/hidl/src/Adapter.cpp index d6f53f05a5..782e815a83 100644 --- a/neuralnetworks/utils/adapter/src/Adapter.cpp +++ b/neuralnetworks/utils/adapter/hidl/src/Adapter.cpp @@ -21,7 +21,6 @@ #include <android/hardware/neuralnetworks/1.3/IDevice.h> #include <nnapi/IDevice.h> #include <nnapi/Types.h> -#include <sys/types.h> #include <functional> #include <memory> @@ -37,7 +36,7 @@ sp<V1_3::IDevice> adapt(nn::SharedDevice device, Executor executor) { } sp<V1_3::IDevice> adapt(nn::SharedDevice device) { - Executor defaultExecutor = [](Task task, uid_t /*uid*/, nn::OptionalTimePoint /*deadline*/) { + Executor defaultExecutor = [](Task task, nn::OptionalTimePoint /*deadline*/) { std::thread(std::move(task)).detach(); }; return adapt(std::move(device), std::move(defaultExecutor)); diff --git a/neuralnetworks/utils/adapter/src/Buffer.cpp b/neuralnetworks/utils/adapter/hidl/src/Buffer.cpp index 3a04bf6b79..3a04bf6b79 100644 --- a/neuralnetworks/utils/adapter/src/Buffer.cpp +++ b/neuralnetworks/utils/adapter/hidl/src/Buffer.cpp diff --git a/neuralnetworks/utils/adapter/src/Burst.cpp b/neuralnetworks/utils/adapter/hidl/src/Burst.cpp index 8b2e1dd465..8b2e1dd465 100644 --- a/neuralnetworks/utils/adapter/src/Burst.cpp +++ b/neuralnetworks/utils/adapter/hidl/src/Burst.cpp diff --git a/neuralnetworks/utils/adapter/src/Device.cpp b/neuralnetworks/utils/adapter/hidl/src/Device.cpp index 96142c3577..4993a80a93 100644 --- a/neuralnetworks/utils/adapter/src/Device.cpp +++ b/neuralnetworks/utils/adapter/hidl/src/Device.cpp @@ -28,7 +28,6 @@ #include <android/hardware/neuralnetworks/1.3/IDevice.h> #include <android/hardware/neuralnetworks/1.3/IPreparedModelCallback.h> #include <android/hardware/neuralnetworks/1.3/types.h> -#include <hwbinder/IPCThreadState.h> #include <nnapi/IBuffer.h> #include <nnapi/IDevice.h> #include <nnapi/IPreparedModel.h> @@ -43,7 +42,6 @@ #include <nnapi/hal/1.2/Utils.h> #include <nnapi/hal/1.3/Conversions.h> #include <nnapi/hal/1.3/Utils.h> -#include <sys/types.h> #include <memory> @@ -64,12 +62,11 @@ auto convertInput(const Type& object) -> decltype(nn::convert(std::declval<Type> using PrepareModelResult = nn::GeneralResult<nn::SharedPreparedModel>; -sp<PreparedModel> adaptPreparedModel(nn::SharedPreparedModel preparedModel, Executor executor, - uid_t userId) { +sp<PreparedModel> adaptPreparedModel(nn::SharedPreparedModel preparedModel, Executor executor) { if (preparedModel == nullptr) { return nullptr; } - return sp<PreparedModel>::make(std::move(preparedModel), std::move(executor), userId); + return sp<PreparedModel>::make(std::move(preparedModel), std::move(executor)); } void notify(V1_0::IPreparedModelCallback* callback, nn::ErrorStatus status, @@ -108,15 +105,14 @@ void notify(V1_3::IPreparedModelCallback* callback, nn::ErrorStatus status, } template <typename CallbackType> -void notify(CallbackType* callback, PrepareModelResult result, Executor executor, uid_t userId) { +void notify(CallbackType* callback, PrepareModelResult result, Executor executor) { if (!result.has_value()) { const auto [message, status] = std::move(result).error(); LOG(ERROR) << message; notify(callback, status, nullptr); } else { auto preparedModel = std::move(result).value(); - auto hidlPreparedModel = - adaptPreparedModel(std::move(preparedModel), std::move(executor), userId); + auto hidlPreparedModel = adaptPreparedModel(std::move(preparedModel), std::move(executor)); notify(callback, nn::ErrorStatus::NONE, std::move(hidlPreparedModel)); } } @@ -137,13 +133,12 @@ nn::GeneralResult<void> prepareModel(const nn::SharedDevice& device, const Execu auto nnModel = NN_TRY(convertInput(model)); - const uid_t userId = hardware::IPCThreadState::self()->getCallingUid(); - Task task = [device, nnModel = std::move(nnModel), userId, executor, callback] { + Task task = [device, nnModel = std::move(nnModel), executor, callback] { auto result = device->prepareModel(nnModel, nn::ExecutionPreference::DEFAULT, nn::Priority::DEFAULT, {}, {}, {}, {}); - notify(callback.get(), std::move(result), executor, userId); + notify(callback.get(), std::move(result), executor); }; - executor(std::move(task), userId, {}); + executor(std::move(task), {}); return {}; } @@ -159,13 +154,12 @@ nn::GeneralResult<void> prepareModel_1_1(const nn::SharedDevice& device, const E auto nnModel = NN_TRY(convertInput(model)); const auto nnPreference = NN_TRY(convertInput(preference)); - const uid_t userId = hardware::IPCThreadState::self()->getCallingUid(); - Task task = [device, nnModel = std::move(nnModel), nnPreference, userId, executor, callback] { + Task task = [device, nnModel = std::move(nnModel), nnPreference, executor, callback] { auto result = device->prepareModel(nnModel, nnPreference, nn::Priority::DEFAULT, {}, {}, {}, {}); - notify(callback.get(), std::move(result), executor, userId); + notify(callback.get(), std::move(result), executor); }; - executor(std::move(task), userId, {}); + executor(std::move(task), {}); return {}; } @@ -187,15 +181,14 @@ nn::GeneralResult<void> prepareModel_1_2(const nn::SharedDevice& device, const E auto nnDataCache = NN_TRY(convertInput(dataCache)); const auto nnToken = nn::CacheToken(token); - const uid_t userId = hardware::IPCThreadState::self()->getCallingUid(); Task task = [device, nnModel = std::move(nnModel), nnPreference, nnModelCache = std::move(nnModelCache), nnDataCache = std::move(nnDataCache), - nnToken, userId, executor, callback] { + nnToken, executor, callback] { auto result = device->prepareModel(nnModel, nnPreference, nn::Priority::DEFAULT, {}, nnModelCache, nnDataCache, nnToken); - notify(callback.get(), std::move(result), executor, userId); + notify(callback.get(), std::move(result), executor); }; - executor(std::move(task), userId, {}); + executor(std::move(task), {}); return {}; } @@ -218,15 +211,14 @@ nn::GeneralResult<void> prepareModel_1_3( auto nnDataCache = NN_TRY(convertInput(dataCache)); const auto nnToken = nn::CacheToken(token); - const uid_t userId = hardware::IPCThreadState::self()->getCallingUid(); Task task = [device, nnModel = std::move(nnModel), nnPreference, nnPriority, nnDeadline, nnModelCache = std::move(nnModelCache), nnDataCache = std::move(nnDataCache), - nnToken, userId, executor, callback] { + nnToken, executor, callback] { auto result = device->prepareModel(nnModel, nnPreference, nnPriority, nnDeadline, nnModelCache, nnDataCache, nnToken); - notify(callback.get(), std::move(result), executor, userId); + notify(callback.get(), std::move(result), executor); }; - executor(std::move(task), userId, nnDeadline); + executor(std::move(task), nnDeadline); return {}; } @@ -245,13 +237,12 @@ nn::GeneralResult<void> prepareModelFromCache(const nn::SharedDevice& device, auto nnDataCache = NN_TRY(convertInput(dataCache)); const auto nnToken = nn::CacheToken(token); - const uid_t userId = hardware::IPCThreadState::self()->getCallingUid(); Task task = [device, nnModelCache = std::move(nnModelCache), - nnDataCache = std::move(nnDataCache), nnToken, userId, executor, callback] { + nnDataCache = std::move(nnDataCache), nnToken, executor, callback] { auto result = device->prepareModelFromCache({}, nnModelCache, nnDataCache, nnToken); - notify(callback.get(), std::move(result), executor, userId); + notify(callback.get(), std::move(result), executor); }; - executor(std::move(task), userId, {}); + executor(std::move(task), {}); return {}; } @@ -270,13 +261,12 @@ nn::GeneralResult<void> prepareModelFromCache_1_3( auto nnDataCache = NN_TRY(convertInput(dataCache)); const auto nnToken = nn::CacheToken(token); - const uid_t userId = hardware::IPCThreadState::self()->getCallingUid(); auto task = [device, nnDeadline, nnModelCache = std::move(nnModelCache), - nnDataCache = std::move(nnDataCache), nnToken, userId, executor, callback] { + nnDataCache = std::move(nnDataCache), nnToken, executor, callback] { auto result = device->prepareModelFromCache(nnDeadline, nnModelCache, nnDataCache, nnToken); - notify(callback.get(), std::move(result), executor, userId); + notify(callback.get(), std::move(result), executor); }; - executor(std::move(task), userId, nnDeadline); + executor(std::move(task), nnDeadline); return {}; } diff --git a/neuralnetworks/utils/adapter/src/PreparedModel.cpp b/neuralnetworks/utils/adapter/hidl/src/PreparedModel.cpp index a14e782b9b..71060d5ca7 100644 --- a/neuralnetworks/utils/adapter/src/PreparedModel.cpp +++ b/neuralnetworks/utils/adapter/hidl/src/PreparedModel.cpp @@ -28,7 +28,6 @@ #include <android/hardware/neuralnetworks/1.3/IFencedExecutionCallback.h> #include <android/hardware/neuralnetworks/1.3/IPreparedModel.h> #include <android/hardware/neuralnetworks/1.3/types.h> -#include <hwbinder/IPCThreadState.h> #include <nnapi/IPreparedModel.h> #include <nnapi/TypeUtils.h> #include <nnapi/Types.h> @@ -37,7 +36,6 @@ #include <nnapi/hal/1.2/Utils.h> #include <nnapi/hal/1.3/Conversions.h> #include <nnapi/hal/1.3/Utils.h> -#include <sys/types.h> #include <memory> #include <thread> @@ -145,7 +143,7 @@ void notify(CallbackType* callback, ExecutionResult result) { } } -nn::GeneralResult<void> execute(const nn::SharedPreparedModel& preparedModel, uid_t userId, +nn::GeneralResult<void> execute(const nn::SharedPreparedModel& preparedModel, const Executor& executor, const V1_0::Request& request, const sp<V1_0::IExecutionCallback>& callback) { if (callback.get() == nullptr) { @@ -164,12 +162,12 @@ nn::GeneralResult<void> execute(const nn::SharedPreparedModel& preparedModel, ui auto result = preparedModel->execute(nnRequest, nn::MeasureTiming::NO, {}, {}); notify(callback.get(), std::move(result)); }; - executor(std::move(task), userId, {}); + executor(std::move(task), {}); return {}; } -nn::GeneralResult<void> execute_1_2(const nn::SharedPreparedModel& preparedModel, uid_t userId, +nn::GeneralResult<void> execute_1_2(const nn::SharedPreparedModel& preparedModel, const Executor& executor, const V1_0::Request& request, V1_2::MeasureTiming measure, const sp<V1_2::IExecutionCallback>& callback) { @@ -190,12 +188,12 @@ nn::GeneralResult<void> execute_1_2(const nn::SharedPreparedModel& preparedModel auto result = preparedModel->execute(nnRequest, nnMeasure, {}, {}); notify(callback.get(), std::move(result)); }; - executor(std::move(task), userId, {}); + executor(std::move(task), {}); return {}; } -nn::GeneralResult<void> execute_1_3(const nn::SharedPreparedModel& preparedModel, uid_t userId, +nn::GeneralResult<void> execute_1_3(const nn::SharedPreparedModel& preparedModel, const Executor& executor, const V1_3::Request& request, V1_2::MeasureTiming measure, const V1_3::OptionalTimePoint& deadline, @@ -222,7 +220,7 @@ nn::GeneralResult<void> execute_1_3(const nn::SharedPreparedModel& preparedModel preparedModel->execute(nnRequest, nnMeasure, nnDeadline, nnLoopTimeoutDuration); notify(callback.get(), std::move(result)); }; - executor(std::move(task), userId, nnDeadline); + executor(std::move(task), nnDeadline); return {}; } @@ -305,8 +303,8 @@ nn::GeneralResult<std::pair<hidl_handle, sp<V1_3::IFencedExecutionCallback>>> ex } // namespace -PreparedModel::PreparedModel(nn::SharedPreparedModel preparedModel, Executor executor, uid_t userId) - : kPreparedModel(std::move(preparedModel)), kExecutor(std::move(executor)), kUserId(userId) { +PreparedModel::PreparedModel(nn::SharedPreparedModel preparedModel, Executor executor) + : kPreparedModel(std::move(preparedModel)), kExecutor(std::move(executor)) { CHECK(kPreparedModel != nullptr); CHECK(kExecutor != nullptr); } @@ -317,7 +315,7 @@ nn::SharedPreparedModel PreparedModel::getUnderlyingPreparedModel() const { Return<V1_0::ErrorStatus> PreparedModel::execute(const V1_0::Request& request, const sp<V1_0::IExecutionCallback>& callback) { - auto result = adapter::execute(kPreparedModel, kUserId, kExecutor, request, callback); + auto result = adapter::execute(kPreparedModel, kExecutor, request, callback); if (!result.has_value()) { auto [message, code] = std::move(result).error(); LOG(ERROR) << "adapter::PreparedModel::execute failed with " << code << ": " << message; @@ -330,8 +328,7 @@ Return<V1_0::ErrorStatus> PreparedModel::execute(const V1_0::Request& request, Return<V1_0::ErrorStatus> PreparedModel::execute_1_2(const V1_0::Request& request, V1_2::MeasureTiming measure, const sp<V1_2::IExecutionCallback>& callback) { - auto result = - adapter::execute_1_2(kPreparedModel, kUserId, kExecutor, request, measure, callback); + auto result = adapter::execute_1_2(kPreparedModel, kExecutor, request, measure, callback); if (!result.has_value()) { auto [message, code] = std::move(result).error(); LOG(ERROR) << "adapter::PreparedModel::execute_1_2 failed with " << code << ": " << message; @@ -346,8 +343,8 @@ Return<V1_3::ErrorStatus> PreparedModel::execute_1_3( const V1_3::OptionalTimePoint& deadline, const V1_3::OptionalTimeoutDuration& loopTimeoutDuration, const sp<V1_3::IExecutionCallback>& callback) { - auto result = adapter::execute_1_3(kPreparedModel, kUserId, kExecutor, request, measure, - deadline, loopTimeoutDuration, callback); + auto result = adapter::execute_1_3(kPreparedModel, kExecutor, request, measure, deadline, + loopTimeoutDuration, callback); if (!result.has_value()) { auto [message, code] = std::move(result).error(); LOG(ERROR) << "adapter::PreparedModel::execute_1_3 failed with " << code << ": " << message; |