MCPcopy Create free account
hub / github.com/Tele-AI/Telechat / RotaryEmbedding

Class RotaryEmbedding

models/7B/modeling_telechat.py:82–127  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

80
81
82class RotaryEmbedding(torch.nn.Module):
83 # Extracted from: https://github.com/EleutherAI/gpt-neox
84 def __init__(self, dim, config, base=10000,precision=torch.half):
85 super().__init__()
86 self.config = config
87 self.dim = dim
88 self.base = base
89 self.max_seq_len_cached = None
90 self.cos_cached = None
91 self.sin_cached = None
92 self.precision = precision
93
94 def get_mscale(self, scale=1):
95 if scale <= 1:
96 return 1.0
97 return 0.1 * math.log(scale) + 1.0
98
99 def get_ntk_alpha(self, true_seq_len):
100 context_value = math.log(true_seq_len / 4096, 2) + 1
101 # ntk_alpha = 2 ** context_value - 1
102 ntk_alpha = 2 ** math.ceil(context_value) - 1
103 ntk_alpha = max(ntk_alpha, 1)
104 return ntk_alpha
105
106 def forward(self, x, seq_dim=0, seq_len=None):
107 if seq_len is None:
108 seq_len = x.shape[seq_dim]
109 seq_len = max(seq_len, self.config.training_seqlen)
110 ntk_alpha = self.get_ntk_alpha(seq_len)
111 mscale = float(self.get_mscale(seq_len / self.config.training_seqlen))
112 base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
113 inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, device=x.device).float( )/ self.dim ))
114 max_seq_len_cached = seq_len
115 t = torch.arange(max_seq_len_cached, device=x.device, dtype=inv_freq.dtype)
116 freqs = torch.einsum('i,j->ij', t, inv_freq)
117 # Different from paper, but it uses a different permutation in order to obtain the same calculation
118 emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
119 if self.precision == torch.bfloat16:
120 emb = emb.float()
121 # [sx, 1 (b * np), hn]
122 cos_cached = mscale *emb.cos()[:, None, :].half()
123 sin_cached = mscale *emb.sin()[:, None, :].half()
124 if self.precision == torch.bfloat16:
125 cos_cached = cos_cached.bfloat16()
126 sin_cached = sin_cached.bfloat16()
127 return cos_cached[:seq_len, ...], sin_cached[:seq_len, ...]
128
129
130# rotary pos emb helpers:

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected