Skip to content

【WIP】 control Prefill con in aisbench - #396

Open
vasede wants to merge 2 commits into
AISBench:masterfrom
vasede:prefill-con
Open

【WIP】 control Prefill con in aisbench #396
vasede wants to merge 2 commits into
AISBench:masterfrom
vasede:prefill-con

Conversation

@vasede

@vasede vasede commented Jul 14, 2026

Copy link
Copy Markdown

改了什么

对齐 benchmark_req.py 的测试方法,新增 “prefill 完成即放行下一个请求” 的流水线机制:

  • 新增全局 prefill 信号量 asyncio.Semaphore(n)
  • stream_infer 中:发请求前 acquire(),流式收到第一个数据块(首 token,prefill 完成)时立即 release()
    让下一个请求的 prefill 立刻开始;finally 兜底释放防死锁。
  • TTFT 计时起点 record_time_point() 放在 acquire() 之后:TTFT 不包含客户端排队等待时间
    (与 benchmark_req.py 口径一致)。
  • 可选 observe 计数,打印实时 prefill/decode 并发数。

环境变量开关(默认关闭,不影响原版行为)

export AISBENCH_PREFILL_PIPELINE=1      # 开启该功能
export AISBENCH_PREFILL_CONCURRENCY=2   # 同时处于 prefill 的最大请求数(默认 1)
export AISBENCH_PREFILL_OBSERVE=1       # 在 stderr 打印实时 prefill/decode 并发数

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 编号)

🔍 Motivation / 变更动机

Please describe the motivation of this PR and the goal you want to achieve through this PR.
请描述您的拉取请求的动机和您希望通过此拉取请求实现的目标。

📝 Modification / 修改内容

Please briefly describe what modification is made in this PR.
请简要描述此拉取请求中进行的修改。

📐 Associated Test Results / 关联测试结果

Please provide links to the related test results, such as CI pipelines, test reports, etc.
请提供相关测试结果的链接,例如 CI 管道、测试报告等。

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

Does the modification introduce changes that break the backward compatibility of the downstream repositories? If so, please describe how it breaks the compatibility and how the downstream projects should modify their code to keep compatibility with this PR.
是否引入了会破坏下游存储库向后兼容性的更改?如果是,请描述它如何破坏兼容性,以及下游项目应该如何修改其代码以保持与此 PR 的兼容性。

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

If the modification introduces performance degradation, please describe the impact of the performance degradation and the expected performance improvement.
如果引入了性能下降,请描述性能下降的影响和预期的性能改进。

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

If this PR introduces a new feature, it is better to list some use cases here and update the documentation.
如果此拉取请求引入了新功能,最好在此处列出一些用例并更新文档。

✅ 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 构建文档。

vasede added 2 commits July 14, 2026 13:58
Added prefill pipeline functionality with environment variable control and logging. Updated various functions to support new prefill behavior and improved error handling.

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces a prefill pipeline semaphore mechanism in base_api.py to allow overlapping the decode phase of one request with the prefill phase of the next, controlled via environment variables. It also simplifies custom URL parsing and cleans up formatting. The review feedback highlights critical issues: using a single global asyncio.Semaphore can cause RuntimeError across different event loops, removing the trailing slash enforcement in _get_base_url introduces a regression for custom URLs with path prefixes, and a potential semaphore leak exists in stream_infer if an exception occurs before entering the try block.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +42 to +43
_prefill_semaphore: Optional[asyncio.Semaphore] = None
_prefill_sem_lock: Optional[asyncio.Lock] = None

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.

high

Using a single global asyncio.Semaphore and asyncio.Lock can cause RuntimeError (e.g., attached to a different loop) when running multiple benchmarks or unit tests sequentially, as they get bound to the first active event loop.

Instead, we can use a dictionary mapping the current running event loop to its corresponding semaphore. This also completely eliminates the need for a lock, as the semaphore creation is synchronous and safe from race conditions within the same event loop.

Suggested change
_prefill_semaphore: Optional[asyncio.Semaphore] = None
_prefill_sem_lock: Optional[asyncio.Lock] = None
_prefill_semaphores: Dict[asyncio.AbstractEventLoop, asyncio.Semaphore] = {}

Comment on lines +70 to +86
async def _get_prefill_semaphore() -> Optional[asyncio.Semaphore]:
"""惰性创建全局 prefill 信号量(绑定到当前事件循环)。"""
global _prefill_semaphore, _prefill_sem_lock
if not _prefill_pipeline_enabled():
return None
if _prefill_sem_lock is None:
_prefill_sem_lock = asyncio.Lock()
async with _prefill_sem_lock:
if _prefill_semaphore is None:
try:
conc = int(os.environ.get("AISBENCH_PREFILL_CONCURRENCY", "1"))
except ValueError:
conc = 1
if conc < 1:
conc = 1
_prefill_semaphore = asyncio.Semaphore(conc)
return _prefill_semaphore

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.

high

Update _get_prefill_semaphore to use the loop-safe dictionary mapping. This avoids binding a single global semaphore to a closed or different event loop, and removes the redundant lock since the initialization is synchronous.

