Last active
November 5, 2024 10:34
-
-
Save niw/456d83732bd2c720359abfab1e6eae0f to your computer and use it in GitHub Desktop.
Check `MPSGraph.padTensor(_:with:leftPadding:rightPadding:constantValue:name)` behavior.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env xcrun swift | |
import Foundation | |
import MetalPerformanceShaders | |
import MetalPerformanceShadersGraph | |
let device = MTLCreateSystemDefaultDevice()! | |
//let size = 256 * 256 - 1 // This size should work | |
let size = 256 * 256 // This size may not work | |
let shape = [1, 1, 1, 1, size] as [NSNumber] | |
let graph = MPSGraph() | |
let input = graph.placeholder(shape: shape, name: "input") | |
let output = graph.padTensor( | |
input, | |
with: .clampToEdge, | |
leftPadding: [0, 0, 2, 0, 0] as [NSNumber], | |
rightPadding: [0, 0, 0, 0, 0] as [NSNumber], | |
constantValue: 0.0, | |
name: nil | |
) | |
let inputArrayDescription = MPSNDArrayDescriptor( | |
dataType: .float32, | |
shape: shape | |
) | |
let inputArray = MPSNDArray(device: device, descriptor: inputArrayDescription) | |
var inputValues = [Float](repeating: 0.0, count: Int(size)) | |
for x in 0..<size { | |
inputValues[x] = Float.random(in: 0.0..<1.0) | |
} | |
inputArray.writeBytes(&inputValues, strideBytes: nil) | |
let results = graph.run( | |
feeds: [ | |
input: MPSGraphTensorData(inputArray) | |
], | |
targetTensors: [ | |
output | |
], | |
targetOperations: [] | |
) | |
let outputData = results[output]! | |
var outputValues = [Float](repeating: 0, count: Int(size * 3)) | |
outputData.mpsndarray().readBytes(&outputValues, strideBytes: nil) | |
print("checking...") | |
for d in 0..<3 { | |
for x in 0..<size { | |
let inputIndex = x | |
let input = inputValues[inputIndex] | |
let outputIndex = d * size + x | |
let output = outputValues[outputIndex] | |
if input != output { | |
print("\(inputIndex) -> \(outputIndex): \(input) != \(output)") | |
} | |
} | |
} | |
print("done") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment