-
Notifications
You must be signed in to change notification settings - Fork 839
Add BinaryEmbedding #6398
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add BinaryEmbedding #6398
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
111 changes: 111 additions & 0 deletions
111
src/Libraries/Microsoft.Extensions.AI.Abstractions/Embeddings/BinaryEmbedding.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Buffers; | ||
using System.Collections; | ||
using System.ComponentModel; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
using Microsoft.Shared.Diagnostics; | ||
|
||
namespace Microsoft.Extensions.AI; | ||
|
||
/// <summary>Represents an embedding composed of a bit vector.</summary> | ||
public sealed class BinaryEmbedding : Embedding | ||
{ | ||
/// <summary>The embedding vector this embedding represents.</summary> | ||
private BitArray _vector; | ||
|
||
/// <summary>Initializes a new instance of the <see cref="BinaryEmbedding"/> class with the embedding vector.</summary> | ||
/// <param name="vector">The embedding vector this embedding represents.</param> | ||
/// <exception cref="ArgumentNullException"><paramref name="vector"/> is <see langword="null"/>.</exception> | ||
public BinaryEmbedding(BitArray vector) | ||
{ | ||
_vector = Throw.IfNull(vector); | ||
} | ||
|
||
/// <summary>Gets or sets the embedding vector this embedding represents.</summary> | ||
[JsonConverter(typeof(VectorConverter))] | ||
public BitArray Vector | ||
{ | ||
get => _vector; | ||
set => _vector = Throw.IfNull(value); | ||
} | ||
|
||
/// <inheritdoc /> | ||
[JsonIgnore] | ||
public override int Dimensions => _vector.Length; | ||
|
||
/// <summary>Provides a <see cref="JsonConverter{BitArray}"/> for serializing <see cref="BitArray"/> instances.</summary> | ||
[EditorBrowsable(EditorBrowsableState.Never)] | ||
public sealed class VectorConverter : JsonConverter<BitArray> | ||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
/// <inheritdoc/> | ||
public override BitArray Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
_ = Throw.IfNull(typeToConvert); | ||
_ = Throw.IfNull(options); | ||
|
||
if (reader.TokenType != JsonTokenType.String) | ||
{ | ||
throw new JsonException("Expected string property."); | ||
} | ||
|
||
ReadOnlySpan<byte> utf8; | ||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
byte[]? tmpArray = null; | ||
if (!reader.HasValueSequence && !reader.ValueIsEscaped) | ||
{ | ||
utf8 = reader.ValueSpan; | ||
} | ||
else | ||
{ | ||
// This path should be rare. | ||
int length = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length; | ||
tmpArray = ArrayPool<byte>.Shared.Rent(length); | ||
utf8 = tmpArray.AsSpan(0, reader.CopyString(tmpArray)); | ||
} | ||
|
||
BitArray result = new(utf8.Length); | ||
|
||
for (int i = 0; i < utf8.Length; i++) | ||
{ | ||
result[i] = utf8[i] switch | ||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
(byte)'0' => false, | ||
(byte)'1' => true, | ||
_ => throw new JsonException("Expected binary character sequence.") | ||
}; | ||
} | ||
|
||
if (tmpArray is not null) | ||
{ | ||
ArrayPool<byte>.Shared.Return(tmpArray); | ||
} | ||
|
||
return result; | ||
} | ||
|
||
/// <inheritdoc/> | ||
public override void Write(Utf8JsonWriter writer, BitArray value, JsonSerializerOptions options) | ||
{ | ||
_ = Throw.IfNull(writer); | ||
_ = Throw.IfNull(value); | ||
_ = Throw.IfNull(options); | ||
|
||
int length = value.Length; | ||
|
||
byte[] tmpArray = ArrayPool<byte>.Shared.Rent(length); | ||
|
||
Span<byte> utf8 = tmpArray.AsSpan(0, length); | ||
for (int i = 0; i < utf8.Length; i++) | ||
{ | ||
utf8[i] = value[i] ? (byte)'1' : (byte)'0'; | ||
} | ||
|
||
writer.WriteStringValue(utf8); | ||
|
||
ArrayPool<byte>.Shared.Return(tmpArray); | ||
} | ||
} | ||
} |
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
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
95 changes: 95 additions & 0 deletions
95
test/Libraries/Microsoft.Extensions.AI.Abstractions.Tests/Embeddings/BinaryEmbeddingTests.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Collections; | ||
using System.Linq; | ||
using System.Text.Json; | ||
using Xunit; | ||
|
||
namespace Microsoft.Extensions.AI; | ||
|
||
public class BinaryEmbeddingTests | ||
{ | ||
[Fact] | ||
public void Ctor_Roundtrips() | ||
{ | ||
BitArray vector = new BitArray(new bool[] { false, true, false, true }); | ||
|
||
BinaryEmbedding e = new(vector); | ||
Assert.Same(vector, e.Vector); | ||
Assert.Null(e.ModelId); | ||
Assert.Null(e.CreatedAt); | ||
Assert.Null(e.AdditionalProperties); | ||
} | ||
|
||
[Fact] | ||
public void Properties_Roundtrips() | ||
{ | ||
BitArray vector = new BitArray(new bool[] { false, true, false, true }); | ||
|
||
BinaryEmbedding e = new(vector); | ||
|
||
Assert.Same(vector, e.Vector); | ||
BitArray newVector = new BitArray(new bool[] { true, false, true, false }); | ||
e.Vector = newVector; | ||
Assert.Same(newVector, e.Vector); | ||
|
||
Assert.Null(e.ModelId); | ||
e.ModelId = "text-embedding-3-small"; | ||
Assert.Equal("text-embedding-3-small", e.ModelId); | ||
|
||
Assert.Null(e.CreatedAt); | ||
DateTimeOffset createdAt = DateTimeOffset.Parse("2022-01-01T00:00:00Z"); | ||
e.CreatedAt = createdAt; | ||
Assert.Equal(createdAt, e.CreatedAt); | ||
|
||
Assert.Null(e.AdditionalProperties); | ||
AdditionalPropertiesDictionary props = new(); | ||
e.AdditionalProperties = props; | ||
Assert.Same(props, e.AdditionalProperties); | ||
} | ||
|
||
[Fact] | ||
public void Serialization_Roundtrips() | ||
{ | ||
foreach (int length in Enumerable.Range(0, 64).Concat(new[] { 10_000 })) | ||
{ | ||
bool[] bools = new bool[length]; | ||
Random r = new(42); | ||
for (int i = 0; i < length; i++) | ||
{ | ||
bools[i] = r.Next(2) != 0; | ||
} | ||
|
||
BitArray vector = new BitArray(bools); | ||
BinaryEmbedding e = new(vector); | ||
|
||
string json = JsonSerializer.Serialize(e, TestJsonSerializerContext.Default.Embedding); | ||
Assert.Equal($$"""{"$type":"binary","vector":"{{string.Concat(vector.Cast<bool>().Select(b => b ? '1' : '0'))}}"}""", json); | ||
|
||
BinaryEmbedding result = Assert.IsType<BinaryEmbedding>(JsonSerializer.Deserialize(json, TestJsonSerializerContext.Default.Embedding)); | ||
Assert.Equal(e.Vector, result.Vector); | ||
} | ||
} | ||
|
||
[Fact] | ||
public void Derialization_SupportsEncodedBits() | ||
{ | ||
BinaryEmbedding result = Assert.IsType<BinaryEmbedding>(JsonSerializer.Deserialize( | ||
"""{"$type":"binary","vector":"\u0030\u0031\u0030\u0031\u0030\u0031"}""", | ||
TestJsonSerializerContext.Default.Embedding)); | ||
|
||
Assert.Equal(new BitArray(new[] { false, true, false, true, false, true }), result.Vector); | ||
} | ||
|
||
[Theory] | ||
[InlineData("""{"$type":"binary","vector":"\u0030\u0032"}""")] | ||
[InlineData("""{"$type":"binary","vector":"02"}""")] | ||
[InlineData("""{"$type":"binary","vector":" "}""")] | ||
[InlineData("""{"$type":"binary","vector":10101}""")] | ||
public void Derialization_InvalidBinaryEmbedding_Throws(string json) | ||
{ | ||
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize(json, TestJsonSerializerContext.Default.Embedding)); | ||
} | ||
} |
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
16 changes: 0 additions & 16 deletions
16
test/Libraries/Microsoft.Extensions.AI.Integration.Tests/BinaryEmbedding.cs
This file was deleted.
Oops, something went wrong.
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
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.