async def _get_prefill_semaphore() -> Optional[asyncio.Semaphore]:
    """惰性创建全局 prefill 信号量(绑定到当前事件循环)。"""
    global _prefill_semaphores
    if not _prefill_pipeline_enabled():
        return None
    loop = asyncio.get_running_loop()
    if loop not in _prefill_semaphores:
        try:
            conc = int(os.environ.get("AISBENCH_PREFILL_CONCURRENCY", "1"))
        except ValueError:
            conc = 1
        if conc < 1:
            conc = 1
        _prefill_semaphores[loop] = asyncio.Semaphore(conc)
    return _prefill_semaphores[loop]

Comment on lines 167 to +174
def _get_base_url(self) -> str:
protocol = "https" if self.enable_ssl else "http"
clean_url = self.url.strip() if isinstance(self.url, str) else ""
if clean_url:
self.logger.info(
f"Using custom URL: [{clean_url}], [host_ip: {self.host_ip}] and [host_port: {self.host_port}] will be ignored"
)
if self.url:
self.logger.info(f"Using custom URL: [{self.url}], [host_ip: {self.host_ip}] and [host_port: {self.host_port}] will be ignored")
# Check if URL already contains protocol
if clean_url.startswith("http://") or clean_url.startswith("https://"):
url = clean_url
else:
url = f"{protocol}://{clean_url}"
# Ensure trailing slash on path to avoid urljoin dropping the last path segment.
# Use urlparse/urlunparse to safely handle URLs with query strings or fragments.
parsed = urllib.parse.urlparse(url)
if not parsed.path or parsed.path.endswith("/"):
return url
return urllib.parse.urlunparse(parsed._replace(path=parsed.path + "/"))
if self.url.startswith("http://") or self.url.startswith("https://"):
return self.url
return f"{protocol}://{self.url}"

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.

high

Removing the trailing slash enforcement logic introduces a regression. If a user provides a custom URL with a path prefix (e.g., http://localhost:8080/v1), urllib.parse.urljoin in subclasses (like VLLMCustomAPI or MindieStreamApi) will drop the last path segment (e.g., /v1), resulting in incorrect endpoint URLs.

We should restore the trailing slash enforcement to ensure path prefixes are preserved.

    def _get_base_url(self) -> str:
        protocol = "https" if self.enable_ssl else "http"
        if self.url:
            self.logger.info(f"Using custom URL: [{self.url}], [host_ip: {self.host_ip}] and [host_port: {self.host_port}] will be ignored")
            # Check if URL already contains protocol
            if self.url.startswith("http://") or self.url.startswith("https://"):
                url = self.url
            else:
                url = f"{protocol}://{self.url}"
            # Ensure trailing slash on path to avoid urljoin dropping the last path segment.
            import urllib.parse
            parsed = urllib.parse.urlparse(url)
            if not parsed.path or parsed.path.endswith("/"):
                return url
            return urllib.parse.urlunparse(parsed._replace(path=parsed.path + "/"))

Comment on lines +323 to +330
if prefill_sem is not None:
await prefill_sem.acquire()
_prefill_inflight += 1
_prefill_log("acquire")
# 计时起点放在 acquire() 之后:TTFT 只反映“真正发出请求 -> 收到首 token”
# 的服务端耗时,不包含客户端等待 prefill 槽位的排队时间(与 benchmark_req.py 口径一致)。
await output.record_time_point()
async with self.session.post(
url=self.url, json=request_body, headers=self.headers
) as response:
if response.status == 200:
async for raw_chunk in self.iter_lines(response.content):
chunk = raw_chunk.strip()
if not chunk:
continue
chunk = chunk.decode("utf-8")
if chunk.startswith(":"):
continue
chunk = chunk.removeprefix("data:").strip()
if chunk == "[DONE]":
break
await output.record_time_point()
try:
data = json.loads(chunk)
except json.JSONDecodeError as e:
output.success = False
output.error_info = f"Unexpected response format: {raw_chunk}. Please check if server is working correctly."
raise AISBenchValueError(
MODEL_CODES.PARSE_TEXT_RSP_INVALID_FORMAT,
f"Unexpected response format. Please check 'error_info' in ***_failed.jsonl for more information.",
)
await self.parse_stream_response(data, output)
output.success = True
else:
output.error_info = response.reason
output.success = False
try:

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.

high

To prevent potential semaphore leaks and deadlocks, the try...finally block should be entered immediately after acquiring the semaphore. If an exception or cancellation occurs during await output.record_time_point(), the acquired semaphore would otherwise be leaked because the try block has not yet been entered.

Additionally, wrapping the state updates (_prefill_inflight += 1 and logging) inside the try block ensures that any unexpected failure there is also safely recovered by the finally block.

        if prefill_sem is not None:
            await prefill_sem.acquire()
        try:
            if prefill_sem is not None:
                _prefill_inflight += 1
                _prefill_log("acquire")
            # 计时起点放在 acquire() 之后:TTFT 只反映“真正发出请求 -> 收到首 token”
            # 的服务端耗时,不包含客户端等待 prefill 槽位的排队时间(与 benchmark_req.py 口径一致)。
            await output.record_time_point()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant