Spaces:
Sleeping
Sleeping
Add application file
Browse files
model.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from torch.utils.data import Dataset
|
5 |
+
import math
|
6 |
+
|
7 |
+
class CustomDataset(Dataset):
|
8 |
+
def __init__(self, texts, input_ids, attention_masks, token_type_ids, labels):
|
9 |
+
self.texts = texts
|
10 |
+
self.input_ids = input_ids
|
11 |
+
self.token_type_ids = token_type_ids
|
12 |
+
self.attention_masks = attention_masks
|
13 |
+
self.labels = labels
|
14 |
+
|
15 |
+
|
16 |
+
def __len__(self):
|
17 |
+
return len(self.texts)
|
18 |
+
|
19 |
+
def __getitem__(self, item ):
|
20 |
+
text = self.texts[item]
|
21 |
+
input_id = torch.LongTensor(self.input_ids[item])
|
22 |
+
token_type_id = torch.LongTensor(self.token_type_ids[item])
|
23 |
+
attention_mask = torch.LongTensor(self.attention_masks[item])
|
24 |
+
label = torch.LongTensor(self.labels[item])
|
25 |
+
|
26 |
+
|
27 |
+
return {
|
28 |
+
'text': text,
|
29 |
+
'input_ids': input_id,
|
30 |
+
'token_type_ids': token_type_id,
|
31 |
+
'attention_mask': attention_mask,
|
32 |
+
'labels': label,
|
33 |
+
}
|
34 |
+
class FeedForwardSubLayer(nn.Module):
|
35 |
+
# Specify the two linear layers' input and output sizes
|
36 |
+
def __init__(self, d_model, d_ff):
|
37 |
+
super(FeedForwardSubLayer, self).__init__()
|
38 |
+
self.fc1 = nn.Linear(d_model, d_ff)
|
39 |
+
self.fc2 = nn.Linear(d_ff, d_model)
|
40 |
+
self.relu = nn.ReLU()
|
41 |
+
|
42 |
+
# Apply a forward pass
|
43 |
+
def forward(self, x):
|
44 |
+
return self.fc2(self.relu(self.fc1(x)))
|
45 |
+
|
46 |
+
# Complete the initialization of elements in the encoder layer
|
47 |
+
class EncoderLayer(nn.Module):
|
48 |
+
def __init__(self, d_model, num_heads, d_ff, dropout):
|
49 |
+
super(EncoderLayer, self).__init__()
|
50 |
+
self.self_attn = MultiHeadAttention(d_model, num_heads)
|
51 |
+
self.feed_forward = FeedForwardSubLayer(d_model, d_ff)
|
52 |
+
self.norm1 = nn.LayerNorm(d_model)
|
53 |
+
self.norm2 = nn.LayerNorm(d_model)
|
54 |
+
self.dropout = nn.Dropout(dropout)
|
55 |
+
|
56 |
+
def forward(self, x, mask):
|
57 |
+
attn_output = self.self_attn(x, x, x, mask)
|
58 |
+
x = self.norm1(x + self.dropout(attn_output))
|
59 |
+
ff_output = self.feed_forward(x)
|
60 |
+
return self.norm2(x + self.dropout(ff_output))
|
61 |
+
|
62 |
+
class MultiHeadAttention(nn.Module):
|
63 |
+
def __init__(self, d_model, num_heads):
|
64 |
+
super(MultiHeadAttention, self).__init__()
|
65 |
+
# Set the number of attention heads
|
66 |
+
self.num_heads = num_heads
|
67 |
+
self.d_model = d_model
|
68 |
+
assert d_model % num_heads == 0 #dimension, headlere tam bölünüyormu kontrol et.
|
69 |
+
self.head_dim = d_model // num_heads
|
70 |
+
# Set up the linear transformations
|
71 |
+
self.query_linear = nn.Linear(d_model, d_model)
|
72 |
+
self.key_linear = nn.Linear(d_model, d_model)
|
73 |
+
self.value_linear = nn.Linear(d_model, d_model)
|
74 |
+
self.output_linear = nn.Linear(d_model, d_model)
|
75 |
+
|
76 |
+
def split_heads(self, x, batch_size):
|
77 |
+
# Split the sequence embeddings in x across the attention heads
|
78 |
+
x = x.view(batch_size, -1, self.num_heads, self.head_dim)
|
79 |
+
return x.permute(0, 2, 1, 3) #.contiguous().view(batch_size * self.num_heads, -1, self.head_dim)
|
80 |
+
|
81 |
+
def compute_attention(self, query, key, mask=None):
|
82 |
+
# Compute dot-product attention scores
|
83 |
+
scores = torch.matmul(query, key.permute(0,1,3,2))
|
84 |
+
mask = mask.unsqueeze(1).unsqueeze(1)
|
85 |
+
|
86 |
+
|
87 |
+
if mask is not None:
|
88 |
+
scores = scores.masked_fill(mask == 0, float("-1e20"))
|
89 |
+
# Normalize attention scores into attention weights
|
90 |
+
attention_weights = F.softmax(scores, dim=-1)
|
91 |
+
return attention_weights
|
92 |
+
|
93 |
+
def forward(self, query, key, value, mask=None):
|
94 |
+
batch_size = query.size(0)
|
95 |
+
|
96 |
+
query = self.split_heads(self.query_linear(query), batch_size)
|
97 |
+
key = self.split_heads(self.key_linear(key), batch_size)
|
98 |
+
value = self.split_heads(self.value_linear(value), batch_size)
|
99 |
+
|
100 |
+
attention_weights = self.compute_attention(query, key, mask)
|
101 |
+
|
102 |
+
# Multiply attention weights by values, concatenate and linearly project outputs
|
103 |
+
output = torch.matmul(attention_weights, value)
|
104 |
+
output = output.view(batch_size, self.num_heads, -1, self.head_dim).permute(0, 2, 1, 3).contiguous().view(
|
105 |
+
batch_size, -1, self.d_model)
|
106 |
+
return self.output_linear(output)
|
107 |
+
|
108 |
+
class PositionalEncoder(nn.Module):
|
109 |
+
def __init__(self, d_model, max_length):
|
110 |
+
super(PositionalEncoder, self).__init__()
|
111 |
+
self.d_model = d_model
|
112 |
+
self.max_length = max_length
|
113 |
+
|
114 |
+
# Initialize the positional encoding matrix
|
115 |
+
pe = torch.zeros(max_length, d_model)
|
116 |
+
position = torch.arange(0, max_length, dtype=torch.float).unsqueeze(1)
|
117 |
+
div_term = torch.exp(torch.arange(0, d_model, 2, dtype=torch.float) * -(math.log(10000.0) / d_model))
|
118 |
+
|
119 |
+
# Calculate and assign position encodings to the matrix
|
120 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
121 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
122 |
+
pe = pe.unsqueeze(0)
|
123 |
+
self.register_buffer('pe', pe)
|
124 |
+
|
125 |
+
# Update the embeddings tensor adding the positional encodings
|
126 |
+
def forward(self, x):
|
127 |
+
x = x + self.pe[:, :x.size(1)]
|
128 |
+
return x
|
129 |
+
|
130 |
+
class TransformerEncoder(nn.Module):
|
131 |
+
def __init__(self):
|
132 |
+
super(TransformerEncoder, self).__init__()
|
133 |
+
self.embedding = nn.Embedding(100000, 512)
|
134 |
+
self.positional_encoding = PositionalEncoder(512, 128)
|
135 |
+
# Define a stack of multiple encoder layers
|
136 |
+
self.layers = nn.ModuleList([EncoderLayer(512, 8, 2048, 0.1) for _ in range(6)])
|
137 |
+
|
138 |
+
# Complete the forward pass method
|
139 |
+
def forward(self, x, mask):
|
140 |
+
x = self.embedding(x)
|
141 |
+
x = self.positional_encoding(x)
|
142 |
+
for layer in self.layers:
|
143 |
+
x = layer(x, mask)
|
144 |
+
return x
|
145 |
+
|
146 |
+
def load_model_to_cpu(model, path="model.pth"):
|
147 |
+
checkpoint = torch.load(path, map_location=torch.device('cpu'))
|
148 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
149 |
+
epoch = checkpoint['epoch']
|
150 |
+
return model, epoch
|