Guanzheng commited on
Commit
54314d4
1 Parent(s): 961d152

Create clex_layer.py

Browse files
Files changed (1) hide show
  1. clex_layer.py +137 -0
clex_layer.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torchdiffeq import odeint
4
+
5
+
6
+
7
+ import math
8
+
9
+ class ODELinear(nn.Module):
10
+ def __init__(
11
+ self,
12
+ dim: int,
13
+ factor,
14
+ **kwargs
15
+ ):
16
+ super().__init__()
17
+ self.ode_up_proj = nn.Parameter(torch.empty(dim//2, factor*dim).to(torch.float32))
18
+ self.ode_down_proj = nn.Parameter(torch.empty(factor*dim, dim//2).to(torch.float32))
19
+ self.dim = dim
20
+ self.act = torch.nn.SiLU()
21
+ self.reset_parameters()
22
+
23
+ def reset_parameters(self):
24
+ nn.init.kaiming_uniform_(self.ode_up_proj, a=math.sqrt(5))
25
+ nn.init.zeros_(self.ode_down_proj)
26
+
27
+ def get_time_embedding(self, t, base=10000, device='cuda', dtype=torch.float32):
28
+ if t < 1:
29
+ alpha = 1
30
+ else:
31
+ alpha = 2*t-1
32
+ ntk_base = base * alpha ** (self.dim / (self.dim-2))
33
+ ntk_inv_freq = 1.0 / (ntk_base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim))
34
+ index = torch.arange(0, self.dim, 2, dtype=torch.float32).to(device)
35
+ delta_ntk_freq = -2*index/(self.dim-2) * 1 / (base ** (index/self.dim) * (alpha ** (index/(self.dim-2) + 1)))
36
+ return delta_ntk_freq.to(device, dtype=dtype), ntk_inv_freq.to(device, dtype=dtype)
37
+
38
+ def forward(self, t, x: torch.Tensor):
39
+ delta_time, time = self.get_time_embedding(t, device=x.device, dtype=x.dtype)
40
+ x = x + torch.log(time)
41
+ time_embed = delta_time / time
42
+ delta_inv_freq = self.act(x @ self.ode_up_proj.float()) @ self.ode_down_proj.float() + time_embed
43
+ return delta_inv_freq
44
+
45
+
46
+
47
+ class LlamaCLEXScalingRotaryEmbedding(nn.Module):
48
+
49
+ def __init__(self, dim, max_position_embeddings=2048, rope_scaling=None, base=10000, device=None) -> None:
50
+ super().__init__()
51
+
52
+ self.max_t = rope_scaling["max_factor"]
53
+ self.dim = dim
54
+ self.max_position_embeddings = max_position_embeddings
55
+ self.base = base
56
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
57
+ self.register_buffer("inv_freq", inv_freq)
58
+
59
+ self.proj_func = ODELinear(dim, rope_scaling["param_factor"])
60
+ self.rope_cached = None
61
+ self.max_t_cached = 0
62
+ self.freq_cached = None
63
+ self.time_dt = 0.01
64
+ self.ode_args = {
65
+ "method": "rk4",
66
+ "options": {"step_size": self.time_dt},
67
+ }
68
+
69
+ def sample_random_times(self, max_t, device):
70
+ return torch.randint(2, max_t, (1,), dtype = torch.long, device=device)
71
+
72
+ def get_random_position_ids(self, n=2048, max=8192):
73
+ positions = torch.randperm(max)[:n].sort().values
74
+ # positions = positions.to(device=device)
75
+ return positions
76
+
77
+
78
+ def get_continuous_freq(self, time_grid, ex_positions, device):
79
+ solution = odeint(
80
+ self.proj_func, torch.log(self.inv_freq.to(device, dtype=torch.float32)), time_grid, **self.ode_args
81
+ )
82
+ if time_grid.size(0) == 2:
83
+ training
84
+ scale_inv_freq = torch.exp(solution[1])
85
+ # print(time_grid[1].tolist(), torch.sum(scale_inv_freq).tolist(), torch.sum(self.proj_func.ode_down_proj).tolist())
86
+ freqs = torch.outer(ex_positions.float().squeeze(), scale_inv_freq)
87
+ else:
88
+ scale_inv_freq = torch.exp(solution)
89
+ freqs = torch.einsum('i, kl -> kil', ex_positions, scale_inv_freq)
90
+ embed = torch.cat((freqs,freqs), dim=-1)
91
+ return embed
92
+
93
+
94
+
95
+ def forward(self, device, dtype, seq_len, do_train=False):
96
+ device = self.proj_func.ode_up_proj.device
97
+ scale_factor = seq_len // self.max_position_embeddings
98
+ if do_train:
99
+ t_val = self.sample_random_times(self.max_t+1, device)[0]
100
+ import math
101
+ sampled_position_ids = self.get_random_position_ids(n=seq_len-2, max=seq_len*t_val-2).float()
102
+ ex_positions = torch.cat([
103
+ torch.tensor([0]),
104
+ (sampled_position_ids + 1) / scale_factor,
105
+ torch.tensor([seq_len*t_val//scale_factor-1])]
106
+ ).to(device, dtype=torch.float32)
107
+ else:
108
+ t_val = scale_factor if seq_len%self.max_position_embeddings == 0.0 else scale_factor + 1
109
+ t_val = t_val if t_val <= self.max_t else self.max_t
110
+ ex_positions = torch.arange(0, self.max_position_embeddings * t_val, dtype=torch.float32).to(device)
111
+
112
+
113
+
114
+ if t_val == 1.0:
115
+ scale_inv_freq = self.inv_freq.to(device)
116
+ freqs = torch.outer(ex_positions.float().squeeze(), scale_inv_freq)
117
+ embed = torch.cat((freqs,freqs), dim=-1)
118
+ cos, sin = embed.cos()[None, None, :, :], embed.sin()[None, None, :, :]
119
+ elif do_train:
120
+ time_grid = torch.tensor([1.0, t_val]).float().to(device)
121
+ embed = self.get_continuous_freq(time_grid, ex_positions, device)
122
+ cos, sin = embed.cos()[None, None, :, :], embed.sin()[None, None, :, :]
123
+ else:
124
+ if t_val > self.max_t_cached:
125
+ time_grid = torch.arange(1.0, self.max_t + 1.0, dtype=torch.float32).to(device)
126
+ if self.freq_cached is None:
127
+ self.freq_cached = self.get_continuous_freq(time_grid, ex_positions, device)
128
+ embed = self.freq_cached[int(t_val)-1.0]
129
+ self.rope_cached = torch.cat((embed.cos()[None, None, None, :, :], embed.sin()[None, None, None, :, :]), dim=0)
130
+ self.max_t_cached = t_val
131
+ cos, sin = self.rope_cached
132
+
133
+ return torch.cat(
134
+ (cos[None, :, :, :seq_len, ...].to(dtype=dtype),
135
+ sin[None, :, :, :seq_len, ...].to(dtype=dtype)),
136
+ dim=0
137
+ )