Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

파이썬 - onnxruntime_genai에서 지원하지 않는 모델 사용

기본적으로 "Foundry Local"에서 지원하는 모델들은 onnx 포맷을 지원할 뿐만 아니라 olive 도구를 이용한 변환까지 지원합니다. 이를 통해 Hugging Face에 공개된 다양한 모델을 사용할 수도 있는데요, 아쉽게도 이게 100% 지원되는 것은 아닙니다.

예를 들어 볼까요? ^^ 테스트를 위해 gemma-3n-E2B-it-ONNX 모델을 다운로드한 후,

(huggingface-build) C:\foundry_cache\models\gemma-3n-E2B-it-ONNX> huggingface-cli download onnx-community/gemma-3n-E2B-it-ONNX --include * --local-dir .

onnxruntime_genai 패키지를 이용해 해당 모델을 로드하려고 시도하면,

import onnxruntime_genai as og

model = og.Model('gemma-3n-E2B-it-ONNX/onnx')

이런 오류가 발생합니다.

[윈도우]
(huggingface-build) C:\foundry_cache\models> python onnx_genai.py
Traceback (most recent call last):
  File "C:\foundry_cache\models\onnx_genai.py", line 3, in <module>
    model = og.Model('gemma-3n-E2B-it-ONNX/onnx')
RuntimeError: Error opening gemma-3n-E2B-it-ONNX/onnx\genai_config.json

[리눅스]
(huggingface-build) testusr@TestPC:/mnt/c/foundry_cache/models$ python onnx_genai.py

실제로 gemma-3n-E2B-it-ONNX로부터 다운로드한 디렉터리에는 (지난 글에서 실습한 "Qwen/Qwen2.5-Math-1.5B-Instruct" 모델과는 다르게) genai_config.json이 없습니다.




다른 예를 하나 들어볼까요? onnxruntime_genai 공식 문서에는 deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B 모델에 대한 예제가 있는데요,

Reasoning in Python with DeepSeek-R1-Distill models
; https://onnxruntime.ai/docs/genai/tutorials/deepseek-python.html

이 모델 역시,

deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B
; https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B/tree/main

파일을 보면 genai_config.json이 없습니다. 하지만, olive 명령어로 이것을 onnx 포맷으로 변환하면,

olive auto-opt --model_name_or_path deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B --output_path ./deepseek-r1-distill-qwen-1.5B --device gpu --provider CUDAExecutionProvider --precision int4 --use_model_builder --log_level 1

로컬에 모델을 다운로드 및 onnx 포맷으로 변환이 완료된 시점에 genai_config.json 파일이 함께 생성됩니다. 그러니까, gemma-3n-E2B-it-ONNX도 원래는 genai_config.json 파일이 있어야 하는데... 그걸 repo에서 담고 있지 않는 것입니다. 문제는, (아마도 이 분야로 잘 아시는 분이라면 개별 parameter를 수작업으로 구성할 수 있겠지만) 저 같은 ^^ 초보가 genai_config.json을 임의로 만드는 것이 어렵다는 점입니다.

사실 가장 쉬운 방법은, 처음부터 다시 gemma-3n-E2B-it 모델을 onnx 포맷으로 olive를 이용해 다운로드/변환하면 되는데,

olive auto-opt --model_name_or_path google/gemma-3n-E2B-it --output_path ./gemma-3n-E2B-it --device gpu --provider CUDAExecutionProvider --precision int4 --use_model_builder --log_level 1

실제로 해보면 이렇게 오류가 발생합니다.

