Sign in

    weopqrst/tally/bpe does not have a README file

    CodePoint

    pub(all) struct CodePoint {
    cp : UInt
    start : Int
    size : Int
    valid : Bool
    } derive(
    Debug
    )

    输入流中的一个码点单元。

    • cp —— 码点值;若 valid 为 false,则它是原始字节值(0…255)。
    • start —— 在原始 Bytes 中的起始字节偏移。
    • size —— 占用的字节数(非法字节恒为 1)。
    • valid —— 是否是合法 UTF-8 码点。

    非法字节在分类时一律按 "既非字母、也非数字、也非空白" 处理, 从而落进预切分模式的 [^\s\p{L}\p{N}] 分支,字节原样保留。

    VocabView

    pub(all) struct VocabView {
    tokens : Array[Bytes]
    byte_ids : Array[Int]
    rank_of : Map[Bytes, Int]
    id_of : Map[Bytes, Int]
    rank_short : Map[Int64, Int]
    id_short : Map[Int64, Int]
    specials : Array[(Bytes, Int)]
    }

    bpe 与 vocab 之间的唯一契约。

    • tokens —— index = token id 的字节序列。
    • byte_ids —— 256 项,单字节 token 的 id(不变量 V1 的根基)。
    • rank_of —— token 字节 -> 合并优先级(越小越先合并)。
    • id_of —— token 字节 -> token id。
    • specials —— 特殊 token 字面量 (字节, id)。建议按长度降序(性能提示), 但正确性由 match_special 自行保证(扫全部取最长)。

    SHORT_MAX

    let SHORT_MAX : Int

    打包进 Int64 的最长字节数:低 8 位存长度,其余按小端存字节。

    concat_bytes

    fn concat_bytes(a : Bytes, b : Bytes) -> Bytes

    拼接两个字节序列。

    注:本版本 Bytes 没有 op_set,写入一律经 Array[Byte] 中转 (Bytes::from_array)。这是工具链层面的约束,不是设计选择。

    count_ordinary

    fn count_ordinary(v : VocabView, bytes : Bytes) -> Int

    普通文本的 token 数(不产出 id 数组)。

    decode

    fn decode(v : VocabView, ids : Array[Int]) -> Bytes

    把 token id 序列拼回字节序列。

    越界的 id 会被忽略(调用方若需严格模式可自行校验)。

    decode_utf8_lenient

    fn decode_utf8_lenient(bytes : Bytes) -> Array[CodePoint]

    宽松 UTF-8 解码:合法序列解出一个码点,非法字节各自成为一个单元。

    合法性判定与 Unicode 表 3-7 一致(拒绝过长编码、代理区、> U+10FFFF)。

    encode

    fn encode(v : VocabView, bytes : Bytes) -> Array[Int]

    完整编码:先把已登记的特殊 token 字面量切出来(最长优先), 其余部分走普通编码。未登记的特殊字面量按普通文本处理(安全默认值)。

    encode_count

    fn encode_count(v : VocabView, bytes : Bytes) -> Int

    完整编码的"只计数"版本:与 encode 同一条切分路径,但不分配 id 数组。 encode_count(v, b) == encode(v, b).length() 由单元测试守着。

    encode_ordinary

    fn encode_ordinary(v : VocabView, bytes : Bytes) -> Array[Int]

    把一段普通文本(不含特殊 token)编码为 token id 序列。

    pack_short

    fn pack_short(piece : Bytes, start : Int, len : Int) -> Int64

    把 piece[start, start+len) 打包成 Int64 键(len 必须 ≤ SHORT_MAX)。

    长度放在最低字节、数据从次低字节起,因此不同长度的字节串永不撞键, 也不需要再拼 Bytes——这是热路径上省掉的分配。vocab 构建短键表时 用的是同一个函数,两端不会漂移。

    pretokenize

    fn pretokenize(bytes : Bytes) -> Array[(Int, Int)]

    预切分结果:把原始字节切成若干"片",每片提供 [start, end) 字节区间。

    返回的是区间而非副本,避免在热路径上反复分配; 调用方需要时用 slice_bytes 取副本。

    slice_bytes

    fn slice_bytes(bytes : Bytes, from : Int, to : Int) -> Bytes

    取 bytes[from, to) 的副本。

    unicode_table_sizes

    fn unicode_table_sizes() -> (Int, Int, Int)

    (字母, 数字, 空白) 三类区间表的条数。

    unicode_version

    fn unicode_version() -> String

    生成表时所用的 Unicode 版本(写入 README 与报告,保证可复算)。