1. Overview
LiteRT-LM is Google's high-performance edge inference engine that runs LLMs across mobile, web, and desktop with CPU, GPU, and NPU acceleration.
In this codelab, you convert a fine-tuned MedGemma 2 E4B checkpoint to LiteRT, compile it ahead-of-time (AOT) for the Google Tensor G6 NPU (Pixel 11), and package it into a .litertlm bundle for on-device deployment. It takes a merged BF16 Hugging Face checkpoint as input (for example, after LoRA fine-tuning with GRPO or SFT, with the adapter merged into the base model).
This codelab is based on the accompanying Colab notebook on GitHub: .
Objective
In this codelab, you will:
- Convert: Quantize and convert the checkpoint to LiteRT.
- Compile: Compile the NPU models ahead-of-time for Google Tensor G6.
- Package: Package the models, tokenizer, and LiteRT-LM metadata into a
.litertlmbundle. - Upload (optional): Upload the bundle to a private Hugging Face repository.
What runs on NPU versus CPU
The final .litertlm bundle splits execution across the Google Tensor NPU and the CPU:
- NPU (
Tensor_G6): Text prefill-decode, vision encoder, audio encoder, and audio adapter. - CPU: Token embedder, per-layer embedder, auxiliary ops, vision adapter, and end-of-vision / end-of-audio markers.
Prerequisites
- Runtime: A Linux x86_64 machine (Python 3.11–3.13) with at least ~160 GB of RAM plus swap and ~150 GB of free disk space (hosted Colab runtimes, including A100 with High-RAM, don't have enough memory for conversion and compilation; connect Colab to a local runtime).
- Checkpoint: A merged BF16 Hugging Face checkpoint from your MedGemma 2 E4B fine-tuning run (including
config.jsonandtokenizer.model), not a standalone LoRA adapter. If you don't have one yet, start with one of the MedGemma 2 E4B fine-tuning Colabs (both merge the LoRA adapter into a BF16 checkpoint in Part B):- Fine-tune MedGemma 2 E4B on a text task (MedQA GRPO / SFT): Trains a LoRA adapter on clinical reasoning questions using GRPO reinforcement learning (or direct-answer SFT) and exports the merged checkpoint.
- Fine-tune MedGemma 2 E4B on a multimodal task (SCIN QLoRA SFT): Trains a 4-bit QLoRA adapter on dermatology images and patient context from the SCIN dataset and exports the merged checkpoint.
- Google Tensor SDK: Access to the Google Tensor SDK Beta and the downloaded compiler tar file (
litert_plugin_compiler.tar.gz). - Compiler options: The
Tensor_G6binary.pbcompiler options files from the MedGemma 2 LiteRT-LM repository on Hugging Face. - Estimated time: Conversion takes several hours.
2. Get started and install packages
Before running the conversion and compilation steps, download the Google Tensor compiler tar file (litert_plugin_compiler.tar.gz) from your Google Tensor SDK Beta approval email and place it on your local Linux machine.
Install base dependencies
Install the libraries used to read the checkpoint:
# No GPU is needed. The CPU-only PyTorch build avoids downloading the much larger CUDA packages.
%pip install -q -U torch --index-url https://download.pytorch.org/whl/cpu
%pip install -q -U "transformers>=5.15.0,<5.24.0" safetensors
Install the conversion and Google Tensor compiler packages
Set GOOGLE_TENSOR_SDK_TARBALL to the local path of your downloaded compiler tar file and install the packages for LiteRT conversion and quantization, AOT compilation for Google Tensor, and LiteRT-LM bundle packaging:
import os
GOOGLE_TENSOR_SDK_TARBALL = "/content/litert_plugin_compiler.tar.gz" # @param {type:"string"}
GOOGLE_TENSOR_SDK_TARBALL = os.path.abspath(os.path.expanduser(GOOGLE_TENSOR_SDK_TARBALL))
assert os.path.isfile(GOOGLE_TENSOR_SDK_TARBALL), (
f"Google Tensor SDK tarball not found at {GOOGLE_TENSOR_SDK_TARBALL}."
)
os.environ["GOOGLE_TENSOR_SDK_BETA"] = GOOGLE_TENSOR_SDK_TARBALL
%pip install -q -U --pre tf-nightly
%pip install -q -U --pre "litert-torch-nightly>=0.11.0.dev20261023" litert-quantizer-nightly ai-edge-litert-nightly
# litert-torch-nightly and litert-quantizer-nightly also install litert-lm-builder-nightly, which provides the same
# Python module as litert-lm-builder. Remove it, then reinstall the pinned release so that its files are the ones used.
%pip uninstall -q -y litert-lm-builder-nightly
%pip install -q --force-reinstall --no-deps "litert-lm-builder==0.20.1"
# --no-cache-dir so pip rebuilds the SDK package from the tarball instead of reusing a cached build.
# --no-deps so the reinstall doesn't change the packages installed above.
%pip install -q -U --pre --no-cache-dir --force-reinstall --no-deps ai-edge-litert-sdk-google-tensor-nightly
from importlib import metadata
for _pkg in ("tf-nightly", "litert-torch-nightly", "litert-quantizer-nightly", "litert-lm-builder",
"ai-edge-litert-nightly", "ai-edge-litert-sdk-google-tensor-nightly"):
print(f"{_pkg:42} {metadata.version(_pkg)}")
_litert = metadata.version("ai-edge-litert-nightly")
_sdk = metadata.version("ai-edge-litert-sdk-google-tensor-nightly")
assert _litert == _sdk, f"ai-edge-litert-nightly ({_litert}) and ai-edge-litert-sdk-google-tensor-nightly ({_sdk}) differ."
# Step 6 runs the litert-torch command-line tool. Put the one installed for this kernel first on PATH.
import sys
os.environ["PATH"] = os.path.dirname(sys.executable) + os.pathsep + os.environ["PATH"]
import ai_edge_litert_sdk_google_tensor as gt_sdk
print(f"Google Tensor compiler libraries: {gt_sdk.path_to_sdk_libs()}")
Verify that the Google Tensor compiler plugin from ai-edge-litert-sdk-google-tensor-nightly is active before starting the long conversion step:
import os
# ai-edge-litert-sdk-google-tensor-nightly ships the Google Tensor compiler plugin, and aot_compile (Step 7) loads it
# from there. Older ai-edge-litert versions bundle an outdated plugin, so stop here,
# before the long conversion, if that one would be used.
os.environ.setdefault("GOOGLE_TENSOR_BACKEND_ENABLED", "1") # Must be set before importing ai_edge_litert.aot.
from ai_edge_litert.aot.core import common as aot_common
from ai_edge_litert.aot.vendors.google_tensor import google_tensor_backend
_plugin = str(aot_common.get_resource(google_tensor_backend.COMPILER_PLUGIN_LIB_PATH))
print(f"Google Tensor compiler plugin: {_plugin}")
assert "ai_edge_litert_sdk_google_tensor" in _plugin, (
"aot_compile would use the outdated plugin bundled in ai-edge-litert. Install matching ai-edge-litert-nightly "
"and ai-edge-litert-sdk-google-tensor-nightly versions, then re-run Step 4."
)
3. Point to your fine-tuned checkpoint
Set the path to your merged checkpoint in Hugging Face format, including its tokenizer files (tokenizer.model). A LoRA adapter on its own won't work, so merge it into the base checkpoint first.
import os
MERGED_MODEL_DIR = "/content/tuned_medgemma2_e4b_merged_hf" # @param {type:"string"}
assert os.path.isfile(os.path.join(MERGED_MODEL_DIR, "config.json")), (
f"No config.json in {MERGED_MODEL_DIR}. Point MERGED_MODEL_DIR at the merged checkpoint folder."
)
assert os.path.isfile(os.path.join(MERGED_MODEL_DIR, "tokenizer.model")), (
f"No tokenizer.model in {MERGED_MODEL_DIR}. The merged checkpoint must include the SentencePiece tokenizer."
)
print(f"Merged checkpoint dir: {MERGED_MODEL_DIR}")
4. Configure conversion settings and quantization recipes
Copy the MedGemma 2 E4B quantization recipes for the text decoder and audio encoder from the Google Tensor SDK SLM compilation page, save each one as a JSON file on your machine, and set their paths below along with the output folder. The vision encoder uses the built-in dynamic_wi8c_afp32 recipe.
import json
import os
EXPORT_ROOT = "/content/exports/medgemma2_e4b" # @param {type:"string"}
TEXT_QUANT_RECIPE = "/content/quant_recipes/quantization_recipe_text.json" # @param {type:"string"}
AUDIO_QUANT_RECIPE = "/content/quant_recipes/quantization_recipe_audio.json" # @param {type:"string"}
VISION_QUANT_RECIPE = "dynamic_wi8c_afp32"
for _recipe in (TEXT_QUANT_RECIPE, AUDIO_QUANT_RECIPE):
assert os.path.isfile(_recipe), f"Quantization recipe not found: {_recipe}"
with open(_recipe) as f:
json.load(f) # Fails early if the file isn't valid JSON (for example, a page saved as HTML).
EXPORT_DIR = os.path.join(EXPORT_ROOT, "mm")
os.makedirs(EXPORT_DIR, exist_ok=True)
print(f"Export dir : {EXPORT_DIR}")
print(f"Text quant recipe : {TEXT_QUANT_RECIPE}")
print(f"Audio quant recipe : {AUDIO_QUANT_RECIPE}")
print(f"Vision quant recipe : {VISION_QUANT_RECIPE}")
5. Post-training quantization (PTQ) and LiteRT conversion
Convert the merged checkpoint into quantized LiteRT models: the text decoder with the MedGemma 2 NPU quantization recipe and up to an 8,192-token context window, and the vision and audio encoders with 8-bit weights. LiteRT-LM metadata comes from the LiteRT-LM repository.
import subprocess
subprocess.run([
"litert-torch", "export_hf",
f"--model={MERGED_MODEL_DIR}", "--task=multimodal_lm", "--use_v2=True",
"--split_cache", "--externalize_embedder", "--keep_temporary_files",
"--prefill_lengths=128,", "--cache_lengths=640,1024,1536,4096,6144,8192",
"--cache_length=8192", "--sliding_window_ring_buffer_size=512",
f"--quantization_recipe={TEXT_QUANT_RECIPE}",
f"--vision_encoder_quantization_recipe={VISION_QUANT_RECIPE}",
f"--audio_encoder_quantization_recipe={AUDIO_QUANT_RECIPE}",
"--gemma4_vision_token_budgets=280,560,1120",
"--use_sdpa_composite_for_vision=True",
"--litert_lm_llm_metadata_override=gemma4",
f"--output_dir={EXPORT_DIR}",
], check=True)
import os
print(sorted(os.listdir(EXPORT_DIR)))
6. Compile ahead-of-time for Google Tensor
Download the compiler options files (binary .pb) from the MedGemma 2 LiteRT-LM repository on Hugging Face, and set their paths below. Then compile the text decoder, vision encoder, and audio encoder and adapter for the Google Tensor G6 system-on-chip (SoC).
Model | Exported | Compiler options |
Text (prefill-decode) |
|
|
Vision encoder |
|
|
Audio encoder |
|
|
Audio adapter |
| Compiler defaults |
import glob
import os
import shutil
import tempfile
SOC_MODEL = "Tensor_G6"
TEXT_COMPILER_OPTIONS = "/content/compiler_options/compiler_options_text_w435b.pb" # @param {type:"string"}
VISION_ENCODER_COMPILER_OPTIONS = "/content/compiler_options/compiler_options_vision_encoder.pb" # @param {type:"string"}
AUDIO_ENCODER_COMPILER_OPTIONS = "/content/compiler_options/compiler_options_audio_encoder.pb" # @param {type:"string"}
for _options in (TEXT_COMPILER_OPTIONS, VISION_ENCODER_COMPILER_OPTIONS, AUDIO_ENCODER_COMPILER_OPTIONS):
assert os.path.isfile(_options), f"Compiler options file not found: {_options}"
# Must be set before importing ai_edge_litert.aot.
os.environ.setdefault("GOOGLE_TENSOR_BACKEND_ENABLED", "1")
from ai_edge_litert.aot import aot_compile as aot_lib
from ai_edge_litert.aot.vendors.google_tensor import target as gt_target
def _pick(directory: str, stem: str) -> str | None:
"""Returns `<stem>_quantized.tflite` if present, else `<stem>.tflite`, else None."""
for name in (f"{stem}_quantized.tflite", f"{stem}.tflite"):
path = os.path.join(directory, name)
if os.path.isfile(path):
return path
return None
def compile_for_google_tensor(src: str, **compiler_kwargs) -> str:
"""AOT-compiles `src` for `SOC_MODEL` into `COMPILED_DIR` with the given `google_tensor_*` options."""
stem = os.path.basename(src)[: -len(".tflite")]
dst = os.path.join(COMPILED_DIR, f"{stem}_Google_{SOC_MODEL}.tflite")
print(f"Compiling {src} for {SOC_MODEL} ({compiler_kwargs or 'compiler defaults'}) ...")
# Keep the compiler's multi-GB temporary files on the export disk instead of /tmp.
with tempfile.TemporaryDirectory(dir=COMPILED_DIR) as work_dir:
_saved_tempdir = tempfile.tempdir
tempfile.tempdir = work_dir
try:
result = aot_lib.aot_compile(
src,
output_dir=work_dir,
target=gt_target.Target(gt_target.SocModel(SOC_MODEL)),
**compiler_kwargs,
)
finally:
tempfile.tempdir = _saved_tempdir
print(result.compilation_report())
if result.failed_backends or not result.models_with_backend:
# Copy the compiler's error logs out of work_dir before it is deleted.
error_logs = []
for log in glob.glob(os.path.join(work_dir, "**", "*.error"), recursive=True):
error_logs.append(shutil.copy(log, COMPILED_DIR))
raise RuntimeError(
f"Google Tensor compilation failed for {src}: {result.failed_backends}. Error logs: {error_logs}"
)
_, compiled_model = result.models_with_backend[0]
# Move the compiled file (a rename on the same disk) instead of copying it through memory.
if compiled_model.in_memory:
compiled_model.save(dst, export_only=True)
else:
shutil.move(str(compiled_model.path), dst)
print(f"[OK] {dst} ({os.path.getsize(dst) / 1e6:.2f} MB)")
return dst
COMPILED_DIR = os.path.join(EXPORT_ROOT, f"compiled_{SOC_MODEL}")
os.makedirs(COMPILED_DIR, exist_ok=True)
PREFILL_DECODE_MODEL = _pick(EXPORT_DIR, "model")
VISION_ENCODER_MODEL = _pick(EXPORT_DIR, "vision_encoder")
AUDIO_ENCODER_MODEL = _pick(EXPORT_DIR, "audio_encoder")
AUDIO_ADAPTER_MODEL = _pick(EXPORT_DIR, "audio_adapter")
for _name, _path in (("prefill-decode", PREFILL_DECODE_MODEL), ("vision encoder", VISION_ENCODER_MODEL),
("audio encoder", AUDIO_ENCODER_MODEL), ("audio adapter", AUDIO_ADAPTER_MODEL)):
assert _path, f"No {_name} .tflite found in {EXPORT_DIR}."
COMPILED_PREFILL_DECODE = compile_for_google_tensor(
PREFILL_DECODE_MODEL, google_tensor_extra_options_path=os.path.abspath(TEXT_COMPILER_OPTIONS)
)
COMPILED_VISION_ENCODER = compile_for_google_tensor(
VISION_ENCODER_MODEL, google_tensor_extra_options_path=os.path.abspath(VISION_ENCODER_COMPILER_OPTIONS)
)
COMPILED_AUDIO_ENCODER = compile_for_google_tensor(
AUDIO_ENCODER_MODEL,
google_tensor_extra_options_path=os.path.abspath(AUDIO_ENCODER_COMPILER_OPTIONS),
google_tensor_sharding_intensity="minimal",
)
COMPILED_AUDIO_ADAPTER = compile_for_google_tensor(AUDIO_ADAPTER_MODEL)
7. Package the LiteRT-LM bundle
Package the compiled NPU models, the CPU models, the tokenizer, and the LiteRT-LM metadata into a self-contained .litertlm bundle using the litert_lm_builder Python API.
import math
import os
from google.protobuf import text_format
from litert_lm_builder.runtime.proto import executor_metadata_pb2, llm_metadata_pb2, sampler_params_pb2
TPU_BUNDLE_PATH = os.path.join(EXPORT_ROOT, f"medgemma2_e4b_Google_{SOC_MODEL}.litertlm")
# Opt-in non-greedy (TOP_P) CPU sampling inside the NPU executor.
# When False, the NPU executor decodes greedily and ignores sampler_params.
ENABLE_NPU_NON_GREEDY_SAMPLING = False # @param {type:"boolean"}
# Sampler parameters written to LlmMetadata.sampler_params (type stays TOP_P).
SAMPLER_TOP_K = 64 # @param {type:"integer"}
SAMPLER_TOP_P = 0.95 # @param {type:"number"}
SAMPLER_TEMPERATURE = 1.0 # @param {type:"number"}
assert SAMPLER_TOP_K > 0, "SAMPLER_TOP_K must be > 0"
assert 0.0 < SAMPLER_TOP_P <= 1.0, "SAMPLER_TOP_P must be in (0, 1]"
assert SAMPLER_TEMPERATURE > 0.0, "SAMPLER_TEMPERATURE must be > 0"
assert math.isfinite(SAMPLER_TOP_P) and math.isfinite(SAMPLER_TEMPERATURE), "Sampler values must be finite"
sections = []
# LlmMetadata from the export (Step 6), with this notebook's vision patch limit and sampler values.
_llm_metadata = llm_metadata_pb2.LlmMetadata()
with open(os.path.join(EXPORT_DIR, "llm_metadata.pb"), "rb") as f:
_llm_metadata.ParseFromString(f.read())
assert _llm_metadata.llm_model_type.HasField("gemma4") and _llm_metadata.jinja_prompt_template, (
"llm_metadata.pb is not the Gemma 4 LiteRT-LM config; check that the export could fetch it."
)
_llm_metadata.llm_model_type.gemma4.max_num_patches = 10080 # 280/560/1120 vision token budgets
if ENABLE_NPU_NON_GREEDY_SAMPLING:
# enable_npu_non_greedy_sampling for NPU first ships in LiteRT-LM 0.20.1.
_llm_metadata.min_runtime_version = "0.20.1"
_sp = _llm_metadata.sampler_params
_sp.type = sampler_params_pb2.SamplerParameters.TOP_P
_sp.k = int(SAMPLER_TOP_K)
_sp.p = float(SAMPLER_TOP_P)
_sp.temperature = float(SAMPLER_TEMPERATURE)
LLM_METADATA_PBTEXT = os.path.join(EXPORT_DIR, "LlmMetadataProto.pbtext")
with open(LLM_METADATA_PBTEXT, "w") as f:
f.write(text_format.MessageToString(_llm_metadata))
print(f"[OK] Wrote {LLM_METADATA_PBTEXT} (max_num_tokens={_llm_metadata.max_num_tokens}, "
f"max_num_patches={_llm_metadata.llm_model_type.gemma4.max_num_patches}, "
f"sampler: k={_sp.k}, p={_sp.p:g}, temperature={_sp.temperature:g})")
sections.append({"section_type": "LlmMetadata", "data_path": LLM_METADATA_PBTEXT})
# Tokenizer from the checkpoint folder.
TOKENIZER_MODEL = os.path.join(MERGED_MODEL_DIR, "tokenizer.model")
assert os.path.isfile(TOKENIZER_MODEL), f"Not found: {TOKENIZER_MODEL}"
sections.append({"section_type": "SP_Tokenizer", "data_path": TOKENIZER_MODEL})
# ExecutorMetadata: the exported binary executor_metadata.pb with the NPU executor block set, written as text.
EXECUTOR_METADATA_PB = os.path.join(EXPORT_DIR, "executor_metadata.pb")
EXECUTOR_METADATA_PBTEXT = os.path.join(EXPORT_DIR, "ExecutorMetadataProto.pbtext")
assert os.path.isfile(EXECUTOR_METADATA_PB), f"Not found: {EXECUTOR_METADATA_PB}"
_executor_metadata = executor_metadata_pb2.ExecutorMetadata()
with open(EXECUTOR_METADATA_PB, "rb") as f:
_executor_metadata.ParseFromString(f.read())
# Only one llm_npu_executor_metadata block is allowed: replace the exported one, if any.
if _executor_metadata.HasField("llm_npu_executor_metadata"):
print(f"[WARNING] {EXECUTOR_METADATA_PB} already has an llm_npu_executor_metadata block; replacing it:\n"
f"{_executor_metadata.llm_npu_executor_metadata}")
_executor_metadata.ClearField("llm_npu_executor_metadata")
_npu = _executor_metadata.llm_npu_executor_metadata
_npu.enable_neon_for_npu_greedy_sampling = True
_npu.use_hw_masking_for_npu = True
_npu.use_hw_cache_update_for_npu = True
_npu.use_hw_ple_for_npu = False
if ENABLE_NPU_NON_GREEDY_SAMPLING:
_npu.enable_npu_non_greedy_sampling = True
print(f"llm_npu_executor_metadata:\n{_npu}")
with open(EXECUTOR_METADATA_PBTEXT, "w") as f:
f.write(text_format.MessageToString(_executor_metadata))
sections.append({"section_type": "ExecutorMetadata", "data_path": EXECUTOR_METADATA_PBTEXT})
# CPU models from the export folder (all required).
for _model_type, _stem in (
("EMBEDDER", "embedder"),
("PER_LAYER_EMBEDDER", "per_layer_embedder"),
("AUX", "auxiliary"),
("VISION_ADAPTER", "vision_adapter"),
("END_OF_VISION", "eoi"),
("END_OF_AUDIO", "eoa"),
):
_path = _pick(EXPORT_DIR, _stem)
assert _path is not None, f"No {_stem} .tflite found in {EXPORT_DIR} (needed for the {_model_type} section)."
sections.append({"section_type": "TFLiteModel", "model_type": _model_type, "data_path": _path})
# NPU models compiled for Google Tensor in Step 7.
for _model_type, _path in (
("AUDIO_ENCODER_HW", COMPILED_AUDIO_ENCODER),
("AUDIO_ADAPTER", COMPILED_AUDIO_ADAPTER),
("VISION_ENCODER", COMPILED_VISION_ENCODER),
("PREFILL_DECODE", COMPILED_PREFILL_DECODE),
):
sections.append({"section_type": "TFLiteModel", "model_type": _model_type, "data_path": _path,
"backend_constraint": "npu"})
from litert_lm_builder import litertlm_builder
# Add each section to the bundle with the litert_lm_builder Python API.
builder = litertlm_builder.LitertLmFileBuilder()
for section in sections:
if section["section_type"] == "LlmMetadata":
builder.add_llm_metadata(section["data_path"])
elif section["section_type"] == "SP_Tokenizer":
builder.add_sentencepiece_tokenizer(section["data_path"])
elif section["section_type"] == "ExecutorMetadata":
builder.add_executor_metadata(section["data_path"])
else:
builder.add_tflite_model(section["data_path"], section["model_type"],
backend_constraint=section.get("backend_constraint"))
print(section)
with open(TPU_BUNDLE_PATH, "wb") as f:
builder.build(f, weights_in_model_graph=True)
print(f"[OK] Google Tensor bundle: {TPU_BUNDLE_PATH} ({os.path.getsize(TPU_BUNDLE_PATH) / 1e6:.2f} MB)")
8. Upload to a private Hugging Face repository (optional)
Upload the .litertlm bundle to a private Hugging Face repository. To upload, set UPLOAD_TO_PRIVATE_HF = True, set PRIVATE_HF_REPO_ID, and run the cell; paste a Hugging Face token with Write permission when prompted (the token isn't saved).
import getpass
import os
UPLOAD_TO_PRIVATE_HF = False # @param {type:"boolean"}
PRIVATE_HF_REPO_ID = "your-hf-username/medgemma2-e4b-google-tensor-litertlm" # @param {type:"string"}
if not UPLOAD_TO_PRIVATE_HF:
print("[SKIP] UPLOAD_TO_PRIVATE_HF is False.")
else:
# Ask for the token on every run; it isn't saved in the notebook or the environment.
hf_token = getpass.getpass("Hugging Face token (Write permission): ").strip()
if not hf_token:
raise RuntimeError("No Hugging Face token entered. Re-run this cell and paste a token with Write permission.")
from huggingface_hub import HfApi
api = HfApi(token=hf_token)
namespace, _, repo_name = PRIVATE_HF_REPO_ID.strip().strip("/").partition("/")
if not repo_name:
namespace, repo_name = "", namespace
if not namespace or namespace == "your-hf-username":
namespace = api.whoami()["name"]
repo_id = f"{namespace}/{repo_name or 'medgemma2-e4b-google-tensor-litertlm'}"
# Create the repository as private. Never change the visibility of an existing repository.
if api.repo_exists(repo_id=repo_id, repo_type="model"):
if not api.repo_info(repo_id=repo_id, repo_type="model").private:
raise RuntimeError(f"Refusing to upload: {repo_id} already exists and is public.")
else:
api.create_repo(repo_id=repo_id, repo_type="model", private=True)
if not api.repo_info(repo_id=repo_id, repo_type="model").private:
raise RuntimeError(f"Refusing to upload to a Hugging Face repository that isn't private: {repo_id}")
print(f"[OK] Private repository: https://huggingface.co/{repo_id}")
# The Google Tensor bundle from Step 8.
print(f"Uploading {TPU_BUNDLE_PATH} ({os.path.getsize(TPU_BUNDLE_PATH) / 1e6:.2f} MB) ...")
api.upload_file(path_or_fileobj=TPU_BUNDLE_PATH, path_in_repo=os.path.basename(TPU_BUNDLE_PATH),
repo_id=repo_id, repo_type="model")
print(f"[OK] https://huggingface.co/{repo_id}/blob/main/{os.path.basename(TPU_BUNDLE_PATH)}")
9. Next steps
Congratulations!
You have converted, AOT-compiled, and packaged your fine-tuned MedGemma 2 E4B model into medgemma2_e4b_Google_Tensor_G6.litertlm.
litert-google-tensorskill: Benchmark the compiled models on a Pixel 11.- Google AI Edge Gallery: Import the
.litertlmbundle on Pixel 11 for on-device deployment. - Compile SLMs for Google Tensor: Explore additional supported models and compilation options.