Skip to content

Commit 9bca62c

Browse files
fix: resolve CI lint and type check failures
- fix finetune call in CLI to pass required data arg - annotate model/tokenizer as Any in inference engine - fix formats sort typing in auto_bench - annotate qlayer and bias to satisfy mypy 2.x - apply ruff format to conform to CI check Co-authored-by: monkeycode-ai <monkeycode-ai@chaitin.com>
1 parent 254d7dd commit 9bca62c

21 files changed

Lines changed: 540 additions & 177 deletions

‎examples/01_quickstart.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,7 @@
3333

3434
# Streaming
3535
print("\nStreaming...")
36-
for token in model.generate(
37-
"Count from 1 to 5:", stream=True, max_new_tokens=30
38-
):
36+
for token in model.generate("Count from 1 to 5:", stream=True, max_new_tokens=30):
3937
print(token, end="", flush=True)
4038
print()
4139

‎examples/05_hqq_quantization.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,14 @@
2828
# Size comparison
2929
orig = weight.numel() * 4
3030
quant = HQQQuantizer.estimate_size(weight, config)
31-
print(f" Size: {orig/1024:.0f} KB -> {quant/1024:.0f} KB ({quant/orig:.3f}x)")
31+
print(f" Size: {orig / 1024:.0f} KB -> {quant / 1024:.0f} KB ({quant / orig:.3f}x)")
3232

3333
# ------------------------------------------------------------------
3434
# Quantise a full model
3535
# ------------------------------------------------------------------
3636
print("\nQuantising a full model...")
3737

38+
3839
class DemoModel(torch.nn.Module):
3940
def __init__(self):
4041
super().__init__()
@@ -47,6 +48,7 @@ def forward(self, x):
4748
x = torch.relu(self.fc2(x))
4849
return self.fc3(x)
4950

51+
5052
model = DemoModel()
5153
print(f" Original params: {sum(p.numel() for p in model.parameters())}")
5254

‎examples/06_inference_server.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
print(f" POST http://{config.host}:{config.port}/v1/completions")
2828
print()
2929
print("Example request:")
30-
print(f' curl -X POST http://localhost:{config.port}/v1/chat/completions \\')
30+
print(f" curl -X POST http://localhost:{config.port}/v1/chat/completions \\")
3131
print(' -H "Content-Type: application/json" \\')
3232
print(' -d \'{"messages":[{"role":"user","content":"Hello"}]}\'')
3333
print()

