LiteRT-LM
detal65 marissaw commited on
Commit
703c1cd
·
0 Parent(s):

Duplicate from litert-community/gemma-4-E2B-it-litert-lm

Browse files

Co-authored-by: Marissa Ikonomidis <marissaw@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ gemma-4-2p3b-it.litertlm filter=lfs diff=lfs merge=lfs -text
37
+ gemma-4-E2B-it.litertlm filter=lfs diff=lfs merge=lfs -text
38
+ gemma-4-E2B-it-web.task filter=lfs diff=lfs merge=lfs -text
39
+ gemma-4-E2B-it_qualcomm_qcs8275.litertlm filter=lfs diff=lfs merge=lfs -text
40
+ gemma-4-E2B-it_qualcomm_sm8750.litertlm filter=lfs diff=lfs merge=lfs -text
41
+ gemma-4-E2B-it_intel_PTL.litertlm filter=lfs diff=lfs merge=lfs -text
42
+ gemma-4-E2B-it_intel_LNL.litertlm filter=lfs diff=lfs merge=lfs -text
43
+ gemma-4-E2B-it-web.litertlm filter=lfs diff=lfs merge=lfs -text
44
+ gemma-4-E2B-it_Google_Tensor_G5.litertlm filter=lfs diff=lfs merge=lfs -text
45
+ gemini4_2b_sizes.png filter=lfs diff=lfs merge=lfs -text
46
+ gemma-4-E2B-it-gpu.litertlm filter=lfs diff=lfs merge=lfs -text
47
+ gemma-4-E2B-it_Google_Tensor_G6.litertlm filter=lfs diff=lfs merge=lfs -text
48
+ gemma-4-E2B-it_qualcomm_sm8850.litertlm filter=lfs diff=lfs merge=lfs -text
49
+ gemma-4-E2B-it_Qualcomm_QCS8275.litertlm filter=lfs diff=lfs merge=lfs -text
50
+ gemma-4-E2B-it_NPU_Uncompiled.litertlm filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model:
4
+ - google/gemma-4-E2B-it
5
+ base_model_relation: quantized
6
+ tags:
7
+ - litert-lm
8
+ ---
9
+
10
+ # litert-community/gemma-4-E2B-it-litert-lm
11
+
12
+ Main Model Card: [google/gemma-4-E2B-it](https://huggingface.co/google/gemma-4-E2B-it)
13
+
14
+ This model card provides the Gemma 4 E2B model in a way that is ready for deployment on Android, iOS, Desktop, IoT and Web.
15
+
16
+ Gemma is a family of lightweight, state-of-the-art open models from Google, built from the same research and technology used to create the Gemini models. This particular Gemma 4 model is small so it is ideal for on-device use cases. By running this model on device, users can have private access to Generative AI technology without even requiring an internet connection.
17
+
18
+ These models are provided in the `.litertlm` format for use with the LiteRT-LM framework. LiteRT-LM is a specialized orchestration layer built directly on top of LiteRT, Google’s high-performance multi-platform runtime trusted by millions of Android and edge developers. LiteRT provides the foundational hardware acceleration via XNNPack for CPU and ML Drift for GPU. LiteRT-LM adds the specialized GenAI libraries and APIs, such as KV-cache management, prompt templating, and function calling. This integrated stack is the same technology powering the Google AI Edge Gallery showcase app.
19
+
20
+ LiteRT-LM uses a state of the art [Gemma-4 mobile quantization scheme](https://blog.google/innovation-and-ai/technology/developers-tools/quantization-aware-training-gemma-4/) that uses a mixture of 2bit, 4bit and 8 bit weights. This means that for text only use cases the weight footprint in memory can be as low as 0.8 GB while the runtime uses memory mapping to support the 1.12GB of embedding parameters. This approach gives significant working memory savings on some platforms as seen in the more detailed data below. Additionally the Vision and Audio models are loaded on demand to further reduce memory consumption.
21
+
22
+ # Try Gemma 4 E2B
23
+
24
+ <div align="center">
25
+
26
+ | [<svg xmlns="http://www.w3.org/2000/svg" height="72px" viewBox="0 -960 960 960" width="72px" fill="currentColor"><path d="M40-240q9-107 65.5-197T256-580l-74-128q-6-9-3-19t13-15q8-5 18-2t16 12l74 128q86-36 180-36t180 36l74-128q6-9 16-12t18 2q10 5 13 15t-3 19l-74 128q94 53 150.5 143T920-240H40Zm275.5-124.5Q330-379 330-400t-14.5-35.5Q301-450 280-450t-35.5 14.5Q230-421 230-400t14.5 35.5Q259-350 280-350t35.5-14.5Zm400 0Q730-379 730-400t-14.5-35.5Q701-450 680-450t-35.5 14.5Q630-421 630-400t14.5 35.5Q659-350 680-350t35.5-14.5Z"/></svg>](https://play.google.com/store/apps/details?id=com.google.ai.edge.gallery&pli=1) | [<svg xmlns="http://www.w3.org/2000/svg" height="84px" viewBox="0 -960 960 960" width="84px" fill="currentColor"><path d="M160-615v-60h60v60h-60Zm0 335v-275h60v275h-60Zm292 0H347q-24.75 0-42.37-17.63Q287-315.25 287-340v-280q0-24.75 17.63-42.38Q322.25-680 347-680h105q24.75 0 42.38 17.62Q512-644.75 512-620v280q0 24.75-17.62 42.37Q476.75-280 452-280Zm-105-60h105v-280H347v280Zm228 60v-60h165v-114H635q-24.75 0-42.37-17.63Q575-489.25 575-514v-106q0-24.75 17.63-42.38Q610.25-680 635-680h165v60H635v106h105q24.75 0 42.38 17.62Q800-478.75 800-454v114q0 24.75-17.62 42.37Q764.75-280 740-280H575Z"/></svg>](https://apps.apple.com/us/app/google-ai-edge-gallery/id6749645337) | [<svg xmlns="http://www.w3.org/2000/svg" height="72px" viewBox="0 -960 960 960" width="72px" fill="currentColor"><path d="M320-120v-40l80-80H160q-33 0-56.5-23.5T80-320v-440q0-33 23.5-56.5T160-840h640q33 0 56.5 23.5T880-760v440q0 33-23.5 56.5T800-240H560l80 80v40H320ZM160-440h640v-320H160v320Zm0 0v-320 320Z"/></svg>](https://ai.google.dev/edge/litert-lm/cli) | [<svg xmlns="http://www.w3.org/2000/svg" height="72px" viewBox="0 -960 960 960" width="72px" fill="currentColor"><path d="M160-120q-33 0-56.5-23.5T80-200v-560q0-33 23.5-56.5T160-840h560q33 0 56.5 23.5T800-760v80h80v80h-80v80h80v80h-80v80h80v80h-80v80q0 33-23.5 56.5T720-120H160Zm0-80h560v-560H160v560Zm80-80h200v-160H240v160Zm240-280h160v-120H480v120Zm-240 80h200v-200H240v200Zm240 200h160v-240H480v240ZM160-760v560-560Z"/></svg>](https://ai.google.dev/edge/litert-lm/cli) | [<svg xmlns="http://www.w3.org/2000/svg" height="72px" viewBox="0 -960 960 960" width="72px" fill="currentColor"><path d="M838-79 710-207v103h-60v-206h206v60H752l128 128-42 43Zm-358-1q-83 0-156-31.5T197-197q-54-54-85.5-126.36T80-478q0-83.49 31.5-156.93Q143-708.36 197-762.68 251-817 324-848.5 397-880 480-880t156 31.5q73 31.5 127 85.82 54 54.32 85.5 127.75Q880-561.49 880-478q0 23-2 44.5t-7 43.5h-63q6-21.67 9-43.33 3-21.67 3-44.47 0-22.8-2.95-45.6-2.94-22.8-8.83-45.6H648q2 23 4 45.5t2 45q0 22.5-1.25 44.5T649-390h-61q3-22 4.5-44t1.5-44q0-22.75-1.5-45.5T588-569H373.42q-3.42 23-4.92 45.5t-1.5 45q0 22.5 1.5 44.5t4.5 44h197v60H384q14 53 34 104t62 86q23 0 45-2.5t45-7.5v60q-23 5-45 7.5T480-80ZM151.78-390H312q-2.5-22-3.75-44T307-478q0-22.75 1-45.5t3-45.5H151.71q-5.85 22.8-8.78 45.6-2.93 22.8-2.93 45.6t2.95 44.47q2.94 21.66 8.83 43.33ZM172-629h149.59q11.41-48 28.91-93.5T395-810q-71 24-129.5 69.5T172-629Zm222 478q-26-41-43.5-86T323-330H172q33 67 91 114t131 65Zm-10-478h193q-13-54-36-104t-61-89q-38 40-61 89.5T384-629Zm255.34 0H788q-35-66-93-112t-129-68q27 41 44.5 86.5t28.84 93.5Z"/></svg>](https://huggingface.co/spaces/tylermullen/Gemma4) |
27
+ | :---: | :---: | :---: | :---: | :---: |
28
+ | [Android](https://play.google.com/store/apps/details?id=com.google.ai.edge.gallery&pli=1) | [iOS](https://apps.apple.com/us/app/google-ai-edge-gallery/id6749645337) | [Desktop](https://ai.google.dev/edge/litert-lm/cli) | [IoT](https://ai.google.dev/edge/litert-lm/cli) | [Web](https://huggingface.co/spaces/tylermullen/Gemma4) |
29
+
30
+ </div>
31
+
32
+
33
+ # Build with Gemma 4 E2B and LiteRT-LM
34
+
35
+ Ready to integrate this into your product? Get started [here](https://ai.google.dev/edge/litert-lm/overview).
36
+
37
+ # Gemma 4 E2B Performance on LiteRT-LM
38
+
39
+ All benchmarks were taken using 1024 prefill tokens and 256 decode tokens with a context length of 2048 tokens via LiteRT-LM. The model can support up to 32k context length. The inference on CPU is accelerated via the LiteRT XNNPACK delegate with 4 threads. Time-to-first-token does not include load time. Benchmarks were run with caches enabled and initialized. During the first run, the latency and memory usage may differ. Model size is the size of the file on disk.
40
+
41
+ CPU memory was measured using, `rusage::ru_maxrss` on Android, Linux and Raspberry Pi, `task_vm_info::phys_footprint` on iOS and MacBook and `process_memory_counters::PrivateUsage` on Windows.
42
+
43
+ **Android**
44
+
45
+ *Note: On [supported Android devices](https://developers.google.com/ml-kit), Gemma 4 is available through Android AI Core as [Gemini Nano](https://developer.android.com/ai/gemini-nano#architecture), which is the recommended path for production applications.*
46
+
47
+
48
+ | Device &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Backend | Prefill (tokens/sec) | Decode (tokens/sec) | <span style="white-space: nowrap;">Time-to-first</span>-token (sec) | Model size (MB) | CPU Memory (MB) |
49
+ | :---- | :---- | :---- | :---- | :---- | :---- | :---- |
50
+ | S26 Ultra | CPU | 557 | 46.9 | 1.8 | 2583 | 1733 |
51
+ | S26 Ultra | GPU | 3,808 | 52.1 | 0.3 | 2583 | 676 |
52
+
53
+ **Android with Speculative Decoding**
54
+
55
+ *The numbers in this section include speculative decoding. Speculative decoding is an optimization that accelerates LLMs by using a small, fast "draft" model to quickly predict multiple upcoming tokens, while a larger “target” model then verifies those tokens in parallel. The effectiveness of speculative decoding is task dependent because the “draft” model can more easily predict the correct tokens of some tasks. The metrics in this section were collected from a variety of sample prompts and grouped into categories by task type. The baseline measurements are an average across all task types. The number of input and output tokens varied across prompts. Note that if you download this model before May 5, 2026, you should re-download the model if you want to use speculative decoding. Speculative decoding is available on CPU and GPU on Mobile and Desktop.*
56
+
57
+ | Device &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Backend | Task Type | Speculative Decoding? | Decode (tokens/sec) | CPU Memory (MB) |
58
+ | :---- | :---- | :---- | :---- | :---- | :---- |
59
+ | S26 Ultra | CPU | Baseline | No | 40.7 | 1362 |
60
+ | S26 Ultra | CPU | Summarize text | Yes | 47.5 | 1582 |
61
+ | S26 Ultra | CPU | Code snippet | Yes | 36.3 | 1440 |
62
+ | S26 Ultra | CPU | Rewrite tone | Yes | 47.1 | 1408 |
63
+ | S26 Ultra | CPU | Free form | Yes | 38.1 | 1459 |
64
+ | S26 Ultra | GPU | Baseline | No | 51.5 | 791 |
65
+ | S26 Ultra | GPU | Summarize text | Yes | 91.7 | 817 |
66
+ | S26 Ultra | GPU | Code snippet | Yes | 84.4 | 788 |
67
+ | S26 Ultra | GPU | Rewrite tone | Yes | 87.4 | 762 |
68
+ | S26 Ultra | GPU | Free form | Yes | 66.5 | 804 |
69
+
70
+
71
+ **iOS**
72
+
73
+ | Device &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Backend | Prefill (tokens/sec) | Decode (tokens/sec) | <span style="white-space: nowrap;">Time-to-first</span>-token (sec) | Model size (MB) | CPU/GPU Memory (MB) |
74
+ | :---- | :---- | :---- | :---- | :---- | :---- | :---- |
75
+ | iPhone 17 Pro | CPU | 532 | 25.0 | 1.9 | 2583 | 607 |
76
+ | iPhone 17 Pro | GPU | 2,878 | 56.5 | 0.3 | 2583 | 1450 |
77
+
78
+ **Linux**
79
+
80
+ | Device &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Backend | Prefill (tokens/sec) | Decode (tokens/sec) | <span style="white-space: nowrap;">Time-to-first</span>-token (sec) | Model size (MB) | CPU Memory (MB) |
81
+ | :---- | :---- | :---- | :---- | :---- | :---- | :---- |
82
+ | Arm 2.3 & 2.8GHz | CPU | 260 | 35.0 | 4.0 | 2583 | 1628 |
83
+ | NVIDIA GeForce RTX 4090 | GPU | 11,234 | 143.4 | 0.1 | 2583 | 913 |
84
+
85
+ **macOS**
86
+
87
+ | Device &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Backend | Prefill (tokens/sec) | Decode (tokens/sec) | <span style="white-space: nowrap;">Time-to-first</span>-token (sec) | Model size (MB) | CPU/GPU Memory (MB) |
88
+ | :---- | :---- | :---- | :---- | :---- | :---- | :---- |
89
+ | MacBook Pro M4 Max | CPU | 901 | 41.6 | 1.1 | 2583 | 736 |
90
+ | MacBook Pro M4 Max | GPU | 7,835 | 160.2 | 0.1 | 2583 | 1623 |
91
+
92
+ **Windows**
93
+
94
+ | Device &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Backend | Prefill (tokens/sec) | Decode (tokens/sec) | <span style="white-space: nowrap;">Time-to-first</span>-token (sec) | Model size (MB) | CPU Memory (MB) |
95
+ | :---- | :---- | :---- | :---- | :---- | :---- | :---- |
96
+ | Intel LunarLake | CPU | 435 | 29.8 | 2.39 | 2583 | 3505 |
97
+ | Intel LunarLake | GPU | 3,751 | 48.4 | 0.29 | 2583 | 3540 |
98
+
99
+ **Web**
100
+
101
+ | Device &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Backend | Prefill (tokens/sec) | Decode (tokens/sec) | <span style="white-space: nowrap;">Time-to-first</span>-token (sec) | Model size (MB) | GPU Memory (MB) |
102
+ | :---- | :---- | :---- | :---- | :---- | :---- | :---- |
103
+ | Macbook Pro M4 Max | WebGPU | 4,853 | 73 | 1.09 | 2341 | ~1800 |
104
+
105
+ <small>
106
+
107
+ * Web on LiteRT-LM uses a [specially optimized model](https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/blob/main/gemma-4-E2B-it-gpu.litertlm) for Web because of its unique memory constraints. The model can support up to 128k context length.
108
+
109
+ </small>
110
+
111
+
112
+ **IoT**
113
+
114
+ | Device &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Backend | Prefill (tokens/sec) | Decode (tokens/sec) | <span style="white-space: nowrap;">Time-to-first</span>-token (sec) | Model size (MB) | CPU Memory (MB) |
115
+ | :---- | :---- | :---- | :---- | :---- | :---- | :---- |
116
+ | Raspberry Pi 5 16GB | CPU | 133 | 7.6 | 7.8 | 2583 | 1546 |
117
+ | Jetson Orin Nano | CPU | 109 | 12.2 | 9.4 | 2583 | 3681 |
118
+ | Jetson Orin Nano | GPU | 1,142 | 24.2 | 0.9 | 2583 | 2739 |
119
+ | Qualcomm Dragonwing IQ8 (IQ-8275) | NPU | 3,747 | 31.7 | 0.3 | 2967 | 1869 |
120
+
121
+ <small>
122
+
123
+ * NPU model is benchmarked with 4096 context length
124
+
125
+ </small>
126
+
127
+
128
+ ## Running Gemma 4 E2B on Web with LiteRT-LM.js
129
+ See our [LiteRT-LM.js overview](https://developers.google.com/edge/litert-lm/js) to get started using the [*gemma-4-E2B-it-gpu.litertlm*](https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/blob/main/gemma-4-E2B-it-gpu.litertlm) model file.
130
+
131
+
132
+ # 🔨 HACKATHON: Qualcomm QCS8275 NPU variant (Arduino Ventuno Q) 🔨
133
+
134
+ `gemma-4-E2B-it_Qualcomm_QCS8275.litertlm` is the ahead-of-time compiled NPU variant for Qualcomm QCS8275 (Hexagon v75), used by the Google × Qualcomm Arduino LiteRT hackathon's [Ventuno Q example](https://github.com/heath0xFF/google-litert-hackathon/tree/main/examples/standalone-litert-lm-npu). It is a separate artifact from `gemma-4-E2B-it.litertlm`; use the NPU variant with the matching Qualcomm dispatch/runtime libraries, not with the CPU backend. Compatibility with other Qualcomm chips or Android runtimes is not established by this example.
135
+
136
+ | Item | Details |
137
+ | :--- | :--- |
138
+ | Target environment documented by the example | Arduino Ventuno Q, Ubuntu 24.04 ARM64, Python 3.12 |
139
+ | Inputs / output | Text, image, and audio inputs; text output |
140
+ | Python runtime used by the example | `litert-lm-api==0.18.0` with the Linux NPU-enabled native runtime described below |
141
+ | QAIRT version embedded in this artifact | `2.50.0.260828` |
142
+ | File size | 2,722,352,245 bytes (approximately 2.72 GB) |
143
+ | SHA-256 | `794339191f0e1dc8353b7f84fb205af5e62870ed5647a315eddbf7a9a9c90f06` |
144
+
145
+ **Download and run**
146
+
147
+ Download with the Hugging Face CLI into the hackathon checkout's `models/` directory:
148
+
149
+ ```bash
150
+ hf download litert-community/gemma-4-E2B-it-litert-lm \
151
+ gemma-4-E2B-it_Qualcomm_QCS8275.litertlm \
152
+ --local-dir models
153
+ ```
154
+
155
+ Follow the [example's board setup instructions](https://github.com/heath0xFF/google-litert-hackathon/blob/main/examples/standalone-litert-lm-npu/README.md) before running inference. Its [`scripts/setup_npu.py`](https://github.com/heath0xFF/google-litert-hackathon/blob/main/scripts/setup_npu.py) retrieves the matching QAIRT libraries and a pinned Linux ARM64 LiteRT-LM native runtime/Qualcomm dispatch bundle from [`native-v0.18.0-e`](https://github.com/DenisovAV/flutter_edge_ai/releases/tag/native-v0.18.0-e). The example uses that native runtime in place of the Python wheel's bundled library; installing the Python package alone is not the complete setup. Qualcomm SDK libraries are downloaded separately under their own terms and are not included in this model file upload.
156
+
157
+ After setup, run on the Ventuno Q from the hackathon checkout:
158
+
159
+ ```bash
160
+ timeout 120 .venv-lm/bin/python examples/standalone-litert-lm-npu/main.py \
161
+ --model models/gemma-4-E2B-it_Qualcomm_QCS8275.litertlm
162
+ ```
163
+
164
+ The example also accepts `--image PATH` or `--audio PATH` with `--prompt TEXT`, and selects the NPU for the corresponding encoder. For audio, the example recommends a short 16 kHz mono WAV file.
165
+
166
+ **Validation scope and limitations**
167
+
168
+ The hackathon project documents successful text, image, and audio NPU runs with `litert-lm-api==0.18.0` using short examples on one Ventuno Q. Its smoke check requires an `NPU evidence:` line and a `PASS: local Gemma answered; backend=NPU; ...` result; a generated answer alone is not evidence of NPU execution. This upload was checked for file integrity, but no new board inference or benchmark was run as part of publishing it.
169
+
170
+ The NPU context length is fixed at compilation and cannot be increased at runtime. The example limits generated output to 128 tokens; that output limit is not the model's context length. No numerical context-length or per-component quantization specification is asserted here for this artifact. The general quantization description and benchmark tables elsewhere in this card should not be treated as measurements or specifications for this particular QCS8275 file.
171
+
chat_template.jinja ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- macro format_parameters(properties, required) -%}
2
+ {%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%}
3
+ {%- set ns = namespace(found_first=false) -%}
4
+ {%- for key, value in properties | dictsort -%}
5
+ {%- set add_comma = false -%}
6
+ {%- if key not in standard_keys -%}
7
+ {%- if ns.found_first %},{% endif -%}
8
+ {%- set ns.found_first = true -%}
9
+ {{ key }}:{
10
+ {%- if value['description'] -%}
11
+ description:<|"|>{{ value['description'] }}<|"|>
12
+ {%- set add_comma = true -%}
13
+ {%- endif -%}
14
+ {%- if value['nullable'] %}
15
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
16
+ nullable:true
17
+ {%- endif -%}
18
+ {%- if value['type'] | upper == 'STRING' -%}
19
+ {%- if value['enum'] -%}
20
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
21
+ enum:{{ format_argument(value['enum']) }}
22
+ {%- endif -%}
23
+ {%- elif value['type'] | upper == 'OBJECT' -%}
24
+ ,properties:{
25
+ {%- if value['properties'] is defined and value['properties'] is mapping -%}
26
+ {{- format_parameters(value['properties'], value['required'] | default([])) -}}
27
+ {%- elif value is mapping -%}
28
+ {{- format_parameters(value, value['required'] | default([])) -}}
29
+ {%- endif -%}
30
+ }
31
+ {%- if value['required'] -%}
32
+ ,required:[
33
+ {%- for item in value['required'] | default([]) -%}
34
+ <|"|>{{- item -}}<|"|>
35
+ {%- if not loop.last %},{% endif -%}
36
+ {%- endfor -%}
37
+ ]
38
+ {%- endif -%}
39
+ {%- elif value['type'] | upper == 'ARRAY' -%}
40
+ {%- if value['items'] is mapping and value['items'] -%}
41
+ ,items:{
42
+ {%- set ns_items = namespace(found_first=false) -%}
43
+ {%- for item_key, item_value in value['items'] | dictsort -%}
44
+ {%- if item_value is not none -%}
45
+ {%- if ns_items.found_first %},{% endif -%}
46
+ {%- set ns_items.found_first = true -%}
47
+ {%- if item_key == 'properties' -%}
48
+ properties:{
49
+ {%- if item_value is mapping -%}
50
+ {{- format_parameters(item_value, value['items']['required'] | default([])) -}}
51
+ {%- endif -%}
52
+ }
53
+ {%- elif item_key == 'required' -%}
54
+ required:[
55
+ {%- for req_item in item_value -%}
56
+ <|"|>{{- req_item -}}<|"|>
57
+ {%- if not loop.last %},{% endif -%}
58
+ {%- endfor -%}
59
+ ]
60
+ {%- elif item_key == 'type' -%}
61
+ {%- if item_value is string -%}
62
+ type:{{ format_argument(item_value | upper) }}
63
+ {%- else -%}
64
+ type:{{ format_argument(item_value | map('upper') | list) }}
65
+ {%- endif -%}
66
+ {%- else -%}
67
+ {{ item_key }}:{{ format_argument(item_value) }}
68
+ {%- endif -%}
69
+ {%- endif -%}
70
+ {%- endfor -%}
71
+ }
72
+ {%- endif -%}
73
+ {%- endif -%}
74
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
75
+ type:<|"|>{{ value['type'] | upper }}<|"|>}
76
+ {%- endif -%}
77
+ {%- endfor -%}
78
+ {%- endmacro -%}
79
+ {%- macro format_function_declaration(tool_data) -%}
80
+ declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|>
81
+ {%- set params = tool_data['function']['parameters'] -%}
82
+ {%- if params -%}
83
+ ,parameters:{
84
+ {%- if params['properties'] -%}
85
+ properties:{ {{- format_parameters(params['properties'], params['required']) -}} },
86
+ {%- endif -%}
87
+ {%- if params['required'] -%}
88
+ required:[
89
+ {%- for item in params['required'] -%}
90
+ <|"|>{{- item -}}<|"|>
91
+ {{- ',' if not loop.last -}}
92
+ {%- endfor -%}
93
+ ],
94
+ {%- endif -%}
95
+ {%- if params['type'] -%}
96
+ type:<|"|>{{- params['type'] | upper -}}<|"|>}
97
+ {%- endif -%}
98
+ {%- endif -%}
99
+ {%- if 'response' in tool_data['function'] -%}
100
+ {%- set response_declaration = tool_data['function']['response'] -%}
101
+ ,response:{
102
+ {%- if response_declaration['description'] -%}
103
+ description:<|"|>{{- response_declaration['description'] -}}<|"|>,
104
+ {%- endif -%}
105
+ {%- if response_declaration['type'] | upper == 'OBJECT' -%}
106
+ type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>}
107
+ {%- endif -%}
108
+ {%- endif -%}
109
+ }
110
+ {%- endmacro -%}
111
+ {%- macro format_argument(argument, escape_keys=True) -%}
112
+ {%- if argument is string -%}
113
+ {{- '<|"|>' + argument + '<|"|>' -}}
114
+ {%- elif argument is boolean -%}
115
+ {{- 'true' if argument else 'false' -}}
116
+ {%- elif argument is mapping -%}
117
+ {{- '{' -}}
118
+ {%- set ns = namespace(found_first=false) -%}
119
+ {%- for key, value in argument | dictsort -%}
120
+ {%- if ns.found_first %},{% endif -%}
121
+ {%- set ns.found_first = true -%}
122
+ {%- if escape_keys -%}
123
+ {{- '<|"|>' + key + '<|"|>' -}}
124
+ {%- else -%}
125
+ {{- key -}}
126
+ {%- endif -%}
127
+ :{{- format_argument(value, escape_keys=escape_keys) -}}
128
+ {%- endfor -%}
129
+ {{- '}' -}}
130
+ {%- elif argument is sequence -%}
131
+ {{- '[' -}}
132
+ {%- for item in argument -%}
133
+ {{- format_argument(item, escape_keys=escape_keys) -}}
134
+ {%- if not loop.last %},{% endif -%}
135
+ {%- endfor -%}
136
+ {{- ']' -}}
137
+ {%- else -%}
138
+ {{- argument -}}
139
+ {%- endif -%}
140
+ {%- endmacro -%}
141
+ {%- macro strip_thinking(text) -%}
142
+ {%- set ns = namespace(result='') -%}
143
+ {%- for part in text.split('<channel|>') -%}
144
+ {%- if '<|channel>' in part -%}
145
+ {%- set ns.result = ns.result + part.split('<|channel>')[0] -%}
146
+ {%- else -%}
147
+ {%- set ns.result = ns.result + part -%}
148
+ {%- endif -%}
149
+ {%- endfor -%}
150
+ {{- ns.result | trim -}}
151
+ {%- endmacro -%}
152
+
153
+ {%- set ns = namespace(prev_message_type=None) -%}
154
+ {%- set loop_messages = messages -%}
155
+ {{ bos_token }}
156
+ {#- Handle System/Tool Definitions Block -#}
157
+ {%- if (enable_thinking is defined and enable_thinking) or tools or messages[0]['role'] in ['system', 'developer'] -%}
158
+ {{- '<|turn>system\n' -}}
159
+
160
+ {#- Inject Thinking token at the very top of the FIRST system turn -#}
161
+ {%- if enable_thinking is defined and enable_thinking -%}
162
+ {{- '<|think|>' -}}
163
+ {%- endif -%}
164
+
165
+ {%- if messages[0]['role'] in ['system', 'developer'] -%}
166
+ {%- if messages[0]['content'] is string -%}
167
+ {{- messages[0]['content'] | trim -}}
168
+ {%- elif messages[0]['content'] is sequence -%}
169
+ {%- for item in messages[0]['content'] -%}
170
+ {%- if item['type'] == 'text' -%}
171
+ {{- item['text'] | trim -}}
172
+ {%- endif -%}
173
+ {%- endfor -%}
174
+ {%- endif -%}
175
+ {%- set loop_messages = messages[1:] -%}
176
+ {%- endif -%}
177
+
178
+ {%- if tools -%}
179
+ {{- '\n\n' -}}
180
+ {%- for tool in tools %}
181
+ {{- '<|tool>' -}}
182
+ {{- format_function_declaration(tool) | trim -}}
183
+ {{- '<tool|>' -}}
184
+ {%- endfor %}
185
+ {%- endif -%}
186
+
187
+ {{- '<turn|>\n' -}}
188
+ {%- endif %}
189
+
190
+ {#- Loop through messages -#}
191
+ {%- for message in loop_messages -%}
192
+ {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}
193
+ {%- if role != 'tool' -%}
194
+ {{- '<|turn>' + role + '\n' }}
195
+ {%- endif -%}
196
+
197
+ {%- if message['tool_calls'] -%}
198
+ {%- for tool_call in message['tool_calls'] -%}
199
+ {%- set function = tool_call['function'] -%}
200
+ {{- '<|tool_call>call:' + function['name'] + '{' -}}
201
+ {%- if function['arguments'] is mapping -%}
202
+ {%- set ns_args = namespace(found_first=false) -%}
203
+ {%- for key, value in function['arguments'] | dictsort -%}
204
+ {%- if ns_args.found_first %},{% endif -%}
205
+ {%- set ns_args.found_first = true -%}
206
+ {{- key -}}:{{- format_argument(value, escape_keys=False) -}}
207
+ {%- endfor -%}
208
+ {%- elif function['arguments'] is string -%}
209
+ {{- function['arguments'] -}}
210
+ {%- endif -%}
211
+ {{- '}<tool_call|>' -}}
212
+ {%- endfor -%}
213
+ {%- set ns.prev_message_type = 'tool_call' -%}
214
+ {%- endif -%}
215
+
216
+ {%- if role == 'tool' and message['content'] is sequence -%}
217
+ {#- Tool Response handling -#}
218
+ {%- for item in message['content'] -%}
219
+ {{- '<|tool_response>' -}}
220
+ {%- if item['response'] is mapping -%}
221
+ {{- 'response:' + item['name'] | default('unknown') + '{' -}}
222
+ {%- for key, value in item['response'] | dictsort -%}
223
+ {{- key -}}:{{- format_argument(value, escape_keys=False) -}}
224
+ {%- if not loop.last %},{% endif -%}
225
+ {%- endfor -%}
226
+ {{- '}' -}}
227
+ {%- else -%}
228
+ {{- 'response:' + item['name'] | default('unknown') + '{value:' + format_argument(item['response'], escape_keys=False) + '}' -}}
229
+ {%- endif -%}
230
+ {{- '<tool_response|>' -}}
231
+ {%- endfor -%}
232
+ {%- set ns.prev_message_type = 'tool_response' -%}
233
+ {%- else -%}
234
+ {%- if message['content'] is string -%}
235
+ {%- if role == 'model' -%}
236
+ {{- strip_thinking(message['content']) -}}
237
+ {%- else -%}
238
+ {{- message['content'] | trim -}}
239
+ {%- endif -%}
240
+ {%- elif message['content'] is sequence -%}
241
+ {%- for item in message['content'] -%}
242
+ {%- if item['type'] == 'text' -%}
243
+ {%- if role == 'model' -%}
244
+ {{- strip_thinking(item['text']) -}}
245
+ {%- else -%}
246
+ {{- item['text'] | trim -}}
247
+ {%- endif -%}
248
+ {%- elif item['type'] == 'image' -%}
249
+ {{- '\n\n<|image|>\n\n' -}}
250
+ {%- elif item['type'] == 'audio' -%}
251
+ {{- '<|audio|>' -}}
252
+ {%- endif -%}
253
+ {%- endfor -%}
254
+ {%- endif -%}
255
+ {%- set ns.prev_message_type = None -%}
256
+ {%- endif -%}
257
+ {%- if ns.prev_message_type == None -%}
258
+ {{- '<turn|>\n' -}}
259
+ {%- endif -%}
260
+ {%- endfor -%}
261
+
262
+ {%- if add_generation_prompt -%}
263
+ {%- if ns.prev_message_type != 'tool_response' -%}
264
+ {{- '<|turn>model\n' -}}
265
+ {%- endif -%}
266
+ {%- endif -%}
gemini4_2b_sizes.png ADDED

Git LFS Details

  • SHA256: 0f268b3b6f268ae7b50ea49267694a380c0ff9d446b5ef71065ab8908591865a
  • Pointer size: 131 Bytes
  • Size of remote file: 119 kB
gemma-4-E2B-it-gpu.litertlm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3cfec6ae2e027a994e51366d44dbf522ec7531a4a35fbbfcd3e9cc9b927afc1
3
+ size 2340870772
gemma-4-E2B-it-web.litertlm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a08e8d94e23b814ae5414469c370c503813949acb8ceaa17e4ebf8a35af35b5
3
+ size 2008432640
gemma-4-E2B-it-web.task ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cbff161177a4d51c9d04360016185976f504517ba5758cd10c1564e5421c5a5
3
+ size 2003697664
gemma-4-E2B-it.litertlm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:181938105e0eefd105961417e8da75903eacda102c4fce9ce90f50b97139a63c
3
+ size 2588147712
gemma-4-E2B-it_Google_Tensor_G5.litertlm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72d056066f34362adcecf6b76995de67ad899f6f33dfe9079593c1acd2984191
3
+ size 3206299658
gemma-4-E2B-it_Google_Tensor_G6.litertlm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6cbe8d625f4965a8c32565f65ae774d19598d0d967a4c2101a7e04988daaf58
3
+ size 3453960202
gemma-4-E2B-it_NPU_Uncompiled.litertlm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4f86de05f54bda24e8633ef20375b81b3fcc5dace7c6ac9f4269644267ca4aa
3
+ size 2614578293
gemma-4-E2B-it_Qualcomm_QCS8275.litertlm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:794339191f0e1dc8353b7f84fb205af5e62870ed5647a315eddbf7a9a9c90f06
3
+ size 2722352245
gemma-4-E2B-it_intel_LNL.litertlm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dacc900381bdc837696fc5deb1f3b7dbfe0854295dc3934564e1841086ab0383
3
+ size 2960506880
gemma-4-E2B-it_intel_PTL.litertlm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c0877f721ff0c057a007b330bbf9f6ec4d0278e730f88db95f2252372c701e8
3
+ size 2948333568
gemma-4-E2B-it_w4a16_w48a16_Google_Tensor_G5.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dbd13d12f156f136b9ea204c720e4523c794e49990e612f3d8dd65b97fce0726
3
+ size 177
gemma-4-E2B-it_w4a16_w48a16_Google_Tensor_G6.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:966850cdf28e0854aa73a5c3d9acca1d0a44d03cc361974163588508160b21b3
3
+ size 177
gemma-4-E2B-it_w8a16_Google_Tensor_G5.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99777ca6a06499386a2af43aed95eb7c9cda68f4b06ab049b40eec0e1edace29
3
+ size 177
gemma-4-E2B-it_w8a16_Google_Tensor_G6.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35ead6a2c1050e1f38f2611d897d99937af3857bcc7c9dbe3374335753e0f51e
3
+ size 177
notebook.ipynb ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4"
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "language_info": {
14
+ "name": "python"
15
+ },
16
+ "accelerator": "GPU"
17
+ },
18
+ "cells": [
19
+ {
20
+ "cell_type": "markdown",
21
+ "source": [
22
+ "# Run On-Device LLM Inference with LiteRT-LM and Gemma 4\n",
23
+ "\n",
24
+ "This tutorial demonstrates how to use the **LiteRT-LM** Python library to run efficient, on-device LLM inference using `.litertlm` model files.\n",
25
+ "\n",
26
+ "[LiteRT-LM](https://ai.google.dev/edge/litert-lm) is a production-ready, open-source inference framework designed to deliver high-performance, cross-platform LLM deployments on edge devices.\n",
27
+ "\n",
28
+ "* **Cross-Platform Support**: Run on Android, iOS, Web, Desktop, and IoT (e.g. Raspberry Pi).\n",
29
+ "* **Hardware Acceleration**: Get peak performance and system stability by leveraging GPU and NPU accelerators across diverse hardware.\n",
30
+ "* **Multi-Modality**: Build with LLMs that have vision and audio support.\n",
31
+ "* **Tool Use**: Function calling support for agentic workflows with constrained decoding for improved accuracy.\n",
32
+ "* **Broad Model Support**: Run Gemma, Llama, Phi-4, Qwen and more.\n",
33
+ "\n",
34
+ "### Useful Links:\n",
35
+ "* **Official Documentation**: https://ai.google.dev/edge/litert-lm\n",
36
+ "* **GitHub Repository**: https://github.com/google-ai-edge/LiteRT-LM\n",
37
+ "* **Web Demo Page**: https://google-ai-edge.github.io/LiteRT-LM/web_demos/chat/index.html\n",
38
+ "* **LiteRT-LM Developers Blogpost**: https://developers.googleblog.com/blazing-fast-on-device-genai-with-litert-lm/\n",
39
+ "\n",
40
+ "---\n",
41
+ "\n",
42
+ "In this notebook, we will showcase the core capabilities of LiteRT-LM using the **Gemma 4 E2B** multimodal model in the following order:\n",
43
+ "1. **Basic text generation**\n",
44
+ "2. **Asynchronous streaming response**\n",
45
+ "3. **Multi-modality (Vision / Image inputs)**\n",
46
+ "4. **Multi-modality (Audio / Speech inputs)**\n",
47
+ "5. **Custom system instructions & conversation history** (with switchable compact personas)\n",
48
+ "6. **Speculative decoding with Multi-Token Prediction (MTP)** (optimized with streaming)\n",
49
+ "7. **Benchmarking model execution speeds**"
50
+ ],
51
+ "metadata": {
52
+ "id": "KLZy2OXwVYw2"
53
+ }
54
+ },
55
+ {
56
+ "cell_type": "markdown",
57
+ "source": [
58
+ "## 1. Setup and Installation\n",
59
+ "\n",
60
+ "First, let's install the required packages. We need `litert-lm-api` for the LiteRT-LM runtime, and `huggingface_hub` to easily download our optimized model from the Hugging Face model hub.\n"
61
+ ],
62
+ "metadata": {
63
+ "id": "sn1KczgNVbag"
64
+ }
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "source": [
69
+ "!pip install -q litert-lm-api huggingface_hub\n",
70
+ "\n",
71
+ "# Required for GPU\n",
72
+ "!apt-get update && apt-get install -y libvulkan1"
73
+ ],
74
+ "metadata": {
75
+ "id": "4cuBn5FSVdfp"
76
+ },
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "markdown",
82
+ "source": [
83
+ "## 2. Download the Gemma 4 E2B Model\n",
84
+ "\n",
85
+ "The Gemma 4 E2B instruction-tuned model is hosted on Hugging Face in the `.litertlm` format, which is optimized specifically for on-device execution.\n",
86
+ "\n",
87
+ "We will download the `gemma-4-E2B-it.litertlm` file from the [litert-community/gemma-4-E2B-it-litert-lm](https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm) repository.\n"
88
+ ],
89
+ "metadata": {
90
+ "id": "sVuZFNSFVik4"
91
+ }
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "source": [
96
+ "from huggingface_hub import hf_hub_download\n",
97
+ "\n",
98
+ "print(\"Downloading Gemma 4 E2B model from Hugging Face. This may take a few minutes...\")\n",
99
+ "model_path = hf_hub_download(\n",
100
+ " repo_id=\"litert-community/gemma-4-E2B-it-litert-lm\",\n",
101
+ " filename=\"gemma-4-E2B-it.litertlm\"\n",
102
+ ")\n",
103
+ "print(f\"Downloaded model successfully to: {model_path}\")"
104
+ ],
105
+ "metadata": {
106
+ "id": "LC-YtowxVkBj"
107
+ },
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "markdown",
113
+ "source": [
114
+ "## 3. Basic Text Generation\n",
115
+ "\n",
116
+ "To perform inference, we initialize the `Engine` with our downloaded model. The `Engine` manages model resources.\n",
117
+ "\n",
118
+ "We then create a `Conversation` object, which handles conversation history and state. Using the `with` statement (context manager) ensures that all on-device memory and hardware resources are properly released when done.\n"
119
+ ],
120
+ "metadata": {
121
+ "id": "ZU3Y-SQtVyrg"
122
+ }
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "source": [
127
+ "import litert_lm\n",
128
+ "\n",
129
+ "# Load the model using the Engine. We will use Backend.CPU() for local CPU execution.\n",
130
+ "# (Note: GPU acceleration can be configured via backend=litert_lm.Backend.GPU() if supported)\n",
131
+ "with litert_lm.Engine(model_path, backend=litert_lm.Backend.CPU()) as engine:\n",
132
+ " # Create a conversation instance\n",
133
+ " with engine.create_conversation() as conversation:\n",
134
+ " # Send a synchronous message\n",
135
+ " response = conversation.send_message(\"What is the capital of France?\")\n",
136
+ "\n",
137
+ " # Extract the response text\n",
138
+ " text = response[\"content\"][0][\"text\"]\n",
139
+ " print(f\"Response:\\n{text}\")"
140
+ ],
141
+ "metadata": {
142
+ "id": "vd2UPI1vVzWI"
143
+ },
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "markdown",
149
+ "source": [
150
+ "## 4. Asynchronous Streaming (Token-by-Token)\n",
151
+ "\n",
152
+ "For interactive chat applications, waiting for the entire response to generate can feel slow.\n",
153
+ "\n",
154
+ "LiteRT-LM provides `send_message_async`, which returns an iterator that yields response chunks in real-time as they are being decoded. This allows you to stream the output token-by-token.\n"
155
+ ],
156
+ "metadata": {
157
+ "id": "gJdHVUtDZqdJ"
158
+ }
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "source": [
163
+ "with litert_lm.Engine(model_path, backend=litert_lm.Backend.CPU()) as engine:\n",
164
+ " with engine.create_conversation() as conversation:\n",
165
+ " prompt = \"Tell me a short 3-sentence story about a brave little robot.\"\n",
166
+ " print(f\"Prompt: {prompt}\\n\\nStreaming Response:\\n\", end=\"\")\n",
167
+ "\n",
168
+ " # Start asynchronous streaming\n",
169
+ " stream = conversation.send_message_async(prompt)\n",
170
+ " for chunk in stream:\n",
171
+ " # Response chunks are dictionary objects containing a content array\n",
172
+ " for item in chunk.get(\"content\", []):\n",
173
+ " if item.get(\"type\") == \"text\":\n",
174
+ " print(item[\"text\"], end=\"\", flush=True)\n",
175
+ " print()"
176
+ ],
177
+ "metadata": {
178
+ "id": "JS9EP0LsZr5S"
179
+ },
180
+ "execution_count": null,
181
+ "outputs": []
182
+ },
183
+ {
184
+ "cell_type": "markdown",
185
+ "source": [
186
+ "## 5. Multi-Modality (Vision / Image Input)\n",
187
+ "\n",
188
+ "The **Gemma 4 E2B** model natively supports vision (images) and audio inputs in addition to text.\n",
189
+ "\n",
190
+ "To pass an image to the model:\n",
191
+ "1. Wrap the inputs in a `litert_lm.Contents` object.\n",
192
+ "2. Use `litert_lm.Content.ImageFile(image_path)` to specify the local path to the image.\n",
193
+ "\n",
194
+ "*Note: While CPU execution is shown here for simplicity, offloading vision encoding to GPU (via `vision_backend=litert_lm.Backend.GPU()`) is strongly recommended for interactive use cases.*\n"
195
+ ],
196
+ "metadata": {
197
+ "id": "NyQnf9GDZx0o"
198
+ }
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "source": [
203
+ "import urllib.request\n",
204
+ "from PIL import Image, ImageDraw\n",
205
+ "import os\n",
206
+ "from IPython.display import display\n",
207
+ "\n",
208
+ "# Download a public image (a standard red STOP sign)\n",
209
+ "image_url = \"https://upload.wikimedia.org/wikipedia/commons/f/f9/STOP_sign.jpg\"\n",
210
+ "image_path = \"stop_sign.jpg\"\n",
211
+ "\n",
212
+ "print(f\"Downloading image from {image_url}...\")\n",
213
+ "try:\n",
214
+ " # Wikimedia requires a User-Agent header to allow downloads, otherwise it returns 403 Forbidden.\n",
215
+ " req = urllib.request.Request(\n",
216
+ " image_url,\n",
217
+ " headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}\n",
218
+ " )\n",
219
+ " with urllib.request.urlopen(req) as response, open(image_path, 'wb') as out_file:\n",
220
+ " out_file.write(response.read())\n",
221
+ " print(\"Download complete.\")\n",
222
+ "except Exception as e:\n",
223
+ " print(f\"Failed to download image: {e}\")\n",
224
+ " # Fallback: create a red square with text \"STOP\" if download fails\n",
225
+ " img = Image.new(\"RGB\", (300, 300), color=\"red\")\n",
226
+ " draw = ImageDraw.Draw(img)\n",
227
+ " draw.text((120, 140), \"STOP\", fill=\"white\")\n",
228
+ " img.save(image_path)\n",
229
+ " print(\"Created a fallback image.\")\n",
230
+ "\n",
231
+ "# Open and display the image\n",
232
+ "img = Image.open(image_path)\n",
233
+ "img.thumbnail((300, 300))\n",
234
+ "display(img)\n",
235
+ "\n",
236
+ "# Load the model with vision support enabled on CPU\n",
237
+ "with litert_lm.Engine(\n",
238
+ " model_path,\n",
239
+ " backend=litert_lm.Backend.CPU(),\n",
240
+ " vision_backend=litert_lm.Backend.CPU() # Specify CPU backend for the vision processor\n",
241
+ ") as engine:\n",
242
+ " with engine.create_conversation() as conversation:\n",
243
+ " # Turn 1: Construct multimodal inputs combining image and a text prompt\n",
244
+ " multimodal_input = litert_lm.Contents.of(\n",
245
+ " litert_lm.Content.ImageFile(image_path),\n",
246
+ " \"Describe what you see in this image.\"\n",
247
+ " )\n",
248
+ "\n",
249
+ " print(\"\\nSending image + prompt to the model (streaming)...\")\n",
250
+ " stream = conversation.send_message_async(multimodal_input)\n",
251
+ " print(f\"\\nModel Description:\\n\", end=\"\")\n",
252
+ " for chunk in stream:\n",
253
+ " for item in chunk.get(\"content\", []):\n",
254
+ " if item.get(\"type\") == \"text\":\n",
255
+ " print(item[\"text\"], end=\"\", flush=True)\n",
256
+ " print(\"\\n\\n\" + \"-\" * 50 + \"\\n\")\n",
257
+ "\n",
258
+ " # Turn 2: Ask the model to read the text (context and image are preserved!)\n",
259
+ " print(\"Asking the model to perform OCR on the same image (streaming)...\")\n",
260
+ " stream2 = conversation.send_message_async(\"What text is written on the sign?\")\n",
261
+ " print(f\"\\nModel OCR Result:\\n\", end=\"\")\n",
262
+ " for chunk in stream2:\n",
263
+ " for item in chunk.get(\"content\", []):\n",
264
+ " if item.get(\"type\") == \"text\":\n",
265
+ " print(item[\"text\"], end=\"\", flush=True)\n",
266
+ " print()\n",
267
+ "\n",
268
+ "# Clean up the temporary image\n",
269
+ "if os.path.exists(image_path):\n",
270
+ " os.remove(image_path)"
271
+ ],
272
+ "metadata": {
273
+ "id": "lurL7oahZzDI"
274
+ },
275
+ "execution_count": null,
276
+ "outputs": []
277
+ },
278
+ {
279
+ "cell_type": "markdown",
280
+ "source": [
281
+ "## 6. Multi-Modality (Audio / Speech Input)\n",
282
+ "\n",
283
+ "In addition to images, **Gemma 4 E2B** natively supports audio inputs. This enables on-device **Automatic Speech Recognition (ASR)** and audio understanding.\n",
284
+ "\n",
285
+ "In this section, we will:\n",
286
+ "1. Download a public audio sample (a WAV file containing spoken words).\n",
287
+ "2. Display an interactive audio player inside the notebook.\n",
288
+ "3. Send the audio along with a text prompt to perform on-device transcription (ASR) using streaming.\n",
289
+ "\n",
290
+ "*Note: Similar to vision, offloading audio processing to CPU is shown here for simplicity, but hardware acceleration is recommended for production.*"
291
+ ],
292
+ "metadata": {
293
+ "id": "OwTWaRAWGEEd"
294
+ }
295
+ },
296
+ {
297
+ "cell_type": "code",
298
+ "source": [
299
+ "import urllib.request\n",
300
+ "from IPython.display import Audio, display\n",
301
+ "import os\n",
302
+ "\n",
303
+ "# Download a public audio file (contains spoken words: \"Have a wonderful day\")\n",
304
+ "audio_url = \"https://github.com/google-ai-edge/LiteRT-LM/raw/refs/heads/main/runtime/testdata/have_a_wonderful_day.wav\"\n",
305
+ "audio_path = \"have_a_wonderful_day.wav\"\n",
306
+ "\n",
307
+ "print(f\"Downloading audio from {audio_url}...\")\n",
308
+ "try:\n",
309
+ " # Use a User-Agent to avoid potential 403 Forbidden errors\n",
310
+ " req = urllib.request.Request(\n",
311
+ " audio_url,\n",
312
+ " headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}\n",
313
+ " )\n",
314
+ " with urllib.request.urlopen(req) as response, open(audio_path, 'wb') as out_file:\n",
315
+ " out_file.write(response.read())\n",
316
+ " print(\"Download complete.\")\n",
317
+ "except Exception as e:\n",
318
+ " print(f\"Failed to download audio: {e}\")\n",
319
+ "\n",
320
+ "# Play the audio in the notebook\n",
321
+ "if os.path.exists(audio_path):\n",
322
+ " display(Audio(audio_path))\n",
323
+ "\n",
324
+ " # Load the model with audio support enabled on CPU\n",
325
+ " with litert_lm.Engine(\n",
326
+ " model_path,\n",
327
+ " backend=litert_lm.Backend.CPU(),\n",
328
+ " audio_backend=litert_lm.Backend.CPU() # Specify CPU backend for the audio processor\n",
329
+ " ) as engine:\n",
330
+ " with engine.create_conversation() as conversation:\n",
331
+ " # Construct multimodal inputs combining audio and a text prompt\n",
332
+ " multimodal_input = litert_lm.Contents.of(\n",
333
+ " litert_lm.Content.AudioFile(audio_path),\n",
334
+ " \"Transcribe this audio.\"\n",
335
+ " )\n",
336
+ "\n",
337
+ " print(\"\\nSending audio + prompt to the model (streaming ASR)...\")\n",
338
+ " stream = conversation.send_message_async(multimodal_input)\n",
339
+ " print(f\"\\nModel Transcription:\\n\", end=\"\")\n",
340
+ " for chunk in stream:\n",
341
+ " for item in chunk.get(\"content\", []):\n",
342
+ " if item.get(\"type\") == \"text\":\n",
343
+ " print(item[\"text\"], end=\"\", flush=True)\n",
344
+ " print()\n",
345
+ "\n",
346
+ " # Clean up the temporary audio file\n",
347
+ " os.remove(audio_path)\n",
348
+ "else:\n",
349
+ " print(\"\\nError: Audio file was not downloaded successfully. Skipping inference.\")"
350
+ ],
351
+ "metadata": {
352
+ "id": "vIGC7kfOGFKh"
353
+ },
354
+ "execution_count": null,
355
+ "outputs": []
356
+ },
357
+ {
358
+ "cell_type": "markdown",
359
+ "source": [
360
+ "## 7. System Instructions & Conversation History\n",
361
+ "\n",
362
+ "A `Conversation` object preserves the state and history of your conversation.\n",
363
+ "\n",
364
+ "You can also customize the assistant's persona and guidelines by passing a list of initial messages containing a **system instruction** when creating the conversation.\n",
365
+ "\n",
366
+ "In this example, we provide two switchable options for the assistant's persona:\n",
367
+ "* **Option A: The Grumpy Pirate**: A curt, direct character who grunts and answers in at most 30 words.\n",
368
+ "* **Option B: The Wise Zen Master**: A calm, cryptic character who answers with a short riddle/koan of at most 30 words.\n",
369
+ "\n",
370
+ "Both options are strictly constrained to at most 30 words. This demonstrates how system instructions can shape diverse assistant behaviors while keeping the generated output very brief to minimize on-device decoding latency."
371
+ ],
372
+ "metadata": {
373
+ "id": "n0FgtNFTZ2IJ"
374
+ }
375
+ },
376
+ {
377
+ "cell_type": "code",
378
+ "source": [
379
+ "# Configure the system instruction. Choose one of the options below by uncommenting:\n",
380
+ "\n",
381
+ "# Option A: The Grumpy Pirate (curt, direct)\n",
382
+ "assistant_name = \"Pirate Assistant\"\n",
383
+ "system_instruction = (\n",
384
+ " \"You are a grumpy, curt pirate who hates talking. You must always answer \"\n",
385
+ " \"in a succinct but critical paragraph of at most 30 words, starting with a pirate grunt \"\n",
386
+ " \"like 'Arr', 'Bah', or 'Avast'.\"\n",
387
+ ")\n",
388
+ "\n",
389
+ "# # Option B: The Wise Zen Master (calm, cryptic) - Uncomment to switch:\n",
390
+ "# assistant_name = \"Zen Master\"\n",
391
+ "# system_instruction = (\n",
392
+ "# \"You are a wise, calm Zen Master. You must always answer with a short, \"\n",
393
+ "# \"cryptic riddle or koan of at most 30 words that forces the user to reflect.\"\n",
394
+ "# )\n",
395
+ "\n",
396
+ "initial_messages = [\n",
397
+ " litert_lm.Message.system(system_instruction)\n",
398
+ "]\n",
399
+ "\n",
400
+ "with litert_lm.Engine(model_path, backend=litert_lm.Backend.CPU()) as engine:\n",
401
+ " # Initialize conversation with our custom system instruction\n",
402
+ " with engine.create_conversation(messages=initial_messages) as conversation:\n",
403
+ "\n",
404
+ " # Turn 1 (Streaming)\n",
405
+ " print(f\"User: How can I write clean code?\\n\\n{assistant_name} (streaming):\\n\", end=\"\")\n",
406
+ " stream = conversation.send_message_async(\"How can I write clean code?\")\n",
407
+ " for chunk in stream:\n",
408
+ " for item in chunk.get(\"content\", []):\n",
409
+ " if item.get(\"type\") == \"text\":\n",
410
+ " print(item[\"text\"], end=\"\", flush=True)\n",
411
+ " print(\"\\n\\n\" + \"-\" * 50 + \"\\n\")\n",
412
+ "\n",
413
+ " # Turn 2 (Context is automatically maintained in this conversation, Streaming)\n",
414
+ " print(f\"User: And what about testing?\\n\\n{assistant_name} (streaming):\\n\", end=\"\")\n",
415
+ " stream2 = conversation.send_message_async(\"And what about testing?\")\n",
416
+ " for chunk in stream2:\n",
417
+ " for item in chunk.get(\"content\", []):\n",
418
+ " if item.get(\"type\") == \"text\":\n",
419
+ " print(item[\"text\"], end=\"\", flush=True)\n",
420
+ " print()"
421
+ ],
422
+ "metadata": {
423
+ "id": "m4GU7oe6Z2v9"
424
+ },
425
+ "execution_count": null,
426
+ "outputs": []
427
+ },
428
+ {
429
+ "cell_type": "markdown",
430
+ "source": [
431
+ "## 8. Multi-Token Prediction (MTP)\n",
432
+ "\n",
433
+ "**Multi-Token Prediction (MTP)** is an advanced performance optimization in LiteRT-LM that significantly accelerates decoding speed. It works by predicting multiple tokens in parallel per execution step (speculative decoding).\n",
434
+ "\n",
435
+ "To learn more about how MTP works and its performance benefits, check out the official [Google DeepMind Blog post](https://blog.google/innovation-and-ai/technology/developers-tools/multi-token-prediction-gemma-4/).\n",
436
+ "\n",
437
+ "<img src=\"https://storage.googleapis.com/gweb-uniblog-publish-prod/images/Chart_Blog_Updated.width-1000.format-webp.webp\" width=\"600\" alt=\"MTP Speedup Chart\" />\n",
438
+ "\n",
439
+ "To use MTP, you simply set `enable_speculative_decoding=True` when creating the `Engine`."
440
+ ],
441
+ "metadata": {
442
+ "id": "Dq2sff4EZ4ob"
443
+ }
444
+ },
445
+ {
446
+ "cell_type": "code",
447
+ "source": [
448
+ "# Initialize with enable_speculative_decoding=True to leverage Multi-Token Prediction (MTP)\n",
449
+ "with litert_lm.Engine(\n",
450
+ " model_path,\n",
451
+ " backend=litert_lm.Backend.CPU(),\n",
452
+ " enable_speculative_decoding=True\n",
453
+ ") as engine:\n",
454
+ " with engine.create_conversation() as conversation:\n",
455
+ " print(\"Sending prompt with MTP enabled (streaming):\\n\", end=\"\")\n",
456
+ " stream = conversation.send_message_async(\"Explain quantum computing in one sentence.\")\n",
457
+ " for chunk in stream:\n",
458
+ " for item in chunk.get(\"content\", []):\n",
459
+ " if item.get(\"type\") == \"text\":\n",
460
+ " print(item[\"text\"], end=\"\", flush=True)\n",
461
+ " print()"
462
+ ],
463
+ "metadata": {
464
+ "id": "gh89sKI3Z7Qf"
465
+ },
466
+ "execution_count": null,
467
+ "outputs": []
468
+ },
469
+ {
470
+ "cell_type": "markdown",
471
+ "source": [
472
+ "## 9. Benchmarking Performance\n",
473
+ "\n",
474
+ "LiteRT-LM includes built-in benchmarking utilities that let you measure important performance metrics for on-device execution:\n",
475
+ "* **Model Init Time**: Time (in seconds) to load and prepare the model.\n",
476
+ "* **Time-to-First-Token (TTFT)**: Latency from sending the prompt to receiving the first generated token.\n",
477
+ "* **Prefill Speed**: Throughput during prompt ingestion (tokens/sec).\n",
478
+ "* **Decode Speed**: Generation speed of subsequent tokens (tokens/sec).\n",
479
+ "\n",
480
+ "Let's measure these on our current environment.\n"
481
+ ],
482
+ "metadata": {
483
+ "id": "9cbhDA8sZ8kL"
484
+ }
485
+ },
486
+ {
487
+ "cell_type": "code",
488
+ "source": [
489
+ "# Configure a benchmark run\n",
490
+ "benchmark = litert_lm.Benchmark(\n",
491
+ " model_path,\n",
492
+ " litert_lm.Backend.CPU(),\n",
493
+ " prefill_tokens=64, # Emulate a 64-token prompt\n",
494
+ " decode_tokens=64, # Emulate generating 64 tokens\n",
495
+ ")\n",
496
+ "\n",
497
+ "print(\"Running benchmark. Please wait...\")\n",
498
+ "results = benchmark.run()\n",
499
+ "\n",
500
+ "print(\"\\n=== Benchmark Results ===\")\n",
501
+ "print(f\"Model Init Time: {results.init_time_in_second:.4f} seconds\")\n",
502
+ "print(f\"Time to First Token (TTFT): {results.time_to_first_token_in_second:.4f} seconds\")\n",
503
+ "print(f\"Prefill Speed: {results.last_prefill_tokens_per_second:.2f} tokens/second\")\n",
504
+ "print(f\"Decode Speed: {results.last_decode_tokens_per_second:.2f} tokens/second\")"
505
+ ],
506
+ "metadata": {
507
+ "id": "Ac5zkAJFZ95J"
508
+ },
509
+ "execution_count": null,
510
+ "outputs": []
511
+ },
512
+ {
513
+ "cell_type": "markdown",
514
+ "source": [
515
+ "## Summary & Next Steps\n",
516
+ "\n",
517
+ "Congratulations! You've completed this LiteRT-LM tutorial with Gemma 4 E2B. You now know how to:\n",
518
+ "1. Download `.litertlm` optimized model files from Hugging Face.\n",
519
+ "2. Run synchronous and asynchronous streaming text generation.\n",
520
+ "3. Use native on-device Multi-Modality by passing both **image** and **audio** files (running on-device OCR and ASR).\n",
521
+ "4. Configure custom system instructions with **switchable compact personas** and maintain conversation context.\n",
522
+ "5. Optimize performance with speculative decoding / Multi-Token Prediction (MTP).\n",
523
+ "6. Benchmark on-device execution speeds with the built-in suite.\n",
524
+ "\n",
525
+ "For more details and native deployment platforms, visit:\n",
526
+ "* **Official Documentation**: [https://ai.google.dev/edge/litert-lm](https://ai.google.dev/edge/litert-lm)\n",
527
+ "* **GitHub Repository**: [https://github.com/google-ai-edge/LiteRT-LM](https://github.com/google-ai-edge/LiteRT-LM)"
528
+ ],
529
+ "metadata": {
530
+ "id": "XgnfA2I_aDZY"
531
+ }
532
+ }
533
+ ]
534
+ }