การส่งออกโมเดลด้วย TorchScript

AI Models แบบ Scalable ด้วย PyTorch Lightning

Sergiy Tkachuk

Director, GenAI Productivity

TorchScript คืออะไร?

  • ทำงานได้อิสระจาก Python

  • มีประสิทธิภาพในการใช้งานจริง

  • ตัวอย่าง:

    • การ deploy บนอุปกรณ์มือถือ

มือถือ

AI Models แบบ Scalable ด้วย PyTorch Lightning

TorchScript คืออะไร?

  • ทำงานได้อิสระจาก Python

  • มีประสิทธิภาพในการใช้งานจริง

  • ตัวอย่าง:

    • การ deploy บนอุปกรณ์มือถือ
    • การ inference ประสิทธิภาพสูงในระบบ production

มือถือและแล็ปท็อปพร้อมเฟืองแสดงถึงสภาพแวดล้อม production

AI Models แบบ Scalable ด้วย PyTorch Lightning

การแปลงโมเดลเป็น TorchScript

วิธีแปลงโมเดลมี 2 แบบ:

  • torch.jit.trace: ใช้ข้อมูล input ตัวอย่างเพื่อ trace การทำงาน
  • torch.jit.script: คอมไพล์โมเดลโดยวิเคราะห์โค้ด Python

ควรใช้เมื่อใด:

  1. ใช้ trace สำหรับโมเดลที่ไม่ซับซ้อน
  2. ใช้ script สำหรับโมเดลที่มี control flow (เช่น ลูป)
import torch
import torch.nn as nn

class SimpleModel(nn.Module): def forward(self, x): return x * 2
model = SimpleModel() scripted_model = torch.jit.script(model)
AI Models แบบ Scalable ด้วย PyTorch Lightning

การบันทึกและโหลดโมเดล TorchScript

$$

  • บันทึกโมเดล:
    • torch.jit.save: บันทึก scripted model ลงไฟล์
  • โหลดโมเดล:
    • torch.jit.load: โหลดโมเดลกลับมาเพื่อ inference

$$

# Save the model
torch.jit.save(scripted_mod,"model.pt")

# Load the model
loaded_model=torch.jit.load("model.pt")
AI Models แบบ Scalable ด้วย PyTorch Lightning

การทำ inference ด้วย TorchScript

  • ขั้นตอน:
    • โหลดโมเดล TorchScript
    • ส่ง input ให้โมเดลเพื่อพยากรณ์ผล
    • ผลลัพธ์เหมือนกับการพยากรณ์ใน PyTorch

ตัวอย่าง Input:

  • Input Tensor: [1.0, 2.0, 3.0]

ตัวอย่าง Output:

  • Output Tensor: [2.0, 4.0, 6.0]
# Perform inference
input_arr = [1.0, 2.0, 3.0]
input_tensor = torch.tensor(input_arr)

output = loaded_model(input_tensor) print(output)
AI Models แบบ Scalable ด้วย PyTorch Lightning

TorchScript โดยสรุป

$$

  • torch.jit.trace: ใช้กับโมเดล static
  • torch.jit.script: รองรับ control flow แบบ dynamic
  • torch.jit.save: บันทึก scripted model
  • torch.jit.load: โหลดกลับมาเพื่อ inference
AI Models แบบ Scalable ด้วย PyTorch Lightning

มาฝึกกันเถอะ!

AI Models แบบ Scalable ด้วย PyTorch Lightning

Preparing Video For Download...