okami.mom/strata

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

Niko1221Merge f-own-5b adfcf9028 into f-own-int (round 16: the strata-image test program and its parts, DiT runner, sampler, noise, PNG writer; hooked into no build)e4309aaf3

main
2.5 KiB61 linesraw
1// src/image/sample/qi21_sampler.cpp - see include/strata/image/qi21_sampler.hpp.
2//
3// No contraction into fused multiply-adds: sd.cpp computes every line as its own pass over a tensor, so each operation
4// rounds on its own.  The passes are kept separate here too (a temporary per line), and contraction is switched off
5// for this file for every compiler that would otherwise fuse (GCC defaults to -ffp-contract=fast; on aarch64 an FMA
6// is always there).
7#if defined(__clang__)
8#pragma clang fp contract(off)
9#elif defined(__GNUC__)
10#pragma GCC optimize("fp-contract=off")
11#endif
12
13#include "strata/image/qi21_sampler.hpp"
14
15#include <cerrno>
16#include <cstdlib>
17#include <sstream>
18
19namespace strata::image {
20
21const char* const QI21_TURBO_SIGMAS = "1.0,0.978453,0.95418,0.926626,0.89508,0.845148,0.704534,0.414568,0.0";
22
23std::vector<float> qi21_parse_sigmas(const std::string& text) {
24    std::string s = text;
25    if (!s.empty() && s.front() == '[') s.erase(0, 1);
26    if (!s.empty() && s.back() == ']') s.pop_back();
27    std::vector<float> out;
28    std::stringstream ss(s);
29    std::string item;
30    const char* ws = " \t\n\r\f\v";
31    while (std::getline(ss, item, ',')) {
32        item.erase(0, item.find_first_not_of(ws));
33        const size_t last = item.find_last_not_of(ws);
34        item.erase(last == std::string::npos ? 0 : last + 1);
35        if (item.empty()) continue;
36        errno = 0;
37        char* end = nullptr;
38        const float f = std::strtof(item.c_str(), &end);   // what std::stof calls
39        if (end == item.c_str() || errno == ERANGE) return {};
40        out.push_back(f);
41    }
42    return out;
43}
44
45float qi21_timestep(float sigma) { return sigma * 1000.f; }
46
47void qi21_euler_step(float* x, const float* v, size_t n, float sigma, float sigma_next) {
48    if (sigma == sigma_next) return;
49    const float c_skip = 1.0f, c_out = -sigma;
50    const float dt = sigma_next - sigma;
51    std::vector<float> den(n), d(n);
52    for (size_t i = 0; i < n; ++i) den[i] = v[i] * c_out;           // guided.pred * c_out
53    for (size_t i = 0; i < n; ++i) d[i] = x[i] * c_skip;             // x * c_skip
54    for (size_t i = 0; i < n; ++i) den[i] = den[i] + d[i];           // denoised
55    for (size_t i = 0; i < n; ++i) d[i] = x[i] - den[i];             // x - denoised
56    for (size_t i = 0; i < n; ++i) d[i] = d[i] / sigma;              // ... / sigma
57    for (size_t i = 0; i < n; ++i) d[i] = d[i] * dt;                 // d * (sigmas[i + 1] - sigma)
58    for (size_t i = 0; i < n; ++i) x[i] = x[i] + d[i];               // x += ...
59}
60
61}  // namespace strata::image