Run this model with HF Jobs
Run thestashthai/Broot-Family-Open-Previews 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/thestashthai/Broot-Family-Open-Previews. 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/thestashthai/Broot-Family-Open-Previews 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.
Instructions to use thestashthai/Broot-Family-Open-Previews with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Basalt
How to use thestashthai/Broot-Family-Open-Previews with Basalt:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Download scripts/slice_broot_ne.py from thestashthai/Broot-Family-Open-Previews: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/thestashthai/Broot-Family-Open-Previews/resolve/main/scripts/slice_broot_ne.py
- Command line
-
hf download hf://thestashthai/Broot-Family-Open-Previews/scripts/slice_broot_ne.py
-
curl -L -o slice_broot_ne.py https://huggingface.co/thestashthai/Broot-Family-Open-Previews/resolve/main/scripts/slice_broot_ne.py
10.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| Clean-cut expert slicer: slices Broot-65B-LoopUD-IQ4_XS.basalt (NE=256) down to | |
| NE = 128 (1/4 QFN), 64 (1/8 QFN), or 32 (1/16 QFN) using the real routing frequency | |
| ranking in qwen4exp-48x256.prof, plus slices ckpt_final_groot256.safetensors and | |
| qwen4exp-48x256.prof identically. | |
| """ | |
| import argparse, json, os, re, shutil, struct, sys, time | |
| from pathlib import Path | |
| import numpy as np | |
| ADAMANT = Path(r"C:\Users\Travis\.gemini\antigravity\scratch\adamant") | |
| sys.path.insert(0, str(ADAMANT / "tools")) | |
| from model_file import ModelFile, ModelWriter | |
| def load_prof256(path: Path): | |
| raw = path.read_bytes() | |
| ver, nl, ne, total, count = struct.unpack_from("<5I", raw, 0) | |
| assert ver == 1 and nl == 48 and ne == 256 and len(raw) == 20 + count * 4, (ver, nl, ne, total, count, len(raw)) | |
| pairs = [] | |
| for i in range(count): | |
| l, e = struct.unpack_from("<HH", raw, 20 + i * 4) | |
| pairs.append((l, e)) | |
| return pairs | |
| def write_prof(path: Path, nl: int, ne: int, pairs: list[tuple[int, int]]): | |
| buf = bytearray(20 + len(pairs) * 4) | |
| struct.pack_into("<5I", buf, 0, 1, nl, ne, len(pairs), len(pairs)) | |
| for i, (l, e) in enumerate(pairs): | |
| struct.pack_into("<HH", buf, 20 + i * 4, l, e) | |
| path.write_bytes(buf) | |
| def slice_safetensors(src_st: Path, dst_st: Path, keep_by_layer: dict[int, list[int]], new_ne: int): | |
| # Pure Python/numpy safetensors reader+writer (no torch needed!) | |
| with open(src_st, "rb") as f: | |
| hlen = struct.unpack("<Q", f.read(8))[0] | |
| hdr = json.loads(f.read(hlen).decode("utf-8")) | |
| data_start = 8 + hlen | |
| meta = hdr.pop("__metadata__", None) | |
| new_hdr = {} | |
| if meta is not None: | |
| new_hdr["__metadata__"] = meta | |
| chunks = [] | |
| off = 0 | |
| sliced_count = 0 | |
| for name, info in hdr.items(): | |
| s0, s1 = info["data_offsets"] | |
| f.seek(data_start + s0) | |
| raw = f.read(s1 - s0) | |
| shape = list(info["shape"]) | |
| dtype = info["dtype"] | |
| # Match router lora_b: [256, 16] -> [new_ne, 16] | |
| m_core = re.search(r"core_steps\.(\d+)\.layer\.mlp\.gate\.lora_b", name) | |
| m_coda = re.search(r"coda\.(\d+)\.mlp\.gate\.lora_b", name) | |
| layer = None | |
| if m_core: | |
| layer = 16 + int(m_core.group(1)) | |
| elif m_coda: | |
| layer = 40 + int(m_coda.group(1)) | |
| if layer is not None and len(shape) == 2 and shape[0] == 256: | |
| bpe = 2 if dtype in ("BF16", "F16") else 4 | |
| arr = np.frombuffer(raw, dtype=np.uint8).reshape(256, shape[1] * bpe) | |
| raw = arr[keep_by_layer.get(layer, list(range(new_ne)))].tobytes() | |
| shape[0] = new_ne | |
| sliced_count += 1 | |
| new_hdr[name] = {"dtype": dtype, "shape": shape, "data_offsets": [off, off + len(raw)]} | |
| chunks.append(raw) | |
| off += len(raw) | |
| assert sliced_count == 24, f"Expected 24 sliced router LoRA tensors, got {sliced_count}" | |
| hdr_bytes = json.dumps(new_hdr, separators=(",", ":")).encode("utf-8") | |
| pad = (-len(hdr_bytes)) % 8 | |
| hdr_bytes += b" " * pad | |
| with open(dst_st, "wb") as out: | |
| out.write(struct.pack("<Q", len(hdr_bytes))) | |
| out.write(hdr_bytes) | |
| for c in chunks: | |
| out.write(c) | |
| src_json = src_st.with_suffix(".json") | |
| if src_json.exists(): | |
| shutil.copy2(src_json, dst_st.with_suffix(".json")) | |
| def slice_basalt(src_path: Path, out_path: Path, keep_by_layer: dict[int, list[int]], new_ne: int): | |
| t0 = time.time() | |
| base = ModelFile(str(src_path)) | |
| meta = json.loads(base.read("meta")) | |
| layout_lines = base.read("experts.layout").decode("utf-8").splitlines() | |
| dense_index_lines = base.read("dense.index").decode("utf-8").splitlines() | |
| # Parse experts.layout | |
| layer_info = [] | |
| for l in layout_lines: | |
| if not l.strip() or l.startswith("#"): | |
| continue | |
| p = l.split() | |
| layer_info.append((int(p[0]), int(p[1]), int(p[2]), int(p[3]), int(p[4]))) | |
| assert len(layer_info) in (48, 49), f"Unexpected layer_info count: {len(layer_info)}" | |
| # Build new experts.layout + chunk generator | |
| new_layout = [] | |
| exp_off_in_file, _ = base.section("experts") | |
| cur_off = 0 | |
| for layer, gu_t, d_t, old_off, blob_bytes in layer_info: | |
| new_layout.append(f"{layer} {gu_t} {d_t} {cur_off} {blob_bytes}") | |
| cur_off += new_ne * blob_bytes | |
| total_exp_bytes = cur_off | |
| layout_bytes = ( | |
| f"# experts v5: layer gu_type d_type offset blob_bytes (n_expert {new_ne}, total {total_exp_bytes})\n" | |
| + "\n".join(new_layout) + "\n" | |
| ).encode("utf-8") | |
| def expert_chunks(): | |
| with open(src_path, "rb") as f: | |
| for layer, gu_t, d_t, old_off, blob_bytes in layer_info: | |
| idxs = keep_by_layer.get(layer, list(range(new_ne))) | |
| for orig_e in idxs: | |
| f.seek(exp_off_in_file + old_off + orig_e * blob_bytes) | |
| yield f.read(blob_bytes) | |
| # Rebuild dense + dense.index (slicing blk.L.ffn_gate_inp.weight rows 256 -> new_ne) | |
| dense_off_in_file, _ = base.section("dense") | |
| new_dense_parts = [] | |
| new_dense_index = [] | |
| d_cur = 0 | |
| with open(src_path, "rb") as f: | |
| for line in dense_index_lines: | |
| if not line.strip(): | |
| continue | |
| if line.startswith("#"): | |
| new_dense_index.append(line) | |
| continue | |
| parts = line.split() | |
| name = parts[0] | |
| old_off = int(parts[3]) | |
| old_sz = int(parts[4]) | |
| f.seek(dense_off_in_file + old_off) | |
| raw = f.read(old_sz) | |
| m = re.match(r"^blk\.(\d+)\.ffn_gate_inp\.weight$", name) | |
| if m: | |
| layer = int(m.group(1)) | |
| # BF16 [256, 2560] -> [new_ne, 2560] | |
| row_bytes = old_sz // 256 | |
| arr = np.frombuffer(raw, dtype=np.uint8).reshape(256, row_bytes) | |
| raw = arr[keep_by_layer.get(layer, list(range(new_ne)))].tobytes() | |
| parts[4] = str(len(raw)) | |
| parts[6] = str(len(raw)) | |
| parts[8] = str(new_ne) | |
| pad = (-d_cur) % 64 | |
| if pad: | |
| new_dense_parts.append(b"\0" * pad) | |
| d_cur += pad | |
| parts[3] = str(d_cur) | |
| parts[5] = str(d_cur) | |
| new_dense_parts.append(raw) | |
| d_cur += len(raw) | |
| new_dense_index.append(" ".join(parts)) | |
| new_dense_bytes = b"".join(new_dense_parts) | |
| new_dense_index_bytes = ("\n".join(new_dense_index) + "\n").encode("utf-8") | |
| # Update meta | |
| meta["name"] = out_path.stem | |
| if "gguf_kv" in meta: | |
| meta["gguf_kv"]["qwen4exp.expert_count"] = new_ne | |
| for tname, tinfo in meta.get("tensors", {}).items(): | |
| if re.match(r"^blk\.(\d+)\.ffn_gate_inp\.weight$", tname): | |
| tinfo["shape"] = [2560, new_ne] | |
| tinfo["bytes"] = 2560 * new_ne * 4 | |
| elif re.match(r"^blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$", tname): | |
| if len(tinfo.get("shape", [])) == 3 and tinfo["shape"][2] == 256: | |
| tinfo["shape"][2] = new_ne | |
| tinfo["bytes"] = tinfo["bytes"] * new_ne // 256 | |
| # Write output .basalt | |
| if out_path.exists(): | |
| out_path.unlink() | |
| w = ModelWriter(str(out_path)) | |
| ok = False | |
| try: | |
| for name in base.names(): | |
| if name == "meta": | |
| continue | |
| elif name == "experts": | |
| w.add_chunks("experts", expert_chunks()) | |
| elif name == "experts.layout": | |
| w.add_bytes("experts.layout", layout_bytes) | |
| elif name == "dense": | |
| w.add_bytes("dense", new_dense_bytes) | |
| elif name == "dense.index": | |
| w.add_bytes("dense.index", new_dense_index_bytes) | |
| else: | |
| off, sz = base.section(name) | |
| w.add_file(name, str(src_path), off, sz) | |
| w.add_bytes("meta", json.dumps(meta, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) | |
| w.close() | |
| ok = True | |
| print(f"DONE {out_path.name}: {out_path.stat().st_size/1024**3:.2f} GiB (experts {total_exp_bytes/1024**3:.2f} GiB) in {time.time()-t0:.1f}s", flush=True) | |
| finally: | |
| if not ok and out_path.exists(): | |
| try: | |
| w.f.close() | |
| except Exception: | |
| pass | |
| out_path.unlink() | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--ne", type=int, required=True, choices=[128, 64, 32]) | |
| a = ap.parse_args() | |
| ne = a.ne | |
| prof256 = ADAMANT / "data" / "profiles" / "qwen4exp-48x256.prof" | |
| pairs = load_prof256(prof256) | |
| keep_by_layer = {l: [] for l in range(48)} | |
| for l, e in pairs: | |
| if len(keep_by_layer[l]) < ne: | |
| keep_by_layer[l].append(e) | |
| # Sort kept expert indices ascending within each layer for clean locality, and build remap | |
| remap = {} | |
| for l in range(48): | |
| assert len(keep_by_layer[l]) == ne, f"Layer {l} only had {len(keep_by_layer[l])} experts" | |
| keep_by_layer[l].sort() | |
| for new_idx, old_idx in enumerate(keep_by_layer[l]): | |
| remap[(l, old_idx)] = new_idx | |
| # Write sliced .prof preserving exact global hotness rank order | |
| new_pairs = [(l, remap[(l, e)]) for (l, e) in pairs if (l, e) in remap] | |
| out_prof = ADAMANT / "data" / "profiles" / f"qwen4exp-48x{ne}.prof" | |
| write_prof(out_prof, 48, ne, new_pairs) | |
| print(f"Wrote {out_prof} ({len(new_pairs)} ranked pairs)", flush=True) | |
| # Slice loop adapter | |
| src_st = ADAMANT / "models" / "looped-adapter" / "ckpt_final_groot256.safetensors" | |
| out_st = ADAMANT / "models" / "looped-adapter" / f"ckpt_final_groot{ne}.safetensors" | |
| slice_safetensors(src_st, out_st, keep_by_layer, ne) | |
| print(f"Wrote {out_st} ({out_st.stat().st_size/1024**2:.1f} MiB)", flush=True) | |
| # Slice .basalt | |
| src_b = ADAMANT / "models" / "Broot-65B-LoopUD-IQ4_XS.basalt" | |
| out_b = ADAMANT / "models" / f"Broot-NE{ne}-LoopUD-IQ4_XS.basalt" | |
| slice_basalt(src_b, out_b, keep_by_layer, ne) | |
| if __name__ == "__main__": | |
| main() | |