Microsoft MVP성태의 닷넷 이야기
닷넷: 2353. C# - Foundry Local을 이용한 gpt-oss-20b 모델 사용 [링크 복사], [링크+제목 복사],
조회: 629
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 6개 있습니다.)
개발 환경 구성: 748. Windows + Foundry Local - 로컬에서 AI 모델 활용
; https://www.sysnet.pe.kr/2/0/13943

닷넷: 2337. C# - Hugging Face에 공개된 LLM 모델을 Foundry Local에서 사용하는 방법
; https://www.sysnet.pe.kr/2/0/13954

닷넷: 2338. C# / Foundry Local - Phi-4-multimodal 모델을 사용하는 방법
; https://www.sysnet.pe.kr/2/0/13957

닷넷: 2339. C# - Phi-4-multimodal 모델의 GPU 가속 방법 (ORT 사용)
; https://www.sysnet.pe.kr/2/0/13958

닷넷: 2348. C# - 카카오 카나나 모델 + Microsoft.ML.OnnxRuntimeGenAI 예제
; https://www.sysnet.pe.kr/2/0/13976

닷넷: 2353. C# - Foundry Local을 이용한 gpt-oss-20b 모델 사용
; https://www.sysnet.pe.kr/2/0/13992




C# - Foundry Local을 이용한 gpt-oss-20b 모델 사용

오호~~~ 최근 OpenAI에서 GPT OSS 20B 모델을 공개했는데요, Hugging Face에도 올라온 상태입니다.

openai/gpt-oss-20b
; https://huggingface.co/openai/gpt-oss-20b/blob/main/config.json

아쉽게도 "GptOssForCausalLM" 구조라 olive를 이용한 ONNX 포맷으로의 전환이 안 되는 유형이었는데, 마이크로소프트에서 발 빠르게 이것을 Foundry Local에 기본 지원 모델로 포함시켰기 때문에,

Available today: gpt-oss-20B Model on Windows with GPU Acceleration – further pushing the boundaries on the edge
; https://blogs.windows.com/windowsdeveloper/2025/08/05/available-today-gpt-oss-20b-model-on-windows-with-gpu-acceleration-further-pushing-the-boundaries-on-the-edge/

지난 글에서 설명한 방법대로 C#에서도 손쉽게 접근할 수 있습니다.

Windows + Foundry Local - 로컬에서 AI 모델 활용
; https://www.sysnet.pe.kr/2/0/13943




그래도 한번 실습을 해볼까요? ^^ 일단 olive 변환은 할 수 없으니, Foundry Local을 이용해 다음과 같이 다운로드할 수 있습니다.

