Skip to content

Commit 0dc48f1

Browse files
committed
support rope
1 parent 412e51b commit 0dc48f1

File tree

3 files changed

+164
-2
lines changed

3 files changed

+164
-2
lines changed

wenet/transformer/attention.py

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import torch
2222
from torch import nn
23+
from wenet.transformer.embedding import apply_rotary_emb
2324

2425
from wenet.utils.common import get_dtype_min
2526

@@ -424,3 +425,101 @@ def forward(
424425
query.size(0), -1,
425426
self.h * self.d_k)) # (batch, time1, d_model)
426427
return self.linear_out(output), new_cache
428+
429+
430+
class RopeMultiHeadedAttention(MultiHeadedAttention):
431+
432+
def __init__(self,
433+
n_head: int,
434+
n_feat: int,
435+
dropout_rate: float,
436+
key_bias: bool = True,
437+
use_sdpa: bool = False,
438+
bias: bool = True,
439+
n_kv_head: Optional[int] = None,
440+
head_dim: Optional[int] = None):
441+
super().__init__(n_head, n_feat, dropout_rate, key_bias, use_sdpa,
442+
bias, n_kv_head, head_dim)
443+
444+
def forward(
445+
self,
446+
query: torch.Tensor,
447+
key: torch.Tensor,
448+
value: torch.Tensor,
449+
mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
450+
pos_emb: torch.Tensor = torch.empty(0),
451+
cache: torch.Tensor = torch.zeros((0, 0, 0, 0))
452+
) -> Tuple[torch.Tensor, torch.Tensor]:
453+
"""Compute scaled dot product attention.
454+
455+
Args:
456+
query (torch.Tensor): Query tensor (#batch, time1, size).
457+
key (torch.Tensor): Key tensor (#batch, time2, size).
458+
value (torch.Tensor): Value tensor (#batch, time2, size).
459+
mask (torch.Tensor): Mask tensor (#batch, 1, time2) or
460+
(#batch, time1, time2).
461+
1.When applying cross attention between decoder and encoder,
462+
the batch padding mask for input is in (#batch, 1, T) shape.
463+
2.When applying self attention of encoder,
464+
the mask is in (#batch, T, T) shape.
465+
3.When applying self attention of decoder,
466+
the mask is in (#batch, L, L) shape.
467+
4.If the different position in decoder see different block
468+
of the encoder, such as Mocha, the passed in mask could be
469+
in (#batch, L, T) shape. But there is no such case in current
470+
Wenet.
471+
cache (torch.Tensor): Cache tensor (1, head, cache_t, d_k * 2),
472+
where `cache_t == chunk_size * num_decoding_left_chunks`
473+
and `head * d_k == size`
474+
475+
476+
Returns:
477+
torch.Tensor: Output tensor (#batch, time1, d_model).
478+
torch.Tensor: Cache tensor (1, head, cache_t + time1, d_k * 2)
479+
where `cache_t == chunk_size * num_decoding_left_chunks`
480+
and `head * d_k == size`
481+
482+
"""
483+
q, k, v = self.forward_qkv(query, key, value)
484+
# see above
485+
if cache.size(0) > 0:
486+
key_cache, value_cache = torch.split(cache,
487+
cache.size(-1) // 2,
488+
dim=-1)
489+
k = torch.cat([key_cache, k], dim=2)
490+
v = torch.cat([value_cache, v], dim=2)
491+
492+
# NOTE(Mddct): In order to make the code easier to read,
493+
# these two lines are not placed in MultiHeadedAttention.
494+
q = apply_rotary_emb(q, freqs_cis=pos_emb)
495+
k = apply_rotary_emb(k, freqs_cis=pos_emb)
496+
497+
new_cache = torch.cat((k, v), dim=-1)
498+
if self.h_kv != self.h:
499+
k = torch.repeat_interleave(
500+
k,
501+
self.h // self.h_kv,
502+
dim=1,
503+
)
504+
v = torch.repeat_interleave(
505+
v,
506+
self.h // self.h_kv,
507+
dim=1,
508+
)
509+
510+
if not self.use_sdpa:
511+
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
512+
return self.forward_attention(v, scores, mask), new_cache
513+
else:
514+
output = torch.nn.functional.scaled_dot_product_attention(
515+
q,
516+
k,
517+
v,
518+
attn_mask=mask.unsqueeze(1),
519+
dropout_p=self.dropout_rate,
520+
scale=1 / math.sqrt(self.d_k),
521+
)
522+
output = (output.transpose(1, 2).contiguous().view(
523+
query.size(0), -1,
524+
self.h * self.d_k)) # (batch, time1, d_model)
525+
return self.linear_out(output), new_cache

