Skip to content
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

perf:reduce allocations in EncodingLoader #60

Merged
merged 1 commit into from
Nov 9, 2024

Conversation

bgrainger
Copy link
Contributor

@bgrainger bgrainger commented Nov 9, 2024

Improve performance of ModelToEncoder.For("gpt-4o") by reducing allocations:

  • Avoid garbage strings from splitting on space.
  • Avoid allocations from using LINQ in a hot loop.
BenchmarkDotNet v0.14.0, Windows 10 (10.0.19045.5073/22H2/2022Update)
Intel Core i7-10875H CPU 2.30GHz, 1 CPU, 16 logical and 8 physical cores
.NET SDK 9.0.100-rc.2.24474.11
  [Host] : .NET 9.0.0 (9.0.24.47305), X64 RyuJIT AVX2
  2.0.3  : .NET 9.0.0 (9.0.24.47305), X64 RyuJIT AVX2
  PR     : .NET 9.0.0 (9.0.24.47305), X64 RyuJIT AVX2
Method Job NuGetReferences Mean Error StdDev Gen0 Gen1 Gen2 Allocated
GetEncoder 2.0.3 Tiktoken 2.0.3 83.67 ms 3.943 ms 5.901 ms 3166.6667 1166.6667 166.6667 36.5 MB
GetEncoder PR This PR 49.26 ms 1.903 ms 2.848 ms 1090.9091 1000.0000 181.8182 19.53 MB

Summary by CodeRabbit

  • New Features

    • Enhanced performance and memory efficiency for string processing and token handling, particularly for .NET 7.0 and greater.
    • Improved methods for loading and processing encodings, optimizing memory usage.
  • Bug Fixes

    • Adjusted validation in the encoding loading process to ensure correct token counts.
  • Documentation

    • Updated comments and formatting for clarity in the EncodingLoader class.

- Avoid garbage strings from splitting on space.
- Avoid allocations from using LINQ in a hot loop.

Signed-off-by: Bradley Grainger <bgrainger@gmail.com>
Copy link

coderabbitai bot commented Nov 9, 2024

Walkthrough

The changes in this pull request involve optimizations in the CoreBPE.cs and EncodingLoader.cs files. In CoreBPE.cs, the logic for handling byte arrays and string conversions has been updated to utilize Span<char> for improved performance, particularly for .NET 6.0 and newer versions. Similarly, EncodingLoader.cs has been modified to enhance the LoadEncodingFromLines method with conditional compilation for .NET 7.0, incorporating Span<Range> and Span<byte> for better memory management. These changes aim to improve efficiency while maintaining compatibility with older frameworks.

Changes

File Path Change Summary
src/libs/Tiktoken.Core/CoreBPE.cs Updated constructor and methods (CountTokensNative, EncodeNative, Explore, ExploreUtfSafe, DecodeNative) to use Span<char> for string handling in .NET 6.0 and greater.
src/libs/Tiktoken.Encodings.Abstractions/EncodingLoader.cs Enhanced LoadEncodingFromLines method with conditional compilation for .NET 7.0, using Span<Range> and Span<byte> for token and byte storage. Adjusted formatting in LoadEncodingFromManifestResource.

Poem

In the land of code where bytes do play,
A rabbit hops, optimizing the way.
With Span and Tokens, we dance and twirl,
Making memory light, as we give it a whirl.
For .NET's new versions, we leap with delight,
Enhancing our methods, making them bright! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@CLAassistant
Copy link

CLAassistant commented Nov 9, 2024

CLA assistant check
All committers have signed the CLA.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (4)
src/libs/Tiktoken.Encodings.Abstractions/EncodingLoader.cs (2)

59-59: Suggestion: Ensure the bytes buffer size is sufficient for decoded data

The bytes buffer is currently allocated with a fixed size of 256 bytes. If the Base64-decoded data exceeds this size, Convert.TryFromBase64Chars will fail. Consider dynamically sizing the buffer based on the maximum possible decoded length of the Base64 input to prevent conversion failures.

For example:

- Span<byte> bytes = stackalloc byte[256];
+ int maxDecodedLength = (line.Length * 3) / 4;
+ Span<byte> bytes = maxDecodedLength <= 1024
+     ? stackalloc byte[maxDecodedLength]
+     : new byte[maxDecodedLength];

58-58: Nitpick: Adjust the size of the tokens buffer

The tokens buffer is allocated with a size of 3, but only 2 tokens are expected per line. Reducing the size to 2 conserves stack space.

Apply this diff:

- Span<Range> tokens = stackalloc Range[3];
+ Span<Range> tokens = stackalloc Range[2];
src/libs/Tiktoken.Core/CoreBPE.cs (2)

Line range hint 222-222: Incorrect initialization of List<byte>

The initialization List<byte> accumulatedBytes = []; is invalid in C#. You should use new List<byte>(); to instantiate the list.

Apply this fix:

-List<byte> accumulatedBytes = [];
+List<byte> accumulatedBytes = new List<byte>();

Line range hint 253-271: Inefficient UTF-8 validation in older .NET versions

Using exception handling for UTF-8 validation in the #else block can impact performance due to the overhead of exceptions.

Consider using Encoding.UTF8.GetDecoder().Convert to validate UTF-8 sequences without exceptions:

#if NET8_0_OR_GREATER
    bool isValid = Utf8.IsValid(accuArr);
#else
-   bool isValid = true;
-
-   try
-   {
-       var _ = encoding.GetString(accuArr);
-   }
-   catch (ArgumentException)
-   {
-       isValid = false;
-   }
+   Decoder utf8Decoder = Encoding.UTF8.GetDecoder();
+   int charsUsed, bytesUsed;
+   bool completed;
+   char[] charBuffer = new char[accuArr.Length];
+   utf8Decoder.Convert(accuArr, 0, accuArr.Length, charBuffer, 0, charBuffer.Length, true, out bytesUsed, out charsUsed, out completed);
+   bool isValid = completed;
#endif

Ensure to test this change thoroughly for correctness and performance improvements.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f7e7404 and 08c2f16.

📒 Files selected for processing (2)
  • src/libs/Tiktoken.Core/CoreBPE.cs (1 hunks)
  • src/libs/Tiktoken.Encodings.Abstractions/EncodingLoader.cs (3 hunks)

@HavenDV HavenDV merged commit 1679b57 into tryAGI:main Nov 9, 2024
4 checks passed
@HavenDV
Copy link
Contributor

HavenDV commented Nov 9, 2024

LGTM. Thank you for your contribution!

@HavenDV
Copy link
Contributor

HavenDV commented Nov 9, 2024

Released as 2.1.0 on NuGet

@bgrainger
Copy link
Contributor Author

Thanks for the quick update!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants