Yuchan commited on
Commit
348bcce
ยท
verified ยท
1 Parent(s): 4423448

Create Model_torch.py

Browse files
Files changed (1) hide show
  1. Model_torch.py +198 -0
Model_torch.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torch.utils.data import Dataset, DataLoader
5
+ import numpy as np
6
+ import sentencepiece as spm
7
+
8
+ # ===============================
9
+ # SentencePiece
10
+ # ===============================
11
+ sp = spm.SentencePieceProcessor("ko_unigram.model")
12
+
13
+ pad_id = sp.piece_to_id("<pad>") if sp.piece_to_id("<pad>") != -1 else 0
14
+ start_id = sp.piece_to_id("<start>")
15
+ end_id = sp.piece_to_id("<end>")
16
+ vocab_size = sp.get_piece_size()
17
+ max_len = 512
18
+ batch_size = 32
19
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
20
+
21
+ def text_to_ids(text):
22
+ return sp.encode(text, out_type=int)
23
+
24
+ def ids_to_text(ids):
25
+ return sp.decode(ids)
26
+
27
+ # ===============================
28
+ # Dataset
29
+ # ===============================
30
+ class TextDataset(Dataset):
31
+ def __init__(self, file_path, num_lines=None):
32
+ self.lines = []
33
+ with open(file_path, "r", encoding="utf-8") as f:
34
+ for i, line in enumerate(f):
35
+ if num_lines is not None and i >= num_lines:
36
+ break
37
+ line = line.strip()
38
+ if line:
39
+ self.lines.append(line)
40
+
41
+ def __len__(self):
42
+ return len(self.lines)
43
+
44
+ def __getitem__(self, idx):
45
+ text = self.lines[idx]
46
+ ids = text_to_ids(text)[:max_len-1]
47
+ full_input = ids + [end_id]
48
+ pad_len = max_len - len(full_input)
49
+ full_input += [pad_id]*pad_len
50
+ target = full_input[1:] + [pad_id]
51
+ return torch.tensor(full_input, dtype=torch.long), torch.tensor(target, dtype=torch.long)
52
+
53
+ dataset = TextDataset("corpus.txt", num_lines=100000)
54
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
55
+
56
+ # ===============================
57
+ # ๋ชจ๋ธ ์ •์˜
58
+ # ===============================
59
+ class SwiGLU(nn.Module):
60
+ def __init__(self, d_model):
61
+ super().__init__()
62
+ self.W = nn.Linear(d_model, 3500)
63
+ self.W1 = nn.Linear(1750, d_model)
64
+ def forward(self, x):
65
+ x = self.W(x.float())
66
+ a,b = x.chunk(2, dim=-1)
67
+ return self.W1(F.silu(a)*b).to(x.dtype)
68
+
69
+ class SparseCausalAttention(nn.Module):
70
+ def __init__(self, num_heads, head_dim, window_size=8):
71
+ super().__init__()
72
+ self.num_heads = num_heads
73
+ self.head_dim = head_dim
74
+ self.window_size = window_size
75
+ self.q = nn.Linear(head_dim*num_heads, num_heads*head_dim)
76
+ self.k = nn.Linear(head_dim*num_heads, num_heads*head_dim)
77
+ self.v = nn.Linear(head_dim*num_heads, num_heads*head_dim)
78
+ self.out = nn.Linear(num_heads*head_dim, head_dim*num_heads)
79
+
80
+ def forward(self, x):
81
+ B,L,D = x.shape
82
+ q = self.q(x).view(B,L,self.num_heads,self.head_dim).transpose(1,2)
83
+ k = self.k(x).view(B,L,self.num_heads,self.head_dim).transpose(1,2)
84
+ v = self.v(x).view(B,L,self.num_heads,self.head_dim).transpose(1,2)
85
+ q = q / (self.head_dim ** 0.5)
86
+
87
+ attn_scores = torch.matmul(q, k.transpose(-2,-1))
88
+ mask = torch.tril(torch.ones(L,L, device=x.device))
89
+ band_mask = torch.triu(mask, -self.window_size)
90
+ attn_scores = attn_scores.masked_fill(band_mask==0, float('-inf'))
91
+ attn_probs = F.softmax(attn_scores, dim=-1)
92
+ out = torch.matmul(attn_probs, v)
93
+ out = out.transpose(1,2).reshape(B,L,D)
94
+ return self.out(out)
95
+
96
+ class Lo(nn.Module):
97
+ def __init__(self,d_model):
98
+ super().__init__()
99
+ self.d = nn.Linear(d_model,64)
100
+ self.w = nn.Linear(64,d_model)
101
+ self.norm = nn.LayerNorm(d_model)
102
+ def forward(self,x):
103
+ return self.norm(self.w(F.silu(self.d(x))) + x)
104
+
105
+ class Block(nn.Module):
106
+ def __init__(self,d_model):
107
+ super().__init__()
108
+ self.attn = SparseCausalAttention(num_heads=2, head_dim=64)
109
+ self.glu = SwiGLU(d_model)
110
+ self.norm = nn.LayerNorm(d_model)
111
+ self.lo = Lo(d_model)
112
+ def forward(self,x):
113
+ x = self.attn(x)
114
+ x = self.norm(self.glu(x)+x)
115
+ x = self.lo(x)
116
+ return x
117
+
118
+ class ReLM(nn.Module):
119
+ def __init__(self,vocab_size,max_seq_len,d_model,n_layers):
120
+ super().__init__()
121
+ self.token_embedding = nn.Embedding(vocab_size,d_model)
122
+ self.pos_embedding = nn.Embedding(max_seq_len,d_model)
123
+ self.blocks = nn.ModuleList([Block(d_model) for _ in range(n_layers)])
124
+ self.ln_f = nn.LayerNorm(d_model)
125
+ self.d_model = d_model
126
+
127
+ def forward(self,x):
128
+ B,L = x.shape
129
+ positions = torch.arange(L,device=x.device).unsqueeze(0)
130
+ x = self.token_embedding(x) + self.pos_embedding(positions)
131
+ for block in self.blocks:
132
+ x = block(x)
133
+ x = self.ln_f(x)
134
+ logits = x @ self.token_embedding.weight.T
135
+ return logits
136
+
137
+ # ===============================
138
+ # ํ•™์Šต
139
+ # ===============================
140
+ model = ReLM(vocab_size, max_len, 128, 2).to(device)
141
+ optimizer = torch.optim.Adam(model.parameters(), lr=5e-5)
142
+ scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.9)
143
+ loss_fn = nn.CrossEntropyLoss(ignore_index=pad_id)
144
+
145
+ epochs = 1
146
+ for epoch in range(epochs):
147
+ model.train()
148
+ total_loss = 0
149
+ for step,(x,y) in enumerate(dataloader):
150
+ x,y = x.to(device), y.to(device)
151
+ optimizer.zero_grad()
152
+ logits = model(x)
153
+ loss = loss_fn(logits.view(-1,vocab_size), y.view(-1))
154
+ loss.backward()
155
+ torch.nn.utils.clip_grad_norm_(model.parameters(),1.0)
156
+ optimizer.step()
157
+ total_loss += loss.item()
158
+ if step % 100 == 0:
159
+ print(f"Epoch {epoch+1}, Step {step}, Loss: {loss.item():.4f}")
160
+ scheduler.step()
161
+ print(f"Epoch {epoch+1} ์™„๋ฃŒ, ํ‰๊ท  Loss: {total_loss/len(dataloader):.4f}")
162
+
163
+ torch.save(model.state_dict(), "relm_model.pth")
164
+ print("๋ชจ๋ธ ์ €์žฅ ์™„๋ฃŒ!")
165
+
166
+ # ===============================
167
+ # Top-p ์ƒ˜ํ”Œ๋ง ์ƒ์„ฑ
168
+ # ===============================
169
+ def generate_text_topp(model, prompt, max_len=150, max_gen=150, p=0.9, temperature=0.6, min_len=20):
170
+ model.eval()
171
+ model_input = text_to_ids(f"<start> {prompt}")
172
+ model_input = model_input[:max_len]
173
+ generated = list(model_input)
174
+ with torch.no_grad():
175
+ for step in range(max_gen):
176
+ input_seq = generated[-max_len:] if len(generated)>max_len else generated
177
+ input_tensor = torch.tensor([input_seq + [pad_id]*(max_len-len(input_seq))], device=device)
178
+ logits = model(input_tensor)
179
+ next_logits = logits[0,len(input_seq)-1]
180
+ next_logits[end_id] -= 5.0
181
+ next_logits[pad_id] -= 10.0
182
+ probs = F.softmax(next_logits/temperature, dim=-1).cpu().numpy()
183
+ sorted_indices = np.argsort(probs)[::-1]
184
+ sorted_probs = probs[sorted_indices]
185
+ cumulative_probs = np.cumsum(sorted_probs)
186
+ cutoff = np.searchsorted(cumulative_probs,p)
187
+ top_indices = sorted_indices[:cutoff+1]
188
+ top_probs = sorted_probs[:cutoff+1]
189
+ top_probs /= top_probs.sum()
190
+ next_token = np.random.choice(top_indices, p=top_probs)
191
+ if next_token==end_id and len(generated)>=min_len:
192
+ break
193
+ generated.append(int(next_token))
194
+ return ids_to_text(generated)
195
+
196
+ # ํ…Œ์ŠคํŠธ
197
+ print("\n===== ์ƒ์„ฑ ๊ฒฐ๊ณผ =====")
198
+ print(generate_text_topp(model, "์ง€๋‚œ 2๋…„ ๋™์•ˆ ์ถœ์—ฐ์—ฐ์ด ๊ตญ๊ฐ€๊ฐ€ ํ•„์š”ํ•œ ์—ฐ๊ตฌ๋ฅผ", p=0.9))