okami.mom/strata

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

Niko1221rc1 merge split (1ba231217)fe57a0cb5

main
2.2 KiB42 linesraw
1// A prompt file's token ids: ref/*.bin (fnx_ref's dump format, ref/refio.py), whose first record is one named
2// "tokens" holding the ids as float32 (later records, per-layer dumps, are not read). Every read is checked and the
3// ids must be whole numbers in [0, 2^24): a short or foreign file is an error here, never a run on a truncated or
4// zero-padded prompt. It throws rather than exits, so a lab worker (bin/fnx_lab) survives a wrong path.
5#pragma once
6#include <cstdint>
7#include <cstdio>
8#include <stdexcept>
9#include <string>
10#include <vector>
11
12inline std::vector<int> ref_tokens(const char* path) {
13    std::FILE* f = std::fopen(path, "rb");
14    if (!f) throw std::runtime_error(std::string(path) + ": cannot open");
15    auto bad = [&](const std::string& why) {
16        std::fclose(f);
17        return std::runtime_error(std::string(path) + ": " + why);
18    };
19    uint32_t nl = 0, nd = 0;
20    if (std::fread(&nl, 4, 1, f) != 1) throw bad("empty file");
21    if (nl == 0 || nl > 256) throw bad("not a prompt file (record name length " + std::to_string(nl) + ")");
22    std::string name(nl, '\0');
23    if (std::fread(name.data(), 1, nl, f) != nl) throw bad("short record name");
24    if (name != "tokens") throw bad("the first record is '" + name + "', not tokens");
25    if (std::fread(&nd, 4, 1, f) != 1 || nd != 1) throw bad("the tokens record is not one-dimensional");
26    int64_t ne = 0;
27    if (std::fread(&ne, 8, 1, f) != 1 || ne < 1 || ne > 0x7fffffffLL) throw bad("no valid token count");
28    std::vector<float> v((size_t) ne);
29    if (std::fread(v.data(), 4, v.size(), f) != v.size()) throw bad("short file: fewer tokens than its header says");
30    std::fclose(f);
31    std::vector<int> ids;
32    ids.reserve(v.size());
33    for (size_t i = 0; i < v.size(); ++i) {
34        const float x = v[i];
35        // float32 holds every integer below 2^24 exactly (the vocabulary is ~248k)
36        if (!(x >= 0.f && x < 16777216.f) || x != (float) (int) x)
37            throw std::runtime_error(std::string(path) + ": value " + std::to_string(x) + " at " + std::to_string(i) +
38                                     " is not a token id");
39        ids.push_back((int) x);
40    }
41    return ids;
42}