mllm-token-visualiser 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,660 @@
1
+ Metadata-Version: 2.4
2
+ Name: mllm-token-visualiser
3
+ Version: 0.7.0
4
+ Summary: Token analysis and visualisation for multimodal language models
5
+ Keywords: multimodal,llm,vlm,tokens,tokenizer,kv-cache,transformers,visualization
6
+ Author: Rafkat Galeev
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE.md
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Dist: av>=18.0.0
18
+ Requires-Dist: librosa>=0.11.0
19
+ Requires-Dist: pillow>=10.0
20
+ Requires-Dist: pyyaml>=6.0
21
+ Requires-Dist: qwen-vl-utils>=0.0.14,<0.1
22
+ Requires-Dist: rich>=13.0
23
+ Requires-Dist: torch>=2.13
24
+ Requires-Dist: torchaudio>=2.11.0
25
+ Requires-Dist: torchcodec>=0.16.0
26
+ Requires-Dist: torchvision>=0.28.0
27
+ Requires-Dist: transformers>=5.2,<6
28
+ Requires-Dist: typer>=0.12
29
+ Requires-Dist: numba>=0.59 ; extra == 'omni'
30
+ Requires-Dist: qwen-omni-utils>=0.0.9,<0.1 ; extra == 'omni'
31
+ Requires-Python: >=3.11, <3.15
32
+ Project-URL: Homepage, https://github.com/Rafkat/mllm-token-visualiser
33
+ Project-URL: Repository, https://github.com/Rafkat/mllm-token-visualiser
34
+ Project-URL: Issues, https://github.com/Rafkat/mllm-token-visualiser/issues
35
+ Project-URL: Changelog, https://github.com/Rafkat/mllm-token-visualiser/blob/main/CHANGELOG.md
36
+ Provides-Extra: omni
37
+ Description-Content-Type: text/markdown
38
+
39
+ # MLLM Token Visualiser
40
+
41
+ > Measure how text, images, video, and audio expand into model context—and estimate their memory cost before inference.
42
+
43
+ `mllm-token-visualiser` is a Python library for analysing tokenised multimodal inputs without loading complete model weights. It exposes one typed, model-independent API while keeping processor-specific behaviour inside adapters.
44
+
45
+ The library distinguishes user text, modality positions, chat-template overhead, and padding instead of treating every special token as removable noise.
46
+
47
+ ## Features
48
+
49
+ - Counts total, text, image, video, audio, and template tokens.
50
+ - Uses each model family's processor and chat template.
51
+ - Preserves interleaved multimodal content order.
52
+ - Excludes padding through the attention mask.
53
+ - Estimates `input_ids` memory and decoder KV-cache memory.
54
+ - Loads processor/configuration metadata rather than full model weights.
55
+ - Provides an adapter interface for adding further model families.
56
+
57
+ ## Supported models
58
+
59
+ | Model family | Text | Image | Video | Audio | Status |
60
+ |---|:---:|:---:|:---:|:---:|---|
61
+ | Qwen3-VL | ✅ | ✅ | ✅ | — | Implemented |
62
+ | Qwen3-Omni | ✅ | ✅ | ✅ | ✅ | Implemented |
63
+ | MiniCPM-o 4.5 | ✅ | ✅ | ✅ | ✅ | Implemented |
64
+ | Gemma 4 | ✅ | ✅ | Checkpoint-dependent | Checkpoint-dependent | Implemented |
65
+ | NVIDIA Nemotron 3 Nano Omni FP8 | ✅ | ✅ | ✅ | ✅ | Implemented |
66
+
67
+ Gemma 4 modality support depends on the selected checkpoint and its processor. The adapter can account for image, video, and audio placeholders when the checkpoint supports them. Audio support is read from `config.audio_config`, so local paths and renamed fine-tunes work: it is set for E2B, E4B, and 12B, and null for 26B-A4B and 31B. Only a config without that attribute falls back to the model ID, with a warning. The 12B checkpoints use `model_type` `gemma4_unified`, which is not yet registered or tested, so they are matched by model ID only.
68
+
69
+ MiniCPM-o 4.5 video frames are sampled the way `minicpmo-utils` 1.0.6 (`get_video_frame_audio_segments`, used by the model card) does it: one frame per started second (`ceil(duration)` frames), or 64 uniformly spaced frames for videos longer than 64 seconds. Each frame is one image with `max_slice_nums=1`, and `use_image_id=False` when the conversation contains video. Frames are decoded with PyAV, so this path does not need the `ffmpeg` executable. The `stack_frames` high-refresh mode and the `MAX_NUM_FRAMES` environment override are not modelled.
70
+
71
+ The Nemotron adapter has been checked against the processor of
72
+ `nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-FP8` (revision `0acd4b1c`).
73
+ Other precision variants may use different revisions of the remote processor
74
+ and have not yet been validated.
75
+ Nemotron 3 Nano Omni currently supports one video per request. Video files are sampled with PyAV before being passed to the model processor.
76
+
77
+ This project is still pre-`1.0`; its public API and report schema may evolve.
78
+
79
+ ## What it reports
80
+
81
+ | Metric | Meaning |
82
+ |---|---|
83
+ | `total_tokens` | All active input positions, excluding padding |
84
+ | `text_tokens` | Tokens produced by user-provided text only |
85
+ | `image_tokens` | Image positions inserted into model context |
86
+ | `video_tokens` | Video positions inserted into model context |
87
+ | `audio_tokens` | Audio positions inserted into model context |
88
+ | `template_tokens` | Roles, separators, generation prompt, and other template overhead |
89
+ | `token_id_bytes` | Memory occupied by the `input_ids` tensor |
90
+ | `kv_cache_bytes` | Estimated KV-cache memory for the analysed input |
91
+ | `kv_cache_bytes_per_token` | Estimated decoder KV-cache cost per active context position |
92
+ | `segments` | Per-content token counts with message index, content index, role, and modality |
93
+ | `spans` | The whole active sequence as contiguous runs: `text`, `image`, `video`, `audio`, or `template`, with the source item and decoded text |
94
+ | `media` | One entry per image/video/audio: tokens, interior overhead, placeholder groups, source-file metadata, and processor details |
95
+ | `metadata` | Library/Transformers versions, adapter, processor class, generation-prompt flag, and KV-cache dimensions |
96
+ | `assumptions` | The accounting and estimation assumptions that apply to this report |
97
+ | `warnings` | Problems detected during analysis, for example a span that could not be aligned |
98
+
99
+ KV-cache values are architectural estimates. They exclude model weights, encoder activations, temporary attention buffers, framework overhead, and allocator fragmentation.
100
+
101
+ ## Detailed report
102
+
103
+ ### Token spans
104
+
105
+ `report.spans` maps every active position to its origin, in sequence order. Spans always cover the whole active sequence exactly once:
106
+
107
+ ```python
108
+ for span in report.spans:
109
+ print(span.start, span.end, span.kind, span.content_index, repr(span.text))
110
+ ```
111
+
112
+ ```text
113
+ 0 3 template None '<|im_start|>system\n'
114
+ 3 9 text 0 'You are a helpful assistant.'
115
+ ...
116
+ 17 18 template None '<|vision_start|>'
117
+ 18 210 image 1 None
118
+ 210 211 template None '<|vision_end|>'
119
+ ```
120
+
121
+ - Media spans come from the processor's placeholder positions and are exact. One item can produce several spans, for example one per video frame group.
122
+ - Template positions between the first and last placeholder of one media item, such as frame timestamps, are attributed to that item (`message_index`/`content_index` set, `kind == "template"`). The total appears as `MediaDetail.overhead_tokens`.
123
+ - Each `Text` item is located in conversation order. `exact` is `False` when its isolated tokenization does not appear verbatim because the tokenizer merged it with neighbouring template characters (for example `":"` + newline). The item is then located by its characters and the span includes the merged token.
124
+ - If spans cannot be aligned, the report still contains all counts and explains the problem in `warnings`.
125
+
126
+ ### Media details
127
+
128
+ ```python
129
+ for item in report.media:
130
+ print(item.modality, item.tokens, item.overhead_tokens, item.properties)
131
+ ```
132
+
133
+ Measured with `Qwen/Qwen3-VL-8B-Instruct` and Transformers 5.14.1 on `examples/assets/video_sample.mp4` (1024×432, 25.1 s, 23.976 fps):
134
+
135
+ ```text
136
+ video 11200 207 {'duration_seconds': 25.108, 'grid_thw': [25, 28, 64], 'frames_sampled': 50,
137
+ 'tokens_per_frame_group': 448, 'tokens_per_second': 446.07, ...}
138
+ ```
139
+
140
+ Source properties (`width`, `height`, `duration_seconds`, `source_fps`, `sample_rate`) are read from file headers only. Processor properties depend on the model family: patch grids for Qwen, pooled patches for Gemma 4, slices and sampled frames for MiniCPM-o, and tiles and sampled frames for Nemotron.
141
+
142
+ ### Terminal view
143
+
144
+ ```python
145
+ report.show() # summary, composition, items, token map, warnings, assumptions
146
+ report.show(show_template=True) # also list decoded chat-template spans
147
+ report.show(width=80, map_rows=4) # bar/map width in cells, map height in rows
148
+ ```
149
+
150
+ Abridged output (bar shortened, one item row shown) for `Qwen/Qwen3-VL-8B-Instruct` with `examples/detailed_report.py`:
151
+
152
+ ```text
153
+ Total tokens 11,639
154
+ KV cache (estimate) 1.60 GiB (144.00 KiB per token, bfloat16)
155
+
156
+ Composition
157
+ █▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒··
158
+ Kind Tokens Share KV cache
159
+ ██ text 15 0.1% 2.11 MiB
160
+ ▓▓ image 192 1.6% 27.00 MiB
161
+ ▒▒ video 11,200 96.2% 1.54 GiB
162
+ ░░ audio 0 0.0% 0 B
163
+ ·· template 232 2.0% 32.62 MiB
164
+
165
+ Input items
166
+ Msg Role Item Tokens Share Details
167
+ 1 user ▒▒ video 11,200 96.2% 1024×432 → 1024×448, 25.108 s, 50 frames,
168
+ grid 25×28×64, 446.07 tok/s, 224 tok/frame,
169
+ +207 overhead
170
+ ```
171
+
172
+ Each kind has its own colour and glyph (`█ text`, `▓ image`, `▒ video`, `░ audio`, `· template`), so the view also works without colour, for example with `NO_COLOR=1` or in logs. In the token map one cell stands for several positions and shows their majority kind; use `report.spans` or the template view for exact positions. `mllm_tokens.display.render_report()` returns the `rich` renderable for embedding in other output.
173
+
174
+ ### HTML report
175
+
176
+ ```python
177
+ report.save_html("report.html") # one self-contained file, no external assets
178
+ report.save_html("report.html", embed_media=True) # also embed image thumbnails
179
+ html = report.to_html(title="Qwen3-VL, 25 s clip")
180
+ ```
181
+
182
+ The page shows the total, the KV-cache estimate, a composition bar, a token map with one lane per kind (hover, or focus it and use the arrow keys, to see each span's positions, owner, and decoded text), the input items with their media properties, the decoded template spans, and the warnings, assumptions, and run details. Every chart has a table view, the page follows the system light or dark theme (with a toggle; `?theme=dark` also works), and "Download JSON" saves `report.to_json()`.
183
+
184
+ By default the file contains no media: only counts, file names, header metadata, and decoded text and template spans. `embed_media=True` adds 240 px JPEG thumbnails of image inputs; keep it off for reports you share.
185
+
186
+ ### Breakdowns and export
187
+
188
+ ```python
189
+ report.tokens_by_kind() # {'text': ..., 'image': ..., 'template': ...}
190
+ report.token_shares() # fraction of total_tokens per kind
191
+ report.kv_cache_bytes_by_kind() # estimated KV-cache bytes per kind
192
+
193
+ report.to_json() # versioned JSON with derived breakdowns and field accuracy
194
+ report.segments_csv() # one row per content item
195
+ report.spans_csv() # one row per span
196
+ ```
197
+
198
+ `to_json()` includes `schema_version` and a `field_accuracy` map that labels each count as processor-exact, tokenizer-based, derived, or estimated.
199
+
200
+ ## Why special-token filtering is not enough
201
+
202
+ An MLLM context contains more than ordinary text tokens:
203
+
204
+ ```text
205
+ total context
206
+ ├── user text
207
+ ├── image / video / audio positions
208
+ └── template overhead
209
+ ├── role markers
210
+ ├── separators and newlines
211
+ └── optional generation prompt
212
+ ```
213
+
214
+ Removing every special token would also remove genuine modality positions, while template fragments such as role text or newlines may remain. The library instead combines the original structured input with the final processor output.
215
+
216
+ ## Requirements
217
+
218
+ - Python `>=3.11,<3.15`
219
+ - PyTorch 2.13 or later
220
+ - Transformers `>=5.2,<6`
221
+ - PyAV 18 or later for Nemotron and MiniCPM-o video decoding
222
+ - FFmpeg shared libraries for processor paths that decode audio or video through TorchCodec
223
+
224
+ TorchAudio 2.11 supports PyTorch 2.11 and later through PyTorch's stable ABI. TorchCodec 0.16 adds support for FFmpeg 9.
225
+
226
+ ## Installation
227
+
228
+ Install from PyPI:
229
+
230
+ ```bash
231
+ pip install mllm-token-visualiser
232
+ # or, in a uv project
233
+ uv add mllm-token-visualiser
234
+ ```
235
+
236
+ The package is imported as `mllm_tokens` and installs the `mllm-tokens` command. For Qwen3-Omni, add the optional utilities with `pip install "mllm-token-visualiser[omni]"`.
237
+
238
+ PyTorch is a dependency. If you need a specific CUDA or CPU build, install PyTorch first by following the [PyTorch instructions](https://pytorch.org/get-started/locally/).
239
+
240
+ ### Development installation
241
+
242
+ The project uses [uv](https://docs.astral.sh/uv/) for dependency management and packaging.
243
+
244
+ ```bash
245
+ git clone https://github.com/Rafkat/mllm-token-visualiser.git
246
+ cd mllm-token-visualiser
247
+ uv sync
248
+ ```
249
+
250
+ Install optional Qwen3-Omni utilities with:
251
+
252
+ ```bash
253
+ uv sync --extra omni
254
+ ```
255
+
256
+ ### Install a built wheel
257
+
258
+ Build the distribution:
259
+
260
+ ```bash
261
+ uv build
262
+ ```
263
+
264
+ Install version 0.7.0 into another uv project:
265
+
266
+ ```bash
267
+ uv add ../mllm-token-visualiser/dist/mllm_token_visualiser-0.7.0-py3-none-any.whl
268
+ ```
269
+
270
+ ### FFmpeg and video support
271
+
272
+ TorchCodec requires an FFmpeg installation that exposes shared libraries. On macOS with Homebrew:
273
+
274
+ ```bash
275
+ brew install ffmpeg
276
+ ffmpeg -version
277
+ ```
278
+
279
+ Recent TorchCodec releases support FFmpeg major versions 4 through 9. The FFmpeg executable being available in `PATH` does not by itself guarantee that the operating-system dynamic loader can locate `libavutil`, `libavcodec`, and the other shared libraries.
280
+
281
+ For Qwen video processing, TorchCodec can be selected explicitly:
282
+
283
+ ```bash
284
+ FORCE_QWENVL_VIDEO_READER=torchcodec \
285
+ uv run python examples/basic_video.py
286
+ ```
287
+
288
+ ## Quick start
289
+
290
+ ```python
291
+ from mllm_tokens import Analyzer, Image, Message, Text
292
+
293
+ analyzer = Analyzer.from_pretrained("Qwen/Qwen3-VL-8B-Instruct")
294
+
295
+ messages = [
296
+ Message.user(
297
+ Image("examples/assets/image_sample.jpg"),
298
+ Text("Describe this image."),
299
+ )
300
+ ]
301
+
302
+ report = analyzer.analyze(messages)
303
+ report.print_dict()
304
+ ```
305
+
306
+ `Analyzer.from_pretrained()` loads the processor and configuration needed for analysis, not complete model weights. Reuse an `Analyzer` across inputs to avoid repeatedly loading processor metadata.
307
+
308
+ ## Command line
309
+
310
+ Installing the package adds `mllm-tokens` (also available as `python -m mllm_tokens`). Content is given in conversation order as positional arguments: a media file path (the modality comes from its extension), `image:PATH`, `video:PATH`, `audio:PATH`, `text:TEXT`, or any other text.
311
+
312
+ ```bash
313
+ # Terminal view (add --show-template to list decoded template spans)
314
+ mllm-tokens analyze Qwen/Qwen3-VL-8B-Instruct examples/assets/image_sample.jpg "What is this?"
315
+
316
+ # Other formats: --format json|html|spans-csv|segments-csv, or inferred from -o
317
+ mllm-tokens analyze Qwen/Qwen3-VL-8B-Instruct clip.mp4 "Describe." -o report.html
318
+ mllm-tokens analyze google/gemma-4-e4b-it --system "Be brief." photo.png "Caption it." -f json
319
+
320
+ # Same input, several models (table, --format json, or --format csv)
321
+ mllm-tokens compare examples/assets/video_sample.mp4 "Describe the video." \
322
+ -m Qwen/Qwen3-VL-8B-Instruct -m google/gemma-4-e4b-it \
323
+ -m nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-FP8 --trust-remote-code
324
+ ```
325
+
326
+ Other options: `--trust-remote-code` (MiniCPM-o and Nemotron processors), `--kv-dtype`, `--no-generation-prompt`, and `--embed-media` for HTML. In `compare`, a model that fails (for example, one that does not accept the given modality) is shown as an error row and the others are still compared.
327
+
328
+ Output of the `compare` command above with the 25 s sample video (processor and config files only, transformers 5.14.1):
329
+
330
+ ```text
331
+ Tokens by kind
332
+ Model Total Text Video Template KV cache (est.) Warnings
333
+ Qwen/Qwen3-VL-8B-Instruct 11,429 4 11,200 225 1.57 GiB 0
334
+ google/gemma-4-e4b-it 2,220 4 1,920 296 182.11 MiB 0
335
+ nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-FP8 13,971 5 13,056 910 81.86 MiB ⚠ 1
336
+ ```
337
+
338
+ Nemotron's warning explains how its video placeholders are rebuilt (see the Nemotron section); of its 13,056 video tokens, 3,916 remain after Efficient Video Sampling.
339
+
340
+ ## Interleaved multimodal input
341
+
342
+ Content order is preserved:
343
+
344
+ ```python
345
+ from mllm_tokens import Analyzer, Image, Message, Text
346
+
347
+ analyzer = Analyzer.from_pretrained("Qwen/Qwen3-VL-8B-Instruct")
348
+
349
+ messages = [
350
+ Message.user(
351
+ Text("First image:"),
352
+ Image("examples/assets/first.jpg"),
353
+ Text("Second image:"),
354
+ Image("examples/assets/second.jpg"),
355
+ Text("Compare them."),
356
+ )
357
+ ]
358
+
359
+ report = analyzer.analyze(messages)
360
+ report.print_dict()
361
+ ```
362
+
363
+ Typed wrappers remove ambiguity: `"cat.jpg"` could mean text or a path, whereas `Text(...)` and `Image(...)` state the intended modality.
364
+
365
+ ## Video example
366
+
367
+ ```python
368
+ from mllm_tokens import Analyzer, Message, Text, Video
369
+
370
+ analyzer = Analyzer.from_pretrained("Qwen/Qwen3-VL-8B-Instruct")
371
+
372
+ messages = [
373
+ Message.user(
374
+ Video("examples/assets/video_sample.mp4"),
375
+ Text("What happens in this video?"),
376
+ )
377
+ ]
378
+
379
+ report = analyzer.analyze(messages)
380
+ report.print_dict()
381
+ ```
382
+
383
+ Run the repository example with:
384
+
385
+ ```bash
386
+ uv run python examples/basic_video.py
387
+ ```
388
+
389
+ ## Qwen3-Omni example
390
+
391
+ ```python
392
+ from mllm_tokens import Analyzer, Audio, Image, Message, Text
393
+
394
+ analyzer = Analyzer.from_pretrained(
395
+ "Qwen/Qwen3-Omni-30B-A3B-Instruct",
396
+ )
397
+
398
+ messages = [
399
+ Message.user(
400
+ Text("Listen to the recording and inspect the image."),
401
+ Audio("examples/assets/audio_sample.wav"),
402
+ Image("examples/assets/image_sample.jpg"),
403
+ Text("Describe the situation and relevant sounds."),
404
+ )
405
+ ]
406
+
407
+ report = analyzer.analyze(messages)
408
+ report.print_dict()
409
+ ```
410
+
411
+ Qwen3-Omni videos are sampled at 2 fps, as in the model card's `qwen-omni-utils` pipeline. The processor's own default keeps every source frame (about 12× more tokens for a 24 fps clip, enough to exceed the context window); the per-frame pixel limits of `qwen-omni-utils` are not replicated.
412
+
413
+ The Qwen3-Omni input KV-cache estimate uses the Thinker text decoder because it maintains the autoregressive multimodal context. Talker-generation memory is separate and is not included in this input-context estimate.
414
+
415
+ ## Gemma 4 example
416
+
417
+ ```python
418
+ from mllm_tokens import Analyzer, Image, Message, Text
419
+
420
+ analyzer = Analyzer.from_pretrained("google/gemma-4-e4b-it")
421
+
422
+ messages = [
423
+ Message.user(
424
+ Image("examples/assets/image_sample.jpg"),
425
+ Text("Describe the image and identify its most important details."),
426
+ )
427
+ ]
428
+
429
+ report = analyzer.analyze(messages)
430
+ report.print_dict()
431
+ ```
432
+
433
+ The Gemma 4 adapter applies the checkpoint's native chat template, counts supported modality placeholders in the active sequence, and derives KV-cache dimensions from `config.text_config`.
434
+
435
+ ## NVIDIA Nemotron example
436
+
437
+ ```python
438
+ from mllm_tokens import Analyzer, Audio, Image, Message, Text, Video
439
+
440
+ analyzer = Analyzer.from_pretrained(
441
+ "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-FP8", trust_remote_code=True
442
+ )
443
+
444
+ messages = [
445
+ Message.user(
446
+ Image("examples/assets/image_sample.jpg"),
447
+ Audio("examples/assets/audio_sample.wav"),
448
+ Video("examples/assets/video_sample.mp4"),
449
+ Text("Describe the image, audio, and video."),
450
+ )
451
+ ]
452
+
453
+ report = analyzer.analyze(messages)
454
+ report.print_dict()
455
+ ```
456
+ The Nemotron adapter uses PyAV to sample video frames at 2 fps (up to 256 frames) and passes them to the model processor with the sampling rate, so frame timestamps in the prompt are correct. The current processor integration supports one video per request.
457
+
458
+ Video placeholders need care with this checkpoint. Its tokenizer has no single `<video>` token, so the processor's output splits every frame placeholder into text fragments that the model never matches: the model scatters video embeddings into positions equal to `config.video_context_token_id`. The adapter rebuilds each frame as `num_image_token` (256) positions of that ID, which is the layout the model expects, and reports this as a warning. `video_tokens` is therefore 256 per sampled frame.
459
+
460
+ The model also applies Efficient Video Sampling (EVS) after the vision encoder and drops a fixed share of video tokens (`config.video_pruning_rate`, 0.7 for this checkpoint). The retained count is deterministic and is reported as `media[i].properties["tokens_after_evs"]`; `total_tokens` and the KV-cache estimate count video tokens before EVS.
461
+ NemotronH combines Mamba-2, attention, and MoE layers. Its KV-cache estimate includes only layers marked as attention layers in hybrid_override_pattern; recurrent Mamba state is not included.
462
+
463
+
464
+ ## Text-token accounting
465
+
466
+ Text tokens are calculated from the original `Text` objects with model special tokens disabled. They are not inferred by subtracting every special token from the final template sequence. This keeps role markers, separators, and generation prompts in `template_tokens` rather than misclassifying them as user text.
467
+
468
+ For batched tensors, modality matching is combined with `attention_mask` so padding positions do not contribute to counts.
469
+
470
+ ## KV-cache estimation
471
+
472
+ For a conventional decoder transformer, the approximate cache cost per active context position is:
473
+
474
+ ```text
475
+ 2 × num_hidden_layers × num_key_value_heads × head_dim × dtype_bytes
476
+ ```
477
+
478
+ The factor `2` represents keys and values. Query heads are not used because queries are not retained in the KV cache.
479
+
480
+ ## Segments
481
+
482
+ ```
483
+ report = analyzer.analyze(messages)
484
+
485
+ for segment in report.segments:
486
+ print(
487
+ segment.message_index,
488
+ segment.content_index,
489
+ segment.role,
490
+ segment.modality,
491
+ segment.tokens,
492
+ )
493
+ ```
494
+
495
+ ## Public API
496
+
497
+ ```python
498
+ from mllm_tokens import (
499
+ Analyzer,
500
+ Audio,
501
+ Image,
502
+ Message,
503
+ Text,
504
+ Video,
505
+ analyze,
506
+ MediaDetail,
507
+ TokenReport,
508
+ TokenSegment,
509
+ TokenSpan,
510
+ )
511
+ ```
512
+
513
+ The distribution and import names intentionally differ:
514
+
515
+ ```text
516
+ distribution: mllm-token-visualiser
517
+ import: mllm_tokens
518
+ ```
519
+
520
+ ## Architecture
521
+
522
+ ```text
523
+ src/mllm_tokens/
524
+ ├── __init__.py
525
+ ├── __main__.py
526
+ ├── analyzer.py
527
+ ├── cli.py
528
+ ├── display.py
529
+ ├── html_report.py
530
+ ├── inputs.py
531
+ ├── media.py
532
+ ├── registry.py
533
+ ├── report.py
534
+ ├── spans.py
535
+ ├── templates/
536
+ │ └── report.html
537
+ └── adapters/
538
+ ├── base.py
539
+ ├── dtype_bytes.py
540
+ ├── gemma4.py
541
+ ├── minicpmo45.py
542
+ ├── nemotron.py
543
+ ├── qwen_adapter.py
544
+ ├── qwen3omni.py
545
+ └── qwen3vl.py
546
+ ```
547
+
548
+ Each model family owns processor conversion and token accounting inside an adapter. Adapters report placeholder positions and processor details; `spans.py` (model-independent position mapping) and `media.py` (file-header probing) turn them into the detailed report. `Analyzer` depends on the common `ModelAdapter` contract, so model support remains additive.
549
+
550
+ `Analyzer.from_pretrained()` selects the adapter from the checkpoint's `config.model_type`, before the processor is loaded, so local paths and renamed fine-tunes resolve correctly and unsupported models fail early. Checkpoints whose `model_type` is not recognised fall back to matching the model ID. `minicpmo` is shared by several MiniCPM-o generations, so it additionally requires `config.version == "4.5"`.
551
+
552
+ | Adapter | `config.model_type` |
553
+ |---|---|
554
+ | Qwen3-VL | `qwen3_vl`, `qwen3_vl_moe` |
555
+ | Qwen3-Omni | `qwen3_omni_moe` |
556
+ | MiniCPM-o 4.5 | `minicpmo` (version `4.5`) |
557
+ | Gemma 4 | `gemma4` |
558
+ | Nemotron 3 Nano Omni | `NemotronH_Nano_Omni_Reasoning_V3` |
559
+
560
+ ## Repository layout
561
+
562
+ ```text
563
+ mllm-token-visualiser/
564
+ ├── pyproject.toml
565
+ ├── README.md
566
+ ├── src/mllm_tokens/
567
+ ├── tests/
568
+ └── examples/
569
+ ├── assets/
570
+ ├── basic_audio.py
571
+ ├── basic_image.py
572
+ ├── basic_video.py
573
+ ├── detailed_report.py
574
+ └── interleaved.py
575
+ ```
576
+
577
+ ## Development
578
+
579
+ ```bash
580
+ uv sync
581
+ uv run ruff format --check .
582
+ uv run ruff check .
583
+ uv run pytest
584
+ uv build
585
+ ```
586
+
587
+ Opt-in checks against real Hugging Face processors download processor and configuration files only (no weights):
588
+
589
+ ```bash
590
+ MLLM_TOKENS_INTEGRATION=1 uv run pytest tests/integration
591
+ # MiniCPM-o and Nemotron processors execute remote code:
592
+ MLLM_TOKENS_INTEGRATION=1 MLLM_TOKENS_TRUST_REMOTE_CODE=1 uv run pytest tests/integration
593
+ ```
594
+
595
+ `tests/fixtures/spans/` holds span-builder inputs recorded from real processors with `scripts/record_span_fixtures.py`; `tests/test_span_fixtures.py` replays them offline.
596
+
597
+ Verify the public import:
598
+
599
+ ```bash
600
+ uv run python -c "import mllm_tokens; print(mllm_tokens.__file__)"
601
+ ```
602
+
603
+ ## Testing the wheel externally
604
+
605
+ Create a separate project so the test cannot accidentally import the source tree:
606
+
607
+ ```bash
608
+ mkdir test_project
609
+ cd test_project
610
+ uv init
611
+ uv python pin 3.12
612
+ uv add ../mllm-token-visualiser/dist/mllm_token_visualiser-0.7.0-py3-none-any.whl
613
+ uv run python -c "import mllm_tokens; print(mllm_tokens.__file__)"
614
+ ```
615
+
616
+ The printed path should be inside `test_project/.venv/.../site-packages/`.
617
+
618
+ ## Roadmap
619
+
620
+ - [x] Typed text, image, video, and audio inputs
621
+ - [x] Ordered interleaved message representation
622
+ - [x] Adapter registry and common adapter contract
623
+ - [x] Structured token and memory report
624
+ - [x] Qwen3-VL adapter
625
+ - [x] Qwen3-Omni adapter and Thinker KV-cache estimate
626
+ - [x] MiniCPM-o 4.5 adapter
627
+ - [x] Gemma 4 adapter
628
+ - [x] Add NVIDIA Nemotron support after selecting and validating the target multimodal checkpoint family
629
+ - [ ] Add a separate streaming-analysis track for incremental MLLM inputs and outputs
630
+ - [ ] Report token growth per streaming chunk or turn
631
+ - [ ] Estimate KV-cache growth and retained context during streaming inference
632
+ - [ ] Separate input-context, generated-text, and generated-audio accounting where the model exposes distinct generation pipelines
633
+ - [x] Add adapter-level unit and integration fixtures
634
+ - [x] Add a CLI built on the library API
635
+ - [x] Add richer terminal visualisation and export formats
636
+ - [ ] Add further MLLM adapters
637
+ - [ ] Stabilise the public API and publish to PyPI
638
+
639
+ ## Design principles
640
+
641
+ - **Processor-aware:** count the sequence the model processor creates.
642
+ - **Content-aware:** distinguish user content from chat-template overhead.
643
+ - **Model-extensible:** isolate family-specific behaviour behind adapters.
644
+ - **Lightweight:** analyse tokenisation without loading full model weights when possible.
645
+ - **Transparent:** expose assumptions behind every memory estimate.
646
+ - **Library first:** keep the core usable from Python; a CLI can reuse it.
647
+
648
+ ## Contributing
649
+
650
+ Issues and pull requests are welcome, especially for processor compatibility, new adapters, reference token-count fixtures, media-decoding portability, and more accurate memory modelling.
651
+
652
+ When adding an adapter, include processor-level tests and document the model checkpoints and Transformers versions used for validation.
653
+
654
+ ## License
655
+
656
+ Licensed under the [Apache License 2.0](https://github.com/Rafkat/mllm-token-visualiser/blob/main/LICENSE.md). See the [changelog](https://github.com/Rafkat/mllm-token-visualiser/blob/main/CHANGELOG.md) for release notes.
657
+
658
+ ---
659
+
660
+ Built to make multimodal context measurable before it becomes an out-of-memory error.
@@ -0,0 +1,26 @@
1
+ mllm_tokens/__init__.py,sha256=npPJj_A9GTQ06RC_amOsiYFYDHwwTO-YrXONiGpZDzM,385
2
+ mllm_tokens/__main__.py,sha256=Jxmt-H84qciuYY2WcaDxbcFTcWWtDXWaNVbZorNvTw0,41
3
+ mllm_tokens/adapters/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ mllm_tokens/adapters/base.py,sha256=sUeFdtN6pfaF-cL6Jfe4KcF-lMIlxyJnBZSqFzNWRMY,18136
5
+ mllm_tokens/adapters/dtype_bytes.py,sha256=1B8k58Yawpg1qWcalwY5bcCDj3tWonE94_JV0rYdWHA,90
6
+ mllm_tokens/adapters/gemma4.py,sha256=L31s7UPaXjlLYxw5tjnYu0xp-ixHFWs8PYiD7KIHj-U,6719
7
+ mllm_tokens/adapters/minicpmo45.py,sha256=rnIjSmzCGw8yhv7QhGd56HMbkcNRGeU5qji3s_lM0W0,11524
8
+ mllm_tokens/adapters/nemotron.py,sha256=y3uqGp-ZCvHDjlA-K8TB423dRWePp_GrX3BTdmBvIQw,19865
9
+ mllm_tokens/adapters/qwen3omni.py,sha256=abMnzPCYAzmeGkw_smXGaXMuh3s7JCBiWaPjqDbxYak,3289
10
+ mllm_tokens/adapters/qwen3vl.py,sha256=xEifYXMRLXx-M2eWE4C9FlYvS9naP55pUFVufMNL4kk,1558
11
+ mllm_tokens/adapters/qwen_adapter.py,sha256=qIBrKcFvNjNDhhF1lt05mUmtBs--ChvxjXlNjaOeeMI,3346
12
+ mllm_tokens/analyzer.py,sha256=wp3ANAO4CqeouwHIAt0bnWOWZJbeGWVrHweGq84Zn9g,2614
13
+ mllm_tokens/cli.py,sha256=oZ6lnBSG6zZHYueZDH-O6_GqzK5sfOlVxpXdZipt9Cc,12015
14
+ mllm_tokens/display.py,sha256=R5AceSxBz2NVk7VNUvGwHjz_dae3rvY_9QFrosyetVs,12430
15
+ mllm_tokens/html_report.py,sha256=zv8c2n_CeWkPrdoCUeSWM-cwfkc1U_Dqftu47HqKg0g,6761
16
+ mllm_tokens/inputs.py,sha256=p9hg5Vlc4wI4WmNRVfwyO4hUKgA-Napz9NujU46Jymo,1151
17
+ mllm_tokens/media.py,sha256=fydH6nXocONI_dTlqtLMyQaBw_XUrtr0b2gHXG-Sefc,2250
18
+ mllm_tokens/registry.py,sha256=5CUua7slhSZEyxI5TgJJbpB6YKGQfwJfS4b5iaQPCT8,3104
19
+ mllm_tokens/report.py,sha256=4fQ8fO8hvhGRVsOUwfhro6qgPv4irYm048wVy6OKKBU,7669
20
+ mllm_tokens/spans.py,sha256=yIxnxsKFCmkn497Fr33vZUt9Wc3CyTM9tUCOwh53mAQ,8675
21
+ mllm_tokens/templates/report.html,sha256=BVfK_8CyuzQPj3spkHesk4hkIZEc8M9tv0V1nf9GSQg,27103
22
+ mllm_token_visualiser-0.7.0.dist-info/licenses/LICENSE.md,sha256=Yt2-U9EDE6zG64Tw-PWKt9_tuv5SjsKJjsj3cO7YYkY,11411
23
+ mllm_token_visualiser-0.7.0.dist-info/WHEEL,sha256=4OL6Foqnnp3xRY5wMkjgc25_i5YJC6dKsC6LPcjqEoU,80
24
+ mllm_token_visualiser-0.7.0.dist-info/entry_points.txt,sha256=ycRHUQlGcUbE7AmQbXrTWFSBe4tm_Ob61TpwottmMhQ,54
25
+ mllm_token_visualiser-0.7.0.dist-info/METADATA,sha256=GB_k1inVHuz08VqaivBKdZxrD2Gk4PMZTcVeEQxAE3g,27663
26
+ mllm_token_visualiser-0.7.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.12.5
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any