Skip to content

Commit 22f35fe

Browse files
committed
Add GPT3 tokenizer (workaround for broken SK tokenizer)
1 parent 55a7608 commit 22f35fe

18 files changed

Lines changed: 50423 additions & 29 deletions

File tree

.editorconfig

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -115,26 +115,23 @@ dotnet_diagnostic.RCS1214.severity = warning # Unnecessary interpolated string.
115115
dotnet_diagnostic.RCS1225.severity = warning # Make class sealed.
116116
dotnet_diagnostic.RCS1232.severity = warning # Order elements in documentation comment.
117117

118-
# Commented out because `dotnet format` change can be disruptive.
119-
# dotnet_diagnostic.RCS1085.severity = warning # Use auto-implemented property.
120-
121-
# Commented out because `dotnet format` removes the xmldoc element, while we should add the missing documentation instead.
122-
# dotnet_diagnostic.RCS1228.severity = warning # Unused element in documentation comment.
123-
124118
# Diagnostics elevated as warnings
125119
dotnet_diagnostic.CA1000.severity = warning # Do not declare static members on generic types
126120
dotnet_diagnostic.CA1031.severity = warning # Do not catch general exception types
127121
dotnet_diagnostic.CA1050.severity = warning # Declare types in namespaces
128122
dotnet_diagnostic.CA1063.severity = warning # Implement IDisposable correctly
129123
dotnet_diagnostic.CA1064.severity = warning # Exceptions should be public
124+
dotnet_diagnostic.CA1303.severity = warning # Do not pass literals as localized parameters
130125
dotnet_diagnostic.CA1416.severity = warning # Validate platform compatibility
131126
dotnet_diagnostic.CA1508.severity = warning # Avoid dead conditional code
127+
dotnet_diagnostic.CS1591.severity = warning # Missing XML comment for publicly visible type or member
132128
dotnet_diagnostic.CA1852.severity = warning # Sealed classes
133129
dotnet_diagnostic.CA1859.severity = warning # Use concrete types when possible for improved performance
134130
dotnet_diagnostic.CA1860.severity = warning # Prefer comparing 'Count' to 0 rather than using 'Any()', both for clarity and for performance
135131
dotnet_diagnostic.CA2000.severity = warning # Call System.IDisposable.Dispose on object before all references to it are out of scope
136132
dotnet_diagnostic.CA2007.severity = error # Do not directly await a Task
137133
dotnet_diagnostic.CA2201.severity = warning # Exception type System.Exception is not sufficiently specific
134+
dotnet_diagnostic.CA2225.severity = warning # Operator overloads have named alternates
138135

139136
dotnet_diagnostic.IDE0001.severity = warning # Simplify name
140137
dotnet_diagnostic.IDE0005.severity = warning # Remove unnecessary using directives
@@ -158,37 +155,40 @@ dotnet_diagnostic.IDE0090.severity = warning # Simplify new expression
158155
dotnet_diagnostic.IDE0130.severity = warning # Namespace does not match folder structure
159156
dotnet_diagnostic.IDE0161.severity = warning # Use file-scoped namespace
160157

158+
dotnet_diagnostic.RCS1032.severity = warning # Remove redundant parentheses.
159+
dotnet_diagnostic.RCS1118.severity = warning # Mark local variable as const.
160+
dotnet_diagnostic.RCS1141.severity = warning # Add 'param' element to documentation comment.
161+
dotnet_diagnostic.RCS1197.severity = warning # Optimize StringBuilder.AppendLine call.
162+
dotnet_diagnostic.RCS1205.severity = warning # Order named arguments according to the order of parameters.
163+
dotnet_diagnostic.RCS1229.severity = warning # Use async/await when necessary.
164+
161165
dotnet_diagnostic.VSTHRD111.severity = error # Use .ConfigureAwait(bool)
162166

