Spaces:
Sleeping
Sleeping
Download bpe_fast.cpp from chocoetom/Morpheus-mini-1.0: direct link, hf CLI and curl.
- Browser
- Download file 5.88 kB
-
https://huggingface.co/spaces/chocoetom/Morpheus-mini-1.0/resolve/main/bpe_fast.cpp
- Command line
-
hf download hf://spaces/chocoetom/Morpheus-mini-1.0/bpe_fast.cpp
-
curl -L -o bpe_fast.cpp https://huggingface.co/spaces/chocoetom/Morpheus-mini-1.0/resolve/main/bpe_fast.cpp
5.88 kB
| // bpe_fast.cpp — acelerador do tokenizador BPE byte-level do TinyAI. | |
| // | |
| // Este módulo é uma porta EXATA do _bpe_encode() em Python usado por | |
| // ia_server.py e chat.py: mesma lista encadeada (prev/next), mesmo heap de | |
| // prioridade ordenado por (rank, posição) e as mesmas verificações de | |
| // validação em cada pop (posição morta / par desatualizado). A sequência de | |
| // operações é idêntica à do heapq de Python, então o resultado é | |
| // byte a byte igual — dá pra usar sem mudar tokenização, cache ou checkpoint. | |
| // | |
| // API: | |
| // encode(text, merges, specials) -> list[int] | |
| // text : str (entra como UTF-8, igual a text.encode('utf-8') do Python) | |
| // merges : dict[(a, b) -> rank] (BPE_MERGES) | |
| // specials : dict[str -> id] (_SPECIAL_IDS / Tokenizer.special) | |
| // | |
| // Compilar (ver build_bpe.py): python build_bpe.py | |
| namespace py = pybind11; | |
| namespace { | |
| using MergeMap = std::unordered_map<uint64_t, uint32_t>; | |
| using HeapItem = std::pair<uint32_t, uint32_t>; // (rank, posição) — mesma ordem das tuplas do heapq | |
| inline uint64_t chave(uint32_t a, uint32_t b) { | |
| return (static_cast<uint64_t>(a) << 32) | b; | |
| } | |
| // Um trecho de texto (bytes) -> ids BPE. Algoritmo 1:1 com o _bpe_encode() do Python. | |
| void bpe_bytes(const uint8_t* data, size_t n, const MergeMap& merges, | |
| std::vector<uint32_t>& out) { | |
| if (n < 2 || merges.empty()) { | |
| for (size_t k = 0; k < n; ++k) out.push_back(data[k]); | |
| return; | |
| } | |
| std::vector<uint32_t> ids(n); | |
| std::vector<int64_t> nxt(n), prv(n); | |
| std::vector<char> alive(n, 1); | |
| for (size_t k = 0; k < n; ++k) { | |
| ids[k] = data[k]; | |
| nxt[k] = (k + 1 < n) ? static_cast<int64_t>(k + 1) : -1; | |
| prv[k] = (k == 0) ? -1 : static_cast<int64_t>(k - 1); | |
| } | |
| std::priority_queue<HeapItem, std::vector<HeapItem>, std::greater<HeapItem>> heap; | |
| for (size_t i = 0; i + 1 < n; ++i) { | |
| auto it = merges.find(chave(ids[i], ids[i + 1])); | |
| if (it != merges.end()) heap.emplace(it->second, static_cast<uint32_t>(i)); | |
| } | |
| while (!heap.empty()) { | |
| const uint32_t rank = heap.top().first; | |
| const uint32_t i = heap.top().second; | |
| heap.pop(); | |
| if (!alive[i]) continue; // posição morta (stale) | |
| const int64_t j = nxt[i]; | |
| if (j == -1) continue; // fim da cadeia | |
| auto it = merges.find(chave(ids[i], ids[static_cast<size_t>(j)])); | |
| if (it == merges.end() || it->second != rank) continue; // par mudou (stale) | |
| const int64_t p_ = prv[i], n_ = nxt[j]; | |
| ids[i] = rank; // funde: vira o novo token | |
| alive[static_cast<size_t>(j)] = 0; | |
| nxt[i] = n_; | |
| if (n_ != -1) prv[static_cast<size_t>(n_)] = i; | |
| if (p_ != -1) { // novo par à esquerda | |
| auto it2 = merges.find(chave(ids[static_cast<size_t>(p_)], ids[i])); | |
| if (it2 != merges.end()) heap.emplace(it2->second, static_cast<uint32_t>(p_)); | |
| } | |
| if (n_ != -1) { // novo par à direita | |
| auto it2 = merges.find(chave(ids[i], ids[static_cast<size_t>(n_)])); | |
| if (it2 != merges.end()) heap.emplace(it2->second, static_cast<uint32_t>(i)); | |
| } | |
| } | |
| size_t i = 0; | |
| while (i != static_cast<size_t>(-1)) { | |
| if (alive[i]) out.push_back(ids[i]); | |
| i = static_cast<size_t>(nxt[i]); | |
| } | |
| } | |
| struct Especial { | |
| std::string tok; | |
| uint32_t id; | |
| }; | |
| py::list encode(const py::str& text, const py::dict& merges, const py::dict& specials) { | |
| MergeMap M; | |
| M.reserve(static_cast<size_t>(py::len(merges))); | |
| for (auto item : merges) { | |
| py::tuple par = py::reinterpret_borrow<py::tuple>(item.first); | |
| M[chave(static_cast<uint32_t>(par[0].cast<int64_t>()), | |
| static_cast<uint32_t>(par[1].cast<int64_t>()))] = | |
| item.second.cast<uint32_t>(); | |
| } | |
| std::vector<Especial> S; | |
| S.reserve(static_cast<size_t>(py::len(specials))); | |
| for (auto item : specials) // ordem do dict = ordem das alternativas do regex | |
| S.push_back({item.first.cast<std::string>(), item.second.cast<uint32_t>()}); | |
| const std::string s = py::cast<std::string>(text); // UTF-8 | |
| py::list out; | |
| std::vector<uint32_t> buf; | |
| size_t pos = 0; | |
| while (pos <= s.size()) { | |
| // Próximo token especial mais à esquerda (empate: o que vier antes no dict, | |
| // igual o re.split resolve a alternância (a|b|c)). | |
| size_t best = std::string::npos; | |
| size_t best_k = 0; | |
| for (size_t k = 0; k < S.size(); ++k) { | |
| const size_t p = s.find(S[k].tok, pos); | |
| if (p == std::string::npos) continue; | |
| if (best == std::string::npos || p < best) { best = p; best_k = k; } | |
| else if (p == best && k < best_k) { best_k = k; } | |
| } | |
| const std::string parte = | |
| (best == std::string::npos) ? s.substr(pos) : s.substr(pos, best - pos); | |
| if (!parte.empty()) { | |
| buf.clear(); | |
| bpe_bytes(reinterpret_cast<const uint8_t*>(parte.data()), parte.size(), M, buf); | |
| for (uint32_t id : buf) out.append(id); | |
| } | |
| if (best == std::string::npos) break; | |
| out.append(S[best_k].id); | |
| pos = best + S[best_k].tok.size(); | |
| } | |
| return out; | |
| } | |
| } // namespace | |
| PYBIND11_MODULE(bpe_fast, m) { | |
| m.doc() = "BPE byte-level idêntico ao _bpe_encode() de Python, em C++ (zig + pybind11)."; | |
| m.def("encode", &encode, py::arg("text"), py::arg("merges"), py::arg("specials"), | |
| "Tokeniza text (UTF-8) com os merges BPE; tokens especiais viram ids atômicos."); | |
| } | |