mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[GH-ISSUE #3862] [Engine] GBNF constrained decoding: stable tool calls + JSON schema (scope) #1648
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#1648
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @sd133cn on GitHub (Oct 23, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/3862
GBNF 约束解码设计(借鉴 llama.cpp)
日期:2026-10-23 · 分支:
feature/gbnf-constrained-decoding· 状态:待审阅0. 接力状态(新会话从这里接)
F:\Strata-dev(检出本分支,共享F:\Strata\.git);F:\Strata保持在main,是用户跑模型的运行实例,不在里面开发。serve/test_server.py等测试文件的 SSRF/路径穿越形态)强制拦截;MCP 深度扫描已对两项目封印(F:\Strata:scan-2026-10-23T15-37-49.786Z-85a1278eb6bb,seal sha256:5bdbe6c2…,472 项;F:\Strata-dev:scan-2026-10-23T15-35-19.666Z-2fedf893d467,seal sha256:490a021a…,333 项;688 个依赖包中 2 包命中 3 条安全公告)。MCP 封印verdictEffect: none,钩子解锁需用户在 Mimosa 应用内标记误报/基线。2026-10-23 审阅核对:repo 与全局均无core.hooksPath,F:\Strata\.git\hooks\pre-commit不存在——拦截经 Mimosa 应用侧发生;实施期分支提交若被拦,基线标记在关键路径上,与计划并行处理。docs/superpowers/plans/2026-10-24-gbnf-constrained-decoding.md(13 任务,TDD,逐任务提交)。用户已授权全程自主实施到交付(m00141:不再提问,按推荐路线);按 CONTRIBUTING 先开 scope issue(计划 Task 1)。1. 目标(用户定调)
最主要目的:稳定的工具调用和 JSON 结构化输出。
在引擎内实现 llama.cpp 同源的 GBNF 语法约束解码:每步采样只在语法允许的 token 中取值,输出结构由解码保证,不再依赖提示词指令与事后校验。通用
grammar参数是底座;JSON Schema 硬约束与工具调用 grammar 是目的。2. 现状与承重事实(已核实)
src/program/generate.cpp:7-8的循环embed_row → 层图 → lm_head → sample → embed_row(next);采样是设备核,链为penalties → top_k → top_p → min_p → temperature → pick(include/strata/kernels/sampler.hpp,实现src/kernels/cuda/sampler.cu),可被 CUDA graph 捕获。src/program/generate.cpp:15864-15865(cudaMemcpyAsyncd_next→host),随后put_input喂回。语法状态机在主机推进不需要新增同步点。logit_bias已有 HTTP→服务器→行协议→设备数组→采样核(penalties/filters 之前加性,-inf 禁)的端到端先例:serve/logit_bias.py、serve/server.py:1437、SamplerParams.logit_bias。include/strata/artifact/gguf_reader.hpp:728(tokenizer.ggml.tokens)。F:\Strata(.gitignore:31忽略/third_party/llama.cpp;worktreeF:\Strata-dev无此目录,2026-10-23 实测):third_party/llama.cpp/src/llama-grammar.cpp/.h(GBNF 解析器 + 状态栈 + bitmask)、common/json-schema-to-grammar.cpp/.h(JSON Schema→GBNF)、grammars/*.gbnf、测试tests/test-grammar-parser.cpp、test-grammar-integration.cpp、test-json-schema-to-grammar.cpp。移植的复制源即该目录;移植产物(含转换器 CLI 用到的common/源)必须提交入库并保留 llama.cpp 的 MIT 署名——构建不得依赖本地third_party/目录。serve/structured.py:1-4明示"native engine has no grammar decoder",prompt 指令 + 事后校验,失败即structured_output_failed。<tool_call>\n<function=NAME>\n(<parameter=KEY>\nVALUE\n</parameter>\n)+</function>\n</tool_call>,多调用以\n分隔,前有散文时以\n\n<tool_call>开板(serve/chat_template.jinja:134-156)。VALUE:字符串是裸文本,其余经tojson成 JSON。解析器在serve/frontend.py:909一带(有rescued/refused计数);tool_choice强制逻辑在serve/server.py:6928、server.py:5244。3. 已定决定(含理由)
metal/独立引擎树)与 CPU 缓做4. 架构与数据流
5. 组件
5.1 引擎 grammar 模块(新)
include/strata/grammar/+src/grammar/:移植 vendoredllama-grammar.cpp/.h为strata::grammar——GBNF 解析器、状态栈、栈推进、per-state token 接受预计算与 bitmask 缓存(llama.cppinit_vocab/parse_token/advanced-cache 结构)。移植手术集中在llama_vocab依赖,换成GrammarVocab(从 GGUF 元数据经 gguf_reader 构造:token 字符串 +tokenizer.ggml.token_type控制/特殊 token 标志 + EOG id)。vendored 侧三处触点(审阅核实):llama-grammar.cpp:186(parse_token)、:1131、:1212。token_type不可省:llama.cpp 靠它跳过 special token,丢了标志<|im_end|>会被当字面文本解析进语法。5.2 mask 管道
uint32[slot][ceil(n_vocab/32)],首次 grammar 请求到达时惰性分配(显存可忽略:152k 词表每槽约 19 KB;不留"启动未启用则请求 400"的路径);核内读mask_ptr + slot*stride,mask 指针经 mapped-params 间接层(与sampler.hpp:56-60coupled_draft_stage的*params <- *mapped_params同型)在图内运行时可读,惰性分配无需重启服务;每步 H2D 在图外更新。SamplerParams增 mask 指针与 stride,默认 null=完全跳过(默认路径零改动);sample_tokens与sample_greedy_cluster两条路径都受限——后者签名现无SamplerParams(sampler.hpp:50),mask 接线需扩其签名,两路各自接。5.3 行协议
GRAMMAR <sha16> <bytes> <文本>内容地址注册 +grammar=<sha16>引用;采样键并入该哈希(serve/server.py:1367sampling_keys,其尾部即bias_api.engine_key,:1437;该串直接拼进 GEN 行server.py:2177-2178,逐请求粒度,无引擎重启语义;grammar 改变采样分布)。服务器发现 grammar 即从 GEN/BGEN 行剔除投机参数。5.4 转换器(服务器侧)
tools/下用 vendoredcommon/json-schema-to-grammar.cpp+json.cpp编小 CLI;服务器子进程调用、按 schema 哈希缓存。零新依赖。5.5 工具调用 grammar 构建器(服务器侧 Python)
从工具 schema + 模板序列化规则(§2 逐字)生成 GBNF:
tool_choice: "required"/"any":强制<tool_call>\n<function=NAME>开板;候选名交替,指定名则定死字面量。<parameter=KEY>\n值\n</parameter>;字符串属性→文本规则(禁\n</parameter>序列);非字符串属性→该属性子 schema 的 JSON 子语法(转换器按属性调用)。tool_choice: "auto":根规则 = 散文 | 工具调用块 交替(模型可不选工具;一旦调用必合法)。server.py:5244)与 rescue 补偿路径(解析器保留为契约检查)。server.py:6945、server.py:6930-6931抛错),回落是放宽;响应形态测试须覆盖"声明 method 的回落"与既有拒绝的边界。5.6 response_format 语义
NVIDIA/AMD:
json_object= 仅对象语法;json_schema= schema→GBNF 硬约束。响应structured_output.method(现 "prompt_and_validate",server.py:4531)→ "grammar"。Mac/CPU 报不支持 → json_schema 回落 prompt+validate 并声明 method;裸grammar参数 → 400。validated_json保留为末端金丝雀(触发=引擎 bug,走现有 502 路径并加 "grammar engine bug" 标记,绝不静默)。6. 错误处理
generate.cpp:11845,11859)。v1 规则:grammar 在 GENI/BGENI 与 GEN/BGEN 完全同路径(mask 机制与图像无关),不单独缓做。7. 测试与验收
test-grammar-parser.cpp+test-grammar-integration.cpp子集;sampler_parity.cpp扩 mask 位点;新增grammar_test.cpp;logit_bias_test.cpp模式沿用。test-json-schema-to-grammar.cpp的金样用例移植进tools/test_grammar_schema.py。serve/test_structured.py、test_responses.py、test_frontend.py扩 grammar 路径;tools/test_grammar_*.py无 GPU 自测(构建器/协议键/回落选择)。tests/terminal覆盖行协议与 launch 面改动。strata connect <app> --check风格工具套件各跑 N 次:schema 通过率 100%;工具调用解析失败 0;grammar 请求rescued计数恒 0。8. 默认与限制(文档要写)
[Engine] …;测量数字注明测量硬件。9. 开放问题(留实施计划)
GRAMMAR行的传输编码(文本转义/分块)细节。<think>)区:v1 初定不约束思考区,约束只作用于其后的工具块/答案。此立场同时覆盖tool_choice: auto与response_format: json_schema/json_object(thinking 模型下从第 0 token 硬约束会掐死思考):服务器把 grammar 组成"放行 think 块、其后硬约束"的前序规则;与模板<think>生成开关对齐,实施时用模板实测确认。<但不可成<tool_call>"(tool_choice:auto 的散文交替)与"think 前序放行"都需手写字符类展开,是全设计手写语法最重的一块;计划须给专门的语法边界测试(含<的散文、<tool_call>前缀、围栏代码、散文中的</think>)。@sd133cn commented on GitHub (Oct 25, 2026):
PR 就绪(Draft):#4113 —— 分支在 #3922 关闭后按预告重做:约束解码现在与 MTP / --batch-mtp 共存(逐行掩码链),并修复了两个词表层缺陷(GPT2 字节映射不全导致 36% 词表被掩码封禁 → 中文长文退化为填充字;字节 0x00 的 NUL piece 终止符碰撞 → 控制字节泄漏进约束 JSON)。验收(RTX 4090, Swift IQ3_S, --spec 2 --mtp):JSON 50/50、工具 30/30、约束 137.2 vs plain 130.5 tok/s。验证分列(HIP/SYCL 未构建)与限制见 PR 描述。
@Niko1221 commented on GitHub (Nov 5, 2026):
Thanks for taking the time to report this.
Strata has changed a lot since this was opened, and 0.2.11 is out now, so many older reports no longer apply. We're closing issues older than a week that have had no new reports in the last week. Closed here does not mean rejected.
To reopen it takes about two minutes:
/reopen. A check runs and either reopens the issue or lists what is still missing.The rules are in CONTRIBUTING.md.