chore: import upstream snapshot with attribution
cffconvert / validate (push) Has been skipped
License Check / license-check (push) Failing after 2s

This commit is contained in:
wehub-resource-sync
2026-07-13 12:14:16 +08:00
commit 8a852e4b4e
36502 changed files with 9277225 additions and 0 deletions
@@ -0,0 +1,5 @@
platform :ios, '9.0'
target 'TestApp' do
pod 'TensorFlowLiteObjC'
end
@@ -0,0 +1,25 @@
// Copyright 2019 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 <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property(nonatomic) UIWindow *window;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,22 @@
// Copyright 2019 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 "AppDelegate.h"
NS_ASSUME_NONNULL_BEGIN
@implementation AppDelegate
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,98 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="23727" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="23721"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Y0Z-8F-bB8"/>
<viewControllerLayoutGuide type="bottom" id="TqJ-Hq-gHs"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" misplaced="YES" text="TensorFlow Lite Test" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumScaleFactor="0.25" translatesAutoresizingMaskIntoConstraints="NO" id="zIC-MS-HeK">
<rect key="frame" x="16" y="313" width="343" height="39"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="32"/>
<color key="textColor" red="1" green="0.50329624702372611" blue="0.013296667412401542" alpha="0.84705882352941175" colorSpace="custom" customColorSpace="displayP3"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstAttribute="trailing" secondItem="zIC-MS-HeK" secondAttribute="trailing" constant="16" id="1Wp-jb-ol6"/>
<constraint firstItem="zIC-MS-HeK" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="R2T-Hp-TBa"/>
<constraint firstItem="zIC-MS-HeK" firstAttribute="leading" secondItem="Ze5-6b-2t3" secondAttribute="leading" constant="16" id="alE-O6-WL6"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="52" y="374.66266866566718"/>
</scene>
</scenes>
</document>
@@ -0,0 +1,92 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="23727" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment version="2304" identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="23721"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="5Qd-iD-SiH"/>
<viewControllerLayoutGuide type="bottom" id="zTS-de-uge"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<toolbar opaque="NO" clearsContextBeforeDrawing="NO" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="ahi-i4-2FP" userLabel="Top Model Toolbar">
<rect key="frame" x="0.0" y="34" width="375" height="44"/>
<constraints>
<constraint firstAttribute="height" constant="44" id="nwy-nk-0wZ"/>
</constraints>
<items>
<barButtonItem style="plain" id="Ywd-KS-s96">
<segmentedControl key="customView" opaque="NO" contentMode="scaleToFill" misplaced="YES" contentHorizontalAlignment="left" contentVerticalAlignment="top" segmentControlStyle="bar" selectedSegmentIndex="0" id="8kc-88-CHj" userLabel="Model Control">
<rect key="frame" x="16" y="6" width="343" height="32"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<segments>
<segment title="Add"/>
<segment title="AddQuantized"/>
<segment title="MultiAdd"/>
</segments>
<connections>
<action selector="modelChanged:" destination="BYZ-38-t0r" eventType="valueChanged" id="z13-8K-EwC"/>
</connections>
</segmentedControl>
</barButtonItem>
</items>
</toolbar>
<toolbar opaque="NO" clearsContextBeforeDrawing="NO" contentMode="scaleToFill" misplaced="YES" translatesAutoresizingMaskIntoConstraints="NO" id="UWb-3E-O5r" userLabel="Bottom Invoke Toolbar">
<rect key="frame" x="0.0" y="139" width="375" height="44"/>
<items>
<barButtonItem title="Invoke Interpreter" width="374" id="He4-7G-biW">
<connections>
<action selector="invokeInterpreter:" destination="BYZ-38-t0r" id="Ycs-E9-Vul"/>
</connections>
</barButtonItem>
</items>
</toolbar>
<textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" misplaced="YES" editable="NO" adjustsFontForContentSizeCategory="YES" selectable="NO" translatesAutoresizingMaskIntoConstraints="NO" id="7Ws-3t-76I">
<rect key="frame" x="0.0" y="194" width="375" height="488"/>
<color key="backgroundColor" red="0.12820077356385221" green="0.40366933178860925" blue="0.96080166101455688" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
<color key="textColor" systemColor="tableCellGroupedBackgroundColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
</textView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="ahi-i4-2FP" firstAttribute="top" secondItem="5Qd-iD-SiH" secondAttribute="bottom" constant="14" id="0V2-16-9cM"/>
<constraint firstAttribute="trailing" secondItem="ahi-i4-2FP" secondAttribute="trailing" id="1D2-FC-OQ0"/>
<constraint firstItem="UWb-3E-O5r" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="1To-8n-Knb"/>
<constraint firstItem="7Ws-3t-76I" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="3Et-px-WCV"/>
<constraint firstItem="zTS-de-uge" firstAttribute="top" secondItem="7Ws-3t-76I" secondAttribute="bottom" id="Lkb-XF-ldX"/>
<constraint firstItem="7Ws-3t-76I" firstAttribute="top" secondItem="UWb-3E-O5r" secondAttribute="bottom" id="bXr-pF-Ld2"/>
<constraint firstItem="ahi-i4-2FP" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="c98-HO-3m5"/>
<constraint firstAttribute="trailing" secondItem="UWb-3E-O5r" secondAttribute="trailing" id="oJz-hf-dJa"/>
<constraint firstAttribute="trailing" secondItem="7Ws-3t-76I" secondAttribute="trailing" id="oyy-C7-mUJ"/>
<constraint firstItem="UWb-3E-O5r" firstAttribute="top" secondItem="ahi-i4-2FP" secondAttribute="bottom" constant="62" id="uFg-MF-aJz"/>
</constraints>
</view>
<connections>
<outlet property="invokeButton" destination="He4-7G-biW" id="kpj-CS-Fss"/>
<outlet property="modelControl" destination="8kc-88-CHj" id="GTB-WG-ozW"/>
<outlet property="resultsTextView" destination="7Ws-3t-76I" id="fnd-i5-Pdh"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="136.80000000000001" y="132.68365817091455"/>
</scene>
</scenes>
<resources>
<systemColor name="tableCellGroupedBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>0.0.1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
</dict>
</plist>
@@ -0,0 +1,22 @@
// Copyright 2019 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 <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface ViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,424 @@
// Copyright 2019 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 "ViewController.h"
#if COCOAPODS
@import TFLTensorFlowLite;
#else
#import "TFLTensorFlowLite.h"
#endif
NS_ASSUME_NONNULL_BEGIN
/**
* Safely dispatches the given `block` on the main thread. If already on the main thread, the given
* block is executed immediately; otherwise, dispatches the block asynchronously on the main thread.
*
* @param block The block to dispatch on the main thread.
*/
void TLTSafeDispatchOnMain(dispatch_block_t block) {
if (block == nil) return;
if (NSThread.isMainThread) {
block();
} else {
dispatch_async(dispatch_get_main_queue(), block);
}
}
/**
* Name of a float model that performs two add operations on one input tensor and returns the result
* in one output tensor.
*/
static NSString *const kModelNameAdd = @"add";
/**
* Name of a quantized model that performs two add operations on one input tensor and returns the
* result in one output tensor.
*/
static NSString *const kModelNameAddQuantized = @"add_quantized";
/**
* Name of a float model that performs three add operations on four input tensors and returns the
* results in 2 output tensors.
*/
static NSString *const kModelNameMultiAdd = @"multi_add";
/** Model resource type. */
static NSString *const kModelType = @"bin";
/** The label for the serial queue for synchronizing interpreter calls. */
static const char *kInterpreterSerialQueueLabel = "com.tensorflow.lite.objc.testapp.interpreter";
static NSString *const kNilInterpreterError =
@"Failed to invoke the interpreter because the interpreter was nil.";
static NSString *const kInvokeInterpreterError = @"Failed to invoke interpreter due to error: %@.";
/** Model paths. */
static NSArray<NSString *> *gModelPaths;
@interface ViewController ()
/** Serial queue for synchronizing interpreter calls. */
@property(nonatomic) dispatch_queue_t interpreterSerialQueue;
/** TensorFlow Lite interpreter for the currently selected model. */
@property(nonatomic) TFLInterpreter *interpreter;
@property(weak, nonatomic) IBOutlet UISegmentedControl *modelControl;
@property(weak, nonatomic) IBOutlet UIBarButtonItem *invokeButton;
@property(weak, nonatomic) IBOutlet UITextView *resultsTextView;
@end
@implementation ViewController
#pragma mark - NSObject
+ (void)initialize {
if (self == [ViewController self]) {
gModelPaths = @[
[NSBundle.mainBundle pathForResource:kModelNameAdd ofType:kModelType],
[NSBundle.mainBundle pathForResource:kModelNameAddQuantized ofType:kModelType],
[NSBundle.mainBundle pathForResource:kModelNameMultiAdd ofType:kModelType],
];
}
}
#pragma mark - UIViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.interpreterSerialQueue =
dispatch_queue_create(kInterpreterSerialQueueLabel, DISPATCH_QUEUE_SERIAL);
self.invokeButton.enabled = NO;
[self updateResultsText:[NSString stringWithFormat:@"Using TensorFlow Lite runtime version %@.",
TFLVersion]];
[self loadModel];
}
#pragma mark - IBActions
- (IBAction)modelChanged:(id)sender {
self.invokeButton.enabled = NO;
NSString *results = [NSString
stringWithFormat:@"Switched to the %@ model.",
[self.modelControl
titleForSegmentAtIndex:self.modelControl.selectedSegmentIndex]];
[self updateResultsText:results];
[self loadModel];
}
- (IBAction)invokeInterpreter:(id)sender {
switch (self.modelControl.selectedSegmentIndex) {
case 0:
[self invokeAdd];
break;
case 1:
[self invokeAddQuantized];
break;
case 2:
[self invokeMultiAdd];
}
}
#pragma mark - Private
/** Path of the currently selected model. */
- (nullable NSString *)currentModelPath {
return self.modelControl.selectedSegmentIndex == UISegmentedControlNoSegment
? nil
: gModelPaths[self.modelControl.selectedSegmentIndex];
}
- (void)loadModel {
NSString *modelPath = [self currentModelPath];
if (modelPath.length == 0) {
[self updateResultsText:@"No model is selected."];
return;
}
__weak typeof(self) weakSelf = self;
dispatch_async(self.interpreterSerialQueue, ^{
TFLInterpreterOptions *options = [[TFLInterpreterOptions alloc] init];
options.numberOfThreads = 2;
NSError *error;
weakSelf.interpreter = [[TFLInterpreter alloc] initWithModelPath:modelPath
options:options
delegates:@[]
error:&error];
if (weakSelf.interpreter == nil || error != nil) {
NSString *results =
[NSString stringWithFormat:@"Failed to create the interpreter due to error:%@",
error.localizedDescription];
[weakSelf updateResultsText:results];
} else {
TLTSafeDispatchOnMain(^{
weakSelf.invokeButton.enabled = YES;
});
}
});
}
- (void)invokeAdd {
__weak typeof(self) weakSelf = self;
dispatch_async(self.interpreterSerialQueue, ^{
if (weakSelf.interpreter == nil) {
[weakSelf updateResultsText:kNilInterpreterError];
return;
}
NSArray<NSNumber *> *shape = @[@2];
NSError *error;
if (![weakSelf.interpreter resizeInputTensorAtIndex:0 toShape:shape error:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
if (![weakSelf.interpreter allocateTensorsWithError:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
TFLTensor *inputTensor = [weakSelf.interpreter inputTensorAtIndex:0 error:&error];
if (inputTensor == nil || error != nil) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
NSMutableData *inputData = [NSMutableData dataWithCapacity:0];
float one = 1.f;
float three = 3.f;
[inputData appendBytes:&one length:sizeof(float)];
[inputData appendBytes:&three length:sizeof(float)];
if (![inputTensor copyData:inputData error:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
if (![weakSelf.interpreter invokeWithError:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
TFLTensor *outputTensor = [weakSelf.interpreter outputTensorAtIndex:0 error:&error];
if (outputTensor == nil || error != nil) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
NSData *outputData = [outputTensor dataWithError:&error];
if (outputData == nil || error != nil) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
float output[2U];
[outputData getBytes:output length:(sizeof(float) * 2U)];
[weakSelf
updateResultsText:[NSString stringWithFormat:@"Performing 2 add operations:\n\nInput = "
@"[%.1f, %.1f]\n\nOutput = [%.1f, %.1f]",
one, three, output[0], output[1]]];
});
}
- (void)invokeAddQuantized {
__weak typeof(self) weakSelf = self;
dispatch_async(self.interpreterSerialQueue, ^{
if (weakSelf.interpreter == nil) {
[weakSelf updateResultsText:kNilInterpreterError];
return;
}
NSArray<NSNumber *> *shape = @[@2];
NSError *error;
if (![weakSelf.interpreter resizeInputTensorAtIndex:0 toShape:shape error:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
if (![weakSelf.interpreter allocateTensorsWithError:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
TFLTensor *inputTensor = [weakSelf.interpreter inputTensorAtIndex:0 error:&error];
if (inputTensor == nil || error != nil) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
NSMutableData *inputData = [NSMutableData dataWithCapacity:0];
uint8_t one = 1U;
uint8_t three = 3U;
[inputData appendBytes:&one length:sizeof(uint8_t)];
[inputData appendBytes:&three length:sizeof(uint8_t)];
if (![inputTensor copyData:inputData error:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
if (![weakSelf.interpreter invokeWithError:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
TFLTensor *outputTensor = [weakSelf.interpreter outputTensorAtIndex:0 error:&error];
if (outputTensor == nil || error != nil) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
TFLQuantizationParameters *params = outputTensor.quantizationParameters;
if (params == nil) {
[weakSelf updateResultsText:
[NSString stringWithFormat:kInvokeInterpreterError,
@"Missing qualitization parameters in the output"]];
return;
}
NSData *outputData = [outputTensor dataWithError:&error];
if (outputData == nil || error != nil) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
uint8_t output[2U];
[outputData getBytes:output length:(sizeof(uint8_t) * 2U)];
float dequantized[2U];
dequantized[0] = params.scale * (output[0] - params.zeroPoint);
dequantized[1] = params.scale * (output[1] - params.zeroPoint);
[weakSelf updateResultsText:
[NSString stringWithFormat:@"Performing 2 add operations on quantized input:\n\n"
@"Input = [%d, %d]\n\nQuantized Output = [%d, %d]\n\n"
@"Dequantized Output = [%f, %f]",
one, three, output[0], output[1], dequantized[0],
dequantized[1]]];
});
}
- (void)invokeMultiAdd {
__weak typeof(self) weakSelf = self;
dispatch_async(self.interpreterSerialQueue, ^{
if (weakSelf.interpreter == nil) {
[weakSelf updateResultsText:kNilInterpreterError];
return;
}
NSArray<NSNumber *> *shape = @[@2];
NSError *error;
for (int i = 0; i < weakSelf.interpreter.inputTensorCount; ++i) {
if (![weakSelf.interpreter resizeInputTensorAtIndex:i toShape:shape error:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
}
if (![weakSelf.interpreter allocateTensorsWithError:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
NSString *inputs = @"";
for (int i = 0; i < weakSelf.interpreter.inputTensorCount; ++i) {
TFLTensor *inputTensor = [weakSelf.interpreter inputTensorAtIndex:i error:&error];
if (inputTensor == nil || error != nil) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
NSMutableData *inputData = [NSMutableData dataWithCapacity:0];
float input1 = (float)(i + 1);
float input2 = (float)(i + 2);
inputs = [NSString stringWithFormat:@"%@%@[%.1f, %.1f]", inputs,
(inputs.length == 0 ? @"[" : @", "), input1, input2];
[inputData appendBytes:&input1 length:sizeof(float)];
[inputData appendBytes:&input2 length:sizeof(float)];
if (![inputTensor copyData:inputData error:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
}
inputs = [NSString stringWithFormat:@"%@]", inputs];
if (![weakSelf.interpreter invokeWithError:&error]) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
NSString *outputs = @"";
for (int i = 0; i < weakSelf.interpreter.outputTensorCount; ++i) {
TFLTensor *outputTensor = [weakSelf.interpreter outputTensorAtIndex:i error:&error];
if (outputTensor == nil || error != nil) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
NSData *outputData = [outputTensor dataWithError:&error];
if (outputData == nil || error != nil) {
[weakSelf updateResultsText:[NSString stringWithFormat:kInvokeInterpreterError,
error.localizedDescription]];
return;
}
float output[2U];
[outputData getBytes:output length:(sizeof(float) * 2U)];
outputs =
[NSString stringWithFormat:@"%@%@[%.1f, %.1f]", outputs,
(outputs.length == 0 ? @"[" : @", "), output[0], output[1]];
}
outputs = [NSString stringWithFormat:@"%@]", outputs];
[weakSelf
updateResultsText:
[NSString
stringWithFormat:@"Performing 3 add operations:\n\nInputs = %@\n\nOutputs = %@",
inputs, outputs]];
});
}
- (void)updateResultsText:(NSString *)text {
__weak typeof(self) weakSelf = self;
TLTSafeDispatchOnMain(^{
weakSelf.resultsTextView.text = text;
});
}
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,22 @@
// Copyright 2019 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 <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char* argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}