| 71 | |
| 72 | # code adapted from https://huggingface.co/kaiokendev/superhot-13b-8k-no-rlhf-test/blob/main/llama_rope_scaled_monkey_patch.py |
| 73 | class CondenseRotaryEmbedding(torch.nn.Module): |
| 74 | def __init__(self, dim, ratio, max_position_embeddings=2048, base=10000, device=None): |
| 75 | super().__init__() |
| 76 | inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim)) |
| 77 | self.register_buffer("inv_freq", inv_freq) |
| 78 | |
| 79 | # Build here to make `torch.jit.trace` work. |
| 80 | self.ratio = ratio |
| 81 | max_position_embeddings *= ratio |
| 82 | print(f"Condensing Positional embeddings from {max_position_embeddings} to {max_position_embeddings // ratio}") |
| 83 | self.max_seq_len_cached = max_position_embeddings |
| 84 | t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype) / ratio |
| 85 | freqs = torch.einsum("i,j->ij", t, self.inv_freq) |
| 86 | # Different from paper, but it uses a different permutation in order to obtain the same calculation |
| 87 | emb = torch.cat((freqs, freqs), dim=-1) |
| 88 | dtype = torch.get_default_dtype() |
| 89 | self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False) |
| 90 | self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False) |
| 91 | |
| 92 | def forward(self, x, seq_len=None): |
| 93 | # x: [bs, num_attention_heads, seq_len, head_size] |
| 94 | # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case. |
| 95 | if seq_len > self.max_seq_len_cached: |
| 96 | self.max_seq_len_cached = seq_len |
| 97 | t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype) / self.ratio |
| 98 | freqs = torch.einsum("i,j->ij", t, self.inv_freq) |
| 99 | # Different from paper, but it uses a different permutation in order to obtain the same calculation |
| 100 | emb = torch.cat((freqs, freqs), dim=-1).to(x.device) |
| 101 | self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(x.dtype), persistent=False) |
| 102 | self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(x.dtype), persistent=False) |
| 103 | return ( |
| 104 | self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype), |
| 105 | self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype), |
| 106 | ) |
| 107 | |
| 108 | def replace_llama_with_condense(ratio): |
| 109 | transformers.models.llama.modeling_llama.LlamaRotaryEmbedding = partial(CondenseRotaryEmbedding, ratio=ratio) |
nothing calls this directly
no outgoing calls
no test coverage detected