okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-5b 9b242bb5b into f-own-int (round 15: the own text encoder and tokenizer as test programs, the DiT reference tool and position tables; committed work only)11c8c701a

main
2.3 KiB67 linesraw
1// src/image/dit/qi21_rope.cpp - see include/strata/image/qi21_rope.hpp.  Written as sd.cpp writes it, operation by
2// operation (float arithmetic, the float overloads of std::cos / std::sin, ::powf), so the bits are the same.
3#include "strata/image/qi21_rope.hpp"
4
5#include <cmath>
6
7namespace strata::image {
8
9namespace {
10const int kAxes[3] = {16, 56, 56};
11
12std::vector<float> rope_frequencies(int dim, float theta) {
13    const int half = dim / 2;
14    // linspace<float>(0.f, (dim * 1.f - 2) / dim, half)
15    const float start = 0.f, end = (dim * 1.f - 2) / dim;
16    std::vector<float> scale(half);
17    if (half == 1) {
18        scale[0] = start;
19    } else {
20        const float step = (end - start) / (half - 1);
21        for (int i = 0; i < half; ++i) scale[i] = start + i * step;
22    }
23    std::vector<float> omega(half);
24    for (int i = 0; i < half; ++i) omega[i] = 1.0f / ::powf(1.f * theta, scale[i]);
25    return omega;
26}
27}  // namespace
28
29std::vector<float> qi21_positions(int64_t text_len, int64_t H, int64_t W) {
30    std::vector<float> p;
31    p.reserve((size_t) (text_len + H * W) * 3);
32    int64_t position = 0;
33    for (int64_t j = 0; j < text_len; ++j, ++position) {
34        const float f = static_cast<float>(position);
35        p.push_back(f), p.push_back(f), p.push_back(f);
36    }
37    for (int64_t h = 0; h < H; ++h)
38        for (int64_t w = 0; w < W; ++w) {
39            p.push_back(static_cast<float>(position));
40            p.push_back(static_cast<float>(h - (H - H / 2)));
41            p.push_back(static_cast<float>(w - (W - W / 2)));
42        }
43    return p;
44}
45
46std::vector<float> qi21_rope_table(const std::vector<float>& positions) {
47    const size_t n = positions.size() / 3;
48    std::vector<float> out(n * 256);
49    size_t offset = 0;
50    for (int a = 0; a < 3; ++a) {
51        const std::vector<float> omega = rope_frequencies(kAxes[a], 10000.0f);
52        for (size_t i = 0; i < n; ++i) {
53            float* row = out.data() + i * 256 + offset;
54            for (size_t j = 0; j < omega.size(); ++j) {
55                const float angle = positions[3 * i + a] * omega[j];
56                row[4 * j] = std::cos(angle);
57                row[4 * j + 1] = -std::sin(angle);
58                row[4 * j + 2] = std::sin(angle);
59                row[4 * j + 3] = std::cos(angle);
60            }
61        }
62        offset += omega.size() * 4;
63    }
64    return out;
65}
66
67}  // namespace strata::image