본문으로 건너뛰기

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])

두 변환 모두 Lua table을 거치지 않고 native 계층에서 직접 복사합니다.

모듈 수준 함수

런타임 및 기본 정보

  • 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를 함께 사용할 수 있으며 broadcasting 규칙에 따라 결과를 생성합니다.
  • 이미지 전처리, 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()는 분리된 스칼라 매개변수 다섯 개가 아니라 shape이 [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의 IoU를 직접 계산합니다. 세 번째 매개변수 opts도 지원하며 compare_size = true 또는 명시적인 width / height를 전달할 수 있습니다.
  • db_postprocess()는 DB / DBNet 계열 텍스트 탐지 후처리에 적합하며 반환되는 각 탐지 항목에 score, points, box가 포함됩니다.
  • decode_dense_detection()opts.strides는 비어 있지 않은 양의 정수 배열이어야 하며 decode_width, decode_height도 필요합니다. 현재는 box_encoding = "grid_center_log_wh"만 지원합니다.
  • ctc_greedy_decode()blank_index, merge_repeated, apply_softmax, return_probabilities, charset을 지원합니다.
  • ctc_greedy_decode()는 항상 indices를 반환합니다. textcharset을 전달했을 때만, confidenceapply_softmax 또는 return_probabilities를 활성화했을 때만, probabilitiesprobability_confidencereturn_probabilities를 활성화했을 때만 반환합니다.
  • nms() / rotated_nms()int64 tensor를 반환하며 인덱스 의미는 1-based입니다.
  • sample_logits()argmax, temperature, top_k, top_p, min_p, seed를 지원합니다.
  • 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)

optional, sequence, map, sparse tensor처럼 순수 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에는 CPUExecutionProvider, CoreMLExecutionProvider 같은 별칭도 사용할 수 있으며 내부에서 "cpu", "coreml"로 정규화됩니다.
  • provider를 명시하지 않았거나 provider 목록이 비어 있으면 session 생성 단계에서 CPU provider를 자동으로 추가합니다.
  • provider 목록에 "coreml"이 있고 fallback_to_cpu = true이면 CPU를 fallback 경로로 추가할 수도 있습니다.
  • 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"))