1// 2// ETCoreMLModelDebugInfo.mm 3// 4// Copyright © 2024 Apple Inc. All rights reserved. 5// 6// Please refer to the license found in the LICENSE file in the root directory of the source tree. 7 8 9#import "ETCoreMLModelDebugInfo.h" 10 11#import "ETCoreMLStrings.h" 12#import "ETCoreMLModelStructurePath.h" 13#import "objc_safe_cast.h" 14 15 16@implementation ETCoreMLModelDebugInfo 17 18- (instancetype)initWithPathToDebugSymbolMap:(NSDictionary<ETCoreMLModelStructurePath *, NSString *> *)pathToDebugSymbolMap 19 pathToDebugHandlesMap:(NSDictionary<ETCoreMLModelStructurePath *, NSArray<NSString *> *> *)pathToDebugHandlesMap { 20 self = [super init]; 21 if (self) { 22 _pathToDebugSymbolMap = [pathToDebugSymbolMap copy]; 23 _pathToDebugHandlesMap = [pathToDebugHandlesMap copy]; 24 } 25 26 return self; 27} 28 29+ (nullable instancetype)modelDebugInfoFromData:(NSData *)data error:(NSError * __autoreleasing *)error { 30 id object = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingOptions)0 error:error]; 31 if (!object) { 32 return nil; 33 } 34 35 NSDictionary<NSString *, id> *jsonDict = SAFE_CAST(object, NSDictionary); 36 // Construct operation path to debug symbol map. 37 NSDictionary<NSString *, NSArray<id> *> *debugSymbolToPathMap = SAFE_CAST(jsonDict[ETCoreMLStrings.debugSymbolToOperationPathKeyName], NSDictionary); 38 NSMutableDictionary<ETCoreMLModelStructurePath *, NSString *> *pathToDebugSymbolMap = [NSMutableDictionary dictionaryWithCapacity:debugSymbolToPathMap.count]; 39 for (NSString *symbolName in debugSymbolToPathMap) { 40 NSArray<NSDictionary<NSString *, id> *> *components = SAFE_CAST(debugSymbolToPathMap[symbolName], NSArray); 41 if (components.count == 0) { 42 continue; 43 } 44 ETCoreMLModelStructurePath *path = [[ETCoreMLModelStructurePath alloc] initWithComponents:components]; 45 pathToDebugSymbolMap[path] = symbolName; 46 47 } 48 // Construct operation path to debug handles map. 49 NSDictionary<NSString *, NSArray<NSString *> *> *debugSymbolToHandles = SAFE_CAST(jsonDict[ETCoreMLStrings.debugSymbolToHandlesKeyName], NSDictionary); 50 NSMutableDictionary<ETCoreMLModelStructurePath *, NSArray<NSString *> *> *pathToDebugHandlesMap = [NSMutableDictionary dictionaryWithCapacity:debugSymbolToHandles.count]; 51 for (NSString *debugSymbol in debugSymbolToHandles) { 52 NSArray<id> *components = debugSymbolToPathMap[debugSymbol]; 53 if (components.count == 0) { 54 continue; 55 } 56 57 NSArray<NSString *> *debugHandles = debugSymbolToHandles[debugSymbol]; 58 if (debugHandles.count == 0) { 59 continue; 60 } 61 62 ETCoreMLModelStructurePath *path = [[ETCoreMLModelStructurePath alloc] initWithComponents:components]; 63 pathToDebugHandlesMap[path] = debugHandles; 64 } 65 66 return [[ETCoreMLModelDebugInfo alloc] initWithPathToDebugSymbolMap:pathToDebugSymbolMap 67 pathToDebugHandlesMap:pathToDebugHandlesMap]; 68 69} 70 71@end 72