视觉语言模型的多轮对话缓存与量化部署

本文介绍图像文本到文本任务的实践方法,包括用Pipeline快速调用模型、通过TextIteratorStreamer实现流式输出、用Quanto做int8量化以适配小硬件,以及在多轮多模态对话中复用编码缓存减少重复计算。

Copyright 2024 HuggingFace Team. 全权保留. 根据 Apache 许可, 版本 2.0 (“ License ”) 获得许可; 您不能使用此文件, 除非符合 您可在下列地点获得许可证副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或书面同意,否则根据许可证分发的软件在下列网址分发: a " :ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,或明示的或暗示的。 《许可证》规定的许可和限制的具体语言。 QQ 注意, 此文件在 Markdown 中, 但包含我们doc- buildinger( 类似于 MDX ) 的特定语法, 可能不是 在您的Markdown 查看器中正确渲染。 # 图像 - text-to-text [[open-in-colab]] 图像- text-to-text 模型,又称视觉语言模型(VLMs),是使用图像输入的语言模型,这些模型可以处理各种任务,从视觉问题回答到图像分割. 这个任务与image-to-text有很多相似之处,但有一些重叠的使用案例如图像字幕.图像到文本模型只接受图像输入,往往完成特定任务,而VLM则接受开放式文本和图像输入,是比较概括的模型. 在本指南中,我们简要概述了VLM,并展示了如何用Transformers进行推论. 首先,VLM有多种类型: - 用于微调的基础模型 - 聊天的微调模式 - 指令精细调整模型 本指南以指导调制模型为重点推论. 让我们开始安装依赖。 ```bash pip install -q transformers accelerate pip install flash-attn --no-build-isolation ``` 让我们初始化模型和处理器。 ```python from transformers import AutoProcessor, AutoModelForImageTextToText from accelerate import Accelerator import torch device = Accelerator().device model = AutoModelForImageTextToText.from_pretrained( "Qwen/Qwen3-VL-4B-Instruct", dtype=torch.bfloat16, attn_implementation="flash_attention_2", ).to(device) ``` > [!WARNING] > 动态分辨率模型,例如 Quen3 - VL 和 Qwen3.5 默认为 ~16MP `longest_edge`,可以发出10,000+ 每张图像的视觉信号符和悬浮推论或OOM设定 `min_pixels` 财务报告和财务报告 `max_pixels` 当装入处理器以盖住此选项时。 ```python processor = AutoProcessor.from_pretrained( "Qwen/Qwen3-VL-4B-Instruct", min_pixels=224 * 224, max_pixels=1024 * 1024, ) ``` 这个模型有一个 [聊天模板](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/chat_templating>) 帮助用户解析聊天输出。此外,该模型还可以接受多个图像作为单个对话或消息中的输入。我们现在准备输入。 图像输入的外观如下. (原始内容存档于2018-07-29). https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png" alt="两只猫坐网"/". (原始内容存档于2017-03-01). https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg" alt="粉红花上的一只蜜蜂"/. 下面显示的您的对话结构, 用于一个带有图像和文本输入的单个提示 。 ```python messages = [ { "role": "user", "content": [ {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png"}, {"type": "text", "text": "What do we see in this image?"}, ] } ] ``` 候补 `user` 财务报告和财务报告 `assistant` (b) 发挥前述作用,为模型打下基础,以产生更好的反应。 ```python messages = [ { "role": "user", "content": [ {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png"}, {"type": "text", "text": "What do we see in this image?"}, ] }, { "role": "assistant", "content": [ {"type": "text", "text": "In this image we can see two cats on the nets."}, ] }, { "role": "user", "content": [ {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"}, {"type": "text", "text": "And how about this image?"}, ] }, ] ``` 我们现在叫处理者们 [`~ProcessorMixin.apply_chat_template`] 与图像输入一起预处理输出的方法。 ```python inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(device) ``` 我们现在可以把预先处理过的输入传递到模型中. ```python input_len = len(inputs.input_ids[0]) with torch.no_grad(): generated_ids = model.generate(**inputs, max_new_tokens=200) generated_texts = processor.batch_decode(generated_ids[:, input_len:], skip_special_tokens=True) print(generated_texts) ## ['In this image we can see flowers, plants and insect.'] ``` ## 管道 最快的启动方式是使用 [`Pipeline`] API 请注明 `"image-text-to-text"` 任务和您想要使用的模型。 ```python from transformers import pipeline pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf") ``` 下面的例子使用聊天模板来格式化文本输入. ```python messages = [ { "role": "user", "content": [ { "type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg", }, {"type": "text", "text": "Describe this image."}, ], }, { "role": "assistant", "content": [ {"type": "text", "text": "There's a pink flower"}, ], }, ] ``` 将聊天模板格式化的文本和图像传递到 [`Pipeline`] 设置 `return_full_text=False` 从生成的输出中删除输入。 ```python outputs = pipe(text=messages, max_new_tokens=20, return_full_text=False) outputs[0]["generated_text"] # with a yellow center in the foreground. The flower is surrounded by red and white flowers with green stems ``` 如果你喜欢的话,你也可以单独装入图像,然后像这样传到管道: ```python import requests from PIL import Image from transformers import pipeline pipe = pipeline("image-text-to-text", model="HuggingFaceTB/SmolVLM-256M-Instruct") img_urls = [ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg", ] images = [ Image.open(requests.get(img_urls[0], stream=True).raw), Image.open(requests.get(img_urls[1], stream=True).raw), ] messages = [ { "role": "user", "content": [ {"type": "image"}, {"type": "image"}, {"type": "text", "text": "What do you see in these images?"}, ], } ] outputs = pipe(text=messages, images=images, max_new_tokens=50, return_full_text=False) outputs[0]["generated_text"] " In the first image, there are two cats sitting on a plant. In the second image, there are flowers with a pinkish hue." ``` 这些图像仍将包含在 `"input_text"` 输出字段 : ```python outputs[0]['input_text'] """ [{'role': 'user', 'content': [{'type': 'image', 'image': <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=622x412>}, {'type': 'image', 'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=5184x3456>}, {'type': 'text', 'text': 'What do you see in these images?'}]}] """ ``` ## 流线 我们能用 [文本流转](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/generation_features#streaming>) 用于更好的一代体验。 Transformers 支持 与 [`TextStreamer`] 或 时 间 [`TextIteratorStreamer`] 学习。我们将使用 [`TextIteratorStreamer`] 与IDEFICS-8B. 假设我们有一个应用程序可以保持聊天历史, 并接收新用户输入。 我们将一如既往地对输入进行预处理并初始化 [`TextIteratorStreamer`] 以单独的线程处理生成。这使您可以实时流出生成的文本符号。任何生成的参数都可以传递到 [`TextIteratorStreamer`]. ```python import time from transformers import TextIteratorStreamer from threading import Thread def model_inference( user_prompt, chat_history, max_new_tokens, images ): user_prompt = { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text": user_prompt}, ] } chat_history.append(user_prompt) streamer = TextIteratorStreamer( processor.tokenizer, skip_prompt=True, timeout=5.0, ) generation_args = { "max_new_tokens": max_new_tokens, "streamer": streamer, "do_sample": False } # add_generation_prompt=True makes model generate bot response prompt = processor.apply_chat_template(chat_history, add_generation_prompt=True) inputs = processor( text=prompt, images=images, return_tensors="pt", ).to(device) generation_args.update(inputs) thread = Thread( target=model.generate, kwargs=generation_args, ) thread.start() acc_text = "" for text_token in streamer: time.sleep(0.04) acc_text += text_token if acc_text.endswith("<end_of_utterance>"): acc_text = acc_text[:-18] yield acc_text thread.join() ``` 瞷и `model_inference` 函数,我们创建并流出值。 ```python generator = model_inference( user_prompt="And what is in this image?", chat_history=messages[:2], max_new_tokens=100, images=images ) for value in generator: print(value) # In # In this # In this image ... ``` ## 在较小的硬件中匹配模型 VLM往往很大,需要优化以适应更小的硬件. Transformers支持许多模型化的四解库,在这里,我们将只显示 int8 的四解 [泉涛](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/quantization/quanto>). int8 量化提供了高达75%的内存改善(如果所有重量被量化的话),但是它不是免费的午餐,因为8 - bit不是CUDA-内在精度,因此在苍蝇上前后的重量被量化,这加起来就是空闲的. 首先,安装依赖性. ```bash pip install -U optimum-quanto bitsandbytes ``` 要在加载时对一个模型进行量化,首先需要创建 [`QuantoConfig`]。然后照常装入模型,但通过 `quantization_config` 在模型初始化期间。 ```python from transformers import AutoModelForImageTextToText, QuantoConfig model_id = "Qwen/Qwen3-VL-4B-Instruct" quantization_config = QuantoConfig(weights="int8") quantized_model = AutoModelForImageTextToText.from_pretrained( model_id, device_map="auto", quantization_config=quantization_config ) messages = [ { "role": "user", "content": [ {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png"}, {"type": "text", "text": "What do we see in this image?"}, ] }, ] inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(quantized_model.device) input_len = len(inputs.input_ids[0]) with torch.no_grad(): generated_ids = quantized_model.generate(**inputs, cache_implementation="static", max_new_tokens=100) generated_texts = processor.batch_decode(generated_ids[:, input_len:], skip_special_tokens=True) print(generated_texts[0]) ## ['In this image, we see two tabby cats resting on a large, tangled pile of fishing nets. The nets are a mix of brown, orange, and red colors, with some blue and green ropes visible in the background. The cats appear relaxed and comfortable, nestled into the fibers of the nets. One cat is in the foreground, looking slightly to the side, while the other is positioned further back, looking directly at the camera. The scene suggests a coastal or fishing-related setting, possibly near'] ``` 就是这样,我们可以用同样的模式,没有变化。 ## 与缓存进行迭代聊天 如果你正在构建多模式聊天代理,你很可能会通过同样的图像或音频,通过转弯。Caching让你重新使用它们编码的表达方式,而不是每次再处理它们,削减冗余的计算。 和只使用文本的模型一样,多式联运模型跟踪对话框历史 [聊天模板](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/chat_templating>)。关键区别在于它应用了聊天模板。 `"text"` 格式并分别处理新的多模式内容。如果用处理程序应用模板,则整个对话会每转一次进行重新处理,因为Jinja无法区分先前编码的输入和新的输入。 下面的例子说明了这种模式。关于文本模式,请参见: [迭代生成](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/kv_cache#iterative-generation>) 向导。 以下是一个简单的 Python 实例, 演示这个模式。 对于只使用文本模式的示例, 请参考 [本指南](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/kv_cache.md#iterative-generation>). ```python import torch from transformers import AutoProcessor, Gemma4ForConditionalGeneration, TextStreamer from transformers.cache_utils import DynamicCache from transformers.image_utils import load_image from transformers.audio_utils import load_audio model_id = 'google/gemma-4-E2B-it' processor = AutoProcessor.from_pretrained(model_id) model = Gemma4ForConditionalGeneration.from_pretrained(model_id, dtype=torch.float32, device_map='cpu') cache = DynamicCache() streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True) ## Turn 1: multimodal input (text + image + audio) audio = load_audio("https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav") image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg") messages = [ { "role": "user", "content": [ {"type": "text", "text": "In detail, describe the following audio and image."}, {"type": "audio"}, {"type": "image"}, ], }, ] input_string = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) inputs = processor(text=input_string, images=[image], audio=[audio], return_tensors='pt') output = model.generate(**inputs, cache=cache, max_new_tokens=1024, do_sample=False, streamer=streamer) first_response = processor.decode(output[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True) ## Turn 2: text-only follow-up (reuses KV cache, no new media) messages.append({"role": "assistant", "content": [{"type": "text", "text": first_response}]}) cached_string = processor.apply_chat_template(messages, tokenize=False) messages.append({"role": "user", "content": [{"type": "text", "text": "Summarize the previous descriptions in one sentence."}]}) full_string = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) new_string = full_string[len(cached_string):] new_input_ids = processor.tokenizer(new_string, add_special_tokens=False, return_tensors='pt')['input_ids'] # Build and pass an attention mask only if batched input or there is padding # attention_mask = torch.ones(1, cache.get_seq_length() + new_input_ids.shape[1], dtype=torch.long) output2 = model.generate(input_ids=new_input_ids, cache=cache, max_new_tokens=1024, do_sample=False, streamer=streamer) second_response = processor.decode(output2[0][new_input_ids.shape[1]:], skip_special_tokens=True) ## Turn 3: new image (must go through processor for image token expansion + encoding) image2 = load_image("https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/artemis.jpeg") messages.append({"role": "assistant", "content": [{"type": "text", "text": second_response}]}) cached_string2 = processor.apply_chat_template(messages, tokenize=False) messages.append({"role": "user", "content": [{"type": "text", "text": "Describe this image."}, {"type": "image"}]}) full_string2 = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) new_string2 = full_string2[len(cached_string2):] new_inputs2 = processor(text=new_string2, images=[image2], add_special_tokens=False, return_tensors='pt') # new_inputs2['attention_mask'] = torch.ones(1, cache.get_seq_length() + new_inputs2['input_ids'].shape[1], dtype=torch.long) new_inputs2['cache'] = cache output3 = model.generate(**new_inputs2, max_new_tokens=1024, do_sample=False, streamer=streamer) ``` ## 进一步阅读 以下是一些用于image-text-to-text任务的资源. - [图像 - text-to-text 任务页面](https://huggingface.co/tasks/image-text-to-text) 覆盖模型类型,使用大小写,数据集等. - [远景语言模型解释](https://huggingface.co/blog/vlms) 一个博客, 覆盖所有关于视觉语言模型, [TRL](https://huggingface.co/docs/trl/en/index). - [学会如何使用 TRL 微调视觉语言模型](https://huggingface.co/blog/trl-vlm-alignment)

查看原始来源