wenet/transformer/embedding.py

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ class NoPositionalEncoding(torch.nn.Module):
178178
""" No position encoding
179179
"""
180180

181-
def __init__(self, d_model: int, dropout_rate: float):
181+
def __init__(self, d_model: int, dropout_rate: float, *args):
182182
super().__init__()
183183
self.d_model = d_model
184184
self.dropout = torch.nn.Dropout(p=dropout_rate)
@@ -195,3 +195,62 @@ def forward(self,
195195
def position_encoding(self, offset: Union[int, torch.Tensor],
196196
size: int) -> torch.Tensor:
197197
return torch.zeros(1, size, self.d_model)
198+
199+
200+
# copy from:https://github.com/google/gemma_pytorch/blob/main/gemma/model.py#L84
201+
def precompute_freqs_cis(dim: int,
202+
end: int,
203+
theta: float = 10000.0) -> torch.Tensor:
204+
"""Precomputes the frequency cis."""
205+
freqs = 1.0 / (theta**(torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
206+
t = torch.arange(end, device=freqs.device)
207+
freqs = torch.outer(t, freqs).float()
208+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
209+
return freqs_cis
210+
211+
212+
# copy from:https://github.com/google/gemma_pytorch/blob/main/gemma/model.py#L95
213+
def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
214+
"""Applies the rotary embedding to the query and key tensors."""
215+
x_ = torch.view_as_complex(
216+
torch.stack(torch.chunk(x.transpose(1, 2).float(), 2, dim=-1), dim=-1))
217+
x_out = torch.view_as_real(x_ * freqs_cis).type_as(x)
218+
x_out = torch.cat(torch.chunk(x_out, 2, dim=-1), dim=-2)
219+
x_out = x_out.reshape(x_out.shape[0], x_out.shape[1], x_out.shape[2],
220+
-1).transpose(1, 2)
221+
return x_out
222+
223+
224+
class RopePositionalEncoding(PositionalEncoding):
225+
226+
def __init__(self,
227+
d_model: int,
228+
dropout_rate: float,
229+
max_len: int = 1500,
230+
rope_theta=10000.0):
231+
super().__init__(d_model, dropout_rate=dropout_rate, max_len=max_len)
232+
delattr(self, 'pe')
233+
self.pe = precompute_freqs_cis(d_model, max_len * 2, rope_theta)
234+
self.dropout_rate = dropout_rate
235+
236+
def forward(
237+
self,
238+
x: torch.Tensor,
239+
offset: Union[int,
240+
torch.Tensor] = 0) -> Tuple[torch.Tensor, torch.Tensor]:
241+
242+
self.pe = self.pe.to(x.device)
243+
pos_emb = self.position_encoding(offset, x.size(1), False)
244+
# NOTE(Mddct): some model don't scale
245+
# TODO(Mddct): fix
246+
x = x * self.xscale
247+
# NOTE(Mddct) dropout don't suuport complex float for pos_emb
248+
return self.dropout(x), self.dropout_complex(pos_emb)
249+
250+
def dropout_complex(self, x):
251+
mask = torch.nn.functional.dropout(
252+
torch.ones_like(x.real),
253+
training=self.training,
254+
p=self.dropout_rate,
255+
)
256+
return x * mask

wenet/utils/class_utils.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,13 @@
2121
from wenet.squeezeformer.subsampling import DepthwiseConv2dSubsampling4
2222
from wenet.transformer.embedding import (PositionalEncoding,
2323
RelPositionalEncoding,
24+
RopePositionalEncoding,
2425
WhisperPositionalEncoding,
2526
LearnablePositionalEncoding,
2627
NoPositionalEncoding)
2728
from wenet.transformer.attention import (MultiHeadedAttention,
28-
RelPositionMultiHeadedAttention)
29+
RelPositionMultiHeadedAttention,
30+
RopeMultiHeadedAttention)
2931
from wenet.efficient_conformer.attention import GroupedRelPositionMultiHeadedAttention
3032

3133
WENET_ACTIVATION_CLASSES = {
@@ -63,12 +65,14 @@
6365
"abs_pos_whisper": WhisperPositionalEncoding,
6466
"embed_learnable_pe": LearnablePositionalEncoding,
6567
"abs_pos_paraformer": ParaformerPositinoalEncoding,
68+
"rope": RopePositionalEncoding,
6669
}
6770

6871
WENET_ATTENTION_CLASSES = {
6972
"selfattn": MultiHeadedAttention,
7073
"rel_selfattn": RelPositionMultiHeadedAttention,
7174
"grouped_rel_selfattn": GroupedRelPositionMultiHeadedAttention,
75+
"rope_selfattn": RopeMultiHeadedAttention,
7276
}
7377

7478
WENET_MLP_CLASSES = {

0 commit comments

Comments
 (0)