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

Upload test_sample_code.py

Browse files
Files changed (1) hide show
  1. test_sample_code.py +205 -0
test_sample_code.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import torch
4
+ from tqdm import tqdm
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM
6
+ from transformers import AutoModel
7
+ import chromadb
8
+ import re
9
+
10
+ # ======== 사용자 설정 ======== #
11
+ base_model = "/home/sooh5090/axolotl/output/spell-finetune2/checkpoint-139"
12
+ test_file = "../data/json/korean_language_rag_V1.0_test.json"
13
+ output_file = "../output/test_predictions_2.json"
14
+ max_new_tokens = 256
15
+
16
+ # ======== GPU 디바이스 분리 ======== #
17
+ device_llm = torch.device("cuda:3" if torch.cuda.is_available() else "cpu") # LLM
18
+ device_rag = torch.device("cuda:2" if torch.cuda.is_available() else "cpu") # 임베딩
19
+
20
+ # ======== 1. 모델 로드 ======== #
21
+ print("🔄 모델 로드 중...")
22
+ tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)
23
+ tokenizer.pad_token = "<|end_of_text|>"
24
+ tokenizer.eos_token = "<|eot_id|>"
25
+ tokenizer.bos_token = "<|begin_of_text|>"
26
+
27
+ model = AutoModelForCausalLM.from_pretrained(
28
+ base_model,
29
+ device_map={"": device_llm},
30
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
31
+ trust_remote_code=True
32
+ )
33
+ model.eval()
34
+ print("✅ FP16 모델 로드 완료 (GPU 3번)")
35
+
36
+ # ======== 2. RAG 검색기 설정 (GPU 2번) ======== #
37
+ embed_model_id = "dragonkue/snowflake-arctic-embed-l-v2.0-ko"
38
+ embed_tokenizer = AutoTokenizer.from_pretrained(embed_model_id)
39
+ embed_model = AutoModel.from_pretrained(embed_model_id).to(device_rag).eval()
40
+
41
+ client = chromadb.PersistentClient(path="../grammar_db")
42
+ collection = client.get_collection(name="korean_grammar_rules", embedding_function=None)
43
+
44
+ # ======== 3. 임베딩 함수 ======== #
45
+ def embed_query(text, chunk_size=512):
46
+ tokens = embed_tokenizer(text, add_special_tokens=False)["input_ids"]
47
+ chunks = [tokens[i:i + chunk_size] for i in range(0, len(tokens), chunk_size)]
48
+ embeddings = []
49
+ for chunk in chunks:
50
+ inputs = torch.tensor([embed_tokenizer.build_inputs_with_special_tokens(chunk)]).to(device_rag)
51
+ with torch.no_grad():
52
+ output = embed_model(input_ids=inputs).last_hidden_state
53
+ valid_token_count = (inputs != embed_tokenizer.pad_token_id).sum(dim=1, keepdim=True)
54
+ chunk_emb = output.sum(dim=1) / valid_token_count
55
+ embeddings.append(chunk_emb.cpu())
56
+ return torch.stack(embeddings).mean(dim=0).squeeze(0).tolist()
57
+
58
+ # ======== 4. 2개 규범 반환 ======== #
59
+ def retrieve_context(query_text, top_k=3):
60
+ query_vec = embed_query(query_text)
61
+ results = collection.query(query_embeddings=[query_vec], n_results=top_k * 4) # 넉넉하게 받아옴
62
+
63
+ docs = results["documents"][0]
64
+ metas = results["metadatas"][0]
65
+
66
+ seen_rules = set()
67
+ contexts = []
68
+
69
+ for doc, meta in zip(docs, metas):
70
+ rule_text = meta.get("rule", "").strip()
71
+
72
+ if rule_text in seen_rules:
73
+ continue # 동일 규범(rule) 중복 제거
74
+
75
+ seen_rules.add(rule_text)
76
+
77
+ # 참고용: 제목 + 해당 규범 내용 (doc는 안 써도 됨)
78
+ context = f"[{meta['title']}]\n{rule_text}"
79
+ contexts.append(context)
80
+
81
+ if len(contexts) == top_k:
82
+ break
83
+
84
+ return "\n\n".join(contexts)
85
+
86
+ # ======== 4-1. 질문 전처리 함수 ======== #
87
+ def extract_query_from_question(q_type, question):
88
+ if q_type == "선택형":
89
+ matches = re.findall(r"\{([^}]+)\}", question)
90
+ parens_matches = re.findall(r"\(([^\)]+)\)", question)
91
+ tokens = []
92
+
93
+ if matches:
94
+ tokens.extend(re.split(r"[ /]", matches[0]))
95
+ for m in parens_matches:
96
+ if m.strip():
97
+ tokens.extend(re.split(r"[ /]", m.strip()))
98
+
99
+ return " ".join(tokens) if tokens else question
100
+
101
+ else: # 교정형
102
+ dash_lines = [line.strip("― ").strip() for line in question.splitlines() if line.strip().startswith("―")]
103
+ if dash_lines:
104
+ return dash_lines[0]
105
+
106
+ quote_matches = re.findall(r"\"([^\"]+)\"", question)
107
+ if quote_matches:
108
+ return quote_matches[0]
109
+
110
+ parens_matches = re.findall(r"\(([^\)]+)\)", question)
111
+ if parens_matches:
112
+ return parens_matches[0]
113
+
114
+ return question
115
+
116
+ # ======== 5. Instruction 템플릿 ======== #
117
+ INSTRUCTION_TEMPLATES = {
118
+ "교정형": """당신은 한국어 어문 규범(맞춤법, 띄어쓰기, 표준어, 문장부호, 외래어 표기법 등)에 따라 문장을 교정하고 그 이유를 설명하는 AI입니다.
119
+
120
+ [문제 유형: 교정형]
121
+ - 문제와 함께 관련 규범이 주어질 수 있으나, 규범의 타당성을 스스로 판단하여 정답을 도출해야 합니다.
122
+ - 제시된 문장은 반드시 어문 규범에 어긋난 표현을 포함하고 있습니다.
123
+ - 틀린 표현을 정확히 찾아 수정하되, 그 외 표현은 변경하지 마십시오.
124
+ - 답변은 반드시 다음 형식을 따라야 합니다:
125
+ "{수정문}이 옳다. {이유}"
126
+
127
+ [예시]
128
+ 문제: 다음 문장에서 어문 규범에 부합하지 않�� 부분을 찾아 고치고, 그렇게 고친 이유를 설명하세요.
129
+ "어서 쾌차하시길 바래요."
130
+ 정답: "어서 쾌차하시길 바라요."가 옳다. 동사 '바라다'에 어미 '-아요'가 결합한 형태이므로 '바라요'로 써야 한다. '바래요'는 비표준어다.""",
131
+
132
+ "선택형": """당신은 한국어 어문 규범(맞춤법, 띄어쓰기, 표준어, 문장부호, 외래어 표기법 등)에 따라 문장에서 올바른 표현을 선택하고 그 이유를 설명하는 AI입니다.
133
+
134
+ [문제 유형: 선택형]
135
+ - 문제와 함께 관련 규범이 주어질 수 있으나, 규범의 타당성을 스스로 판단하여 정답을 도출해야 합니다.
136
+ - 보기 중 단 하나의 정답이 있으며, 반드시 어문 규범에 따라 하나의 표현만 선택해야 합니다.
137
+ - 선택한 표현 이외의 문장 구성은 수정하지 마십시오.
138
+ - 답변은 반드시 다음 형식을 따라야 합니다:
139
+ "{정답문}이 옳다. {이유}"
140
+
141
+ [예시]
142
+ 문제: "가축을 기를 때에는 {먹이량/먹이양}을 조절해 주어야 한다." 가운데 올바른 것을 선택하고, 그 이유를 설명하세요.
143
+ 정답: "가축을 기를 때에는 먹이양을 조절해 주어야 한다."가 옳다. '먹이'는 고유어이므로, 한자어 '量'은 두음 법칙에 따라 '양'으로 표기해야 한다."""
144
+ }
145
+
146
+ # ======== 6. 테스트 데이터 로드 ======== #
147
+ with open(test_file, "r", encoding="utf-8") as f:
148
+ test_data = json.load(f)
149
+
150
+ # ======== 7. 예측 ======== #
151
+ predictions = []
152
+ for sample in tqdm(test_data, desc="🔍 Test 예측 중"):
153
+ q_type = sample.get("input", {}).get("question_type")
154
+ question = sample.get("input", {}).get("question", "").strip()
155
+
156
+ search_query = extract_query_from_question(q_type, question)
157
+ retrieved = retrieve_context(search_query)
158
+
159
+ instruction = INSTRUCTION_TEMPLATES.get(q_type, INSTRUCTION_TEMPLATES["교정형"])
160
+ input_text = f"[참고 규범]\n{retrieved}\n=====\n문제: {question}\n정답:"
161
+
162
+ # ======== 카나나 프롬프트 ======== #
163
+ prompt = (
164
+ "<|begin_of_text|>\n"
165
+ f"[|system|]{instruction}<|eot_id|>\n"
166
+ f"[|user|]{input_text}<|eot_id|>\n"
167
+ "[|assistant|]"
168
+ )
169
+
170
+ # LLM (GPU 3번)
171
+ inputs = tokenizer(prompt, return_tensors="pt").to(device_llm)
172
+ inputs.pop("token_type_ids", None)
173
+
174
+ with torch.no_grad():
175
+ outputs = model.generate(
176
+ **inputs,
177
+ max_new_tokens=max_new_tokens,
178
+ do_sample=False,
179
+ temperature=0.0,
180
+ eos_token_id=tokenizer.eos_token_id,
181
+ pad_token_id=tokenizer.pad_token_id
182
+ )
183
+
184
+ decoded = tokenizer.decode(outputs[0], skip_special_tokens=False)
185
+ prediction = decoded.split("[|assistant|]")[-1].split(tokenizer.eos_token)[0].strip()
186
+
187
+ print("\n=============================")
188
+ print(f"📝 질문: {question}")
189
+ print(f"🔍 검색 쿼리: {search_query}")
190
+ print(f"📚 검색 컨텍스트:\n{retrieved}")
191
+ print(f"🤖 모델 답변: {prediction}")
192
+ print("=============================\n")
193
+
194
+ predictions.append({
195
+ "id": sample.get("id", ""),
196
+ "input": sample.get("input", {}),
197
+ "output": {"answer": prediction}
198
+ })
199
+
200
+ # ======== 8. 결과 저장 ======== #
201
+ os.makedirs(os.path.dirname(output_file), exist_ok=True)
202
+ with open(output_file, "w", encoding="utf-8") as f:
203
+ json.dump(predictions, f, ensure_ascii=False, indent=2)
204
+
205
+ print(f"\n📄 테스트 결과 저장 완료: {output_file}")