Upload folder using huggingface_hub
Browse files- code/inference.py +191 -0
- code/requirement.txt +5 -0
- config.json +27 -0
- special_tokens_map.json +7 -0
- tokenizer.json +0 -0
- tokenizer_config.json +56 -0
- vocab.txt +0 -0
code/inference.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import torch
|
4 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, AutoConfig
|
5 |
+
|
6 |
+
# 모델과 토크나이저를 로드하는 함수
|
7 |
+
def model_fn(model_dir):
|
8 |
+
"""
|
9 |
+
SageMaker가 모델을 로드하기 위해 호출하는 함수
|
10 |
+
|
11 |
+
Args:
|
12 |
+
model_dir (str): 모델 파일이 저장된 디렉토리 경로
|
13 |
+
|
14 |
+
Returns:
|
15 |
+
dict: 모델, 토크나이저, 설정 등을 포함한 딕셔너리
|
16 |
+
"""
|
17 |
+
# 환경 변수 설정 (선택 사항)
|
18 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
19 |
+
|
20 |
+
# 설정 파일 로드
|
21 |
+
config_path = os.path.join(model_dir, "config.json")
|
22 |
+
config = AutoConfig.from_pretrained(config_path)
|
23 |
+
|
24 |
+
print(f"Loading model from {model_dir}")
|
25 |
+
print(f"Device: {'cuda' if torch.cuda.is_available() else 'cpu'}")
|
26 |
+
|
27 |
+
# 레이블 매핑 로드 (있는 경우)
|
28 |
+
label_map = {}
|
29 |
+
label_map_path = os.path.join(model_dir, "label_map.json")
|
30 |
+
if os.path.exists(label_map_path):
|
31 |
+
with open(label_map_path, 'r', encoding='utf-8') as f:
|
32 |
+
label_map = json.load(f)
|
33 |
+
print(f"Loaded label map from {label_map_path}")
|
34 |
+
else:
|
35 |
+
print("No label map found. Using numeric indices as labels.")
|
36 |
+
|
37 |
+
# 모델 로드
|
38 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
39 |
+
model_dir,
|
40 |
+
config=config,
|
41 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
|
42 |
+
)
|
43 |
+
|
44 |
+
# GPU 사용 가능한 경우 모델을 GPU로 이동
|
45 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
46 |
+
model = model.to(device)
|
47 |
+
model.eval()
|
48 |
+
|
49 |
+
# 토크나이저 로드
|
50 |
+
tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
51 |
+
|
52 |
+
return {
|
53 |
+
"model": model,
|
54 |
+
"tokenizer": tokenizer,
|
55 |
+
"config": config,
|
56 |
+
"device": device,
|
57 |
+
"label_map": label_map
|
58 |
+
}
|
59 |
+
|
60 |
+
# 입력 데이터 처리 함수
|
61 |
+
def input_fn(request_body, request_content_type):
|
62 |
+
"""
|
63 |
+
SageMaker가 요청 데이터를 처리하기 위해 호출하는 함수
|
64 |
+
|
65 |
+
Args:
|
66 |
+
request_body: 요청 본문 데이터
|
67 |
+
request_content_type (str): 요청 콘텐츠 타입
|
68 |
+
|
69 |
+
Returns:
|
70 |
+
dict: 처리된 입력 데이터
|
71 |
+
"""
|
72 |
+
if request_content_type == "application/json":
|
73 |
+
input_data = json.loads(request_body)
|
74 |
+
|
75 |
+
# 문자열인 경우 텍스트로 처리
|
76 |
+
if isinstance(input_data, str):
|
77 |
+
return {"text": input_data}
|
78 |
+
|
79 |
+
return input_data
|
80 |
+
|
81 |
+
elif request_content_type == "text/plain":
|
82 |
+
# 일반 텍스트 처리
|
83 |
+
return {"text": request_body.decode('utf-8')}
|
84 |
+
|
85 |
+
else:
|
86 |
+
raise ValueError(f"지원되지 않는 콘텐츠 타입: {request_content_type}")
|
87 |
+
|
88 |
+
# 예측 함수
|
89 |
+
def predict_fn(input_data, model_dict):
|
90 |
+
"""
|
91 |
+
SageMaker가 모델 예측을 수행하기 위해 호출하는 함수
|
92 |
+
|
93 |
+
Args:
|
94 |
+
input_data (dict): 처리된 입력 데이터
|
95 |
+
model_dict (dict): model_fn에서 반환한 모델 정보
|
96 |
+
|
97 |
+
Returns:
|
98 |
+
dict: 예측 결과
|
99 |
+
"""
|
100 |
+
model = model_dict["model"]
|
101 |
+
tokenizer = model_dict["tokenizer"]
|
102 |
+
device = model_dict["device"]
|
103 |
+
label_map = model_dict["label_map"]
|
104 |
+
|
105 |
+
# 입력 텍스트 가져오기
|
106 |
+
if "text" in input_data:
|
107 |
+
text = input_data["text"]
|
108 |
+
else:
|
109 |
+
raise ValueError("입력 데이터에 'text' 필드가 없습니다")
|
110 |
+
|
111 |
+
# 토큰화 옵션
|
112 |
+
max_length = input_data.get("max_length", 512)
|
113 |
+
padding = input_data.get("padding", "max_length")
|
114 |
+
truncation = input_data.get("truncation", True)
|
115 |
+
|
116 |
+
# 토큰화
|
117 |
+
inputs = tokenizer(
|
118 |
+
text,
|
119 |
+
return_tensors="pt",
|
120 |
+
padding=padding,
|
121 |
+
truncation=truncation,
|
122 |
+
max_length=max_length
|
123 |
+
)
|
124 |
+
|
125 |
+
# 입력 텐서를 디바이스로 이동
|
126 |
+
inputs = {name: tensor.to(device) for name, tensor in inputs.items()}
|
127 |
+
|
128 |
+
# 모델 추론
|
129 |
+
with torch.no_grad():
|
130 |
+
outputs = model(**inputs)
|
131 |
+
logits = outputs.logits
|
132 |
+
probabilities = torch.softmax(logits, dim=1)
|
133 |
+
|
134 |
+
# 이진 분류 모델인 경우 (클래스 수가 2인 경우)
|
135 |
+
if logits.shape[1] == 2:
|
136 |
+
positive_prob = probabilities[0, 1].item()
|
137 |
+
negative_prob = probabilities[0, 0].item()
|
138 |
+
prediction = 1 if positive_prob > 0.5 else 0
|
139 |
+
|
140 |
+
result = {
|
141 |
+
"prediction": prediction,
|
142 |
+
"positive_probability": positive_prob,
|
143 |
+
"negative_probability": negative_prob
|
144 |
+
}
|
145 |
+
|
146 |
+
# 레이블 매핑이 있는 경우 레이블 추가
|
147 |
+
if label_map:
|
148 |
+
pred_label = str(prediction)
|
149 |
+
if pred_label in label_map:
|
150 |
+
result["label"] = label_map[pred_label]
|
151 |
+
|
152 |
+
# 다중 클래스 모델인 ���우
|
153 |
+
else:
|
154 |
+
predictions = torch.argmax(probabilities, dim=1).cpu().numpy().tolist()
|
155 |
+
probabilities = probabilities.cpu().numpy().tolist()[0]
|
156 |
+
|
157 |
+
result = {
|
158 |
+
"prediction": predictions[0],
|
159 |
+
"probabilities": probabilities,
|
160 |
+
}
|
161 |
+
|
162 |
+
# 레이블 매핑이 있는 경우 레이블 추가
|
163 |
+
if label_map:
|
164 |
+
pred_label = str(predictions[0])
|
165 |
+
if pred_label in label_map:
|
166 |
+
result["label"] = label_map[pred_label]
|
167 |
+
|
168 |
+
# 모든 레이블에 대한 확률 매핑 추가
|
169 |
+
result["label_probabilities"] = {
|
170 |
+
label_map.get(str(idx), str(idx)): prob
|
171 |
+
for idx, prob in enumerate(probabilities)
|
172 |
+
}
|
173 |
+
|
174 |
+
return result
|
175 |
+
|
176 |
+
# 출력 데이터 처리 함수
|
177 |
+
def output_fn(prediction, response_content_type):
|
178 |
+
"""
|
179 |
+
SageMaker가 예측 결과를 응답 형식으로 변환하기 위해 호출하는 함수
|
180 |
+
|
181 |
+
Args:
|
182 |
+
prediction: predict_fn에서 반환한 예측 결과
|
183 |
+
response_content_type (str): 원하는 응답 콘텐츠 타입
|
184 |
+
|
185 |
+
Returns:
|
186 |
+
str: 직렬화된 예측 결과
|
187 |
+
"""
|
188 |
+
if response_content_type == "application/json":
|
189 |
+
return json.dumps(prediction, ensure_ascii=False)
|
190 |
+
else:
|
191 |
+
raise ValueError(f"지원되지 않는 콘텐츠 타입: {response_content_type}")
|
code/requirement.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch>=1.13.0
|
2 |
+
transformers>=4.26.0
|
3 |
+
numpy>=1.23.5
|
4 |
+
scikit-learn>=1.0.2
|
5 |
+
protobuf>=3.20.0,<4.0.0
|
config.json
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "bert-base-uncased",
|
3 |
+
"architectures": [
|
4 |
+
"BertForSequenceClassification"
|
5 |
+
],
|
6 |
+
"attention_probs_dropout_prob": 0.1,
|
7 |
+
"classifier_dropout": null,
|
8 |
+
"gradient_checkpointing": false,
|
9 |
+
"hidden_act": "gelu",
|
10 |
+
"hidden_dropout_prob": 0.1,
|
11 |
+
"hidden_size": 768,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 3072,
|
14 |
+
"layer_norm_eps": 1e-12,
|
15 |
+
"max_position_embeddings": 512,
|
16 |
+
"model_type": "bert",
|
17 |
+
"num_attention_heads": 12,
|
18 |
+
"num_hidden_layers": 12,
|
19 |
+
"pad_token_id": 0,
|
20 |
+
"position_embedding_type": "absolute",
|
21 |
+
"problem_type": "single_label_classification",
|
22 |
+
"torch_dtype": "float32",
|
23 |
+
"transformers_version": "4.49.0",
|
24 |
+
"type_vocab_size": 2,
|
25 |
+
"use_cache": true,
|
26 |
+
"vocab_size": 30522
|
27 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cls_token": "[CLS]",
|
3 |
+
"mask_token": "[MASK]",
|
4 |
+
"pad_token": "[PAD]",
|
5 |
+
"sep_token": "[SEP]",
|
6 |
+
"unk_token": "[UNK]"
|
7 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"0": {
|
4 |
+
"content": "[PAD]",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
},
|
11 |
+
"100": {
|
12 |
+
"content": "[UNK]",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": true
|
18 |
+
},
|
19 |
+
"101": {
|
20 |
+
"content": "[CLS]",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false,
|
25 |
+
"special": true
|
26 |
+
},
|
27 |
+
"102": {
|
28 |
+
"content": "[SEP]",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false,
|
33 |
+
"special": true
|
34 |
+
},
|
35 |
+
"103": {
|
36 |
+
"content": "[MASK]",
|
37 |
+
"lstrip": false,
|
38 |
+
"normalized": false,
|
39 |
+
"rstrip": false,
|
40 |
+
"single_word": false,
|
41 |
+
"special": true
|
42 |
+
}
|
43 |
+
},
|
44 |
+
"clean_up_tokenization_spaces": false,
|
45 |
+
"cls_token": "[CLS]",
|
46 |
+
"do_lower_case": true,
|
47 |
+
"extra_special_tokens": {},
|
48 |
+
"mask_token": "[MASK]",
|
49 |
+
"model_max_length": 512,
|
50 |
+
"pad_token": "[PAD]",
|
51 |
+
"sep_token": "[SEP]",
|
52 |
+
"strip_accents": null,
|
53 |
+
"tokenize_chinese_chars": true,
|
54 |
+
"tokenizer_class": "BertTokenizer",
|
55 |
+
"unk_token": "[UNK]"
|
56 |
+
}
|
vocab.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|