Skip to content

[Feature]AISBench支持大模型响应异常检测 - #468

Merged
SJTUyh merged 40 commits into
AISBench:masterfrom
Libotry:br_response_anomaly
Aug 19, 2026
Merged

SJTUyh merged 40 commits into
AISBench:masterfrom
Libotry:br_response_anomaly

Conversation

@Libotry

@Libotry Libotry commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks for your contribution; we appreciate it a lot. The following instructions will make your pull request healthier and help you get feedback more easily. If you do not understand some items, don't worry, just make the pull request and seek help from maintainers.
感谢您的贡献,我们非常重视。以下说明将使您的拉取请求更健康,更易于获得反馈。如果您不理解某些项目,请不要担心,只需提交拉取请求并从维护人员那里寻求帮助即可。

PR Type / PR类型

  • Feature(功能新增)
  • Bugfix(Bug 修复)
  • Docs(文档更新)
  • CI/CD(持续集成/持续部署)
  • Refactor(代码重构)
  • Perf(性能优化)
  • Dependency(依赖项更新)
  • Test-Cases(测试用例更新)
  • Other(其他)

Related Issue | 关联 Issue
Fixes #(issue ID / issue 编号) / Relates to #(issue ID / issue 编号)
Relates to #467

🔍 Motivation / 变更动机

大模型服务推理过程中可能出现生僻字、乱码、重复输出、NaN/Inf logprob 等响应异常。当前 AISBench 能够完成推理与评测,但缺少对服务返回内容的独立异常检测与审计能力。

本 PR 集成 msProbe 的 Response Anomaly 能力,在不改变原有评测指标和主流程行为的前提下,为服务化模型推理增加 Case 级响应异常检测、结果落盘、进度展示以及断点续跑支持。

📝 Modification / 修改内容

1. 新增响应异常检测开关与配置

  • 新增 CLI 参数:
    • --response-anomaly / --no-response-anomaly:开启或关闭响应异常检测。
    • --response-anomaly-payload-retention {all,anomalies,none}:配置 payload 保留策略。
  • 新增全局 response_anomaly 配置,并支持模型级 response_anomaly 配置覆盖。
  • 启用检测时自动向服务请求注入:
    • logprobs=True
    • top_logprobs=20
  • 对模式和配置进行校验:
    • 仅支持 all、infer、infer_judge 普通生成链路。
    • 不支持 perf / perf_viz、Agent、函数调用及自定义 Agent 类评测链路。
    • 仅支持 service 模型。
    • 校验 payload 存储格式、压缩参数及分片配置。

2. 接入 msProbe 响应异常检测流程

  • 新增 ResponseAnomalyCoordinator:
    • 推理完成后以后台线程执行 msProbe ILLDetector 检测。
    • 与 Judge / Eval / 汇总流程并行执行。
    • 工作流结束前等待检测线程完成,保证结果完整落盘。
  • 支持检测以下异常类型:
    • normal
    • rare_character
    • garbled
    • repetition
    • nan_value
  • 对未返回 token id 或 top-k logprobs 的 Case 标记为 skipped。
  • 当未安装 msProbe 或检测器初始化失败时,记录 unavailable / failed 状态,不影响原有推理与评测主流程。

3. 服务响应采集与 payload 存储

  • 在 API 模型响应中提取 token id 与 top-k logprobs。
  • 支持普通响应和流式响应,并兼容 vLLM OpenAI 风格 logprobs 数据。
  • vLLM 服务启用检测时自动请求返回 token id。
  • 将完整检测 payload 分流保存为 ZSTD 压缩 JSONL 分片,避免长期写入 prediction 文件。
  • 支持以下 payload 保留策略:
    • all:保留全部 payload。
    • anomalies:仅保留异常、检测失败或检测不可用的 Case。
    • none:不保留 payload。
  • 检测结果独立输出到:
    • response_anomaly/<model_abbr>/<dataset_abbr>.jsonl
  • 支持按 id + uuid 继承已完成检测结果,避免 --reuse 场景重复检测。

4. 状态面板、日志与配置生成工具

  • 将 ResponseAnomaly 作为辅助任务接入任务状态面板,展示配置准备、检测器加载、流式检测、归档收尾等阶段。
  • 为每个模型/数据集组合生成独立检测日志。
  • 新增 ais_bench-gen-response-anomaly-config 工具:
    • 包装 msProbe 官方模型配置生成脚本。
    • 支持从本地模型目录生成 msProbe 配置。
    • 支持合并已有 mtype_config.json,避免多模型配置互相覆盖。
  • 新增可选依赖 response_anomaly,包含 mindstudio-probe 与 zstandard。

