Skip to content

Commit b551468

Browse files
feat: update mypy configuration and add type hints across the codebase
1 parent 5d7da93 commit b551468

8 files changed

Lines changed: 131 additions & 46 deletions

File tree

‎examples/09_custom_workflow.py‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
# Suppress banner for clean output
2323
os.environ["QUANTLLM_BANNER"] = "0"
2424

25-
from quantllm import turbo, TurboModel, register_architecture
25+
from quantllm import turbo, TurboModel, register_architecture, register_model
2626
from quantllm.quant import HQQLinear, HQQQuantizer, HQQConfig
2727
from quantllm.registry import list_models, search_models
2828

@@ -38,7 +38,7 @@ def phase1_load_model():
3838

3939
print(f"Loaded: {model.config.bits}-bit {model.config.quant_type}")
4040
print(f"Device: {model.config.device}, dtype: {model.config.dtype}")
41-
print(f"Params: {model.config.stats.get('params', 0)/1e9:.2f}B")
41+
print(f"Params: {model.config.stats.get('params', 0) / 1e9:.2f}B")
4242
print(f"Quantized: {model.is_quantized}")
4343

4444
# Test generation
@@ -59,7 +59,9 @@ def phase2_quantization():
5959
print("\nBitsAndBytes quantization:")
6060
for bits in [4, 8]:
6161
model = turbo("Qwen/Qwen2.5-7B-Instruct", bits=bits)
62-
print(f" BnB {bits}-bit: bits={model.config.bits}, quant={model.config.quant_type}, quantized={model.is_quantized}")
62+
print(
63+
f" BnB {bits}-bit: bits={model.config.bits}, quant={model.config.quant_type}, quantized={model.is_quantized}"
64+
)
6365
del model
6466

6567
# Test HQQ native quantization (no calibration, for export/optimization)
@@ -71,7 +73,9 @@ def phase2_quantization():
7173
for bits in [2, 4, 8]:
7274
config = HQQConfig(bits=bits, group_size=64, optimize=True)
7375
hqq_layer = HQQLinear(weight, config) # Quantize linear layer
74-
print(f" HQQ {bits}-bit: Original={weight.numel()*2/1e6:.2f}MB, Quantized={hqq_layer.quantized_weight.numel()/1e6:.2f}MB")
76+
print(
77+
f" HQQ {bits}-bit: Original={weight.numel() * 2 / 1e6:.2f}MB, Quantized={hqq_layer.quantized_weight.numel() / 1e6:.2f}MB"
78+
)
7579
del hqq_layer
7680

7781
torch.cuda.empty_cache()
@@ -102,7 +106,9 @@ def phase3_export(model):
102106
for fmt, quant, desc in formats:
103107
print(f"\nExporting {desc}...")
104108
try:
105-
output = tmp_path / f"model_{fmt}_{quant or 'default'}.gguf" if fmt == "gguf" else tmp_path / f"model_{fmt}"
109+
output = (
110+
tmp_path / f"model_{fmt}_{quant or 'default'}.gguf" if fmt == "gguf" else tmp_path / f"model_{fmt}"
111+
)
106112
result = model.export(fmt, str(output), quantization=quant or "auto", chunked_conversion=True)
107113
size_gb = Path(result).stat().st_size / (1024**3) if Path(result).exists() else 0
108114
exports[f"{fmt}_{quant or 'default'}"] = {"path": result, "size_gb": size_gb}
@@ -268,4 +274,4 @@ def main():
268274

269275

270276
if __name__ == "__main__":
271-
main()
277+
main()

‎mypy.ini‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
[mypy]
2+
python_version = 3.10
3+
ignore_missing_imports = true
4+
disallow_untyped_defs = false
5+
warn_unused_ignores = false
6+
7+
[mypy-numpy.*]
8+
ignore_errors = true
9+
follow_imports = skip
10+
11+
[mypy-numpy]
12+
ignore_errors = true
13+
follow_imports = skip

