onnxruntime/js/react_native/example/ios/MNISTDataHandler.mm
harshithapv 8c0c25c768
cherry picked commits for rel-1.8.1 (#8076)
* Cache initializers and avoid device check ot end of forward (#7905)

* ATenOp Enhancement (#7725)

* config parser, default argument values

* ut

* win build

* maxpool2d

* fix win build

* fix build

* unfold atenop

* Update CMakeLists.txt for openvino EP (#7980)

* Add SoftmaxCrossEntropyLossInternal to Support Dynamic ignore_index Input (#7899)

* add SoftmaxCrossEntropyLossInternal

* bugfix and ut

* fix ut

* fix ut

* support torch1.8.1

* function body for nll_loss_internal

* Override ORTModule named_modules to support extra arg (#7954)

* add missing provider_options.h in packages (#7995)

* consolidate copy binary script for gpu/trt tarball package

* add provider_options.h

* add provider_options.h

* Add cuda provides files (#8002)

* Save module output for backward if needed (#8010)

* Save module output for backward if needed

* Make logic in InsertCastTransformer around forcing a node to fp32 more precise. (#8018)

* Address #7981

Reworked the logic around forcing a node to run on fp32 even if it was supported on fp16.

The github issue had multiple factors. In ORT 1.8 we remove Identity nodes that produce graph outputs as they're not needed. That resulted in a Loop node no longer having output nodes (it produces graph outputs instead), which meant the check in IsSingleInputNodeFloat16Node returned true as there was no longer a downstream Identity node processing fp16 data.

We shouldn't only force a node to fp32 in very specific circumstances, and the changes hopefully check for those more precisely.

* Fix Memory Leak from DlpackToOrtValue (#8029)

* Update DirectML EP changes from DmlDev as of 2021-06-07 (#7987)

* Merged PR 6093117: Fix test_DynamicQuantizedLinear_max_adjusted_expanded by allowing Identity operator to run on non-float inputs

Motivation:
As part of the OnnxConformance Backend tests, DynamicQuantizedLinear_max_adjusted_expanded is failing.

Root Cause:
- The test model has `Identity` operator as one of the node. The input of this node is of non-float data type.
- In DML, `Identity` operator is registered as operator which requires floating input.
- As per `DirectMLSchema.h`, support for non-float input has been added for `Identity` operator in DML but the same has not been reflected in the `OperatorRegistration.cpp`.

Changes:
- Removed all traces of the requiresFloatFormatsForGraph flag from it's definition and usage. This flag was only used for Identity and it's related operator.
- Added null check for the graphOutput nodeArg in GraphDescBuilder.cpp to stop the crash of the test.

Related work items: #33076298

* Merged PR 6103324: Remove usage of non-generic error code (FWP_E_NULL_POINTER)

Motivation:
Addressing Dwayne comment on the previous PR. [Ref: [6093117](https://dev.azure.com/microsoft/WindowsAI/_git/onnxruntime/pullrequest/6093117?discussionId=44292162&path=%2Fonnxruntime%2Fcore%2Fproviders%2Fdml%2FDmlExecutionProvider%2Fsrc%2FGraphPartitioner.cpp)]

Changes:
Inside the DML EP, we should not use some other platform specific error codes. Instead we should a appropriate generic error code.

Related work items: #33076298

Co-authored-by: Sumit Agarwal <sumitagarwal@microsoft.com>

* [js/react_native] Use a mobile ORT instead of a full ORT (#8042)

* Change full ort to mobile ort

* Update Android example to load mobile ort

* Change the format of test models to ort

* update ios to use mobile ort

* revise README

* use onnxruntime-mobile-c CocoaPods in a npm package

* fix PATH addition in windows

should set PATH, not add to the tail the copy of PATH

* Reduce Kernel Optimization (#8067)

* reduce optimization

* bug fix

* add a check

* add ut

* refactor

* add ut cases for keepdims=true

Co-authored-by: baijumeswani <bmeswani@microsoft.com>
Co-authored-by: Vincent Wang <wangwchpku@outlook.com>
Co-authored-by: Changming Sun <chasun@microsoft.com>
Co-authored-by: George Wu <jywu@microsoft.com>
Co-authored-by: Ryan Hill <38674843+RyanUnderhill@users.noreply.github.com>
Co-authored-by: Sherlock <baihan.huang@gmail.com>
Co-authored-by: Scott McKay <skottmckay@gmail.com>
Co-authored-by: sumitsays <sumitagarwal330@gmail.com>
Co-authored-by: Sumit Agarwal <sumitagarwal@microsoft.com>
Co-authored-by: Sunghoon <35605090+hanbitmyths@users.noreply.github.com>
Co-authored-by: iperov <lepersorium@gmail.com>
2021-06-18 07:44:55 -07:00

168 lines
5.6 KiB
Text

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#import "MNISTDataHandler.h"
#import "OnnxruntimeModule.h"
#import "TensorHelper.h"
#import <Foundation/Foundation.h>
#import <React/RCTLog.h>
NS_ASSUME_NONNULL_BEGIN
@implementation MNISTDataHandler
RCT_EXPORT_MODULE(MNISTDataHandler)
// It returns mode path in local device,
// so that onnxruntime is able to load a model using a given path.
RCT_EXPORT_METHOD(getLocalModelPath : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject) {
@try {
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"mnist" ofType:@"ort"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:modelPath]) {
resolve(modelPath);
} else {
reject(@"mnist", @"no such a model", nil);
}
} @catch (NSException *exception) {
reject(@"mnist", @"no such a model", nil);
}
}
// It returns image path.
RCT_EXPORT_METHOD(getImagePath : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)reject) {
@try {
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"jpg"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath]) {
resolve(imagePath);
} else {
reject(@"mnist", @"no such an image", nil);
}
} @catch (NSException *exception) {
reject(@"mnist", @"no such an image", nil);
}
}
// It gets raw input data, which can be uri or byte array and others,
// returns cooked data formatted as input of a model.
RCT_EXPORT_METHOD(preprocess
: (NSString *)uri resolve
: (RCTPromiseResolveBlock)resolve reject
: (RCTPromiseRejectBlock)reject) {
@try {
NSDictionary *inputDataMap = [self preprocess:uri];
resolve(inputDataMap);
} @catch (NSException *exception) {
reject(@"mnist", @"can't load an image", nil);
}
}
// It gets a result from onnxruntime and a duration of session time for input data,
// returns output data formatted as React Native map.
RCT_EXPORT_METHOD(postprocess
: (NSDictionary *)result resolve
: (RCTPromiseResolveBlock)resolve reject
: (RCTPromiseRejectBlock)reject) {
@try {
NSDictionary *cookedMap = [self postprocess:result];
resolve(cookedMap);
} @catch (NSException *exception) {
reject(@"mnist", @"can't pose-process an image", nil);
}
}
- (NSDictionary *)preprocess:(NSString *)uri {
UIImage *image = [UIImage imageNamed:@"3.jpg"];
CGSize scale = CGSizeMake(28, 28);
UIGraphicsBeginImageContextWithOptions(scale, NO, 1.0);
[image drawInRect:CGRectMake(0, 0, scale.width, scale.height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef imageRef = [scaledImage CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
const NSUInteger rawDataSize = height * width * 4;
std::vector<unsigned char> rawData(rawDataSize);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
CGContextRef context = CGBitmapContextCreate(rawData.data(), width, height, 8, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGImageByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
const NSInteger dimSize = height * width;
const NSInteger byteBufferSize = dimSize * sizeof(float);
unsigned char *byteBuffer = static_cast<unsigned char *>(malloc(byteBufferSize));
NSData *byteBufferRef = [NSData dataWithBytesNoCopy:byteBuffer length:byteBufferSize];
float *floatPtr = (float *)[byteBufferRef bytes];
for (NSUInteger h = 0; h < height; ++h) {
for (NSUInteger w = 0; w < width; ++w) {
NSUInteger byteIndex = (bytesPerRow * h) + w * bytesPerPixel;
*floatPtr++ = rawData[byteIndex];
}
}
floatPtr = (float *)[byteBufferRef bytes];
NSMutableDictionary *inputDataMap = [NSMutableDictionary dictionary];
NSMutableDictionary *inputTensorMap = [NSMutableDictionary dictionary];
// dims
NSArray *dims = @[
[NSNumber numberWithInt:1], [NSNumber numberWithInt:static_cast<int>(height)],
[NSNumber numberWithInt:static_cast<int>(width)]
];
inputTensorMap[@"dims"] = dims;
// type
inputTensorMap[@"type"] = JsTensorTypeFloat;
// encoded data
NSString *data = [byteBufferRef base64EncodedStringWithOptions:0];
inputTensorMap[@"data"] = data;
inputDataMap[@"flatten_2_input"] = inputTensorMap;
return inputDataMap;
}
- (NSDictionary *)postprocess:(NSDictionary *)result {
NSMutableString *detectionResult = [NSMutableString string];
NSDictionary *outputTensor = [result objectForKey:@"Identity"];
NSString *data = [outputTensor objectForKey:@"data"];
NSData *buffer = [[NSData alloc] initWithBase64EncodedString:data options:0];
float *values = (float *)[buffer bytes];
int count = (int)[buffer length] / 4;
int argmax = 0;
float maxValue = 0.0f;
for (int i = 0; i < count; ++i) {
if (values[i] > maxValue) {
maxValue = values[i];
argmax = i;
}
}
if (maxValue == 0.0f) {
detectionResult = [NSMutableString stringWithString:@"No match"];
} else {
detectionResult = [NSMutableString stringWithFormat:@"I guess, it's %d", argmax];
}
NSDictionary *cookedMap = @{@"result" : detectionResult};
return cookedMap;
}
@end
NS_ASSUME_NONNULL_END