"""Answer questions about retrieved pages with Granite Vision 5.0 and a Granite language model.""" import os from collections.abc import Iterator from threading import Thread import torch from PIL import Image from transformers import ( AutoModelForCausalLM, AutoModelForImageTextToText, AutoProcessor, AutoTokenizer, TextIteratorStreamer, ) # Private until release: the Space needs an HF_TOKEN secret with read access to ibm-granite. VISION_MODEL_ID = os.environ.get("VISION_MODEL_ID", "ibm-granite/granite-vision-5.0-4b") # The fp8 checkpoint is what the Granite Guardian Space ships; MPS cannot dequantize fp8, so use bf16 there. LLM_MODEL_ID = os.environ.get("LLM_MODEL_ID", "ibm-granite/granite-4.1-3b-fp8") LLM_MODEL_ID_BF16 = "ibm-granite/granite-4.1-3b" VISION_MAX_NEW_TOKENS = 512 LLM_MAX_NEW_TOKENS = 512 _vision: tuple | None = None _llm: tuple | None = None def _device() -> str: if torch.cuda.is_available(): return "cuda" return "mps" if torch.backends.mps.is_available() else "cpu" def _load_vision() -> tuple: """Load the vision model and processor once, on CPU (moved to GPU inside the GPU call).""" global _vision if _vision is None: processor = AutoProcessor.from_pretrained(VISION_MODEL_ID) processor.tokenizer.padding_side = "left" model = AutoModelForImageTextToText.from_pretrained(VISION_MODEL_ID, dtype=torch.bfloat16).eval() _vision = (model, processor) return _vision def _load_llm() -> tuple: """Load the language model and tokenizer once, on CPU (moved to GPU inside the GPU call).""" global _llm if _llm is None: # Pick bf16 on Apple silicon, which cannot dequantize the fp8 checkpoint. model_id = LLM_MODEL_ID_BF16 if _device() == "mps" and LLM_MODEL_ID.endswith("-fp8") else LLM_MODEL_ID tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16).eval() _llm = (model, tokenizer) return _llm def _move(model: torch.nn.Module) -> torch.nn.Module: device = _device() if next(model.parameters()).device.type != device: model.to(device) return model def read_page(question: str, image: Image.Image) -> Iterator[tuple[str, int]]: """Ask Granite Vision about one page image, yielding (text so far, tokens so far) as it streams.""" model, processor = _load_vision() model = _move(model) conversation = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": question}]}] text = processor.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True) inputs = processor(text=[text], images=[image], return_tensors="pt", padding=True, do_pad=True).to(model.device) streamer = TextIteratorStreamer(processor.tokenizer, skip_special_tokens=True, skip_prompt=True) thread = Thread( target=_generate, kwargs={"model": model, "streamer": streamer, "max_new_tokens": VISION_MAX_NEW_TOKENS, **inputs}, ) thread.start() page_text = "" for chunk in streamer: page_text += chunk yield page_text, _count_tokens(processor.tokenizer, page_text) thread.join() def _count_tokens(tokenizer: object, text: str) -> int: return len(tokenizer(text, add_special_tokens=False).input_ids) def _generate(model: torch.nn.Module, **kwargs: object) -> None: with torch.inference_mode(): model.generate(**kwargs, use_cache=True) def answer_from_notes(question: str, notes: str) -> Iterator[tuple[str, int]]: """Stream the language model's answer from the vision model's notes, yielding (answer so far, tokens so far).""" model, tokenizer = _load_llm() model = _move(model) messages = [ { "role": "system", "content": ( "You answer questions about a document. You are given notes that a vision model wrote " "after reading the most relevant pages. " "Answer using only that material. If it does not contain the answer, say so. " "Cite the page number like (page 3). Answer in the language of the question." ), }, {"role": "user", "content": f"Material:\n{notes}\n\nQuestion: {question}"}, ] prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) inputs = tokenizer(prompt, return_tensors="pt").to(model.device) streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True, skip_prompt=True) thread = Thread( target=_generate, kwargs={ "model": model, "streamer": streamer, "max_new_tokens": LLM_MAX_NEW_TOKENS, "do_sample": True, "temperature": 0.2, "top_p": 0.95, **inputs, }, ) thread.start() answer = "" for chunk in streamer: answer += chunk yield answer, _count_tokens(tokenizer, answer) thread.join()