Views
No views yet
1from transformers import AutoTokenizer, AutoModel, DistilBertForMaskedLM
2import torch
3import torch.nn.functional as F
4
5tokenizer = AutoTokenizer.from_pretrained('bongsoo/mdistilbertV2.1', do_lower_case=False)
6model = DistilBertForMaskedLM.from_pretrained('bongsoo/mdistilbertV2.1')
7
8text = ['한국의 수도는 [MASK] 이다', '에펠탑은 [MASK]에 있다', '충무공 이순신은 [MASK]에 최고의 장수였다']
9tokenized_input = tokenizer(text, max_length=128, truncation=True, padding='max_length', return_tensors='pt')
10
11outputs = model(**tokenized_input)
12logits = outputs.logits
13
14mask_idx_list = []
15for tokens in tokenized_input['input_ids'].tolist():
16 token_str = [tokenizer.convert_ids_to_tokens(s) for s in tokens]
17
18 # **위 token_str리스트에서 [MASK] 인덱스를 구함
19 # => **해당 [MASK] 안덱스 값 mask_idx 에서는 아래 출력하는데 사용됨
20 mask_idx = token_str.index('[MASK]')
21 mask_idx_list.append(mask_idx)
22
23for idx, mask_idx in enumerate(mask_idx_list):
24
25 logits_pred=torch.argmax(F.softmax(logits[idx]), dim=1)
26 mask_logits_idx = int(logits_pred[mask_idx])
27 # [MASK]에 해당하는 token 구함
28 mask_logits_token = tokenizer.convert_ids_to_tokens(mask_logits_idx)
29 # 결과 출력
30 print('\n')
31 print('*Input: {}'.format(text[idx]))
32 print('*[MASK] : {} ({})'.format(mask_logits_token, mask_logits_idx))*Input: 한국의 수도는 [MASK] 이다
*[MASK] : 서울 (48253)
*Input: 에펠탑은 [MASK]에 있다
*[MASK] : 프랑스 (47364)
*Input: 충무공 이순신은 [MASK]에 최고의 장수였다
*[MASK] : 임진왜란 (122835)1from transformers import AutoTokenizer, AutoModel
2import torch
3
4
5#Mean Pooling - Take attention mask into account for correct averaging
6def mean_pooling(model_output, attention_mask):
7 token_embeddings = model_output[0] #First element of model_output contains all token embeddings
8 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
9 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
10
11
12# Sentences we want sentence embeddings for
13sentences = ['This is an example sentence', 'Each sentence is converted']
14
15# Load model from HuggingFace Hub
16tokenizer = AutoTokenizer.from_pretrained('bongsoo/mdistilbertV2.1')
17model = AutoModel.from_pretrained('bongsoo/mdistilbertV2.1')
18
19# Tokenize sentences
20encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
21
22# Compute token embeddings
23with torch.no_grad():
24 model_output = model(**encoded_input)
25
26# Perform pooling. In this case, mean pooling.
27sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
28
29print("Sentence embeddings:")
30print(sentence_embeddings)
31
32# sklearn 을 이용하여 cosine_scores를 구함
33# => 입력값 embeddings 은 (1,768) 처럼 2D 여야 함.
34from sklearn.metrics.pairwise import paired_cosine_distances, paired_euclidean_distances, paired_manhattan_distances
35cosine_scores = 1 - (paired_cosine_distances(sentence_embeddings[0].reshape(1,-1), sentence_embeddings[1].reshape(1,-1)))
36
37print(f'*cosine_score:{cosine_scores[0]}')Sentence embeddings:
tensor([[-0.0166, 0.0129, 0.2805, ..., -0.1452, -0.0855, -0.4914],
[-0.0973, 0.0845, 0.2841, ..., 0.1996, -0.1497, -0.2990]])
*cosine_score:0.5162007808685303{
"_name_or_path": "../../data11/model/distilbert/mdistilbertV2.1-4",
"activation": "gelu",
"architectures": [
"DistilBertForMaskedLM"
],
"attention_dropout": 0.1,
"dim": 768,
"dropout": 0.1,
"hidden_dim": 3072,
"initializer_range": 0.02,
"max_position_embeddings": 512,
"model_type": "distilbert",
"n_heads": 12,
"n_layers": 6,
"output_past": true,
"pad_token_id": 0,
"qa_dropout": 0.1,
"seq_classif_dropout": 0.2,
"sinusoidal_pos_embds": false,
"tie_weights_": true,
"torch_dtype": "float32",
"transformers_version": "4.21.2",
"vocab_size": 152537
}