Instructions to use HyperionGrayAI/cybermodels-linux-drivers with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use HyperionGrayAI/cybermodels-linux-drivers with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Coder-Next") model = PeftModel.from_pretrained(base_model, "HyperionGrayAI/cybermodels-linux-drivers") - Notebooks
- Google Colab
- Kaggle
Download training/fit.py from HyperionGrayAI/cybermodels-linux-drivers: direct link, hf CLI and curl.
- Browser
- Download file 8.98 kB
-
https://huggingface.co/HyperionGrayAI/cybermodels-linux-drivers/resolve/main/training/fit.py
- Command line
-
hf download hf://HyperionGrayAI/cybermodels-linux-drivers/training/fit.py
-
curl -L -o fit.py https://huggingface.co/HyperionGrayAI/cybermodels-linux-drivers/resolve/main/training/fit.py
8.98 kB
| """Train a rank-four GPUless head on whole Windows Internals reference answers.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from gpuless_native_bridge import NativeLibrary, NativeSession | |
| from gpuless_peft_export import export_peft | |
| from safetensors.numpy import load_file | |
| from subspace import CompactObjective, expand | |
| def load_features(directory, examples): | |
| parts = [] | |
| starts, lengths = [], [] | |
| offset = 0 | |
| for row in examples: | |
| path = directory / (row["id"] + "-" + row["condition"] + ".npz") | |
| with np.load(path, allow_pickle=False) as data: | |
| values = {k: data[k] for k in data} | |
| parts.append(values) | |
| starts.append(offset) | |
| lengths.append(len(values["y"])) | |
| offset += lengths[-1] | |
| values = {k: np.concatenate([part[k] for part in parts]) for k in parts[0]} | |
| return values, np.array(starts), np.array(lengths) | |
| def basis_for(hidden): | |
| torch.manual_seed(341) | |
| h = torch.from_numpy(hidden.astype(np.float32)) | |
| _, _, v = torch.pca_lowrank(h, q=32, center=False, niter=3) | |
| b = v[:, :24].T.contiguous() | |
| rms = (h @ b.T).square().mean(0).sqrt().clamp_min(1e-5) | |
| return (b / rms[:, None]).numpy().copy() | |
| def dataset_entry(data, rows, basis): | |
| selected = data["selected"] | |
| lse = np.logaddexp(data["outside_lse"], np.logaddexp.reduce(selected, axis=1)) | |
| indices = {token: i for i, token in enumerate(rows.tolist())} | |
| return { | |
| "hidden": np.ascontiguousarray(data["h"].astype(np.float32) @ basis.T), | |
| "selected": selected, | |
| "outside_lse": data["outside_lse"], | |
| "base_lse": lse, | |
| "reference_p": np.exp(selected - lse[:, None]), | |
| "label_base": data["label"], | |
| "label_indices": np.array([indices.get(int(t), -1) for t in data["y"]]), | |
| } | |
| def score(data, rows, delta): | |
| logits = data["selected"] + delta | |
| denom = np.logaddexp(data["outside_lse"], np.logaddexp.reduce(logits, axis=1)) | |
| cols = np.searchsorted(rows, data["y"]).clip(max=len(rows) - 1) | |
| targets = data["label"] + delta[np.arange(len(cols)), cols] * ( | |
| rows[cols] == data["y"] | |
| ) | |
| peak = logits.argmax(1) | |
| best = logits[np.arange(len(peak)), peak] | |
| use_selected = (best > data["outside_max"]) | ( | |
| (best == data["outside_max"]) & (rows[peak] < data["outside_id"]) | |
| ) | |
| winner = np.where( | |
| use_selected, | |
| rows[peak], | |
| data["outside_id"], | |
| ) | |
| return denom - targets, winner == data["y"] | |
| def fit(features, dataset, out): | |
| meta = json.loads((features / "meta.json").read_text()) | |
| if meta["dataset_sha256"] != hashlib.sha256(dataset.read_bytes()).hexdigest(): | |
| msg = "capture belongs to another dataset" | |
| raise ValueError(msg) | |
| examples = [json.loads(x) for x in dataset.read_text().splitlines()] | |
| data, starts, lengths = load_features(features, examples) | |
| train = np.array([i for i, r in enumerate(examples) if r["split"] == "train"]) | |
| held = {r["passage"] for r in examples if r["split"] == "test"} | |
| if held & {examples[i]["passage"] for i in train}: | |
| msg = "passage leaked across the split" | |
| raise ValueError(msg) | |
| train_positions = np.concatenate( | |
| [np.arange(starts[i], starts[i] + lengths[i]) for i in train] | |
| ) | |
| basis = basis_for(data["h"][train_positions]) | |
| rows = np.array(meta["rows"]) | |
| rank = 4 | |
| out.mkdir(exist_ok=False, parents=True) | |
| obj = CompactObjective(basis=basis, rows=rows, rank=rank, alpha=rank) | |
| obj.active = "batch" | |
| entry = dataset_entry(data, rows, basis) | |
| rng = np.random.default_rng(20261126) | |
| initial_a = rng.normal(0, len(basis) ** -0.5, size=(rank, len(basis))).astype( | |
| np.float32 | |
| ) | |
| config = { | |
| "library": NativeLibrary(), | |
| "model_id": meta["model"], | |
| "model_revision": meta["revision"], | |
| "rank": rank, | |
| "alpha": rank, | |
| "learning_rate": 0.008, | |
| "seed": 342, | |
| } | |
| try: | |
| with NativeSession( | |
| **config, | |
| target_name="lm_head.compact", | |
| in_features=len(basis), | |
| out_features=len(rows), | |
| initial_a=initial_a, | |
| initial_b=np.zeros((len(rows), rank), np.float32), | |
| loss_callback=obj.callback, | |
| ) as session: | |
| t = time.monotonic() | |
| for _epoch in range(32): | |
| order = rng.permutation(train) | |
| for start in range(0, len(order), 16): | |
| ids = order[start : start + 16] | |
| # Same minibatch for all +/- measurements in the native step. | |
| pos = ( | |
| starts[ids, None] | |
| + rng.integers(0, lengths[ids, None], (len(ids), 8)) | |
| ).ravel() | |
| obj.entries["batch"] = {k: v[pos] for k, v in entry.items()} | |
| session.step(identity="batch", examples=len(ids), directions=4) | |
| elapsed = time.monotonic() - t | |
| a, b, generation = session.copy_adapter() | |
| session.save_checkpoint(out / "compact.checkpoint") | |
| np.savez(out / "space.npz", basis=basis, rows=rows) | |
| full_a, full_b = expand(a, b, basis, rows, meta["vocabulary"]) | |
| def export_only(_request): | |
| msg = "expanded session is serialization only" | |
| raise RuntimeError(msg) | |
| with NativeSession( | |
| **config, | |
| target_name="lm_head", | |
| in_features=full_a.shape[1], | |
| out_features=full_b.shape[0], | |
| initial_a=full_a, | |
| initial_b=full_b, | |
| loss_callback=export_only, | |
| ) as expanded: | |
| expanded.export_adapter(out / "lm_head.gpuless") | |
| export_peft( | |
| out / "lm_head.gpuless", | |
| out / "peft", | |
| expected_model_id=meta["model"], | |
| expected_revision=meta["revision"], | |
| base_model=meta["model"], | |
| base_revision=meta["revision"], | |
| ) | |
| weights = load_file(str(out / "peft/adapter_model.safetensors")) | |
| delta = ( | |
| data["h"].astype(np.float32) | |
| ) @ weights["base_model.model.lm_head.lora_B.weight"][rows].T | |
| np.testing.assert_allclose( | |
| delta[:128], | |
| obj.ptpu.add( | |
| a, b, entry["hidden"][:128], np.zeros((128, len(rows)), np.float32) | |
| ), | |
| rtol=2e-4, | |
| atol=2e-4, | |
| ) | |
| pairs = { | |
| key: score(data, rows, d) | |
| for key, d in (("flash", np.zeros_like(delta)), ("lora", delta)) | |
| } | |
| scores, per_question = {}, [] | |
| for i, r in enumerate(examples): | |
| sel = slice(starts[i], starts[i] + lengths[i]) | |
| rec = {k: r[k] for k in ("id", "split", "condition", "passage")} | |
| for key, (nll, acc) in pairs.items(): | |
| rec[key] = { | |
| "mean_nll": float(nll[sel].mean()), | |
| "correct": int(acc[sel].sum()), | |
| } | |
| rec["tokens"] = int(lengths[i]) | |
| per_question.append(rec) | |
| for split, condition in sorted( | |
| {(r["split"], r["condition"]) for r in examples} | |
| ): | |
| group = [ | |
| r | |
| for r in per_question | |
| if (r["split"], r["condition"]) == (split, condition) | |
| ] | |
| total = sum(r["tokens"] for r in group) | |
| scores[split + "-" + condition] = { | |
| "questions": len(group), | |
| "tokens": total, | |
| **{ | |
| key: { | |
| "nll": sum(r[key]["mean_nll"] * r["tokens"] for r in group) | |
| / total, | |
| "top1": sum(r[key]["correct"] for r in group) / total, | |
| } | |
| for key in pairs | |
| }, | |
| } | |
| report = { | |
| "model_revision": meta["revision"], | |
| "capture_control": meta["control"], | |
| "optimizer": "GPUless native MeZO + pTPU", | |
| "rank": rank, | |
| "vocabulary_rows": len(rows), | |
| "basis_dimensions": len(basis), | |
| "steps": generation, | |
| "directions": 4, | |
| "train_seconds": elapsed, | |
| "dataset_sha256": meta["dataset_sha256"], | |
| "scores": scores, | |
| } | |
| (out / "scores.json").write_text(json.dumps(report, indent=2) + "\n") | |
| (out / "question_scores.json").write_text( | |
| json.dumps(per_question, indent=2) + "\n" | |
| ) | |
| print(json.dumps(report)) | |
| finally: | |
| obj.close() | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| for arg in ("features", "dataset", "out"): | |
| parser.add_argument(arg, type=Path) | |
| args = parser.parse_args() | |
| torch.set_num_threads(2) | |
| fit(args.features, args.dataset, args.out) | |