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

How to calculate token size from string? #1962

Closed
sindresorhus opened this issue Mar 16, 2024 · 4 comments
Closed

How to calculate token size from string? #1962

sindresorhus opened this issue Mar 16, 2024 · 4 comments

Comments

@sindresorhus
Copy link
Contributor

I'm using the params.initial_prompt setting in my app, and I would like to interactively warn the user if they exceed the prompt limit. Given a string, how can I calculate the token size?

@felrock
Copy link
Collaborator

felrock commented Mar 18, 2024

You could use static std::vector<whisper_vocab::id> tokenize(const whisper_vocab & vocab, const std::string & text) on your initial_prompt and check the length, compare it to your context size.

@sindresorhus
Copy link
Contributor Author

I'm using Whisper.cpp's C API from Swift. But I now see that I could use whisper_tokenize. However, it's a bit of a waste to fill up the tokens array when I only care about the size.

So my request is to add something like this:

int whisper_token_count(struct whisper_context * ctx, const char * text) {
    const auto res = tokenize(ctx->vocab, text);
    return res.size();
}

@felrock
Copy link
Collaborator

felrock commented Mar 19, 2024

Your request is a bit too specific imo. You can create a function like that yourself, just disregard the tokens after you've checked the size.

@sindresorhus
Copy link
Contributor Author

Any app accepting a custom prompt will need this. Of course every app could reinvent the wheel, but I think many app developers don't even realize they have to validate the prompt. I for sure did not. Having a specific function like this makes it more discoverable that they need to.

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

No branches or pull requests

3 participants