Repository navigation
Define equality/GetHashCode for the Vector class - #22
Conversation
1d703a9 to
00518ef
Compare
|
Thanks @roji. I think it should use value-based equality. Happy to consider using |
|
Switched in 5602594. |
|
|
||
| var vec = value.ToArray(); | ||
| var dim = vec.Length; | ||
| var span = value.Memory.Span; |
There was a problem hiding this comment.
This accesses the data directly, removing an additional memory allocation and copy.
| public class Vector : IEquatable<Vector> | ||
| { | ||
| private ReadOnlyMemory<float> vec; | ||
| public ReadOnlyMemory<float> Memory { get; } |
There was a problem hiding this comment.
This exposes the ReadOnlyMemory publicly, so that users (as well as the plugin's converter) can access the data without copying (which is what ToArray does below)
| public Vector(ReadOnlyMemory<float> v) | ||
| => vec = v; | ||
|
|
||
| public Vector(float[] v) |
There was a problem hiding this comment.
Note that arrays are implicitly convertible to Memory/ReadOnlyMemory, so there's no need for this constructor.
|
Awesome, thanks! |
|
Thanks for merging! Great to see this coming along. |
@ankane here's a change adding equality/hash code logic to the Vector class.
Note that this implementation compares the
float[]reference and not its contents, so two Vector instances with identical float contents are not considered equal.I actually think that true value semantics (i.e. comparing the data) would be more useful. However, although the array itself is currently immutable (I added
readonlyto vec to make that explicit), its contents are mutable (since the full array is exposed rather than e.g.ReadOnlyMemory<float>). This means that Vector is currently a mutable type, and so it's a bad idea to define GetHashCode() over the contents.IMHO ideally Vector would be fully immutable, accepting and exposing only
ReadOnlyMemory<float>; this would allow full value semantics (i.e. equality and hash code based on the data contents), and would incidentally also allow users to define Vectors over slices of data/native memory (this is a general advantage of ReadOnlyMemory over working only with arrays). FYI we're trying to more or less standardize onReadOnlyMemory<float>in general as the representation for vector databases (e.g. in the SemanticKernel project). Let me know if you want to take it in this direction.One unrelated note: I'd recommend changing the ToArray() method; there are many places in .NET where ToArray() means that an array copy is created (e.g. IEnumerable.ToArray), whereas here it simply returns the vector (this confused me as well).