1. खास जानकारी
Google Tensor SDK का इस्तेमाल, Pixel डिवाइसों के लिए LiteRT मॉडल को कंपाइल करने के लिए किया जाता है. कंपाइल किए गए मॉडल को Pixel डिवाइसों पर डिप्लॉय किया जा सकता है, ताकि एमएल इन्फ़्रेंस की परफ़ॉर्मेंस को बेहतर बनाया जा सके. एसडीके का इस्तेमाल करने के लिए, आपको पहले अपने मॉडल को LiteRT (tflite) मॉडल में बदलना होगा.
यह कोडलैब, GitHub पर मौजूद सामान्य कोडलैब पर आधारित है. इसका नाम है, LiteRT AOT कंपाइलेशन ट्यूटोरियल कोडलैब:.
मकसद
इस कोडलैब में, LiteRT AOT (ऐड ऑफ़ टाइम) कंपाइलर का इस्तेमाल करके, TFLite मॉडल से सेल्फ़ी सेगमेंटेशन मॉडल को LiteRT मॉडल में कंपाइल करने का तरीका बताया गया है. यह मॉडल, डिवाइस पर मौजूद EdgeTPU के लिए ऑप्टिमाइज़ और कंपाइल किया गया है.
इस कोलाब में, Play for On-device AI (PODAI) की मदद से मॉडल तैयार करने का तरीका भी बताया गया है.
PODAI, डिवाइस पर एआई की सुविधाओं के लिए कस्टम मॉडल को ज़्यादा बेहतर तरीके से डिलीवर करता है. इससे एआई मॉडल को लॉन्च करने, टारगेट करने, वर्शन बनाने, और डाउनलोड करने की प्रोसेस आसान हो जाती है. LiteRT EdgeTPU AOT कंपाइलेशन के साथ मिलकर काम करने पर, यह डेवलपर को अलग-अलग डिवाइसों के लिए कंपाइल किए गए एमएल मॉडल डिलीवर करने की सुविधा देता है. इसके लिए, यह जानना ज़रूरी नहीं है कि फ़ोन में कौनसे EdgeTPU मौजूद हैं.
इस्तेमाल किए गए मॉडल
हम जिन मॉडल का इस्तेमाल कर रहे हैं उन्हें MediaPipe की इमेज सेगमेंटेशन गाइड में पब्लिश किया गया है. इस कोडलैब में इस्तेमाल किए गए मॉडल के बारे में यहां कुछ जानकारी दी गई है:
SelfieMulticlass: यह एक LiteRT मॉडल है. यह किसी व्यक्ति की इमेज लेता है, बाल, त्वचा, और कपड़ों जैसी जगहों का पता लगाता है, और इन आइटम के लिए इमेज सेगमेंटेशन मैप आउटपुट करता है.
2. अपनी प्रोफ़ाइल बनाना शुरू करें
Google Tensor SDK का ऐक्सेस पाने और इसका इस्तेमाल शुरू करने के लिए, यह तरीका अपनाएं:
- Google Tensor SDK का ऐक्सेस पाने के लिए, साइन अप करें. आगे बढ़ने से पहले, आपको Google से एक ईमेल मिलेगा. इसमें कंपाइलर प्लगिन को डाउनलोड करने का लिंक होगा.
- कंपाइलर प्लगिन (litert_plugin_compiler.tar.gz) डाउनलोड करें और इसे अपनी पसंद के फ़ोल्डर में रखें.
- डाउनलोड की गई फ़ाइल के लोकल सिस्टम पाथ,
GOOGLE_TENSOR_SDK_BETAपर एनवायरमेंट वैरिएबल सेट करें.
इस कमांड को बैश टर्मिनल पर चलाया जा सकता है: इसके अलावा, इसे अपनी Colab नोटबुक में भी चलाया जा सकता है:export GOOGLE_TENSOR_SDK_BETA=/path/to/downloaded/compiler%env GOOGLE_TENSOR_SDK_BETA=/path/to/downloaded/compiler - इसके बाद, पैकेज इंस्टॉल करने के लिए यह कमांड चलाएं:
pip install ai-edge-litert-sdk-google-tensor
3. ज़रूरी पैकेज इंस्टॉल करना
ज़रूरी पैकेज इंस्टॉल करके शुरू करें. इनमें ai-edge-litert-nightly शामिल है, जिसमें EdgeTPU AOT कंपाइलर होता है. साथ ही, इसमें मॉडल कन्वर्ज़न के लिए इस्तेमाल की जाने वाली अन्य लाइब्रेरी भी होती हैं.
Google Tensor के लिए LiteRT बैकएंड इंस्टॉल करने के लिए, इस पैकेज का इस्तेमाल करें: ai-edge-litert-sdk-google-tensor.
पैकेज इंस्टॉल करने के बाद, सेशन को रीस्टार्ट करें और इंस्टॉलेशन के चरणों से आगे बढ़ें. इंस्टॉल करने की प्रोसेस को दोबारा न करें.
अगर आपको अपने सिस्टम पर सेटअप करना है, तो हमारा सुझाव है कि Python वर्चुअल एनवायरमेंट (venv) का इस्तेमाल करें. साथ ही, इन कमांड को वर्चुअल एनवायरमेंट में चलाएं.
कुछ पैकेज अनइंस्टॉल करना
इससे पहले, Colab रनटाइम के साथ डिफ़ॉल्ट रूप से आने वाले TensorFlow को अनइंस्टॉल करें.
pip uninstall -y tensorflow ai-edge-litert
सभी लाइब्रेरी इंस्टॉल करना
Google Tensor के लिए LiteRT बैकएंड इंस्टॉल करना
pip install ai-edge-litert-sdk-google-tensor
बचे हुए पैकेज इंस्टॉल करना
pip install matplotlib huggingface-hub ai-edge-litert-nightly
4. सभी लाइब्रेरी इंपोर्ट करना
इंस्टॉल पूरा होने के बाद, मुख्य प्रोग्राम को चलाने की प्रोसेस शुरू करें.
ज़रूरी पैकेज इंपोर्ट करें:
import os
import shutil
from ai_edge_litert.aot import aot_compile as aot_lib
from ai_edge_litert.aot.ai_pack import export_lib as ai_pack_export
from ai_edge_litert.aot.vendors.google_tensor import target as gt_target
import huggingface_hub
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import requests
5. LiteRT मॉडल को कंपाइल करना
इस सेक्शन में, सीधे तौर पर LiteRT (TFLite) मॉडल को कंपाइल करने जैसे ऐडवांस इस्तेमाल के बारे में बताया गया है.
TFLite मॉडल से EdgeTPU कंपाइलेशन
इस चरण के लिए, TFLite मॉडल की ज़रूरत होती है. अगर आपके पास TFLite मॉडल नहीं है, तो अपने मॉडल को TFLite फ़ॉर्मैट में बदलें.
TFLite मॉडल पाना
हम इस मामले में, MediaPipe MultiClass Segmentation मॉडल का इस्तेमाल करते हैं.
TFLite मॉडल, MediaPipe Image segmentation पेज पर उपलब्ध है.
work_dir = '.'
model_url = 'https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_multiclass_256x256/float32/latest/selfie_multiclass_256x256.tflite'
tflite_model_path = os.path.join(work_dir, 'selfie_multiclass_256x256.tflite')
model_content = requests.get(model_url)
with open(tflite_model_path, 'wb') as fout:
fout.write(model_content.content)
LiteRT Python API का इस्तेमाल करके, TfLite मॉडल की तुरंत पुष्टि करना
यहां दिए गए उदाहरण में, आपको मास्क की गई इमेज और ब्लेंड किया गया नतीजा, दोनों दिखेंगे.
# Downloading Testing image
test_image = huggingface_hub.hf_hub_download(
repo_id="litert-community/MediaPipe-Selfie-Segmentation",
filename="test_img.png",
)
pil_image = Image.open(test_image).convert("RGB").resize((256, 256))
from ai_edge_litert.compiled_model import CompiledModel
SEGMENT_COLORS = [
(0, 0, 0),
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 255, 0),
(255, 0, 255),
]
INPUT_SIZE = (256, 256)
NUM_CLASSES = 6
# Load the model and image
model = CompiledModel.from_file(tflite_model_path)
original_image = np.array(Image.open(test_image).convert('RGB'))
img_array = np.array(pil_image).astype(np.float32)
# Normalize the image
normalized = (img_array - 127.5) / 127.5
normalized = np.ascontiguousarray(normalized, dtype=np.float32)
# Run inference
sig_idx = 0
input_buffers = model.create_input_buffers(sig_idx)
output_buffers = model.create_output_buffers(sig_idx)
input_data = normalized.reshape(-1)
input_buffers[0].write(input_data)
model.run_by_index(sig_idx, input_buffers, output_buffers)
# Get output data
height, width = INPUT_SIZE
output_size = height * width * NUM_CLASSES
output_data = output_buffers[0].read(output_size, np.float32)
output_data = output_data.reshape(height, width, NUM_CLASSES)
mask = np.argmax(output_data, axis=2).astype(np.uint8)
# Create colored mask
colored_mask = np.zeros((height, width, 3), dtype=np.uint8)
for label_idx in range(NUM_CLASSES):
class_mask = mask == label_idx
color = SEGMENT_COLORS[label_idx]
colored_mask[class_mask] = color
# Blend with original image
# Resize colored mask to match original image if necessary
if original_image.shape[:2] != colored_mask.shape[:2]:
colored_mask_pil = Image.fromarray(colored_mask)
colored_mask_pil = colored_mask_pil.resize(
(original_image.shape[1], original_image.shape[0])
)
colored_mask = np.array(colored_mask_pil)
# Blend images with alpha 0.5
alpha = 0.5
blended_image = (
original_image * (1 - alpha) + colored_mask * alpha
).astype(np.uint8)
# Display them
fig, axes = plt.subplots(1, 3, figsize=(9, 3))
for idx, (title, image) in enumerate([
('Original Image', original_image),
('Colored Mask', colored_mask),
('Blended Image', blended_image),
]):
axes[idx].imshow(image)
axes[idx].set_title(title)
axes[idx].axis('off')
plt.tight_layout()
plt.show()
EdgeTPU AOT कंपाइलेशन के साथ, LiteRT मॉडल में बदलें.
हम मॉडल को कंपाइल करने के लिए, ai_edge_litert.aot के एपीआई का इस्तेमाल करते हैं.
compiled_models = aot_lib.aot_compile(tflite_model_path, keep_going=True)
# This variable will be used later to create the AI Pack.
all_google_tensor_compiled_models = compiled_models
# Print Compilation Report
print(all_google_tensor_compiled_models.compilation_report())
# Saving compiled models to disk. This saves all the compiled models, and a CPU
# fallback model.
all_google_tensor_compiled_models.export(
work_dir, model_name='selfie_segmentation'
)
कंपाइलेशन पूरा होने के बाद, सभी मॉडल को डिस्क में एक्सपोर्ट करने के लिए model.export तरीके का इस्तेमाल करें.
डिफ़ॉल्ट रूप से, मॉडल को आउटपुट डायरेक्ट्री में फ़्लैट स्ट्रक्चर में सेव किया जाता है. हर मॉडल के नाम के आखिर में बैकएंड आईडी जोड़ा जाता है.
उदाहरण के लिए:
मॉडल का फ़ाइल नाम | बैकएंड | SoC | नोट |
selfie_segmentation_fallback.tflite | CPU/GPU | लागू नहीं | लागू नहीं |
selfie_segmentation_Google_Tensor_G3.tflite | Tensor_G3 | Google Tensor G3 | |
selfie_segmentation_Google_Tensor_G4.tflite | Tensor_G4 | Google Tensor G4 | |
selfie_segmentation_Google_Tensor_G5.tflite | Tensor_G5 | Google Tensor G5 |
6. सीपीयू पर एक्सपोर्ट और पुष्टि करना
कंपाइल करने की प्रोसेस पूरी होने के बाद, सीपीयू पर TFLite मॉडल की पुष्टि करें. कंपाइलेशन के दौरान जनरेट किए गए "फ़ॉलबैक मॉडल" का इस्तेमाल करके ऐसा करें.
# Run LiteRT with test image
from ai_edge_litert.compiled_model import CompiledModel
# Normalize the image to [-1, 1]
img_array = np.array(pil_image, dtype=np.float32)
normalized = (img_array - 127.5) / 127.5
numpy_array = np.ascontiguousarray(normalized)[None, ...]
cpu_model_path = os.path.join(work_dir, "selfie_segmentation_fallback.tflite")
cm_model = CompiledModel.from_file(cpu_model_path)
sig_idx = 0
input_buffers = cm_model.create_input_buffers(sig_idx)
output_buffers = cm_model.create_output_buffers(sig_idx)
input_buffers[0].write(numpy_array)
cm_model.run_by_index(sig_idx, input_buffers, output_buffers)
# Read the 6-channel output and apply argmax
output_data = output_buffers[0].read(256 * 256 * 6, np.float32)
output_data = output_data.reshape((256, 256, 6))
mask = np.argmax(output_data, axis=2).astype(np.uint8)
# Create a colored mask using the previously defined SEGMENT_COLORS
colored_mask = np.zeros((256, 256, 3), dtype=np.uint8)
for label_idx in range(6):
class_mask = mask == label_idx
color = SEGMENT_COLORS[label_idx]
colored_mask[class_mask] = color
mask_image = Image.fromarray(colored_mask)
# Show output results
fig, axes = plt.subplots(1, 2, figsize=(9, 3))
for idx, (title, image) in enumerate([
('Test Image', pil_image),
('TFLite Mask Image', mask_image),
]):
axes[idx].imshow(image)
axes[idx].set_title(title)
axes[idx].axis('off')
plt.tight_layout()
plt.show()
7. PODAI के लिए मॉडल एक्सपोर्ट करना
अपने मॉडल की पुष्टि करने के बाद, अगला ज़रूरी चरण उन्हें डिप्लॉय करने के लिए तैयार करना है. इस सेक्शन में, कंपाइल किए गए मॉडल को Google Play पर अपलोड करने के लिए पैकेज करने का तरीका बताया गया है. इससे, Google Play On-Device AI (PODAI) फ़्रेमवर्क के ज़रिए, उपयोगकर्ताओं के डिवाइसों पर मॉडल डिलीवर किए जा सकते हैं.
AiEdgeLiteRT AOT (Ahead-of-Time) मॉड्यूल, इस काम के लिए खास तौर पर ai_pack यूटिलिटी उपलब्ध कराता है. इन यूटिलिटी से एआई पैक बनता है, जो एक अहम डेटा ऐसेट है. एआई पैक, आपके कंपाइल किए गए मॉडल को डिवाइस टारगेटिंग कॉन्फ़िगरेशन के साथ बंडल करता है. इससे यह पक्का होता है कि सही मॉडल और ऐसेट, उपयोगकर्ता के सही डिवाइसों पर डिलीवर की गई हैं. यह खास तौर पर एनपीयू (न्यूरल प्रोसेसिंग यूनिट) कंपाइलेशन के लिए ज़रूरी है. इससे यह पक्का किया जाता है कि किसी खास सिस्टम-ऑन-चिप (एसओसी) के लिए ऑप्टिमाइज़ किए गए मॉडल, सिर्फ़ उस एसओसी से लैस डिवाइसों तक पहुंचें.
# Configuring the AI Pack
os.makedirs('selfie_multiclass', exist_ok=True)
ai_pack_dir = os.path.join(work_dir, 'ai_pack')
ai_pack_name = 'selfie_segmentation'
litert_model_name = 'segmentation_model'
# Clean up
shutil.rmtree(ai_pack_dir, ignore_errors=True)
# Export
ai_pack_export.export(
all_google_tensor_compiled_models,
ai_pack_dir,
ai_pack_name,
litert_model_name
)
एआई पैक के सोर्स की जांच की जा रही है
def list_files(startpath):
"""Function to print out the tree structure of a directory."""
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = ' ' * 4 * (level)
print('{}{}/'.format(indent, os.path.basename(root)))
subindent = ' ' * 4 * (level + 1)
for f in files:
print('{}{}'.format(subindent, f))
"""View the files generated within the AI pack directory"""
list_files(ai_pack_dir)
8. बेहतर विकल्प कॉन्फ़िगर करना
किसी डिवाइस या EdgeTPU के लिए NPU कंपाइलेशन
डिफ़ॉल्ट रूप से, LiteRT AOT कंपाइलेशन, रजिस्टर किए गए सभी बैकएंड के लिए कंपाइल होता है. लोकल डेवलपमेंट के लिए, आपको सिर्फ़ कुछ डिवाइसों के लिए कंपाइल करना पड़ सकता है. जैसे, डेवलपमेंट फ़ोन. इसके लिए, कंपाइलेशन के टारगेट साफ़ तौर पर बताएं.
यहां दिया गया उदाहरण, Google Tensor G5 के लिए कंपाइल किया गया है.
# Specifying the compilation target
tensor_g5_target = gt_target.Target(gt_target.SocModel.TENSOR_G5)
# Compile from the TFLite model for a specific target
compiled_models = aot_lib.aot_compile(
tflite_model_path,
target=[tensor_g5_target],
keep_going=False, # We want to error out when there's failure.
)
print(compiled_models.compilation_report())
Google Tensor के लिए कंपाइलेशन फ़्लैग
कंपाइलेशन फ़्लैग की मदद से, कंपाइलेशन प्रोसेस को पसंद के मुताबिक बनाएं. यहां इस फ़्लैग का इस्तेमाल किया गया है: google_tensor_truncation_type="half"
TFLite मॉडल को कंपाइल करते समय
compiled_models = aot_lib.aot_compile(
tflite_model_path,
target=[tensor_g5_target],
keep_going=False,
google_tensor_truncation_type="half"
)
9. अगले चरण
बधाई हो!
आपके मॉडल, PODAI के इस्तेमाल के लिए तैयार हैं!
अब यहां दिए गए चरणों के लिए, Android Studio पर जाएं. ज़्यादा जानकारी के लिए, LiteRT इमेज सेगमेंटेशन के सैंपल देखें.