Token 数量计算
更新时间:2026-09-14
简介
文本 token 数统计算子,用 HuggingFace tokenizer 统计每条文本的 token 数量,默认 tokenizer 为 EleutherAI/pythia-6.9b-deduped。算子只产出计数,按上下界过滤交给 pipeline 的 where。
功能描述
- 只加载
model_path/model_name目录下的分词器,不加载模型权重,纯 CPU 即可运行 - 分词时
add_special_tokens=False,计数不含 BOS/EOS - 按
batch_size微批分词;某个微批整批失败时降级为逐条重试,只把失败的那一条置 None,不带走整批 - 空字符串、纯空白、非字符串(含 null)不进入分词,直接返回 None
- tokenizer 目录不存在抛
FileNotFoundError、加载失败抛RuntimeError,都发生在算子初始化阶段,不静默降级成全 None
算子参数
输入
| 输入 | 含义 |
|---|---|
| texts | 文本字符串数组 |
输出
| 输出 | 含义 |
|---|---|
| num_token | token 数量(int64);空文本或分词失败返回 None |
参数
| 参数名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| model_path | str | "/opt/aihc/model" | 权重根目录 |
| model_name | str | "EleutherAI/pythia-6.9b-deduped" | 相对 model_path 的 tokenizer 目录名 |
| trust_remote_code | bool | False | 是否允许加载 tokenizer 仓库内的自定义代码 |
| batch_size | int | 64 | 算子内部分词的微批大小,与 aihc_udf 的 batch_size 相互独立 |
注意事项
- 与存量「文本长度计算器」(
TextLengthCalculator,按字符数计)量纲不可比,不能复用同一套阈值。 - 换 tokenizer 后同一段文本的 token 数会变,阈值需随
model_name重新校准。 - 默认目录名带
6.9b,但只用到目录里的分词器文件(词表与 tokenizer 配置),不需要下载 6.9B 模型权重。
调用示例
Python
1from __future__ import annotations
2
3import os
4
5import daft
6from daft import col
7
8from daft.aihc.common.udf import aihc_udf
9from daft.aihc.functions.text.token_count_calculator import TokenCountCalculator
10
11if __name__ == "__main__":
12 if os.getenv("DAFT_RUNNER", "native") == "ray":
13 import ray
14 ray.init(dashboard_host="0.0.0.0", ignore_reinit_error=True)
15 daft.set_runner_ray()
16 daft.set_execution_config(actor_udf_ready_timeout=6000, min_cpu_per_task=0)
17
18samples = {
19 "text": [
20 "Hello world, this is a tokenizer test.",
21 "百度智能云 AIHC 数据处理算子。",
22 "",
23 ]
24 }
25 ds = daft.from_pydict(samples)
26 ds = ds.with_column(
27 "num_token",
28 aihc_udf(
29 TokenCountCalculator,
30 construct_args={
31 "model_path": "/path/to/models",
32 "model_name": "EleutherAI/pythia-6.9b-deduped",
33 },
34 num_cpus=1,
35 concurrency=1,
36 batch_size=64,
37 )(col("text")),
38 )
39 ds.show()
评价此篇文章
