feat: MLXArray initializers for nested Swift arrays (#161)#392
Open
VDurocher wants to merge 2 commits intoml-explore:mainfrom
Open
feat: MLXArray initializers for nested Swift arrays (#161)#392VDurocher wants to merge 2 commits intoml-explore:mainfrom
VDurocher wants to merge 2 commits intoml-explore:mainfrom
Conversation
Introduces MLXNestedArray protocol and MLXArray.init(_ nested:) to support ergonomic construction of multi-dimensional arrays from nested Swift array literals, mirroring the Python mx.array() API.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #161
What
Adds
MLXArrayinitializers that accept nested Swift arrays of any depth, matching the ergonomics of the Pythonmx.array([[1, 2], [3, 4]])API.How
MLXNestedArrayprotocol withmlxShapeandmlxFlattenedValues()requirementsArrayconforms when itsElementalso conforms (recursive) — supports any depthFloat32,Float64,Int32,Int64,UInt8,UInt16,UInt32,Bool,Float16) conform as leaf typesMLXArray.init(_ rows: [[T]])(2D) andMLXArray.init(_ slices: [[[T]]])(3D) overloads for clean type inference at call-site[[Int]]and[[[Int]]]overloads that mirror the existing[Int]behaviour (converts toInt32, with bounds-checking precondition)precondition— jagged arrays fail fast with a descriptive messageExamples
Files changed
Source/MLX/MLXArray+NestedInit.swiftTests/MLXTests/MLXArray+NestedInitTests.swiftNotes
MLXNestedArraygenericinitis available as an escape hatch for deeper nesting (4D+), but the 2D/3D typed overloads are preferred for day-to-day use because Swift's type inference works better with concrete overloads[[Double]]works through theFloat64: MLXNestedArrayconformance (dtype.float64) — consistent with the existinginit<T: HasDType>(_ value: [T])behaviour forDouble