카테고리 보관물: Programming

[Tip] Emacs: rust-analyzer-tramp가 계속 죽는 문제

Remote server에 tramp mode로 rust file을 읽어서 rust-mode에 진입한 후에 미니버퍼에 아래와 같은 경고가 뜨는데, ‘y’를 입력해서 rust-analyzer-tramp를 재실행 시켜도 계속해서 죽어서 같은 오류가 보이는 문제가 생겼다.

rust-analyzer 설치 확인

Remote server측에 rust-analyzer가 설치되어 있지 않으면 이와 같은 문제가 생길 수 있으니 다음의 명령어로 rust-analyzer를 update해본다. 만약 설치 되어 있지 않다면 이 과정에서 설치될 것이다.

rustup component add rust-analyzer

Remote path 사용

rust-analyzer가 이미 설치 되어 있음에도 문제가 발생 한다면 서버측의 path가 제대로 설정되고 있는지 확인해 보자. Trump mode는 서버측의 PATH 환경변수 값 을 읽지 않으므로 경로정보를 서버의 것으로 유지 하도록 설정해 주어야 한다.

 (require 'tramp)
 (setq tramp-default-method "ssh")
 ;; Respect remote path.
 (with-eval-after-load 'tramp
   (add-to-list 'tramp-remote-path 'tramp-own-remote-path))

OpenVINO Object Detection Model의 전처리와 후처리를 간단하게

AI model들은 입출력 layer의 구조가 다르므로 서로 다른 pre/post processing을 필요로 한다. Vision model을 예로 들면 어떤 모델은 입력을 416×416으로 받게 되어 있어서 입력 전에 원본 크기로 부터 resizing을 해주어야 하고, 어떤 모델은 resizing layer을 포함하고 있어서 그냥 입력해도 잘 동작하기도 한다. 또한 어떤 모델은 입력값을 정규화 해서 입력해 주어야 하고, 어떤 모델은 정규화가 필요 없기도 하다.

입력층 뿐 아니라 출력층도 제각각이다. Object detection을 수행하는 모델들을 보면 YOLO같은 모델은 score값을 bounding box와 함께 전달하고, D-Fine같은 모델은 bounding box, score, label을 각각 따로 출력하기도 한다.

어떤 모델의 입출력 형태의 차이를 보고 싶으면 읽어들인 모델의 inputs와 outputs 변수의 내용을 살펴보면 된다.

def print_model_io_layer(ovcore: Core, model_path: str, model_name: str):
    read_model = ovcore.read_model(model_path)
    print(f"[{model_name}]")

    # Display input layer
    for idx, input_layer in enumerate(read_model.inputs):
        print(f"Input({idx+1}):")
        print("  any_name     :", input_layer.get_any_name())
        print("  names        :", input_layer.get_names())
        print("  shape        :", input_layer.get_partial_shape())
        print("  element type :", input_layer.get_element_type())

    # Display output layer
    for idx, output_layer in enumerate(read_model.outputs):
        print(f"Output({idx+1}):")
        print("  any_name     :", output_layer.get_any_name())
        print("  names        :", output_layer.get_names())
        print("  shape        :", output_layer.get_partial_shape())
        print("  element type :", output_layer.get_element_type())

이렇게 다양한 모델들의 입출력을 직접 처리하는 것은 여간 번거로운 일이 아니다. OpenVINO에서는 모델에 전/후처리를 사용자가 지정할 수 있는 PrePostProcessor를 지원하기는 하지만 이 마저도 모델별로 상이한 부분을 직접 수정해 주어야 하기 때문에 번거로운 것은 마찬가지다.

OpenVINO Model API 사용법

예를 들어 ATSS, YOLOX-S, YOLOX-Tiny, D-Fine 네개의 OpenVINO model과 각각에 대한 ONNX model들까지 8개의 서로 다른 세개의 서로 다른 모델들이 있다고 할 때, 8개의 서로 다른 입출력 결과를 처리하는 것은 아주 많은 노력을 필요로 할 것이다.

openvino-model-api를 사용하면 이러한 부분을 비교적 간단하게 처리 할 수 있다. 사용하려면 다음과 같이 필요한 패키지들을 설치해 준다.

pip install openvino openvino-model-api onnx

설치가 끝나면 먼저 서로 다른 입출력 계층을 맞춰 주는 모델을 생성한다. 추론에 사용하고자 하는 모델 파일로 OpenvinoAdapter를 만들어서 create_model()에 넘겨 준다. 이렇게 생성된 모델은 입력을 위한 전처리 과정을 자동으로 수행한다.

from openvino import Core
from model_api.adapters import OpenvinoAdapter
from model_api.models import Model


ovcore = Core()

# Adapter를 생성하고 create_model()에 넘겨준다.
ovadapter = OpenvinoAdapter(ovcore, model_path)
model = Model.create_model(ovadapter, preload=True)

그리고 나서 추론을 실행하면 그 결과는 DetectionResult 타입으로 정리되어 반환된다. 따라서 모델별로 서로다른 후처리(post processing) 과정 필요 없이 DetectionResult으로 반환되는 결과를 처리해주면 된다.

# 추론 실행
detection_result = model(test_image)

결과물 처리를 위해서 detection_result를 원본 이미지에 overlay하는 함수로 만들었다(overlay_detection_result). 이 함수는 Threshold값을 넘는 결과물을 원본 이미지 위에 bounding box와 label로 표시하고 detect된 object의 갯수와 함께 반환해 준다.

DetectionResult에서 참조되는 주요한 멤버변수는 Socre값을 나타내는 .score, bounding box를 나타내는 .xmin, .ymin, .xmax, .ymax 그리고 label을 가지고 있는 .str_label이다. Bounding box 좌표도 입력 이미지의 크기에 맞게 이미 scaling되어 있으므로 좌표를 그대로 가져다 쓰면 된다.

from model_api.models.utils import DetectionResult


def overlay_detection_result(
    original_image: np.ndarray, detection_result: DetectionResult, threshold: float
) -> Tuple[np.ndarray, int]:
    num_detected = 0
    processed_image = original_image.copy()

    for det in detection_result[0]:
        score = det.score
        if score >= threshold:
            num_detected += 1

            # Bounding box
            x1 = int(det.xmin)
            y1 = int(det.ymin)
            x2 = int(det.xmax)
            y2 = int(det.ymax)

            # Clamping
            x1 = max(0, min(x1, original_image.shape[1]))
            y1 = max(0, min(y1, original_image.shape[0]))
            x2 = max(0, min(x2, original_image.shape[1]))
            y2 = max(0, min(y2, original_image.shape[0]))

            # Draw BBox
            cv2.rectangle(processed_image, (x1, y1), (x2, y2), BBOX_COLOR, 2)

            # Draw label.
            display_text = (
                f"{det.str_label} {score:.2f}" if {det.str_label} else f"{score:.2f}"
            )
            cv2.putText(
                processed_image,
                display_text,
                (x1, y1 - 10),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.5,
                LABEL_COLOR,
                2,
            )
    return processed_image, num_detected

8개의 모델에 시험해 보자

사용하려는 8개의 모델들은 다음과 같다.

atss_model_file = os.path.join(MODEL_PATH, "atss_fp32/model.xml")
atss_onnx_model_file = os.path.join(MODEL_PATH, "atss_onnx_fp32/model.onnx")
yolos_model_file = os.path.join(MODEL_PATH, "yolos_fp32/model.xml")
yolos_onnx_model_file = os.path.join(MODEL_PATH, "yolos_onnx_fp32/model.onnx")
yolotiny_model_file = os.path.join(MODEL_PATH, "yolotiny_fp32/model.xml")
yolotiny_onnx_model_file = os.path.join(MODEL_PATH, "yolotiny_onnx_fp32/model.onnx")
dfinex_model_file = os.path.join(MODEL_PATH, "dfinex_fp32/model.xml")
dfinex_onnx_model_file = os.path.join(MODEL_PATH, "dfinex_onnx_fp32/model.onnx")

이것들을 all_models라는 list에 넣고 한번에 돌린다. 즉, 각 모델들의 서로 다른 입력과 출력 계층에 대한 처리를 단일한 코드로 수행하는 것이다.

ovcore = Core()


# Test image
test_image = cv2.imread("./data/test_image.jpg")

threshold = 0.8
for m in all_models:
    model_path = m[0]
    model_name = m[1]
    ovadapter = OpenvinoAdapter(ovcore, model_path)
    model = Model.create_model(ovadapter, preload=True)
    detection_result = model(test_image)
    proc_image, num_det = overlay_detection_result(
        test_image, detection_result, threshold
    )

    print(f"{model_name} :: {num_det} objects detected (threshold: {threshold}).")
    cv2.imwrite(f"output_{model_name}.jpg", proc_image)

전체 소스코드

Image file의 partition 크기 늘리기

이미지파일에서 주어지는 파티션의 크기가 너무 작은 경우 더이상 파일을 복사 할 수 없는 경우가 종종 생긴다.

fdisk 명령어로 보면 이미지 파일의 파티션정보가 보이는데, 이 경우 기본적으로 5.5GB의 공간이 Linux partition (ext4)으로 할당되어 있다.

이 크기를 늘리고 싶다면 truncate로 image file의 크기를 조절하고, parted로 원하는 파티션에 할당해 주면된다.

# Image의 크기를 1GB 늘림
truncate -s +1G ./raspios_inc_7gb.img

# 두번째 파티션(ext4)에 100%를 할당
parted raspios_inc_7gb.img resizepart 2 100%

다시 한번 fdisk를 실행해보면 이전 5.5GB에서 6.5GB로 1GB 늘어난 파티션이 두번째인 Linux partition에 적용된 것을 확인할 수 있다.