Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 103 additions & 4 deletions scripts/generate_jieba_embedded_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

"""Generate embedded Jieba dictionaries as raw LZ4 blocks.
"""Generate the precompiled Jieba main dictionary and embedded HMM model.

Run from any directory:
python3 scripts/generate_jieba_embedded_dict.py
Expand All @@ -29,7 +29,9 @@
import ctypes
import ctypes.util
import hashlib
import itertools
import logging
import struct
from pathlib import Path


Expand Down Expand Up @@ -78,13 +80,96 @@ def compress(library, original: bytes) -> bytes:
return destination.raw[:size]


def compile_dictionary(source: bytes) -> tuple[bytes, str]:
"""Store cppjieba entries in source order, in little-endian columns.

Each entry has a uint16 rune count, uint16 tag byte count and uint32
frequency. The variable-length columns hold UTF-32LE words and UTF-8 tags.
"""
word_lengths = bytearray()
tag_lengths = bytearray()
frequencies = bytearray()
words = bytearray()
tags = bytearray()
counts = []
spellings = []
for line in source.splitlines():
word, count, tag = line.split()
spelling = word.decode("utf-8")
spellings.append(spelling)
runes = spelling.encode("utf-32-le")
frequency = int(count)
if not (0 < frequency <= 0xFFFFFFFF):
raise ValueError(f"invalid dictionary frequency: {count!r}")
word_lengths.extend(struct.pack("<H", len(runes) // 4))
tag_lengths.extend(struct.pack("<H", len(tag)))
frequencies.extend(struct.pack("<I", frequency))
words.extend(runes)
tags.extend(tag)
counts.append(frequency)

if not counts:
raise ValueError("empty main dictionary")
counts.sort()
total = sum(counts)
if total > 2**53:
raise ValueError("dictionary frequency sum must fit exactly in a double")
metadata = (
f"constexpr std::size_t kJiebaWordCount = {len(counts)};\n"
f"constexpr std::size_t kJiebaRuneCount = {len(words) // 4};\n"
f"constexpr double kJiebaFrequencySum = {total}.0;\n"
f"constexpr unsigned kJiebaMinFrequency = {counts[0]};\n"
f"constexpr unsigned kJiebaMedianFrequency = {counts[len(counts) // 2]};\n"
f"constexpr unsigned kJiebaMaxFrequency = {counts[-1]};\n"
)
metadata += trie_layout(spellings)
return b"".join((word_lengths, tag_lengths, frequencies, words, tags)), metadata


def trie_layout(words: list[str]) -> str:
"""Locate each trie level and encode lexical order as runs of source rows."""
level_sizes = [0] * max(map(len, words))
ranges = []
previous = ""
# Stable order preserves cppjieba's last-entry-wins rule for duplicates.
for row in sorted(range(len(words)), key=words.__getitem__):
word = words[row]
shared = 0
limit = min(len(word), len(previous))
while shared < limit and word[shared] == previous[shared]:
shared += 1
for depth in range(shared, len(word)):
level_sizes[depth] += 1
if ranges and ranges[-1][1] == row:
ranges[-1][1] += 1
else:
ranges.append([row, row + 1])
previous = word

# Node zero is the root.
offsets = list(itertools.accumulate(level_sizes, initial=1))
if offsets[-1] > 0xFFFFFFFF or len(words) > 0xFFFFFFFF:
raise ValueError("embedded trie indices must fit in uint32")
level_offsets = ", ".join(map(str, offsets))
row_ranges = "".join(f" {{{start}, {end}}},\n" for start, end in ranges)
root_size = max(ord(word[0]) for word in words) + 1
return (
f"constexpr std::array<uint32_t, {len(offsets)}> kJiebaLevelOffsets = "
f"{{{level_offsets}}};\n"
f"constexpr uint32_t kJiebaSortedRowRanges[][2] = {{\n{row_ranges}}};\n"
f"constexpr std::size_t kJiebaRootSize = {root_size};\n"
)


def write_include(
output: Path,
symbol: str,
source_name: str,
original: bytes,
compressed: bytes,
lz4_version: int,
payload_size: int,
metadata: str,
):
with output.open("w", encoding="ascii", newline="\n") as stream:
stream.write("// Generated by scripts/generate_jieba_embedded_dict.py.\n")
Expand All @@ -98,7 +183,8 @@ def write_include(
chunk = compressed[offset : offset + 16]
stream.write(" " + ", ".join(f"0x{byte:02x}" for byte in chunk) + ",\n")
stream.write("};\n")
stream.write(f"constexpr std::size_t {symbol}OriginalSize = {len(original)};\n")
stream.write(f"constexpr std::size_t {symbol}OriginalSize = {payload_size};\n")
stream.write(metadata)
stream.write("// clang-format on\n")


Expand All @@ -125,16 +211,29 @@ def main():
("hmm_model.utf8", "jieba_hmm_model_lz4.inc", "kJiebaHmmModelLz4"),
):
original = (args.dict_dir / source_name).read_bytes()
compressed = compress(library, original)
payload, metadata = (
compile_dictionary(original)
if source_name == "jieba.dict.utf8"
else (original, "")
)
compressed = compress(library, payload)
write_include(
args.output_dir / output_name,
symbol,
source_name,
original,
compressed,
library.LZ4_versionNumber(),
len(payload),
metadata,
)
logging.info(
"%s: %d source bytes, %d payload bytes, %d compressed bytes",
source_name,
len(original),
len(payload),
len(compressed),
)
logging.info("%s: %d -> %d bytes", source_name, len(original), len(compressed))


if __name__ == "__main__":
Expand Down
12 changes: 8 additions & 4 deletions src/db/index/column/fts_column/fts_column_indexer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ Result<void> FtsColumnIndexer::open(FieldSchema::Ptr field_meta,
field_meta->name()));
}

