Smelter 0.10.5

Smelter 0.10.5

Eugene Bokhans1ddok 维护。



 
依赖
SwiftProtobuf~> 1.7.0
Alloy/ML~> 0.16.3
 

Smelter 0.10.5

  • Andrey Volodin 和 Eugene Bokhan

Smelter

无需开销的 ONNX 图形推理引擎,底层使用 Metal。

⚠️重要:尽管我们在生产环境中使用此库运行所有神经网络,但当前它处于高度实验状态:API 可能会更改,ONNX 格式的所有层均不支持。欢迎所有拉取请求!

主要特性

  • 原生的 ONNX 文件格式支持,不同存储模式
  • ONNX 图优化预处理步骤
  • 无缝的原生 GPU 集成
  • 易于使用的 API

使用示例

  • 图形初始化
    // Read ONNX model data.
    let context = MTLContext(device: Metal.device)
    let modelURL = Bundle.main.url(forResource: "yourAwesomeModel",
                                  withExtension: "onnx")!
    let modelData = try Data(contentsOf: modelURL)
    // Specify ONNXGraph configuration.
    let configuration = ONNXGraph.Configuration(inputConstraint: .forceInputScale(scale: .bilinear))
    // Initialize the MPSNNGraph.
    let nnGraph = try ONNXGraph(data: modelData).metalGraph(device: context.device,
                                                            configuration: configuration)
  • 图推理

    由于《Melter》使用了Alloy作为一个依赖项,我们可以自由使用其方便的工具来创建纹理和读取图结果。

    /// Create texture from CGImage.
    guard
        let inputTexture = try self.metalContext.texture(from: cgImage)
    else { throw Errors.textureCreationFailed }
    
    /// Create MPSImage from MTLTexture.
    let inputMPSImage = MPSImage(texture: inputTexture,
                                 featureChannels: 3)
                                 
    /// Encode the MPSNNGraph.
    guard
        let modelGraphResult = nnGraph.encode(to: commandBuffer,
                                              sourceImages: [inputMPSImage])
    else { throw Errors.graphEncodingFailed }
    
    /// Read the results.
    guard
        let output = modelGraphResult.toFloatArray()
    else { throw Errors.graphResultReadingFailed }
  • 预处理步骤

    由于ONNX存储权重时的存储规范与Metal性能着色器中使用的不同,Smelter支持在运行时对这些权重进行转置,但某些图的转换可能需要一段时间。我们建议您用我们的脚本对图进行预处理。它具有融合某些层(例如,批归一化到卷积)、将您的权重转换为fp16等一些额外功能。

    python3 ONNX2MPS.py --input ulr_to_your_model.onnx --output ulr_to_your_optimized_model.onnx [--half]

已知问题

  • 由于MPSNNGraph不提供所有由ONNX提供的层的对应物,因此不支持所有模型
  • 一些Metal实现存在bug
    • 当两个操作数都具有4的倍数个功能通道时,Concat才能工作
    • 当它们是第二个操作数时,Concat在某些层中不起作用(例如,“Upsample + Conv”可以工作,而“Conv + Upsample”则不行)
    • 某些节点仅在更高版本的iOS上可用(例如,Reshape仅在12.1之后可用,但通常您可以将其全部从模型中删除)
    • 某些Metal卷积实现产生NaN

安装

CocoaPods

CocoaPods是Cocoa项目的依赖项管理器。有关用法和安装说明,请访问他们的网站。要使用CocoaPods将Melter集成到您的Xcode项目中,请在您的Podfile中指定它。

# Optionally add version, i.e. '~> 1.0.0'
pod 'Smelter'

许可协议

MIT

作者

Oleg Poyaganov (@opedge), Andrey Volodin (@s1ddok), Konstantin Semyanov (@ksemianov), Eugene Bokhan (@eugenebokhan) Anton Lebedev (@antoleb)