okami.mom/strata

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

Niko1221Merge f-own-5 56630caca into f-own-int (round 14: Strata's own VAE decoder for sd-cli and the images "vae_decoder" switch)736266e87

main
2.6 KiB58 linesraw
1// src/image/vae/convert.hpp - host-side weight conversion of Strata's VAE decoder, split over threads.
2// Every value is converted on its own (bf16 -> f32 exact, f32 -> f16 round to nearest even with
3// strata::kernels::f16_from_f32), so the result is the same bytes for any thread count
4// (tools/image/gate/test_vae_convert.py checks it on every bf16 bit pattern).  Host only.
5#pragma once
6
7#include "strata/kernels/bf16_bits.hpp"
8#include "strata/kernels/f16_bits.hpp"
9
10#include <algorithm>
11#include <cstddef>
12#include <cstdint>
13#include <cstring>
14#include <thread>
15#include <vector>
16
17namespace strata::image {
18
19// fn(begin, end) over [0, n) in `threads` contiguous parts (threads <= 1: on the calling thread).
20template <class F>
21void parallel_ranges(size_t n, int threads, F fn) {
22    const size_t t = (size_t) std::max(1, std::min<int>(threads, (int) std::max<size_t>(1, n)));
23    if (t <= 1) {
24        fn((size_t) 0, n);
25        return;
26    }
27    std::vector<std::thread> pool;
28    const size_t step = (n + t - 1) / t;
29    for (size_t b = 0; b < n; b += step) pool.emplace_back(fn, b, std::min(n, b + step));
30    for (auto& th : pool) th.join();
31}
32
33inline uint16_t bf16_at(const unsigned char* raw, size_t i) { return (uint16_t) (raw[2 * i] | (raw[2 * i + 1] << 8)); }
34
35// bf16 bits (little-endian bytes) -> float, values [b, e).
36inline void bf16_to_f32_range(const unsigned char* raw, size_t b, size_t e, float* out) {
37    for (size_t i = b; i < e; ++i) out[i] = strata::kernels::f32_from_bf16(bf16_at(raw, i));
38}
39
40// A convolution's bf16 weights [oc][ic][taps] -> f16 bits [oc][taps * ic] (row index tap * ic + i), rows [ob, oe).
41inline void bf16_conv_to_f16_rows(const unsigned char* raw, int ic, int taps, size_t ob, size_t oe, uint16_t* out) {
42    const size_t K = (size_t) taps * ic;
43    for (size_t o = ob; o < oe; ++o)
44        for (int i = 0; i < ic; ++i)
45            for (int t = 0; t < taps; ++t)
46                out[o * K + (size_t) t * ic + i] =
47                    strata::kernels::f16_from_f32(strata::kernels::f32_from_bf16(bf16_at(raw, (o * ic + i) * taps + t)));
48}
49
50// The same two over threads (the test's entry points; the decoder splits a list of jobs instead).
51inline void bf16_to_f32(const unsigned char* raw, size_t n, float* out, int threads) {
52    parallel_ranges(n, threads, [&](size_t b, size_t e) { bf16_to_f32_range(raw, b, e, out); });
53}
54inline void bf16_conv_to_f16(const unsigned char* raw, int oc, int ic, int taps, uint16_t* out, int threads) {
55    parallel_ranges((size_t) oc, threads, [&](size_t b, size_t e) { bf16_conv_to_f16_rows(raw, ic, taps, b, e, out); });
56}
57
58}  // namespace strata::image