Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/test-example-collection.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ name: Validate example collection
on:
pull_request:
paths:
- "examples/qwen_audio_jev/classify_instrument.py"
- "tests/test_jev_example_output.py"
- "examples/mcp_server/**"
- "examples/openai_api/**"
- "examples/industrial_data_pretraining/fun_asr_nano/client_test.py"
Expand All @@ -14,6 +16,8 @@ on:
push:
branches: [main]
paths:
- "examples/qwen_audio_jev/classify_instrument.py"
- "tests/test_jev_example_output.py"
- "examples/mcp_server/**"
- "examples/openai_api/**"
- "examples/industrial_data_pretraining/fun_asr_nano/client_test.py"
Expand Down Expand Up @@ -48,6 +52,7 @@ jobs:
git rev-parse HEAD > source-commit.txt
python -m pip freeze > resolved-dependencies.txt
python -m pytest -q \
tests/test_jev_example_output.py \
tests/test_example_smoke_collection.py \
tests/test_streaming_client_collection.py \
tests/test_mcp_server_example.py \
Expand Down
3 changes: 2 additions & 1 deletion examples/qwen_audio_jev/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ The demo was exercised with the public Tiny revision above on one NVIDIA L20Z, P
- Call `generate(input=request, key="instrument-demo", jev_base_dir=...)` with a decision dictionary, not an audio URL. Resolve the example's relative audio paths against the official checkout's `examples/` directory. Accept only local audio the user authorized. Read `rows[0]["decision"]["answers"][question_id]`, not the ASR field `text`. A model answer is not authorization to act.
- Use `choice` for named alternatives, `noul` for a binary judgment and `score` for an ordered rubric. See the [task-specific fixtures](https://github.com/QwenAudio/Qwen-Audio-Jev/tree/d8b50fd5b5f68356b8e96b9e5b4386071ae21f39/examples); the outputs are not interchangeable confidence scores. Tiny alone supports step-by-step decisions on one file, every 160 ms. Set `pad_final_chunk=True` to accept an incomplete last step. This is not a microphone session.
- This `AutoModel` adapter processes a list in order with a fresh local worker per request. It is not a warm batched server; if a request raises, the list is not partially returned. Bound concurrency and track each request separately in an application. The ASR WebSocket and transcription endpoint do not serve this contract.
- All script arguments are filesystem paths. The output must be new and its parent writable. Preflight rejects a missing example/checkpoint path or an existing output with exit 2. A runner failure exits nonzero: do not consume the output. Set GPU visibility **before** starting Python; check snapshot completeness or address memory pressure before retrying. Do not automatically fetch weights or resubmit unchanged invalid inputs. Set a private `jev_work_dir` only for diagnosis; it may retain audio and worker logs.
- Write `decision.json` to a new path **outside the checkpoint**. Its directory must already exist, be writable, and support hard links (a local Linux filesystem works). An existing output, including a dangling symlink, or a path inside the checkpoint is rejected before inference with exit 2. A write failure such as a full disk does not publish a partial decision; another process's output is never replaced.
- A runner failure exits nonzero: do not consume the output. Set GPU visibility **before** starting Python; check snapshot completeness or address memory pressure before retrying. Do not automatically fetch weights or resubmit unchanged invalid inputs. Set a private `jev_work_dir` only for diagnosis; it may retain audio and worker logs.

<a id="jev-vllm"></a>

Expand Down
3 changes: 2 additions & 1 deletion examples/qwen_audio_jev/README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ python -c 'import json; r=json.load(open("decision.json")); print(r["decision"][
- `generate(input=request, key="instrument-demo", jev_base_dir=...)`:`request` 是字典而非音频 URL;示例中的 `audio` 是相对路径列表,基准是官方仓库的 `examples/`。只接受应用已获准读取的本地文件。用 `question_id` 取 `rows[0]["decision"]["answers"][question_id]`,不要读 ASR 的 `text`,也不要把模型答案当成操作授权。
- 多选用 `choice`,二元判断用 `noul`,有序量表用 `score`;各自的[请求示例](https://github.com/QwenAudio/Qwen-Audio-Jev/tree/d8b50fd5b5f68356b8e96b9e5b4386071ae21f39/examples)定义选项和输出,不共用一个“置信度阈值”。仅 Tiny 支持文件上的逐步判断:每步 160 毫秒,末段不足一步须显式选择补齐。这不是实时麦克风服务。
- 此 `AutoModel` 适配器对每个请求启动一个本地子进程;列表按顺序处理,不是常驻批量服务。生产应用应限制并发,并按请求保存成功或失败;列表中一项失败,不会返回之前各项的部分结果。不要把 Jev 配到语音转写 WebSocket 或 `/audio/transcriptions`。
- 脚本的参数都是路径;输出文件必须不存在,其父目录须可写。缺少文件或输出已存在时先改正路径,参数检查退出 2;运行时失败返回非零,不消费输出。遇到 CUDA 可见卡数量错误,请在启动 Python **前**只暴露一张卡;快照不全,请核查导出文件,不要由 Agent 自动下载。OOM 先释放自己占用的显存或缩短输入,同样参数不循环重试。需要排错时才设置私有 `jev_work_dir`,不要公开其中的音频、中间结果或日志。
- 把 `decision.json` 写到**权重目录之外**的新路径。父目录须已存在、可写并支持硬链接(一般的 Linux 本地文件系统即可)。如果输出已存在、是悬空符号链接,或位于权重目录内,脚本会在推理前以状态码 2 退出。磁盘写满等写入错误不会留下一份只有半截的判断结果,也不会覆盖其他进程已写好的文件。
- 运行时失败返回非零,不消费输出。遇到 CUDA 可见卡数量错误,请在启动 Python **前**只暴露一张卡;快照不全,请核查导出文件,不要由 Agent 自动下载。OOM 先释放自己占用的显存或缩短输入,同样参数不循环重试。需要排错时才设置私有 `jev_work_dir`,不要公开其中的音频、中间结果或日志。

<a id="jev-vllm"></a>

Expand Down
26 changes: 22 additions & 4 deletions examples/qwen_audio_jev/classify_instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,24 @@

import argparse
import json
import os
from pathlib import Path
import tempfile


def write_decision(output, row):
payload = json.dumps(row, ensure_ascii=False, allow_nan=False, indent=2) + "\n"
stage = tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=output.parent, delete=False)
temporary = Path(stage.name)
try:
with stage as out:
out.write(payload)
out.flush()
os.fsync(out.fileno())
# Link only the complete file, without replacing a concurrent result.
os.link(temporary, output)
finally:
temporary.unlink(missing_ok=True)


def main():
Expand All @@ -17,8 +34,11 @@ def main():
parser.error("Missing official examples/choice.json or examples/audios/choice.wav")
if not args.checkpoint.is_dir():
parser.error("--checkpoint must be a local directory, not a Hub ID")
if args.output.exists() or not args.output.parent.is_dir():
if args.output.exists() or args.output.is_symlink() or not args.output.parent.is_dir():
parser.error("--output must be a new file in an existing directory")
output = args.output.parent.resolve() / args.output.name
if args.checkpoint.resolve() in output.parents:
parser.error("--output must be outside the checkpoint directory")
request = json.loads(fixture.read_text(encoding="utf-8"))
if request["task"] != "choice" or request["audio"] != ["audios/choice.wav"]:
parser.error("Use the instrument-choice fixture from the documented Jev revision")
Expand All @@ -32,9 +52,7 @@ def main():
answer = row["decision"]["answers"][request["question_id"]]
if row["key"] != "instrument-demo" or answer["type"] != "choice" or answer["choice"] not in request["criteria"]:
raise ValueError("Unexpected instrument-choice response")
payload = json.dumps(row, ensure_ascii=False, allow_nan=False, indent=2)
with args.output.open("x", encoding="utf-8") as out:
out.write(payload + "\n")
write_decision(output, row)
print(f"Choice: {answer['choice']}")


Expand Down
76 changes: 76 additions & 0 deletions tests/test_jev_example_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Output handling of the Jev CLI example; model responses here are fixtures."""
import json
import os
from pathlib import Path
import subprocess
import sys

import pytest


SCRIPT = Path(__file__).resolve().parents[1] / "examples/qwen_audio_jev/classify_instrument.py"
STUB = '''
import os
from pathlib import Path

class AutoModel:
def __init__(self, **kwargs):
Path("constructed").touch()

def generate(self, input, key, **kwargs):
case = os.environ["OUTPUT_CASE"]
if case == "race":
Path("out/decision.json").write_text("other process")
if case == "full":
import resource
import signal
signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
resource.setrlimit(resource.RLIMIT_FSIZE, (64, 64))
return [{"key": key, "decision": {"answers": {
"instrument_family": {"type": "choice", "choice": "bass"}}}}]
'''


@pytest.mark.parametrize("case", ["ok", "checkpoint", "alias", "exists", "dangling", "race", "full"])
def test_cli_output(case, tmp_path):
if case == "full" and not sys.platform.startswith("linux"):
pytest.skip("Requires Linux file size limit semantics")
examples, checkpoint, out = (tmp_path / n for n in ("source/examples", "weights", "out"))
(examples / "audios").mkdir(parents=True)
checkpoint.mkdir()
out.mkdir()
(examples / "audios/choice.wav").touch()
fixture = {"task": "choice", "audio": ["audios/choice.wav"], "question_id": "instrument_family",
"criteria": ["bass", "guitar"]}
(examples / "choice.json").write_text(json.dumps(fixture))
(tmp_path / "funasr.py").write_text(STUB)
target = out / "decision.json"
if case == "checkpoint":
target = checkpoint / "decision.json"
elif case == "alias":
(tmp_path / "alias").symlink_to(checkpoint, target_is_directory=True)
target = tmp_path / "alias/decision.json"
elif case == "exists":
target.write_text("old result")
elif case == "dangling":
target.symlink_to(tmp_path / "missing")
env = dict(os.environ, PYTHONPATH=str(tmp_path), PYTHONDONTWRITEBYTECODE="1", OUTPUT_CASE=case)
proc = subprocess.run([sys.executable, str(SCRIPT), "--jev-source", str(examples.parent),
"--checkpoint", str(checkpoint), "--output", str(target)],
env=env, cwd=tmp_path, capture_output=True, text=True, timeout=10)
if case == "ok":
assert proc.returncode == 0 and proc.stdout.strip() == "Choice: bass"
assert json.loads(target.read_bytes())["decision"]["answers"]["instrument_family"]["choice"] == "bass"
elif case in ("checkpoint", "alias", "exists", "dangling"):
assert proc.returncode == 2 and not (tmp_path / "constructed").exists()
if case == "exists":
assert target.read_text() == "old result"
elif case == "dangling":
assert target.is_symlink() and not target.exists()
else:
assert not list(checkpoint.iterdir())
elif case == "race":
assert proc.returncode != 0 and target.read_text() == "other process"
else:
assert proc.returncode != 0 and not target.exists()
assert all(file == target for file in out.iterdir()), "a temporary output was left behind"
Loading