2025년 8월 31일 일요일

RAG 시스템 돌리기

[실행 환경] windows11, python=3.10, conda 가상환경, amd 7950x CPU,  64gb main ram, RTX Titan 24Gb GPU


1. llm 모델: Qwen2.5-32B-Instruct-AWQ (Alibaba모델)

- vllm의 직접 실행이 안되어서 docker기반으로 실행

- G:\huggingface_models 폴더 아래에 다운 받은 qwen모델 있음

(testllm) G:\>docker run --gpus all -v G:\huggingface_models:/root/.cache/huggingface -p 8000:8000 --ipc=host -e HUGGING_FACE_HUB_TOKEN=hf_xxxxxxxx vllm/vllm-openai:v0.5.5 --model Qwen/Qwen2.5-32B-Instruct-AWQ --dtype float16 --served-model-name qwen2.5-32b --api-key pnu-vislab --max-model-len 2500 --gpu-memory-utilization 0.95


(option의미)

--gpu-memory-utilization 0.92: gpu메모리(vram) 이용율, 92%까지 gpu메모리 사용 가능

--api-key pnu-vislab: rag_api.py 코드 등에서 이 키를 사용해야 함

HUGGING_FACE_HUB_TOKEN=... : llm모델 다운 가능하려면 huggingface 키를 받아 사용해야 함

--served-model-name qwen2.5-32b: Qwen/Qwen2.5-32B-Instruct-AWQ모델을 사용 중인데 외부에서 refering을 위한 이름


(실행)

INFO 08-31 19:12:37 weight_utils.py:236] Using model weights format ['*.safetensors']

Loading safetensors checkpoint shards:   0% Completed | 0/5 [00:00<?, ?it/s]

Loading safetensors checkpoint shards:  20% Completed | 1/5 [01:36<06:27, 96.96s/it]

Loading safetensors checkpoint shards:  40% Completed | 2/5 [03:17<04:56, 98.87s/it]

.....

다운 받은 파일을 vram에 로드(시간 좀 걸림) 한 후, 오류가 잘 발생하는데, KV(key-value) cache memory부족 오류가 자주 뜸. 

--max-model-len 2500를 1024로 더 줄이고,

--gpu-memory-utilization 0.92를 0.95로 더 늘리고...

현재 모델을 24g vram에서 돌리기에는 빠듯한 느낌



2. 벡터 DB(qdrant) 실행

(testllm) G:\>docker run -d --name qdrant -p 6333:6333 -p 6334:6334 -v G:/qdrant_storage:/qdrant/storage qdrant/qdrant



3. 문서 인덱싱

(testllm) G:\2025\rag_server>python index_documents.py

🚀 테스트 문서 인덱싱 시작

임베딩 모델 로딩 중...

Fetching 30 files: 100%|██████████████| 30/30 [00:00<00:00, 14999.30it/s]

✅ 임베딩 모델 로드 완료

✅ Qdrant 연결 성공

⚠️  기존 컬렉션 'pet_corpus_m3' 발견. 삭제 후 재생성...

✅ 컬렉션 'pet_corpus_m3' 생성 완료

✅ 10개 문서 로드 완료

문서 임베딩 중...

You're using a XLMRobertaTokenizerFast tokenizer. Please note that with a fast tokenizer, using the __call__ method is faster than using a method to encode the text followed by a call to the pad method to get a padded encoding.

진행률: 5/10 - 벡터 차원: 1024

진행률: 10/10 - 벡터 차원: 1024

✅ 10개 포인트 생성 완료

Qdrant에 업로드 중...

✅ 인덱싱 완료: 10개 문서

📊 컬렉션 통계: 10개 포인트

⏱️  총 소요시간: 4.33초




4. RAG_API 서버 시작

(testllm) G:\2025\rag_server>python rag_api.py

G:\2025\rag_server\rag_api.py:65: DeprecationWarning:

        on_event is deprecated, use lifespan event handlers instead.

        Read more about it in the

        [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).

  @app.on_event("startup")

🐾 테스트 케어 RAG API 서버 시작

📖 API 문서: http://localhost:9000/docs

🔍 테스트: curl -X POST http://localhost:9000/chat-rag -H 'Content-Type: application/json' -d '{"question":"강아지 체온이 높을 때 어떻게 해야 하나요?"}'

INFO:     Will watch for changes in these directories: ['G:\\2025\\rag_server']

INFO:     Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit)

INFO:     Started reloader process [17224] using WatchFiles

INFO:     Started server process [40288]

INFO:     Waiting for application startup.

INFO:rag_api:🚀 서버 초기화 시작

INFO:rag_api:임베딩 모델 로딩...

INFO:watchfiles.main:5 changes detected

Fetching 30 files: 100%|████████████████| 30/30 [00:00<00:00, 9983.27it/s]

INFO:FlagEmbedding.finetune.embedder.encoder_only.m3.runner:loading existing colbert_linear and sparse_linear---------

