From c9ab29cfbabea1af94d8754358d71998345bcd30 Mon Sep 17 00:00:00 2001 From: Chandan Date: Tue, 1 Dec 2026 20:42:56 +0530 Subject: [PATCH 1/2] feat: prepare persistent BitWiser Qwen voice pilot and TTFT benchmarks --- .github/workflows/python-tests.yml | 18 ++ README.md | 8 + benchmark.py | 139 ++++++++++ benchmarks/voice_tools.json | 416 +++++++++++++++++++++++++++++ docs/qwen-stage-pilot.md | 112 ++++++++ serve.py | 60 +++++ setup.sh | 4 +- tests/test_pilot.py | 64 +++++ 8 files changed, 819 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/python-tests.yml create mode 100644 benchmark.py create mode 100644 benchmarks/voice_tools.json create mode 100644 docs/qwen-stage-pilot.md create mode 100644 serve.py create mode 100644 tests/test_pilot.py diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml new file mode 100644 index 0000000..e16e63b --- /dev/null +++ b/.github/workflows/python-tests.yml @@ -0,0 +1,18 @@ +name: Python unit tests (no GPU) +on: + pull_request: + push: + branches: [main] +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - run: python -m unittest discover -s tests -v + - run: python -m py_compile serve.py benchmark.py + - run: bash -n setup.sh diff --git a/README.md b/README.md index 1d6bd88..d1cca1d 100644 --- a/README.md +++ b/README.md @@ -148,3 +148,11 @@ The idea that large language models can be aggressively compressed down to rough That paper introduces **BitNet b1.58**, a Transformer variant whose weights are constrained to the ternary set {-1, 0, +1} (≈1.58 bits/weight) and still matches full-precision baselines on perplexity and downstream tasks while dramatically reducing memory, bandwidth, and energy. BitWiser is a practical, post-hoc analogue: instead of training a model in 1.58-bit form, it takes any already-trained GGUF and uses llama.cpp's **IQ1_S** (≈1.56 bits/weight, importance-matrix guided) quantization to hit a similar regime on a laptop. Quality is not preserved as well as in BitNet b1.58 — that's the price of compressing after the fact rather than training natively — but the speed and RAM wins translate directly. Credit for the underlying inference and quantization tooling goes to [ggml-org/llama.cpp](https://github.com/ggml-org/llama.cpp) and its contributors, particularly the authors of the IQ-quant family (Kawrakow et al.). + +## Persistent voice-agent pilot + +For client-observed TTFT and structured tool calls, see +[the Qwen3.5-4B stage pilot](docs/qwen-stage-pilot.md). `serve.py` keeps the model +resident using llama-server and its native tool-aware chat template; +`benchmark.py` measures streamed TTFT separately from completed tool calls. +The pilot is experimental; no sub-200 ms result has been established. diff --git a/benchmark.py b/benchmark.py new file mode 100644 index 0000000..a9f8e71 --- /dev/null +++ b/benchmark.py @@ -0,0 +1,139 @@ +"""Measure client-observed TTFT and completed tool calls against BitWiser. + +Cases contain full OpenAI messages/tools plus expected_tool or expect_no_tools. +Token rates do not substitute for TTFT. This runner never executes emitted tools. +""" +from __future__ import annotations + +import argparse +from concurrent.futures import ThreadPoolExecutor +import json +import math +from pathlib import Path +import time +from urllib.request import Request, urlopen + + +def consume_sse(lines, started, clock=time.perf_counter): + first_content = first_tool = tool_complete = None + content, calls, usage, timings = '', {}, {}, {} + finish = None + done = False + for raw in lines: + line = raw.decode() if isinstance(raw, bytes) else raw + if not line.startswith('data:'): + continue + data = line[5:].strip() + if data == '[DONE]': + done = True + break + item = json.loads(data) + if item.get('error'): + raise ValueError('Server returned a streaming error') + usage = item.get('usage') or usage + timings = item.get('timings') or timings + for choice in item.get('choices', []): + now = (clock() - started) * 1000 + delta = choice.get('delta', {}) + if delta.get('content'): + if first_content is None: + first_content = now + content += delta['content'] + for call in delta.get('tool_calls') or []: + fn = call.get('function') or {} + # Role-only and empty tool announcements are not first tokens. + if fn.get('name') or fn.get('arguments'): + if first_tool is None: + first_tool = now + current = calls.setdefault(call.get('index', 0), {'name': '', 'arguments': ''}) + current['name'] += fn.get('name', '') + current['arguments'] += fn.get('arguments', '') + if choice.get('finish_reason'): + finish = choice['finish_reason'] + if calls: + tool_complete = now + if not done or finish is None: + raise ValueError('Incomplete SSE response') + parsed = [] + for call in calls.values(): + parsed.append({'name': call['name'], 'arguments': json.loads(call['arguments'])}) + first = [x for x in (first_content, first_tool) if x is not None] + return {'ttft_ms': min(first) if first else None, 'first_content_ms': first_content, + 'first_tool_delta_ms': first_tool, 'tool_complete_ms': tool_complete, + 'total_ms': (clock() - started) * 1000, 'content': content, + 'tool_calls': parsed, 'finish_reason': finish, 'usage': usage, 'timings': timings} + + +def check_expectation(case, result): + if result['finish_reason'] == 'length': + return False + if case.get('expected_tool') is not None: + return result['tool_calls'] == [case['expected_tool']] + if case.get('expect_no_tools'): + return not result['tool_calls'] and bool(result['content'].strip()) + return None # Do not silently call unchecked output a quality pass. + + +def run_case(case, base_url, model, key, cache_prompt, timeout): + payload = {'model': model, 'temperature': 0, 'max_tokens': 256, + 'messages': case['messages'], 'tools': case.get('tools', []), + 'stream': True, 'stream_options': {'include_usage': True}, + 'cache_prompt': cache_prompt, 'chat_template_kwargs': {'enable_thinking': False}} + headers = {'Content-Type': 'application/json'} + if key: + headers['Authorization'] = 'Bearer ' + key + request = Request(base_url.rstrip('/') + '/chat/completions', + data=json.dumps(payload).encode(), headers=headers) + started = time.perf_counter() + try: + with urlopen(request, timeout=timeout) as response: + result = consume_sse(response, started) + result.update(case_id=case['id'], passed=check_expectation(case, result)) + return result + except Exception as exc: + # Never record request headers/credentials or full HTTP error bodies. + return {'case_id': case['id'], 'passed': False, 'error_type': type(exc).__name__} + + +def percentile(values, p): + values = sorted(x for x in values if x is not None) + return values[max(0, math.ceil(len(values) * p) - 1)] if values else None + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--base-url', default='http://127.0.0.1:8080/v1') + p.add_argument('--model', default='bitwiser-qwen35-4b') + p.add_argument('--api-key-file', type=Path) + p.add_argument('--cases', type=Path, required=True) + p.add_argument('--output', type=Path, required=True) + p.add_argument('--repeats', type=int, default=1) + p.add_argument('--concurrency', type=int, default=1) + p.add_argument('--cache-prompt', action='store_true', help='Allow server prompt reuse; report separately from cold runs') + p.add_argument('--timeout', type=float, default=60) + args = p.parse_args() + if args.repeats < 1 or args.concurrency < 1: + p.error('repeats and concurrency must be positive') + cases = json.loads(args.cases.read_text()) + key = args.api_key_file.read_text().strip() if args.api_key_file else None + work = cases * args.repeats + with ThreadPoolExecutor(max_workers=args.concurrency) as pool: + results = list(pool.map(lambda case: run_case(case, args.base_url, args.model, key, + args.cache_prompt, args.timeout), work)) + measured = [r for r in results if 'ttft_ms' in r and r['ttft_ms'] is not None] + summary = {'requests': len(results), 'completed_with_tokens': len(measured), + 'checks_passed': sum(r['passed'] is True for r in results), + 'checks_failed': sum(r['passed'] is False for r in results), + 'unchecked': sum(r['passed'] is None for r in results), + 'concurrency': args.concurrency, 'cache_prompt': args.cache_prompt, + 'ttft_p50_ms': percentile([r['ttft_ms'] for r in measured], .50), + 'ttft_p95_ms': percentile([r['ttft_ms'] for r in measured], .95), + 'tool_complete_p95_ms': percentile([r.get('tool_complete_ms') for r in results], .95), + 'requests_under_200ms': sum(r['ttft_ms'] < 200 for r in measured)} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps({'summary': summary, 'results': results}, indent=2)) + print(json.dumps(summary, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/benchmarks/voice_tools.json b/benchmarks/voice_tools.json new file mode 100644 index 0000000..b8bc8bf --- /dev/null +++ b/benchmarks/voice_tools.json @@ -0,0 +1,416 @@ +[ + { + "id": "synthetic-1", + "messages": [ + { + "role": "system", + "content": "You are a concise hotel booking assistant on a phone call. Speak Hindi or English to match the caller. Use check_availability only after the city and both dates are known. Dates are ISO YYYY-MM-DD. Do not invent dates, availability or prices. For a human agent request use transfer_to_human with reason customer_request. Never claim a booking was made. Ask for missing information without calling a tool." + }, + { + "role": "user", + "content": "Check Delhi rooms from 2026-12-10 to 2026-12-12." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "check_availability", + "description": "Check hotel room availability for a city and stay dates.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "check_in": { + "type": "string" + }, + "check_out": { + "type": "string" + } + }, + "required": [ + "city", + "check_in", + "check_out" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "transfer_to_human", + "description": "Transfer the caller to a human agent on request.", + "parameters": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "enum": [ + "customer_request" + ] + } + }, + "required": [ + "reason" + ], + "additionalProperties": false + } + } + } + ], + "expected_tool": { + "name": "check_availability", + "arguments": { + "city": "Delhi", + "check_in": "2026-12-10", + "check_out": "2026-12-12" + } + } + }, + { + "id": "synthetic-2", + "messages": [ + { + "role": "system", + "content": "You are a concise hotel booking assistant on a phone call. Speak Hindi or English to match the caller. Use check_availability only after the city and both dates are known. Dates are ISO YYYY-MM-DD. Do not invent dates, availability or prices. For a human agent request use transfer_to_human with reason customer_request. Never claim a booking was made. Ask for missing information without calling a tool." + }, + { + "role": "user", + "content": "Mujhe Jaipur mein 2026-12-15 se 2026-12-17 tak room chahiye." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "check_availability", + "description": "Check hotel room availability for a city and stay dates.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "check_in": { + "type": "string" + }, + "check_out": { + "type": "string" + } + }, + "required": [ + "city", + "check_in", + "check_out" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "transfer_to_human", + "description": "Transfer the caller to a human agent on request.", + "parameters": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "enum": [ + "customer_request" + ] + } + }, + "required": [ + "reason" + ], + "additionalProperties": false + } + } + } + ], + "expected_tool": { + "name": "check_availability", + "arguments": { + "city": "Jaipur", + "check_in": "2026-12-15", + "check_out": "2026-12-17" + } + } + }, + { + "id": "synthetic-3", + "messages": [ + { + "role": "system", + "content": "You are a concise hotel booking assistant on a phone call. Speak Hindi or English to match the caller. Use check_availability only after the city and both dates are known. Dates are ISO YYYY-MM-DD. Do not invent dates, availability or prices. For a human agent request use transfer_to_human with reason customer_request. Never claim a booking was made. Ask for missing information without calling a tool." + }, + { + "role": "user", + "content": "Please connect me to a human agent." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "check_availability", + "description": "Check hotel room availability for a city and stay dates.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "check_in": { + "type": "string" + }, + "check_out": { + "type": "string" + } + }, + "required": [ + "city", + "check_in", + "check_out" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "transfer_to_human", + "description": "Transfer the caller to a human agent on request.", + "parameters": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "enum": [ + "customer_request" + ] + } + }, + "required": [ + "reason" + ], + "additionalProperties": false + } + } + } + ], + "expected_tool": { + "name": "transfer_to_human", + "arguments": { + "reason": "customer_request" + } + } + }, + { + "id": "synthetic-4", + "messages": [ + { + "role": "system", + "content": "You are a concise hotel booking assistant on a phone call. Speak Hindi or English to match the caller. Use check_availability only after the city and both dates are known. Dates are ISO YYYY-MM-DD. Do not invent dates, availability or prices. For a human agent request use transfer_to_human with reason customer_request. Never claim a booking was made. Ask for missing information without calling a tool." + }, + { + "role": "user", + "content": "Mujhe kisi insaan se baat karni hai." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "check_availability", + "description": "Check hotel room availability for a city and stay dates.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "check_in": { + "type": "string" + }, + "check_out": { + "type": "string" + } + }, + "required": [ + "city", + "check_in", + "check_out" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "transfer_to_human", + "description": "Transfer the caller to a human agent on request.", + "parameters": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "enum": [ + "customer_request" + ] + } + }, + "required": [ + "reason" + ], + "additionalProperties": false + } + } + } + ], + "expected_tool": { + "name": "transfer_to_human", + "arguments": { + "reason": "customer_request" + } + } + }, + { + "id": "synthetic-5", + "messages": [ + { + "role": "system", + "content": "You are a concise hotel booking assistant on a phone call. Speak Hindi or English to match the caller. Use check_availability only after the city and both dates are known. Dates are ISO YYYY-MM-DD. Do not invent dates, availability or prices. For a human agent request use transfer_to_human with reason customer_request. Never claim a booking was made. Ask for missing information without calling a tool." + }, + { + "role": "user", + "content": "I need a room in Delhi but have not decided the dates." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "check_availability", + "description": "Check hotel room availability for a city and stay dates.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "check_in": { + "type": "string" + }, + "check_out": { + "type": "string" + } + }, + "required": [ + "city", + "check_in", + "check_out" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "transfer_to_human", + "description": "Transfer the caller to a human agent on request.", + "parameters": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "enum": [ + "customer_request" + ] + } + }, + "required": [ + "reason" + ], + "additionalProperties": false + } + } + } + ], + "expect_no_tools": true + }, + { + "id": "synthetic-6", + "messages": [ + { + "role": "system", + "content": "You are a concise hotel booking assistant on a phone call. Speak Hindi or English to match the caller. Use check_availability only after the city and both dates are known. Dates are ISO YYYY-MM-DD. Do not invent dates, availability or prices. For a human agent request use transfer_to_human with reason customer_request. Never claim a booking was made. Ask for missing information without calling a tool." + }, + { + "role": "user", + "content": "Hello!" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "check_availability", + "description": "Check hotel room availability for a city and stay dates.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + }, + "check_in": { + "type": "string" + }, + "check_out": { + "type": "string" + } + }, + "required": [ + "city", + "check_in", + "check_out" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "transfer_to_human", + "description": "Transfer the caller to a human agent on request.", + "parameters": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "enum": [ + "customer_request" + ] + } + }, + "required": [ + "reason" + ], + "additionalProperties": false + } + } + } + ], + "expect_no_tools": true + } +] \ No newline at end of file diff --git a/docs/qwen-stage-pilot.md b/docs/qwen-stage-pilot.md new file mode 100644 index 0000000..125cb0c --- /dev/null +++ b/docs/qwen-stage-pilot.md @@ -0,0 +1,112 @@ +# Qwen3.5-4B voice pilot through BitWiser + +This path uses BitWiser's existing scanner/compressor and pinned llama.cpp. It +adds a resident OpenAI-compatible server instead of starting `llama-completion` +for each turn. The playground remains useful for comparing compression, but its +decode tokens/sec is not a measurement of client-observed TTFT. + +## Build and prepare + +On a dedicated CUDA host, run `BACKEND=cuda JOBS=2 ./setup.sh`. This now also builds +`llama-server`. Keep the pilot separate from production voice workers. + +For this pilot, use the text-decoder GGUF from +https://huggingface.co/unsloth/Qwen3.5-4B-GGUF, pinned to revision +`e87f176479d0855a907a41277aca2f8ee7a09523`. This is a third-party conversion of +Qwen's weights. Download `Qwen3.5-4B-BF16.gguf` into `~/Models/`. Do not load an +`mmproj` file: this is a text LLM behind the existing STT/TTS pipeline. + +Use BitWiser itself to prepare the Q4 baseline from the BF16 source: + +```bash +.venv/bin/python scanner.py +.venv/bin/python compressor.py Qwen3.5-4B-BF16.gguf --target Q4_K_M +``` + +Then, separately, prepare the 1-bit candidate from the same original source: + +```bash +.venv/bin/python compressor.py Qwen3.5-4B-BF16.gguf --target IQ1_S +``` + +IQ1_S invokes BitWiser's importance-matrix calibration. This has NOT yet been +validated for this model on the stage GPU. If the scanner or pinned runtime +rejects the model, stop and retain the error; do not remove the multimodal guard +or silently switch to another model. The checked-in generic calibration corpus +is only a baseline, not evidence of hotel/booking tool accuracy. A later +calibration corpus needs approved domain examples and a disjoint evaluation set. + +## Serve continuously + +```bash +.venv/bin/python serve.py \ + --model compressed/Qwen3.5-4B-BF16.Q4_K_M.gguf \ + --slots 1 --context-per-slot 8192 +``` + +This binds localhost by default. For the private stage endpoint, set `--host` to +the private interface address and provide `--api-key-file /path/to/private/key`. +The key value is not passed on the command line. The security group must allow +port 8080 only from the stage voice worker; do not expose inference publicly. +The GPU instance needs working outbound access to fetch model/build dependencies. + +The native model Jinja template receives messages, tool definitions and tool +results. Thinking is disabled. Clients use `/v1/chat/completions` with model alias +`bitwiser-qwen35-4b`. No prompt rewriting or per-turn model subprocess is involved. +Run the server under systemd when testing sustained concurrency. Reserve enough +GPU memory for the model, all slots, attention/KV state, and runtime workspaces. +The default is only an initial 8K-context pilot, not a production context limit. + +## Measure honestly + +```bash +.venv/bin/python benchmark.py \ + --cases benchmarks/voice_tools.json \ + --repeats 20 --concurrency 1 --output /tmp/qwen-cold.json + +.venv/bin/python benchmark.py \ + --cases benchmarks/voice_tools.json --cache-prompt \ + --repeats 20 --concurrency 1 --output /tmp/qwen-reuse.json +``` + +The checked-in cases are **synthetic** Hindi/English tool-contract examples, not +OSVI production logs. They do not measure conversational quality. Pass a private +JSON file with approved real messages and tool schemas for the representative +replay; do not commit customer conversations. `expected_tool` verifies the exact +function and arguments, and `expect_no_tools` verifies that the response contains +text without a tool call. Results without an expectation are explicitly unchecked. +No returned tool is executed by the benchmark. + +Measure from the stage voice worker (or an equivalent caller on its network), not +only localhost. Separate cold-prefix and reuse runs, first-call and subsequent +turns, and run at realistic concurrency. Repeated identical synthetic requests +can exaggerate cache reuse. Long prompts must fit the configured context; never +truncate them silently to achieve the latency target. Record input/cache tokens +and server timings where returned. The first request includes server warm-up. + +Metrics: first actual content/tool fragment (not a role-only SSE event), first +spoken-text content, completion of tool-call generation, total request time, +structural tool checks, and errors. A tool fragment cannot be executed yet. +Errors and incomplete streams remain failures, not zero-latency successes. + +Promotion requires representative p95 TTFT below 200 ms at the required +concurrency, acceptable no-tool and tool behavior, and human assessment of +Hindi/Hinglish responses. Do not equate perplexity, decode throughput or valid +JSON with correct business actions. A short synthetic pass is not approval to +replace production DeepSeek. + +## Current execution status (2026-12-01) + +AWS permitted the launch dry run. Actual Mumbai launches returned +`InsufficientInstanceCapacity` for G6.2xlarge in 1a/1b, G5.2xlarge in 1a/1b, +G6e.xlarge in 1a/1b, and G6.xlarge in 1b. Temporary security groups were removed; +no GPU was launched. There are no Qwen inference/TTFT measurements yet. +The planned temporary host has a four-hour automatic stop timer; stopped disks +still incur storage charges and should be removed after the pilot. + +The requested Hyderabad fallback (`ap-south-2`) is `not-opted-in` on the AWS +account. Enabling it was denied because the current identity lacks +`account:EnableRegion`. An account administrator must enable that region before +its GPU offerings, quotas, capacity, and network can be checked. Nothing has +been provisioned there. A Hyderabad run must include a Mumbai-origin caller so +its TTFT includes the additional network trip. diff --git a/serve.py b/serve.py new file mode 100644 index 0000000..3bf3c2c --- /dev/null +++ b/serve.py @@ -0,0 +1,60 @@ +"""Persistent BitWiser OpenAI-compatible inference using the pinned llama.cpp. + +Uses the GGUF's native Jinja chat template, including tool definitions and results. +Unlike the side-by-side playground, model weights and server slots stay resident. +""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +SERVER_BIN = ROOT / 'vendor/llama.cpp/build/bin/llama-server' + + +def command(model: Path, *, host: str = '127.0.0.1', port: int = 8080, + slots: int = 1, context_per_slot: int = 8192, + api_key_file: Path | None = None) -> list[str]: + if slots < 1 or context_per_slot < 512: + raise ValueError('slots must be positive and context per slot at least 512') + if not model.is_file(): + raise ValueError(f'Model file not found: {model}') + if host not in ('127.0.0.1', 'localhost', '::1') and api_key_file is None: + raise ValueError('A non-loopback listener requires --api-key-file') + if api_key_file is not None: + keys = api_key_file.read_text().splitlines() if api_key_file.is_file() else [] + if not any(line.strip() and not line.lstrip().startswith('#') for line in keys): + raise ValueError('API key file must contain a key, not only comments') + args = [str(SERVER_BIN), '-m', str(model.resolve()), '--alias', 'bitwiser-qwen35-4b', + '--host', host, '--port', str(port), '-ngl', '99', + '-c', str(context_per_slot * slots), '-np', str(slots), + '--jinja', '--chat-template-kwargs', json.dumps({'enable_thinking': False}), + '--reasoning-budget', '0', '--flash-attn', 'on'] + if api_key_file: + args += ['--api-key-file', str(api_key_file.resolve())] + return args + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--model', type=Path, required=True) + parser.add_argument('--host', default='127.0.0.1') + parser.add_argument('--port', type=int, default=8080) + parser.add_argument('--slots', type=int, default=1) + parser.add_argument('--context-per-slot', type=int, default=8192) + parser.add_argument('--api-key-file', type=Path) + args = parser.parse_args() + if not SERVER_BIN.is_file(): + parser.error('llama-server is missing; run ./setup.sh first') + try: + cmd = command(args.model, host=args.host, port=args.port, slots=args.slots, + context_per_slot=args.context_per_slot, api_key_file=args.api_key_file) + except ValueError as exc: + parser.error(str(exc)) + os.execv(cmd[0], cmd) + + +if __name__ == '__main__': + main() diff --git a/setup.sh b/setup.sh index 51da750..d2ac0b9 100755 --- a/setup.sh +++ b/setup.sh @@ -94,7 +94,7 @@ echo "$CONFIG" > "$STAMP" echo "==> Building (Release, $JOBS jobs)" cmake --build "$BUILD" --config Release -j "$JOBS" \ - --target llama-quantize llama-imatrix llama-completion + --target llama-quantize llama-imatrix llama-completion llama-server echo "==> Installing Python deps into .venv" python3 -m venv "$ROOT/.venv" @@ -103,4 +103,4 @@ python3 -m venv "$ROOT/.venv" echo echo "Done ($BACKEND). Binaries:" -ls "$BUILD/bin" | grep -E '^(llama-quantize|llama-imatrix|llama-completion)$' || true +ls "$BUILD/bin" | grep -E '^(llama-quantize|llama-imatrix|llama-completion|llama-server)$' || true diff --git a/tests/test_pilot.py b/tests/test_pilot.py new file mode 100644 index 0000000..152f707 --- /dev/null +++ b/tests/test_pilot.py @@ -0,0 +1,64 @@ +import json +from pathlib import Path +import tempfile +import unittest +from benchmark import consume_sse, check_expectation, percentile +from serve import command + + +def event(delta=None, finish=None): + return 'data: '+json.dumps({'choices':[{'delta': delta or {}, 'finish_reason':finish}]})+'\n' + + +class StreamMetricsTest(unittest.TestCase): + def test_role_chunk_is_not_ttft_and_tool_fragments_are_assembled(self): + times=iter([10.01,10.05,10.08,10.10,10.12]) + result=consume_sse([ + event({'role':'assistant'}), + event({'tool_calls':[{'index':0,'function':{'name':'lookup','arguments':'{"city":'}}]}), + event({'tool_calls':[{'index':0,'function':{'arguments':'"Delhi"}'}}]}), + event(finish='tool_calls'), 'data: [DONE]\n', + ],10,clock=lambda:next(times)) + self.assertAlmostEqual(result['ttft_ms'],50) + self.assertIsNone(result['first_content_ms']) + self.assertAlmostEqual(result['tool_complete_ms'],100) + self.assertTrue(check_expectation({'expected_tool':{'name':'lookup','arguments':{'city':'Delhi'}}},result)) + self.assertFalse(check_expectation({'expected_tool':{'name':'lookup','arguments':{'city':'Mumbai'}}},result)) + + def test_dropped_stream_and_invalid_json_fail(self): + with self.assertRaises(ValueError): + consume_sse([event({'content':'partial'})],0,clock=lambda:1) + with self.assertRaises(ValueError): + consume_sse([event({'tool_calls':[{'index':0,'function':{'name':'lookup','arguments':'{'}}]},'tool_calls'),'data: [DONE]'],0,clock=lambda:1) + + def test_unchecked_text_and_truncation_do_not_pass(self): + result={'finish_reason':'stop','tool_calls':[],'content':'Hello'} + self.assertIsNone(check_expectation({},result)) + self.assertTrue(check_expectation({'expect_no_tools':True},result)) + result['finish_reason']='length' + self.assertFalse(check_expectation({'expect_no_tools':True},result)) + + def test_empty_percentile_is_not_reported_as_fast(self): + self.assertIsNone(percentile([None],.95)) + self.assertEqual(percentile([100,200,None],.95),200) + + +class ServingSafetyTest(unittest.TestCase): + def test_external_binding_requires_key_file(self): + with tempfile.TemporaryDirectory() as d: + model=Path(d)/'model.gguf';model.write_bytes(b'GGUF') + with self.assertRaises(ValueError): + command(model,host='0.0.0.0') + key=Path(d)/'api-key';key.write_text('# only a comment\n') + with self.assertRaises(ValueError): + command(model,host='0.0.0.0',api_key_file=key) + key.write_text('test-only-key') + args=command(model,host='0.0.0.0',api_key_file=key) + self.assertNotIn('test-only-key',args) + self.assertIn('--api-key-file',args) + self.assertIn('--jinja',args) + self.assertIn('{"enable_thinking": false}',args) + + +if __name__=='__main__': + unittest.main() From 9a6d2bf2143ca0fcd27eccc9574f073ede425dd4 Mon Sep 17 00:00:00 2001 From: Chandan Date: Tue, 1 Dec 2026 22:16:50 +0530 Subject: [PATCH 2/2] feat: add local BitWiser Q4 and IQ1 comparison pilot --- .github/workflows/python-tests.yml | 4 +- .gitignore | 4 + README.md | 11 +++ benchmark.py | 4 +- docs/local-pilot.md | 77 ++++++++++++++++++++ docs/qwen-stage-pilot.md | 3 +- local_pilot.py | 66 +++++++++++++++++ local_playground.py | 107 +++++++++++++++++++++++++++ server.py | 2 + start-local.command | 4 + stop-local.command | 22 ++++++ web/src/App.tsx | 11 ++- web/src/components/LocalPilot.tsx | 113 +++++++++++++++++++++++++++++ 13 files changed, 423 insertions(+), 5 deletions(-) create mode 100644 docs/local-pilot.md create mode 100644 local_pilot.py create mode 100644 local_playground.py create mode 100755 start-local.command create mode 100755 stop-local.command create mode 100644 web/src/components/LocalPilot.tsx diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index e16e63b..1e79c57 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -14,5 +14,5 @@ jobs: with: python-version: '3.11' - run: python -m unittest discover -s tests -v - - run: python -m py_compile serve.py benchmark.py - - run: bash -n setup.sh + - run: python -m py_compile serve.py benchmark.py local_pilot.py local_playground.py server.py + - run: bash -n setup.sh start-local.command stop-local.command diff --git a/.gitignore b/.gitignore index 2d74cac..450ed79 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,7 @@ compressed/ # Notes (not for repo) implementation.md implementation.txt + +.local-pilot/ + +web/*.tsbuildinfo diff --git a/README.md b/README.md index d1cca1d..64b701e 100644 --- a/README.md +++ b/README.md @@ -156,3 +156,14 @@ For client-observed TTFT and structured tool calls, see resident using llama-server and its native tool-aware chat template; `benchmark.py` measures streamed TTFT separately from completed tool calls. The pilot is experimental; no sub-200 ms result has been established. + +For the local 4-bit / 1-bit comparison UI, follow +[the local setup guide](docs/local-pilot.md). After preparing both artifacts, +run `./start-local.command` and open http://127.0.0.1:8000. You can edit prompts, +inspect tool calls, and compare sequential runs with prompt caching enabled or +disabled. Tools are displayed only and never executed. + +Initial Apple M5 smoke tests passed the Q4 tool checks, but IQ1 produced invalid +or empty answers and failed every required tool call. Neither these synthetic +tests nor compression alone establish production suitability. Cloud rollout is +deferred until local evaluation is complete. diff --git a/benchmark.py b/benchmark.py index a9f8e71..a1e1955 100644 --- a/benchmark.py +++ b/benchmark.py @@ -14,7 +14,7 @@ from urllib.request import Request, urlopen -def consume_sse(lines, started, clock=time.perf_counter): +def consume_sse(lines, started, clock=time.perf_counter, on_delta=None): first_content = first_tool = tool_complete = None content, calls, usage, timings = '', {}, {}, {} finish = None @@ -48,6 +48,8 @@ def consume_sse(lines, started, clock=time.perf_counter): current = calls.setdefault(call.get('index', 0), {'name': '', 'arguments': ''}) current['name'] += fn.get('name', '') current['arguments'] += fn.get('arguments', '') + if on_delta is not None: + on_delta(delta) if choice.get('finish_reason'): finish = choice['finish_reason'] if calls: diff --git a/docs/local-pilot.md b/docs/local-pilot.md new file mode 100644 index 0000000..4f752af --- /dev/null +++ b/docs/local-pilot.md @@ -0,0 +1,77 @@ +# Local Qwen3.5-4B: 4-bit and 1-bit + +The local pilot uses BitWiser and Metal on Apple Silicon. It serves both +quantized text models on loopback; no AWS service or real hotel tool is called. + +## Prepare once + +```bash +./setup.sh +cd web && npm ci && npm run build && cd .. +``` + +Download `Qwen3.5-4B-BF16.gguf` from the pinned conversion revision documented in +[qwen-stage-pilot.md](qwen-stage-pilot.md) into `~/Models/`. The source's SHA-256 is +`9e6e2841a75f503ccb330831832fd7861266e187e0dbf149a954219ccb8c197a`. +This GGUF contains the text decoder; its separate mmproj is not needed. + +Create **both** variants from BF16 using BitWiser, not by requantizing Q4: + +```bash +.venv/bin/python compressor.py Qwen3.5-4B-BF16.gguf --target Q4_K_M +.venv/bin/python compressor.py Qwen3.5-4B-BF16.gguf --target IQ1_S +``` + +## Start + +```bash +.venv/bin/python local_pilot.py +``` + +On macOS you can also double-click `start-local.command`; use `stop-local.command` +to stop the owned launcher and release both models. + +Open http://127.0.0.1:8000. The comparison tab offers separate runs or sequential +runs of both models, an editable system prompt, example tool requests, and a +prompt-cache toggle. Each run starts a fresh conversation. The two optional +hotel tools are exposed to the models but **never executed**. The output shows +structured function names/arguments for inspection. + +Both models remain resident. Q4 listens on `127.0.0.1:8081` and IQ1 on +`127.0.0.1:8082`; both expose `/v1/chat/completions`. The model alias is +`bitwiser-qwen35-4b`. Ctrl+C in the launcher stops all three processes. Logs are +in `.local-pilot/`. The launcher refuses occupied ports instead of killing an +unrelated process. Keep a single launcher running. + +TTFT is measured by the local API bridge from request send to the first actual +text or tool fragment. The role-only SSE event is ignored. Time to a complete +tool call is separate. This does not include speech recognition or synthesis, +and is not an AWS or production voice-worker benchmark. Use sequential runs +for comparison; concurrent runs share the Mac's GPU. Repeated prompts can +reuse cache, so also test with the cache toggle disabled and realistic long +prompts. The resident servers each have an 8192-token context for this pilot. + +For reproducible structural tool tests, run `benchmark.py` against ports 8081 +and 8082 using `benchmarks/voice_tools.json`. Those cases are synthetic, not +customer logs. Valid tool JSON is only one part of quality validation: manually +check the chosen tool, values, missing-information behavior, and Hindi/Hinglish. +IQ1_S is a mixed tensor quantization scheme; the actual file's effective bits +per weight are not necessarily exactly one. + +## Initial local validation (2026-12-01) + +Apple M5, 24 GB unified memory, Metal; both models resident, sequential requests. +BF16 source checksum verified; generated Q4_K_M is 2.71 GB and IQ1_S is 1.36 GB. +The checked-in calibration corpus produced five 512-token chunks for the IQ1 +importance matrix. No domain-specific calibration or fine-tuning was applied. + +Six synthetic cases were run without prompt caching, then the same six cases +twice with caching enabled. Q4 passed every exact tool/structural check in both +runs. IQ1 failed every tool-required case, including empty and repetitive output. +Its no-tool structural passes are not evidence of useful answers: manual review +found degraded text there too. Do not use this IQ1 artifact for production agents. + +This setup did not consistently reach 200 ms TTFT. Cache-enabled repeated prompts +are only a controlled smoke test, not a production cache-hit-rate or latency SLA. +The compression/UI work is functional; these results do not approve a cloud or +production rollout. diff --git a/docs/qwen-stage-pilot.md b/docs/qwen-stage-pilot.md index 125cb0c..c5ead34 100644 --- a/docs/qwen-stage-pilot.md +++ b/docs/qwen-stage-pilot.md @@ -100,7 +100,8 @@ replace production DeepSeek. AWS permitted the launch dry run. Actual Mumbai launches returned `InsufficientInstanceCapacity` for G6.2xlarge in 1a/1b, G5.2xlarge in 1a/1b, G6e.xlarge in 1a/1b, and G6.xlarge in 1b. Temporary security groups were removed; -no GPU was launched. There are no Qwen inference/TTFT measurements yet. +no GPU was launched. Local Apple M5 measurements are now documented in [local-pilot.md](local-pilot.md); +there are still no AWS inference/TTFT measurements. The planned temporary host has a four-hour automatic stop timer; stopped disks still incur storage charges and should be removed after the pilot. diff --git a/local_pilot.py b/local_pilot.py new file mode 100644 index 0000000..689059a --- /dev/null +++ b/local_pilot.py @@ -0,0 +1,66 @@ +"""Start the local BitWiser web app and both resident Qwen models. Ctrl+C stops all.""" +from pathlib import Path +import signal +import os +import socket +import subprocess +import sys +import time +from urllib.request import urlopen + +ROOT = Path(__file__).resolve().parent + +def main(): + models = [('q4', 8081, ROOT/'compressed/Qwen3.5-4B-BF16.Q4_K_M.gguf'), + ('iq1', 8082, ROOT/'compressed/Qwen3.5-4B-BF16.IQ1_S.gguf')] + for _, _, path in models: + if not path.is_file(): + raise SystemExit(f'Missing model: {path}. See docs/local-pilot.md.') + if not (ROOT/'web/dist/index.html').is_file(): + raise SystemExit('Build the UI first: cd web && npm ci && npm run build') + for port in (8000, 8081, 8082): + with socket.socket() as sock: + if sock.connect_ex(('127.0.0.1', port)) == 0: + raise SystemExit(f'Port {port} is already in use; stop the previous local pilot first.') + logdir = ROOT/'.local-pilot';logdir.mkdir(exist_ok=True) + pidfile = logdir/'launcher.pid' + pidfile.write_text(str(os.getpid())) + children, logs = [], [] + def stop(*_): + raise KeyboardInterrupt + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + try: + for name, port, path in models: + log = (logdir/f'{name}.log').open('a');logs.append(log) + proc = subprocess.Popen([sys.executable, str(ROOT/'serve.py'), '--model', str(path), + '--port', str(port), '--slots', '1', '--context-per-slot', '8192'], + cwd=ROOT, stdout=log, stderr=subprocess.STDOUT) + children.append(proc) + for _ in range(120): + if proc.poll() is not None: + raise RuntimeError(f'{name} server exited; see {logdir/name}.log') + try: + with urlopen(f'http://127.0.0.1:{port}/health', timeout=1) as r: + if r.status == 200:break + except Exception:pass + time.sleep(1) + else:raise RuntimeError(f'{name} server did not become ready; see its log') + log = (logdir/'web.log').open('a');logs.append(log) + children.append(subprocess.Popen([sys.executable, str(ROOT/'server.py')], cwd=ROOT, + stdout=log, stderr=subprocess.STDOUT)) + print('BitWiser local pilot: http://127.0.0.1:8000 — Ctrl+C to stop all servers', flush=True) + while all(p.poll() is None for p in children): + time.sleep(1) + except KeyboardInterrupt: + pass + finally: + for proc in children: + if proc.poll() is None:proc.terminate() + for proc in children: + try:proc.wait(timeout=10) + except subprocess.TimeoutExpired:proc.kill();proc.wait() + for log in logs:log.close() + pidfile.unlink(missing_ok=True) + +if __name__ == '__main__':main() diff --git a/local_playground.py b/local_playground.py new file mode 100644 index 0000000..99f3e72 --- /dev/null +++ b/local_playground.py @@ -0,0 +1,107 @@ +"""Loopback-only UI bridge for the resident 4-bit and 1-bit pilot servers.""" +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +import queue +import threading +import time +from typing import Literal +from urllib.request import Request, urlopen + +from fastapi import APIRouter, HTTPException +from fastapi.responses import StreamingResponse +from pydantic import BaseModel, Field +from benchmark import consume_sse + +ROOT = Path(__file__).resolve().parent +SERVERS = {'q4': 'http://127.0.0.1:8081', 'iq1': 'http://127.0.0.1:8082'} +EXAMPLE = json.loads((ROOT / 'benchmarks/voice_tools.json').read_text())[0] +router = APIRouter(prefix='/api/local-pilot') + + +def health(name): + try: + with urlopen(SERVERS[name] + '/health', timeout=2) as r: + return r.status == 200 + except Exception: + return False + + +@router.get('/status') +async def status(): + ready = await asyncio.gather(*(asyncio.to_thread(health, name) for name in SERVERS)) + return {'models': dict(zip(SERVERS, ready)), 'system_prompt': EXAMPLE['messages'][0]['content'], + 'tool_names': [t['function']['name'] for t in EXAMPLE['tools']]} + + +class ChatMessage(BaseModel): + role: Literal['user', 'assistant'] + content: str = Field(max_length=30000) + + +class PilotRequest(BaseModel): + variant: Literal['q4', 'iq1'] + messages: list[ChatMessage] = Field(min_length=1, max_length=50) + system_prompt: str = Field(default=EXAMPLE['messages'][0]['content'], max_length=30000) + tools_enabled: bool = True + max_tokens: int = Field(default=256, ge=32, le=1024) + cache_prompt: bool = True + + +@router.post('/chat') +async def chat(req: PilotRequest): + if not await asyncio.to_thread(health, req.variant): + raise HTTPException(503, 'This local model is not ready. Start local_pilot.py first.') + q = queue.Queue() + cancelled = threading.Event() + responses = [] + done = object() + payload = {'model': 'bitwiser-qwen35-4b', 'messages': [ + {'role': 'system', 'content': req.system_prompt}, + *[m.model_dump() for m in req.messages]], + 'temperature': 0, 'max_tokens': req.max_tokens, 'stream': True, + 'stream_options': {'include_usage': True}, 'cache_prompt': req.cache_prompt, + 'chat_template_kwargs': {'enable_thinking': False}} + if req.tools_enabled: + payload['tools'] = EXAMPLE['tools'] + + def worker(): + def delta(part): + if cancelled.is_set(): + raise InterruptedError('Client disconnected') + if part.get('content'): + q.put({'type': 'token', 'text': part['content']}) + if part.get('tool_calls'): + q.put({'type': 'tool_delta', 'calls': part['tool_calls']}) + try: + request = Request(SERVERS[req.variant] + '/v1/chat/completions', + data=json.dumps(payload).encode(), headers={'Content-Type': 'application/json'}) + start = time.perf_counter() + with urlopen(request, timeout=90) as response: + responses.append(response) + result = consume_sse(response, start, on_delta=delta) + q.put({'type': 'done', **result}) + except Exception as exc: + if not cancelled.is_set(): + q.put({'type': 'error', 'message': f'{type(exc).__name__}: {exc}'}) + finally: + q.put(done) + + threading.Thread(target=worker, daemon=True).start() + + async def stream(): + try: + while True: + item = await asyncio.to_thread(q.get) + if item is done: + break + yield 'data: ' + json.dumps(item) + '\n\n' + finally: + cancelled.set() + # Never block the ASGI loop while another thread reads the socket. + for response in responses: + await asyncio.to_thread(response.close) + + return StreamingResponse(stream(), media_type='text/event-stream') diff --git a/server.py b/server.py index ac42d4b..992767a 100644 --- a/server.py +++ b/server.py @@ -14,6 +14,7 @@ from fastapi.responses import FileResponse, StreamingResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel +from local_playground import router as local_playground_router import compressor import inference @@ -25,6 +26,7 @@ app = FastAPI(title="BitWiser") +app.include_router(local_playground_router) app.add_middleware( CORSMiddleware, diff --git a/start-local.command b/start-local.command new file mode 100755 index 0000000..299fbd2 --- /dev/null +++ b/start-local.command @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")" +exec .venv/bin/python "$PWD/local_pilot.py" diff --git a/stop-local.command b/stop-local.command new file mode 100755 index 0000000..964941c --- /dev/null +++ b/stop-local.command @@ -0,0 +1,22 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")" +.venv/bin/python - <<'PY' +from pathlib import Path +import psutil +root = Path.cwd() +f = root/'.local-pilot/launcher.pid' +if not f.exists(): + print('Local pilot is not running.');raise SystemExit(0) +try: + p = psutil.Process(int(f.read_text())) + args = p.cmdline() + owns_script = str(root/'local_pilot.py') in args or (p.cwd() == str(root) and 'local_pilot.py' in args) + if not owns_script: + raise SystemExit('PID no longer belongs to this pilot; refusing to stop it.') + p.terminate() + print('Stopping BitWiser local pilot and both model servers.') +except psutil.NoSuchProcess: + f.unlink(missing_ok=True) + print('Local pilot already stopped.') +PY diff --git a/web/src/App.tsx b/web/src/App.tsx index e8669ac..8ce3e4f 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -5,8 +5,10 @@ import { ShrinkPanel, type CompressedArtifact } from "./components/ShrinkPanel"; import { VitalsCards } from "./components/VitalsCards"; import { DownloadCard } from "./components/DownloadCard"; import { Playground } from "./components/Playground"; +import { LocalPilot } from "./components/LocalPilot"; export default function App() { + const [view, setView] = useState<"pilot" | "compress">("pilot"); const [models, setModels] = useState([]); const [system, setSystem] = useState(null); const [selected, setSelected] = useState(null); @@ -40,7 +42,13 @@ export default function App() {
-
+ +
+ {view === "pilot" ? : <> +
)} + }