Skip to content

Commit 07e474e

Browse files
committed
[gpt_oss] Move YaRN attention mscale from rope cos/sin to softmax scale
CosSinRoPE is now a pure rotation (no mscale baked into cos/sin). gpt-oss, which was the only CosSinRoPE+YaRN user, instead folds mscale^2 into its softmax_scale. Mathematically equivalent: applying mscale to cos/sin scaled q and k each by m, so the attention logit was scaled by m^2. Applying m^2 to the softmax scale produces the same logit. Verified logit-neutral to ~1e-6 on gpt-oss params.
1 parent f67ed61 commit 07e474e

2 files changed

Lines changed: 7 additions & 6 deletions

File tree

torchtitan/models/common/rope.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ class Config(Module.Config):
106106
beta_fast: float = 32.0
107107
beta_slow: float = 1.0
108108
original_seq_len: int = 4096
109-
mscale: float = 0.0
110109
truncate: bool = True
111110

112111
def __init__(self, config: Config):
@@ -282,13 +281,10 @@ def _precompute_cache(self) -> torch.Tensor:
282281
max_seq_len = cfg.max_seq_len
283282
base = cfg.theta
284283

285-
mscale = 1.0
286-
287284
if cfg.scaling == "llama":
288285
raise NotImplementedError("Cos/sin RoPE does not support Llama scaling.")
289286

290287
if cfg.scaling == "yarn" and cfg.rope_factor > 1.0:
291-
mscale = 0.1 * math.log(cfg.rope_factor) + 1.0
292288
inv_freq = _yarn_inv_freq(
293289
dim,
294290
base,
@@ -307,8 +303,8 @@ def _precompute_cache(self) -> torch.Tensor:
307303
freqs = torch.outer(t, inv_freq).float()
308304
theta = torch.cat([freqs, freqs], dim=-1)
309305

310-
cos = theta.cos() * mscale
311-
sin = theta.sin() * mscale
306+
cos = theta.cos()
307+
sin = theta.sin()
312308
return torch.cat([cos, sin], dim=-1)
313309

314310
def _reshape_cache(

torchtitan/models/gpt_oss/model.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,11 @@ def __init__(self, config: Config):
104104

105105
# Standard attention softmax scale (1/sqrt(head_dim))
106106
self.softmax_scale = 1.0 / math.sqrt(self.head_dim)
107+
if config.rope.scaling == "yarn" and config.rope.rope_factor > 1.0:
108+
mscale = 0.1 * math.log(config.rope.rope_factor) + 1.0
109+
# Merge YaRN attention mscale into softmax_scale, with
110+
# m**2 being equivalent to scaling q / k each by mscale.
111+
self.softmax_scale *= mscale * mscale
107112

108113
self.qkv_linear = config.qkv_linear.build()
109114
self.wo = config.wo.build()

0 commit comments

Comments
 (0)