Post

Replies

Boosts

Views

Activity

BNNSNDArrayDescriptor rejects manually calculated strides?
Supporse, in a tight loop, I want to matrix MxP with PxN to get MxN (in rowNum x colNum convention). The call to BNNSNDArrayDescriptor.init(data:shape:) always fails if I (correctly) specify all the strides. /* The simplest and fastest matmul(A,B) is when both A and B are in inner- dimension-major order - with the size P dimension stored continuous. i.e. A*(B^T) when A,B are stored in C-like row-major order, or, first-dimension-major order, but first index is the row index, like BLAS */ import Accelerate // Different sizes, so incorrectly-ordered sizes/strides/indices generate error let M: Int = 16 let N: Int = 8 let P: Int = 32 let sizeA = BNNS.Shape.matrixFirstMajor(M, P, stride: (0, 0)) // OK: stride:(1, 0) // bad: stride:(0, 1) -- Matmul failed, because 1 is given to the wrong dimension: should be at least P // stride:(1, P) -- Failed to create BNNSNDArrayDescriptor??? let sizeB = BNNS.Shape.matrixFirstMajor(N, P, stride: (0, 0)) // OK: stride:(1, 0) bad: stride:(0, 1), stride:(1, P) let sizeC = BNNS.Shape.matrixFirstMajor(M, N, stride: (0, 0)) // OK: stride:(1, 0) bad: stride:(0, 1), stride:(1, N) let Mat1 = UnsafeMutableRawBufferPointer .allocate(byteCount: (M+N)*P*4, alignment: 128) .initializeMemory(as: Float.self, repeating: 1.234) let Mat2 = UnsafeMutableRawBufferPointer .allocate(byteCount: M*N*4, alignment: 128) .initializeMemory(as: Float.self, repeating: 0.0) guard let descA = BNNSNDArrayDescriptor( data: Mat1.extracting(0..<M*P), shape: sizeA), let descB = BNNSNDArrayDescriptor( data: Mat1.extracting(M*P..<(M+N)*P), shape: sizeB), let descC = BNNSNDArrayDescriptor( data: Mat2, shape: sizeC) else { print("Failed to create BNNSNDArrayDescriptor."); exit(1) } print(descA) // workspaceSize = BNNS.matrixMultiplicationWorkspaceSize(...) // withUnsafeTemporaryAllocation(byteCount: workspaceSize, alignment: ...) { wksp in var iter = 0 while iter < 1000{ do { try BNNS.applyMatrixMultiplication( inputA: descA, transposed: false, inputB: descB, transposed: true, output: descC, alpha: 1.0, workspace: /*wksp*/ nil) } catch { // Probably got the dimensions backwards, so two matrices are not multiplicable print("Matmul failed: \(error)") break } iter += 1 }I guess in the Swift overlay, the verifying initializer checked a wrong arrangement of stride[k] >= size[k-1] * stride[k-1]. These RowMajor FirstMajor, etc. with all different size and index orderings, are surely confusing. bnns_constants.h:1394 gives the right description. PS: Please don't educate me about deprecation of BNNS. context.executeFunction(arguments: [Aptr, Bptr, Cptr]) is nearly 5x slower for this one-matmul-in-a-tight-loop case, and there's no way to reuse the underlying graph in another thread yet, not withBNNSGraph.Builder. The (im)practical alternative is calling sgemm() that is even more verbose than this.
2
0
132
2w
`log collect` cannot handle shorthands?
While the man page explicitly states that log collect --predicate accepts NSPredicate as well as shorthand, in practice it does not. # Shorthand. log crashes, sudo crashes $ sudo log collect --predicate 's:^"com.apple.power"' log: Unable to process predicate: Unable to parse the format string "s:^"com.apple.power"" Trace/BPT trap: 5 # Full predicate. OK $ sudo log collect --predicate 'subsystem BEGINSWITH "com.apple.power"' Archive successfully written to /PWD/system_logs.logarchive # But: # OK $ sudo log repack --predicate 's:^"com.apple.power"' --archive ./system_logs.logarchive # cleaning up rm -rf ./system_logs.logarchive ./system_logs_repacked.logarchive # OK $ sudo log show --predicate 's:^"com.apple.power"' # OK $ sudo log stats --predicate 's:^"com.apple.power"' # OK $ sudo log stream --predicate 's:^"com.apple.power"' Indeed any form of non-NSPredicate crashes it, including simple mistakes like those: # predicate: =, == # shorthand: IS sudo log collect --predicate 'subsystem IS "com.apple.power"'; rm -rf ./system_logs.logarchive log: Unable to process predicate: Unable to parse the format string "subsystem IS "com.apple.power"" # Strings need to be quoted; identifiers not sudo log collect --predicate 'subsystem = com.apple.power'; rm -rf ./system_logs.logarchive log: Unable to validate mapped predicate log: failed to create archive: Unknown error: -1 (-1) You'd think those verbs all share one predicate parsing code…
1
0
608
Jul ’26
Ditto cannot extract ZIP file into filesystem-compressed files
It's quite common for app bundles to be distributed in .zip files, and to be stored on-disk as filesystem-compressed files. However, having them both appears to be an edge case that's broken for at least two major releases! (FB19048357, FB19329524) I'd expect a simple ditto -x -k appbundle.zip ~/Applications (-x: extract, -k: work on a zip file) to work. Instead it spits out countless errors and leaves 0 Byte files in the aftermath 😭 Please fix.
4
0
554
Jan ’26
hdiutil prints invisible characters for its devnode output
This script from man hdiutil no longer works: devnode=$(hdiutil attach -nomount ram://102400) newfs_hfs “$devnode” mount -t hfs “$devnode” /path/to/ramdisk because $devnode contains spaces and tabs!! $ hdiutil attach -nomount ram://1 | xxd 00000000: 2f64 6576 2f64 6973 6b34 2020 2020 2020 /dev/disk4 00000010: 2020 2020 0920 2020 2020 2020 2020 2020 . 00000020: 2020 2020 2020 2020 2020 2020 2020 2020 00000030: 2020 2020 090a # remember to clean up afterwards $ hdiutil detach /dev/disk4 Please properly quote your variables in CI test scripts to catch such regression. It could pass because unquoted expansion of $devnode undergoes word splitting after the variable is substituted, removing the trailing whitespaces. FB20303191
1
0
134
Nov ’25
MPSMatrixRandom SEGFAULTs when ran in an async context
The following minimal snippet SEGFAULTS with SDK 26.0 and 26.1. Won't crash if I remove async from the enclosing function signature - but it's impractical in a real project. import Metal import MetalPerformanceShaders let SEED = UInt64(0x0) typealias T = Float16 /* Why ran in async context? Because global GPU object, and async makeMTLFunction, and async makeMTLComputePipelineState. Nevertheless, can trigger the bug without using global @MainActor let myGPU = MyGPU() */ @main struct CMDLine { static func main() async { let ptr = UnsafeMutablePointer<T>.allocate(capacity: 0) async let future: Void = randomFillOnGPU(ptr, count: 0) print("Main thread is playing around") await future print("Successfully reached the end.") } static func randomFillOnGPU(_ buf: UnsafeMutablePointer<T>, count destbufcount: Int) async { // let (device, queue) = await (myGPU.device, myGPU.commandqueue) let myGPU = MyGPU() let (device, queue) = (myGPU.device, myGPU.commandqueue) // Init MTLBuffer, async let makeFunction, makeComputePipelineState, etc. let tempDataType = MPSDataType.uInt32 let randfiller = MPSMatrixRandomMTGP32(device: device, destinationDataType: tempDataType, seed: Int(bitPattern:UInt(SEED))) print("randomFillOnGPU: successfully created MPSMatrixRandom.") // try await computePipelineState // ^ Crashes before this could return // Or in this minimal case, after randomFillOnGPU() returns // make encoder, set pso, dispatch, commit... } } actor MyGPU { let device : MTLDevice let commandqueue : MTLCommandQueue init() { guard let dev: MTLDevice = MPSGetPreferredDevice(.skipRemovable), let cq = dev.makeCommandQueue(), dev.supportsFamily(.apple6) || dev.supportsFamily(.mac2) else { print("Unable to get Metal Device! Exiting"); exit(EX_UNAVAILABLE) } print("Selected device: \(String(format: "%llX", dev.registryID))") self.device = dev self.commandqueue = cq print("myGPU: initialization complete.") } } See FB20916929. Apparently objc autorelease pool is releasing the wrong address during context switch (across suspension points). I wonder why such obvious case has not been caught before.
0
0
589
Nov ’25
Horrendous Swift overlay of vDSP Fourier Transform functions
I'm very unpleased to have found out the hard way, that vDSP.FFT&amp;lt;T&amp;gt; where T : vDSP_FourierTransformable and its associated vDSP_FourierTransformFunctions, only does real-complex conversion!!! This is horribly misleading - the only hint that it calls vDSP_fft_zrop() (split-complex real-complex out-of-place) under the hood, not vDSP_fft_zop()[1], is "A 1D single- and double-precision fast Fourier transform." - instead of "a single- and double-precision complex fast Fourier transform". Holy ******* ****. Just look at how people miss-call this routine. Poor him, realizing he had to log2n+1 lest only the first half of the array was transformed, not understanding why [2]. And poor me, having taken days investigating why a simple Swift overlay vDSP.FFT.transform may execute at 1.4x the speed of vDSP_fft_zopt(out-of-place with temporary buffer)! [3] [1]: or better, vDSP_fft_zopt with the temp buffer alloc/dealloc taken care of, for us [2]: for real-complex conversion, say real signal of length 16. log2n is 4 no problem, but then the real and imaginary vectors are both length 8. Also, vDSP_fft only works on integer powers of 2, so he had to choose next integer power of 2 (i.e. 1&amp;lt;&amp;lt;(log2n-1)) instead of plain length for his internal arrays. [3]: you guessed it. fft_zrop(log2n-1, ...) vs. fft_zop(log2n, ...). Half the problem size lol. Now we have vDSP.DiscreteFourierTransform, which wraps vDSP_DFT routines and "calls FFT routines when the size allows it", and works too for interleaved complexes. Just go all DFT, right? if let setup_f = try? vDSP.DiscreteFourierTransform(previous: nil, count: 8, direction: .forward, transformType: .complexComplex, ofType: DSPComplex.self) { // Done forward transformation // and scaled the results with 1/N // How about going reverse? if let setup_r = try? vDSP.DiscreteFourierTransform(previous: setup_f, count: 8, direction: .inverse, transformType: .complexComplex, ofType: DSPComplex.self) { // Error: cannot convert vDSP.DiscreteFourierTransform&amp;lt;DSPComplex&amp;gt; to vDSP.DiscreteFourierTransform&amp;lt;Float&amp;gt; // lolz } } This API appeared in macOS 12. 3 years later nobody have ever noticed. I'm at a loss for words.
4
0
757
Jun ’25
BNNSNDArrayDescriptor rejects manually calculated strides?
Supporse, in a tight loop, I want to matrix MxP with PxN to get MxN (in rowNum x colNum convention). The call to BNNSNDArrayDescriptor.init(data:shape:) always fails if I (correctly) specify all the strides. /* The simplest and fastest matmul(A,B) is when both A and B are in inner- dimension-major order - with the size P dimension stored continuous. i.e. A*(B^T) when A,B are stored in C-like row-major order, or, first-dimension-major order, but first index is the row index, like BLAS */ import Accelerate // Different sizes, so incorrectly-ordered sizes/strides/indices generate error let M: Int = 16 let N: Int = 8 let P: Int = 32 let sizeA = BNNS.Shape.matrixFirstMajor(M, P, stride: (0, 0)) // OK: stride:(1, 0) // bad: stride:(0, 1) -- Matmul failed, because 1 is given to the wrong dimension: should be at least P // stride:(1, P) -- Failed to create BNNSNDArrayDescriptor??? let sizeB = BNNS.Shape.matrixFirstMajor(N, P, stride: (0, 0)) // OK: stride:(1, 0) bad: stride:(0, 1), stride:(1, P) let sizeC = BNNS.Shape.matrixFirstMajor(M, N, stride: (0, 0)) // OK: stride:(1, 0) bad: stride:(0, 1), stride:(1, N) let Mat1 = UnsafeMutableRawBufferPointer .allocate(byteCount: (M+N)*P*4, alignment: 128) .initializeMemory(as: Float.self, repeating: 1.234) let Mat2 = UnsafeMutableRawBufferPointer .allocate(byteCount: M*N*4, alignment: 128) .initializeMemory(as: Float.self, repeating: 0.0) guard let descA = BNNSNDArrayDescriptor( data: Mat1.extracting(0..<M*P), shape: sizeA), let descB = BNNSNDArrayDescriptor( data: Mat1.extracting(M*P..<(M+N)*P), shape: sizeB), let descC = BNNSNDArrayDescriptor( data: Mat2, shape: sizeC) else { print("Failed to create BNNSNDArrayDescriptor."); exit(1) } print(descA) // workspaceSize = BNNS.matrixMultiplicationWorkspaceSize(...) // withUnsafeTemporaryAllocation(byteCount: workspaceSize, alignment: ...) { wksp in var iter = 0 while iter < 1000{ do { try BNNS.applyMatrixMultiplication( inputA: descA, transposed: false, inputB: descB, transposed: true, output: descC, alpha: 1.0, workspace: /*wksp*/ nil) } catch { // Probably got the dimensions backwards, so two matrices are not multiplicable print("Matmul failed: \(error)") break } iter += 1 }I guess in the Swift overlay, the verifying initializer checked a wrong arrangement of stride[k] >= size[k-1] * stride[k-1]. These RowMajor FirstMajor, etc. with all different size and index orderings, are surely confusing. bnns_constants.h:1394 gives the right description. PS: Please don't educate me about deprecation of BNNS. context.executeFunction(arguments: [Aptr, Bptr, Cptr]) is nearly 5x slower for this one-matmul-in-a-tight-loop case, and there's no way to reuse the underlying graph in another thread yet, not withBNNSGraph.Builder. The (im)practical alternative is calling sgemm() that is even more verbose than this.
Replies
2
Boosts
0
Views
132
Activity
2w
`log collect` cannot handle shorthands?
While the man page explicitly states that log collect --predicate accepts NSPredicate as well as shorthand, in practice it does not. # Shorthand. log crashes, sudo crashes $ sudo log collect --predicate 's:^"com.apple.power"' log: Unable to process predicate: Unable to parse the format string "s:^"com.apple.power"" Trace/BPT trap: 5 # Full predicate. OK $ sudo log collect --predicate 'subsystem BEGINSWITH "com.apple.power"' Archive successfully written to /PWD/system_logs.logarchive # But: # OK $ sudo log repack --predicate 's:^"com.apple.power"' --archive ./system_logs.logarchive # cleaning up rm -rf ./system_logs.logarchive ./system_logs_repacked.logarchive # OK $ sudo log show --predicate 's:^"com.apple.power"' # OK $ sudo log stats --predicate 's:^"com.apple.power"' # OK $ sudo log stream --predicate 's:^"com.apple.power"' Indeed any form of non-NSPredicate crashes it, including simple mistakes like those: # predicate: =, == # shorthand: IS sudo log collect --predicate 'subsystem IS "com.apple.power"'; rm -rf ./system_logs.logarchive log: Unable to process predicate: Unable to parse the format string "subsystem IS "com.apple.power"" # Strings need to be quoted; identifiers not sudo log collect --predicate 'subsystem = com.apple.power'; rm -rf ./system_logs.logarchive log: Unable to validate mapped predicate log: failed to create archive: Unknown error: -1 (-1) You'd think those verbs all share one predicate parsing code…
Replies
1
Boosts
0
Views
608
Activity
Jul ’26
Ditto cannot extract ZIP file into filesystem-compressed files
It's quite common for app bundles to be distributed in .zip files, and to be stored on-disk as filesystem-compressed files. However, having them both appears to be an edge case that's broken for at least two major releases! (FB19048357, FB19329524) I'd expect a simple ditto -x -k appbundle.zip ~/Applications (-x: extract, -k: work on a zip file) to work. Instead it spits out countless errors and leaves 0 Byte files in the aftermath 😭 Please fix.
Replies
4
Boosts
0
Views
554
Activity
Jan ’26
hdiutil prints invisible characters for its devnode output
This script from man hdiutil no longer works: devnode=$(hdiutil attach -nomount ram://102400) newfs_hfs “$devnode” mount -t hfs “$devnode” /path/to/ramdisk because $devnode contains spaces and tabs!! $ hdiutil attach -nomount ram://1 | xxd 00000000: 2f64 6576 2f64 6973 6b34 2020 2020 2020 /dev/disk4 00000010: 2020 2020 0920 2020 2020 2020 2020 2020 . 00000020: 2020 2020 2020 2020 2020 2020 2020 2020 00000030: 2020 2020 090a # remember to clean up afterwards $ hdiutil detach /dev/disk4 Please properly quote your variables in CI test scripts to catch such regression. It could pass because unquoted expansion of $devnode undergoes word splitting after the variable is substituted, removing the trailing whitespaces. FB20303191
Replies
1
Boosts
0
Views
134
Activity
Nov ’25
MPSMatrixRandom SEGFAULTs when ran in an async context
The following minimal snippet SEGFAULTS with SDK 26.0 and 26.1. Won't crash if I remove async from the enclosing function signature - but it's impractical in a real project. import Metal import MetalPerformanceShaders let SEED = UInt64(0x0) typealias T = Float16 /* Why ran in async context? Because global GPU object, and async makeMTLFunction, and async makeMTLComputePipelineState. Nevertheless, can trigger the bug without using global @MainActor let myGPU = MyGPU() */ @main struct CMDLine { static func main() async { let ptr = UnsafeMutablePointer<T>.allocate(capacity: 0) async let future: Void = randomFillOnGPU(ptr, count: 0) print("Main thread is playing around") await future print("Successfully reached the end.") } static func randomFillOnGPU(_ buf: UnsafeMutablePointer<T>, count destbufcount: Int) async { // let (device, queue) = await (myGPU.device, myGPU.commandqueue) let myGPU = MyGPU() let (device, queue) = (myGPU.device, myGPU.commandqueue) // Init MTLBuffer, async let makeFunction, makeComputePipelineState, etc. let tempDataType = MPSDataType.uInt32 let randfiller = MPSMatrixRandomMTGP32(device: device, destinationDataType: tempDataType, seed: Int(bitPattern:UInt(SEED))) print("randomFillOnGPU: successfully created MPSMatrixRandom.") // try await computePipelineState // ^ Crashes before this could return // Or in this minimal case, after randomFillOnGPU() returns // make encoder, set pso, dispatch, commit... } } actor MyGPU { let device : MTLDevice let commandqueue : MTLCommandQueue init() { guard let dev: MTLDevice = MPSGetPreferredDevice(.skipRemovable), let cq = dev.makeCommandQueue(), dev.supportsFamily(.apple6) || dev.supportsFamily(.mac2) else { print("Unable to get Metal Device! Exiting"); exit(EX_UNAVAILABLE) } print("Selected device: \(String(format: "%llX", dev.registryID))") self.device = dev self.commandqueue = cq print("myGPU: initialization complete.") } } See FB20916929. Apparently objc autorelease pool is releasing the wrong address during context switch (across suspension points). I wonder why such obvious case has not been caught before.
Replies
0
Boosts
0
Views
589
Activity
Nov ’25
Horrendous Swift overlay of vDSP Fourier Transform functions
I'm very unpleased to have found out the hard way, that vDSP.FFT&amp;lt;T&amp;gt; where T : vDSP_FourierTransformable and its associated vDSP_FourierTransformFunctions, only does real-complex conversion!!! This is horribly misleading - the only hint that it calls vDSP_fft_zrop() (split-complex real-complex out-of-place) under the hood, not vDSP_fft_zop()[1], is "A 1D single- and double-precision fast Fourier transform." - instead of "a single- and double-precision complex fast Fourier transform". Holy ******* ****. Just look at how people miss-call this routine. Poor him, realizing he had to log2n+1 lest only the first half of the array was transformed, not understanding why [2]. And poor me, having taken days investigating why a simple Swift overlay vDSP.FFT.transform may execute at 1.4x the speed of vDSP_fft_zopt(out-of-place with temporary buffer)! [3] [1]: or better, vDSP_fft_zopt with the temp buffer alloc/dealloc taken care of, for us [2]: for real-complex conversion, say real signal of length 16. log2n is 4 no problem, but then the real and imaginary vectors are both length 8. Also, vDSP_fft only works on integer powers of 2, so he had to choose next integer power of 2 (i.e. 1&amp;lt;&amp;lt;(log2n-1)) instead of plain length for his internal arrays. [3]: you guessed it. fft_zrop(log2n-1, ...) vs. fft_zop(log2n, ...). Half the problem size lol. Now we have vDSP.DiscreteFourierTransform, which wraps vDSP_DFT routines and "calls FFT routines when the size allows it", and works too for interleaved complexes. Just go all DFT, right? if let setup_f = try? vDSP.DiscreteFourierTransform(previous: nil, count: 8, direction: .forward, transformType: .complexComplex, ofType: DSPComplex.self) { // Done forward transformation // and scaled the results with 1/N // How about going reverse? if let setup_r = try? vDSP.DiscreteFourierTransform(previous: setup_f, count: 8, direction: .inverse, transformType: .complexComplex, ofType: DSPComplex.self) { // Error: cannot convert vDSP.DiscreteFourierTransform&amp;lt;DSPComplex&amp;gt; to vDSP.DiscreteFourierTransform&amp;lt;Float&amp;gt; // lolz } } This API appeared in macOS 12. 3 years later nobody have ever noticed. I'm at a loss for words.
Replies
4
Boosts
0
Views
757
Activity
Jun ’25