sooh098 commited on
Commit
80a808c
·
verified ·
1 Parent(s): bb27d82

Delete test_sample_code.py

Browse files
Files changed (1) hide show
  1. test_sample_code.py +0 -176
test_sample_code.py DELETED
@@ -1,176 +0,0 @@
1
- import os
2
- import json
3
- import torch
4
- from tqdm import tqdm
5
- from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
6
- from peft import PeftModel
7
- from transformers import AutoModel, AutoModelForSequenceClassification
8
- import chromadb
9
-
10
- # ======== 사용자 설정 ======== #
11
- base_model = "K-intelligence/Midm-2.0-Base-Instruct"
12
- lora_ckpt = "/home/sooh5090/axolotl/output/midm-finetuneb/checkpoint-1845"
13
- fp16_model_path = "/home/sooh5090/axolotl/output/spell-merged-fp16"
14
- test_file = "../data/json/korean_language_rag_V1.0_test.json"
15
- output_file = "../output/test_predictions.json"
16
- max_new_tokens = 512
17
-
18
- # ======== GPU 디바이스 분리 ======== #
19
- device_llm = torch.device("cuda:3" if torch.cuda.is_available() else "cpu") # LLM
20
- device_rag = torch.device("cuda:2" if torch.cuda.is_available() else "cpu") # 임베딩+리랭커
21
-
22
- # ======== 1. LoRA 병합 ======== #
23
- print("🔄 LoRA 병합 중...")
24
- tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)
25
- base = AutoModelForCausalLM.from_pretrained(
26
- base_model,
27
- device_map={"": device_llm},
28
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
29
- trust_remote_code=True
30
- )
31
- model = PeftModel.from_pretrained(base, lora_ckpt)
32
- model = model.merge_and_unload()
33
- os.makedirs(fp16_model_path, exist_ok=True)
34
- model.save_pretrained(fp16_model_path)
35
- tokenizer.save_pretrained(fp16_model_path)
36
- print(f"✅ FP16 모델 저장 완료: {fp16_model_path}")
37
-
38
- # ======== 2. 4bit 로드 ======== #
39
- bnb_config = BitsAndBytesConfig(
40
- load_in_4bit=True,
41
- bnb_4bit_quant_type="nf4",
42
- bnb_4bit_compute_dtype=torch.float16
43
- )
44
- model = AutoModelForCausalLM.from_pretrained(
45
- fp16_model_path,
46
- quantization_config=bnb_config,
47
- device_map={"": device_llm},
48
- trust_remote_code=True
49
- )
50
- model.eval()
51
- print("✅ 4bit 모델 로드 완료 (GPU 3번)")
52
-
53
- # ======== 3. RAG 검색기/리랭커 설정 (GPU 2번) ======== #
54
- embed_model_id = "dragonkue/snowflake-arctic-embed-l-v2.0-ko"
55
- embed_tokenizer = AutoTokenizer.from_pretrained(embed_model_id)
56
- embed_model = AutoModel.from_pretrained(embed_model_id).to(device_rag).eval()
57
-
58
- reranker_id = "dragonkue/bge-reranker-v2-m3-ko"
59
- reranker_tokenizer = AutoTokenizer.from_pretrained(reranker_id)
60
- reranker_model = AutoModelForSequenceClassification.from_pretrained(reranker_id).to(device_rag).eval()
61
-
62
- client = chromadb.PersistentClient(path="../grammar_db")
63
- collection = client.get_collection(name="korean_grammar_rules", embedding_function=None)
64
-
65
- # ======== 4. 임베딩/리랭킹 함수 ======== #
66
- def embed_query(text, chunk_size=512):
67
- tokens = embed_tokenizer(text, add_special_tokens=False)["input_ids"]
68
- chunks = [tokens[i:i + chunk_size] for i in range(0, len(tokens), chunk_size)]
69
- embeddings = []
70
- for chunk in chunks:
71
- inputs = torch.tensor([embed_tokenizer.build_inputs_with_special_tokens(chunk)]).to(device_rag)
72
- with torch.no_grad():
73
- output = embed_model(input_ids=inputs).last_hidden_state
74
- valid_token_count = (inputs != embed_tokenizer.pad_token_id).sum(dim=1, keepdim=True)
75
- chunk_emb = output.sum(dim=1) / valid_token_count
76
- embeddings.append(chunk_emb.cpu())
77
- return torch.stack(embeddings).mean(dim=0).squeeze(0).tolist()
78
-
79
- def rerank(query, docs):
80
- pairs = [(query, doc) for doc in docs]
81
- inputs = reranker_tokenizer(pairs, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device_rag)
82
- with torch.no_grad():
83
- scores = reranker_model(**inputs).logits.squeeze(-1)
84
- ranked = sorted(zip(docs, scores.tolist()), key=lambda x: x[1], reverse=True)
85
- return ranked[0][0]
86
-
87
- def retrieve_context(query_text, top_k=3):
88
- query_vec = embed_query(query_text)
89
- results = collection.query(query_embeddings=[query_vec], n_results=top_k)
90
- docs = results["documents"][0]
91
- metas = results["metadatas"][0]
92
- best_doc = rerank(query_text, docs)
93
- best_idx = docs.index(best_doc)
94
- title = metas[best_idx]["title"]
95
- return f"[{title}]\n{best_doc.strip()}"
96
-
97
- # ======== 5. Instruction 템플릿 ======== #
98
- INSTRUCTION_TEMPLATES = {
99
- "교정형": """당신은 한국어 어문 규범(맞춤법, 띄어쓰기, 표준어, 문장부호, 외래어 표기법 등)에 따라 문장을 교정하고 그 이유를 설명하는 AI입니다.
100
-
101
- [문제 유형: 교정형]
102
- - 주어진 문장이 어문 규범에 맞는지 판단하십시오.
103
- - 틀린 경우 올바른 형태로 고친 뒤, “~가 옳다. {이유}” 형식으로 답하십시오.
104
- - 문제 문장은 다시 출력하지 마십시오.""",
105
- "선택형": """당신은 한국어 어문 규범(맞춤법, 띄어쓰기, 표준어, 문장부호, 외래어 표기법 등)에 따라 문장에서 올바른 표현을 선택하고 그 이유를 설명하는 AI입니다.
106
-
107
- [문제 유형: 선택형]
108
- - 주어진 보기 중에서 올바른 표현을 선택하십시오.
109
- - 정답은 “~가 옳다. {이유}” 형식으로 작성하십시오.
110
- - 문제 문장은 ��시 출력하지 마십시오."""
111
- }
112
-
113
- # ======== 6. 테스트 데이터 로드 ======== #
114
- with open(test_file, "r", encoding="utf-8") as f:
115
- test_data = json.load(f)
116
-
117
- # ======== 7. 예측 ======== #
118
- predictions = []
119
- for sample in tqdm(test_data, desc="🔍 Test 예측 중"):
120
- q_type = sample.get("input", {}).get("question_type")
121
- question = sample.get("input", {}).get("question", "").strip()
122
-
123
- # RAG 검색 (GPU 2번)
124
- retrieved = retrieve_context(question)
125
-
126
- # 프롬프트 구성
127
- instruction = INSTRUCTION_TEMPLATES.get(q_type, INSTRUCTION_TEMPLATES["교정형"])
128
- input_text = f"[참고 규범]\n{retrieved}\n\n질문: {question}\n답변:"
129
-
130
- prompt = (
131
- "<|begin_of_text|>\n"
132
- f"<|start_header_id|>system<|end_header_id|>\n{instruction}\n"
133
- "<|eot_id|>\n"
134
- f"<|start_header_id|>user<|end_header_id|>\n{input_text}\n"
135
- "<|eot_id|>\n"
136
- "<|start_header_id|>assistant<|end_header_id|>\n"
137
- )
138
-
139
- # LLM (GPU 3번)
140
- inputs = tokenizer(prompt, return_tensors="pt").to(device_llm)
141
- inputs.pop("token_type_ids", None)
142
-
143
- with torch.no_grad():
144
- outputs = model.generate(
145
- **inputs,
146
- max_new_tokens=max_new_tokens,
147
- do_sample=False,
148
- temperature=0.01,
149
- eos_token_id=tokenizer.eos_token_id,
150
- pad_token_id=tokenizer.pad_token_id
151
- )
152
-
153
- decoded = tokenizer.decode(outputs[0], skip_special_tokens=False)
154
- if "<|start_header_id|>assistant<|end_header_id|>\n" in decoded:
155
- prediction = decoded.split("<|start_header_id|>assistant<|end_header_id|>\n")[-1].split("<|end_of_text|>")[0].strip()
156
- else:
157
- prediction = decoded.strip()
158
-
159
- print("\n=============================")
160
- print(f"📝 질문: {question}")
161
- print(f"📚 검색 컨텍스트:\n{retrieved}")
162
- print(f"🤖 모델 답변: {prediction}")
163
- print("=============================\n")
164
-
165
- predictions.append({
166
- "id": sample.get("id", ""),
167
- "input": sample.get("input", {}),
168
- "output": {"answer": prediction}
169
- })
170
-
171
- # ======== 8. 결과 저장 ======== #
172
- os.makedirs(os.path.dirname(output_file), exist_ok=True)
173
- with open(output_file, "w", encoding="utf-8") as f:
174
- json.dump(predictions, f, ensure_ascii=False, indent=2)
175
-
176
- print(f"\n📄 테스트 결과 저장 완료: {output_file}")