📐 Associated Test Results / 关联测试结果

生僻字、乱码、重复输出、NaN/Inf logprob 等响应异常测试:
image

image image image

中断续推
image

⚠️ BC-breaking (Optional) / 向后不兼容变更(可选)

无

默认情况下 response_anomaly.enabled=False,未启用该功能时不改变现有推理、评测和结果文件行为。

启用该功能后,服务端需要支持返回 token id 和 top-k logprobs;对于不支持的服务响应,AISBench 会将对应 Case 标记为 skipped,不会中断原有评测流程。

⚠️ Performance degradation (Optional) / 性能下降(可选)

启用响应异常检测后:

  • 推理请求会额外请求 logprobs=True 和固定 top_logprobs=20,可能增加服务端返回数据量与推理开销。
  • AISBench 会额外进行 payload 压缩写盘和 msProbe 检测,增加一定 CPU、磁盘 I/O 和任务收尾时间。
  • 检测在线程中与后续 Judge / Eval / 汇总流程并行执行,尽量降低对整体工作流耗时的影响。
  • 未启用功能时不会引入上述额外开销。

🌟 Use cases (Optional) / 使用案例(可选)

适用于以下场景:

  1. 对服务化大模型进行批量评测时,审计生僻字、乱码、重复输出及 NaN 类异常响应。
  2. 在模型服务升级、推理框架变更或参数调整后,对输出稳定性进行回归检查。
  3. 结合 payload_retention='anomalies',仅保留异常样本及检测失败样本,方便后续问题定位。
  4. 通过 --reuse 继续中断任务时复用已完成的异常检测结果,避免重复检测。

✅ Checklist / 检查列表

Before PR:

  • Pre-commit or other linting tools are used to fix the potential lint issues. / 使用预提交或其他 linting 工具来修复潜在的 lint 问题。
  • Bug fixes are fully covered by unit tests, the case that causes the bug should be added in the unit tests. / 修复的 Bug 已完全由单元测试覆盖,导致 Bug 的情况应在单元测试中添加。
  • The modification is covered by complete unit tests. If not, please add more unit tests to ensure the correctness. / 此拉取请求中的修改已完全由单元测试覆盖。如果不是,请添加更多单元测试以确保正确性。
  • All relevant documentation (API docs, docstrings, example tutorials) has been updated to reflect these changes. / 所有相关文档(API 文档、文档字符串、示例教程)已更新以反映这些更改。

After PR:

  • If the modification has potential influence on downstream or other related projects, this PR should be tested with those projects. / 如果此拉取请求对下游或其他相关项目有潜在影响,应在那些项目中测试此 PR。
  • CLA has been signed and all committers have signed the CLA in this PR. / CLA 已签署,且本 PR 中的所有提交者均已签署 CLA。

👥 Collaboration Info / 协作信息

  • Suggested Reviewers / 建议审核人: @xxx
  • Relevant Module Owners / 相关模块负责人: @xxx
  • Other Collaboration Notes / 其他协作说明:

🌟 Useful CI Command / 实用的CI命令

Command / 命令 Introduction / 介绍
/gemini review Performs a code review for the current pull request in its current state by Gemini. / 对当前拉取请求在当前状态下由 Gemini 执行代码审核。
/gemini summary Provides a summary of the current pull request in its current state by Gemini. / 对当前拉取请求在当前状态下由 Gemini 提供摘要。
/gemini help Displays a list of available commands of Gemini. / 显示 Gemini 可用命令的列表。
/readthedocs build Triggers a build of the documentation for the current pull request in its current state by Read the Docs. / 触发当前拉取请求在当前状态下由 Read the Docs 构建文档。
/pr_check 手动重新触发 PR 合入质量检查工作流(PR Quality Check),并在 PR 上评论即可生效。 / Manually re-runs the PR Quality Check workflow by commenting on the pull request.

Copilot AI lite review requested due to automatic review settings August 15, 2026 09:31
@github-actions github-actions Bot added large_pr PR 新增代码超过 1000 行,建议拆分为更小的 PR no_issue PR 未关联任何 Issue,合入前必须关联 Issue no_review PR 未包含任何检视意见,合入前必须包含检视意见 labels Aug 15, 2026
@github-actions

