User01110 commited on
Commit
dbb89f9
·
verified ·
1 Parent(s): 9632173

Use explicit causal attention for stable remote inference

Browse files
Files changed (1) hide show
  1. modeling_tinyqwen3_novelty.py +14 -1
modeling_tinyqwen3_novelty.py CHANGED
@@ -89,6 +89,19 @@ def apply_rope(x, cos, sin):
89
  return (x * cos.to(dtype=x.dtype)) + (rotate_half(x) * sin.to(dtype=x.dtype))
90
 
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  class MathNoveltyGate(nn.Module):
93
  def __init__(self, head_dim, floor=0.05):
94
  super().__init__()
@@ -141,7 +154,7 @@ class NoveltyGQA(nn.Module):
141
  k = apply_rope(k, cos, sin)
142
  k = k.repeat_interleave(self.kv_repeat, dim=1)
143
  v = v.repeat_interleave(self.kv_repeat, dim=1)
144
- heads = F.scaled_dot_product_attention(q, k, v, is_causal=True)
145
  heads = self.novelty(heads)
146
  out = heads.transpose(1, 2).contiguous().view(bsz, seq_len, self.dim)
147
  return self.o_proj(out)
 
89
  return (x * cos.to(dtype=x.dtype)) + (rotate_half(x) * sin.to(dtype=x.dtype))
90
 
91
 
92
+ def causal_attention(q, k, v):
93
+ scores = (q.float() @ k.float().transpose(-2, -1)) / (q.size(-1) ** 0.5)
94
+ causal_mask = torch.ones(
95
+ scores.size(-2),
96
+ scores.size(-1),
97
+ dtype=torch.bool,
98
+ device=scores.device,
99
+ ).triu(1)
100
+ scores = scores.masked_fill(causal_mask, torch.finfo(scores.dtype).min)
101
+ probs = F.softmax(scores, dim=-1).to(dtype=v.dtype)
102
+ return probs @ v
103
+
104
+
105
  class MathNoveltyGate(nn.Module):
106
  def __init__(self, head_dim, floor=0.05):
107
  super().__init__()
 
154
  k = apply_rope(k, cos, sin)
155
  k = k.repeat_interleave(self.kv_repeat, dim=1)
156
  v = v.repeat_interleave(self.kv_repeat, dim=1)
157
+ heads = causal_attention(q, k, v)
158
  heads = self.novelty(heads)
159
  out = heads.transpose(1, 2).contiguous().view(bsz, seq_len, self.dim)
160
  return self.o_proj(out)