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: defer the allocation of matchValue. #61

Merged
merged 1 commit into from
Nov 9, 2024

Conversation

bgrainger
Copy link
Contributor

@bgrainger bgrainger commented Nov 9, 2024

matchValue isn't needed on the fast path, so don't allocate it until it's actually needed. Additionally, use a Span-based conversion to UTF-8 bytes to avoid the creation of a temporary char array.

[Benchmark]
public int CountTokens() => m_encoder.CountTokens(Text);

[Benchmark]
public IReadOnlyCollection<int> Encode() => m_encoder.Encode(Text);
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.1.0  : .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 Median Gen0 Allocated
CountTokens 2.1.0 Tiktoken 2.1.0 10.893 us 1.6238 us 2.3802 us 9.392 us 0.6104 5.08 KB
CountTokens PR This PR 8.482 us 0.2161 us 0.3168 us 8.421 us 0.2899 2.49 KB
Encode 2.1.0 Tiktoken 2.1.0 9.396 us 0.2398 us 0.3362 us 9.269 us 0.9155 7.56 KB
Encode PR This PR 8.802 us 0.1064 us 0.1592 us 8.790 us 0.5951 4.98 KB

Summary by CodeRabbit

  • New Features

    • Enhanced text encoding and tokenization processes for improved performance.
    • Introduced a new method for efficient conversion of character spans to byte spans.
  • Bug Fixes

    • Optimized memory usage during token processing, reducing unnecessary allocations.
  • Documentation

    • Updated internal documentation to reflect changes in tokenization and encoding methods.

matchValue isn't needed on the fast path, so don't allocate it until it's actually needed. Additionally, use a Span-based conversion to UTF-8 bytes to avoid the creation of a temporary char array.
Copy link

coderabbitai bot commented Nov 9, 2024

Walkthrough

The changes in this pull request primarily enhance the CoreBpe class within CoreBPE.cs, focusing on improving text encoding and tokenization efficiency. Key modifications include the introduction of a Span<byte> pieceBytes variable for stack allocation, which optimizes memory usage. Methods such as CountTokensNative, EncodeNative, and Explore have been updated to leverage this span-based approach. Additionally, a new private method, GetUtf8Bytes, has been added to facilitate efficient conversion of character spans to byte spans, particularly for .NET 5.0 and above.

Changes

File Path Change Summary
src/libs/Tiktoken.Core/CoreBPE.cs - Enhanced CoreBpe class for better text encoding and tokenization.
- Added private static byte[] GetUtf8Bytes(ReadOnlySpan<char> text, Span<byte> scratch) method.
- Updated CountTokensNative, EncodeNative, and Explore methods to utilize pieceBytes for improved memory efficiency.

Possibly related PRs

  • perf:reduce allocations in EncodingLoader #60: The changes in this PR also modify the CoreBpe class in CoreBPE.cs, focusing on optimizing memory usage and performance in string processing, which aligns closely with the enhancements made in the main PR regarding text encoding and tokenization.

Poem

In the land of bytes and spans,
A rabbit hops with clever plans.
With tokens light and memory tight,
Encoding dreams take joyful flight.
So here’s to code, both sleek and bright,
A hop, a skip, in pure delight! 🐇✨


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.

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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a1b5ca5 and e92dd25.

📒 Files selected for processing (1)
  • src/libs/Tiktoken.Core/CoreBPE.cs (6 hunks)

src/libs/Tiktoken.Core/CoreBPE.cs Show resolved Hide resolved
Comment on lines +558 to +571
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte[] GetUtf8Bytes(ReadOnlySpan<char> text, Span<byte> scratch)
{
// check if text can be decoded into the buffer; each UTF-16 char can become at most 3 UTF-8 bytes
if (text.Length * 3 < scratch.Length)
{
return scratch[..System.Text.Encoding.UTF8.GetBytes(text, scratch)].ToArray();
}
else
{
return System.Text.Encoding.UTF8.GetBytes(text.ToArray());
}
}
#endif
Copy link

@coderabbitai coderabbitai bot Nov 9, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect buffer size estimation in GetUtf8Bytes leading to potential overrun

In the GetUtf8Bytes method, the buffer size estimation assumes each UTF-16 character can expand to a maximum of 3 bytes in UTF-8:

if (text.Length * 3 < scratch.Length)

However, UTF-8 encoding of certain Unicode characters can require up to 4 bytes per character. This miscalculation might cause the buffer scratch to be too small, potentially leading to buffer overruns.

Suggested Fix:

Update the buffer size estimation to account for the maximum of 4 bytes per character and adjust the condition accordingly:

-if (text.Length * 3 < scratch.Length)
+if (text.Length * 4 <= scratch.Length)

This change ensures the buffer is large enough for all possible UTF-8 encodings of the input text.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

However, UTF-8 encoding of certain Unicode characters can require up to 4 bytes per character.

This is wrong. A single UTF-16 code unit can decode into at most three UTF-8 bytes. (Two UTF-16 code units representing a surrogate pair could decode into four bytes, but that would only be two per char.)

Copy link

Choose a reason for hiding this comment

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

@bgrainger, thank you for the clarification. You are correct; a single UTF-16 code unit can encode into at most three bytes in UTF-8, and your code accurately reflects this. I appreciate you pointing this out.

(・⊝・)?


✏️ Learnings added
Learnt from: bgrainger
PR: tryAGI/Tiktoken#61
File: src/libs/Tiktoken.Core/CoreBPE.cs:558-571
Timestamp: 2024-11-09T17:47:46.917Z
Learning: In the `GetUtf8Bytes` method in `CoreBPE.cs`, when converting from `ReadOnlySpan<char>` to `Span<byte>` using UTF-8 encoding in C#, a single UTF-16 code unit (`char`) can expand to a maximum of three bytes in UTF-8. Although surrogate pairs (two UTF-16 code units) can encode into four bytes, the buffer size estimation using `text.Length * 3` is appropriate since it considers the maximum expansion per `char`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines +114 to +116
#if NET7_0_OR_GREATER
var piece = GetUtf8Bytes(textSpan.Slice(match.Index, match.Length), pieceBytes);
#else
Copy link

@coderabbitai coderabbitai bot Nov 9, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential misuse of shared pieceBytes buffer in loops

In lines 115 and 209, GetUtf8Bytes is called within loops using the shared pieceBytes buffer:

var piece = GetUtf8Bytes(textSpan.Slice(match.Index, match.Length), pieceBytes);

If the textSpan slices exceed the size of pieceBytes, this could lead to incorrect encoding or runtime exceptions, especially since the buffer size is fixed.

Recommendation:

  • Ensure that pieceBytes is sufficiently sized for the largest expected input within the loops.
  • Alternatively, allocate pieceBytes inside the loop or adjust GetUtf8Bytes to handle cases where the buffer isn't large enough.

This will prevent potential errors due to buffer overflow or insufficient buffer capacity.

Also applies to: 209-210

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Wrong again.

Copy link

Choose a reason for hiding this comment

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

@bgrainger, Understood.

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

HavenDV commented Nov 9, 2024

It's just a bot, probably using gpt4o-mini or worse models, so don't expect any insight into such matters. But sometimes it works
https://coderabbit.ai/

@bgrainger
Copy link
Contributor Author

I've heard of it before, but never seen it enabled on a project. I know to take its suggestions with a (large) grain of salt, but couldn't resist defending myself against the incorrect AI 😂

(If anything it seems worthwhile to note the objections to its review for future maintainers/contributors who are looking into the history of the code.)

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.

2 participants