|
| 1 | +""" |
| 2 | +HF wrapper for Gemma |
| 3 | +""" |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | +from typing import Optional |
| 7 | + |
| 8 | +import torch |
| 9 | +from transformers import AutoProcessor, Gemma3ForConditionalGeneration |
| 10 | + |
| 11 | +from interact_llm.data_models.chat import ChatMessage |
| 12 | + |
| 13 | + |
| 14 | +class ChatHFGemma: |
| 15 | + """ |
| 16 | + Model wrapper for loading and using a HuggingFace causal language model with HF's own libraries |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self, |
| 21 | + model_id: str = "google/gemma-3-12b-it", |
| 22 | + cache_dir: Optional[Path] = None, |
| 23 | + sampling_params: Optional[dict] = None, |
| 24 | + penalty_params: Optional[dict] = None, |
| 25 | + max_memory: Optional[dict] = {0: "48GB", 1: "48GB"} # specify the amount of GPUs and their vrams - Gemma needs this to be able to use 2 gpus (it is too slow on a single) |
| 26 | + ): |
| 27 | + self.model_id = model_id |
| 28 | + self.cache_dir = cache_dir |
| 29 | + self.processor = None # multi-modal model does not have a tokenizer, but a processor |
| 30 | + self.model = None |
| 31 | + self.sampling_params = sampling_params |
| 32 | + self.penalty_params = penalty_params |
| 33 | + self.max_memory = max_memory |
| 34 | + |
| 35 | + def load(self) -> None: |
| 36 | + """ |
| 37 | + Lazy-loading (loads model and tokenizer if not already loaded) |
| 38 | + """ |
| 39 | + if self.processor is None: |
| 40 | + self.processor = AutoProcessor.from_pretrained( |
| 41 | + self.model_id, cache_dir=self.cache_dir, use_fast=True |
| 42 | + ) |
| 43 | + |
| 44 | + if self.model is None: |
| 45 | + try: |
| 46 | + self.model = Gemma3ForConditionalGeneration.from_pretrained( |
| 47 | + self.model_id, device_map="auto", cache_dir=self.cache_dir, |
| 48 | + max_memory=self.max_memory |
| 49 | + ).eval() |
| 50 | + except Exception as e: |
| 51 | + print(f"Failed to load model with max_memory={self.max_memory}. Error: {e}") |
| 52 | + print("Retrying without max_memory...") |
| 53 | + try: |
| 54 | + self.model = Gemma3ForConditionalGeneration.from_pretrained( |
| 55 | + self.model_id, device_map="auto", cache_dir=self.cache_dir |
| 56 | + ).eval() |
| 57 | + except Exception as e: |
| 58 | + print(f"Model loading failed even without max_memory. Error: {e}") |
| 59 | + raise |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + def format_params(self): |
| 64 | + if self.sampling_params: |
| 65 | + # normalise "temp" to "temperature" (ensures you can pass temp to the model as this is how MLX/HF defines it) |
| 66 | + if "temp" in self.sampling_params: |
| 67 | + self.sampling_params["temperature"] = self.sampling_params.pop("temp") |
| 68 | + |
| 69 | + kwargs = self.sampling_params |
| 70 | + else: |
| 71 | + kwargs = {} |
| 72 | + |
| 73 | + if self.penalty_params: |
| 74 | + kwargs.update(self.penalty_params) |
| 75 | + |
| 76 | + return kwargs |
| 77 | + |
| 78 | + def format_chat_for_gemma(self, chat: list[ChatMessage]) -> list[dict]: |
| 79 | + formatted_chat = [] |
| 80 | + |
| 81 | + for msg in chat.messages: |
| 82 | + formatted_chat.append({ |
| 83 | + "role": msg.role, |
| 84 | + "content": [{"type": "text", "text": msg.content}] |
| 85 | + }) |
| 86 | + |
| 87 | + return formatted_chat |
| 88 | + |
| 89 | + def generate(self, chat: list[ChatMessage], max_new_tokens: int = 3000): |
| 90 | + kwargs = self.format_params() |
| 91 | + |
| 92 | + if len(kwargs) > 0: |
| 93 | + do_sample = True |
| 94 | + else: |
| 95 | + do_sample = False |
| 96 | + print( |
| 97 | + "[INFO:] No sampling parameters nor penalty parameters were passed. Setting do_sample to 'False'" |
| 98 | + ) |
| 99 | + |
| 100 | + self.processor.use_default_system_prompt = False # ensure no system prompt is there |
| 101 | + |
| 102 | + formatted_chat = self.format_chat_for_gemma(chat) |
| 103 | + |
| 104 | + model_inputs = self.processor.apply_chat_template( |
| 105 | + formatted_chat, |
| 106 | + tokenize=True, |
| 107 | + return_dict=True, |
| 108 | + add_generation_prompt=True, |
| 109 | + return_tensors = "pt", |
| 110 | + # params to fix flash attn error: https://github.com/google-deepmind/gemma/issues/169 |
| 111 | + padding="longest", |
| 112 | + pad_to_multiple_of=8, |
| 113 | + ).to(self.model.device, dtype=torch.bfloat16) |
| 114 | + |
| 115 | + # fix flash attn error: https://github.com/google-deepmind/gemma/issues/169 |
| 116 | + self.processor.tokenizer.padding_side = "left" |
| 117 | + |
| 118 | + input_len = model_inputs["input_ids"].shape[-1] |
| 119 | + |
| 120 | + with torch.inference_mode(): |
| 121 | + output = self.model.generate( |
| 122 | + **model_inputs, |
| 123 | + |
| 124 | + max_new_tokens=max_new_tokens, |
| 125 | + do_sample=do_sample, |
| 126 | + **kwargs, |
| 127 | + ) |
| 128 | + |
| 129 | + # chat (decoded output) |
| 130 | + response = self.processor.decode(output[0][input_len:], skip_special_tokens=True) |
| 131 | + |
| 132 | + chat_message = ChatMessage(role="assistant", content=response) |
| 133 | + |
| 134 | + return chat_message |
0 commit comments