이 문서에서는 LiteRT의 op 버전 관리 스키마를 설명합니다. Op 버전 관리를 사용하면 개발자가 기존 작업에 새로운 기능과 매개변수를 추가할 수 있습니다. 또한 다음을 보장합니다.
- 하위 호환성: 새로운 LiteRT 구현은 이전 모델 파일을 처리해야 합니다.
- 순방향 호환성: 새로운 기능이 사용되지 않는 한 이전 LiteRT 구현은 새로운 버전의 변환기에서 생성된 새로운 모델 파일을 처리해야 합니다.
- 비호환성 감지 전달: 지원되지 않는 새 버전의 작업이 포함된 새 모델을 이전 LiteRT 구현이 읽으면 오류를 보고해야 합니다.
예: 깊이별 컨볼루션에 팽창 추가
이 문서의 나머지 부분에서는 깊이별 컨볼루션 연산에 팽창 매개변수를 추가하는 방법을 보여주어 TFLite의 op 버전 관리를 설명합니다.
이 문서를 이해하는 데 팽창에 대한 지식이 필요하지 않습니다. 참고:
dilation_width_factor및dilation_height_factor이라는 새로운 정수 매개변수 2개가 추가됩니다.- 팽창을 지원하지 않는 이전 깊이별 컨볼루션 커널은 팽창 계수를 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 구조체에서 매개변수를 읽습니다.
원래 깊이별 컨볼루션 매개변수는 다음과 같습니다.
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 작업 버전 변경
다음 단계는 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, ®istration));
if (registration->version > kMaxVersion) {
// Reject the node if the version isn't supported.
}
이는 위임이 버전 1 작업만 지원하는 경우에도 필요하므로 위임이 더 높은 버전 작업을 가져올 때 비호환성을 감지할 수 있습니다.