p0x0q commited on
Commit
07816a1
·
1 Parent(s): 79e008e

モデルマージ

Browse files
Files changed (1) hide show
  1. merge-pytorch-model.py +50 -0
merge-pytorch-model.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from transformers import AutoModel, AutoTokenizer, XLMRobertaModel
4
+
5
+ # カスタムモデルの定義
6
+ class CustomXLMRobertaModel(XLMRobertaModel):
7
+ def __init__(self, config):
8
+ super(CustomXLMRobertaModel, self).__init__(config)
9
+ self.sparse_linear = SparseLinear(config.hidden_size, 1) # 適切な出力次元を設定
10
+
11
+ def forward(self, *args, **kwargs):
12
+ outputs = super(CustomXLMRobertaModel, self).forward(*args, **kwargs)
13
+ dense_embeddings = outputs.last_hidden_state
14
+ sparse_embeddings = self.sparse_linear(dense_embeddings)
15
+ return sparse_embeddings
16
+
17
+ # カスタムレイヤーの定義
18
+ class SparseLinear(nn.Module):
19
+ def __init__(self, input_dim, output_dim):
20
+ super(SparseLinear, self).__init__()
21
+ self.linear = nn.Linear(input_dim, output_dim)
22
+
23
+ def forward(self, x):
24
+ return self.linear(x)
25
+
26
+ # モデルとトークナイザーのロード
27
+ model_name = "." # ローカルディレクトリを指定
28
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
29
+ config = AutoModel.from_pretrained(model_name).config
30
+ model = CustomXLMRobertaModel.from_pretrained(model_name, config=config)
31
+
32
+ # カスタムレイヤーのインスタンスを作成
33
+ input_dim = 1024 # Denseベクトルの次元(モデルのhidden_sizeに合わせる)
34
+ output_dim = 1 # Sparseベクトルの次元(保存された重みに合わせる)
35
+ sparse_linear = SparseLinear(input_dim, output_dim)
36
+
37
+ # Sparse線形変換のロード
38
+ sparse_linear_path = "sparse_linear.pt"
39
+ sparse_linear_state_dict = torch.load(sparse_linear_path, weights_only=True)
40
+
41
+ # state_dictのキーを変換
42
+ sparse_linear_state_dict = {
43
+ f"linear.{key}": value for key, value in sparse_linear_state_dict.items()
44
+ }
45
+
46
+ # カスタムレイヤーにstate_dictをロード
47
+ sparse_linear.load_state_dict(sparse_linear_state_dict)
48
+
49
+ # カスタムレイヤーの重みを元のモデルの重みに追加
50
+ model.sparse_linear.load_state_dict(sparse_linear.state_dict())