1. نظرة عامة
يتم استخدام حزمة تطوير البرامج (SDK) من Google Tensor لتجميع نماذج LiteRT لأجهزة Pixel. يمكن نشر النماذج المجمَّعة على أجهزة Pixel لتحسين أداء الاستدلال في تعلُّم الآلة. لاستخدام حزمة تطوير البرامج (SDK)، عليك أولاً تحويل النموذج إلى نموذج LiteRT (tflite).
يستند هذا الدرس التطبيقي حول الترميز إلى الإصدار العام من Colab على GitHub، الدرس التطبيقي حول الترميز الخاص بتجميع LiteRT AOT:.
الهدف
تعرَّف على كيفية استخدام برنامج التجميع LiteRT AOT (التجميع المسبق) لتجميع نموذج تقسيم الصور الذاتية من نموذج TFLite إلى نموذج LiteRT محسَّن ومجمَّع لأجهزة Edge TPU على الجهاز فقط.
يشرح لك هذا المستند أيضًا خطوات إعداد النماذج باستخدام Play للذكاء الاصطناعي على الجهاز فقط (PODAI).
توفّر PODAI نماذج مخصّصة لميزات الذكاء الاصطناعي على الجهاز فقط بكفاءة أكبر. فهي تبسّط عملية إطلاق نماذج الذكاء الاصطناعي واستهدافها وتحديد إصداراتها وتنزيلها. وعند دمجه مع ميزة تجميع LiteRT EdgeTPU AOT، يتيح للمطوّرين تقديم نماذج تعلُّم الآلة المجمَّعة لمختلف الأجهزة بدون الحاجة إلى معرفة عدد شرائح EdgeTPU التي يتضمّنها هاتف المستخدم النهائي.
النماذج المستخدَمة
تم نشر النماذج التي نستخدمها في الأصل على دليل تقسيم الصور في MediaPipe. في ما يلي بعض التفاصيل حول النموذج المستخدَم في هذا الدرس العملي:
SelfieMulticlass: نموذج LiteRT يأخذ صورة لشخص، ويحدّد مناطق مثل الشعر والبشرة والملابس، ويُخرج خريطة تقسيم الصورة لهذه العناصر.
2. البدء
اتّبِع الخطوات التالية للحصول على إذن الوصول إلى حزمة تطوير البرامج (SDK) الخاصة بمعالج Google Tensor وبدء استخدامها:
- اشترِك للحصول على إذن الوصول إلى حزمة تطوير البرامج (SDK) من Google Tensor. قبل المتابعة، عليك انتظار رسالة إلكترونية من Google تحتوي على رابط تنزيل البرنامج المساعد للمترجم.
- نزِّل المكوّن الإضافي لبرنامج التجميع (litert_plugin_compiler.tar.gz) وضَعْه في مجلد من اختيارك.
- اضبط متغيّر البيئة على مسار النظام المحلي للملف الذي تم تنزيله،
GOOGLE_TENSOR_SDK_BETA.
يمكنك تنفيذ هذا الأمر في وحدة bash الطرفية: أو يمكنك تشغيل هذا الرمز في ورقة ملاحظات 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 التي تحتوي على برنامج تجميع AOT الخاص بـ EdgeTPU، والمكتبات الأخرى التي تستخدمها لتحويل النماذج.
استخدِم هذه الحزمة لتثبيت LiteRT backend على Google Tensor: ai-edge-litert-sdk-google-tensor.
بعد تثبيت الحِزم، أعِد تشغيل الجلسة وتابِع من خطوات التثبيت. لا تعِد تثبيت التطبيق.
إذا كنت تخطّط لإجراء عملية الإعداد على نظامك، ننصحك باستخدام بيئة Python افتراضية (venv) وتنفيذ هذه الأوامر داخل البيئة الافتراضية.
إلغاء تثبيت حِزم معيّنة
قبل ذلك، عليك إلغاء تثبيت TensorFlow الذي يأتي مع بيئة تشغيل Colab تلقائيًا.
pip uninstall -y tensorflow ai-edge-litert
تثبيت جميع المكتبات
تثبيت LiteRT backend على Google Tensor
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) مباشرةً.
تجميع EdgeTPU من نموذج TFLite
تتطلّب هذه الخطوة نموذج TFLite. إذا لم يكن لديك نموذج TFLite، حوِّل النموذج إلى تنسيق TFLite.
الحصول على نموذج TFLite
نستخدم نموذج MediaPipe MultiClass Segmentation لحالة الاستخدام هذه.
يتوفّر نموذج TFLite من صفحة تقسيم الصور في MediaPipe.
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)
التحقّق بسرعة من صحة نموذج TfLite باستخدام LiteRT Python API
في المثال التالي، سترى كلاً من صورة القناع والنتيجة المدمجة.
# 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()
حوِّل إلى نموذج LiteRT، مع تجميع AOT في EdgeTPU.
نستخدم واجهات برمجة التطبيقات من 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، ما يتيح إرسالها إلى أجهزة المستخدمين من خلال إطار عمل الذكاء الاصطناعي على الجهاز (PODAI) من Google Play.
يوفّر وحدة AOT (الترجمة المسبقة) في AiEdgeLiteRT أدوات ai_pack مخصّصة لهذا الغرض. تنشئ هذه الأدوات المساعدة حزمة ذكاء اصطناعي، وهي من أصول البيانات المهمة. تحزّم حزمة الذكاء الاصطناعي نماذجك المجمّعة مع إعدادات استهداف الأجهزة، ما يضمن تسليم النماذج ومواد العرض الصحيحة إلى أجهزة المستخدمين المناسبة. ويُعدّ ذلك مهمًا بشكل خاص لعمليات تجميع وحدة المعالجة العصبية (NPU)، لأنّها تضمن وصول النماذج المحسَّنة لنظام معيّن على شريحة واحدة (SoC) إلى الأجهزة المزوّدة بهذه الشريحة فقط.
# 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. ضبط الخيارات المتقدّمة
تجميع NPU لجهاز أو EdgeTPU محدّد
تتم عملية الترجمة البرمجية إلى جميع الأنظمة الخلفية المسجّلة تلقائيًا عند استخدام ميزة الترجمة البرمجية مسبقًا في LiteRT. بالنسبة إلى التطوير المحلي، قد تحتاج فقط إلى تجميع التطبيق لأجهزة معيّنة، مثل هواتف التطوير. يمكنك تحقيق ذلك من خلال توفير أهداف التجميع بشكل صريح.
يتم تجميع المثال التالي إلى 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" لتنفيذ الخطوات التالية. اطّلِع على أمثلة على تقسيم الصور باستخدام LiteRT للحصول على التفاصيل.