|
| 1 | +--- |
| 2 | +title: Deploy Vision Chatbot LLM backend server |
| 3 | +weight: 4 |
| 4 | + |
| 5 | +layout: learningpathall |
| 6 | +--- |
| 7 | + |
| 8 | +## Backend Script for Vision Chatbot LLM Server |
| 9 | +Once the virtual environment is activated, create a `backend.py` script using the following content. This script downloads the Llama 3.2 Vision model from Hugging Face, performs 4-bit quantization on the model and then serves it with PyTorch on Arm: |
| 10 | + |
| 11 | +```python |
| 12 | +from flask import Flask, request, Response, stream_with_context |
| 13 | +from transformers import MllamaForConditionalGeneration, AutoProcessor, TextIteratorStreamer |
| 14 | +from threading import Thread |
| 15 | +from PIL import Image |
| 16 | +import torch |
| 17 | +import json |
| 18 | +import time |
| 19 | +import io |
| 20 | +import base64 |
| 21 | + |
| 22 | +app = Flask(__name__) |
| 23 | + |
| 24 | +# Load model and processor |
| 25 | +model_id = "meta-llama/Llama-3.2-11B-Vision-Instruct" |
| 26 | +model = MllamaForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.float32) |
| 27 | + |
| 28 | +# Apply torchao quantization |
| 29 | +from torchao.dtypes import PlainLayout |
| 30 | +from torchao.experimental.packed_linear_int8_dynamic_activation_intx_weight_layout import ( |
| 31 | + PackedLinearInt8DynamicActivationIntxWeightLayout, |
| 32 | +) |
| 33 | +from torchao.experimental.quant_api import int8_dynamic_activation_intx_weight |
| 34 | +from torchao.quantization.granularity import PerGroup |
| 35 | +from torchao.quantization.quant_api import quantize_ |
| 36 | +from torchao.quantization.quant_primitives import MappingType |
| 37 | + |
| 38 | +quantize_( |
| 39 | + model, |
| 40 | + int8_dynamic_activation_intx_weight( |
| 41 | + weight_dtype=torch.int4, |
| 42 | + granularity=PerGroup(32), |
| 43 | + has_weight_zeros=True, |
| 44 | + weight_mapping_type=MappingType.SYMMETRIC_NO_CLIPPING_ERR, |
| 45 | + layout=PackedLinearInt8DynamicActivationIntxWeightLayout(target="aten"), |
| 46 | + ), |
| 47 | +) |
| 48 | + |
| 49 | +processor = AutoProcessor.from_pretrained(model_id) |
| 50 | +model.eval() |
| 51 | + |
| 52 | +@app.route("/v1/chat/completions", methods=["POST"]) |
| 53 | +def chat_completions(): |
| 54 | + image = None |
| 55 | + prompt = "" |
| 56 | + |
| 57 | + if "image" in request.files: |
| 58 | + file = request.files["image"] |
| 59 | + image = Image.open(file.stream).convert("RGB") |
| 60 | + prompt = request.form.get("prompt", "") |
| 61 | + elif request.is_json: |
| 62 | + data = request.get_json() |
| 63 | + if "image" in data: |
| 64 | + image_bytes = base64.b64decode(data["image"]) |
| 65 | + image = Image.open(io.BytesIO(image_bytes)).convert("RGB") |
| 66 | + if "prompt" in data: |
| 67 | + prompt = data["prompt"] |
| 68 | + elif "messages" in data: |
| 69 | + for msg in data["messages"]: |
| 70 | + if msg.get("role") == "user": |
| 71 | + prompt = msg.get("content", "") |
| 72 | + break |
| 73 | + |
| 74 | + if image is None or not prompt: |
| 75 | + return {"error": "Both image and prompt are required."}, 400 |
| 76 | + |
| 77 | + # Format the prompt |
| 78 | + formatted_prompt = ( |
| 79 | + f"<|begin_of_text|><|image|>\n" |
| 80 | + f"<|user|>\n{prompt.strip()}<|end_of_text|>\n" |
| 81 | + "<|assistant|>\n" |
| 82 | + ) |
| 83 | + |
| 84 | + inputs = processor(image, formatted_prompt, return_tensors="pt").to(model.device) |
| 85 | + tokenizer = processor.tokenizer if hasattr(processor, "tokenizer") else processor |
| 86 | + |
| 87 | + # Initialize the TextIteratorStreamer |
| 88 | + text_streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) |
| 89 | + |
| 90 | + # Define generation arguments |
| 91 | + gen_kwargs = { |
| 92 | + "max_new_tokens": 512, |
| 93 | + "do_sample": False, |
| 94 | + "temperature": 1.0, |
| 95 | + "streamer": text_streamer, |
| 96 | + "eos_token_id": tokenizer.eos_token_id, |
| 97 | + } |
| 98 | + |
| 99 | + # Run generation in a separate thread |
| 100 | + generation_thread = Thread(target=model.generate, kwargs={**inputs, **gen_kwargs}) |
| 101 | + generation_thread.start() |
| 102 | + |
| 103 | + def stream_response(): |
| 104 | + assistant_role_chunk = { |
| 105 | + "id": f"chatcmpl-{int(time.time()*1000)}", |
| 106 | + "object": "chat.completion.chunk", |
| 107 | + "created": int(time.time()), |
| 108 | + "model": model_id, |
| 109 | + "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}] |
| 110 | + } |
| 111 | + yield f"data: {json.dumps(assistant_role_chunk)}\n\n" |
| 112 | + |
| 113 | + for token in text_streamer: |
| 114 | + if token.strip(): |
| 115 | + content_chunk = { |
| 116 | + "id": assistant_role_chunk["id"], |
| 117 | + "object": "chat.completion.chunk", |
| 118 | + "created": int(time.time()), |
| 119 | + "model": model_id, |
| 120 | + "choices": [{"index": 0, "delta": {"content": token}, "finish_reason": None}] |
| 121 | + } |
| 122 | + yield f"data: {json.dumps(content_chunk)}\n\n" |
| 123 | + |
| 124 | + finish_chunk = { |
| 125 | + "id": assistant_role_chunk["id"], |
| 126 | + "object": "chat.completion.chunk", |
| 127 | + "created": int(time.time()), |
| 128 | + "model": model_id, |
| 129 | + "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}] |
| 130 | + } |
| 131 | + yield f"data: {json.dumps(finish_chunk)}\n\n" |
| 132 | + yield "data: [DONE]\n\n" |
| 133 | + |
| 134 | + return Response(stream_with_context(stream_response()), mimetype='text/event-stream') |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + app.run(host="0.0.0.0", port=5000, threaded=True) |
| 138 | +``` |
| 139 | + |
| 140 | +## Run the Backend Server |
| 141 | + |
| 142 | +You are now ready to run the backend server for the Vision Chatbot. |
| 143 | +Use the following command in a terminal to start the backend server: |
| 144 | + |
| 145 | +```python |
| 146 | +LD_PRELOAD=/usr/lib/aarch64-linux-gnu/libtcmalloc.so.4 TORCHINDUCTOR_CPP_WRAPPER=1 TORCHINDUCTOR_FREEZING=1 OMP_NUM_THREADS=16 python3 backend.py |
| 147 | +``` |
| 148 | + |
| 149 | +You should see output similar to the image below when the backend server starts successfully: |
| 150 | + |
0 commit comments