PaddleMobileCPU.mm 9.7 KB
Newer Older
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
L
liuruilong 已提交
2

3 4 5
 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
L
liuruilong 已提交
6

7
 http://www.apache.org/licenses/LICENSE-2.0
L
liuruilong 已提交
8

9 10 11 12 13 14
 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. */

15
#import "PaddleMobileCPU.h"
H
hjchen2 已提交
16 17
#import "framework/load_ops.h"
#import "framework/tensor.h"
18 19 20 21
#import "io/paddle_mobile.h"
#import <memory>
#import <vector>

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
@interface PaddleMobileCPUResult()

-(void)toSetOutput:(float *)output;

-(void)toSetOutputSize:(int)outputSize;

@end

@implementation PaddleMobileCPUResult

-(void)releaseOutput {
  delete [] _output;
  _output = nil;
  _outputSize = 0;
}

-(void)toSetOutput:(float *)output {
  _output = output;
}

-(void)toSetOutputSize:(int)outputSize {
  _outputSize = outputSize;
}

@end

L
liuruilong 已提交
48 49 50 51 52 53 54 55 56 57 58
@implementation  PaddleMobileCPUConfig

-(instancetype)init {
  if (self = [super init]) {
    self.threadNum = 1;
    self.optimize = YES;
  }
  return self;
}

@end
59 60

@interface  PaddleMobileCPU()
61
{
62
  paddle_mobile::PaddleMobile<paddle_mobile::CPU, float> *pam_;
63 64
  BOOL loaded_;
}
L
liuruilong 已提交
65 66 67

@property (strong, nonatomic) PaddleMobileCPUConfig *config;

68 69
@end

70
@implementation PaddleMobileCPU
71 72 73

static std::mutex shared_mutex;

L
liuruilong 已提交
74
- (instancetype)initWithConfig:(PaddleMobileCPUConfig *)config {
75
  if (self = [super init]) {
76 77
    paddle_mobile::PaddleMobileConfigInternal configInternal;
    configInternal.load_when_predict = config.loadWhenPredict;
78
    pam_ = new paddle_mobile::PaddleMobile<paddle_mobile::CPU, float>();
L
liuruilong 已提交
79 80 81 82 83 84 85 86
    _config = config;
  }
  return self;
}

-(instancetype)init {
  if (self = [super init]) {
    _config = [[PaddleMobileCPUConfig alloc] init];
R
Ray Liu 已提交
87
    pam_ = new paddle_mobile::PaddleMobile<paddle_mobile::CPU, float>();
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  }
  return self;
}

- (void)dealloc {
  if (pam_) {
    delete pam_;
  }
}

+ (instancetype)sharedInstance{
  static dispatch_once_t onceToken;
  static id sharedManager = nil;
  dispatch_once(&onceToken, ^{
    sharedManager = [[[self class] alloc] init];
  });
  return sharedManager;
}

L
liuruilong 已提交
107
- (BOOL)loadModel:(NSString *)modelPath andWeightsPath:(NSString *)weighsPath {
108 109
  std::string model_path_str = std::string([modelPath UTF8String]);
  std::string weights_path_str = std::string([weighsPath UTF8String]);
L
liuruilong 已提交
110 111
  pam_->SetThreadNum(self.config.threadNum);
  if (loaded_ = pam_->Load(model_path_str, weights_path_str, self.config.optimize, false, 1, self.config.loddable)) {
112 113 114 115 116 117
    return YES;
  } else {
    return NO;
  }
}

118 119 120 121
- (BOOL)LoadCombinedMemory:(size_t)modelLen
               andModelBuf:(const uint8_t *)modelBuf
         andModelParamsLen:(size_t)combinedParamsLen
      andCombinedParamsBuf:(const uint8_t *)combinedParamsBuf {
L
liuruilong 已提交
122
  pam_->SetThreadNum(self.config.threadNum);
123
  return loaded_ = pam_->LoadCombinedMemory(modelLen, modelBuf, combinedParamsLen,
L
liuruilong 已提交
124
          const_cast<uint8_t*>(combinedParamsBuf), self.config.optimize, false, 1, self.config.loddable);
125 126
}

