tzh
2024-08-22 c7d0944258c7d0943aa7b2211498fd612971ce27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Copyright 2018 Google Inc. All rights reserved.
//
// 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.
 
import Foundation
import TensorFlowLiteCAPI
 
/// A TensorFlow Lite interpreter that performs inference from a given model.
public final class Interpreter {
 
  /// The `TFL_Interpreter` C pointer type represented as an `UnsafePointer<TFL_Interpreter>`.
  private typealias CInterpreter = OpaquePointer
 
  /// Total number of input tensors associated with the model.
  public var inputTensorCount: Int {
    return Int(TFL_InterpreterGetInputTensorCount(cInterpreter))
  }
 
  /// Total number of output tensors associated with the model.
  public var outputTensorCount: Int {
    return Int(TFL_InterpreterGetOutputTensorCount(cInterpreter))
  }
 
  /// The underlying `TFL_Interpreter` C pointer.
  private var cInterpreter: CInterpreter?
 
  /// Creates a new model interpreter instance.
  ///
  /// - Parameters:
  ///   - modelPath: Local file path to a TensorFlow Lite model.
  ///   - options: Custom configurations for the interpreter. The default is `nil` indicating that
  ///       interpreter will determine the configuration options.
  /// - Throws: An error if the model could not be loaded or the interpreter could not be created.
  public init(modelPath: String, options: InterpreterOptions? = nil) throws {
    guard let model = Model(filePath: modelPath) else { throw InterpreterError.failedToLoadModel }
 
    let cInterpreterOptions: OpaquePointer? = try options.map { options in
      guard let cOptions = TFL_NewInterpreterOptions() else {
        throw InterpreterError.failedToCreateInterpreter
      }
      if let threadCount = options.threadCount, threadCount > 0 {
        TFL_InterpreterOptionsSetNumThreads(cOptions, Int32(threadCount))
      }
      if options.isErrorLoggingEnabled {
        TFL_InterpreterOptionsSetErrorReporter(
          cOptions,
          { (_, format, arguments) in
            guard let cFormat = format,
                  let message = String(cFormat: cFormat, arguments: arguments)
            else {
              return
            }
            print(String(describing: InterpreterError.tensorFlowLiteError(message)))
          },
          nil
        )
      }
      return cOptions
    }
    defer { TFL_DeleteInterpreterOptions(cInterpreterOptions) }
 
    guard let cInterpreter = TFL_NewInterpreter(model.cModel, cInterpreterOptions) else {
      throw InterpreterError.failedToCreateInterpreter
    }
    self.cInterpreter = cInterpreter
  }
 
  deinit {
    TFL_DeleteInterpreter(cInterpreter)
  }
 
  /// Invokes the interpreter to perform inference from the loaded graph.
  ///
  /// - Throws: An error if the model was not ready because tensors were not allocated.
  public func invoke() throws {
    guard TFL_InterpreterInvoke(cInterpreter) == kTfLiteOk else {
      // TODO(b/117510052): Determine which error to throw.
      throw InterpreterError.allocateTensorsRequired
    }
  }
 
  /// Returns the input tensor at the given index.
  ///
  /// - Parameters:
  ///   - index: The index for the input tensor.
  /// - Throws: An error if the index is invalid or the tensors have not been allocated.
  /// - Returns: The input tensor at the given index.
  public func input(at index: Int) throws -> Tensor {
    let maxIndex = inputTensorCount - 1
    guard case 0...maxIndex = index else {
      throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
    }
    guard let cTensor = TFL_InterpreterGetInputTensor(cInterpreter, Int32(index)),
          let bytes = TFL_TensorData(cTensor),
          let nameCString = TFL_TensorName(cTensor)
    else {
      throw InterpreterError.allocateTensorsRequired
    }
    guard let dataType = TensorDataType(type: TFL_TensorType(cTensor)) else {
      throw InterpreterError.invalidTensorDataType
    }
 
    let name = String(cString: nameCString)
    let rank = TFL_TensorNumDims(cTensor)
    let dimensions = (0..<rank).map { Int(TFL_TensorDim(cTensor, $0)) }
    let shape = TensorShape(dimensions)
    let byteCount = TFL_TensorByteSize(cTensor)
    let data = Data(bytes: bytes, count: byteCount)
    let cQuantizationParams = TFL_TensorQuantizationParams(cTensor)
    let scale = cQuantizationParams.scale
    let zeroPoint = Int(cQuantizationParams.zero_point)
    var quantizationParameters: QuantizationParameters? = nil
    if scale != 0.0 {
      // TODO(b/117510052): Update this check once the TfLiteQuantizationParams struct has a mode.
      quantizationParameters = QuantizationParameters(scale: scale, zeroPoint: zeroPoint)
    }
    let tensor = Tensor(
      name: name,
      dataType: dataType,
      shape: shape,
      data: data,
      quantizationParameters: quantizationParameters
    )
    return tensor
  }
 
