|
| 1 | +import llama_cpp |
| 2 | +from llama_cpp import LLAMA_TOKEN_NULL |
| 3 | + |
| 4 | +import llama_cpp.mtmd_cpp as mtmd |
| 5 | +from .mtmd_cpp import mtmd_input_chunk_type, mtmd_free |
| 6 | +from ._internals import LlamaContext, LlamaBatch |
| 7 | + |
| 8 | +import ctypes |
| 9 | +from typing import Union, List |
| 10 | + |
| 11 | +class TextChunk: |
| 12 | + def __init__(self, tokens: List[int]): |
| 13 | + self.tokens = tokens |
| 14 | + self.n_tokens = len(tokens) |
| 15 | + |
| 16 | +class MediaChunk: |
| 17 | + def __init__(self, chunk_ptr: ctypes.c_void_p): |
| 18 | + self.chunk_ptr = mtmd.mtmd_input_chunk_copy(chunk_ptr) |
| 19 | + self.n_tokens = mtmd.mtmd_input_chunk_get_n_tokens(self.chunk_ptr) |
| 20 | + |
| 21 | + def __del__(self): |
| 22 | + if self.chunk_ptr: |
| 23 | + mtmd.mtmd_input_chunk_free(self.chunk_ptr) |
| 24 | + |
| 25 | +class MultimodalTokenList: |
| 26 | + def __init__(self): |
| 27 | + self.chunks: List[Union[TextChunk, MediaChunk]] = [] |
| 28 | + self.total_tokens = 0 |
| 29 | + |
| 30 | + def add(self, chunk_ptr: mtmd.mtmd_input_chunk_p_ctypes): |
| 31 | + chunk_type = mtmd.mtmd_input_chunk_get_type(chunk_ptr) |
| 32 | + |
| 33 | + if chunk_type in [ |
| 34 | + mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_IMAGE, |
| 35 | + mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_AUDIO |
| 36 | + ]: |
| 37 | + m_chunk = MediaChunk(chunk_ptr) |
| 38 | + self.chunks.append(m_chunk) |
| 39 | + self.total_tokens += m_chunk.n_tokens |
| 40 | + |
| 41 | + elif chunk_type == mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_TEXT: |
| 42 | + n_tokens_ref = ctypes.c_size_t() |
| 43 | + text_tokens_ptr = mtmd.mtmd_input_chunk_get_tokens_text(chunk_ptr, ctypes.byref(n_tokens_ref)) |
| 44 | + tokens = [text_tokens_ptr[j] for j in range(n_tokens_ref.value)] |
| 45 | + self.add_text(tokens) |
| 46 | + |
| 47 | + else: |
| 48 | + raise ValueError(f"Invalid chunk type {chunk_type}") |
| 49 | + |
| 50 | + def add_text(self, tokens: List[int]): |
| 51 | + if not tokens: return |
| 52 | + # combine text nodes |
| 53 | + if self.chunks and isinstance(self.chunks[-1], TextChunk): |
| 54 | + self.chunks[-1].tokens.extend(tokens) |
| 55 | + self.chunks[-1].n_tokens += len(tokens) |
| 56 | + else: |
| 57 | + self.chunks.append(TextChunk(tokens)) |
| 58 | + self.total_tokens += len(tokens) |
| 59 | + |
| 60 | + def __len__(self): |
| 61 | + return self.total_tokens |
| 62 | + |
| 63 | + |
| 64 | +class MultiModalContext: |
| 65 | + def __init__( |
| 66 | + self, |
| 67 | + ctx |
| 68 | + ): |
| 69 | + self.ctx = ctx |
| 70 | + |
| 71 | + def close(self): |
| 72 | + if self.ctx is None: |
| 73 | + return |
| 74 | + mtmd_free(self.ctx) |
| 75 | + self.ctx = None |
| 76 | + |
| 77 | + def __del__(self): |
| 78 | + self.close() |
| 79 | + |
| 80 | + |
| 81 | +# Simple FNV-1a hash implementation to match fnv_hash in C++ |
| 82 | +def fnv_hash(data: bytes) -> str: |
| 83 | + h = 0x811c9dc5 |
| 84 | + for b in data: |
| 85 | + h = (h ^ b) * 0x01000193 |
| 86 | + h &= 0xffffffff |
| 87 | + return f"{h:08x}" |
| 88 | + |
| 89 | +def mtmd_tokenize( |
| 90 | + mctx: mtmd.mtmd_context_p, |
| 91 | + prompt: str, |
| 92 | + files_data: list[bytes | str]) -> MultimodalTokenList: |
| 93 | + |
| 94 | + bitmaps = [] |
| 95 | + do_hash = False |
| 96 | + |
| 97 | + for data in files_data: |
| 98 | + |
| 99 | + bmp = None |
| 100 | + if isinstance(data, str): |
| 101 | + bmp = mtmd.mtmd_helper_bitmap_init_from_file(mctx, data.encode("utf-8")) |
| 102 | + elif isinstance(data, bytes): |
| 103 | + buf = (ctypes.c_ubyte * len(data)).from_buffer_copy(data) |
| 104 | + bmp = mtmd.mtmd_helper_bitmap_init_from_buf(mctx, buf, len(buf)) |
| 105 | + elif isinstance(data, bytearray): |
| 106 | + buf = (ctypes.c_ubyte * len(data)).from_buffer(data) |
| 107 | + bmp = mtmd.mtmd_helper_bitmap_init_from_buf(mctx, buf, len(buf)) |
| 108 | + |
| 109 | + if bmp is None: |
| 110 | + raise RuntimeError("Failed to load image or audio file") |
| 111 | + |
| 112 | + if do_hash: |
| 113 | + data_ptr = mtmd.mtmd_bitmap_get_data(bmp) |
| 114 | + data_size = mtmd.mtmd_bitmap_get_n_bytes(bmp) |
| 115 | + |
| 116 | + raw_node_data = ctypes.string_at(data_ptr, data_size) |
| 117 | + h = fnv_hash(raw_node_data) |
| 118 | + mtmd.mtmd_bitmap_set_id(bmp, h.encode('utf-8')) |
| 119 | + |
| 120 | + bitmaps.append(bmp) |
| 121 | + |
| 122 | + inp_txt = mtmd.mtmd_input_text( |
| 123 | + text=prompt.encode('utf-8'), |
| 124 | + add_special=True, |
| 125 | + parse_special=True |
| 126 | + ) |
| 127 | + |
| 128 | + chunks_ptr = mtmd.mtmd_input_chunks_init() |
| 129 | + |
| 130 | + n_bitmaps = len(bitmaps) |
| 131 | + if n_bitmaps > 0: |
| 132 | + BitmapPtr = mtmd.mtmd_bitmap_p_ctypes * n_bitmaps |
| 133 | + bitmaps_ptr = BitmapPtr(*bitmaps) |
| 134 | + else: |
| 135 | + bitmaps_ptr = None |
| 136 | + |
| 137 | + res = mtmd.mtmd_tokenize( |
| 138 | + mctx, |
| 139 | + chunks_ptr, |
| 140 | + ctypes.pointer(inp_txt), |
| 141 | + bitmaps_ptr, |
| 142 | + n_bitmaps |
| 143 | + ) |
| 144 | + |
| 145 | + # TODO Hash based cache |
| 146 | + for data in bitmaps: |
| 147 | + mtmd.mtmd_bitmap_free(bmp) |
| 148 | + |
| 149 | + if res != 0: |
| 150 | + mtmd.mtmd_input_chunks_free(chunks_ptr) |
| 151 | + raise RuntimeError(f"Tokenization failed with code {res}") |
| 152 | + |
| 153 | + st = MultimodalTokenList() |
| 154 | + |
| 155 | + n_chunks = mtmd.mtmd_input_chunks_size(chunks_ptr) |
| 156 | + for i in range(n_chunks): |
| 157 | + chunk_ptr = mtmd.mtmd_input_chunks_get(chunks_ptr, i) |
| 158 | + st.add(chunk_ptr) |
| 159 | + |
| 160 | + mtmd.mtmd_input_chunks_free(chunks_ptr) |
| 161 | + |
| 162 | + return st |
| 163 | + |
| 164 | +def mtmd_prefill( |
| 165 | + ctx: LlamaContext, |
| 166 | + mctx: mtmd.mtmd_context_p, |
| 167 | + batch: LlamaBatch, |
| 168 | + mtmd_tokens: MultimodalTokenList |
| 169 | +) -> int: |
| 170 | + n_past = 0 |
| 171 | + n_batch = ctx.n_batch() |
| 172 | + total_chunks = len(mtmd_tokens.chunks) |
| 173 | + |
| 174 | + for i, chunk in enumerate(mtmd_tokens.chunks): |
| 175 | + is_last_chunk = (i == total_chunks - 1) |
| 176 | + |
| 177 | + if isinstance(chunk, TextChunk): |
| 178 | + batch.set_batch( |
| 179 | + chunk.tokens, |
| 180 | + n_past, |
| 181 | + logits_all=False, |
| 182 | + logits_last=is_last_chunk |
| 183 | + ) |
| 184 | + ctx.decode(batch) |
| 185 | + |
| 186 | + n_past += chunk.n_tokens |
| 187 | + else: |
| 188 | + new_n_past = llama_cpp.llama_pos(0) |
| 189 | + result = mtmd.mtmd_helper_eval_chunk_single( |
| 190 | + mctx, |
| 191 | + ctx.ctx, |
| 192 | + chunk.chunk_ptr, |
| 193 | + llama_cpp.llama_pos(n_past), |
| 194 | + llama_cpp.llama_seq_id(0), |
| 195 | + n_batch, |
| 196 | + False, # logits_last |
| 197 | + ctypes.byref(new_n_past) |
| 198 | + ) |
| 199 | + if result != 0: |
| 200 | + raise RuntimeError(f"MTMD eval error: {result}") |
| 201 | + |
| 202 | + n_past = new_n_past.value |
0 commit comments