C:\temp> foundry model download gpt-oss-20B
Downloading gpt-oss-20b-cuda-gpu...
[####################################] 100.00 % [Time remaining: about 0s]        36.9 MB/s
Tips:
- To find model cache location use: foundry cache location
- To find models already downloaded use: foundry cache ls

이후 OpenAI 패키지로 Foundry Local과 연동해 이런 식으로 코딩할 수 있습니다.

using OpenAI;
using OpenAI.Chat;
using System.ClientModel;

namespace ConsoleApp1;

internal class Program
{
    // Install-Package OpenAI 
    static void Main(string[] args)
    {
        string ep = "http://localhost:5273/v1";
        string key = "OPENAI_API_KEY";
        string alias = "gpt-oss-20b-cuda-gpu";

        OpenAIClientOptions options = new OpenAIClientOptions();
        options.Endpoint = new Uri(ep);

        ApiKeyCredential akc = new ApiKeyCredential(key);
        ChatClient client = new(alias, akc, options);

        ChatCompletion completion = client.CompleteChat("하늘이 파란 이유는?'");

        foreach (var message in completion.Content)
        {
            Console.WriteLine($"[{message.Kind}]: {message.Text}");
        }
    }
}

/* 실행 결과:

[Text]: <|channel|>analysis<|message|>The user says: "하늘이 파란 이유는?" in Korean, which translates to "The reason why the sky is blue?" The question is likely about the reason behind Rayleigh scattering, color of sky because of scattering of shorter wavelengths of visible light off atmosphere, etc.

We need to respond. The user didn't give any context besides asking. They just say in Korean: "The reason the sky is blue?" So answer: It's due to Rayleigh scattering causing blue light to be scattered more.

We can provide explanation: solar light: white, but Earth's atmosphere scatters more of blue wavelengths, causing blue sky.

So just answer like: "태양빛이 투과하면서 대기 중 분자와 아주 작은 입자에 의해 산란된 파장에서 가장 짧은 파장이 산란이 가장 잘 일어나므로..." or we can keep simple.

We can also mention the "Huygens–Fresnel principle" or "Mie scattering
*/

참고로, 모델 용량이 11GB 정도여서 그런지 초기 로딩 시간이 꽤 걸리는군요. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




Foundry Local을 통해 다운로드한 모델의 경우 .\Microsoft\gpt-oss-20b-cuda-gpu\v1 디렉터리에 genai_config.json 파일이 함께 있습니다. 아하... 그렇다면 Microsoft.ML.OnnxRuntimeGenAI 패키지를 이용하는 것도 가능하다는 의미일 텐데요,

using Microsoft.ML.OnnxRuntimeGenAI;
using System.Reflection;
using System.Reflection.Emit;

namespace ConsoleApp2;

internal class Program
{
    // Install-Package Microsoft.ML.OnnxRuntimeGenAI.CUDA

    static void Main(string[] args)
    {
        // cuDNN 필요
        string? path = Environment.GetEnvironmentVariable("PATH");
        path += @";C:\Program Files\NVIDIA\CUDNN\v9.10\bin\12.9";
        Environment.SetEnvironmentVariable("PATH", path);

        string modelPath = @"C:\foundry_cache\Microsoft\gpt-oss-20b-cuda-gpu\v1";

        Console.Write("Loading model from " + modelPath + "...");
        using Model model = new(modelPath);
        Console.Write("Done\n");
        using Tokenizer tokenizer = new(model);
        using TokenizerStream tokenizerStream = tokenizer.CreateStream();

        while (true)
        {
            Console.Write("User:");

            string prompt = "<|im_start|>user\n" +
                            Console.ReadLine() +
                            "<|im_end|>\n<|im_start|>assistant\n";
            var sequences = tokenizer.Encode(prompt);

            using GeneratorParams gParams = new GeneratorParams(model);
            gParams.SetSearchOption("max_length", 2400);
            using Generator generator = new(model, gParams);
            generator.AppendTokenSequences(sequences);

            Console.Out.Write("\nAI:");
            while (!generator.IsDone())
            {
                generator.GenerateNextToken();
                var token = generator.GetSequence(0)[^1];
                Console.Out.Write(tokenizerStream.Decode(token));
                Console.Out.Flush();
            }
            Console.WriteLine();
        }
    }
}

아쉽게도 실행해 보면 이런 오류가 발생합니다.

Loading model from C:\foundry_cache\Microsoft\gpt-oss-20b-cuda-gpu\v1...Unhandled exception. Microsoft.ML.OnnxRuntimeGenAI.OnnxRuntimeGenAIException: Load model from E:\foundry_cache\Microsoft\gpt-oss-20b-cuda-gpu\v1\model.onnx failed:This is an invalid model. In Node, ("/model/layers.0/attn/GroupQueryAttention", GroupQueryAttention, "com.microsoft", -1) : ("/model/layers.0/attn/qkv_proj/Add/output_0": tensor(float16),"","","past_key_values.0.key": tensor(float16),"past_key_values.0.value": tensor(float16),"/model/attn_mask_reformat/attn_mask_subgraph/Sub/Cast/output_0": tensor(int32),"/model/attn_mask_reformat/attn_mask_subgraph/Gather/Cast/output_0": tensor(int32),"cos_cache": tensor(float16),"sin_cache": tensor(float16),"","","model.layers.0.attn.sinks": tensor(float16),) -> ("/model/layers.0/attn/GroupQueryAttention/output_0": tensor(float16),"present.0.key": tensor(float16),"present.0.value": tensor(float16),) , Error Node(/model/layers.0/attn/GroupQueryAttention) with schema(com.microsoft::GroupQueryAttention:1) has input size 12 not in range [min=7, max=11].
at Microsoft.ML.OnnxRuntimeGenAI.Model..ctor(String modelPath)
at ConsoleApp2.Program.Main(String[] args)


음... 아마도 Microsoft.ML.OnnxRuntimeGenAI 패키지가 업데이트되기를 기다려야 할 것 같습니다. ^^ (기록을 보니까 불과 5일 전에 0.9.0 업데이트가 되었는데 그 버전이 안 됩니다.)




혹시나 Foundry Local에서 gpt-oss-20B 모델을 찾지 못한다고 나오면?

C:\foundry_cache> foundry model run gpt-oss-20B
Exception: Model gpt-oss-20B not found

지난 버전의 Foundry Local을 사용하고 있는 경우인데요, 최신 버전으로 업데이트하면 됩니다.




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







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

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

비밀번호

댓글 작성자
 




1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13872정성태1/23/20254724오류 유형: 944. WinDbg - 원격 커널 디버깅이 연결은 되지만 Break (Ctrl + Break) 키를 눌러도 멈추지 않는 현상
13871정성태1/22/20255454Windows: 278. Windows - 윈도우를 다른 모니터 화면으로 이동시키는 단축키 (Window + Shift + 화살표)
13870정성태1/18/20256760개발 환경 구성: 741. WinDbg - 네트워크 커널 디버깅이 가능한 NIC 카드 지원 확대
13869정성태1/18/20255458개발 환경 구성: 740. WinDbg - _NT_SYMBOL_PATH 환경 변수에 설정한 경로로 심벌 파일을 다운로드하지 않는 경우
13868정성태1/17/20254935Windows: 277. Hyper-V - Windows 11 VM의 Enhanced Session 모드로 로그인을 할 수 없는 문제
13867정성태1/17/20257549오류 유형: 943. Hyper-V에 Windows 11 설치 시 "This PC doesn't currently meet Windows 11 system requirements" 오류
13866정성태1/16/20258200개발 환경 구성: 739. Windows 10부터 바뀐 device driver 서명 방법
13865정성태1/15/20256892오류 유형: 942. C# - .NET Framework 4.5.2 이하의 버전에서 HttpWebRequest로 https 호출 시 "System.Net.WebException" 예외 발생
13864정성태1/15/20256940Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
13863정성태1/14/20255172Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
13862정성태1/13/20255957Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
13861정성태1/11/20256243Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
13860정성태1/10/20255609디버깅 기술: 216. WinDbg - 2가지 유형의 식 평가 방법(MASM, C++)
13859정성태1/9/20256816디버깅 기술: 215. Windbg - syscall 이후 실행되는 KiSystemCall64 함수 및 SSDT 디버깅
13858정성태1/8/20256977개발 환경 구성: 738. PowerShell - 원격 호출 시 "powershell.exe"가 아닌 "pwsh.exe" 환경으로 명령어를 실행하는 방법
13857정성태1/7/20257257C/C++: 187. Golang - 콘솔 응용 프로그램을 Linux 데몬 서비스를 지원하도록 변경파일 다운로드1
13856정성태1/6/20255480디버깅 기술: 214. Windbg - syscall 단계까지의 Win32 API 호출 (예: Sleep)
13855정성태12/28/20247934오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20247656C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20245993디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20247880디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20246293디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20248194오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20248115디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20247296디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20247100오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...