跳至主要內容

ONNX Runtime 模組 (onnxruntime)

該模組在 20260402 以後版本方可使用
僅支援 iOS 13 及以上版本系統

onnxruntime 模組用於在裝置上直接載入和運行 ONNX 模型,適合文字、Embedding、分類、檢測以及各種通用張量推理場景。

載入模組

local ort = require("onnxruntime")

這是一個按需載入模組,不像 coreml 那樣是內置全域模組。

require("onnxruntime") 成功執行後,還會向內置 coreml 模組注入兩組橋接介面:

  • coreml.multi_array_from_ort_tensor(tensor[, data_type])
  • multi_array:to_ort_tensor([data_type])

這兩組轉換都在 native 層直接拷貝,不經過 Lua table。

模組級函式

運行時與基礎資訊

  • onnxruntime.version()
  • onnxruntime.providers()
  • onnxruntime.configure(opts)

說明:

  • providers() 返回目前 ORT 運行時實際可用的 Execution Provider 清單
  • configure() 用於設定全域運行時預設值,必須在建立任何 session 之前呼叫

張量、影像與數值輔助

  • onnxruntime.tensor(type, shape[, data])
  • onnxruntime.tensor_from_bytes(type, shape, bytes)
  • onnxruntime.tensor_from_cv_mat(mat[, opts])
  • onnxruntime.tensor_from_quad(mat, quad[, opts])
  • onnxruntime.tensor_from_quads(mat, quads[, opts])
  • onnxruntime.tensor_from_image(image[, opts])
  • onnxruntime.tensor_from_images(images[, opts])
  • onnxruntime.image_from_tensor(tensor[, opts])
  • onnxruntime.clamp(tensor, min, max)
  • onnxruntime.sigmoid(tensor)
  • onnxruntime.exp(tensor)
  • onnxruntime.where(condition, x, y)
  • onnxruntime.matmul(lhs, rhs)
  • onnxruntime.concat(tensors[, axis])
  • onnxruntime.stack(tensors[, axis])

說明:

  • clamp()sigmoid()exp()matmul() 與同名 tensor: 方法等價,只是把 tensor 作為第一個參數傳入
  • where() 支援標量 / 布林值 / tensor 混用,並按廣播規則生成結果
  • 影像預處理、OpenCV 橋接和 image_from_tensor() 的細節,詳見 張量模組

檢測、解碼與後處理輔助

  • onnxruntime.nms(boxes, scores[, opts])
  • onnxruntime.box_points(rotated_boxes)
  • onnxruntime.xywh_to_xyxy(boxes)
  • onnxruntime.xyxy_to_xywh(boxes)
  • onnxruntime.rotated_iou(lhs_box, rhs_box)
  • onnxruntime.rotated_nms(boxes, scores[, opts])
  • onnxruntime.create_decoder(schema)
  • onnxruntime.decode_yolo(output[, opts])
  • onnxruntime.decode_yolo_obb(output[, opts])
  • onnxruntime.decode_matrix_candidates(output, schema[, opts])
  • onnxruntime.decode_dense_detection(output, opts)
  • onnxruntime.records_from_boxes(boxes, scores, class_ids[, keep_indices])
  • onnxruntime.obb_records_from_rows(rows, scores, class_ids[, angles[, keep_indices[, opts]]])
  • onnxruntime.points_to_records(points[, opts])
  • onnxruntime.threshold_masks(masks, threshold)
  • onnxruntime.crop_masks_by_boxes(masks, boxes)
  • onnxruntime.resize_masks(masks, width, height[, opts])
  • onnxruntime.mask_iou(lhs_mask, rhs_mask)
  • onnxruntime.mask_to_polygon(mask[, opts])
  • onnxruntime.proto_masks(proto, coeffs, boxes, image_width, image_height[, opts])
  • onnxruntime.project_masks(proto, coeffs, boxes, image_width, image_height[, opts])
  • onnxruntime.db_postprocess(score_map[, opts])
  • onnxruntime.tracker([opts])
  • onnxruntime.reshape_keypoints(points[, keypoint_count[, keypoint_dim|opts]])
  • onnxruntime.scale_boxes(boxes, transform)
  • onnxruntime.clip_boxes(boxes, clip_width, clip_height)
  • onnxruntime.scale_points(points, transform[, opts])
  • onnxruntime.scale_keypoints(points, transform[, opts])
  • onnxruntime.clip_keypoints(points, clip_width, clip_height[, opts])
  • onnxruntime.ctc_greedy_decode(logits[, opts])
  • onnxruntime.sample_logits(logits[, opts])

