Files
cenet/example/tokenizer.hpp

352 lines
11 KiB
C++

#ifndef TOKENIZER_HPP
#define TOKENIZER_HPP
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
class string_storage {
private:
static constexpr std::size_t MIN_CHUNK_CAP = 8ULL * 1024;
public:
string_storage() = default;
~string_storage() { free(); }
string_storage(string_storage&& other) noexcept { *this = std::move(other); }
string_storage& operator=(string_storage&& other) noexcept {
if (this == &other) return *this;
free();
m_head = other.m_head;
m_tail = other.m_tail;
other.m_head = nullptr;
other.m_tail = nullptr;
return *this;
}
string_storage(const string_storage&) = delete;
string_storage& operator=(const string_storage&) = delete;
public:
std::string_view allocate(const char* begin, std::size_t length) {
region* reg = m_head;
while (reg != nullptr && reg->size > reg->used + length)
reg = reg->next;
if (reg == nullptr) {
const std::size_t size = (std::max(MIN_CHUNK_CAP, length) + 3) & ~0x4ULL;
reg = reinterpret_cast<region*>(std::malloc(sizeof(region) + size)); // NOLINT
new (reg) region(size);
if (m_head == nullptr) {
m_head = m_tail = reg;
} else {
m_tail = m_tail->next = reg;
}
}
char* string = reg->data() + reg->used;
std::memcpy(string, begin, length);
reg->used += length;
return { string, length };
}
std::string_view allocate(std::string_view lhs, std::string_view rhs) {
std::size_t length = lhs.size() + rhs.size();
region* reg = m_head;
while (reg != nullptr && reg->size > reg->used + length)
reg = reg->next;
if (reg == nullptr) {
const std::size_t size = (std::max(MIN_CHUNK_CAP, length) + 3) & ~0x4ULL;
reg = reinterpret_cast<region*>(std::malloc(sizeof(region) + size)); // NOLINT
new (reg) region(size);
if (m_head == nullptr) {
m_head = m_tail = reg;
} else {
m_tail = m_tail->next = reg;
}
}
char* string = reg->data() + reg->used;
std::memcpy(string, lhs.data(), lhs.size());
std::memcpy(string + lhs.size(), rhs.data(), rhs.size());
reg->used += length;
return { string, length };
}
private:
void free() {
while (m_head != nullptr) {
region* next = m_head->next;
std::free(m_head); // NOLINT
m_head = next;
}
m_tail = m_head = nullptr;
}
private:
struct region {
region* next = nullptr;
std::size_t size;
std::size_t used = 0;
explicit region(std::size_t size)
: size(size) {}
char* data() { return reinterpret_cast<char*>(this + 1); }
};
private:
region* m_head = nullptr;
region* m_tail = nullptr;
};
template <std::uint32_t DictionarySize>
class tokenizer {
static_assert(DictionarySize >= 256);
public:
tokenizer() {
m_dict.reserve(DictionarySize);
for (int i = 0; i < 256; ++i) {
char ch = static_cast<char>(i);
m_dict.push_back(m_strings.allocate(&ch, 1));
}
}
public:
void train(std::string_view text, std::size_t minFreq = 2) {
// TODO: split the tokens into groupings so that "abc123" is treated as "abc" and "123"
std::vector<std::uint32_t> tokens;
std::unordered_map<std::uint64_t, std::size_t> freaks{};
const auto* it = text.begin();
for (; it + 1 < text.end(); ++it) {
tokens.push_back(static_cast<std::uint8_t>(*it) & 0xFFULL);
++freaks[(static_cast<std::uint8_t>(*it) & 0xFFULL) |
(((static_cast<std::uint8_t>(*(it + 1))) & 0xFFULL) << 32ULL)];
}
if (it < text.end()) tokens.push_back(static_cast<std::uint8_t>(*it) & 0xFFULL);
if (tokens.empty()) return;
while (tokens.size() > 1 && m_dict.size() < DictionarySize) {
auto best = freaks.begin();
auto it = freaks.begin();
++it;
while (it != freaks.end()) {
if (it->second == 0) {
it = freaks.erase(it);
continue;
}
if (it->second > best->second || (it->second == best->second && it->first > best->first)) best = it;
++it;
}
if (best->second < minFreq) break;
std::uint32_t newToken = m_dict.size();
m_merges.emplace(best->first, newToken);
m_dict.push_back(
m_strings.allocate(m_dict[best->first & 0xFFFFFFFF], m_dict[(best->first >> 32ULL) & 0xFFFFFFFF]));
std::size_t newIdx = 0; // Index pointing to the current element in the "new version" of tokens vector.
// Essentially, we just override tokens instead of back buffering or whatever.
for (std::size_t i = 0; i < tokens.size();) {
if (i + 1 >= tokens.size()) {
tokens[newIdx++] = tokens[i++];
continue;
}
std::uint64_t pair = (tokens[i] & 0xFFFFFFFF) | ((tokens[i + 1] & 0xFFFFFFFFULL) << 32ULL);
if (pair == best->first) {
if (i > 0) {
pair <<= 32ULL;
pair |= (tokens[newIdx - 1] & 0xFFFFFFFF);
auto it = freaks.find(pair);
assert(it != freaks.end());
assert(it != freaks.end() && it->second > 0);
--it->second;
pair &= 0xFFFFFFFF;
pair |= (newToken & 0xFFFFFFFFULL) << 32ULL;
++freaks[pair];
}
pair = best->first;
auto it = freaks.find(pair);
assert(it != freaks.end());
assert(it->second > 0);
--it->second;
tokens[(++i, newIdx++)] = newToken;
if (i + 1 < tokens.size()) {
pair = tokens[i] | (tokens[i + 1] & 0xFFFFFFFFULL) << 32ULL;
auto it = freaks.find(pair);
assert(it != freaks.end() && it->second > 0);
--it->second;
pair &= ~0xFFFFFFFFULL;
pair |= newToken & 0xFFFFFFFFULL;
++freaks[pair];
}
++i;
continue;
}
tokens[newIdx++] = tokens[i++];
}
tokens.resize(newIdx);
}
}
std::vector<std::uint32_t> encode(std::string_view source) const {
if (source.empty()) return {};
std::vector<std::uint32_t> tokens;
const auto* it = source.begin();
std::uint64_t pair = (extend_char(*it++) << 32);
while ((pair & 0xFFFFFFFF00000000) != 0) {
pair >>= 32ULL;
if (it != source.end()) pair |= (extend_char(*it++) << 32);
auto jt = m_merges.find(pair);
if (jt == m_merges.end()) {
tokens.push_back(pair & 0xFFFFFFFF);
continue;
}
pair = (jt->second & 0xFFFFFFFFULL) << 32ULL;
if (!tokens.empty()) {
while (!tokens.empty()) {
jt = m_merges.find(tokens.back() | pair);
if (jt == m_merges.end()) break;
pair = (jt->second & 0xFFFFFFFFULL) << 32ULL;
tokens.pop_back();
}
}
}
return tokens;
}
std::string decode(const std::vector<std::uint32_t>& tokens) const {
if (tokens.empty()) return {};
std::string string;
for (auto tok : tokens) {
string.append(m_dict.at(tok));
}
return string;
}
public:
bool dump(const char* filepath) const {
std::ofstream file(filepath, std::ios::binary | std::ios::out | std::ios::trunc);
if (!file.is_open()) return false;
dump_u64(file, m_dict.size());
for (auto sv : m_dict) {
dump_sv(file, sv);
}
dump_u64(file, m_merges.size());
for (const auto& [pair, merge] : m_merges) {
dump_u32(file, (pair >> 0ULL) & 0xFFFFFFFF);
dump_u32(file, (pair >> 32ULL) & 0xFFFFFFFF);
dump_u32(file, merge);
}
return true;
}
private:
void dump_u64(std::ofstream& file, std::uint64_t value) const {
dump(file, value, std::make_index_sequence<sizeof(value)>{});
}
void dump_u32(std::ofstream& file, std::uint32_t value) const {
dump(file, value, std::make_index_sequence<sizeof(value)>{});
}
void dump_sv(std::ofstream& file, std::string_view value) const {
dump_u32(file, value.size());
file.write(value.data(), static_cast<std::streamsize>(value.size()));
}
template <typename T, std::size_t... Is>
void dump(std::ofstream& file, T value, std::index_sequence<Is...>) const {
char buf[] = { static_cast<char>((value >> (Is << 3ULL)) & 0xFF)... };
file.write(buf, sizeof(buf));
}
public:
bool load(const char* filepath) {
std::ifstream file(filepath, std::ios::binary | std::ios::in);
if (!file.is_open()) return false;
m_dict.clear();
auto dictSize = load_u64(file);
assert(dictSize <= DictionarySize);
m_dict.resize(dictSize);
for (std::uint64_t i = 0; i < dictSize; ++i) {
m_dict[i] = load_sv(file);
}
m_merges.clear();
auto mergesSize = load_u64(file);
m_merges.reserve(mergesSize);
for (std::uint64_t i = 0; i < mergesSize; ++i) {
auto lhs = load_u32(file);
auto rhs = load_u32(file);
auto merge = load_u32(file);
m_merges.emplace(lhs | (static_cast<std::uint64_t>(rhs) << 32ULL), merge);
}
return true;
}
private:
auto load_u64(std::ifstream& file) const { return load<std::uint64_t>(file); }
auto load_u32(std::ifstream& file) const { return load<std::uint32_t>(file); }
auto load_sv(std::ifstream& file) {
auto length = load_u32(file);
char buf[length];
file.read(buf, length);
return m_strings.allocate(buf, length);
}
template <typename T>
T load(std::ifstream& file) const {
return load<T>(file, std::make_index_sequence<sizeof(T)>{});
}
template <typename T, std::size_t... Is>
T load(std::ifstream& file, std::index_sequence<Is...>) const {
char buf[sizeof(T)];
file.read(buf, sizeof(buf));
return (((buf[Is] & 0xFFULL) << Is) | ...);
}
public:
std::string_view token_text(std::uint32_t token) const { return m_dict.at(token); }
private:
constexpr std::uint64_t extend_char(char ch) const {
return static_cast<std::uint64_t>(static_cast<std::uint8_t>(ch));
}
private:
string_storage m_strings;
std::vector<std::string_view> m_dict;
std::unordered_map<std::uint64_t, std::uint32_t> m_merges;
};
#endif // TOKENIZER_HPP