AI/LLM

Qwen2.5-VL-32B 모델로 OCR, 질문 답 해보기(LLM OCR)

bigc 2025. 4. 2. 17:03
반응형

https://huggingface.co/Qwen/Qwen2.5-VL-32B-Instruct

 

Qwen/Qwen2.5-VL-32B-Instruct · Hugging Face

Qwen2.5-VL-32B-Instruct Latest Updates: In addition to the original formula, we have further enhanced Qwen2.5-VL-32B's mathematical and problem-solving abilities through reinforcement learning. This has also significantly improved the model's subjective us

huggingface.co

 

 

Qwen2.5-VL 나온 초창기에 7B 모델로 OCR 테스트해 봤는데, table 처리 성능이 별로라 아얘 안 보고 있었습니다.

매일 huggingface에 무슨 모델 나오나 보던중 Qwen2.5-VL-32B 모델이 있길래 바로 클릭

 

Gemma3-27B, Qwen2-VL-72B 모델도 뛰어넘는 성과라고 해서 기대

 

OCR 테스트 가봅니다.

 

 

Huggingface transformers 중 가장 최신께 필요해서

pip install git+https://github.com/huggingface/transformers accelerate

# It's highly recommanded to use `[decord]` feature for faster video loading.
pip install qwen-vl-utils[decord]==0.0.8

 

- Qwen2.5-VL-32B-Instruct OCR, 질의응답 예시 

 

from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
import torch

# 모델 로드
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-VL-32B-Instruct", torch_dtype="auto", device_map="auto"
    #"Qwen/Qwen2.5-VL-72B-Instruct", torch_dtype="auto", device_map="auto"
    
)
processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-32B-Instruct")
#processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-72B-Instruct")

# 이미지 파일
image_path = "KDS677015-09.jpg"

# 1️⃣ OCR 수행 - 이미지에서 텍스트 추출
messages_ocr = [
    {
        "role": "user",
        "content": [
            {"type": "image", "image": image_path},
            {"type": "text", "text": "이미지를 OCR을 수행하여 문자를 추출하시오. 그 외의 다른 출력은 하지 마시오."}
        ],
    }
]

# 입력 데이터 처리
text_ocr = processor.apply_chat_template(messages_ocr, tokenize=False, add_generation_prompt=True)
image_inputs, _ = process_vision_info(messages_ocr)

inputs_ocr = processor(
    text=[text_ocr],
    images=image_inputs,
    padding=True,
    return_tensors="pt",
).to("cuda")

# OCR 실행
generated_ids_ocr = model.generate(**inputs_ocr, max_new_tokens=2048)
ocr_text = processor.batch_decode(generated_ids_ocr, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]

print("\n🔹 [OCR 결과]")
print(ocr_text)

# 2️⃣ LLM에게 질문하여 답변 생성
messages_qna = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": f"OCR 결과를 바탕으로, '밭의 자갈함유량이 7%일 때의 급위는?'이라는 질문에 답하시오.\n\nOCR 결과:\n{ocr_text}"}
        ],
    }
]

# 입력 데이터 처리
text_qna = processor.apply_chat_template(messages_qna, tokenize=False, add_generation_prompt=True)

inputs_qna = processor(
    text=[text_qna],
    padding=True,
    return_tensors="pt",
).to("cuda")

# 모델 실행
generated_ids_qna = model.generate(**inputs_qna, max_new_tokens=1024)
answer = processor.batch_decode(generated_ids_qna, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]

print("\n🔹 [LLM의 답변]")
print(answer)

 

 

위 표가 들어가있는 이미지를 OCR 해봤습니다.

H100 80GB GPU 사용하였고, 70GB정도 사용하였으며 약 70s 걸렸습니다. 

 

 

구분 밑에 '밭'을 '발'이라 한 것 빼고는 아주 깔끔하게 가져왔습니다.

7B 모델 사용할 때는 '밭'을 이상하게 인식하지 못하더라고요.

 

 

다음으로 "OCR 결과를 바탕으로, '밭의 자갈함유량이 7% 일 때의 급위는?'이라는 질문에 답하시오"라는 질문에 대한 답입니다. 

'밭'을 '발'로 인식했는데 어떻게 답은 잘하더라고요. 7B 모델은 답 실패했었습니다.

 

 

Qwen2.5-VL-32B 모델 성능 좋네요. 이 모델로 이것저것 테스트 좀 더 해봐야겠습니다.

 

LLM이 모델이 무거워서 아직 적용이 어려운 분야들이 있지만 앞으로 OCR이라던가 비전 관련 과제들 많이 처리해 줄 것으로 큰 기대됩니다.

 

반응형