auto pipeline_result = zvec::detail::AcquireFtsPipeline(*fts_param);
auto pipeline_result = zvec::detail::PrepareFtsPipeline(*fts_param);
if (!pipeline_result.has_value()) {
return tl::make_unexpected(Status::InternalError(
"FtsColumnIndexer: failed to create tokenizer pipeline. field=",
Expand Down Expand Up @@ -153,7 +153,7 @@ Result<void> FtsColumnIndexer::close() {
}

ctx_ = nullptr;
tokenizer_pipeline_.reset();
tokenizer_pipeline_ = {};
postings_cf_ = nullptr;
positions_cf_ = nullptr;
term_freq_cf_.store(nullptr, std::memory_order_release);
Expand Down Expand Up @@ -607,7 +607,7 @@ Result<void> FtsColumnIndexer::insert(uint64_t seg_doc_id,
const std::string &text) {
// safe access check

if (!tokenizer_pipeline_ || !ctx_) {
if (!tokenizer_pipeline_.valid() || !ctx_) {
return tl::make_unexpected(Status::InternalError(
"FtsColumnIndexer::insert: not opened. field=", field_name_));
}
Expand All @@ -618,7 +618,11 @@ Result<void> FtsColumnIndexer::insert(uint64_t seg_doc_id,
}

// Tokenize
std::vector<Token> tokens = tokenizer_pipeline_->process(text);
const auto &pipeline = tokenizer_pipeline_.get();
if (!pipeline) {
return tl::make_unexpected(pipeline.error());
}
std::vector<Token> tokens = (*pipeline)->process(text);
const uint32_t doc_len = static_cast<uint32_t>(tokens.size());

// Aggregate position lists by term
Expand Down
2 changes: 1 addition & 1 deletion src/db/index/column/fts_column/fts_column_indexer.h
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ class FtsColumnIndexer {

// --- Tokenizer (write path only) ---
FieldSchema::Ptr field_meta_{};
TokenizerPipelinePtr tokenizer_pipeline_{nullptr};
PreparedTokenizerPipeline tokenizer_pipeline_;
std::shared_ptr<zvec::FtsIndexParams> fts_params_;

// --- Reader state ---
Expand Down
8 changes: 4 additions & 4 deletions src/db/index/column/fts_column/fts_pipeline.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@
#include <memory>
#include <zvec/db/index_params.h>
#include <zvec/db/status.h>
#include "tokenizer/tokenizer_factory.h"

namespace zvec {

namespace fts {
class TokenizerPipeline;
} // namespace fts

namespace detail {

Result<fts::PreparedTokenizerPipeline> PrepareFtsPipeline(
FtsIndexParams &params);

// Internal entry to lazily acquire (and cache, per FtsIndexParams instance)
// the tokenizer pipeline. Thread-safe; same params instance returns the
// same shared_ptr on subsequent calls; the manager-side reference is
Expand Down
Loading
Loading