Instructions to use barakplasma/translategemma-4b-it-android-task-quantized with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- LiteRT
How to use barakplasma/translategemma-4b-it-android-task-quantized with LiteRT:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Upload scripts/convert_translategemma_android.py with huggingface_hub
Browse files
scripts/convert_translategemma_android.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import argparse
|
| 3 |
+
import importlib
|
| 4 |
+
import inspect
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import traceback
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
os.environ.setdefault("TRANSFORMERS_NO_TORCHVISION", "1")
|
| 13 |
+
os.environ.setdefault("PYTHONUNBUFFERED", "1")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def log(msg): print(f"[+] {msg}", flush=True)
|
| 17 |
+
def warn(msg): print(f"[!] {msg}", flush=True)
|
| 18 |
+
def die(msg):
|
| 19 |
+
print(f"[x] {msg}", file=sys.stderr, flush=True)
|
| 20 |
+
sys.exit(1)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
SUPPORTED_QUANT = {
|
| 24 |
+
"none",
|
| 25 |
+
"dynamic_int8",
|
| 26 |
+
"float16",
|
| 27 |
+
"int8",
|
| 28 |
+
"int4",
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def normalize_quantize(q: str) -> str:
|
| 33 |
+
q = (q or "dynamic_int8").strip().lower()
|
| 34 |
+
aliases = {
|
| 35 |
+
"fp32": "none",
|
| 36 |
+
"no": "none",
|
| 37 |
+
"off": "none",
|
| 38 |
+
"fp16": "float16",
|
| 39 |
+
"f16": "float16",
|
| 40 |
+
"i8": "int8",
|
| 41 |
+
"q8": "int8",
|
| 42 |
+
"i4": "int4",
|
| 43 |
+
"q4": "int4",
|
| 44 |
+
}
|
| 45 |
+
q = aliases.get(q, q)
|
| 46 |
+
if q not in SUPPORTED_QUANT:
|
| 47 |
+
die(f"Unsupported --quantize '{q}'. Supported: {sorted(SUPPORTED_QUANT)}")
|
| 48 |
+
return q
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def load_config(model_dir: Path):
|
| 52 |
+
cfg_path = model_dir / "config.json"
|
| 53 |
+
if not cfg_path.exists():
|
| 54 |
+
die(f"Missing config: {cfg_path}")
|
| 55 |
+
cfg = json.loads(cfg_path.read_text())
|
| 56 |
+
text_cfg = cfg.get("text_config", {})
|
| 57 |
+
return cfg, text_cfg
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def inspect_arch(model_dir: Path):
|
| 61 |
+
cfg, text_cfg = load_config(model_dir)
|
| 62 |
+
info = {
|
| 63 |
+
"model_type": cfg.get("model_type", "unknown"),
|
| 64 |
+
"architecture": (cfg.get("architectures") or ["unknown"])[0],
|
| 65 |
+
"vocab_size": cfg.get("vocab_size", text_cfg.get("vocab_size", 262144)),
|
| 66 |
+
}
|
| 67 |
+
log(f"ARCH: {info}")
|
| 68 |
+
return info
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def ensure_model_downloaded(model_id: str, model_dir: Path, hf_token: str):
|
| 72 |
+
if (model_dir / "config.json").exists():
|
| 73 |
+
log(f"Using existing model dir: {model_dir}")
|
| 74 |
+
return
|
| 75 |
+
|
| 76 |
+
log(f"Downloading {model_id} -> {model_dir}")
|
| 77 |
+
try:
|
| 78 |
+
from huggingface_hub import snapshot_download
|
| 79 |
+
snapshot_download(
|
| 80 |
+
repo_id=model_id,
|
| 81 |
+
local_dir=str(model_dir),
|
| 82 |
+
token=hf_token if hf_token else None,
|
| 83 |
+
local_dir_use_symlinks=False,
|
| 84 |
+
)
|
| 85 |
+
except Exception as e:
|
| 86 |
+
die(f"Model download failed: {e}")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def try_builders(mod, builder_names, model_dir: Path):
|
| 90 |
+
for fn_name in builder_names:
|
| 91 |
+
fn = getattr(mod, fn_name, None)
|
| 92 |
+
if fn is None:
|
| 93 |
+
continue
|
| 94 |
+
log(f"Trying {mod.__name__}.{fn_name} ...")
|
| 95 |
+
try:
|
| 96 |
+
m = fn(str(model_dir))
|
| 97 |
+
if m is None:
|
| 98 |
+
warn(" returned None")
|
| 99 |
+
continue
|
| 100 |
+
if isinstance(m, (tuple, list)) and len(m) > 0:
|
| 101 |
+
m = m[0]
|
| 102 |
+
if not hasattr(m, "eval"):
|
| 103 |
+
warn(f" unsupported return type: {type(m)}")
|
| 104 |
+
continue
|
| 105 |
+
m.eval()
|
| 106 |
+
log(f" success with {fn_name}")
|
| 107 |
+
return m
|
| 108 |
+
except Exception as e:
|
| 109 |
+
warn(f" failed: {e}")
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def build_translategemma_4b(checkpoint_path: str):
|
| 114 |
+
"""
|
| 115 |
+
Custom builder for TranslateGemma 4B IT (Gemma3 multimodal decoder).
|
| 116 |
+
Strips 'language_model.' prefix from safetensors keys so the standard
|
| 117 |
+
TENSOR_NAMES_SEP_QKV mapping works.
|
| 118 |
+
|
| 119 |
+
Architecture (from config.json / verified weight shapes):
|
| 120 |
+
34 layers, embedding_dim=2560, 8 heads, head_dim=256, 4 KV heads,
|
| 121 |
+
intermediate=10240, sliding_window=1024, global every 6th layer.
|
| 122 |
+
"""
|
| 123 |
+
import safetensors.torch as st_lib
|
| 124 |
+
import json as json_lib
|
| 125 |
+
from litert_torch.generative.utilities import model_builder, loader as loading_utils
|
| 126 |
+
from litert_torch.generative.layers import kv_cache as kv_utils
|
| 127 |
+
from litert_torch.generative.examples.gemma3 import decoder as gemma3_decoder
|
| 128 |
+
import litert_torch.generative.layers.model_config as cfg_mod
|
| 129 |
+
|
| 130 |
+
norm = cfg_mod.NormalizationConfig(
|
| 131 |
+
type=cfg_mod.NormalizationType.RMS_NORM, epsilon=1e-6, zero_centered=True
|
| 132 |
+
)
|
| 133 |
+
ff = cfg_mod.FeedForwardConfig(
|
| 134 |
+
type=cfg_mod.FeedForwardType.GATED,
|
| 135 |
+
activation=cfg_mod.ActivationConfig(cfg_mod.ActivationType.GELU_TANH),
|
| 136 |
+
intermediate_size=10240,
|
| 137 |
+
pre_ff_norm_config=norm, post_ff_norm_config=norm,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def blk(idx):
|
| 141 |
+
attn = cfg_mod.AttentionConfig(
|
| 142 |
+
num_heads=8, head_dim=256, num_query_groups=4,
|
| 143 |
+
rotary_base=1_000_000 if (idx + 1) % 6 == 0 else 10_000,
|
| 144 |
+
rotary_percentage=1.0, qkv_transpose_before_split=True,
|
| 145 |
+
query_norm_config=norm, key_norm_config=norm, logit_softcap=None,
|
| 146 |
+
sliding_window_size=1024,
|
| 147 |
+
attn_type=cfg_mod.AttentionType.GLOBAL if (idx + 1) % 6 == 0
|
| 148 |
+
else cfg_mod.AttentionType.LOCAL_SLIDING,
|
| 149 |
+
)
|
| 150 |
+
return cfg_mod.TransformerBlockConfig(
|
| 151 |
+
attn_config=attn, ff_config=ff,
|
| 152 |
+
pre_attention_norm_config=norm, post_attention_norm_config=norm,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
model_config = cfg_mod.ModelConfig(
|
| 156 |
+
vocab_size=262208, num_layers=34, max_seq_len=8192,
|
| 157 |
+
embedding_dim=2560, embedding_scale=2560 ** 0.5,
|
| 158 |
+
block_configs=[blk(i) for i in range(34)],
|
| 159 |
+
final_norm_config=norm, lm_head_use_bias=False, final_logit_softcap=None,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
tensor_names = loading_utils.ModelLoader.TensorNames(
|
| 163 |
+
ff_up_proj="model.layers.{}.mlp.up_proj",
|
| 164 |
+
ff_down_proj="model.layers.{}.mlp.down_proj",
|
| 165 |
+
ff_gate_proj="model.layers.{}.mlp.gate_proj",
|
| 166 |
+
attn_query_proj="model.layers.{}.self_attn.q_proj",
|
| 167 |
+
attn_key_proj="model.layers.{}.self_attn.k_proj",
|
| 168 |
+
attn_value_proj="model.layers.{}.self_attn.v_proj",
|
| 169 |
+
attn_output_proj="model.layers.{}.self_attn.o_proj",
|
| 170 |
+
attn_query_norm="model.layers.{}.self_attn.q_norm",
|
| 171 |
+
attn_key_norm="model.layers.{}.self_attn.k_norm",
|
| 172 |
+
pre_attn_norm="model.layers.{}.input_layernorm",
|
| 173 |
+
post_attn_norm="model.layers.{}.post_attention_layernorm",
|
| 174 |
+
pre_ff_norm="model.layers.{}.pre_feedforward_layernorm",
|
| 175 |
+
post_ff_norm="model.layers.{}.post_feedforward_layernorm",
|
| 176 |
+
embedding="model.embed_tokens",
|
| 177 |
+
final_norm="model.norm",
|
| 178 |
+
lm_head=None,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def custom_loader(path: str):
|
| 182 |
+
idx = json_lib.loads((Path(path) / "model.safetensors.index.json").read_text())
|
| 183 |
+
out = {}
|
| 184 |
+
for fname in set(idx["weight_map"].values()):
|
| 185 |
+
for k, v in st_lib.load_file(str(Path(path) / fname)).items():
|
| 186 |
+
out[k[len("language_model."):] if k.startswith("language_model.") else k] = v
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
return model_builder.build_decoder_only_model(
|
| 190 |
+
checkpoint_path=checkpoint_path,
|
| 191 |
+
config=model_config,
|
| 192 |
+
tensor_names=tensor_names,
|
| 193 |
+
model_class=gemma3_decoder.Decoder,
|
| 194 |
+
custom_loader=custom_loader,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def strategy1_litert_native(model_dir: Path, out_dir: Path, model_type: str, quantize: str, prefill: int, kvcache: int):
|
| 199 |
+
"""
|
| 200 |
+
Native LiteRT conversion with explicit quantization support.
|
| 201 |
+
"""
|
| 202 |
+
log("Strategy 1: litert-torch native")
|
| 203 |
+
|
| 204 |
+
from litert_torch.generative.utilities import converter
|
| 205 |
+
from litert_torch.generative.utilities.export_config import ExportConfig
|
| 206 |
+
from litert_torch.generative.layers import kv_cache
|
| 207 |
+
|
| 208 |
+
export_config = ExportConfig()
|
| 209 |
+
export_config.kvcache_layout = kv_cache.KV_LAYOUT_TRANSPOSED
|
| 210 |
+
export_config.mask_as_input = True
|
| 211 |
+
|
| 212 |
+
# Map our quantize flags to converter's QuantizationName values
|
| 213 |
+
QUANT_MAP = {
|
| 214 |
+
"none": "none",
|
| 215 |
+
"dynamic_int8": "dynamic_int8",
|
| 216 |
+
"int8": "weight_only_int8",
|
| 217 |
+
"float16": "fp16",
|
| 218 |
+
"int4": "dynamic_int4_block128",
|
| 219 |
+
}
|
| 220 |
+
quant_for_converter = QUANT_MAP.get(quantize)
|
| 221 |
+
if quant_for_converter is None:
|
| 222 |
+
warn(f"No converter mapping for '{quantize}', falling back to Strategy 2")
|
| 223 |
+
return None
|
| 224 |
+
|
| 225 |
+
model = None
|
| 226 |
+
|
| 227 |
+
if model_type == "gemma3":
|
| 228 |
+
# Try custom 4B builder first (handles TranslateGemma 4B multimodal weight prefix)
|
| 229 |
+
log("Trying custom build_translategemma_4b ...")
|
| 230 |
+
try:
|
| 231 |
+
model = build_translategemma_4b(str(model_dir))
|
| 232 |
+
if model is not None:
|
| 233 |
+
model.eval()
|
| 234 |
+
log(" build_translategemma_4b success")
|
| 235 |
+
except Exception as e:
|
| 236 |
+
warn(f" build_translategemma_4b failed: {e}")
|
| 237 |
+
model = None
|
| 238 |
+
|
| 239 |
+
if model is None:
|
| 240 |
+
mod = importlib.import_module("litert_torch.generative.examples.gemma3.gemma3")
|
| 241 |
+
available = [n for n in dir(mod) if n.startswith("build_model")]
|
| 242 |
+
log(f"Gemma3 builders available: {available}")
|
| 243 |
+
preferred = ["build_model_4b", "build_model_2b", "build_model_1b", "build_model_270m", "build_model"]
|
| 244 |
+
ordered = [n for n in preferred if n in available] + [n for n in available if n not in preferred]
|
| 245 |
+
model = try_builders(mod, ordered, model_dir)
|
| 246 |
+
|
| 247 |
+
elif model_type in ("gemma", "gemma2"):
|
| 248 |
+
mod = importlib.import_module("litert_torch.generative.examples.gemma2.gemma2")
|
| 249 |
+
available = [n for n in dir(mod) if n.startswith("build_model")]
|
| 250 |
+
log(f"Gemma2 builders available: {available}")
|
| 251 |
+
preferred = ["build_model_4b", "build_model_2b", "build_model"]
|
| 252 |
+
ordered = [n for n in preferred if n in available] + [n for n in available if n not in preferred]
|
| 253 |
+
model = try_builders(mod, ordered, model_dir)
|
| 254 |
+
|
| 255 |
+
else:
|
| 256 |
+
warn(f"Model type '{model_type}' not handled by native strategy")
|
| 257 |
+
return None
|
| 258 |
+
|
| 259 |
+
if model is None:
|
| 260 |
+
warn("Strategy 1 did not find a compatible builder")
|
| 261 |
+
return None
|
| 262 |
+
|
| 263 |
+
converter.convert_to_tflite(
|
| 264 |
+
model,
|
| 265 |
+
output_path=str(out_dir),
|
| 266 |
+
output_name_prefix=f"translategemma-4b-it-{quantize}",
|
| 267 |
+
prefill_seq_len=prefill,
|
| 268 |
+
kv_cache_max_len=kvcache,
|
| 269 |
+
quantize=quant_for_converter,
|
| 270 |
+
export_config=export_config,
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
produced = sorted(out_dir.glob(f"*{quantize}*.tflite")) or sorted(out_dir.glob("*.tflite"))
|
| 274 |
+
return produced[0] if produced else None
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def strategy2_generic(model_dir: Path, out_dir: Path, prefill: int, quantize: str):
|
| 278 |
+
"""
|
| 279 |
+
Generic fallback conversion (logits-only). Always exports float32; use
|
| 280 |
+
strategy3_post_tflite_quantize() afterwards for real int4/int8 compression.
|
| 281 |
+
"""
|
| 282 |
+
log("Strategy 2: ai_edge_torch generic (wrapped logits-only)")
|
| 283 |
+
|
| 284 |
+
import torch
|
| 285 |
+
try:
|
| 286 |
+
import litert_torch as ai_edge_torch
|
| 287 |
+
except Exception:
|
| 288 |
+
import ai_edge_torch # deprecated fallback
|
| 289 |
+
|
| 290 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
| 291 |
+
|
| 292 |
+
dtype = torch.float32
|
| 293 |
+
if quantize == "float16":
|
| 294 |
+
dtype = torch.float16
|
| 295 |
+
|
| 296 |
+
cfg = AutoConfig.from_pretrained(str(model_dir), trust_remote_code=True)
|
| 297 |
+
vocab = getattr(cfg, "vocab_size", None)
|
| 298 |
+
if vocab is None and hasattr(cfg, "text_config"):
|
| 299 |
+
vocab = getattr(cfg.text_config, "vocab_size", None)
|
| 300 |
+
vocab = int(vocab or 262144)
|
| 301 |
+
|
| 302 |
+
log(f"Loading HF model on CPU with dtype={dtype} ...")
|
| 303 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
| 304 |
+
str(model_dir),
|
| 305 |
+
trust_remote_code=True,
|
| 306 |
+
torch_dtype=dtype,
|
| 307 |
+
)
|
| 308 |
+
base_model.eval()
|
| 309 |
+
|
| 310 |
+
# TFLite embedding_lookup does not support f16 weights — keep embedding in float32
|
| 311 |
+
if dtype == torch.float16:
|
| 312 |
+
log("Casting embedding and lm_head to float32 for TFLite compatibility")
|
| 313 |
+
if hasattr(base_model, "model") and hasattr(base_model.model, "embed_tokens"):
|
| 314 |
+
base_model.model.embed_tokens = base_model.model.embed_tokens.to(torch.float32)
|
| 315 |
+
if hasattr(base_model, "lm_head"):
|
| 316 |
+
base_model.lm_head = base_model.lm_head.to(torch.float32)
|
| 317 |
+
|
| 318 |
+
if hasattr(base_model, "config") and hasattr(base_model.config, "use_cache"):
|
| 319 |
+
base_model.config.use_cache = False
|
| 320 |
+
|
| 321 |
+
class LogitsOnlyWrapper(torch.nn.Module):
|
| 322 |
+
def __init__(self, model):
|
| 323 |
+
super().__init__()
|
| 324 |
+
self.model = model
|
| 325 |
+
|
| 326 |
+
def forward(self, input_ids):
|
| 327 |
+
out = self.model(
|
| 328 |
+
input_ids=input_ids,
|
| 329 |
+
use_cache=False,
|
| 330 |
+
return_dict=False,
|
| 331 |
+
)
|
| 332 |
+
logits = out[0] if isinstance(out, (tuple, list)) else out.logits
|
| 333 |
+
return logits
|
| 334 |
+
|
| 335 |
+
wrapped = LogitsOnlyWrapper(base_model).eval()
|
| 336 |
+
sample_ids = torch.randint(0, vocab, (1, min(prefill, 128)), dtype=torch.int64)
|
| 337 |
+
|
| 338 |
+
# Always export float32 base; int4/int8 quantization applied post-export via Strategy 3
|
| 339 |
+
out_file = out_dir / f"translategemma-4b-it-generic-none.tflite"
|
| 340 |
+
edge_model = ai_edge_torch.convert(wrapped, (sample_ids,))
|
| 341 |
+
edge_model.export(str(out_file))
|
| 342 |
+
|
| 343 |
+
return out_file if out_file.exists() else None
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def strategy3_post_tflite_quantize(tflite_in: Path, out_dir: Path, quantize: str):
|
| 347 |
+
"""
|
| 348 |
+
Post-conversion weight quantization applied directly to a TFLite flatbuffer
|
| 349 |
+
using ai_edge_quantizer (bundled with litert_torch).
|
| 350 |
+
|
| 351 |
+
Supported modes and their recipes (per get_supported_layer_schemes()):
|
| 352 |
+
int4 -> INT4 DYNAMIC_RANGE BLOCKWISE_128 (~2 GB for 4B model)
|
| 353 |
+
int8 -> INT8 WEIGHT_ONLY CHANNELWISE (~4 GB)
|
| 354 |
+
dynamic_int8 -> INT8 DYNAMIC_RANGE CHANNELWISE (~4 GB)
|
| 355 |
+
float16 -> FP16 WEIGHT_ONLY FLOAT_CAST (~8 GB)
|
| 356 |
+
"""
|
| 357 |
+
log(f"Strategy 3: post-TFLite quantization ({quantize}) on {tflite_in.name}")
|
| 358 |
+
|
| 359 |
+
from litert_torch.generative.quantize import quant_attrs as qa, quant_recipe, quant_recipe_utils
|
| 360 |
+
from litert_torch.quantize import translate_recipe
|
| 361 |
+
|
| 362 |
+
if quantize == "int4":
|
| 363 |
+
layer = quant_recipe_utils.create_layer_quant_dynamic(qa.Dtype.INT4, qa.Granularity.BLOCKWISE_128)
|
| 364 |
+
elif quantize == "int8":
|
| 365 |
+
layer = quant_recipe_utils.create_layer_quant_weight_only(qa.Dtype.INT8, qa.Granularity.CHANNELWISE)
|
| 366 |
+
elif quantize == "dynamic_int8":
|
| 367 |
+
layer = quant_recipe_utils.create_layer_quant_dynamic(qa.Dtype.INT8, qa.Granularity.CHANNELWISE)
|
| 368 |
+
elif quantize == "float16":
|
| 369 |
+
layer = quant_recipe_utils.create_layer_quant_fp16()
|
| 370 |
+
else:
|
| 371 |
+
warn(f"Strategy 3: no post-TFLite recipe for '{quantize}', skipping")
|
| 372 |
+
return None
|
| 373 |
+
|
| 374 |
+
gen_recipe = quant_recipe.GenerativeQuantRecipe(default=layer)
|
| 375 |
+
ai_recipe = translate_recipe.translate_to_ai_edge_recipe(gen_recipe)
|
| 376 |
+
|
| 377 |
+
model_bytes = tflite_in.read_bytes()
|
| 378 |
+
log(f" Input: {len(model_bytes) / 1024**3:.2f} GB — quantizing ...")
|
| 379 |
+
quantized_bytes = translate_recipe.quantize_model(model_bytes, ai_recipe)
|
| 380 |
+
|
| 381 |
+
out_file = out_dir / f"translategemma-4b-it-{quantize}.tflite"
|
| 382 |
+
out_file.write_bytes(quantized_bytes)
|
| 383 |
+
log(f" Output: {len(quantized_bytes) / 1024**3:.2f} GB -> {out_file}")
|
| 384 |
+
return out_file
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def ensure_tokenizer_model(model_dir: Path):
|
| 388 |
+
tok_model = model_dir / "tokenizer.model"
|
| 389 |
+
if tok_model.exists():
|
| 390 |
+
return tok_model
|
| 391 |
+
|
| 392 |
+
tok_json = model_dir / "tokenizer.json"
|
| 393 |
+
if not tok_json.exists():
|
| 394 |
+
die(f"Missing tokenizer files: neither {tok_model} nor {tok_json} exists")
|
| 395 |
+
|
| 396 |
+
log("Converting tokenizer.json -> tokenizer.model")
|
| 397 |
+
cmd = [
|
| 398 |
+
sys.executable,
|
| 399 |
+
"-m",
|
| 400 |
+
"litert_torch.generative.tools.tokenizer_to_sentencepiece",
|
| 401 |
+
f"--checkpoint={model_dir}",
|
| 402 |
+
f"--output_path={tok_model}",
|
| 403 |
+
]
|
| 404 |
+
res = subprocess.run(cmd, text=True, capture_output=True)
|
| 405 |
+
if res.stdout:
|
| 406 |
+
print(res.stdout, flush=True)
|
| 407 |
+
if res.returncode != 0:
|
| 408 |
+
if res.stderr:
|
| 409 |
+
print(res.stderr, file=sys.stderr, flush=True)
|
| 410 |
+
die("Tokenizer conversion failed")
|
| 411 |
+
|
| 412 |
+
if not tok_model.exists():
|
| 413 |
+
die("Tokenizer conversion reported success but tokenizer.model is missing")
|
| 414 |
+
|
| 415 |
+
return tok_model
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def bundle_task(tflite_file: Path, tokenizer_model: Path, task_file: Path):
|
| 419 |
+
log(f"Bundling .task -> {task_file}")
|
| 420 |
+
from mediapipe.tasks.python.genai import bundler
|
| 421 |
+
|
| 422 |
+
task_file.parent.mkdir(parents=True, exist_ok=True)
|
| 423 |
+
|
| 424 |
+
sig = inspect.signature(bundler.BundleConfig)
|
| 425 |
+
params = sig.parameters
|
| 426 |
+
log(f"BundleConfig params: {list(params.keys())}")
|
| 427 |
+
|
| 428 |
+
kwargs = {
|
| 429 |
+
"tflite_model": str(tflite_file),
|
| 430 |
+
"tokenizer_model": str(tokenizer_model),
|
| 431 |
+
"output_filename": str(task_file),
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
if "start_token" in params:
|
| 435 |
+
kwargs["start_token"] = "<bos>"
|
| 436 |
+
elif "start_tokens" in params:
|
| 437 |
+
kwargs["start_tokens"] = ["<bos>"]
|
| 438 |
+
|
| 439 |
+
if "stop_tokens" in params:
|
| 440 |
+
kwargs["stop_tokens"] = ["<eos>"]
|
| 441 |
+
|
| 442 |
+
if "prompt_prefix" in params:
|
| 443 |
+
kwargs["prompt_prefix"] = ""
|
| 444 |
+
if "prompt_suffix" in params:
|
| 445 |
+
kwargs["prompt_suffix"] = ""
|
| 446 |
+
|
| 447 |
+
kwargs = {k: v for k, v in kwargs.items() if k in params}
|
| 448 |
+
cfg = bundler.BundleConfig(**kwargs)
|
| 449 |
+
bundler.create_bundle(cfg)
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def main():
|
| 453 |
+
ap = argparse.ArgumentParser(description="TranslateGemma -> Android .task converter")
|
| 454 |
+
|
| 455 |
+
ap.add_argument("--model-id", default="google/translategemma-4b-it")
|
| 456 |
+
ap.add_argument("--model-dir", default="./translategemma-4b-it")
|
| 457 |
+
ap.add_argument("--tflite-dir", default="./tflite_output")
|
| 458 |
+
ap.add_argument("--output-dir", default="./output")
|
| 459 |
+
ap.add_argument("--task-file", default="./output/translategemma-4b-it-android.task")
|
| 460 |
+
|
| 461 |
+
ap.add_argument("--quantize", default="dynamic_int8", help=f"One of: {sorted(SUPPORTED_QUANT)}")
|
| 462 |
+
|
| 463 |
+
ap.add_argument("--prefill-seq-len", "--prefill", dest="prefill_seq_len", type=int, default=1024)
|
| 464 |
+
ap.add_argument("--kv-cache-max-len", "--kvcache", dest="kv_cache_max_len", type=int, default=1024)
|
| 465 |
+
|
| 466 |
+
ap.add_argument("--skip-strategy1", action="store_true")
|
| 467 |
+
ap.add_argument("--bundle-only", action="store_true", help="Skip conversion; only bundle existing TFLite")
|
| 468 |
+
ap.add_argument("--existing-tflite", default="", help="Path to an existing .tflite to bundle")
|
| 469 |
+
ap.add_argument("--allow-no-token", action="store_true", help="Allow model download from public repo without HF_TOKEN")
|
| 470 |
+
|
| 471 |
+
args = ap.parse_args()
|
| 472 |
+
q = normalize_quantize(args.quantize)
|
| 473 |
+
|
| 474 |
+
hf_token = os.environ.get("HF_TOKEN", "").strip()
|
| 475 |
+
if not hf_token and not args.allow_no_token:
|
| 476 |
+
warn("HF_TOKEN is not set. If model is public, you can pass --allow-no-token.")
|
| 477 |
+
|
| 478 |
+
model_dir = Path(args.model_dir)
|
| 479 |
+
tflite_dir = Path(args.tflite_dir)
|
| 480 |
+
output_dir = Path(args.output_dir)
|
| 481 |
+
task_file = Path(args.task_file)
|
| 482 |
+
|
| 483 |
+
tflite_dir.mkdir(parents=True, exist_ok=True)
|
| 484 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 485 |
+
|
| 486 |
+
tflite_file = None
|
| 487 |
+
|
| 488 |
+
if args.bundle_only:
|
| 489 |
+
if not args.existing_tflite:
|
| 490 |
+
die("--bundle-only requires --existing-tflite /path/to/model.tflite")
|
| 491 |
+
tflite_file = Path(args.existing_tflite)
|
| 492 |
+
if not tflite_file.exists():
|
| 493 |
+
die(f"Existing tflite not found: {tflite_file}")
|
| 494 |
+
log(f"Bundle-only mode using: {tflite_file}")
|
| 495 |
+
# Apply post-TFLite quantization if requested
|
| 496 |
+
if q != "none":
|
| 497 |
+
try:
|
| 498 |
+
quantized = strategy3_post_tflite_quantize(tflite_file, tflite_dir, q)
|
| 499 |
+
if quantized:
|
| 500 |
+
tflite_file = quantized
|
| 501 |
+
log(f"Strategy 3 success: {tflite_file}")
|
| 502 |
+
else:
|
| 503 |
+
warn("Strategy 3 skipped; bundling input as-is")
|
| 504 |
+
except Exception as e:
|
| 505 |
+
warn(f"Strategy 3 failed: {e}")
|
| 506 |
+
traceback.print_exc()
|
| 507 |
+
else:
|
| 508 |
+
ensure_model_downloaded(args.model_id, model_dir, hf_token if hf_token else "")
|
| 509 |
+
arch = inspect_arch(model_dir)
|
| 510 |
+
model_type = arch["model_type"]
|
| 511 |
+
|
| 512 |
+
strategy1_succeeded = False
|
| 513 |
+
if not args.skip_strategy1:
|
| 514 |
+
try:
|
| 515 |
+
tflite_file = strategy1_litert_native(
|
| 516 |
+
model_dir=model_dir,
|
| 517 |
+
out_dir=tflite_dir,
|
| 518 |
+
model_type=model_type,
|
| 519 |
+
quantize=q,
|
| 520 |
+
prefill=args.prefill_seq_len,
|
| 521 |
+
kvcache=args.kv_cache_max_len,
|
| 522 |
+
)
|
| 523 |
+
if tflite_file:
|
| 524 |
+
log(f"Strategy 1 success: {tflite_file}")
|
| 525 |
+
strategy1_succeeded = True
|
| 526 |
+
except Exception as e:
|
| 527 |
+
warn(f"Strategy 1 failed: {e}")
|
| 528 |
+
traceback.print_exc()
|
| 529 |
+
|
| 530 |
+
if not tflite_file:
|
| 531 |
+
try:
|
| 532 |
+
tflite_file = strategy2_generic(
|
| 533 |
+
model_dir=model_dir,
|
| 534 |
+
out_dir=tflite_dir,
|
| 535 |
+
prefill=args.prefill_seq_len,
|
| 536 |
+
quantize=q,
|
| 537 |
+
)
|
| 538 |
+
if tflite_file:
|
| 539 |
+
log(f"Strategy 2 success: {tflite_file}")
|
| 540 |
+
warn("Generic TFLite may not have MediaPipe LLM prefill/decode signatures.")
|
| 541 |
+
except Exception as e:
|
| 542 |
+
warn(f"Strategy 2 failed: {e}")
|
| 543 |
+
traceback.print_exc()
|
| 544 |
+
|
| 545 |
+
# Strategy 3: post-TFLite quantization — only when Strategy 2 was used (Strategy 1
|
| 546 |
+
# already applies quantization natively via the converter).
|
| 547 |
+
if tflite_file and not strategy1_succeeded and q != "none":
|
| 548 |
+
try:
|
| 549 |
+
quantized = strategy3_post_tflite_quantize(tflite_file, tflite_dir, q)
|
| 550 |
+
if quantized:
|
| 551 |
+
tflite_file = quantized
|
| 552 |
+
log(f"Strategy 3 success: {tflite_file}")
|
| 553 |
+
else:
|
| 554 |
+
warn("Strategy 3 skipped; bundling unquantized model")
|
| 555 |
+
except Exception as e:
|
| 556 |
+
warn(f"Strategy 3 failed: {e}")
|
| 557 |
+
traceback.print_exc()
|
| 558 |
+
|
| 559 |
+
if not tflite_file:
|
| 560 |
+
die("All conversion strategies failed")
|
| 561 |
+
|
| 562 |
+
tokenizer_model = ensure_tokenizer_model(model_dir)
|
| 563 |
+
bundle_task(tflite_file, tokenizer_model, task_file)
|
| 564 |
+
|
| 565 |
+
log(f"DONE: {task_file}")
|
| 566 |
+
if task_file.exists():
|
| 567 |
+
log(f"Size: {task_file.stat().st_size / (1024 * 1024):.2f} MB")
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
if __name__ == "__main__":
|
| 571 |
+
main()
|