{"id":2480,"date":"2024-03-11T21:15:07","date_gmt":"2024-03-11T13:15:07","guid":{"rendered":"https:\/\/www.aqwu.net\/wp\/?p=2480"},"modified":"2024-04-28T20:02:27","modified_gmt":"2024-04-28T12:02:27","slug":"%e4%ba%86%e8%a7%a3-llama-2-%e6%a8%a1%e5%9e%8b%e7%bb%93%e6%9e%846","status":"publish","type":"post","link":"https:\/\/www.aqwu.net\/wp\/?p=2480","title":{"rendered":"\u4e86\u89e3 LLaMA-2 \u6a21\u578b\u7ed3\u6784(6)"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\"><strong>11. \u5c06\u5b57\u7b26\u4e32\u7f16\u7801\u4e3a\u4ee4\u724c\u5e8f\u5217<\/strong><\/h2>\n\n\n\n<p>\u5728\u804a\u5929\u7684\u65f6\u5019\uff0c\u9700\u8981\u628a\u5b57\u7b26\u4e32\u901a\u8fc7 tokenizer \u8fdb\u884c\u7f16\u7801\uff0c\u547d\u540d\u4e3a test10.py\uff0c\u6587\u4ef6\u4fdd\u5b58\u5230 newsrc \u76ee\u5f55\u4e0b\uff1a<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >import os\nimport struct\nimport argparse\nfrom typing import List\n\nfrom sentencepiece import SentencePieceProcessor\n\nclass Tokenizer:\n    def __init__(self, tokenizer_model=None):\n        model_path = tokenizer_model\n        assert os.path.isfile(model_path), model_path\n        self.sp_model = SentencePieceProcessor(model_file=model_path)\n        self.model_path = model_path\n\n        # BOS \/ EOS token IDs\n        self.n_words: int = self.sp_model.vocab_size()\n        self.bos_id: int = self.sp_model.bos_id()\n        self.eos_id: int = self.sp_model.eos_id()\n        self.pad_id: int = self.sp_model.pad_id()\n        #print(f\"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}\")\n        assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()\n\n    def encode(self, s: str, bos: bool, eos: bool) -&gt; List[int]:\n        assert type(s) is str\n        t = self.sp_model.encode(s)\n        if bos:\n            t = [self.bos_id] + t\n        if eos:\n            t = t + [self.eos_id]\n        return t\n\n    def decode(self, t: List[int]) -&gt; str:\n        return self.sp_model.decode(t)\n\n    def export(self):\n\n        # get all the tokens (postprocessed) and their scores as floats\n        tokens, scores = [], []\n        for i in range(self.n_words):\n\n            # decode the token and light postprocessing\n            t = self.sp_model.id_to_piece(i)\n            s = self.sp_model.get_score(i)\n            if i == self.bos_id:\n                t = '\\n&lt;s&gt;\\n'\n            elif i == self.eos_id:\n                t = '\\n&lt;\/s&gt;\\n'\n            t = t.replace('\u2581', ' ') # sentencepiece uses this character as whitespace\n            b = t.encode('utf-8') # bytes of this token, utf-8 encoded\n\n            tokens.append(b)\n            scores.append(s)\n\n        # record the max token length\n        max_token_length = max(len(t) for t in tokens)\n\n        # write to a binary file\n        # the tokenizer.bin file is the same as .model file, but .bin\n        tokenizer_bin = self.model_path.replace('.model', '.bin')\n        with open(tokenizer_bin, 'wb') as f:\n            f.write(struct.pack(\"I\", max_token_length))\n            for bytes, score in zip(tokens, scores):\n                f.write(struct.pack(\"fI\", score, len(bytes)))\n                f.write(bytes)\n\nt = Tokenizer(\"newsrc\/tokenizer.model\")\n\nprompt = \"The meaning of life is\"\n\nstart_ids = t.encode(prompt, bos=True, eos=False)\nprint(start_ids)\n\n<\/pre><\/div>\n\n\n\n<p>\u8fd0\u884c test10.py<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:sh decode:true \">python newsrc\/test10.py\n[1, 450, 6593, 310, 2834, 338]<\/pre><\/div>\n\n\n\n<p>\u901a\u8fc7 AutoTokenizer \u6765\u7f16\u7801\uff0c\u547d\u540d\u4e3a test11.py\uff0c\u6587\u4ef6\u4fdd\u5b58\u5230 newsrc \u76ee\u5f55\u4e0b\uff1a<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">from transformers import AutoTokenizer\n\nmodel_path = \"meta-llama\/Llama-2-7b-chat-hf\"\ntokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)\n\nprompt = \"The meaning of life is\"\nstart_ids = tokenizer.encode(prompt)\nprint(start_ids)\n<\/pre><\/div>\n\n\n\n<p>\u8fd0\u884c test11.py<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">python newsrc\/test11.py\n[1, 450, 6593, 310, 2834, 338]<\/pre><\/div>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><\/div>\n\n\n\n<p>\u4e0b\u9762\u6211\u4eec\u901a\u8fc7C\u8bed\u8a00\u6765\u5b9e\u73b0\uff0c\u53c2\u7167 https:\/\/github.com\/karpathy\/llama2.c \u9879\u76ee\u4e0b\u7684 run.c \u6587\u4ef6\uff0c\u547d\u540d\u4e3a test02.c\uff0c\u6587\u4ef6\u4fdd\u5b58\u5230 newsrc \u76ee\u5f55\u4e0b\uff1a<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:c decode:true \" >#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;ctype.h&gt;\n#include &lt;time.h&gt;\n#include &lt;math.h&gt;\n#include &lt;string.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;sys\/mman.h&gt;\n\/\/ The Byte Pair Encoding (BPE) Tokenizer that translates strings &lt;-&gt; tokens\n\ntypedef struct {\n    \/\/ \u4e00\u4e2a\u5b57\u7b26\u6307\u9488\uff0c\u6307\u5411\u4e0eID\u5173\u8054\u7684\u5b57\u7b26\u4e32\u3002\n    char *str;\n    \/\/ \u4e00\u4e2a\u6574\u6570\uff0c\u8868\u793a\u4e0e\u5b57\u7b26\u4e32\u5173\u8054\u7684ID\u3002\n    int id;\n} TokenIndex;\n\ntypedef struct {\n    \/\/ \u4e00\u4e2a\u6307\u9488\u6570\u7ec4\uff0c\u5b58\u50a8\u8bcd\u6c47\u8868\u4e2d\u6bcf\u4e2a\u5355\u8bcd\u7684\u5b57\u7b26\u4e32\u8868\u793a\u3002\n    \/\/ \u4f8b\u5982\uff0c\u5982\u679c vocab[0] \u662f \"apple\"\uff0c\u90a3\u4e48 vocab[0][0] \u5c31\u662f\u5b57\u7b26 'a'\u3002  \n    char** vocab;\n    \/\/ \u4e00\u4e2a\u6d6e\u70b9\u6570\u6570\u7ec4\uff0c\u53ef\u80fd\u5b58\u50a8\u4e0e\u8bcd\u6c47\u8868\u4e2d\u7684\u6bcf\u4e2a\u5355\u8bcd\u76f8\u5173\u8054\u7684\u5206\u6570\u6216\u6743\u91cd\u3002\n    float* vocab_scores;\n    \/\/ \u7ed3\u6784\u4f53\uff0c\u5b58\u50a8\u4e00\u4e2a\u5b57\u7b26\u4e32\u548c\u4e0e\u5176\u76f8\u5173\u8054\u7684\u6574\u6570ID\n    TokenIndex *sorted_vocab;\n    \/\/ \u4e00\u4e2a\u6574\u6570\uff0c\u8868\u793a\u8bcd\u6c47\u8868\u7684\u5927\u5c0f\uff0c\u5373vocab\u548cvocab_scores\u6570\u7ec4\u4e2d\u7684\u5143\u7d20\u6570\u91cf\u3002\n    int vocab_size;\n    \/\/ \u4e00\u4e2a\u65e0\u7b26\u53f7\u6574\u6570\uff0c\u8868\u793a\u8bcd\u6c47\u8868\u4e2d\u7684\u6700\u5927token\u957f\u5ea6\u3002\n    unsigned int max_token_length;\n    \/\/ \u4e00\u4e2a\u65e0\u7b26\u53f7\u5b57\u7b26\u6570\u7ec4\uff0c\u5b58\u50a8\u6240\u6709\u5355\u5b57\u8282\u5b57\u7b26\u4e32\n    \/\/ \u8fd9\u4e2a\u6570\u7ec4\u7684\u5927\u5c0f\u88ab\u8bbe\u5b9a\u4e3a512\uff0c\u53ef\u80fd\u662f\u4e3a\u4e86\u5b58\u50a8ASCII\u5b57\u7b26\u8868\u4e2d\u7684\u6240\u6709\u53ef\u80fd\u7684\u5355\u5b57\u8282\u5b57\u7b26\u4e32\u3002\n    unsigned char byte_pieces[512]; \/\/ stores all single-byte strings\n} Tokenizer;\n\nint compare_tokens(const void *a, const void *b) {\n    return strcmp(((TokenIndex*)a)-&gt;str, ((TokenIndex*)b)-&gt;str);\n}\n\nvoid build_tokenizer(Tokenizer* t, char* tokenizer_path, int vocab_size) {\n    \/\/ i should have written the vocab_size into the tokenizer file... sigh\n    \/\/ \u8bbe\u7f6e\u4e86Tokenizer\u7ed3\u6784\u4f53\u4e2dvocab_size\u7684\u503c\u3002\n    t-&gt;vocab_size = vocab_size;\n    \/\/ malloc space to hold the scores and the strings\n    \/\/ \u4e3avocab\uff0cvocab_scores\u6570\u7ec4\u5206\u914d\u4e86\u5185\u5b58\uff0c\u800csorted_vocab\u88ab\u521d\u59cb\u5316\u4e3aNULL\uff0c\u8868\u793a\u5b83\u5c06\u5728\u540e\u7eed\u88ab\u201c\u61d2\u60f0\u5730\u201d\u521d\u59cb\u5316\u3002\n    t-&gt;vocab = (char**)malloc(vocab_size * sizeof(char*));\n    t-&gt;vocab_scores = (float*)malloc(vocab_size * sizeof(float));\n    t-&gt;sorted_vocab = NULL; \/\/ initialized lazily\n    \/\/ \u521d\u59cb\u5316byte_pieces\u6570\u7ec4\uff0c\u8be5\u6570\u7ec4\u5b58\u50a8\u6240\u6709\u5355\u5b57\u8282\u5b57\u7b26\u4e32\n    for (int i = 0; i &lt; 256; i++) {\n        t-&gt;byte_pieces[i * 2] = (unsigned char)i;\n        t-&gt;byte_pieces[i * 2 + 1] = '\\0';\n    }\n    \/\/ read in the file\n    FILE *file = fopen(tokenizer_path, \"rb\");\n    if (!file) { fprintf(stderr, \"couldn't load %s\\n\", tokenizer_path); exit(EXIT_FAILURE); }\n    \/\/ \u4ece\u6587\u4ef6\u4e2d\u8bfb\u53d6max_token_length\u7684\u503c\n    if (fread(&amp;t-&gt;max_token_length, sizeof(int), 1, file) != 1) { fprintf(stderr, \"failed read\\n\"); exit(EXIT_FAILURE); }\n    int len;\n    \/\/ \u8fd9\u4e2a\u5faa\u73af\u5757\u8bfb\u53d6\u6bcf\u4e2avocab\u5b57\u7b26\u4e32\u53ca\u5176\u5bf9\u5e94\u7684vocab_scores\u503c\u3002\n    for (int i = 0; i &lt; vocab_size; i++) {\n        if (fread(t-&gt;vocab_scores + i, sizeof(float), 1, file) != 1) { fprintf(stderr, \"failed read\\n\"); exit(EXIT_FAILURE);}\n        if (fread(&amp;len, sizeof(int), 1, file) != 1) { fprintf(stderr, \"failed read\\n\"); exit(EXIT_FAILURE); }\n        t-&gt;vocab[i] = (char *)malloc(len + 1);\n        if (fread(t-&gt;vocab[i], len, 1, file) != 1) { fprintf(stderr, \"failed read\\n\"); exit(EXIT_FAILURE); }\n        t-&gt;vocab[i][len] = '\\0'; \/\/ add the string terminating token\n    }\n    fclose(file);\n}\n\nvoid free_tokenizer(Tokenizer* t) {\n    for (int i = 0; i &lt; t-&gt;vocab_size; i++) \n    { \n      free(t-&gt;vocab[i]); \n    }\n    if(t-&gt;vocab) free(t-&gt;vocab);\n    if(t-&gt;vocab_scores) free(t-&gt;vocab_scores);\n    if(t-&gt;sorted_vocab) free(t-&gt;sorted_vocab);\n}\n\nvoid print_tokenizer(Tokenizer* t) {\n    printf(\"vocab = %d\\n\", t-&gt;vocab_size);\n    printf(\"max_token_length = %d\\n\", t-&gt;max_token_length);\n    for (int i = 0; i &lt; t-&gt;vocab_size; i++) \n    { \n      printf(\"%5d, %12.6lf, (%s)\\n\", i, t-&gt;vocab_scores[i], t-&gt;vocab[i]);\n    }\n}\n\nint str_lookup(char *str, TokenIndex *sorted_vocab, int vocab_size) {\n    \/\/ efficiently find the perfect match for str in vocab, return its index or -1 if not found\n    TokenIndex tok = { .str = str }; \/\/ acts as the key to search for\n    TokenIndex *res = bsearch(&amp;tok, sorted_vocab, vocab_size, sizeof(TokenIndex), compare_tokens);\n    return res != NULL ? res-&gt;id : -1;\n}\n\n\/\/ \u8be5encode\u51fd\u6570\u5728\u63d0\u4f9b\u7684C\u4ee3\u7801\u4e2d\uff0c\u5c06\u5b57\u7b26\u4e32text\u7f16\u7801\u4e3a\u4e00\u7cfb\u5217\u4ee4\u724c\u3002\u5b83\u6267\u884c\u591a\u4e2a\u6b65\u9aa4\u548c\u64cd\u4f5c\u6765\u5b8c\u6210\u6b64\u64cd\u4f5c\uff0c\u8fd9\u5305\u62ec\u5904\u7406UTF-8\u5b57\u8282\u5e8f\u5217\u3001\u5904\u7406\u5b57\u8282\u5bf9\u7f16\u7801\uff08BPE\uff09\uff0c\u7b49\u7b49\u3002\n\/\/ \n\/\/ \u53c2\u6570\uff1a\n\/\/ Tokenizer* t \u2013 \u6307\u5411Tokenizer\u7ed3\u6784\u7684\u6307\u9488\u3002\n\/\/ char *text \u2013 \u9700\u8981\u7f16\u7801\u7684\u8f93\u5165\u5b57\u7b26\u4e32\u3002\n\/\/ int8_t bos \u2013 \u4e00\u4e2a\u6807\u5fd7\uff0c\u8868\u793a\u662f\u5426\u5728\u5e8f\u5217\u5f00\u59cb\u5904\u6dfb\u52a0BOS\uff08\u5e8f\u5217\u5f00\u59cb\uff09\u4ee4\u724c\u3002\n\/\/ int8_t eos \u2013 \u4e00\u4e2a\u6807\u5fd7\uff0c\u8868\u793a\u662f\u5426\u5728\u5e8f\u5217\u672b\u5c3e\u6dfb\u52a0EOS\uff08\u5e8f\u5217\u7ed3\u675f\uff09\u4ee4\u724c\u3002\n\/\/ int *tokens \u2013 \u6307\u5411\u5b58\u50a8\u7ed3\u679c\u4ee4\u724c\u7684\u6570\u7ec4\u7684\u6307\u9488\u3002\n\/\/ int *n_tokens \u2013 \u6307\u5411\u5b58\u50a8\u7ed3\u679c\u4ee4\u724c\u6570\u91cf\u7684\u6574\u6570\u7684\u6307\u9488\u3002\nvoid encode(Tokenizer* t, char *text, int8_t bos, int8_t eos, int *tokens, int *n_tokens) {\n    \/\/ encode the string text (input) into an upper-bound preallocated tokens[] array\n    \/\/ bos != 0 means prepend the BOS token (=1), eos != 0 means append the EOS token (=2)\n    \/\/ \u5c06\u5b57\u7b26\u4e32 text\uff08\u8f93\u5165\uff09\u7f16\u7801\u8fdb\u9884\u5148\u5206\u914d\u597d\u7684\u4e0a\u9650 tokens[] \u6570\u7ec4\u4e2d\n    \/\/ bos != 0 \u610f\u5473\u7740\u5728\u524d\u9762\u52a0\u4e0a BOS \u4ee4\u724c\uff08=1\uff09\uff0ceos != 0 \u610f\u5473\u7740\u5728\u540e\u9762\u52a0\u4e0a EOS \u4ee4\u724c\uff08=2\uff09\n    if (text == NULL) { fprintf(stderr, \"cannot encode NULL text\\n\"); exit(EXIT_FAILURE); }\n\n    if (t-&gt;sorted_vocab == NULL) {\n        \/\/ lazily malloc and sort the vocabulary\n        \/\/ \u5982\u679c\u8fd8\u672a\u5206\u914d\uff0c\u61d2\u52a0\u8f7d\u5e76\u6392\u5e8f\u8bcd\u6c47\u8868\n        t-&gt;sorted_vocab = malloc(t-&gt;vocab_size * sizeof(TokenIndex));\n        for (int i = 0; i &lt; t-&gt;vocab_size; i++) {\n            t-&gt;sorted_vocab[i].str = t-&gt;vocab[i];\n            t-&gt;sorted_vocab[i].id = i;\n        }\n        qsort(t-&gt;sorted_vocab, t-&gt;vocab_size, sizeof(TokenIndex), compare_tokens);\n    }\n\n    \/\/ create a temporary buffer that will store merge candidates of always two consecutive tokens\n    \/\/ *2 for concat, +1 for null terminator +2 for UTF8 (in case max_token_length is 1)\n    \/\/ \u521b\u5efa\u4e00\u4e2a\u4e34\u65f6\u7f13\u51b2\u533a\uff0c\u8be5\u7f13\u51b2\u533a\u5c06\u59cb\u7ec8\u5b58\u50a8\u4e24\u4e2a\u8fde\u7eed\u4ee4\u724c\u7684\u5408\u5e76\u5019\u9009\u9879\n    \/\/ *2 \u7528\u4e8e\u4e32\u8054\uff0c+1 \u7528\u4e8e\u7a7a\u7ec8\u6b62\u7b26 +2 \u7528\u4e8eUTF8\uff08\u4ee5\u9632 max_token_length \u4e3a 1\uff09\n    char* str_buffer = malloc((t-&gt;max_token_length*2 +1 +2) * sizeof(char));\n    size_t str_len = 0;\n\n    \/\/ start at 0 tokens\n    *n_tokens = 0;\n\n    \/\/ add optional BOS (=1) token, if desired\n    \/\/ \u5982\u679c\u9700\u8981\uff0c\u6dfb\u52a0 BOS (=1) \u4ee4\u724c\n    if (bos) tokens[(*n_tokens)++] = 1;\n\n    \/\/ add_dummy_prefix is true by default\n    \/\/ so prepend a dummy prefix token to the input string, but only if text != \"\"\n    \/\/ TODO: pretty sure this isn't correct in the general case but I don't have the\n    \/\/ energy to read more of the sentencepiece code to figure out what it's doing\n    \/\/ add_dummy_prefix \u9ed8\u8ba4\u4e3a true\n    \/\/ \u56e0\u6b64\uff0c\u5728\u8f93\u5165\u5b57\u7b26\u4e32\u524d\u52a0\u4e00\u4e2a\u865a\u62df\u524d\u7f00\u4ee4\u724c\uff0c\u4f46\u53ea\u5728 text != \"\" \u7684\u60c5\u51b5\u4e0b\u52a0\n    \/\/ TODO: \u5728\u4e00\u822c\u60c5\u51b5\u4e0b\uff0c\u6211\u5f88\u786e\u4fe1\u8fd9\u4e0d\u6b63\u786e\uff0c\u4f46\u6211\u6ca1\u6709\u7cbe\u529b\u53bb\u9605\u8bfb\u66f4\u591a\u7684 sentencepiece \u4ee3\u7801\u4ee5\u5f04\u6e05\u695a\u5b83\u5728\u505a\u4ec0\u4e48\n    if (text[0] != '\\0') {\n        int dummy_prefix = str_lookup(\" \", t-&gt;sorted_vocab, t-&gt;vocab_size);\n        tokens[(*n_tokens)++] = dummy_prefix;\n    }\n\n    \/\/ Okay UTF-8 time. This will get messy. Here is the reference from Wikipedia:\n    \/\/ Code point \u2194 UTF-8 conversion\n    \/\/ First code point Last code point Byte 1  Byte 2  Byte 3  Byte 4\n    \/\/ \u597d\u7684\uff0c\u73b0\u5728\u662f UTF-8 \u7684\u65f6\u95f4\u3002\u8fd9\u4f1a\u53d8\u5f97\u6709\u70b9\u6df7\u4e71\u3002\u4e0b\u9762\u662f\u6765\u81ea\u7ef4\u57fa\u767e\u79d1\u7684\u53c2\u8003\uff1a\n    \/\/ \u4ee3\u7801\u70b9 \u2194 UTF-8 \u8f6c\u6362\n    \/\/ \u7b2c\u4e00\u4e2a\u4ee3\u7801\u70b9 \u6700\u540e\u4e00\u4e2a\u4ee3\u7801\u70b9 \u5b57\u8282 1  \u5b57\u8282 2  \u5b57\u8282 3  \u5b57\u8282 4\n    \/\/ U+0000 U+007F      0xxxxxxx\n    \/\/ U+0080 U+07FF      110xxxxx  10xxxxxx\n    \/\/ U+0800 U+FFFF      1110xxxx  10xxxxxx  10xxxxxx\n    \/\/ U+10000  U+10FFFF    11110xxx  10xxxxxx  10xxxxxx  10xxxxxx\n\n    \/\/ process the raw (UTF-8) byte sequence of the input string\n    \/\/ \u5904\u7406\u8f93\u5165\u5b57\u7b26\u4e32\u7684\u539f\u59cb\uff08UTF-8\uff09\u5b57\u8282\u5e8f\u5217\n    for (char *c = text; *c != '\\0'; c++) {\n\n        \/\/ reset buffer if the current byte is ASCII or a leading byte\n        \/\/ 0xC0 is 11000000, so (*c &amp; 0xC0) keeps the first 2 bits and zeros the rest\n        \/\/ 0x80 is 10000000\n        \/\/ in UTF-8, all continuation bytes start with \"10\" in first two bits\n        \/\/ so in English this is: \"if this byte is not a continuation byte\"\n        if ((*c &amp; 0xC0) != 0x80) {\n            \/\/ this byte must be either a leading byte (11...) or an ASCII char (0x...)\n            \/\/ =&gt; reset our location, as we're starting a new UTF-8 codepoint\n            str_len = 0;\n        }\n\n        \/\/ append the current byte to the buffer\n        str_buffer[str_len++] = *c; \/\/ ++ is post-increment, incremented after this line\n        str_buffer[str_len] = '\\0';\n\n        \/\/ while the next character is a continuation byte, continue appending\n        \/\/ but if there are too many of them, just stop to avoid overruning str_buffer size.\n        if ((*(c+1) &amp; 0xC0) == 0x80 &amp;&amp; str_len &lt; 4) {\n            continue;\n        }\n\n        \/\/ ok c+1 is not a continuation byte, so we've read in a full codepoint\n        int id = str_lookup(str_buffer, t-&gt;sorted_vocab, t-&gt;vocab_size);\n\n        if (id != -1) {\n            \/\/ we found this codepoint in vocab, add it as a token\n            tokens[(*n_tokens)++] = id;\n        } else {\n            \/\/ byte_fallback encoding: just encode each byte as a token\n            \/\/ +3 is here because the first 3 vocab elements are &lt;unk&gt;, &lt;s&gt;, &lt;\/s&gt;\n            \/\/ so the individual bytes only start at index 3\n            for (int i=0; i &lt; str_len; i++) {\n                tokens[(*n_tokens)++] = (unsigned char)str_buffer[i] + 3;\n            }\n        }\n        str_len = 0; \/\/ protect against a sequence of stray UTF8 continuation bytes\n    }\n\n    \/\/ merge the best consecutive pair each iteration, according the scores in vocab_scores\n    \/\/ \u5728\u6bcf\u6b21\u8fed\u4ee3\u4e2d\u5408\u5e76\u6700\u4f73\u8fde\u7eed\u5bf9\uff0c\u6839\u636evocab_scores\u4e2d\u7684\u5206\u6570\n    while (1) {\n        float best_score = -1e10;\n        int best_id = -1;\n        int best_idx = -1;\n\n        for (int i=0; i &lt; (*n_tokens-1); i++) {\n            \/\/ check if we can merge the pair (tokens[i], tokens[i+1])\n            \/\/ \u68c0\u67e5\u6211\u4eec\u662f\u5426\u53ef\u4ee5\u5408\u5e76\u5bf9(tokens[i], tokens[i+1])\n            sprintf(str_buffer, \"%s%s\", t-&gt;vocab[tokens[i]], t-&gt;vocab[tokens[i+1]]);\n            int id = str_lookup(str_buffer, t-&gt;sorted_vocab, t-&gt;vocab_size);\n            if (id != -1 &amp;&amp; t-&gt;vocab_scores[id] &gt; best_score) {\n                \/\/ this merge pair exists in vocab! record its score and position\n                \/\/ \u8fd9\u4e2a\u5408\u5e76\u5bf9\u5728\u8bcd\u6c47\u8868\u4e2d\u5b58\u5728\uff01\u8bb0\u5f55\u5176\u5206\u6570\u548c\u4f4d\u7f6e\n                best_score = t-&gt;vocab_scores[id];\n                best_id = id;\n                best_idx = i;\n            }\n        }\n\n        if (best_idx == -1) {\n            break; \/\/ we couldn't find any more pairs to merge, so we're done\n        }\n\n        \/\/ merge the consecutive pair (best_idx, best_idx+1) into new token best_id\n        tokens[best_idx] = best_id;\n        \/\/ delete token at position best_idx+1, shift the entire sequence back 1\n        for (int i = best_idx+1; i &lt; (*n_tokens-1); i++) {\n            tokens[i] = tokens[i+1];\n        }\n        (*n_tokens)--; \/\/ token length decreased\n    }\n\n    \/\/ add optional EOS (=2) token, if desired\n    \/\/ \u5982\u679c\u9700\u8981\uff0c\u6dfb\u52a0 EOS (=2) \u4ee4\u724c\n    if (eos) tokens[(*n_tokens)++] = 2;\n\n    free(str_buffer);\n}\n\n\nint main(int argc, char *argv[]) {\n\n    char *tokenizer_path = \"tokenizer.bin\";\n    \n    \/\/ build the Tokenizer via the tokenizer .bin file\n    Tokenizer tokenizer;\n    int vocab_size = 32000; \/\/ \u4ece\u6a21\u578b\u6587\u4ef6\u7684 config.json \u83b7\u53d6\n    build_tokenizer(&amp;tokenizer, tokenizer_path, vocab_size);\n    \n    \/\/ encode the (string) prompt into tokens sequence\n    \/\/ \u5c06\u5b57\u7b26\u4e32\u63d0\u793a\u7f16\u7801\u4e3a\u4ee4\u724c\u5e8f\u5217\n    char *prompt = \" The meaning of life is\";\n    int num_prompt_tokens = 0;\n    int* prompt_tokens = (int*)malloc((strlen(prompt)+3) * sizeof(int)); \/\/ +3 for '\\0', ?BOS, ?EOS\n    encode(&amp;tokenizer, prompt, 1, 0, prompt_tokens, &amp;num_prompt_tokens);\n    if (num_prompt_tokens &lt; 1) {\n        fprintf(stderr, \"something is wrong, expected at least 1 prompt token\\n\");\n        exit(EXIT_FAILURE);\n    }\n    \n    int i = 0;\n    for(i = 0; i &lt; num_prompt_tokens; i++)\n    {\n      int token = prompt_tokens[i];\n      printf(\"%2d, %5d, %12.6lf, (%s)\\n\", i, token, \n        tokenizer.vocab_scores[token], tokenizer.vocab[token]);\n    }\n\n    free_tokenizer(&amp;tokenizer);\n    free(prompt_tokens);\n    \n    return 0;\n}<\/pre><\/div>\n\n\n\n<p>\u7f16\u8bd1 test02.c<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:sh decode:true \">make test02\ncc     test02.c   -o test02<\/pre><\/div>\n\n\n\n<p>\u8fd0\u884c test02<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:sh decode:true \">.\/test02\n 0,     1,     0.000000, (\n&lt;s&gt;\n)\n 1,   450,  -191.000000, ( The)\n 2,  6593, -6334.000000, ( meaning)\n 3,   310,   -51.000000, ( of)\n 4,  2834, -2575.000000, ( life)\n 5,   338,   -79.000000, ( is)<\/pre><\/div>\n\n\n\n<p>\u4ece test10.py \u548c test02.c \u7684\u8fd0\u884c\u7ed3\u679c\u6765\u770b\uff0c\u8fd0\u884c\u7ed3\u679c\u662f\u4e00\u81f4\u7684<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>11. \u5c06\u5b57\u7b26\u4e32\u7f16\u7801\u4e3a\u4ee4\u724c\u5e8f\u5217 \u5728\u804a\u5929\u7684\u65f6\u5019\uff0c\u9700\u8981\u628a\u5b57\u7b26\u4e32\u901a\u8fc7 tokenizer \u8fdb\u884c\u7f16\u7801\uff0c\u547d\u540d\u4e3a test [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[313,289,443,442,312],"tags":[242,314],"class_list":["post-2480","post","type-post","status-publish","format-standard","hentry","category-chatgpt","category-gpt","category-llm","category-llms","category-openai","tag-chatgpt","tag-openai-api"],"views":1018,"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=\/wp\/v2\/posts\/2480","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2480"}],"version-history":[{"count":12,"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=\/wp\/v2\/posts\/2480\/revisions"}],"predecessor-version":[{"id":2512,"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=\/wp\/v2\/posts\/2480\/revisions\/2512"}],"wp:attachment":[{"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2480"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2480"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aqwu.net\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2480"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}