163167
# Suppressed diagnostics
168+
169+
# Commented out because `dotnet format` change can be disruptive.
170+
# dotnet_diagnostic.RCS1085.severity = warning # Use auto-implemented property.
171+
172+
# Commented out because `dotnet format` removes the xmldoc element, while we should add the missing documentation instead.
173+
# dotnet_diagnostic.RCS1228.severity = warning # Unused element in documentation comment.
174+
164175
dotnet_diagnostic.CA1002.severity = none # Change 'List<string>' in '...' to use 'Collection<T>' ...
165176
dotnet_diagnostic.CA1032.severity = none # We're using RCS1194 which seems to cover more ctors
166177
dotnet_diagnostic.CA1034.severity = none # Do not nest type. Alternatively, change its accessibility so that it is not externally visible
167178
dotnet_diagnostic.CA1062.severity = none # Disable null check, C# already does it for us
168-
dotnet_diagnostic.CA1303.severity = warning # Do not pass literals as localized parameters
169-
dotnet_diagnostic.CS1591.severity = warning # Missing XML comment for publicly visible type or member
170179
dotnet_diagnostic.CA1805.severity = none # Member is explicitly initialized to its default value
171180
dotnet_diagnostic.CA1822.severity = none # Member does not access instance data and can be marked as static
172181
dotnet_diagnostic.CA1848.severity = none # For improved performance, use the LoggerMessage delegates
173-
dotnet_diagnostic.CA2007.severity = warning # Do not directly await a Task
174-
dotnet_diagnostic.CA2225.severity = warning # Operator overloads have named alternates
175182
dotnet_diagnostic.CA2227.severity = none # Change to be read-only by removing the property setter
176183
dotnet_diagnostic.CA2253.severity = none # Named placeholders in the logging message template should not be comprised of only numeric characters
177-
178-
dotnet_diagnostic.VSTHRD111.severity = none # Use .ConfigureAwait(bool) is hidden by default, set to none to prevent IDE from changing on autosave
179-
dotnet_diagnostic.xUnit1004.severity = none # Test methods should not be skipped. Remove the Skip property to start running the test again.
180-
181184
dotnet_diagnostic.RCS1021.severity = none # Use expression-bodied lambda.
182-
dotnet_diagnostic.RCS1032.severity = warning # Remove redundant parentheses.
183185
dotnet_diagnostic.RCS1061.severity = none # Merge 'if' with nested 'if'.
184186
dotnet_diagnostic.RCS1069.severity = none # Remove unnecessary case label.
185187
dotnet_diagnostic.RCS1074.severity = none # Remove redundant constructor.
186188
dotnet_diagnostic.RCS1077.severity = none # Optimize LINQ method call.
187-
dotnet_diagnostic.RCS1118.severity = warning # Mark local variable as const.
188189
dotnet_diagnostic.RCS1124.severity = none # Inline local variable.
189190
dotnet_diagnostic.RCS1129.severity = none # Remove redundant field initialization.
190191
dotnet_diagnostic.RCS1140.severity = none # Add exception to documentation comment.
191-
dotnet_diagnostic.RCS1141.severity = warning # Add 'param' element to documentation comment.
192192
dotnet_diagnostic.RCS1142.severity = none # Add 'typeparam' element to documentation comment.
193193
dotnet_diagnostic.RCS1146.severity = none # Use conditional access.
194194
dotnet_diagnostic.RCS1151.severity = none # Remove redundant cast.
@@ -201,18 +201,14 @@ dotnet_diagnostic.RCS1181.severity = none # Convert comment to documentation com
201201
dotnet_diagnostic.RCS1186.severity = none # Use Regex instance instead of static method.
202202
dotnet_diagnostic.RCS1188.severity = none # Remove redundant auto-property initialization.
203203
dotnet_diagnostic.RCS1189.severity = none # Add region name to #endregion.
204-
dotnet_diagnostic.RCS1197.severity = warning # Optimize StringBuilder.AppendLine call.
205204
dotnet_diagnostic.RCS1201.severity = none # Use method chaining.
206-
dotnet_diagnostic.RCS1205.severity = warning # Order named arguments according to the order of parameters.
207205
dotnet_diagnostic.RCS1212.severity = none # Remove redundant assignment.
208206
dotnet_diagnostic.RCS1217.severity = none # Convert interpolated string to concatenation.
209207
dotnet_diagnostic.RCS1222.severity = none # Merge preprocessor directives.
210208
dotnet_diagnostic.RCS1226.severity = none # Add paragraph to documentation comment.
211-
dotnet_diagnostic.RCS1229.severity = warning # Use async/await when necessary.
212209
dotnet_diagnostic.RCS1234.severity = none # Enum duplicate value
213210
dotnet_diagnostic.RCS1238.severity = none # Avoid nested ?: operators.
214211
dotnet_diagnostic.RCS1241.severity = none # Implement IComparable when implementing IComparable<T><T>.
215-
216212
dotnet_diagnostic.IDE0001.severity = none # Simplify name
217213
dotnet_diagnostic.IDE0002.severity = none # Simplify member access
218214
dotnet_diagnostic.IDE0004.severity = none # Remove unnecessary cast
@@ -227,6 +223,8 @@ dotnet_diagnostic.IDE0100.severity = none # Remove unnecessary equality operator
227223
dotnet_diagnostic.IDE0110.severity = none # Remove unnecessary discards
228224
dotnet_diagnostic.IDE0032.severity = none # Use auto property
229225
dotnet_diagnostic.IDE0160.severity = none # Use block-scoped namespace
226+
dotnet_diagnostic.VSTHRD111.severity = none # Use .ConfigureAwait(bool) is hidden by default, set to none to prevent IDE from changing on autosave
227+
dotnet_diagnostic.xUnit1004.severity = none # Test methods should not be skipped. Remove the Skip property to start running the test again.
230228

