Run this model with HF Jobs

Run brendanboyle/Inkling-2-Mini-Codex-MLX on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/brendanboyle/Inkling-2-Mini-Codex-MLX. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/brendanboyle/Inkling-2-Mini-Codex-MLX on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/brendanboyle/Inkling-2-Mini-Codex-MLX. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/brendanboyle/Inkling-2-Mini-Codex-MLX. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
File size: 7,911 Bytes
dbe026e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""Convert the pinned Harness Hub PEFT weights into a standalone MLX-LM adapter."""

import argparse
import hashlib
import json
import tempfile
from dataclasses import dataclass
from pathlib import Path

import numpy as np
from huggingface_hub import hf_hub_download
from safetensors.numpy import load_file, save_file

@dataclass(frozen=True)
class AdapterSource:
    id: str
    revision: str
    weights_sha256: str

    def provenance(self) -> dict:
        return {
            "id": self.id,
            "revision": self.revision,
            "sha256": {
                "adapter_config.json": "a84f0f3ebda595e925c5a2542ccdac1c4e2a274db5a62fcc60b492446e4ced91",
                "adapter_model.safetensors": self.weights_sha256,
            },
        }


SOURCES = {
    "pi": AdapterSource(
        "harness-hub/Inkling-2-Mini-pi-adapted",
        "14b5b5ad446a7686eb9cc9f0accfc4e7e4cb0ec2",
        "fbe6a110c14435d6ccaede0f9d3e0ecb8040f5c16029a6d5e38bbd77858b0b12",
    ),
    "pi-preview": AdapterSource(
        "harness-hub/Inkling-2-Mini-pi-adapted-preview",
        "7788a5325f3223440e2812a02ecc7759f77f344a",
        "772f1b9a4585448106929b5c3a8540ef1a523d85c2a4694f37d8d5380bb3c903",
    ),
    "hermes": AdapterSource(
        "harness-hub/Inkling-2-Mini-hermes-adapted",
        "df327d81a82f124e6f8abf2ae303c04922ee5130",
        "b10a3e00c0f0f5768bcbd1f727ad1f280c9fdfc4695a7c996f9cb1cc4b088112",
    ),
    "codex": AdapterSource(
        "harness-hub/Inkling-2-Mini-codex-adapted",
        "a82c463b5c7715d35baed9a9d58b155756c84ef5",
        "e35567ab39e43dd2c1409e64ce5ec7238927a5d114cbc4e31b663c692273550c",
    ),
}
BASE = "mlx-community/Inkling-2-Mini-4bit"
BASE_REVISION = "9c0e2960609ba7cb40daf92c6f7bf8ed56e1dd62"
RUNTIME_REPO = "https://github.com/tj-doomer-it/mlx-lm.git"
RUNTIME_REVISION = "a7fdb4b0529477526de1f25e2c99472d8b585529"
RANK = 32
SCALE = 2.0
FEATURE_COUNTS = {
    "q_proj": (2304, 3072),
    "k_proj": (2304, 1024),
    "v_proj": (2304, 1024),
    "o_proj": (3072, 2304),
}
TARGETS = {
    f"model.language_model.layers.{layer}.self_attn.{projection}": dims
    for layer in range(24)
    for projection, dims in FEATURE_COUNTS.items()
}


def sha256(path: Path) -> str:
    with path.open("rb") as file:
        return hashlib.file_digest(file, "sha256").hexdigest()


def write_json(path: Path, value: dict) -> None:
    path.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8")


def source_weights(source: AdapterSource) -> dict[str, np.ndarray]:
    paths = {}
    for name, digest in source.provenance()["sha256"].items():
        path = Path(hf_hub_download(source.id, name, revision=source.revision))
        if sha256(path) != digest:
            raise ValueError(f"SHA-256 mismatch for {name}")
        paths[name] = path

    config = json.loads(paths["adapter_config.json"].read_text(encoding="utf-8"))
    if (
        config["peft_type"] != "LORA"
        or config["r"] != RANK
        or config["lora_alpha"] / RANK != SCALE
        or config["lora_dropout"] != 0
        or any(config.get(key) for key in (
            "fan_in_fan_out", "lora_bias", "use_dora", "use_rslora",
            "alpha_pattern", "rank_pattern", "modules_to_save",
        ))
    ):
        raise ValueError("Unexpected PEFT LoRA configuration")

    return load_file(paths["adapter_model.safetensors"])


def key(target: str, factor: str) -> str:
    return f"base_model.model.{target}.linear.lora_{factor.upper()}.weight"


def convert(source: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
    shapes = {}
    for target, (inputs, outputs) in TARGETS.items():
        shapes[key(target, "a")] = (RANK, inputs)
        shapes[key(target, "b")] = (outputs, RANK)
    if source.keys() != shapes.keys():
        raise ValueError("The source tensor keys do not match the 96 expected projections")

    for name, shape in shapes.items():
        value = source[name]
        if value.shape != shape or value.dtype != np.float32 or not np.isfinite(value).all():
            raise ValueError(f"Unexpected shape, dtype, or non-finite data in {name}")

    return {
        f"{target}.lora_{factor}": np.ascontiguousarray(source[key(target, factor)].T)
        for target in TARGETS
        for factor in ("a", "b")
    }


def verify(source: dict[str, np.ndarray], converted_path: Path) -> dict:
    weights = load_file(converted_path)
    expected = {f"{target}.lora_{factor}" for target in TARGETS for factor in ("a", "b")}
    if weights.keys() != expected:
        raise ValueError("The converted file does not contain exactly the expected tensors")

    rng = np.random.default_rng(91)
    input_widths = sorted({inputs for inputs, _ in TARGETS.values()})
    probes = {inputs: rng.standard_normal((3, inputs)) for inputs in input_widths}
    max_absolute_error = 0.0
    for target, (inputs, outputs) in TARGETS.items():
        a = weights[f"{target}.lora_a"]
        b = weights[f"{target}.lora_b"]
        peft_a, peft_b = source[key(target, "a")], source[key(target, "b")]
        for name, mlx_array, peft_array, shape in (
            ("a", a, peft_a, (inputs, RANK)),
            ("b", b, peft_b, (RANK, outputs)),
        ):
            if mlx_array.shape != shape or mlx_array.dtype != np.float32:
                raise ValueError(f"Invalid MLX factor shape or dtype in {target}.lora_{name}")
            # Compare the IEEE-754 payloads to verify exact float32 preservation.
            np.testing.assert_array_equal(mlx_array.T.view(np.uint32), peft_array.view(np.uint32))

        probe = probes[inputs]
        peft_output = SCALE * (peft_b @ (peft_a @ probe.T)).T
        mlx_output = SCALE * ((probe @ a) @ b)
        np.testing.assert_allclose(mlx_output, peft_output, rtol=1e-12, atol=1e-12)
        max_absolute_error = max(
            max_absolute_error, float(np.max(np.abs(mlx_output - peft_output)))
        )

    return {
        "projections": len(TARGETS),
        "bit_exact_float32_factors": len(weights),
        "float64_probe_rows_per_projection": 3,
        "float64_probe_max_absolute_error": max_absolute_error,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("output", type=Path, help="New directory for the converted adapter")
    parser.add_argument("--source", choices=SOURCES, default="pi", help="Harness Hub checkpoint")
    args = parser.parse_args()
    output = args.output.resolve()
    if output.exists():
        parser.error(f"Output already exists: {output}")

    checkpoint = SOURCES[args.source]
    source = source_weights(checkpoint)
    weights = convert(source)
    output.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(dir=output.parent) as temporary:
        candidate = Path(temporary) / "adapter"
        candidate.mkdir()
        write_json(candidate / "adapter_config.json", {
            "fine_tune_type": "lora",
            "num_layers": len(TARGETS) // len(FEATURE_COUNTS),
            "lora_parameters": {
                "rank": RANK,
                "scale": SCALE,
                "dropout": 0.0,
                "keys": list(TARGETS),
            },
        })
        weight_path = candidate / "adapters.safetensors"
        save_file(weights, weight_path)
        verification = verify(source, weight_path)
        write_json(candidate / "provenance.json", {
            "source": checkpoint.provenance(),
            "base": {"id": BASE, "revision": BASE_REVISION},
            "mlx_lm": {"repo": RUNTIME_REPO, "revision": RUNTIME_REVISION},
            "output_sha256": {
                path.name: sha256(path) for path in (weight_path, candidate / "adapter_config.json")
            },
            "conversion_checks": verification,
        })
        candidate.rename(output)
    print(json.dumps({"output": str(output), **verification}, indent=2))


if __name__ == "__main__":
    main()