llama_index [Bug]: TreeSummarize Llamacpp llm 请求的令牌超过上下文窗口

apeeds0o  于 22天前  发布在  Mac
关注(0)|答案(2)|浏览(34)

Bug描述

我尝试使用llamacpp和Mistral-7b进行树形摘要。然而,我遇到了一个问题,即模型默认嵌入了一个BOS标记。当我在提示模板中使用prompttemplate时,已经给出了一个BOS标记,它会给出警告并超过上下文窗口。
以下是llamacpp的配置:

llama_model_loader: loaded meta data with 29 key-value pairs and 291 tensors from model.gguf (version GGUF V3 (latest))
llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
llama_model_loader: - kv   0:                       general.architecture str              = llama
llama_model_loader: - kv   1:                               general.name str              = Mistral-7B-Instruct-v0.3
llama_model_loader: - kv   2:                          llama.block_count u32              = 32
llama_model_loader: - kv   3:                       llama.context_length u32              = 32768
llama_model_loader: - kv   4:                     llama.embedding_length u32              = 4096
llama_model_loader: - kv   5:                  llama.feed_forward_length u32              = 14336
llama_model_loader: - kv   6:                 llama.attention.head_count u32              = 32
llama_model_loader: - kv   7:              llama.attention.head_count_kv u32              = 8
llama_model_loader: - kv   8:                       llama.rope.freq_base f32              = 1000000.000000
llama_model_loader: - kv   9:     llama.attention.layer_norm_rms_epsilon f32              = 0.000010
llama_model_loader: - kv  10:                          general.file_type u32              = 18
llama_model_loader: - kv  11:                           llama.vocab_size u32              = 32768
llama_model_loader: - kv  12:                 llama.rope.dimension_count u32              = 128
llama_model_loader: - kv  13:                       tokenizer.ggml.model str              = llama
llama_model_loader: - kv  14:                         tokenizer.ggml.pre str              = default
llama_model_loader: - kv  15:                      tokenizer.ggml.tokens arr[str,32768]   = ["<unk>", "<s>", "</s>", "[INST]", "[...
llama_model_loader: - kv  16:                      tokenizer.ggml.scores arr[f32,32768]   = [0.000000, 0.000000, 0.000000, 0.0000...
llama_model_loader: - kv  17:                  tokenizer.ggml.token_type arr[i32,32768]   = [2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, ...
llama_model_loader: - kv  18:                tokenizer.ggml.bos_token_id u32              = 1
llama_model_loader: - kv  19:                tokenizer.ggml.eos_token_id u32              = 2
llama_model_loader: - kv  20:            tokenizer.ggml.unknown_token_id u32              = 0
llama_model_loader: - kv  21:               tokenizer.ggml.add_bos_token bool             = true
llama_model_loader: - kv  22:               tokenizer.ggml.add_eos_token bool             = false
llama_model_loader: - kv  23:                    tokenizer.chat_template str              = {{ bos_token }}{% for message in mess...
llama_model_loader: - kv  24:               general.quantization_version u32              = 2
llama_model_loader: - kv  25:                      quantize.imatrix.file str              = /models/Mistral-7B-Instruct-v0.3-GGUF...
llama_model_loader: - kv  26:                   quantize.imatrix.dataset str              = /training_data/calibration_data.txt
llama_model_loader: - kv  27:             quantize.imatrix.entries_count i32              = 224
llama_model_loader: - kv  28:              quantize.imatrix.chunks_count i32              = 228
llama_model_loader: - type  f32:   65 tensors
llama_model_loader: - type q6_K:  226 tensors
llm_load_vocab: special tokens cache size = 1027
llm_load_vocab: token to piece cache size = 0.1731 MB
llm_load_print_meta: format           = GGUF V3 (latest)
llm_load_print_meta: arch             = llama
llm_load_print_meta: vocab type       = SPM
llm_load_print_meta: n_vocab          = 32768
llm_load_print_meta: n_merges         = 0
llm_load_print_meta: n_ctx_train      = 32768
llm_load_print_meta: n_embd           = 4096
llm_load_print_meta: n_head           = 32
llm_load_print_meta: n_head_kv        = 8
llm_load_print_meta: n_layer          = 32
llm_load_print_meta: n_rot            = 128
llm_load_print_meta: n_embd_head_k    = 128
llm_load_print_meta: n_embd_head_v    = 128
llm_load_print_meta: n_gqa            = 4
llm_load_print_meta: n_embd_k_gqa     = 1024
llm_load_print_meta: n_embd_v_gqa     = 1024
llm_load_print_meta: f_norm_eps       = 0.0e+00
llm_load_print_meta: f_norm_rms_eps   = 1.0e-05
llm_load_print_meta: f_clamp_kqv      = 0.0e+00
llm_load_print_meta: f_max_alibi_bias = 0.0e+00
llm_load_print_meta: f_logit_scale    = 0.0e+00
llm_load_print_meta: n_ff             = 14336
llm_load_print_meta: n_expert         = 0
llm_load_print_meta: n_expert_used    = 0
llm_load_print_meta: causal attn      = 1
llm_load_print_meta: pooling type     = 0
llm_load_print_meta: rope type        = 0
llm_load_print_meta: rope scaling     = linear
llm_load_print_meta: freq_base_train  = 1000000.0
llm_load_print_meta: freq_scale_train = 1
llm_load_print_meta: n_ctx_orig_yarn  = 32768
llm_load_print_meta: rope_finetuned   = unknown
llm_load_print_meta: ssm_d_conv       = 0
llm_load_print_meta: ssm_d_inner      = 0
llm_load_print_meta: ssm_d_state      = 0
llm_load_print_meta: ssm_dt_rank      = 0
llm_load_print_meta: model type       = 7B
llm_load_print_meta: model ftype      = Q6_K
llm_load_print_meta: model params     = 7.25 B
llm_load_print_meta: model size       = 5.54 GiB (6.56 BPW) 
llm_load_print_meta: general.name     = Mistral-7B-Instruct-v0.3
llm_load_print_meta: BOS token        = 1 '<s>'
llm_load_print_meta: EOS token        = 2 '</s>'
llm_load_print_meta: UNK token        = 0 '<unk>'
llm_load_print_meta: LF token         = 781 '<0x0A>'
llm_load_tensors: ggml ctx size =    0.15 MiB
llm_load_tensors:        CPU buffer size =  5671.02 MiB
...................................................................................................
llama_new_context_with_model: n_ctx      = 3904
llama_new_context_with_model: n_batch    = 512
llama_new_context_with_model: n_ubatch   = 512
llama_new_context_with_model: flash_attn = 0
llama_new_context_with_model: freq_base  = 1000000.0
llama_new_context_with_model: freq_scale = 1
llama_kv_cache_init:        CPU KV buffer size =   488.00 MiB
llama_new_context_with_model: KV self size  =  488.00 MiB, K (f16):  244.00 MiB, V (f16):  244.00 MiB
llama_new_context_with_model:        CPU  output buffer size =     0.13 MiB
llama_new_context_with_model:        CPU compute buffer size =   283.63 MiB
llama_new_context_with_model: graph nodes  = 1030
llama_new_context_with_model: graph splits = 1
AVX = 1 | AVX_VNNI = 0 | AVX2 = 1 | AVX512 = 1 | AVX512_VBMI = 0 | AVX512_VNNI = 0 | AVX512_BF16 = 0 | FMA = 1 | NEON = 0 | SVE = 0 | ARM_FMA = 0 | F16C = 1 | FP16_VA = 0 | WASM_SIMD = 0 | BLAS = 0 | SSE3 = 1 | SSSE3 = 1 | VSX = 0 | MATMUL_INT8 = 0 | LLAMAFILE = 1 | 
Model metadata: {'quantize.imatrix.entries_count': '224', 'quantize.imatrix.dataset': '/training_data/calibration_data.txt', 'quantize.imatrix.chunks_count': '228', 'quantize.imatrix.file': '/models/Mistral-7B-Instruct-v0.3-GGUF/Mistral-7B-Instruct-v0.3.imatrix', 'tokenizer.chat_template': "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}", 'tokenizer.ggml.add_eos_token': 'false', 'tokenizer.ggml.unknown_token_id': '0', 'tokenizer.ggml.eos_token_id': '2', 'general.quantization_version': '2', 'tokenizer.ggml.model': 'llama', 'general.architecture': 'llama', 'llama.rope.freq_base': '1000000.000000', 'tokenizer.ggml.pre': 'default', 'llama.context_length': '32768', 'general.name': 'Mistral-7B-Instruct-v0.3', 'tokenizer.ggml.add_bos_token': 'true', 'llama.embedding_length': '4096', 'llama.feed_forward_length': '14336', 'llama.attention.layer_norm_rms_epsilon': '0.000010', 'tokenizer.ggml.bos_token_id': '1', 'llama.attention.head_count': '32', 'llama.block_count': '32', 'llama.attention.head_count_kv': '8', 'general.file_type': '18', 'llama.vocab_size': '32768', 'llama.rope.dimension_count': '128'}
Available chat formats from metadata: chat_template.default
Guessed chat format: mistral-instruct

我是这样初始化llm的:

llm = LlamaCPP(
    model_url=None,
    model_path='model.gguf',
    temperature=0.1,
    max_new_tokens=256,
    context_window=3900,
    generate_kwargs={},
    model_kwargs={"n_gpu_layers": -1},
    messages_to_prompt=messages_to_prompt,
    completion_to_prompt=completion_to_prompt,
    verbose=True,
)

然后像这样调用TreeSummary:

summarizer = TreeSummarize(llm=llm,verbose=True, summary_template=qa_prompt)
response = summarizer.get_response(
    "Now please summarize text below", [text], tone_name="an intelligent summarizer"
)

下面的警告错误如下:

llama_tokenize_internal: Added a BOS token to the prompt as specified by the model but the prompt also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. Are you sure this is what you want?
2 text chunks after repacking
/usr/local/lib/python3.10/dist-packages/llama_cpp/llama.py:1031: RuntimeWarning: Detected duplicate leading "<s>" in prompt, this will likely reduce response quality, consider removing it...
  warnings.warn(
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
[<ipython-input-19-f523ca93d56a>](https://localhost:8080/#) in <cell line: 1>()
----> 1 response = summarizer.get_response(
      2     "Now please summarize the meeting from the given coversation below", [text], tone_name="an intelligent meeting notes keeper"
      3 )

10 frames
[/usr/local/lib/python3.10/dist-packages/llama_cpp/llama.py](https://localhost:8080/#) in _create_completion(self, prompt, suffix, max_tokens, temperature, top_p, min_p, typical_p, logprobs, echo, stop, frequency_penalty, presence_penalty, repeat_penalty, top_k, stream, seed, tfs_z, mirostat_mode, mirostat_tau, mirostat_eta, model, stopping_criteria, logits_processor, grammar, logit_bias)
   1060 
   1061         if len(prompt_tokens) >= self._n_ctx:
-> 1062             raise ValueError(
   1063                 f"Requested tokens ({len(prompt_tokens)}) exceed context window of {llama_cpp.llama_n_ctx(self.ctx)}"
   1064             )

ValueError: Requested tokens (4212) exceed context window of 3904

我可以向你保证问题不在于上下文长度本身。因为每次我在配置中增加上下文长度时,消息都会不断增加其阈值,例如
ValueError: 请求的标记数(8462)超过了上下文窗口大小为8000时的上下文窗口大小。

版本

llama_index_llms_llama_cpp-0.1.3

重现步骤

!wget -L https://huggingface.co/bartowski/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/Mistral-7B-Instruct-v0.3-Q6_K.gguf -O model.gguf
from llama_index.llms.llama_cpp import LlamaCPP
from llama_index.llms.llama_cpp.llama_utils import (
    messages_to_prompt,
    completion_to_prompt,
)

llm = LlamaCPP(
    # You can pass in the URL to a GGML model to download it automatically
    model_url=None,
    # optionally, you can set the path to a pre-downloaded model instead of model_url
    model_path='model.gguf',
    temperature=0.1,
    max_new_tokens=256,
    # llama2 has a context window of 4096 tokens, but we set it lower to allow for some wiggle room
    context_window=3900,
    # kwargs to pass to __call__()
    generate_kwargs={},
    # kwargs to pass to __init__()
    # set to at least 1 to use GPU
    model_kwargs={"n_gpu_layers": -1},
    # transform inputs into Llama2 format
    messages_to_prompt=messages_to_prompt,
    completion_to_prompt=completion_to_prompt,
    verbose=True,
)
from llama_index.core import SimpleDirectoryReader
reader = SimpleDirectoryReader(
    input_files=["con.txt"]
)
docs = reader.load_data()
text = docs[0].text
from llama_index.core import PromptTemplate
# NOTE: we add an extra tone_name variable here
qa_prompt_tmpl = (
    "Please also write the answer in the style of {tone_name}.\n"
    "Query: {query_str}\n"
    "---------------------\n"
    "{context_str}\n"
    "---------------------\n"
)
qa_prompt = PromptTemplate(qa_prompt_tmpl)

refine_prompt_tmpl = (
    "The original query is as follows: {query_str}\n"
    "We have provided an existing answer: {existing_answer}\n"
    "We have the opportunity to refine the existing answer "
    "(only if needed) with some more context below.\n"
    "------------\n"
    "{context_msg}\n"
    "------------\n"
    "Given the new context, refine the original answer to better "
    "answer the query. "
    "Please also write the answer in the style of {tone_name}.\n"
    "If the context isn't useful, return the original answer.\n"
    "Refined Answer: "
)
refine_prompt = PromptTemplate(refine_prompt_tmpl)

from llama_index.core.response_synthesizers import TreeSummarize, Refine
from llama_index.core.types import BaseModel
from typing import List
summarizer = TreeSummarize(llm=llm,verbose=True, summary_template=qa_prompt)
response = summarizer.get_response(
    "Now please summarize text below", [text], tone_name="an intelligent summarizer"
)

相关日志/回溯

llama_tokenize_internal: Added a BOS token to the prompt as specified by the model but the prompt also starts with a BOS token. So now the final prompt starts with 2 BOS tokens. Are you sure this is what you want?
2 text chunks after repacking
/usr/local/lib/python3.10/dist-packages/llama_cpp/llama.py:1031: RuntimeWarning: Detected duplicate leading "<s>" in prompt, this will likely reduce response quality, consider removing it...
  warnings.warn(
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
[<ipython-input-19-f523ca93d56a>](https://localhost:8080/#) in <cell line: 1>()
----> 1 response = summarizer.get_response(
      2     "Now please summarize the meeting from the given coversation below", [text], tone_name="an intelligent meeting notes keeper"
      3 )

10 frames
[/usr/local/lib/python3.10/dist-packages/llama_cpp/llama.py](https://localhost:8080/#) in _create_completion(self, prompt, suffix, max_tokens, temperature, top_p, min_p, typical_p, logprobs, echo, stop, frequency_penalty, presence_penalty, repeat_penalty, top_k, stream, seed, tfs_z, mirostat_mode, mirostat_tau, mirostat_eta, model, stopping_criteria, logits_processor, grammar, logit_bias)
   1060 
   1061         if len(prompt_tokens) >= self._n_ctx:
-> 1062             raise ValueError(
   1063                 f"Requested tokens ({len(prompt_tokens)}) exceed context window of {llama_cpp.llama_n_ctx(self.ctx)}"
   1064             )

ValueError: Requested tokens (4212) exceed context window of 3904
k75qkfdt

k75qkfdt1#

嘿,@syedfahimabrar!我在这里帮助你解决任何错误、问题或与贡献相关的事情。告诉我如何帮助你!
要解决Mistra-7b模型添加重复BOS令牌的问题,这会导致警告并在使用TreeSummarizellamacpp时超过上下文窗口,你需要确保在重新打包文本块时不会多次添加BOS令牌。这可以通过修改messages_to_prompt函数来正确处理BOS令牌来实现。
以下是确保提示以系统提示开头并避免重复BOS令牌的messages_to_prompt函数的相关部分:

def messages_to_prompt(messages):
    prompt = ""
    for message in messages:
        if message.role == 'system':
            prompt += f"<|system|>\n{message.content}</s>\n"
        elif message.role == 'user':
            prompt += f"<|user|>\n{message.content}</s>\n"
        elif message.role == 'assistant':
            prompt += f"<|assistant|>\n{message.content}</s>\n"

    # ensure we start with a system prompt, insert blank if needed
    if not prompt.startswith("<|system|>\n"):
        prompt = "<|system|>\n</s>\n" + prompt

    # add final assistant prompt
    prompt = prompt + "<|assistant|>\n"

    return prompt

此函数通过检查提示是否已经以"<|system|>\n"开头来确保提示以系统提示开头并避免添加重复的BOS令牌。如果没有,它会在提示前添加"<|system|>\n</s>\n"
此外,你还可以在PromptHelper类中修改repack方法来正确处理BOS令牌:

class PromptHelper:
    def repack(self, summary_template, text_chunks):
        # Ensure BOS token is not duplicated
        processed_chunks = []
        for chunk in text_chunks:
            if chunk.startswith(BOS_TOKEN):
                chunk = chunk[len(BOS_TOKEN):]
            processed_chunks.append(chunk)
        
        # Repack the chunks to fit the context window
        # (Assuming repack logic here)
        repacked_chunks = self._repack_logic(summary_template, processed_chunks)
        
        return repacked_chunks

    def _repack_logic(self, summary_template, text_chunks):
        # Implement the logic to repack text chunks to fit the context window
        # This is a placeholder for the actual repacking logic
        pass

请确保将BOS_TOKEN替换为Mistra-7b模型实际使用的BOS令牌。这种修改可以确保在重新打包过程中不会出现重复的BOS令牌,从而防止警告和上下文窗口溢出。
通过实施这些更改,你应该能够避免重复的BOS令牌及其导致的上下文窗口溢出问题。

  • 要继续与Dosu交谈,请提及@dosu。*
zqry0prt

zqry0prt2#

@syedfahimabrar set the tokenizer so that the token counting is correct

Settings.tokenizer = AutoTokenizer.from_pretrained(
    # I used llama2 here, use whatever model matches for you
    "NousResearch/Llama-2-7b-chat-hf" 
)

相关问题