LiteRT 연산자 버전

이 문서에서는 LiteRT의 op 버전 관리 스키마를 설명합니다. Op 버전 관리를 사용하면 개발자가 기존 작업에 새 기능과 매개변수를 추가할 수 있습니다. 또한 다음을 보장합니다.

  • 하위 호환성: 새 LiteRT 구현은 이전 모델 파일을 처리해야 합니다.
  • 전방 호환성: 새 기능이 사용되지 않는 한 이전 LiteRT 구현은 새 버전의 변환기로 생성된 새 모델 파일을 처리해야 합니다.
  • 전방 호환성 감지: 이전 LiteRT 구현이 지원되지 않는 새 버전의 연산이 포함된 새 모델을 읽는 경우 오류를 보고해야 합니다.

예: 깊이 방향 컨볼루션에 확장 추가

이 문서의 나머지 부분에서는 깊이 방향 컨볼루션 연산에 확장 파라미터를 추가하는 방법을 보여줌으로써 TFLite의 op 버전 관리를 설명합니다.

이 문서를 이해하는 데는 확장에 대한 지식이 필요하지 않습니다. 참고:

  • dilation_width_factordilation_height_factor라는 두 가지 새로운 정수 매개변수가 추가됩니다.
  • 확장을 지원하지 않는 이전의 깊이 방향 컨볼루션 커널은 확장 계수를 1로 설정하는 것과 같습니다.

FlatBuffer 스키마 변경

연산에 새 매개변수를 추가하려면 lite/schema/schema.fbs의 옵션 표를 변경합니다.

예를 들어 깊이 방향 컨볼루션의 옵션 표는 다음과 같습니다.

table DepthwiseConv2DOptions {
  padding:Padding;
  stride_w:int;
  stride_h:int;
  depth_multiplier:int;
  fused_activation_function:ActivationFunctionType;
}

새 매개변수를 추가할 때는 다음 사항을 고려하세요.

  • 어떤 버전에서 어떤 매개변수가 지원되는지 나타내는 주석을 추가합니다.
  • 새 구현이 새로 추가된 매개변수의 기본값을 가져오면 이전 구현과 정확히 동일하게 작동해야 합니다.

새 매개변수가 추가된 후 표는 다음과 같이 표시됩니다.

table DepthwiseConv2DOptions {
  // Parameters for DepthwiseConv version 1 or above.
  padding:Padding;
  stride_w:int;
  stride_h:int;
  depth_multiplier:int;
  fused_activation_function:ActivationFunctionType;
  // Parameters for DepthwiseConv version 2 or above.
  dilation_w_factor:int = 1;
  dilation_h_factor:int = 1;
}

새 스키마를 위해 lite/schema/schema_generated.h 파일을 다시 생성해야 합니다.

C 구조 및 커널 구현 변경

LiteRT에서 커널 구현은 FlatBuffer 정의에서 분리됩니다. 커널은 lite/c/builtin_op_data.h에 정의된 C 구조에서 매개변수를 읽습니다.

원래의 depthwise 컨볼루션 매개변수는 다음과 같습니다.

typedef struct {
  TfLitePadding padding;
  int stride_width;
  int stride_height;
  int depth_multiplier;
  TfLiteFusedActivation activation;
} TfLiteDepthwiseConvParams;

FlatBuffer 스키마와 마찬가지로 어떤 버전부터 어떤 매개변수가 지원되는지 나타내는 주석을 추가합니다. 결과는 다음과 같습니다.

typedef struct {
  // Parameters for DepthwiseConv version 1 or above.
  TfLitePadding padding;
  int stride_width;
  int stride_height;
  int depth_multiplier;
  TfLiteFusedActivation activation;
  // Parameters for DepthwiseConv version 2 or above.
  int dilation_width_factor;
  int dilation_height_factor;
} TfLiteDepthwiseConvParams;

C 구조체에서 새로 추가된 매개변수를 읽도록 커널 구현도 변경하세요. 세부정보는 생략되었습니다.

FlatBuffer 읽기 코드 변경

FlatBuffer를 읽고 C 구조를 생성하는 로직은 lite/core/api/flatbuffer_conversions.cc에 있습니다.

아래와 같이 새 매개변수를 처리하도록 파일을 업데이트합니다.

