Skip to content

Commit 1d01257

Browse files
authored
Fix for kimi k2 (#593)
* fix for kimi k2 * actually dequant * use native int4
1 parent 2959af0 commit 1d01257

3 files changed

Lines changed: 39 additions & 8 deletions

File tree

mlx_lm/benchmark.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from mlx_lm import batch_generate, load, stream_generate
88
from mlx_lm.generate import DEFAULT_MODEL
9+
from mlx_lm.utils import pipeline_load
910

1011

1112
def setup_arg_parser():
@@ -56,11 +57,21 @@ def main():
5657
args = parser.parse_args()
5758
mx.random.seed(0)
5859

60+
group = mx.distributed.init()
61+
rank = group.rank()
62+
63+
def rprint(*args, **kwargs):
64+
if rank == 0:
65+
print(*args, **kwargs)
66+
5967
model_path = args.model or DEFAULT_MODEL
6068

61-
model, tokenizer, config = load(
62-
args.model, return_config=True, tokenizer_config={"trust_remote_code": True}
63-
)
69+
if group.size() > 1:
70+
model, tokenizer, config = pipeline_load(args.model, return_config=True)
71+
else:
72+
model, tokenizer, config = load(
73+
args.model, return_config=True, tokenizer_config={"trust_remote_code": True}
74+
)
6475

6576
# Empty to avoid early stopping
6677
tokenizer._eos_token_ids = {}
@@ -89,26 +100,26 @@ def batch_bench():
89100
else:
90101
_bench = batch_bench
91102

92-
print("Running warmup..")
103+
rprint("Running warmup..")
93104
_bench()
94105

95106
report_keys = ["prompt_tps", "generation_tps", "peak_memory"]
96-
print(f"Timing with {prompt_tokens=}, {generation_tokens=}, {batch_size=}.")
107+
rprint(f"Timing with {prompt_tokens=}, {generation_tokens=}, {batch_size=}.")
97108
responses = []
98109
for i in range(args.num_trials):
99110
response = _bench()
100111
responses.append(response)
101112
results = [(k, getattr(response, k)) for k in report_keys]
102113
results = [f"{k}={v:.3f}" for k, v in results]
103-
print(f"Trial {i+1}: " + ", ".join(results))
114+
rprint(f"Trial {i+1}: " + ", ".join(results))
104115

105116
def avg(k):
106117
vals = (getattr(response, k) for response in responses)
107118
return sum(vals) / args.num_trials
108119

109120
results = [(k, avg(k)) for k in report_keys]
110121
results = [f"{k}={v:.3f}" for k, v in results]
111-
print(f"Averages: " + ", ".join(results))
122+
rprint(f"Averages: " + ", ".join(results))
112123

113124

114125
if __name__ == "__main__":

mlx_lm/models/deepseek_v3.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,22 @@ def dequant(weight, scale_inv):
466466
)
467467
return weight[:m, :n].astype(dtype)
468468

469-
# Dequantize
469+
# Remap for int4
470+
new_weights = {}
471+
for k, v in weights.items():
472+
if k.endswith("weight_shape"):
473+
base = k.replace("weight_shape", "")
474+
new_weights[base + "weight"] = weights[base + "weight_packed"].view(
475+
mx.uint32
476+
)
477+
s = weights[base + "weight_scale"]
478+
new_weights[base + "scales"] = s
479+
new_weights[base + "biases"] = -8 * s
480+
elif not (k.endswith("weight_scale") or k.endswith("weight_packed")):
481+
new_weights[k] = v
482+
weights = new_weights
483+
484+
# Dequantize fp8
470485
new_weights = {}
471486
for k, v in weights.items():
472487
if "weight_scale_inv" in k:

mlx_lm/utils.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,11 @@ def class_predicate(p, m):
238238
config["quantization"] = quantization
239239
config["quantization_config"] = quantization
240240
_quantize(quantization)
241+
elif quant_method == "compressed-tensors":
242+
quantization = {"group_size": 32, "bits": 4, "mode": "affine"}
243+
config["quantization"] = quantization
244+
config["quantization_config"] = quantization
245+
_quantize(quantization)
241246

242247
model.load_weights(list(weights.items()), strict=strict)
243248

0 commit comments

Comments
 (0)