231229
###############################
232230
# Naming Conventions #

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ to **start the Semantic Memory Service**:
161161
> ### On Windows:
162162
>
163163
> ```shell
164-
> cd dotnet/Service
164+
> cd dotnet\Service
165165
> setup.cmd
166166
> run.cmd
167167
> ```

SemanticMemory.sln

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ EndProject
1818
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{0A43C65C-6007-4BB4-B3FE-8D439FC91841}"
1919
ProjectSection(SolutionItems) = preProject
2020
samples\README.md = samples\README.md
21+
samples\.editorconfig = samples\.editorconfig
2122
EndProjectSection
2223
EndProject
2324
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "001-dotnet-Serverless", "samples\001-dotnet-Serverless\001-dotnet-Serverless.csproj", "{CF55CAED-81D1-4748-8172-AE678047B760}"
@@ -69,6 +70,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "nuget", "nuget", "{02B67859
6970
dotnet\nuget\NUGET.md = dotnet\nuget\NUGET.md
7071
EndProjectSection
7172
EndProject
73+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "010-using-core-nuget", "samples\010-using-core-nuget\010-using-core-nuget.csproj", "{17F42A38-46CB-4471-AF93-3AE6981B7278}"
74+
EndProject
7275
Global
7376
GlobalSection(SolutionConfigurationPlatforms) = preSolution
7477
Debug|Any CPU = Debug|Any CPU
@@ -85,6 +88,7 @@ Global
8588
{8A90555B-C28B-401B-960A-619DE9A87C4C} = {0A43C65C-6007-4BB4-B3FE-8D439FC91841}
8689
{87DEAE8D-138C-4FDD-B4C9-11C3A7817E8F} = {6EF76FD8-4C35-4370-8539-5DDF45357A50}
8790
{02B67859-5B16-46E3-9CB4-916887275649} = {87DEAE8D-138C-4FDD-B4C9-11C3A7817E8F}
91+
{17F42A38-46CB-4471-AF93-3AE6981B7278} = {0A43C65C-6007-4BB4-B3FE-8D439FC91841}
8892
EndGlobalSection
8993
GlobalSection(ProjectConfigurationPlatforms) = postSolution
9094
{8A9FA587-7EBA-4D43-BE47-38D798B1C74C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
@@ -131,5 +135,9 @@ Global
131135
{8A90555B-C28B-401B-960A-619DE9A87C4C}.Debug|Any CPU.Build.0 = Debug|Any CPU
132136
{8A90555B-C28B-401B-960A-619DE9A87C4C}.Release|Any CPU.ActiveCfg = Release|Any CPU
133137
{8A90555B-C28B-401B-960A-619DE9A87C4C}.Release|Any CPU.Build.0 = Release|Any CPU
138+
{17F42A38-46CB-4471-AF93-3AE6981B7278}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
139+
{17F42A38-46CB-4471-AF93-3AE6981B7278}.Debug|Any CPU.Build.0 = Debug|Any CPU
140+
{17F42A38-46CB-4471-AF93-3AE6981B7278}.Release|Any CPU.ActiveCfg = Release|Any CPU
141+
{17F42A38-46CB-4471-AF93-3AE6981B7278}.Release|Any CPU.Build.0 = Release|Any CPU
134142
EndGlobalSection
135143
EndGlobal
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
3+
using System.IO;
4+
using System.Reflection;
5+
using Microsoft.SemanticMemory.Core.Configuration;
6+
7+
namespace Microsoft.SemanticMemory.Core.AI.Tokenizers.GPT3;
8+
9+
/// <summary>
10+
/// Resource helper to load resources embedded in the assembly. By default we embed only
11+
/// text files, so the helper is limited to returning text.
12+
///
13+
/// You can find information about embedded resources here:
14+
/// * https://learn.microsoft.com/dotnet/core/extensions/create-resource-files
15+
/// * https://learn.microsoft.com/dotnet/api/system.reflection.assembly.getmanifestresourcestream?view=net-7.0
16+
///
17+
/// To know which resources are embedded, check the csproj file.
18+
/// </summary>
19+
internal static class EmbeddedResource
20+
{
21+
private static readonly string? s_namespace = typeof(EmbeddedResource).Namespace;
22+
23+
/// <summary>
24+
/// Return content of BPE file.
25+
/// </summary>
26+
internal static string ReadBytePairEncodingTable()
27+
{
28+
return Read("vocab.bpe");
29+
}
30+
31+
/// <summary>
32+
/// Return content of encoding table file.
33+
/// </summary>
34+
internal static string ReadEncodingTable()
35+
{
36+
return Read("encoder.json");
37+
}
38+
39+
private static string Read(string fileName)
40+
{
41+
// Get the current assembly. Note: this class is in the same assembly where the embedded resources are stored.
42+
Assembly? assembly = typeof(EmbeddedResource).GetTypeInfo().Assembly;
43+
if (assembly == null) { throw new ConfigurationException($"[{s_namespace}] {fileName} assembly not found"); }
44+
45+
// Resources are mapped like types, using the namespace and appending "." (dot) and the file name
46+
var resourceName = $"{s_namespace}." + fileName;
47+
using Stream? resource = assembly.GetManifestResourceStream(resourceName);
48+
if (resource == null) { throw new ConfigurationException($"{resourceName} resource not found"); }
49+
50+
// Return the resource content, in text format.
51+
using var reader = new StreamReader(resource);
52+
return reader.ReadToEnd();
53+
}
54+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Linq;
6+
using System.Text.Json;
7+
using Microsoft.SemanticKernel.AI;
8+
9+
namespace Microsoft.SemanticMemory.Core.AI.Tokenizers.GPT3;
10+
11+
internal static class GPT3Settings
12+
{
13+
// Lazy load and cache encoding table (encoder.json)
14+
internal static Dictionary<string, int> Encoder => s_encoder.Value;
15+
16+
// Lazy load and cache byte pair encoding table (vocab.bpe)
17+
internal static Dictionary<Tuple<string, string>, int> BpeRanks => s_bpeRanks.Value;
18+
19+
// Lazy load and cache encoding table (encoder.json)
20+
private static readonly Lazy<Dictionary<string, int>> s_encoder = new(BuildEncoder);
21+
22+
// Lazy load and cache byte pair encoding table (vocab.bpe)
23+
private static readonly Lazy<Dictionary<Tuple<string, string>, int>> s_bpeRanks = new(BuildBpeRanks);
24+
25+
private static Dictionary<Tuple<string, string>, int> BuildBpeRanks()
26+
{
27+
string[] lines = EmbeddedResource.ReadBytePairEncodingTable().Split('\n');
28+
List<Tuple<string, string>> bpeMerges = new ArraySegment<string>(lines, 1, lines.Length - 1)
29+
.Where(x => x.Trim().Length > 0)
30+
.Select(x =>
31+
{
32+
string[] y = x.Split(' ');
33+
return new Tuple<string, string>(y[0], y[1]);
34+
}).ToList();
35+
return DictZip(bpeMerges, Range(0, bpeMerges.Count));
36+
}
37+
38+
private static Dictionary<string, int> BuildEncoder()
39+
{
40+
string json = EmbeddedResource.ReadEncodingTable();
41+
var encoder = JsonSerializer.Deserialize<Dictionary<string, int>>(json, new JsonSerializerOptions());
42+
43+
return encoder
44+
?? throw new AIException(AIException.ErrorCodes.InvalidConfiguration,
45+
"Encoding table deserialization returned NULL");
46+
}
47+
48+
private static Dictionary<Tuple<string, string>, int> DictZip(List<Tuple<string, string>> x, List<int> y)
49+
{
50+
var result = new Dictionary<Tuple<string, string>, int>();
51+
for (int i = 0; i < x.Count; i++)
52+
{
53+
result.Add(x[i], y[i]);
54+
}
55+
56+
return result;
57+
}
58+
59+
private static List<int> Range(int x, int y)
60+
{
61+
return Enumerable.Range(x, y - x).ToList();
62+
}
63+
}

0 commit comments

Comments
 (0)