說明:

  • tensor_from_quad() / tensor_from_quads() 需要先 require("image.cv"),適合 OCR 四邊形裁剪後直接生成張量
  • box_points() 接收形狀為 [5][1, 5][N, 5] 的旋轉框 tensor,不是五個分離標量參數
  • create_decoder() 返回 decoder 物件,支援 :decode():task():schema()
  • tracker() 返回 tracker 物件,支援 :update():reset():state():close()
  • records_from_boxes()obb_records_from_rows()points_to_records() 會把 tensor 結果整理成更適合 Lua 側消費的 record table
  • proto_masks()project_masks() 目前是同一套實現,後者只是別名
  • mask_iou() 用於直接計算兩張 mask 的交並比,也支援第三個參數 opts,可傳 compare_size = true,或顯式傳 width / height
  • db_postprocess() 適合 DB / DBNet 一類文字檢測後處理;返回的每個檢測項都帶 scorepointsbox
  • decode_dense_detection() 要求 opts.strides 為非空正整數陣列,並且還需要 decode_widthdecode_height;目前只支援 box_encoding = "grid_center_log_wh"
  • ctc_greedy_decode() 支援 blank_indexmerge_repeatedapply_softmaxreturn_probabilitiescharset
  • ctc_greedy_decode() 一定返回 indicestext 僅在傳入 charset 時返回;confidence 僅在啟用 apply_softmaxreturn_probabilities 時返回;probabilitiesprobability_confidence 僅在啟用 return_probabilities 時返回
  • nms() / rotated_nms() 返回的是 int64 tensor,索引語義為 1-based
  • sample_logits() 支援 argmaxtemperaturetop_ktop_pmin_pseed
  • sample_logits() 對 1D logits 返回單個索引;對 batched logits 返回 int64 tensor

結構化值

  • onnxruntime.value(value)
  • onnxruntime.optional(value, type_info)
  • onnxruntime.sequence(items)
  • onnxruntime.map(key_type, value_type, pairs)
  • onnxruntime.sparse_tensor(type, dense_shape, indices, values)
  • onnxruntime.sparse_tensor_from_dense(tensor)

適合處理非純 tensor 的輸入輸出,例如 optional、sequence、map 和 sparse tensor。

目前行為可以概括為:

  • onnxruntime.value(x) 如果 x 已經是 ORT tensor / value / sequence / map / sparse tensor,則原樣返回;如果 x 是 Lua table,則按 sequence 處理;否則會把標量包裝成 tensor
  • onnxruntime.optional(value, type_info) 第二個參數必填;type_info 可以是字串,也可以直接傳 session:input_info(...) / output_info(...) 返回的類型資訊表;空 optional 用 onnxruntime.optional(nil, type_info) 表示
  • onnxruntime.map(key_type, value_type, pairs) 目前 key_type 僅支援 "string""int64"
  • onnxruntime.sparse_tensor(type, dense_shape, indices, values) 目前只支援數值 / bool 稀疏張量,按 COO 方式構造;indices 可以是扁平陣列,也可以是座標陣列
  • onnxruntime.sparse_tensor_from_dense(tensor) 目前不支援 string tensor

常用物件方法:

  • value:type() / value:has_value() / value:get()
  • sequence:length() / sequence:get(i) / sequence:items()
  • map:get(key) / map:set(key, value) / map:keys() / map:pairs()
  • sparse_tensor:dense_shape() / sparse_tensor:values() / sparse_tensor:indices() / sparse_tensor:format() / sparse_tensor:to_dense()

會話與推理

  • onnxruntime.session(model_path[, opts])
  • onnxruntime.session_from_bytes(model_bytes[, opts])
  • onnxruntime.run_options([opts])
  • onnxruntime.load_custom_op_library(path)

會話物件負責模型載入、輸入輸出資訊查詢、執行推理以及 IOBinding。詳見 會話模組

支援的資料類型

目前張量介面支援以下元素類型名稱:

  • "float32" / "float"
  • "float16"
  • "bfloat16"
  • "uint8"
  • "uint16"
  • "uint32"
  • "uint64"
  • "int8"
  • "int16"
  • "int32"
  • "int64"
  • "double" / "float64"
  • "bool"
  • "string"

說明:

  • tensor_from_bytes()copy_from_bytes() 只支援數值和 bool 類型
  • bytes() 不支援 string tensor
  • tensor:to("string") 目前只支援 string -> string

Provider 說明

onnxruntime.providers() 會返回運行時可見的 provider 清單,但目前 session 選項里原生處理並支援的 provider 字串是:

  • "cpu"
  • "coreml"

說明:

  • provider / providers 也接受 CPUExecutionProviderCoreMLExecutionProvider 這類別名,內部會歸一化到 "cpu""coreml"
  • 如果沒有顯式指定 provider,或 provider 清單為空,session 建立階段會自動補上 CPU provider
  • 如果 provider 清單裡包含 "coreml"fallback_to_cpu = true,實現也可能補上 CPU 作為回退路徑
  • 如果你傳入 providers = {"coreml", "cpu"},表示優先嘗試 CoreML,再嘗試 CPU

與 CoreML 聯動

如果你要復用 coreml 分詞器或 MLMultiArray 預處理流程,推薦這樣組合:

local ort = require("onnxruntime")

local tokenizer = assert(coreml.new_text_tokenizer({
type = "wordpiece",
vocab_path = XXT_HOME_PATH.."/models/demo/vocab.txt",
context_length = 52,
}))

local input_ids = assert(tokenizer:encode("hello", {
output = "ort_tensor",
}))

或者把已有的 MLMultiArray 直接轉成 ORT tensor:

local ort = require("onnxruntime")
local tensor = assert(multi_array:to_ort_tensor("int64"))