File size: 1,435 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# SPDX-License-Identifier: Apache-2.0
"""Host check (no device): GLM's interleaved M-RoPE == the half-split rope on q / k rows permuted per head (the
layout the ttnn decoder and the DEC megakernel use), for image (3D) and text positions."""

import numpy as np
import torch

from tt_glmocr.reference import model as R
from tt_glmocr.tt.mk_dec import weights as E


def _half_perm():
    return torch.cat([torch.arange(0, 128, 2), torch.arange(1, 128, 2)])


def test_mrope_half_split_equivalence():
    torch.manual_seed(0)
    L = 40
    pos = torch.stack([torch.full((L,), 5), 5 + torch.arange(L) % 4, 5 + torch.arange(L) // 4])
    q = torch.randn(L, 128, dtype=torch.float64)
    k = torch.randn(L, 128, dtype=torch.float64)
    c, s = R.mrope_cos_sin(pos)
    c, s = c.double(), s.double()
    qi = q * c + R.rotate_pairs(q) * s
    ki = k * c + R.rotate_pairs(k) * s
    p = _half_perm()
    qp, kp, ch, sh = q[:, p], k[:, p], c[:, p], s[:, p]
    qh = qp * ch + R.rotate_half(qp) * sh
    kh = kp * ch + R.rotate_half(kp) * sh
    assert torch.allclose(qh, qi[:, p]) and torch.allclose(kh, ki[:, p])
    assert torch.allclose(qh @ kh.T, qi @ ki.T)


def test_text_positions_match_mk_tables():
    pos = torch.arange(100)
    c, s = R.mrope_cos_sin(pos.reshape(1, -1).expand(3, -1))
    p = _half_perm()
    ch, sh = E.rope_tables(pos)
    assert torch.allclose(c[:, p], ch, atol=1e-5) and torch.allclose(s[:, p], sh, atol=1e-5)