TfLiteStatus ParseDepthwiseConv2D(const Operator* op,
                                  ErrorReporter* error_reporter,
                                  BuiltinDataAllocator* allocator,
                                  void** builtin_data) {
  CheckParsePointerParams(op, error_reporter, allocator, builtin_data);

  SafeBuiltinDataAllocator safe_allocator(allocator);

  std::unique_ptr<TfLiteDepthwiseConvParams,
                  SafeBuiltinDataAllocator::BuiltinDataDeleter>
      params = safe_allocator.Allocate<TfLiteDepthwiseConvParams>();
  TF_LITE_ENSURE(error_reporter, params != nullptr);

  const DepthwiseConv2DOptions* schema_params =
      op->builtin_options_as_DepthwiseConv2DOptions();

  if (schema_params != nullptr) {
    params->padding = ConvertPadding(schema_params->padding());
    params->stride_width = schema_params->stride_w();
    params->stride_height = schema_params->stride_h();
    params->depth_multiplier = schema_params->depth_multiplier();
    params->activation =
        ConvertActivation(schema_params->fused_activation_function());

    params->dilation_width_factor = schema_params->dilation_w_factor();
    params->dilation_height_factor = schema_params->dilation_h_factor();
  }

  *builtin_data = params.release();
  return kTfLiteOk;
}

여기서는 op 버전을 확인할 필요가 없습니다. 새 구현이 확장 계수가 누락된 이전 모델 파일을 읽으면 1을 기본값으로 사용하고 새 커널은 이전 커널과 일관되게 작동합니다.

커널 등록 변경

MutableOpResolver (lite/mutable_op_resolver.h에 정의됨)는 op 커널을 등록하는 몇 가지 함수를 제공합니다. 기본적으로 최소 버전과 최대 버전은 1입니다.

void AddBuiltin(tflite::BuiltinOperator op, TfLiteRegistration* registration,
                int min_version = 1, int max_version = 1);
void AddCustom(const char* name, TfLiteRegistration* registration,
               int min_version = 1, int max_version = 1);

내장 연산은 lite/kernels/register.cc에 등록됩니다. 이 예에서는 DepthwiseConv2D 버전 1과 2를 처리할 수 있는 새 op 커널을 구현했으므로 다음 줄을 변경해야 합니다.

AddBuiltin(BuiltinOperator_DEPTHWISE_CONV_2D, Register_DEPTHWISE_CONV_2D());

다음과 같이 변경합니다.

AddBuiltin(BuiltinOperator_DEPTHWISE_CONV_2D, Register_DEPTHWISE_CONV_2D(),
             /* min_version = */ 1,
             /* max_version = */ 2);

TFLite op 버전 변경

다음 단계는 TFLite가 연산을 실행하는 데 필요한 최소 버전을 채우도록 하는 것입니다. 이 예에서는 다음을 의미합니다.

  • 확장 인수가 모두 1인 경우 version=1을 채웁니다.
  • 그 밖의 경우에는 version=2를 채웁니다.

DepthwiseConv2D의 사례에 새 버전을 추가하여 lite/tools/versioning/op_version.cc의 연산자에 관한 GetBuiltinOperatorVersion 함수를 수정합니다.

case BuiltinOperator_DEPTHWISE_CONV_2D:
  auto depthwise_conv_params =
      reinterpret_cast<TfLiteDepthwiseConvParams*>(op_sig.builtin_data);
  TFLITE_DCHECK(depthwise_conv_params != nullptr);
  if (depthwise_conv_params->dilation_width_factor != 1 ||
       depthwise_conv_params->dilation_height_factor != 1) {
    return 2;
  }
  return 1;

운영자 버전 맵 업데이트

마지막 단계는 새 버전 정보를 운영자 버전 맵에 추가하는 것입니다. 이 버전 맵을 기반으로 모델의 최소 요구 런타임 버전을 생성해야 하므로 이 단계가 필요합니다.

이렇게 하려면 lite/tools/versioning/runtime_version.cc에 새 맵 항목을 추가해야 합니다.

이 예에서는 op_version_map에 다음 항목을 추가해야 합니다.

{ {BuiltinOperator_DEPTHWISE_CONV_2D, 2}, %CURRENT_RUNTIME_VERSION%}

여기서 %CURRENT_RUNTIME_VERSION%release_version.h에 정의된 현재 런타임 버전에 해당합니다.

위임 구현

LiteRT는 하드웨어 백엔드에 작업을 위임할 수 있는 위임 API를 제공합니다. 대리자의 Prepare 함수에서 위임 코드의 모든 노드에서 버전이 지원되는지 확인합니다.

const int kMaxVersion = 1;
TfLiteNode* node;
TfLiteRegistration* registration = nullptr;
TF_LITE_ENSURE_STATUS(context->GetNodeAndRegistration(context, node_index, &node, &registration));

if (registration->version > kMaxVersion) {
  // Reject the node if the version isn't supported.
}

위임이 버전 1 작업만 지원하는 경우에도 필요하므로 위임은 더 높은 버전 작업을 가져올 때 비호환성을 감지할 수 있습니다.