MCPcopy Create free account
hub / github.com/OpenBMB/ToolBench / CondenseRotaryEmbedding

Class CondenseRotaryEmbedding

toolbench/train/llama_condense_monkey_patch.py:8–41  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6from functools import partial
7
8class CondenseRotaryEmbedding(torch.nn.Module):
9 def __init__(self, dim, ratio, max_position_embeddings=2048, base=10000, device=None):
10 super().__init__()
11 inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
12 self.register_buffer("inv_freq", inv_freq)
13
14 # Build here to make `torch.jit.trace` work.
15 self.ratio = ratio
16 max_position_embeddings *= ratio
17 print(f"Condensing Positional embeddings from {max_position_embeddings} to {max_position_embeddings // ratio}")
18 self.max_seq_len_cached = max_position_embeddings
19 t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype) / ratio
20 freqs = torch.einsum("i,j->ij", t, self.inv_freq)
21 # Different from paper, but it uses a different permutation in order to obtain the same calculation
22 emb = torch.cat((freqs, freqs), dim=-1)
23 dtype = torch.get_default_dtype()
24 self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
25 self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
26
27 def forward(self, x, seq_len=None):
28 # x: [bs, num_attention_heads, seq_len, head_size]
29 # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
30 if seq_len > self.max_seq_len_cached:
31 self.max_seq_len_cached = seq_len
32 t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype) / self.ratio
33 freqs = torch.einsum("i,j->ij", t, self.inv_freq)
34 # Different from paper, but it uses a different permutation in order to obtain the same calculation
35 emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
36 self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(x.dtype), persistent=False)
37 self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(x.dtype), persistent=False)
38 return (
39 self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
40 self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
41 )
42
43def replace_llama_with_condense(ratio):
44 transformers.models.llama.modeling_llama.LlamaRotaryEmbedding = partial(CondenseRotaryEmbedding, ratio=ratio)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected