Skip to content
Draft
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
18 changes: 18 additions & 0 deletions .github/workflows/python-tests.yml
Original file line number Diff line number Diff line change
@@ -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 local_pilot.py local_playground.py server.py
- run: bash -n setup.sh start-local.command stop-local.command
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,7 @@ compressed/
# Notes (not for repo)
implementation.md
implementation.txt

.local-pilot/

web/*.tsbuildinfo
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,22 @@ 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.

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.
141 changes: 141 additions & 0 deletions benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""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, on_delta=None):
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 on_delta is not None:
on_delta(delta)
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()
Loading
Loading