Sadjad Alikhani
commited on
Delete lwm_model.py
Browse files- lwm_model.py +0 -173
lwm_model.py
DELETED
@@ -1,173 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
LWM (Large Wireless Model) Implementation and Loading
|
3 |
-
|
4 |
-
@author: salikha4
|
5 |
-
|
6 |
-
This module defines a Large Wireless Model (LWM) using PyTorch, including custom layers
|
7 |
-
for embedding, self-attention, and feed-forward networks. It also provides functionality
|
8 |
-
to load a pre-trained model from a checkpoint.
|
9 |
-
|
10 |
-
Dependencies:
|
11 |
-
- torch
|
12 |
-
- numpy
|
13 |
-
"""
|
14 |
-
|
15 |
-
import torch
|
16 |
-
import torch.nn as nn
|
17 |
-
import torch.nn.functional as F
|
18 |
-
import numpy as np
|
19 |
-
|
20 |
-
ELEMENT_LENGTH = 16
|
21 |
-
D_MODEL = 64
|
22 |
-
MAX_LEN = 129
|
23 |
-
N_LAYERS = 12
|
24 |
-
N_HEADS = 12
|
25 |
-
D_FF = D_MODEL * 4
|
26 |
-
D_K = D_MODEL // N_HEADS
|
27 |
-
D_V = D_MODEL // N_HEADS
|
28 |
-
DROPOUT = 0.1
|
29 |
-
|
30 |
-
class LayerNormalization(nn.Module):
|
31 |
-
def __init__(self, d_model: int, eps: float = 1e-6) -> None:
|
32 |
-
super().__init__()
|
33 |
-
self.eps = eps
|
34 |
-
self.alpha = nn.Parameter(torch.ones(d_model))
|
35 |
-
self.bias = nn.Parameter(torch.zeros(d_model))
|
36 |
-
|
37 |
-
def forward(self, x):
|
38 |
-
mean = x.mean(dim=-1, keepdim=True)
|
39 |
-
std = x.std(dim=-1, keepdim=True)
|
40 |
-
return self.alpha * (x - mean) / (std + self.eps) + self.bias
|
41 |
-
|
42 |
-
class Embedding(nn.Module):
|
43 |
-
def __init__(self, element_length, d_model, max_len):
|
44 |
-
super().__init__()
|
45 |
-
self.element_length = element_length
|
46 |
-
self.d_model = d_model
|
47 |
-
self.proj = nn.Linear(element_length, d_model)
|
48 |
-
self.pos_embed = nn.Embedding(max_len, d_model)
|
49 |
-
self.norm = LayerNormalization(d_model)
|
50 |
-
|
51 |
-
def forward(self, x):
|
52 |
-
seq_len = x.size(1)
|
53 |
-
pos = torch.arange(seq_len, dtype=torch.long, device=x.device)
|
54 |
-
pos = pos.unsqueeze(0).expand_as(x[:, :, 0])
|
55 |
-
tok_emb = self.proj(x.float())
|
56 |
-
embedding = tok_emb + self.pos_embed(pos)
|
57 |
-
return self.norm(embedding)
|
58 |
-
|
59 |
-
class ScaledDotProductAttention(nn.Module):
|
60 |
-
def __init__(self):
|
61 |
-
super().__init__()
|
62 |
-
|
63 |
-
def forward(self, Q, K, V):
|
64 |
-
scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(D_K)
|
65 |
-
attn = F.softmax(scores, dim=-1)
|
66 |
-
context = torch.matmul(attn, V)
|
67 |
-
return context, attn
|
68 |
-
|
69 |
-
class MultiHeadAttention(nn.Module):
|
70 |
-
def __init__(self):
|
71 |
-
super().__init__()
|
72 |
-
self.W_Q = nn.Linear(D_MODEL, D_K * N_HEADS)
|
73 |
-
self.W_K = nn.Linear(D_MODEL, D_K * N_HEADS)
|
74 |
-
self.W_V = nn.Linear(D_MODEL, D_V * N_HEADS)
|
75 |
-
self.linear = nn.Linear(N_HEADS * D_V, D_MODEL)
|
76 |
-
self.norm = LayerNormalization(D_MODEL)
|
77 |
-
self.dropout = nn.Dropout(DROPOUT)
|
78 |
-
|
79 |
-
def forward(self, Q, K, V):
|
80 |
-
residual, batch_size = Q, Q.size(0)
|
81 |
-
q_s = self.W_Q(Q).view(batch_size, -1, N_HEADS, D_K).transpose(1, 2)
|
82 |
-
k_s = self.W_K(K).view(batch_size, -1, N_HEADS, D_K).transpose(1, 2)
|
83 |
-
v_s = self.W_V(V).view(batch_size, -1, N_HEADS, D_V).transpose(1, 2)
|
84 |
-
|
85 |
-
context, attn = ScaledDotProductAttention()(q_s, k_s, v_s)
|
86 |
-
output = context.transpose(1, 2).contiguous().view(batch_size, -1, N_HEADS * D_V)
|
87 |
-
output = self.linear(output)
|
88 |
-
return residual + self.dropout(output), attn #residual + self.dropout(output), attn
|
89 |
-
|
90 |
-
class PoswiseFeedForwardNet(nn.Module):
|
91 |
-
def __init__(self):
|
92 |
-
super().__init__()
|
93 |
-
self.fc1 = nn.Linear(D_MODEL, D_FF)
|
94 |
-
self.fc2 = nn.Linear(D_FF, D_MODEL)
|
95 |
-
self.dropout = nn.Dropout(DROPOUT)
|
96 |
-
self.norm = LayerNormalization(D_MODEL)
|
97 |
-
|
98 |
-
def forward(self, x):
|
99 |
-
output = self.fc2(self.dropout(F.relu(self.fc1(x))))
|
100 |
-
return x + self.dropout(output) #x + self.dropout(output)
|
101 |
-
|
102 |
-
class EncoderLayer(nn.Module):
|
103 |
-
def __init__(self):
|
104 |
-
super().__init__()
|
105 |
-
self.enc_self_attn = MultiHeadAttention()
|
106 |
-
self.pos_ffn = PoswiseFeedForwardNet()
|
107 |
-
self.norm = LayerNormalization(D_MODEL)
|
108 |
-
|
109 |
-
def forward(self, enc_inputs):
|
110 |
-
attn_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs)
|
111 |
-
attn_outputs = self.norm(attn_outputs)
|
112 |
-
enc_outputs = self.pos_ffn(attn_outputs)
|
113 |
-
return enc_outputs, attn
|
114 |
-
|
115 |
-
class LWM(nn.Module):
|
116 |
-
def __init__(self, element_length=16, d_model=64, max_len=129, n_layers=12):
|
117 |
-
super().__init__()
|
118 |
-
|
119 |
-
self.embedding = Embedding(element_length, d_model, max_len)
|
120 |
-
self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])
|
121 |
-
self.linear = nn.Linear(d_model, d_model)
|
122 |
-
self.norm = LayerNormalization(d_model)
|
123 |
-
|
124 |
-
embed_weight = self.embedding.proj.weight
|
125 |
-
d_model, n_dim = embed_weight.size()
|
126 |
-
self.decoder = nn.Linear(d_model, n_dim, bias=False)
|
127 |
-
self.decoder.weight = nn.Parameter(embed_weight.transpose(0, 1))
|
128 |
-
self.decoder_bias = nn.Parameter(torch.zeros(n_dim))
|
129 |
-
|
130 |
-
def forward(self, input_ids, masked_pos):
|
131 |
-
output = self.embedding(input_ids)
|
132 |
-
|
133 |
-
for layer in self.layers:
|
134 |
-
output, _ = layer(output)
|
135 |
-
|
136 |
-
masked_pos = masked_pos.long()[:, :, None].expand(-1, -1, output.size(-1))
|
137 |
-
h_masked = torch.gather(output, 1, masked_pos)
|
138 |
-
h_masked = self.norm(F.relu(self.linear(h_masked)))
|
139 |
-
logits_lm = self.decoder(h_masked) + self.decoder_bias
|
140 |
-
|
141 |
-
return logits_lm, output
|
142 |
-
|
143 |
-
def load_model(model, model_path, device=None):
|
144 |
-
"""
|
145 |
-
Load a pre-trained LWM model from a checkpoint.
|
146 |
-
|
147 |
-
Args:
|
148 |
-
model_path (str): Path to the checkpoint file.
|
149 |
-
device (torch.device, optional): Device to load the model onto.
|
150 |
-
|
151 |
-
Returns:
|
152 |
-
LWM: Loaded model instance.
|
153 |
-
"""
|
154 |
-
if device is None:
|
155 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
156 |
-
|
157 |
-
#model = LWM(ELEMENT_LENGTH, D_MODEL, MAX_LEN, N_LAYERS)
|
158 |
-
state_dict = torch.load(model_path, map_location=device)
|
159 |
-
model.load_state_dict(state_dict)
|
160 |
-
model.to(device)
|
161 |
-
return model
|
162 |
-
|
163 |
-
# Usage example
|
164 |
-
if __name__ == "__main__":
|
165 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
166 |
-
model_name = 'model_weights.pth'
|
167 |
-
model_path = f'models/{model_name}'
|
168 |
-
|
169 |
-
model = LWM()
|
170 |
-
|
171 |
-
model = load_model(model, model_path, device)
|
172 |
-
print(f"Model loaded successfully on {device}")
|
173 |
-
print(f"Model parameters: {sum(p.numel() for p in model.parameters())}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|