Copy link
Copy Markdown

🚫 PR 合入质量检查未通过,PR 已被禁止合入。

未通过项:large_pr、no_issue、no_review

  • 超大 PR:新增代码 4693 行,超过 1000 行上限,建议拆分。
  • 未关联 Issue:请在 PR 描述中关联 Issue,例如 Fixes #123 或 Relates to #123。
  • 无检视意见:请至少邀请一位 reviewer 提交检视意见(Approve / Request changes / Comment 均可)。

请按上述提示整改后,重新推送(push)或评论本 PR 即可触发再次检查。

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds an optional “response anomaly detection” pipeline to AISBench that captures token ids + top-k logprobs from service-model responses, stages payloads into compressed shards, and runs msProbe’s detector in a background thread after inference to produce per-case anomaly results and live task-board status.

Changes:

  • Add response-anomaly payload capture (API response parsing + request kwarg injection), staging (zstd jsonl shards), and background detection coordinator with resumable archives.
  • Extend CLI/config/runner/task-board support to enable/monitor/cleanup the auxiliary ResponseAnomaly task across supported modes.
  • Add packaging extras, documentation, and extensive unit tests for config generation, payload extraction, staging, and detection/resume flows.

Reviewed changes

Copilot reviewed 39 out of 39 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/UT/utils/test_response_anomaly.py End-to-end and edge-case tests for detection coordinator (status/logging, resume, retention modes).
tests/UT/utils/test_response_anomaly_jsonl.py Tests for zstd JSONL writer/staging + manifest generation.
tests/UT/tools/response_anomaly/test_gen_model_config.py Tests for msProbe model-config wrapper tool (merge/copy/failure modes).
tests/UT/runners/test_base.py Update TasksMonitor tmp cleanup and auxiliary-status handling tests.
tests/UT/openicl/icl_inferencer/output_handler/test_base_handler.py Validate prediction writing stages payload separately.
tests/UT/models/api_models/test_vllm_custom_api_chat.py Ensure vLLM chat requests ask for token ids when anomaly detection enabled.
tests/UT/models/api_models/test_response_anomaly_payload.py Unit tests for payload extraction/accumulation from service responses (streaming + OpenAI-style logprobs).
tests/UT/cli/test_config_manager.py Tests for response anomaly config normalization/validation and CLI overrides.
tests/UT/cli/test_argument_parser.py Tests for new CLI arguments parsing.
setup.py Add response_anomaly extra + CLI entrypoint for config generator.
requirements/response_anomaly.txt New optional deps for msProbe (pinned) + zstandard.
docs/source_zh_cn/get_started/install.md Installation docs for response anomaly optional deps.
docs/source_zh_cn/design/AISBench推理响应异常检测模块设计.md Full design doc for response anomaly module.
docs/source_zh_cn/base_tutorials/all_params/models.md Document model-level response_anomaly config fields.
docs/source_zh_cn/base_tutorials/all_params/mode.md Document supported/unsupported modes for anomaly detection.
docs/source_zh_cn/base_tutorials/all_params/cli_args.md Document new CLI flags and response anomaly config block.
docs/source_en/get_started/install.md English installation docs for response anomaly optional deps.
docs/source_en/base_tutorials/all_params/models.md English docs for model-level response_anomaly config fields.
docs/source_en/base_tutorials/all_params/mode.md English docs for supported/unsupported modes.
docs/source_en/base_tutorials/all_params/cli_args.md English docs for new CLI flags and response anomaly config block.
ais_bench/tools/response_anomaly/gen_model_config.py New wrapper to run msProbe generator safely and merge outputs.
ais_bench/tools/response_anomaly/init.py Package init for response anomaly tools.
ais_bench/benchmark/utils/response_anomaly.py New background coordinator: detect, resume, archive payloads, write status/logs.
ais_bench/benchmark/utils/response_anomaly_jsonl.py New zstd JSONL shard writer/reader + manifest builder.
ais_bench/benchmark/utils/config/build.py Strip response_anomaly from model cfg before building model.
ais_bench/benchmark/runners/local.py Preserve response anomaly status file during tmp cleanup.
ais_bench/benchmark/runners/base.py Task-board: read ResponseAnomaly status without clearing; handle auxiliary tasks.
ais_bench/benchmark/openicl/icl_inferencer/output_handler/gen_inferencer_output_handler.py Add response_anomaly_payload into prediction records when available.
ais_bench/benchmark/openicl/icl_inferencer/output_handler/base_handler.py Stage payload to compressed shards and remove from predictions.
ais_bench/benchmark/openicl/icl_inferencer/icl_multiturn_inferencer.py Pass response-anomaly staging runtime into output handler.
ais_bench/benchmark/openicl/icl_inferencer/icl_lmm_gen_inferencer.py Pass response-anomaly staging runtime into output handler.
ais_bench/benchmark/openicl/icl_inferencer/icl_gen_inferencer.py Pass response-anomaly staging runtime into output handler.
ais_bench/benchmark/openicl/icl_inferencer/icl_base_inferencer.py Deepcopy model cfg; plumb staging runtime through inferencer.
ais_bench/benchmark/models/api_models/vllm_custom_api_chat.py Request token ids when anomaly detection enabled.
ais_bench/benchmark/models/api_models/base_api.py Extract/record/accumulate anomaly payload from text/stream responses.
ais_bench/benchmark/configs/models/vllm_api/vllm_api_general_chat.py Document example response_anomaly model config block.
ais_bench/benchmark/cli/workers.py Start coordinator post-infer; add ResponseAnomalyWait worker + dedicated monitor.
ais_bench/benchmark/cli/config_manager.py Normalize/validate response anomaly config; inject request kwargs; reject unsupported modes.
ais_bench/benchmark/cli/argument_parser.py Add new CLI flags: --response-anomaly and --response-anomaly-payload-retention.
Suppressed comments (1)

