File size: 6,623 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""Track A steps 1 and 2: one spoken question in, one spoken answer out, through the
released inference path, with the single-stream numbers.

The released examples show two ways to open the assistant turn: "<think>\\n" (every
Step-Audio-R1 example, text out) and "<tts_start>" (every Step-Audio 2 speech example).
Which one makes R1.1 speak is not written down anywhere, so both are sent and the raw
stream of each is saved. Nothing is assumed about the result.

Saves to --out: question.wav, answer_<variant>.wav (when audio came back),
raw_<variant>_run<k>.jsonl (every streamed chunk with its arrival time), probe.json.

  python -m serving.probe_baseline --wav /src/Step-Audio2/assets/give_me_a_brief_introduction_to_the_great_wall.wav \
      --step-audio2-dir /src/Step-Audio2 --token2wav-dir /models/Step-Audio-2-mini/token2wav \
      --prompt-wav /src/Step-Audio2/assets/default_female.wav --out eval/results/probe
"""
import argparse
import asyncio
import json
import subprocess
import time
from pathlib import Path

import aiohttp
import numpy as np

from duplex.spec import OUT_SR, SR, read_wav, write_json, write_wav
from serving.baseline_client import human_turn, stream_chat
from serving.speech_out import NativeSpeechOut

VARIANTS = {"think": "<think>\n", "tts": "<tts_start>"}


def gpu_memory():
    """Per-GPU memory as nvidia-smi reports it (MiB). vLLM reserves a fixed share of the
    card up front, so 'used' is the reservation, not what the model strictly needs."""
    out = subprocess.run(["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv,noheader,nounits"],
                         capture_output=True, text=True, check=True).stdout
    rows = [[c.strip() for c in line.split(",")] for line in out.strip().splitlines()]
    return [{"gpu": int(r[0]), "name": r[1], "used_mib": int(r[2]), "total_mib": int(r[3])} for r in rows]


async def run_once(http, args, speech, pcm, prefix, raw_path):
    messages = [{"role": "system", "content": args.system}] if args.system else []
    messages += [human_turn(pcm), {"role": "assistant", "content": prefix, "eot": False}]
    st = speech.new_reply()
    t0 = time.perf_counter()
    m = {"first_chunk_s": None, "first_audio_token_s": None, "first_audio_s": None, "audio_tokens": 0}
    text, audio = "", bytearray()
    with open(raw_path, "w", encoding="utf-8") as raw:
        async for delta, t, tokens in stream_chat(http, args.api_url, args.model, messages, max_tokens=args.max_tokens,
                                                  temperature=args.temperature, top_p=args.top_p,
                                                  repetition_penalty=args.repetition_penalty, stop_token_ids=[151665]):
            now = time.perf_counter() - t0
            raw.write(json.dumps({"t": round(now, 4), "delta": delta}, ensure_ascii=False) + "\n")
            m["first_chunk_s"] = m["first_chunk_s"] or now
            text += t
            if tokens:
                m["first_audio_token_s"] = m["first_audio_token_s"] or now
                m["audio_tokens"] += len(tokens)
                for chunk in await speech.feed(st, tokens):
                    m["first_audio_s"] = m["first_audio_s"] or time.perf_counter() - t0
                    audio += chunk
        for chunk in await speech.finish(st):
            m["first_audio_s"] = m["first_audio_s"] or time.perf_counter() - t0
            audio += chunk
    m["total_s"] = time.perf_counter() - t0
    m["audio_s"] = len(audio) / 2 / OUT_SR
    m["real_time_factor"] = m["total_s"] / m["audio_s"] if m["audio_s"] else None    # below 1 is faster than real time
    m["text"] = text
    return m, bytes(audio)


async def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--api-url", default="http://localhost:9999/v1/chat/completions")
    ap.add_argument("--model", default="Step-Audio-R1.1")
    ap.add_argument("--wav", required=True, help="the spoken question, 16-bit PCM wav")
    ap.add_argument("--step-audio2-dir", required=True)
    ap.add_argument("--token2wav-dir", required=True)
    ap.add_argument("--prompt-wav", required=True, help="voice prompt for the released decoder")
    ap.add_argument("--out", default="eval/results/probe")
    ap.add_argument("--variants", default="think,tts")
    ap.add_argument("--runs", type=int, default=3, help="per variant; run 0 includes warm-up")
    ap.add_argument("--system", default="You are a helpful assistant.", help="as in the released multi-turn speech example")
    ap.add_argument("--max-tokens", type=int, default=2048)
    ap.add_argument("--temperature", type=float, default=0.7)
    ap.add_argument("--top-p", type=float, default=0.9)
    ap.add_argument("--repetition-penalty", type=float, default=1.05)
    args = ap.parse_args()

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    x, sr = read_wav(args.wav)
    x = x.mean(axis=1)
    if sr != SR:
        from scipy.signal import resample_poly
        x = resample_poly(x, SR, sr)
    pcm = (np.clip(x, -1, 1) * 32767).astype(np.int16)
    write_wav(out / "question.wav", pcm.astype(np.float32) / 32768, SR)

    report = {"question_s": len(pcm) / SR, "args": vars(args), "gpu_before": gpu_memory(), "variants": {}}
    speech = NativeSpeechOut(args.step_audio2_dir, args.token2wav_dir, args.prompt_wav)
    report["gpu_after_decoder_load"] = gpu_memory()
    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None)) as http:
        for name in args.variants.split(","):
            runs = []
            for k in range(args.runs):
                try:
                    m, audio = await run_once(http, args, speech, pcm, VARIANTS[name], out / f"raw_{name}_run{k}.jsonl")
                except Exception as e:                      # keep the evidence, move to the next variant
                    runs.append({"error": repr(e)})
                    break
                runs.append(m)
                if audio:
                    write_wav(out / f"answer_{name}.wav", np.frombuffer(audio, dtype="<i2").astype(np.float32) / 32768, OUT_SR)
                print(name, k, {key: m[key] for key in ("first_chunk_s", "first_audio_s", "total_s", "audio_s", "real_time_factor", "audio_tokens")})
            report["variants"][name] = runs
    report["gpu_after"] = gpu_memory()
    write_json(out / "probe.json", report)
    speaking = [n for n, runs in report["variants"].items() if any(r.get("audio_s") for r in runs)]
    print("variants that produced audio:", speaking or "NONE: the released path did not speak; stop and report")


if __name__ == "__main__":
    asyncio.run(main())