Wolfvin commited on
Commit
1ce3289
·
verified ·
1 Parent(s): 087c85d

Upload diffusion_llm/model/rope.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. diffusion_llm/model/rope.py +141 -0
diffusion_llm/model/rope.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AAM Diffusion LLM — Rotary Position Encoding (RoPE)
2
+
3
+ Implements Rotary Position Encoding from Su et al. (2021).
4
+ Better length generalization than learned positional encodings.
5
+ Applied inside attention computation, not as a separate embedding.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from typing import Optional, Tuple
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+
16
+
17
+ class RotaryPositionEncoding(nn.Module):
18
+ """Rotary Position Encoding (RoPE).
19
+
20
+ Applies rotary embeddings to query and key tensors before
21
+ attention computation. This allows the model to naturally
22
+ encode relative positions through the rotation matrix.
23
+ """
24
+
25
+ def __init__(self, d_model: int, max_seq_len: int = 8192, base: float = 10000.0) -> None:
26
+ super().__init__()
27
+ self.d_model = d_model
28
+ self.max_seq_len = max_seq_len
29
+ self.base = base
30
+
31
+ # Precompute frequency bands
32
+ inv_freq = 1.0 / (base ** (torch.arange(0, d_model, 2, dtype=torch.float32) / d_model))
33
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
34
+
35
+ # Precompute cos/sin for max_seq_len
36
+ self._precompute_cache(max_seq_len)
37
+
38
+ def _precompute_cache(self, seq_len: int) -> None:
39
+ t = torch.arange(seq_len, dtype=torch.float32)
40
+ freqs = torch.outer(t, self.inv_freq)
41
+ emb = torch.cat([freqs, freqs], dim=-1)
42
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
43
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
44
+
45
+ def forward(
46
+ self,
47
+ q: torch.Tensor,
48
+ k: torch.Tensor,
49
+ seq_len: Optional[int] = None,
50
+ offset: int = 0,
51
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
52
+ """Apply rotary embeddings to query and key.
53
+
54
+ Args:
55
+ q: Query tensor (batch, n_heads, seq_len, d_head)
56
+ k: Key tensor (batch, n_heads, seq_len, d_head)
57
+ seq_len: Sequence length (inferred from q if None)
58
+ offset: Position offset (for KV cache)
59
+
60
+ Returns:
61
+ Tuple (rotated_q, rotated_k)
62
+ """
63
+ if seq_len is None:
64
+ seq_len = q.shape[2]
65
+
66
+ if offset + seq_len > self.max_seq_len:
67
+ self._precompute_cache(offset + seq_len)
68
+
69
+ cos = self.cos_cached[offset:offset + seq_len].unsqueeze(0).unsqueeze(0) # (1, 1, seq, d)
70
+ sin = self.sin_cached[offset:offset + seq_len].unsqueeze(0).unsqueeze(0)
71
+
72
+ q_rot = self._apply_rotation(q, cos, sin)
73
+ k_rot = self._apply_rotation(k, cos, sin)
74
+
75
+ return q_rot, k_rot
76
+
77
+ @staticmethod
78
+ def _apply_rotation(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
79
+ d = x.shape[-1]
80
+ x1 = x[..., :d // 2]
81
+ x2 = x[..., d // 2:]
82
+
83
+ # Handle dimension mismatch
84
+ if cos.shape[-1] != d:
85
+ cos = cos[..., :d]
86
+ sin = sin[..., :d]
87
+
88
+ cos1 = cos[..., :d // 2]
89
+ cos2 = cos[..., d // 2:]
90
+ sin1 = sin[..., :d // 2]
91
+ sin2 = sin[..., d // 2:]
92
+
93
+ rotated = torch.cat([
94
+ x1 * cos1 - x2 * sin1,
95
+ x1 * sin2 + x2 * cos2,
96
+ ], dim=-1)
97
+
98
+ return rotated
99
+
100
+
101
+ def apply_rope_to_attention(
102
+ q: torch.Tensor,
103
+ k: torch.Tensor,
104
+ d_model: int,
105
+ seq_len: int,
106
+ offset: int = 0,
107
+ device: torch.device = torch.device("cpu"),
108
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
109
+ """Functional RoPE application — use when you don't want a module.
110
+
111
+ Args:
112
+ q: Query tensor (batch, n_heads, seq_len, d_head)
113
+ k: Key tensor (batch, n_heads, seq_len, d_head)
114
+ d_model: Model dimension
115
+ seq_len: Sequence length
116
+ offset: Position offset
117
+ device: Device
118
+
119
+ Returns:
120
+ Tuple (rotated_q, rotated_k)
121
+ """
122
+ d_head = q.shape[-1]
123
+ inv_freq = 1.0 / (10000.0 ** (torch.arange(0, d_head, 2, dtype=torch.float32, device=device) / d_head))
124
+
125
+ positions = torch.arange(offset, offset + seq_len, dtype=torch.float32, device=device)
126
+ freqs = torch.outer(positions, inv_freq)
127
+ emb = torch.cat([freqs, freqs], dim=-1)
128
+ cos = emb.cos().unsqueeze(0).unsqueeze(0)
129
+ sin = emb.sin().unsqueeze(0).unsqueeze(0)
130
+
131
+ d = q.shape[-1]
132
+ x1_q, x2_q = q[..., :d // 2], q[..., d // 2:]
133
+ x1_k, x2_k = k[..., :d // 2], k[..., d // 2:]
134
+
135
+ cos1, cos2 = cos[..., :d // 2], cos[..., d // 2:]
136
+ sin1, sin2 = sin[..., :d // 2], sin[..., d // 2:]
137
+
138
+ q_rot = torch.cat([x1_q * cos1 - x2_q * sin1, x1_q * sin2 + x2_q * cos2], dim=-1)
139
+ k_rot = torch.cat([x1_k * cos1 - x2_k * sin1, x1_k * sin2 + x2_k * cos2], dim=-1)
140
+
141
+ return q_rot, k_rot