File size: 7,807 Bytes
4606829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""Bounded CPU tensor slices and arithmetic probes; not an inference benchmark.

Uses safetensors' slice contract; never loads a complete checkpoint or engine.
"""
from __future__ import annotations
import argparse
import gc
import json
import math
from pathlib import Path
import time

import mlx.core as mx
import numpy as np
import torch
from safetensors import safe_open

ROOT = Path(__file__).resolve().parent
mx.set_default_device(mx.cpu)
torch.set_num_threads(2)


def rows(root, name, start, end, *, max_bytes=32 * 1024 * 1024):
    if mx.default_device() != mx.cpu:
        raise ValueError('Bounded checkpoint probes require CPU device')
    root = Path(root).resolve()
    mapping = json.loads((root / 'model.safetensors.index.json').read_text())['weight_map']
    if name not in mapping:
        raise ValueError('Missing checkpoint tensor: ' + name)
    filename = mapping[name]
    if Path(filename).name != filename:
        raise ValueError('Unsafe checkpoint shard path')
    path = (root / filename).resolve()
    if path.parent != root:
        raise ValueError('Checkpoint shard path escapes root')
    with safe_open(path, framework='pt', device='cpu') as handle:
        if name not in handle.keys():
            raise ValueError('Index points at missing tensor: ' + name)
        tensor = handle.get_slice(name)
        shape = tensor.get_shape()
        if not shape or not (0 <= start < end <= shape[0]):
            raise ValueError('Invalid checkpoint row bounds')
        # Conservative worst-case dtype width; guard before materialization.
        if (end - start) * math.prod(shape[1:]) * 8 > max_bytes:
            raise ValueError('Checkpoint slice exceeds memory bound')
        value = tensor[start:end]
    if value.dtype == torch.bfloat16:
        return mx.array(value.view(torch.uint16).numpy()).view(mx.bfloat16)
    return mx.array(value.numpy())


def all_small(root, name):
    mapping = json.loads((Path(root) / 'model.safetensors.index.json').read_text())['weight_map']
    with safe_open(Path(root) / mapping[name], framework='pt', device='cpu') as handle:
        count = handle.get_slice(name).get_shape()[0]
    return rows(root, name, 0, count)


def probes(output):
    started = time.monotonic()
    target, source = ROOT / 'target-affine4-g64', ROOT / 'source/BF16'
    from mlx_vlm.models.qwen3_vl.vision import PatchEmbed
    records = []
    # Projection arithmetic is checked against an independent torch matmul of
    # explicitly dequantized weights; this does not test end-to-end model quality.
    for name, count in [
        ('language_model.model.layers.0.linear_attn.in_proj_a.weight', 48),
        ('language_model.model.layers.0.mlp.up_proj.weight', 8),
        ('language_model.model.layers.31.self_attn.q_proj.weight', 8),
        ('language_model.lm_head.weight', 8),
    ]:
        prefix = name.removesuffix('.weight')
        q = rows(target, name, 0, count)
        scale = rows(target, prefix + '.scales', 0, count)
        bias = rows(target, prefix + '.biases', 0, count)
        width = q.shape[1] * 8
        x = (mx.arange(2 * width).reshape(2, width).astype(mx.float32) % 19 - 9) / 32
        x = x.astype(mx.bfloat16)
        # CPU BF16 quantized_matmul can accumulate/round differently from a
        # float32 dequantized matmul. Keep that observation, but isolate packed
        # layout correctness with matched float32 arithmetic, not a looser gate.
        bf16_result = mx.quantized_matmul(x, q, scale, bias, transpose=True, group_size=64, bits=4)
        xf, sf, bf = x.astype(mx.float32), scale.astype(mx.float32), bias.astype(mx.float32)
        actual = mx.quantized_matmul(xf, q, sf, bf, transpose=True, group_size=64, bits=4)
        dense = mx.dequantize(q, sf, bf, group_size=64, bits=4)
        mx.eval(actual, dense, xf, bf16_result)
        ref = torch.from_numpy(np.asarray(xf)) @ torch.from_numpy(np.asarray(dense)).T
        want = mx.array(ref.numpy())
        error = float(mx.max(mx.abs(actual - want)))
        denominator = max(float(mx.max(mx.abs(want))), 1e-6)
        bf16_error = float(mx.max(mx.abs(bf16_result.astype(mx.float32) - want)))
        finite = bool(mx.all(mx.isfinite(actual)))
        if not finite or error > 1e-4 * max(1., denominator):
            raise ValueError('CPU float32 packed projection parity failed: ' + name)
        records.append({'probe': 'quantized_projection', 'tensor': name, 'rows': count,
                        'output_shape': list(actual.shape), 'finite': finite,
                        'layout_parity_arithmetic_dtype': 'float32',
                        'max_abs_error': error, 'max_abs_error_over_peak': error / denominator,
                        'cpu_bf16_vs_float32_max_abs_error': bf16_error,
                        'cpu_bf16_vs_float32_error_over_peak': bf16_error / denominator,
                        'bf16_cpu_inference_parity_claimed': False})
        del q, scale, bias, x, actual, dense, ref, want, xf, sf, bf, bf16_result
        gc.collect()

    # True source Conv3d vs native MLX PatchEmbed, with just 8 output channels.
    config = json.loads((target / 'config.json').read_text())['vision_config']
    original = rows(source, 'model.visual.patch_embed.proj.weight', 0, 8).astype(mx.float32)
    converted = rows(target, 'vision_tower.patch_embed.proj.weight', 0, 8).astype(mx.float32)
    bias = rows(target, 'vision_tower.patch_embed.proj.bias', 0, 8).astype(mx.float32)
    patch = PatchEmbed(patch_size=config['patch_size'], temporal_patch_size=config['temporal_patch_size'],
                       in_channels=config['in_channels'], hidden_size=8)
    patch.load_weights([('proj.weight', converted), ('proj.bias', bias)], strict=True)
    pixels = mx.arange(3 * 2 * 16 * 16).astype(mx.float32).reshape(1, -1) / 4096
    actual = patch(pixels)
    ref = torch.nn.functional.conv3d(torch.from_numpy(np.asarray(pixels).reshape(1, 3, 2, 16, 16)),
                                    torch.from_numpy(np.asarray(original)), torch.from_numpy(np.asarray(bias)),
                                    stride=(2, 16, 16)).reshape(1, 8)
    mx.eval(actual)
    error = float(mx.max(mx.abs(actual - mx.array(ref.numpy()))))
    if error > .001 or not bool(mx.all(mx.isfinite(actual))):
        raise ValueError('Source/native vision patch arithmetic mismatch')
    records.append({'probe': 'vision_patch_embed', 'output_channels': 8,
                    'native_module': 'mlx_vlm.models.qwen3_vl.vision.PatchEmbed',
                    'comparison': 'original-source torch Conv3d CPU', 'max_abs_error': error})

    norm = all_small(target, 'language_model.model.layers.0.input_layernorm.weight').astype(mx.float32)
    x = (mx.arange(norm.size).astype(mx.float32) % 17 - 8).reshape(1, -1) / 16
    actual = mx.fast.rms_norm(x, norm, 1e-6)
    refx = torch.from_numpy(np.asarray(x))
    ref = refx * torch.rsqrt(refx.square().mean(dim=-1, keepdim=True) + 1e-6) * torch.from_numpy(np.asarray(norm))
    mx.eval(actual)
    error = float(mx.max(mx.abs(actual - mx.array(ref.numpy()))))
    if error > .0001:
        raise ValueError('CPU norm arithmetic mismatch')
    records.append({'probe': 'rmsnorm', 'max_abs_error': error})

    result = {'device': 'cpu', 'scope': 'bounded projection, vision patch and norm arithmetic only',
              'full_model_loaded': False, 'model_forward_or_answer': False,
              'inference_speed_measured': False, 'all_passed': True,
              'elapsed_s': time.monotonic() - started, 'probes': records}
    output.write_text(json.dumps(result, indent=2) + '\n')
    return result


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    print(json.dumps(probes(args.output), indent=2))