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.
brendanboyle's picture
Release v0.1.0 with standalone MLX-LM and oMLX adapters
dbe026e verified
Raw History Blame Contribute Delete
7.91 kB
"""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()