スパースが得られるように
Browse files- sample-encoding-sparse.py +28 -9
sample-encoding-sparse.py
CHANGED
@@ -1,23 +1,42 @@
|
|
1 |
import torch
|
2 |
import torch.nn as nn
|
3 |
-
from transformers import AutoModel, AutoTokenizer
|
4 |
|
5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
|
|
7 |
|
8 |
# マージされたモデルのロード
|
9 |
-
merged_model =
|
10 |
merged_model.load_state_dict(torch.load("merged_pytorch_model.bin"))
|
11 |
|
12 |
# テキストのエンコード
|
13 |
def encode_text(text):
|
14 |
inputs = tokenizer(text, return_tensors="pt")
|
15 |
-
outputs = merged_model(**inputs)
|
16 |
-
|
17 |
-
|
18 |
-
# Sparseベクトルへの変換
|
19 |
-
sparse_embeddings = merged_model.sparse_linear(dense_embeddings)
|
20 |
-
return dense_embeddings
|
21 |
|
22 |
# テキストのエンコード例
|
23 |
text = "こんにちは"
|
|
|
1 |
import torch
|
2 |
import torch.nn as nn
|
3 |
+
from transformers import AutoModel, AutoTokenizer, XLMRobertaModel
|
4 |
|
5 |
+
# カスタムレイヤーの定義
|
6 |
+
class SparseLinear(nn.Module):
|
7 |
+
def __init__(self, input_dim, output_dim):
|
8 |
+
super(SparseLinear, self).__init__()
|
9 |
+
self.linear = nn.Linear(input_dim, output_dim)
|
10 |
+
|
11 |
+
def forward(self, x):
|
12 |
+
return self.linear(x)
|
13 |
+
|
14 |
+
# カスタムモデルの定義
|
15 |
+
class CustomXLMRobertaModel(XLMRobertaModel):
|
16 |
+
def __init__(self, config):
|
17 |
+
super(CustomXLMRobertaModel, self).__init__(config)
|
18 |
+
self.sparse_linear = SparseLinear(config.hidden_size, 1) # 適切な出力次元を設定
|
19 |
+
|
20 |
+
def forward(self, *args, **kwargs):
|
21 |
+
outputs = super(CustomXLMRobertaModel, self).forward(*args, **kwargs)
|
22 |
+
dense_embeddings = outputs.last_hidden_state
|
23 |
+
sparse_embeddings = self.sparse_linear(dense_embeddings)
|
24 |
+
return outputs, sparse_embeddings
|
25 |
+
|
26 |
+
# モデルとトークナイザーのロード
|
27 |
+
model_name = "." # ローカルディレクトリを指定
|
28 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
29 |
+
config = AutoModel.from_pretrained(model_name).config
|
30 |
|
31 |
# マージされたモデルのロード
|
32 |
+
merged_model = CustomXLMRobertaModel.from_pretrained(model_name, config=config)
|
33 |
merged_model.load_state_dict(torch.load("merged_pytorch_model.bin"))
|
34 |
|
35 |
# テキストのエンコード
|
36 |
def encode_text(text):
|
37 |
inputs = tokenizer(text, return_tensors="pt")
|
38 |
+
outputs, sparse_embeddings = merged_model(**inputs)
|
39 |
+
return outputs, sparse_embeddings
|
|
|
|
|
|
|
|
|
40 |
|
41 |
# テキストのエンコード例
|
42 |
text = "こんにちは"
|