用两个输入实现CoreML自定义层

时间:2018-09-18 20:37:54

标签: metal coreml coremltools

我有一个想要转换为CoreML的张量流图,但是它使用了一些缺少的操作,这些操作必须作为自定义层来实现。

我现在关注的两个操作是SinFloorDiv

Sin非常简单,我可以遵循this tutorial,并且我有一个可以正常工作的Swift类和Metal内核,我用玩具coreml文件对其进行了测试:< / p>

import Foundation
import CoreML
import Accelerate

@objc(Sin) class Sin: NSObject, MLCustomLayer {

    let sinPipeline: MTLComputePipelineState

    required init(parameters: [String : Any]) throws {
        print(#function, parameters)

        let sinFunction = GPUDispatch.sharedInstance.library.makeFunction(name: "sin")!
        sinPipeline = try! GPUDispatch.sharedInstance.device.makeComputePipelineState(
            function: sinFunction)


        super.init()
    }

    func setWeightData(_ weights: [Data]) throws {
        print(#function, weights)
    }


    func outputShapes(forInputShapes inputShapes: [[NSNumber]]) throws
        -> [[NSNumber]] {
            print(#function, inputShapes)
            return inputShapes
    }

    func evaluate(inputs: [MLMultiArray], outputs: [MLMultiArray]) throws {

        for i in 0..<inputs.count {
            let input = inputs[i]
            let output = outputs[i]

            var count = Int32(input.count)
            let iptr = UnsafeMutablePointer<Float>(OpaquePointer(input.dataPointer))
            let optr = UnsafeMutablePointer<Float>(OpaquePointer(output.dataPointer))

            vvsinf(optr, iptr, &count)
        }

    }

    func encode(commandBuffer: MTLCommandBuffer,
                inputs: [MTLTexture], outputs: [MTLTexture]) throws {
        if let encoder = commandBuffer.makeComputeCommandEncoder() {
            for i in 0..<inputs.count {
                encoder.setTexture(inputs[i], index: 0)
                encoder.setTexture(outputs[i], index: 1)
                encoder.dispatch(pipeline: sinPipeline, texture: inputs[i])
                encoder.endEncoding()
            }
        }
    }

}

Sin.metal中的

kernel void sin(
                  texture2d_array<half, access::read> inTexture [[texture(0)]],
                  texture2d_array<half, access::write> outTexture [[texture(1)]],
                  ushort3 gid [[thread_position_in_grid]])
{
    if (gid.x >= outTexture.get_width() ||
        gid.y >= outTexture.get_height()) {
        return;
    }

    const float4 x = float4(inTexture.read(gid.xy, gid.z));
    const float4 y = sin(x);
    outTexture.write(half4(y), gid.xy, gid.z);
}

我不明白的是,如果自定义层有两个输入,例如我对FloorDiv的要求,它将返回floor(x / y),这将如何工作。

即使提供的Sin类仅在CPU上,我该如何调整它来产生类似sin(x*y)的类?这类事情还有其他好的教程吗?

1 个答案:

答案 0 :(得分:0)

模式与我预期的不同,但是现在我已经处理了更多的代码,这非常明显。

这是一个实现FloorDiv的类:

import Foundation
import CoreML
import Accelerate

@objc(FloorDiv) class FloorDiv: NSObject, MLCustomLayer {

    let floorDivPipeline: MTLComputePipelineState

    required init(parameters: [String : Any]) throws {
        print(#function, parameters)

        let floorDivFunction = GPUDispatch.sharedInstance.library.makeFunction(name: "floordiv")!
        floorDivPipeline = try! GPUDispatch.sharedInstance.device.makeComputePipelineState(
            function: floorDivFunction)

        super.init()
    }

    func setWeightData(_ weights: [Data]) throws {
        print(#function, weights)
    }

    func outputShapes(forInputShapes inputShapes: [[NSNumber]]) throws
        -> [[NSNumber]] {
            print(#function, inputShapes)
            return inputShapes
    }

    func evaluate(inputs: [MLMultiArray], outputs: [MLMultiArray]) throws {

        let numerator = inputs[0]
        let denominator = inputs[1]
        var output = outputs[0]


        assert(numerator.count == denominator.count)

        var count = Int32(numerator.count)
        let numerator_ptr = UnsafeMutablePointer<Float>(OpaquePointer(numerator.dataPointer))
        let denominator_ptr = UnsafeMutablePointer<Float>(OpaquePointer(denominator.dataPointer))

        let output_ptr = UnsafeMutablePointer<Float>(OpaquePointer(output.dataPointer))

        vvdivf(output_ptr, numerator_ptr, denominator_ptr, &count)
        vvfloorf(output_ptr, output_ptr, &count)

    }


    func encode(commandBuffer: MTLCommandBuffer,
                inputs: [MTLTexture], outputs: [MTLTexture]) throws {

        if let encoder = commandBuffer.makeComputeCommandEncoder() {

                encoder.setTexture(inputs[0], index: 0)
                encoder.setTexture(inputs[1], index: 1)
                encoder.setTexture(outputs[0], index: 2)

                encoder.dispatch(pipeline: floorDivPipeline, texture: inputs[0])
                encoder.endEncoding()

        }
    }

}

这是金属内核:

#include <metal_stdlib>
using namespace metal;

kernel void floordiv(
                 texture2d_array<half, access::read> inTexture [[texture(0)]],
                 texture2d_array<half, access::read> inTexture2 [[texture(1)]],
                 texture2d_array<half, access::write> outTexture [[texture(2)]],
                 ushort3 gid [[thread_position_in_grid]])
{
    if (gid.x >= outTexture.get_width() ||
        gid.y >= outTexture.get_height()) {
        return;
    }

    const float4 x = float4(inTexture.read(gid.xy, gid.z));
    const float4 x2 = float4(inTexture2.read(gid.xy, gid.z));
    const float4 y = floor(x / x2);
    outTexture.write(half4(y), gid.xy, gid.z);
}