  /// Returns the output tensor at the given index.
  ///
  /// - Parameters:
  ///   - index: The index for the output tensor.
  /// - Throws: An error if the index is invalid, tensors haven't been allocated, or interpreter
  ///     hasn't been invoked for models that dynamically compute output tensors based on the values
  ///     of its input tensors.
  /// - Returns: The output tensor at the given index.
  public func output(at index: Int) throws -> Tensor {
    let maxIndex = outputTensorCount - 1
    guard case 0...maxIndex = index else {
      throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
    }
    guard let cTensor = TFL_InterpreterGetOutputTensor(cInterpreter, Int32(index)),
          let bytes = TFL_TensorData(cTensor),
          let nameCString = TFL_TensorName(cTensor)
    else {
      // TODO(b/117510052): Determine which error to throw.
      throw InterpreterError.invokeInterpreterRequired
    }
    guard let dataType = TensorDataType(type: TFL_TensorType(cTensor)) else {
      throw InterpreterError.invalidTensorDataType
    }
 
    let name = String(cString: nameCString)
    let rank = TFL_TensorNumDims(cTensor)
    let dimensions = (0..<rank).map { Int(TFL_TensorDim(cTensor, $0)) }
    let shape = TensorShape(dimensions)
    let byteCount = TFL_TensorByteSize(cTensor)
    let data = Data(bytes: bytes, count: byteCount)
    let cQuantizationParams = TFL_TensorQuantizationParams(cTensor)
    let scale = cQuantizationParams.scale
    let zeroPoint = Int(cQuantizationParams.zero_point)
    var quantizationParameters: QuantizationParameters? = nil
    if scale != 0.0 {
      // TODO(b/117510052): Update this check once the TfLiteQuantizationParams struct has a mode.
      quantizationParameters = QuantizationParameters(scale: scale, zeroPoint: zeroPoint)
    }
    let tensor = Tensor(
      name: name,
      dataType: dataType,
      shape: shape,
      data: data,
      quantizationParameters: quantizationParameters
    )
    return tensor
  }
 
  /// Resizes the input tensor at the given index to the specified tensor shape.
  ///
  /// - Note: After resizing an input tensor, the client **must** explicitly call
  ///     `allocateTensors()` before attempting to access the resized tensor data or invoking the
  ///     interpreter to perform inference.
  /// - Parameters:
  ///   - index: The index for the input tensor.
  ///   - shape: The shape that the input tensor should be resized to.
  /// - Throws: An error if the input tensor at the given index could not be resized.
  public func resizeInput(at index: Int, to shape: TensorShape) throws {
    let maxIndex = inputTensorCount - 1
    guard case 0...maxIndex = index else {
      throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
    }
    guard TFL_InterpreterResizeInputTensor(
            cInterpreter,
            Int32(index),
            shape.int32Dimensions,
            Int32(shape.rank)
          ) == kTfLiteOk
    else {
      throw InterpreterError.failedToResizeInputTensor(index: index)
    }
  }
 
  /// Copies the given data to the input tensor at the given index.
  ///
  /// - Parameters:
  ///   - data: The data to be copied to the input tensor's data buffer.
  ///   - index: The index for the input tensor.
  /// - Throws: An error if the `data.count` does not match the input tensor's `data.count` or if
  ///     the given index is invalid.
  /// - Returns: The input tensor with the copied data.
  @discardableResult
  public func copy(_ data: Data, toInputAt index: Int) throws -> Tensor {
    let maxIndex = inputTensorCount - 1
    guard case 0...maxIndex = index else {
      throw InterpreterError.invalidTensorIndex(index: index, maxIndex: maxIndex)
    }
    guard let cTensor = TFL_InterpreterGetInputTensor(cInterpreter, Int32(index)) else {
      throw InterpreterError.allocateTensorsRequired
    }
 
    let byteCount = TFL_TensorByteSize(cTensor)
    guard data.count == byteCount else {
      throw InterpreterError.invalidTensorDataCount(provided: data.count, required: byteCount)
    }
 
    let status = data.withUnsafeBytes { TFL_TensorCopyFromBuffer(cTensor, $0, data.count) }
    guard status == kTfLiteOk else { throw InterpreterError.failedToCopyDataToInputTensor }
    return try input(at: index)
  }
 
  /// Allocates memory for all input tensors based on their `TensorShape`s.
  ///
  /// - Note: This is a relatively expensive operation and should only be called after creating the
  ///     interpreter and/or resizing any input tensors.
  /// - Throws: An error if memory could not be allocated for the input tensors.
  public func allocateTensors() throws {
    guard TFL_InterpreterAllocateTensors(cInterpreter) == kTfLiteOk else {
      throw InterpreterError.failedToAllocateTensors
    }
  }
}
 
// MARK: - Extensions
 
extension String {
  /// Returns a new `String` initialized by using the given format C array as a template into which
  /// the remaining argument values are substituted according to the user’s default locale.
  ///
  /// - Note: Returns `nil` if a new `String` could not be constructed from the given values.
  /// - Parameters:
  ///   - cFormat: The format C array as a template for substituting values.
  ///   - arguments: A C pointer to a `va_list` of arguments to substitute into `cFormat`.
  init?(cFormat: UnsafePointer<CChar>, arguments: CVaListPointer) {
    var buffer: UnsafeMutablePointer<CChar>?
    guard vasprintf(&buffer, cFormat, arguments) != 0, let cString = buffer else { return nil }
    self.init(validatingUTF8: cString)
  }
}