‎pyproject.toml‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,11 +144,21 @@ ignore = [
144144
"quantllm/core/__init__.py" = ["F401"]
145145

146146
[tool.mypy]
147-
python_version = "3.10"
147+
python_version = "3.12"
148148
ignore_missing_imports = true
149149
disallow_untyped_defs = false
150150
warn_unused_ignores = false
151151

152+
[[tool.mypy.overrides]]
153+
module = "numpy"
154+
ignore_errors = true
155+
follow_imports = "skip"
156+
157+
[[tool.mypy.overrides]]
158+
module = "numpy.*"
159+
ignore_errors = true
160+
follow_imports = "skip"
161+
152162
[tool.pytest.ini_options]
153163
minversion = "7.0"
154164
testpaths = ["tests"]

‎quantllm/benchmark/__init__.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,12 @@
1010
# Add a simple run_benchmark function as alias
1111
run_benchmark = run_benchmark_cli
1212

13-
__all__ = ["BenchmarkRunner", "BenchmarkResult", "run_benchmark_cli", "run_benchmark", "BenchmarkComparer", "format_report_table", "HardwareAutoBench"]
13+
__all__ = [
14+
"BenchmarkRunner",
15+
"BenchmarkResult",
16+
"run_benchmark_cli",
17+
"run_benchmark",
18+
"BenchmarkComparer",
19+
"format_report_table",
20+
"HardwareAutoBench",
21+
]

‎quantllm/benchmark/runner.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def generate_report(self) -> str:
151151

152152
def run_benchmark_cli(
153153
model=None,
154-
model_name: str = None,
154+
model_name: str | None = None,
155155
tokenizer=None,
156156
config=None,
157157
bits: int = 4,
@@ -167,12 +167,14 @@ def run_benchmark_cli(
167167

168168
# Handle TurboModel object passed directly as first argument
169169
if model is not None and not isinstance(model, str):
170-
if hasattr(model, 'model') and hasattr(model, 'tokenizer') and hasattr(model, 'config'):
170+
if hasattr(model, "model") and hasattr(model, "tokenizer") and hasattr(model, "config"):
171171
tokenizer = model.tokenizer if tokenizer is None else tokenizer
172172
config = model.config if config is None else config
173173
model = model.model
174174
elif model_name is None and tokenizer is None and config is None:
175-
raise ValueError("If passing a model object, tokenizer and config must also be provided, or pass a TurboModel")
175+
raise ValueError(
176+
"If passing a model object, tokenizer and config must also be provided, or pass a TurboModel"
177+
)
176178

177179
if isinstance(model, str):
178180
if model_name is None:

‎quantllm/core/turbo_model.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,12 @@ def _dequantize_model(self) -> nn.Module:
240240
if hasattr(weight, "dequantize"):
241241
dequant_weight = weight.dequantize()
242242
else:
243-
dequant_weight = bnb.functional.dequantize_4bit(weight.data, weight.quant_state)
243+
# Linear4bit weight may have quant_state or quant_state attribute
244+
quant_state = getattr(weight, "quant_state", None)
245+
if quant_state is not None:
246+
dequant_weight = bnb.functional.dequantize_4bit(weight.data, quant_state)
247+
else:
248+
dequant_weight = weight.data.to(target_dtype)
244249
target_module.weight.data.copy_(dequant_weight.to(target_dtype))
245250
if module.bias is not None:
246251
target_module.bias.data.copy_(module.bias.data.to(target_dtype))

‎quantllm/registry.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ def register_model(self, model_id: str, metadata: Dict[str, Any]) -> bool:
189189
except Exception as e:
190190
try:
191191
from quantllm.utils import print_warning
192+
192193
print_warning(f"Failed to register model: {e}")
193194
except ImportError:
194195
print(f"Warning: Failed to register model: {e}")

0 commit comments

Comments
 (0)