Views
No views yet
1import torch
2from transformers import AutoModel, AutoTokenizer
3
4class DimensionReducer(torch.nn.Module):
5 def __init__(self):
6 super().__init__()
7 self.linear = torch.nn.Linear(768, 384)
8 self.layer_norm = torch.nn.LayerNorm(384)
9
10 def forward(self, x):
11 return self.layer_norm(self.linear(x))
12
13# 모델 로드
14model = AutoModel.from_pretrained("kimseongsan/ko-sbert-384")
15tokenizer = AutoTokenizer.from_pretrained("kimseongsan/ko-sbert-384")
16
17# Reducer 로드
18reducer = DimensionReducer()
19reducer.load_state_dict(torch.load("reducer.pt"))
20reducer.eval()
21
22def encode(sentences):
23 if isinstance(sentences, str):
24 sentences = [sentences]
25
26 inputs = tokenizer(sentences, padding=True, truncation=True,
27 max_length=128, return_tensors="pt")
28
29 with torch.no_grad():
30 outputs = model(**inputs)
31 attention_mask = inputs['attention_mask']
32 token_embeddings = outputs.last_hidden_state
33
34 # Mean pooling
35 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
36 sum_embeddings = torch.sum(token_embeddings * input_mask_expanded, 1)
37 sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9)
38 embeddings = sum_embeddings / sum_mask
39
40 # 차원 축소
41 reduced = reducer(embeddings)
42
43 return reduced
44
45# 예시
46sentences = ["안녕하세요", "반갑습니다"]
47embeddings = encode(sentences)
48print(f"Shape: {embeddings.shape}") # torch.Size([2, 384])python quantize_model.py --model kimseongsan/ko-sbert-384