L
liuruilong 已提交
127 128
- (BOOL)load:(NSString *)modelAndWeightPath{
  std::string model_path_str = std::string([modelAndWeightPath UTF8String]);
L
liuruilong 已提交
129
  if (loaded_ = pam_->Load(model_path_str, self.config.optimize, false, 1, self.config.loddable)) {
L
liuruilong 已提交
130 131 132 133 134 135
    return YES;
  } else {
    return NO;
  }
}

136 137 138 139 140 141 142 143

-(void)preprocess:(CGImageRef)image
           output:(float *)output
            means:(NSArray<NSNumber *> *)means
        scale:(float)scale
        dim:(NSArray<NSNumber *> *)dim {
  std::lock_guard<std::mutex> lock(shared_mutex);

L
liuruilong 已提交
144 145 146 147
  if (means == nil) {
    means = @[@0, @0, @0];
  }

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
  // dim to c++ vector, get numel
  std::vector<int64_t > dim_vec;
  int numel = 1;
  for (int k = 0; k < dim.count; ++k) {
    int d = dim[k].intValue;
    numel *= d;
    dim_vec.push_back(d);
  }

  const int sourceRowBytes = CGImageGetBytesPerRow(image);
  const int imageWidth = CGImageGetWidth(image);
  const int imageHeight = CGImageGetHeight(image);
  const int imageChannels = 4;
  CGDataProviderRef provider = CGImageGetDataProvider(image);
  CFDataRef cfData = CGDataProviderCopyData(provider);
  const UInt8 *input = CFDataGetBytePtr(cfData);

  int wanted_input_width = dim_vec[3];
  int wanted_input_height = dim_vec[2];
  int wanted_input_channels = dim_vec[1];

  for (int c = 0; c < wanted_input_channels; ++c) {
    float *out_channel = output + c * wanted_input_height * wanted_input_width;
    for (int y = 0; y < wanted_input_height; ++y) {
      float *out_row = out_channel + y * wanted_input_width;
      for (int x = 0; x < wanted_input_width; ++x) {
        int in_row = (y * imageHeight) / wanted_input_height;
        int in_col = (x * imageWidth) / wanted_input_width;
        const UInt8 *in_pixel = input + (in_row * imageWidth * imageChannels) + (in_col * imageChannels);
        float *out_pos = out_row + x;
        if (c == 0) {
          *out_pos = (in_pixel[c] - means[c].floatValue) * scale;
        }else if (c == 1){
          *out_pos = (in_pixel[c] - means[c].floatValue) * scale;
        }else if (c == 2){
          *out_pos = (in_pixel[c] - means[c].floatValue) * scale;
        }
      }
    }
  }

}

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
-(void)preprocess:(const UInt8 *)input output:(float *)output imageWidth:(int)imageWidth imageHeight:(int)imageHeight imageChannels:(int)imageChannels means:(NSArray<NSNumber *> *)means scale:(float)scale dim:(std::vector<int64_t>)dim{
  if (means == nil) {
    means = @[@0, @0, @0];
  }

  int wanted_input_width = dim[3];
  int wanted_input_height = dim[2];
  int wanted_input_channels = dim[1];

  for (int c = 0; c < wanted_input_channels; ++c) {
    float *out_channel = output + c * wanted_input_height * wanted_input_width;
    for (int y = 0; y < wanted_input_height; ++y) {
      float *out_row = out_channel + y * wanted_input_width;
      for (int x = 0; x < wanted_input_width; ++x) {
        int in_row = (y * imageHeight) / wanted_input_height;
        int in_col = (x * imageWidth) / wanted_input_width;
        const UInt8 *in_pixel = input + (in_row * imageWidth * imageChannels) + (in_col * imageChannels);
        float *out_pos = out_row + x;
        if (c == 0) {
          *out_pos = (in_pixel[c] - means[c].floatValue) * scale;
        }else if (c == 1){
          *out_pos = (in_pixel[c] - means[c].floatValue) * scale;
        }else if (c == 2){
          *out_pos = (in_pixel[c] - means[c].floatValue) * scale;
        }
      }
    }
  }
}