INFO:rag_api:✅ 임베딩 모델 로드 완료

INFO:rag_api:Qdrant 연결 중...

INFO:httpx:HTTP Request: GET http://127.0.0.1:6333 "HTTP/1.1 200 OK"

INFO:httpx:HTTP Request: GET http://127.0.0.1:6333/collections "HTTP/1.1 200 OK"

INFO:httpx:HTTP Request: GET http://127.0.0.1:6333/collections/pet_corpus_m3 "HTTP/1.1 200 OK"

INFO:rag_api:✅ Qdrant 연결 완료 (문서 수: 10)

INFO:rag_api:vLLM 연결 중...

INFO:httpx:HTTP Request: GET http://127.0.0.1:8000/v1/models "HTTP/1.1 200 OK"

INFO:rag_api:✅ vLLM 연결 완료 (사용 가능 모델: ['qwen2.5-32b'])

INFO:rag_api:🎉 서버 초기화 완료!

INFO:     Application startup complete.

INFO:rag_api:질문 받음: 강아지 체온이 높을 때 어떻게 해야 하나요?

You're using a XLMRobertaTokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.

INFO:httpx:HTTP Request: POST http://127.0.0.1:6333/collections/pet_corpus_m3/points/search "HTTP/1.1 200 OK"

INFO:rag_api:LLM 응답 생성 중...

INFO:httpx:HTTP Request: POST http://127.0.0.1:8000/v1/chat/completions "HTTP/1.1 200 OK"

INFO:rag_api:✅ 응답 생성 완료

INFO:     127.0.0.1:59283 - "POST /chat-rag HTTP/1.1" 200 OK

INFO:httpx:HTTP Request: GET http://127.0.0.1:6333/collections/pet_corpus_m3 "HTTP/1.1 200 OK



5. 실행 예

(testllm) G:\2025\rag_server>curl -X POST http://localhost:9000/chat-rag -H "Content-Type: application/json" -d "{\"question\":\"강아지 체온이 높을 때 어떻게 해야 하나요?\"}"

{"answer":"강아지의 체온이 높을 때, 즉 40도 이상일 경우, 열사병을 의심해야 합니다. 이럴 때는 강아지를 시원한 곳으로 옮기고, 물을 조금씩 먹이도록 합니다. 하지만 이러한 증상이 계속된다면 수의사 상담을 권장드립니다.","sources":[{"text":"강아지의 적정 체온은 38-39도 사이입니다. 체온이 40도 이상이면 열사병을 의심해야 하며, 즉시 시원한 곳으로 옮기고 물을 조금씩 먹여야 합니다.","score":0.7699,"meta":{"category":"건강","species":"강아지"}},{"text":"햄스터는 온도에 민감합니다. 실내 온도는 20-24도가 적당하며, 직사광선과 급격한 온도 변화는 피해야 합니다. 겨울철에는 보온에 특히 신경써야 합니다.","score":0.592,"meta":{"category":"환경","species":"햄스터"}},{"text":"고양이가 구토를 자주 한다면 헤어볼, 식이 알레르기, 또는 소화기 질환을 의심해야 합니다. 하루에 2회 이상 구토하면 수의사 진료를 받으세요.","score":0.5769,"meta":{"category":"건강","species":"고양이"}},{"text":"강아지 치아 관리를 위해서는 주 2-3회 양치질이 필요합니다. 사람용 치약은 절대 사용하지 말고, 반려동물 전용 치약을 사용하세요.","score":0.5598,"meta":{"category":"케어","species":"강아지"}},{"text":"강아지 예방접종은 종합백신(DHPPL), 켄넬코프, 광견병이 기본입니다. 첫 접종은 생후 6-8주, 추가접종은 수의사와 상담하여 결정하세요.","score":0.5527,"meta":{"category":"건강","species":"강아지"}}],"query_info":{"question":"강아지 체온이 높을 때 어떻게 해야 하나요?","results_count":5,"filters_applied":false,"avg_score":0.6102}}



6. 다운된 도커 이미지 확인

(testllm) G:\>docker images

REPOSITORY               TAG        IMAGE ID       CREATED         SIZE

qdrant/qdrant            latest    6ac4807063bb   4 days ago      254MB

vllm/vllm-openai        latest    d731ee65c044   11 days ago     31GB



7. 실행 중인 도커 container 확인

(testllm) G:\huggingface_models>docker container ls

CONTAINER ID   IMAGE                     COMMAND                   CREATED          STATUS          PORTS                              NAMES

f03b00e22ff7   vllm/vllm-openai:v0.5.5   "python3 -m vllm.ent…"   27 seconds ago   Up 27 seconds   0.0.0.0:8000->8000/tcp             admiring_satoshi

d072b9b35f76   qdrant/qdrant             "./entrypoint.sh"         2 days ago       Up 2 days       0.0.0.0:6333-6334->6333-6334/tcp   qdrant