ais_bench/benchmark/openicl/icl_inferencer/output_handler/base_handler.py:512

  • _stage_response_anomaly_payload() re-raises staging failures, which can prevent predictions from being persisted and turn an auxiliary feature into a hard failure. If staging fails (e.g., missing zstandard / filesystem issues), consider disabling staging and leaving response_anomaly_payload inline in the prediction record so the main workflow can still complete.
        try:
            self._response_anomaly_staging_writer.write(json_data)
        except Exception as exc:
            self._response_anomaly_staging_error = exc
            raise

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 39 out of 39 changed files in this pull request and generated 1 comment.

Comment thread setup.py Resolved
Libotry added 13 commits August 15, 2026 17:59
- Move model-specific msProbe settings into model-level response_anomaly config
- Use ILLDetector with configurable config.yaml/mtype_config.json/token2category paths
- Add ais_bench-gen-response-anomaly-config tool wrapping the official msProbe generator
- Auto-generate model configs from model_path when custom paths are absent
- Make status board, resume inheritance and unsupported-mode gating robust
- Replace same-length non-prefix snapshots instead of dropping them
- Reuse ResponseAnomalyCoordinator.STATUS_FILE_NAME in all call sites
- Keep gen_model_config tools dir on failure and add tests
- Remove redundant model_name fallback and simplify status file read
- Force logprobs/top_logprobs when response anomaly is enabled and validate
- Extend monitor progress total for auxiliary tasks
- Handle mixed full-token/current-topk stream chunks and ignore misaligned ones
…match id+uuid on resume

- Run the official msProbe generator inside an isolated temp directory so a
  partial failure never clobbers the target mtype_config.json; merge
  generated files into the target only on success
- Overwrite None-valued msprobe_config_path (set by ConfigManager) with the
  auto-generated path so user-tuned config.yaml thresholds take effect
- Match inherited results on id+uuid instead of id alone so a re-inferred
  response is not assigned a stale anomaly result
- Add tests for all three fixes
- Change the full-snapshot branch from >= to > so that a single-token
  chunk equal to the current state (two consecutive identical tokens in
  an incremental stream) falls through to the incremental-append branch
  instead of being silently dropped as a no-op snapshot
- Cache the per-model anomaly config and ILLDetector so that a model
  with multiple datasets only generates its msProbe config and loads
  token2category once instead of once per dataset
- Add test_stream_consecutive_identical_tokens_are_not_dropped
- Log a debug message when a misaligned streaming response chunk is
  dropped so payload misalignment is not silently ignored
- Warn per model/dataset group when predictions are missing, and warn
  once when no service model/dataset groups are configured at all,
  instead of silently finishing with zero analyzed cases
