OpenAI GPT-3 API:如何计算不同语言的令牌?

问题描述 投票:0回答:2

我们都知道GPT-3模型可以接受并生成英语、法语、中文、日语等各种语言。

在传统的NLP中,不同的语言有不同的token制作方法。

  • 对于英语等字母语言,
    Bert
    使用BPE方法来制作如下标记:
Insomnia caused much frustration.
==>
In-, som-, nia, caus-, ed, much, frus-, tra-, tion, .,
  • 对于中文或日语等特征语言,只需使用字符本身作为标记,如下所示。
東京メトロは心に寄り添う
==>
東, 京, メ, ト, ロ, は, 心, に, 寄, り, 添, う,
我说你倒是快点啊!!!
==>
我, 说, 你, 倒, 是, 快, 点, 啊, !, !, !, 

但是对于GPT-3来说,它是由不同的语言组成的,一句话可以同时产生中文和英文。所以我真的很好奇这个模型是如何制作代币的。

nlp tokenize openai-api gpt-3
2个回答
3
投票

使用 Tokenizer 了解 OpenAI API 如何对一段文本进行标记。

例如,

Insomnia caused much frustration.
将被标记为 6 个标记。

然而,

我说你倒是快点啊!!!
将被标记为 27 个标记,并在底部有一个小注释:

注意:您的输入包含一个或多个映射到的 unicode 字符 多个令牌。输出可视化可能会显示以下字节 每个令牌都以非标准方式。


0
投票

使用抖音^^ https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken

# https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken

import tiktoken


def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613"):
    """Return the number of tokens used by a list of messages."""
    try:
        encoding = tiktoken.encoding_for_model(model)
    except KeyError:
        print("Warning: model not found. Using cl100k_base encoding.")
        encoding = tiktoken.get_encoding("cl100k_base")
    if model in {
        "gpt-3.5-turbo-0613",
        "gpt-3.5-turbo-16k-0613",
        "gpt-4-0314",
        "gpt-4-32k-0314",
        "gpt-4-0613",
        "gpt-4-32k-0613",
    }:
        tokens_per_message = 3
        tokens_per_name = 1
    elif model == "gpt-3.5-turbo-0301":
        tokens_per_message = 4  # every message follows <|start|>{role/name}\n{content}<|end|>\n
        tokens_per_name = -1  # if there's a name, the role is omitted
    elif "gpt-3.5-turbo" in model:
        print("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")
        return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")
    elif "gpt-4" in model:
        print("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")
        return num_tokens_from_messages(messages, model="gpt-4-0613")
    else:
        raise NotImplementedError(
            f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens."""
        )
    num_tokens = 0
    for message in messages:
        num_tokens += tokens_per_message
        for key, value in message.items():
            num_tokens += len(encoding.encode(value))
            if key == "name":
                num_tokens += tokens_per_name
    num_tokens += 3  # every reply is primed with <|start|>assistant<|message|>
    return num_tokens
© www.soinside.com 2019 - 2024. All rights reserved.