221 222 223 224 225 226 227 228 229 230
- (PaddleMobileCPUResult *)predictInput:(float *)input
                      dim:(NSArray<NSNumber *> *)dim {
  std::lock_guard<std::mutex> lock(shared_mutex);
  if (!loaded_) {
    printf("PaddleMobile doesn't be loaded yet");
    return nil;
  }

  if (dim.count != 4) {
    printf("dim must have 4 elements");
L
liuruilong 已提交
231 232
    return nil;
  }
233

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  // dim to c++ vector, get numel
  std::vector<int64_t > dim_vec;
  int numel = 1;
  for (int k = 0; k < dim.count; ++k) {
    int d = dim[k].intValue;
    numel *= d;
    dim_vec.push_back(d);
  }

  paddle_mobile::framework::Tensor input_tensor;

  paddle_mobile::framework::DDim dims = paddle_mobile::framework::make_ddim(dim_vec);

  float *input_ptr = input_tensor.mutable_data<float>(dims);

  memcpy(input_ptr, input,
         numel * sizeof(float));

252 253
  pam_->Predict(input_tensor);
  std::shared_ptr<paddle_mobile::framework::Tensor> output = pam_->Fetch();
254 255 256 257 258 259 260 261 262 263 264 265 266

  float *output_pointer = new float[output->numel()];

  memcpy(output_pointer, output->data<float>(),
         output->numel() * sizeof(float));

  PaddleMobileCPUResult *cpuResult = [[PaddleMobileCPUResult alloc] init];
  [cpuResult toSetOutput: output_pointer];
  [cpuResult toSetOutputSize: output->numel()];

  return cpuResult;
}

L
liuruilong 已提交
267
- (PaddleMobileCPUResult *)predict:(CGImageRef)image dim:(NSArray<NSNumber *> *)dim means:(NSArray<NSNumber *> *)means scale:(float)scale{
268 269
//  printf(" predict one ");
  std::lock_guard<std::mutex> lock(shared_mutex);
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
  if (!loaded_) {
    printf("PaddleMobile doesn't be loaded yet");
    return nil;
  }

  if (dim.count != 4) {
    printf("dim must have 4 elements");
    return nil;
  }

  // dim to c++ vector, get numel
  std::vector<int64_t > dim_vec;
  int numel = 1;
  for (int k = 0; k < dim.count; ++k) {
    int d = dim[k].intValue;
    numel *= d;
    dim_vec.push_back(d);
  }

  const int sourceRowBytes = CGImageGetBytesPerRow(image);
  const int image_width = CGImageGetWidth(image);
  const int image_height = CGImageGetHeight(image);
  const int image_channels = 4;
  CGDataProviderRef provider = CGImageGetDataProvider(image);
  CFDataRef cfData = CGDataProviderCopyData(provider);
  const UInt8 *input = CFDataGetBytePtr(cfData);

  // sample image
  float *output = (float *)malloc(numel*sizeof(float));
  [self preprocess:input output:output imageWidth:image_width imageHeight:image_height imageChannels:image_channels means:means scale:scale dim:dim_vec];
  float *dataPointer = nullptr;
  if (nullptr != output) {
    dataPointer = output;
  } else {
    return nil;
  }

  // input
308
  std::vector<float> predict_input;
309
  for (int j = 0; j < numel; ++j) {
310
    predict_input.push_back(dataPointer[j]);
311 312 313
  }

  // predict
314
  std::vector<float> cpp_result = pam_->Predict(predict_input, dim_vec);
315

L
liuruilong 已提交
316 317 318 319 320 321
  float *output_pointer = new float[cpp_result.size()];
  memcpy(output_pointer, cpp_result.data(),
         cpp_result.size() * sizeof(float));
  PaddleMobileCPUResult *cpuResult = [[PaddleMobileCPUResult alloc] init];
  [cpuResult toSetOutput: output_pointer];
  [cpuResult toSetOutputSize: cpp_result.size()];
L
liuruilong 已提交
322

323 324 325 326
  free(output);
  CFRelease(cfData);
  cfData = NULL;

L
liuruilong 已提交
327
  return cpuResult;
328 329
}

L
liuruilong 已提交
330 331
- (PaddleMobileCPUResult *)predict:(CGImageRef)image dim:(NSArray<NSNumber *> *)dim {
  return [self predict:image dim:dim means:nil scale:1];
332 333 334 335 336 337 338
}

- (void)clear{
  pam_->Clear();
}

@end