okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fe57a0cb5
main
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" ); 14if (!f )throw std::runtime_error (std::string (path )+ ": cannot open" ); 15auto bad = [& ](const std::string & why ) { 16 std::fclose (f ); 17return std::runtime_error (std::string (path )+ ": " + why ); 18 }; 19uint32_t nl = 0 ,nd = 0 ; 20if (std::fread (& nl ,4 ,1 ,f )!= 1 )throw bad ("empty file" ); 21if (nl == 0 || nl > 256 )throw bad ("not a prompt file (record name length " + std::to_string (nl )+ ")" ); 22 std::string name (nl ,'\0' ); 23if (std::fread (name .data (),1 ,nl ,f )!= nl )throw bad ("short record name" ); 24if (name != "tokens" )throw bad ("the first record is '" + name + "', not tokens" ); 25if (std::fread (& nd ,4 ,1 ,f )!= 1 || nd != 1 )throw bad ("the tokens record is not one-dimensional" ); 26int64_t ne = 0 ; 27if (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 ); 29if (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 ; 32ids .reserve (v .size ()); 33for (size_t i = 0 ;i < v .size ();++ i ) { 34const float x = v [i ]; 35// float32 holds every integer below 2^24 exactly (the vocabulary is ~248k) 36if (!(x >=0.f && x < 16777216.f )|| x != (float ) (int )x ) 37throw std::runtime_error (std::string (path )+ ": value " + std::to_string (x )+ " at " + std::to_string (i )+ 38" is not a token id" ); 39ids .push_back ((int )x ); 40 } 41return ids ; 42}