- Hoist the result directory mkdir out of the per-prediction loop
- Add end-to-end tests for the _detect loop, the empty-prediction
  warning, and misaligned chunk logging
The normalized model name is written by AISBench and looked up by msProbe
using the same split+join algorithm, so consecutive separators produce
double dashes on both sides (foo__bar -> foo--bar). Lock this behavior
with tests so a future cleanup cannot silently break the msProbe sync.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

Copy link
Copy Markdown

🚫 PR 合入质量检查未通过,PR 已被禁止合入。

未通过项:large_pr、review_opened

  • 超大 PR:新增代码 5552 行,超过 1000 行上限,建议拆分。
  • 检视意见未闭环:还存在 5 条未 Resolve 的检视意见,请全部 Resolve 后再合入。

请按上述提示整改后,重新推送(push)或评论本 PR 即可触发再次检查。

Copilot AI review requested due to automatic review settings August 19, 2026 07:59
@Libotry
Libotry had a problem deploying to smoke-test-approval August 19, 2026 07:59 — with GitHub Actions Failure

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

Copy link
Copy Markdown

🚫 PR 合入质量检查未通过,PR 已被禁止合入。

未通过项:large_pr、review_opened

  • 超大 PR:新增代码 5560 行,超过 1000 行上限,建议拆分。
  • 检视意见未闭环:还存在 5 条未 Resolve 的检视意见,请全部 Resolve 后再合入。

请按上述提示整改后,重新推送(push)或评论本 PR 即可触发再次检查。

Copilot AI review requested due to automatic review settings August 19, 2026 08:20
@Libotry
Libotry temporarily deployed to smoke-test-approval August 19, 2026 08:20 — with GitHub Actions Inactive

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

Copy link
Copy Markdown

🚫 PR 合入质量检查未通过,PR 已被禁止合入。

未通过项:large_pr、review_opened

  • 超大 PR:新增代码 5858 行,超过 1000 行上限,建议拆分。
  • 检视意见未闭环:还存在 5 条未 Resolve 的检视意见,请全部 Resolve 后再合入。

请按上述提示整改后,重新推送(push)或评论本 PR 即可触发再次检查。

Copilot AI review requested due to automatic review settings August 19, 2026 08:55
@Libotry
Libotry temporarily deployed to smoke-test-approval August 19, 2026 08:56 — with GitHub Actions Inactive

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

Copy link
Copy Markdown

🚫 PR 合入质量检查未通过,PR 已被禁止合入。

未通过项:large_pr、review_opened

  • 超大 PR:新增代码 5859 行,超过 1000 行上限,建议拆分。
  • 检视意见未闭环:还存在 5 条未 Resolve 的检视意见,请全部 Resolve 后再合入。

请按上述提示整改后,重新推送(push)或评论本 PR 即可触发再次检查。

@SJTUyh

SJTUyh commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator

/pr_check

@github-actions

Copy link
Copy Markdown

🚫 PR 合入质量检查未通过,PR 已被禁止合入。

未通过项:large_pr、review_opened

  • 超大 PR:新增代码 5859 行,超过 1000 行上限,建议拆分。
  • 检视意见未闭环:还存在 2 条未 Resolve 的检视意见,请全部 Resolve 后再合入。

请按上述提示整改后,重新推送(push)或评论本 PR 即可触发再次检查。

@SJTUyh

SJTUyh commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator

/pr_check

@github-actions

Copy link
Copy Markdown

🚫 PR 合入质量检查未通过,PR 已被禁止合入。

未通过项:large_pr

  • 超大 PR:新增代码 5859 行,超过 1000 行上限,建议拆分。

请按上述提示整改后,重新推送(push)或评论本 PR 即可触发再次检查。

@github-actions github-actions Bot removed the review_opened PR 中存在未闭环的检视意见,所有检视意见必须闭环后才能合入 label Aug 19, 2026

@SJTUyh SJTUyh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

超大PR已报备

This branch was previously deployed

1 inactive deployment
smoke-test-approval — 0bba2121 Deployed Aug 19, 2026 by Libotry via run_smoke_test_cases #601
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature large_pr PR 新增代码超过 1000 行,建议拆分为更小的 PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC]AISBench 推理响应异常检测模块设计 [RFC] AISBench推理响应异常检测技术方案设计

3 participants