‎examples/07_benchmark.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
print(" (This loads the model three times, may take a while)")
4141
try:
4242
from quantllm.benchmark import BenchmarkComparer
43+
4344
comparer = BenchmarkComparer(
4445
model_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
4546
verbose=True,

‎examples/08_full_pipeline.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@
2929
# 2. Generate
3030
# ------------------------------------------------------------------
3131
print("\n2. Generating text...")
32-
resp = model.generate("What is the difference between AI and ML?",
33-
max_new_tokens=100, temperature=0.7)
32+
resp = model.generate("What is the difference between AI and ML?", max_new_tokens=100, temperature=0.7)
3433
print(f" {resp[:120]}...")
3534

3635
# ------------------------------------------------------------------
@@ -53,8 +52,7 @@
5352

5453
# Also export ONNX for cross-format comparison
5554
print("\n Exporting ONNX...")
56-
model2 = turbo("TinyLlama/TinyLlama-1.1B-Chat-v1.0",
57-
config={"format": "onnx", "quantization": "Q4_K_M"})
55+
model2 = turbo("TinyLlama/TinyLlama-1.1B-Chat-v1.0", config={"format": "onnx", "quantization": "Q4_K_M"})
5856
path2 = model2.export()
5957
print(f" {path2}")
6058

‎quantllm/benchmark/auto_bench.py‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
try:
1818
import torch
19+
1920
HAS_TORCH = True
2021
except ImportError:
2122
HAS_TORCH = False
@@ -63,6 +64,7 @@ def _detect(self) -> HWProfile:
6364
hw.cpu_name = platform.processor() or "Unknown"
6465
try:
6566
import psutil
67+
6668
hw.ram_gb = psutil.virtual_memory().total / (1024**3)
6769
except Exception:
6870
hw.ram_gb = 16.0
@@ -129,7 +131,7 @@ def get_recommendations(self) -> Dict[str, Any]:
129131
quant = self._score_quant(micro)
130132
bq = quant[0] if quant else None
131133

132-
formats = [{"format": "safetensors", "score": 9.0, "reason": "Best HF compatibility"}]
134+
formats: List[Dict[str, Any]] = [{"format": "safetensors", "score": 9.0, "reason": "Best HF compatibility"}]
133135
if self.hw.has_cuda:
134136
formats.append({"format": "gguf", "score": 8.5, "reason": "Optimized for llama.cpp/Ollama"})
135137
if platform.system() == "Darwin" and platform.machine() == "arm64":
@@ -138,7 +140,8 @@ def get_recommendations(self) -> Dict[str, Any]:
138140
formats.sort(key=lambda x: x["score"], reverse=True)
139141

140142
recs = {
141-
"hardware": asdict(self.hw), "micro": micro,
143+
"hardware": asdict(self.hw),
144+
"micro": micro,
142145
"quant_scores": [{"method": q.method, "bits": q.bits, "overall": q.overall} for q in quant],
143146
"format_scores": formats,
144147
"recommended_quant": {"method": bq.method if bq else "bitsandbytes", "bits": bq.bits if bq else 4},
@@ -152,9 +155,13 @@ def get_recommendations(self) -> Dict[str, Any]:
152155
def generate_report(self) -> str:
153156
r = self.get_recommendations()
154157
h = r["hardware"]
155-
lines = ["=" * 70, " QuantLLM Hardware Auto-Benchmark Report", "=" * 70,
156-
f"\n CPU: {h['cpu_name']} ({h['cpu_cores']} cores, {h['ram_gb']:.1f} GB RAM)"]
157-
if h['has_cuda']:
158+
lines = [
159+
"=" * 70,
160+
" QuantLLM Hardware Auto-Benchmark Report",
161+
"=" * 70,
162+
f"\n CPU: {h['cpu_name']} ({h['cpu_cores']} cores, {h['ram_gb']:.1f} GB RAM)",
163+
]
164+
if h["has_cuda"]:
158165
lines.append(f" GPU: {h['gpu_name']} ({h['gpu_vram_gb']:.1f} GB, SM{h['gpu_compute']})")
159166
else:
160167
lines.append(f" GPU: None (CPU mode)")

‎quantllm/benchmark/compare.py‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,26 @@ def run_comparison(self, prompt: str = "The meaning of life is", max_new_tokens:
3535
except Exception as e:
3636
if self.verbose:
3737
from ..utils import print_warning
38+
3839
print_warning(f"{name} failed: {e}")
3940
return self.results
4041

4142
def generate_comparison_report(self) -> str:
4243
if not self.results:
4344
return "No data."
44-
lines = ["=" * 80, " QuantLLM Comparison", f" Model: {self.model_name}", "=" * 80,
45-
f" {'Config':<15} {'Decode':<12} {'Prefill':<12} {'Latency':<12} {'VRAM':<10} {'Size':<10}",
46-
f" {'-'*15} {'-'*12} {'-'*12} {'-'*12} {'-'*10} {'-'*10}"]
45+
lines = [
46+
"=" * 80,
47+
" QuantLLM Comparison",
48+
f" Model: {self.model_name}",
49+
"=" * 80,
50+
f" {'Config':<15} {'Decode':<12} {'Prefill':<12} {'Latency':<12} {'VRAM':<10} {'Size':<10}",
51+
f" {'-' * 15} {'-' * 12} {'-' * 12} {'-' * 12} {'-' * 10} {'-' * 10}",
52+
]
4753
for name, r in self.results.items():
48-
lines.append(f" {name:<15} {r.decode_tokens_per_sec:<12.1f} {r.prefill_tokens_per_sec:<12.1f} "
49-
f"{r.total_latency_ms:<12.1f} {r.peak_vram_gb:<10.2f} {r.model_size_gb:<10.2f}")
54+
lines.append(
55+
f" {name:<15} {r.decode_tokens_per_sec:<12.1f} {r.prefill_tokens_per_sec:<12.1f} "
56+
f"{r.total_latency_ms:<12.1f} {r.peak_vram_gb:<10.2f} {r.model_size_gb:<10.2f}"
57+
)
5058

5159
best = max(self.results, key=lambda k: self.results[k].decode_tokens_per_sec) if self.results else None
5260
if best:

‎quantllm/benchmark/report.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,15 @@
88
def format_report_table(results: list[BenchmarkResult]) -> str:
99
if not results:
1010
return "No results."
11-
lines = ["=" * 90,
12-
f" {'Model':<30} {'Backend':<12} {'Bits':<6} {'Decode':<10} {'VRAM':<10} {'Size':<10}",
13-
f" {'-'*30} {'-'*12} {'-'*6} {'-'*10} {'-'*10} {'-'*10}"]
11+
lines = [
12+
"=" * 90,
13+
f" {'Model':<30} {'Backend':<12} {'Bits':<6} {'Decode':<10} {'VRAM':<10} {'Size':<10}",
14+
f" {'-' * 30} {'-' * 12} {'-' * 6} {'-' * 10} {'-' * 10} {'-' * 10}",
15+
]
1416
for r in results:
1517
s = r.model.split("/")[-1][:28]
16-
lines.append(f" {s:<30} {r.backend or 'transformers':<12} {r.bits:<6} {r.decode_tokens_per_sec:<10.1f} {r.peak_vram_gb:<10.2f} {r.model_size_gb:<10.2f}")
18+
lines.append(
19+
f" {s:<30} {r.backend or 'transformers':<12} {r.bits:<6} {r.decode_tokens_per_sec:<10.1f} {r.peak_vram_gb:<10.2f} {r.model_size_gb:<10.2f}"
20+
)
1721
lines.append("=" * 90)
1822
return "\n".join(lines)

‎quantllm/benchmark/runner.py‎

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,18 @@ def __init__(self, verbose: bool = True):
3333
self.verbose = verbose
3434
self.results: List[BenchmarkResult] = []
3535

36-
def benchmark_model(self, model, tokenizer, config, prompt: str = "The meaning of life is",
37-
max_new_tokens: int = 128, num_warmup: int = 3, num_runs: int = 5) -> BenchmarkResult:
36+
def benchmark_model(
37+
self,
38+
model,
39+
tokenizer,
40+
config,
41+
prompt: str = "The meaning of life is",
42+
max_new_tokens: int = 128,
43+
num_warmup: int = 3,
44+
num_runs: int = 5,
45+
) -> BenchmarkResult:
3846
from ..utils import print_info, print_success
47+
3948
r = BenchmarkResult(
4049
model=getattr(getattr(model, "config", None), "_name_or_path", "unknown"),
4150
bits=getattr(config, "bits", 16),
@@ -52,21 +61,36 @@ def benchmark_model(self, model, tokenizer, config, prompt: str = "The meaning o
5261

5362
for _ in range(num_warmup):
5463
with torch.inference_mode():
55-
model.generate(input_ids, max_new_tokens=16, do_sample=False,
56-
pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id)
64+
model.generate(
65+
input_ids,
66+
max_new_tokens=16,
67+
do_sample=False,
68+
pad_token_id=tokenizer.pad_token_id,
69+
eos_token_id=tokenizer.eos_token_id,
70+
)
5771

5872
start = time.time()
5973
with torch.inference_mode():
60-
model.generate(input_ids, max_new_tokens=1, do_sample=False,
61-
pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id)
74+
model.generate(
75+
input_ids,
76+
max_new_tokens=1,
77+
do_sample=False,
78+
pad_token_id=tokenizer.pad_token_id,
79+
eos_token_id=tokenizer.eos_token_id,
80+
)
6281
r.prefill_tokens_per_sec = prefill_len / (time.time() - start) if (time.time() - start) > 0 else 0
6382

6483
decode_times = []
6584
for _ in range(num_runs):
6685
start = time.time()
6786
with torch.inference_mode():
68-
model.generate(input_ids, max_new_tokens=max_new_tokens, do_sample=False,
69-
pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id)
87+
model.generate(
88+
input_ids,
89+
max_new_tokens=max_new_tokens,
90+
do_sample=False,
91+
pad_token_id=tokenizer.pad_token_id,
92+
eos_token_id=tokenizer.eos_token_id,
93+
)
7094
elapsed = time.time() - start
7195
decode_times.append(max_new_tokens / elapsed if elapsed > 0 else 0)
7296
r.decode_tokens_per_sec = sum(decode_times) / len(decode_times)
@@ -91,7 +115,8 @@ def generate_report(self) -> str:
91115
lines = ["=" * 70, " QuantLLM Benchmark Report", "=" * 70]
92116
for i, r in enumerate(self.results):
93117
lines += [
94-
f"\n Run {i+1}: {r.model}", f" {'='*50}",
118+
f"\n Run {i + 1}: {r.model}",
119+
f" {'=' * 50}",
95120
f" Params: {r.num_params_billion:.2f}B",
96121
f" Bits: {r.bits}",
97122
f" Prefill: {r.prefill_tokens_per_sec:.1f} tok/s",
@@ -103,9 +128,16 @@ def generate_report(self) -> str:
103128
return "\n".join(lines)
104129

105130

106-
def run_benchmark_cli(model_name: str, bits: int = 4, prompt: str = "The meaning of life is",
107-
max_new_tokens: int = 128, save: bool = True, verbose: bool = True) -> BenchmarkResult:
131+
def run_benchmark_cli(
132+
model_name: str,
133+
bits: int = 4,
134+
prompt: str = "The meaning of life is",
135+
max_new_tokens: int = 128,
136+
save: bool = True,
137+
verbose: bool = True,
138+
) -> BenchmarkResult:
108139
from .. import turbo
140+
109141
m = turbo(model_name, bits=bits, verbose=verbose)
110142
runner = BenchmarkRunner(verbose=verbose)
111143
result = runner.benchmark_model(m.model, m.tokenizer, m.config, prompt=prompt, max_new_tokens=max_new_tokens)

0 commit comments

Comments
 (0)