xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/mlir/tensorflow/ir/tf_ops_device_helper.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops_device_helper.h"
17 
18 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_structs.h"
19 #include "tensorflow/core/framework/types.h"
20 #include "tensorflow/core/util/device_name_utils.h"
21 
22 namespace mlir {
23 namespace TF {
24 namespace {
25 using DeviceNameUtils = ::tensorflow::DeviceNameUtils;
26 using ParsedName = ::tensorflow::DeviceNameUtils::ParsedName;
27 
IsGpuDevice(const DeviceNameUtils::ParsedName & device)28 bool IsGpuDevice(const DeviceNameUtils::ParsedName &device) {
29   return device.type == ::tensorflow::DEVICE_GPU;
30 }
31 
32 }  // namespace
33 
34 // Returns true if at least one GPU device is available at runtime.
CanUseGpuDevice(const RuntimeDevices & devices)35 bool CanUseGpuDevice(const RuntimeDevices &devices) {
36   return llvm::any_of(devices.device_names(), IsGpuDevice);
37 }
38 
39 // Returns true if all of the GPUs available at runtime support TensorCores
40 // (NVIDIA compute capability >= 7.0).
CanUseTensorCores(const RuntimeDevices & devices)41 bool CanUseTensorCores(const RuntimeDevices &devices) {
42   auto has_tensor_cores = [&](const DeviceNameUtils::ParsedName &device) {
43     auto md = devices.GetGpuDeviceMetadata(device);
44     return md ? md->getCcMajor() >= 7 : false;
45   };
46   return llvm::all_of(
47       llvm::make_filter_range(devices.device_names(), IsGpuDevice),
48       has_tensor_cores);
49 }
50 
51 // Returns true if operation does not have explicit device placement that would
52 // prevent it from running on GPU device.
CanUseGpuDevice(Operation * op)53 bool CanUseGpuDevice(Operation *op) {
54   auto device_attr = op->getAttrOfType<StringAttr>("device");
55   if (!device_attr || device_attr.getValue().empty()) return true;
56 
57   DeviceNameUtils::ParsedName device;
58   if (!DeviceNameUtils::ParseFullName(device_attr.getValue().str(), &device))
59     return false;
60 
61   // We can't use GPU if operation explicitly placed on non-GPU device.
62   return !device.has_type || device.type == ::tensorflow::DEVICE_GPU;
63 }
64 
65 }  // namespace TF
66 }  // namespace mlir
67