Loading HuggingFace model from google/gemma-3n-E2B-it
[... 13:24:56,566] [INFO] [run.py:138:run_engine] Running workflow default_workflow
[... 13:24:56,650] [INFO] [cache.py:138:__init__] Using cache directory: C:\foundry_cache\models\.olive-cache\default_workflow
[... 13:24:56,664] [INFO] [accelerator_creator.py:224:create_accelerators] Running workflow on accelerator specs: gpu-cuda
[... 13:24:56,667] [INFO] [engine.py:246:run] Running Olive on accelerator: gpu-cuda
[... 13:24:56,667] [INFO] [engine.py:888:_create_system] Creating target system ...
[... 13:24:56,668] [INFO] [engine.py:891:_create_system] Target system created in 0.000000 seconds
[... 13:24:56,668] [INFO] [engine.py:902:_create_system] Creating host system ...
[... 13:24:56,668] [INFO] [engine.py:905:_create_system] Host system created in 0.000000 seconds
[... 13:24:56,935] [INFO] [engine.py:709:_run_pass] Running pass model_builder:ModelBuilder {}
[... 13:24:58,063] [ERROR] [engine.py:776:_run_pass] Pass run failed.
Traceback (most recent call last):
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\engine\engine.py", line 764, in _run_pass
    output_model_config = host.run_pass(p, input_model_config, output_model_path, pass_search_point)
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\systems\local.py", line 30, in run_pass
    output_model = the_pass.run(model, output_model_path, point)
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\passes\olive_pass.py", line 245, in run
    output_model = self._run_for_config(model, config, output_model_path)
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\passes\onnx\model_builder.py", line 184, in _run_for_config
    create_model(
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\onnxruntime_genai\models\builder.py", line 3794, in create_model
    raise NotImplementedError(f"The {hf_name} model is not currently supported.")
NotImplementedError: The google/gemma-3n-E2B-it model is not currently supported.
[... 13:24:58,069] [WARNING] [engine.py:334:run_accelerator] Failed to run Olive on gpu-cuda.
Traceback (most recent call last):
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\engine\engine.py", line 330, in run_accelerator
    output_footprint = self.run_no_search(input_model_config, input_model_id, accelerator_spec, output_dir)
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\engine\engine.py", line 400, in run_no_search
    should_prune, signal, model_ids = self._run_passes(
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\engine\engine.py", line 664, in _run_passes
    model_config, model_id = self._run_pass(
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\engine\engine.py", line 764, in _run_pass
    output_model_config = host.run_pass(p, input_model_config, output_model_path, pass_search_point)
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\systems\local.py", line 30, in run_pass
    output_model = the_pass.run(model, output_model_path, point)
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\passes\olive_pass.py", line 245, in run
    output_model = self._run_for_config(model, config, output_model_path)
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\olive\passes\onnx\model_builder.py", line 184, in _run_for_config
    create_model(
  File "C:\Users\testusr\anaconda3\envs\huggingface-build\lib\site-packages\onnxruntime_genai\models\builder.py", line 3794, in create_model
    raise NotImplementedError(f"The {hf_name} model is not currently supported.")
NotImplementedError: The google/gemma-3n-E2B-it model is not currently supported.
[... 13:24:58,070] [INFO] [engine.py:265:run] Run history for gpu-cuda:
[... 13:24:58,070] [INFO] [engine.py:519:dump_run_history] Please install tabulate for better run history output
Command failed. Please set the log_level to 1 for more detailed logs.

아직 지원을 안 하고 있다는 건데요, 반면 (유사하지만 다른 모델인) 예를 들어 gemma-2-2b-it 모델을 입력으로 하면 변환이 잘됩니다.

olive auto-opt --model_name_or_path google/gemma-2-2b-it --output_path ./gemma-2-2b-it --device gpu --provider CUDAExecutionProvider --precision int4 --use_model_builder --log_level 1

공식 문서에 보면,

microsoft/onnxruntime-genai
; https://github.com/microsoft/onnxruntime-genai

* DeepSeek
* Gemma
* Llama *
* Mistral +
* Phi (language + vision)
* Qwen
* Nemotron
* Granite
* AMD OLMo

Gemma 모델 지원이 있긴 하지만, 아직 3n-E2B-it 모델은 지원하지 않는 것 같습니다. 현재 olive 패키지에서 HuggingFace의 특정 모델을 onnx 포맷으로 변환할 수 있는지에 대한 확인은 builder.py 파일을 직접 봐야 합니다. 제 경우에 다음의 경로에 있는데요,

// pip로 설치한 경우
"%USERPROFILE%\anaconda3\envs\huggingface-build\Lib\site-packages\onnxruntime_genai\models\builder.py"

// github 최신 소스 코드
https://github.com/microsoft/onnxruntime-genai/blob/main/src/python/py/models/builder.py

코드를 보면,

...[생략]...

    if "config_only" not in extra_options:
        # List architecture options in alphabetical order
        if config.architectures[0] == "ChatGLMForConditionalGeneration" or config.architectures[0] == "ChatGLMModel":
            # Quantized ChatGLM model has ChatGLMForConditionalGeneration as architecture whereas HF model as the latter
            config.hidden_act = "swiglu"
            onnx_model = ChatGLMModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "GemmaForCausalLM":
            onnx_model = GemmaModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "Gemma2ForCausalLM":
            if precision == "fp16":
                print("WARNING: This model loses accuracy with float16 precision. Setting `--precision bf16` by default.")
                precision = "bf16"
            onnx_model = Gemma2Model(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "Gemma3ForCausalLM":
            if precision == "fp16":
                print("WARNING: This model loses accuracy with float16 precision. Setting `--precision bf16` by default.")
                precision = "bf16"
            onnx_model = Gemma3Model(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
            onnx_model.model_type = "gemma3_text"
        elif config.architectures[0] == "Gemma3ForConditionalGeneration":
            print("WARNING: This is only generating the text component of the model. Setting `--extra_options exclude_embeds=true` by default.")
            text_config = config.text_config
            for key in text_config:
                if not hasattr(config, key):
                    setattr(config, key, getattr(text_config, key))
            if precision == "fp16":
                print("WARNING: This model loses accuracy with float16 precision. Setting `--precision bf16` by default.")
                precision = "bf16"
            onnx_model = Gemma3Model(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "GraniteForCausalLM":
            onnx_model = GraniteModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "LlamaForCausalLM":
            onnx_model = LlamaModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "MistralForCausalLM":
            onnx_model = MistralModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "NemotronForCausalLM":
            onnx_model = NemotronModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "OlmoForCausalLM":
            onnx_model = OLMoModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "PhiForCausalLM":
            onnx_model = PhiModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "Phi3ForCausalLM" and config.max_position_embeddings == config.original_max_position_embeddings:
            onnx_model = Phi3MiniModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "Phi3ForCausalLM" and config.max_position_embeddings != config.original_max_position_embeddings:
            onnx_model = Phi3MiniLongRoPEModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "PhiMoEForCausalLM" and config.max_position_embeddings != config.original_max_position_embeddings:
            print("WARNING: This model only works for CUDA currently because `MoE` is only supported for CUDA in ONNX Runtime. Setting `--execution_provider cuda` by default.")
            print("WARNING: This model currently only supports the quantized version. Setting `--precision int4` by default.")
            execution_provider = "cuda"
            precision = "int4"
            onnx_model = Phi3MoELongRoPEModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "Phi3SmallForCausalLM" and config.max_position_embeddings == config.original_max_position_embeddings:
            onnx_model = Phi3SmallModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "Phi3SmallForCausalLM" and config.max_position_embeddings != config.original_max_position_embeddings:
            onnx_model = Phi3SmallLongRoPEModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "Phi3VForCausalLM":
            print("WARNING: This is only generating the text component of the model. Setting `--extra_options exclude_embeds=true` by default.")
            extra_options["exclude_embeds"] = True
            onnx_model = Phi3VModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "Phi4MMForCausalLM":
            print("WARNING: This is only generating the text component of the model. Setting `--extra_options exclude_embeds=true` by default.")
            extra_options["exclude_embeds"] = True
            onnx_model = Phi4MMModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        elif config.architectures[0] == "Qwen2ForCausalLM":
            onnx_model = QwenModel(config, io_dtype, precision, execution_provider, cache_dir, extra_options)
        else:
            print('model:', hf_name, config.architectures[0])
            raise NotImplementedError(f"The {hf_name} model is not currently supported.")
...[생략]...

여기서 config 변수는 HuggingFace의 모델 페이지에서 공개한 config.json 파일의 내용에 해당합니다. 가령 gemma-3n-E2B-it의 config.json에는,

{
  "architectures": [
    "Gemma3nForConditionalGeneration"
  ],
  ...[생략]...
}

이렇게 architectures[0]의 값이 "Gemma3nForConditionalGeneration"라고 나오는데요, 바로 이 문자열이 builder.py 파일의 if 문에 포함돼 있어야 하는 것입니다.

// gemma-3n-E2B-it의 경우 지원하는 목록에 없는 경우
c:\temp> type "%USERPROFILE%\anaconda3\envs\huggingface-build\Lib\site-packages\onnxruntime_genai\models\builder.py" | findstr "Gemma3nForConditionalGeneration"

// meta-llama/Llama-3.2-1B-Instruct의 경우 지원 목록에 포함한 경우
c:\temp> type "%USERPROFILE%\anaconda3\envs\huggingface-build\Lib\site-packages\onnxruntime_genai\models\builder.py" | findstr "LlamaForCausalLM"
        elif config.architectures[0] == "LlamaForCausalLM":

// 또는, 가끔씩 onnxruntime_genai 패키지가 업데이트되면 github의 소스 코드를 방문해 "Gemma3nForConditionalGeneration" 문자열을 포함하고 있는지 확인해 봐야 합니다. ^^




아쉽지만, 위와 같은 이유로 인해 onnxruntime_genai 패키지로는 gemma-3n-E2B-it를 사용할 수 없고 (README.md 파일에서 설명하듯이) pipeline을 직접 다루는 것으로 우회할 수 있습니다.

import datetime


def log(message):
    print(f"{datetime.datetime.now().strftime('%X')} {message}")


log('import pipeline')

from transformers import pipeline
import torch

log('loading...')

pipe = pipeline(
    "image-text-to-text",
    model="google/gemma-3n-e2b-it",
    device="cuda",
    torch_dtype=torch.bfloat16,
)

log('loaded.')

messages = [
   {
       "role": "user",
       "content": [
           {"type": "image", "url": "https://huggingface.co/datasets/ariG23498/demo-data/resolve/main/airplane.jpg"},
           {"type": "text", "text": "Describe this image"}
       ]
   }
]

output = pipe(text=messages, max_new_tokens=32)

log('chat-completed.')

log(output[0]["generated_text"][-1]["content"])

Windows 환경이라면 WSL을 이용해 다음과 같이 실행할 수 있는데,

// 미리 윈도우 환경에서 다운로드한 모델 파일을 재사용하기 위해 HF_HOME 환경 변수를 설정했습니다.

$ export HF_HOME=/mnt/e/python310/cache/huggingface
$ cd /mnt/c/foundry_cache/models
$ python test.py
10:24:48 import pipeline
10:25:15 loading...
...[생략]...
Device set to use cuda
10:32:35 loaded.
...[생략]...
10:34:45 chat-completed.
10:34:45 The image shows a futuristic, sleek airplane soaring through the sky. It has a very streamlined, almost alien design with a long, narrow body, swept-back

WSL과 Windows 시스템 간의 전송 오버헤드가 있다 보니 모델 로딩에 시간이 꽤 걸리는 것을 볼 수 있습니다. (패키지를 import하는 것만 해도 27초가 걸렸고 모델 로딩에는 약 7분이 넘게 걸렸습니다.)

어쨌든 Gemma 3n 모델을 성공적으로 로딩했고, 이미지에 대한 설명이 적절하게 나오는 것을 볼 수 있습니다.




그나저나, 혹시나 싶어서 OCR 기능도 되지 않을까... 하는 바람으로 다음과 같이 이미지 경로를 바꿔서 질의해 보았는데요,

messages = [
   {
       "role": "user",
       "content": [
           {"type": "image", "url": "https://sysnetblobaccount.blob.core.windows.net/sysnetimages/hf_request_model_access_1.png"},
           {"type": "text", "text": "extract all texts from this image"}
       ]
   }
]

결과가 이렇게 나옵니다. ^^;

13:52:48 Here's the text extracted from the image:

**Top Left:**

* .B- 3- 3M- .S-S-

이 정도면, 이미지 서술과 OCR 기능은 완전 별개임을 짐작게 합니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 7/7/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...
NoWriterDateCnt.TitleFile(s)
13232정성태1/27/202313682스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/202312384오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/202313701개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/202316145.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/202316991.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/202315651개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/202313692.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/202313929개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/202313738Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/202313232오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/202313364개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/202313858Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/202314040오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/202313193Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/202313106VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/202313909디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/202313052디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/202316741Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/202316278.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/202313442오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/202315746기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/202315711웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/202314524Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/202312624Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/202314453.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/202215195.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법 [1]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...