Metadata-Version: 2.4
Name: omnia-surgery
Version: 0.11.0
Summary: Model surgery & verification toolkit with AutoArch (structural understanding of unseen checkpoints), exact-by-construction transformations, bounded-retention editing, merging and format readers — NumPy core, cross-validated against scikit-learn, JAX/optax, onnxruntime, safetensors, gguf-py and Hugging Face Flax models.
Author-email: "M. Sarhan" <prof7mohamedsarhan@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/Mohamed2007Sarhan/omnia-surgery
Project-URL: Source, https://github.com/Mohamed2007Sarhan/omnia-surgery
Project-URL: Issues, https://github.com/Mohamed2007Sarhan/omnia-surgery/issues
Project-URL: Validation, https://github.com/Mohamed2007Sarhan/omnia-surgery/blob/main/VALIDATION.md
Project-URL: Paper, https://github.com/Mohamed2007Sarhan/omnia-surgery/blob/main/paper/omnia_paper.pdf
Project-URL: Author, https://mohamed-sarhan-2007.vercel.app
Keywords: machine-learning,model-editing,model-merging,model-surgery,gguf,safetensors,onnx,interpretability
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: scipy>=1.10
Provides-Extra: onnx
Requires-Dist: onnx>=1.14; extra == "onnx"
Provides-Extra: jax
Requires-Dist: jax; extra == "jax"
Provides-Extra: validate
Requires-Dist: scikit-learn; extra == "validate"
Requires-Dist: jax; extra == "validate"
Requires-Dist: optax; extra == "validate"
Requires-Dist: onnx; extra == "validate"
Requires-Dist: onnxruntime; extra == "validate"
Requires-Dist: safetensors; extra == "validate"
Requires-Dist: gguf; extra == "validate"
Requires-Dist: ml_dtypes; extra == "validate"
Requires-Dist: flax; extra == "validate"
Requires-Dist: transformers<5; extra == "validate"
Dynamic: license-file

<div align="center">

# 🔬 omnia-surgery

### Understand any model. Change it safely. **Prove** it worked.

`pip install omnia-surgery` &nbsp;·&nbsp; `import omnia` &nbsp;·&nbsp; Python ≥ 3.10 &nbsp;·&nbsp; NumPy + SciPy core &nbsp;·&nbsp; MIT

*A model-surgery & verification toolkit with an architecture-understanding engine (**AutoArch**), exact function-preserving transformations, knowledge editing with bounded retention, model merging, a statistically-gated self-improvement loop, and dependency-light readers for safetensors / GGUF / ONNX / Hugging Face checkpoints.*

**173 tests tests &nbsp;·&nbsp; cross-validated against scikit-learn, JAX/optax, onnxruntime, official safetensors, gguf-py and Hugging Face's own Flax models**

</div>

---

## Why does this exist?

Models are changed all the time — merged, edited, quantised, pruned, converted, fine-tuned — and almost nobody can say **what exactly the change did**. Most tooling answers *"it ran"*. omnia answers *"here is the measured difference, here is what is mathematically guaranteed, and here is what is only an approximation"*.

* **Every operation carries an honest label** — `exact`, `approximate`, `statistical`, `learned`, `proposed` (see `omnia.catalog`). No operation claims more than its tests show.
* **Exact where exactness is possible.** Widening, deepening, norm folding, residual-stream rotation and head/MLP permutation symmetries preserve the function to ~1e-15 — and the tests prove it.
* **Hand-written math is verified against independent references**, not just against itself (table below).
* **It tells you what it cannot know.** When weights alone do not determine behaviour (RoPE base, activation, causal vs bidirectional masking), omnia says so, measures *identifiability* on calibration data, and refuses to guess silently.

> **Scope, honestly.** The reference core is NumPy (readable, verifiable, slow). An optional JAX backend gives jit/GPU speed for Llama-family models. omnia is **not** a replacement for PyTorch, JAX or 🤗 Transformers — it is the layer you reach for when you want to *inspect, transform and verify* models. See [Limitations](#honest-limitations).

---

## ✨ AutoArch — point it at a model it has never seen

```python
import numpy as np
from omnia import autoarch, llama

sd = llama.to_hf_llama(llama.LlamaLM(vocab=100, d=32, heads=4, kv=2, layers=3, hidden=64))   # any {name: array} works: safetensors, GGUF, ONNX initialisers, Flax trees
report = autoarch.inspect(sd)
print(report.summary())
```
```
decoder_transformer (confidence 0.70) | params 34,272 | d_model 32 | blocks 3 | vocab 100
  evidence: 1 stack(s); main 'model.layers' x3, homogeneous=True; self-attention stack with lm head / gated MLP / decoder-style names
  ambiguities: causal vs bidirectional masking is NOT stored in weights ...; heads/head_dim ambiguous among [(2, 1), (4, 2), (8, 4)] (use config or calibration); rope base/layout, activation (silu vs gelu), norm eps are not stored in weights
```

AutoArch reasons from **tensor shapes and their relations**, not from a table of known models:

1. finds repeated stacks (`layers.{i}`, `h.{i}`, `block.{i}`, even PyTorch's `weight_ih_l{i}`),
2. infers `d_model` from dimension statistics and re-detects matrix orientation,
3. assigns roles (q/k/v/o, gate/up/down, norms, experts, SSM state, recurrent pairs, conv kernels…) from shape relations, using names only to break ties,
4. classifies the family **with an evidence list and a confidence**, and says `unknown_stacked` for architectures it does not recognise instead of mislabelling them.

**Measured on 23 official 🤗 architectures** (random-weight Flax models: GPT-2, Llama, Mistral, Gemma, OPT, GPT-J, XGLM, BERT, RoBERTa, DistilBERT, ELECTRA, ALBERT, Wav2Vec2, T5, BART, Marian, Whisper, Blenderbot, Pegasus, ViT, ResNet, RegNet, CLIP):

| Test | Result |
|---|---|
| Structural family (self-attention stack / enc-dec / ViT / CNN / multi-tower …) | **23 / 23** |
| …with **every name token randomly replaced** | **23 / 23** |
| Fine label incl. causal-vs-bidirectional prior | 21 / 23 (the 2 misses are an honest *"masking unknown"*) |
| First pass, before any rule was fixed (21 models) | 16 / 21 — the failures drove the fixes; both numbers are logged in `paper/` |

Causal vs bidirectional masking is **not stored in weights**, so AutoArch reports it as a prior with `masking="unknown"` when there is no evidence.

### …and then make it run

```python
import numpy as np
from omnia import autoarch, llama

# a checkpoint with unfamiliar names (Meta-style): AutoArch maps it onto the runnable Llama-family model
m = llama.LlamaLM(vocab=50, d=32, heads=4, kv=2, layers=2, hidden=64, seed=1)
hf = llama.to_hf_llama(m)
meta = {"tok_embeddings.weight": hf["model.embed_tokens.weight"], "norm.weight": hf["model.norm.weight"], "output.weight": hf["lm_head.weight"]}
for i in range(2):
    h, p = f"model.layers.{i}.", f"layers.{i}."
    meta[p + "attention.wq.weight"] = hf[h + "self_attn.q_proj.weight"]; meta[p + "attention.wk.weight"] = hf[h + "self_attn.k_proj.weight"]
    meta[p + "attention.wv.weight"] = hf[h + "self_attn.v_proj.weight"]; meta[p + "attention.wo.weight"] = hf[h + "self_attn.o_proj.weight"]
    meta[p + "feed_forward.w1.weight"] = hf[h + "mlp.gate_proj.weight"]; meta[p + "feed_forward.w3.weight"] = hf[h + "mlp.up_proj.weight"]; meta[p + "feed_forward.w2.weight"] = hf[h + "mlp.down_proj.weight"]
    meta[p + "attention_norm.weight"] = hf[h + "input_layernorm.weight"]; meta[p + "ffn_norm.weight"] = hf[h + "post_attention_layernorm.weight"]
model, info = autoarch.build(meta, config={"rope_theta": 1e4, "hidden_act": "silu", "num_attention_heads": 4})   # config settles what weights cannot say; without it pass calib=<token ids>
ids = np.random.default_rng(0).integers(0, 50, (2, 9)); print("max |logit diff| vs the original model:", np.abs(model(ids).data - m(ids).data).max())
```

What the weights cannot say (head count, RoPE layout, activation, which of two identical-shape tensors is *k* and which is *v*) is resolved by **likelihood on a few calibration sequences**, with an Occam rule (prefer the default unless the data clearly disagrees) and a per-factor *identifiability margin*:

| Calibration data | Function recovered **exactly** from randomised names + shuffled order + (half the cases) Meta's interleaved RoPE |
|---|---|
| 62 tokens | 6 / 12 |
| 248 tokens | 6 / 12 |
| 992 tokens | **12 / 12** |

On a position-sensitive toy task the head count and RoPE layout are *strongly* identifiable (wrong choice ⇒ NLL 4.5–5.2 vs 0.20), whereas the RoPE base and the activation are **not** (NLL 0.205/0.206 vs 0.203) — omnia keeps the default and tells you. (Toy scale; see the paper.)

**Brand-new architecture, not in any table?** `GenericModel` works on *any* state dict without a forward pass, and exported **ONNX** graphs of any architecture can be run and profiled by the built-in interpreter (52 operators; 50 of them individually validated against onnxruntime):

```python
import numpy as np
from omnia import weightspace as ws, llama

sd = llama.to_hf_llama(llama.LlamaLM(60, 32, 4, 2, 3, 64, seed=0)); rng = np.random.default_rng(0)
base = ws.GenericModel(sd)
tuned = {k: v.copy() for k, v in sd.items()}
for i in range(3):                                        # pretend a LoRA fine-tune touched q and v
    for n in ("q_proj", "v_proj"):
        k = f"model.layers.{i}.self_attn.{n}.weight"; tuned[k] = sd[k] + 0.1 * rng.normal(size=(sd[k].shape[0], 2)) @ rng.normal(size=(2, sd[k].shape[1]))
d = base.diff(ws.GenericModel(tuned))
print(d["n_changed"], "tensors changed;", f"{d['lora_like_fraction']:.0%} of changed matrices have a low-rank (LoRA-like) delta")
small, rep = base.compress(bits=8); print(f"int8 role-aware compression: {rep['ratio']:.2f}x")
```

---

## 🧰 The toolbox

| Area | What you get | Status label |
|---|---|---|
| **Build from scratch** | `builder.build(kind)` — 17 families: MLP, CNN, GPT, GQA/MQA, Cross-Layer-Attention LM, Llama, GPT-2, RNN/LSTM/GRU, Mamba block, RetNet, RWKV, SSM, ViT, MoE, GCN | verified by gradient checks |
| **Exact surgery** | widen/deepen (MLP & Transformer), RMSNorm/BatchNorm folding, residual-stream rotation (Hadamard/orthogonal), conv→dense unrolling, MLP/head/KV-group permutation symmetries | **exact** (~1e-15) |
| **Merging** | linear, SLERP, task-arithmetic, TIES, DARE, Fisher, permutation-aligned (MLPs *and* Transformers), optimal-transport across different widths, layer-wise coefficient search | exact / approximate |
| **Knowledge editing** | ROME rank-one, null-space edit, **LyapLock-style bounded-retention sequential editor** (conflicting edits are *rejected*, not forced) | exact / approximate |
| **Self-improvement** | verifier-checked RFT / GRPO / DPO child models; accepted only if a paired exact test *and* retention/overfit guards agree; rollback otherwise | statistical |
| **Quantisation & compression** | INT2–16, NF4 + double quantisation, QLoRA, low-rank, pruning, role-aware `GenericModel.compress` | approximate |
| **Formats** | safetensors (lazy, BF16, streaming merge), **GGUF (13 block types incl. K-quants, bit-exact)**, ONNX, NPZ, HF GPT-2/Llama/Mistral/Qwen2-style/Gemma (+sharded) | validated |
| **Learning paradigms** | supervised, SSL, distillation, EWC, Reptile/FOMAML, FedAvg/FedProx, active learning, BC/DAgger, multi-task, SimCLR, VAE/GAN/flow-matching, DQN, DPO/IPO/SimPO/PPO/GRPO | tested |
| **Classical ML & data** | Ridge/Lasso/Logistic/KNN/NB/KMeans/PCA/GMM/DBSCAN/CART/RF/GBM/XGBoost-style, scalers, encoders, SMOTE family, MinHash-LSH, drift & outlier tools | scikit-learn-checked |
| **Backends** | NumPy reference · optional **JAX** (`jit`, `jax.grad`, GPU/TPU) | verified to ~5e-15 |
| **Runtime architecture** | `cla.CLASystem` — Maestro DAG with **non-bypassable** safety/security/verification gates | engineering design |

### A few one-liners

```python
import numpy as np
from omnia import builder, edit, symmetry, train

seqs = np.stack([np.roll(np.tile(np.arange(8), 8), s) for s in range(8)])
m = builder.build("llama", 8, d=32, heads=4, kv=2, layers=2, hidden=128)             # 1. build from scratch...
train.fit(m, lambda r: (seqs,), train.lm_loss, 250, 0.01)                              #    ...and train it

preserved = [list(seqs[i][:12]) for i in (0, 2, 4, 6)]
m2, rep = edit.edit_fact(m, layer=1, prompt=[1, 2, 3], target=6, preserved=preserved)  # 2. edit one fact, measure retention
print(rep["success"], f"preserved-prompt logit drift = {rep['preserved_max_logit_drift']:.1e}")

scrambled = symmetry.random_symmetry(m, seed=3)                                        # 3. same function, scrambled weights
merged = symmetry.merge_aligned(m, scrambled)                                          #    permutation-aligned merge is lossless
print("aligned merge error:", float(np.abs(merged(seqs[:, :-1]).data - m(seqs[:, :-1]).data).max()))
```

### JAX backend (optional)

```python
import numpy as np, jax.numpy as jnp
from omnia import llama, jaxbackend as jb

m = llama.LlamaLM(8, 32, 4, 2, 2, 64, seed=0); seqs = jnp.array(np.stack([np.roll(np.tile(np.arange(8), 8), s) for s in range(8)]))
params, cfg = jb.to_jax(m); step = jb.make_train_step(cfg, lr=0.3)                      # jit-compiled; runs on GPU/TPU if JAX sees one
for _ in range(100): params, loss = step(params, seqs)
jb.from_jax(params, m); print("loss after JAX training:", round(float(loss), 3))
```

---

## 📊 Evidence

**Cross-validation against independent references** (`python -m unittest tests.test_crossval`; full table with tolerances in [VALIDATION.md](https://github.com/Mohamed2007Sarhan/omnia-surgery/blob/main/VALIDATION.md)):

| Area | Reference | Agreement |
|---|---|---|
| Ridge / OLS / Lasso, KMeans, PCA, scalers, DBSCAN, LOF, KNN/NB | scikit-learn 1.8 | 1e-14 … 1e-10 (DBSCAN ARI = 1.0) |
| SGD(+momentum/Nesterov), Adam, AdamW, Lion, LAMB, RMSProp, Adagrad | optax 0.2.8 | ≤ 1e-15 |
| Conv2D forward + both gradients; GELU/SiLU/softmax; cross-entropy; BCE; Huber | JAX autodiff | ≤ 2e-13 |
| **GGUF dequantisation, 13 block types** | official `gguf-py` | **bit-exact (0.0)** |
| safetensors (F32/F16/BF16/I64/U8), both directions | official `safetensors` | identical |
| ONNX interpreter, 50 of 52 operators individually | onnxruntime 1.24 | ≤ 1e-4 |
| GPT-2 / Llama (MHA, GQA, MQA, bias, θ, ε) / Mistral window / Gemma | **Hugging Face Flax implementations** | 1e-15 … 2e-7 |
| Whole-model forward **and hand-written backward** | JAX `jax.grad` | ≤ 5e-15 |

Validation also surfaced quirks *of the references* (documented, not hidden): Flax Llama/Mistral/Gemma hard-code RoPE base 10 000; Flax Mistral treats `sliding_window=None` as "attend to self only". omnia exposes both sliding-window conventions (`window_style`).

**Selected experiments** (toy scale, fixed seeds; regenerate with `python paper/make_results.py <part>`):

| Experiment | Result |
|---|---|
| Permutation-aligned Transformer merge vs naive averaging | error **0.0** vs 10.6 (GPT-style) / 15.5 (Llama-style) |
| Sequential editing: plain vs LyapLock-style (6 edits) | preserved-prompt logit drift **7.79 → 5e-7**; 3 applied, 3 *rejected* because they conflict with protected knowledge |
| Gated self-improvement (3-digit reversal, hold-out problems) | hold-out accuracy **0% → 53.5%** in 10 generations (3 accepted, 7 rolled back) |
| JAX-jit vs NumPy forward (d=64, 2 layers, single CPU) | 237k vs 34k tokens/s (≈ 6.9×; timings vary run to run) |

---

## ⚠️ Honest limitations

* **Toy-scale evidence.** Experiments use small synthetic tasks. Loaders are validated against Hugging Face's *Flax* models with random weights — **not yet on real pretrained checkpoints or against the PyTorch implementations**. Run `python compare_with_transformers.py gpt2` (needs `torch` + `transformers`) and please report the result.
* **Speed.** The NumPy core is slow by design. Use the JAX backend for anything non-trivial. No custom kernels.
* **AutoArch can classify and map; it cannot execute everything.** Runnable: Llama-family decoders (+ HF GPT-2 names). Everything else gets analysis + weight-space operations (`GenericModel`) and, if exported to ONNX, interpreter support for 52 operators (50 individually validated against onnxruntime).
* **Calibration needs data.** Resolution of ambiguities improves with calibration tokens (table above); factors the data cannot identify are reported, not guessed.
* **Edits and merges can silently change behaviour — including safety behaviour.** Always evaluate afterwards. Parameter-merging two models fine-tuned on *unrelated* tasks failed in our toy experiments; ensembling worked.
* **Not included, on purpose:** tooling to strip safety training/refusals from models ("abliteration").

---

## 🧭 What to use when

| If you need… | Reach for |
|---|---|
| Train / serve large models, GPU kernels, ecosystem | PyTorch, JAX, 🤗 Transformers, vLLM, llama.cpp |
| Parameter-efficient fine-tuning | PEFT |
| Declarative merging recipes for large HF checkpoints | mergekit |
| Classical ML at scale | scikit-learn |
| **Understand an unfamiliar checkpoint, apply *provably exact* transformations, edit with bounded retention, check what a merge/edit changed, read GGUF/safetensors/ONNX without heavy dependencies** | **omnia** |

omnia deliberately *validates against* these projects rather than competing with them.

---

## 🚀 Install

```bash
pip install omnia-surgery                 # core: numpy + scipy
pip install "omnia-surgery[jax]"          # + JAX backend
pip install "omnia-surgery[validate]"     # + everything needed to re-run the cross-validation suite
python -m omnia info model.gguf           # CLI: info | merge | taskarith   (safetensors / GGUF / ONNX / NPZ)
python -m unittest discover -s tests -t . # run the test-suite
```

Project map: `autoarch` · `weightspace` · `builder` · `nn/nn2/nn3` · `llama/gpt2` · `edit` · `symmetry` · `fold` · `fuse` · `modify` · `selfimprove` · `paradigms` · `jaxbackend` · `formats/ggml_quants/onnx_reader/io` · `cla` · `catalog`. Generated API docs: [docs/API.md](https://github.com/Mohamed2007Sarhan/omnia-surgery/blob/main/docs/API.md) · honest status per requirement: [AUDIT.md](https://github.com/Mohamed2007Sarhan/omnia-surgery/blob/main/AUDIT.md) · research paper: [paper/](https://github.com/Mohamed2007Sarhan/omnia-surgery/blob/main/paper/).

---

## 🗺️ Roadmap

Real-checkpoint verification (PyTorch comparison) · more runnable families through AutoArch (Mixtral/MoE, Phi, GPT-NeoX fused-QKV, Mamba) · YaRN / dynamic RoPE · larger-scale evaluation of calibration-based resolution · ONNX operator coverage (RNN/LSTM, attention ops) · GPU-backed editing.

---

## 📝 Citation

```bibtex
@software{sarhan2026omnia,
  author  = {Sarhan, Mohamed},
  title   = {omnia-surgery: a model-surgery and verification toolkit with structural architecture understanding},
  year    = {2026},
  url     = {https://github.com/Mohamed2007Sarhan},
  note    = {Version 0.10, MIT licence}
}
```

## 👤 Author

**M. Sarhan** — [ORCID 0009-0005-9766-6267](https://orcid.org/0009-0005-9766-6267) · [GitHub @Mohamed2007Sarhan](https://github.com/Mohamed2007Sarhan) · [Website](https://mohamed-sarhan-2007.vercel.app) · [LinkedIn](https://www.linkedin.com/in/mohamed-sarhan-a18530383) · [Kaggle](https://www.kaggle.com/mohamedsarhanhamed) · ✉ prof7mohamedsarhan@gmail.com

Related projects by the author: **NeuroScalpel** (weight-editing toolkit), **SIRA** (self-improving research agent), **CLA** (Clean Layer Architecture draft) — omnia re-implements the *ideas* of the first two as tested library components (ROME-style editing with a Lyapunov-inspired bounded-retention controller; SIRA-style gated self-improvement) and a runtime inspired by the third. *(Note: "CLA" here is unrelated to Cross-Layer Attention, which omnia also supports as `cla_lm` / `transform.to_cla`.)*

## 🙏 Acknowledgements

Validated against **scikit-learn, JAX, optax, onnx/onnxruntime, safetensors, gguf-py (llama.cpp), 🤗 Transformers (Flax)**. LyapLock (Wang et al., EMNLP 2025), AlphaEdit (Fang et al., ICLR 2025), ROME (Meng et al., NeurIPS 2022), Cross-Layer Attention (Brandon et al., NeurIPS 2024) and the merging literature (TIES, DARE, Git Re-Basin, task arithmetic, Fisher merging, mergekit) inspired the corresponding components — omnia's implementations are independent re-derivations; where they are *inspired by* rather than *reproductions of* a paper, the docstring says so. MIT licensed.

---

<div dir="rtl">

## 🇪🇬 بالعربي، باختصار

**omnia-surgery** مكتبة بايثون لـ"جراحة الموديلات والتحقق منها": بتفهم أي موديل جديد من شكل الـtensors بتاعته (حتى لو الأسماء عشوائية)، وتعمل عليه تحويلات **دقيقة رياضياً** (توسيع، تعميق، طيّ الـnorms، دوران، تناظرات)، وتعدّل معلومة جواه مع قياس أثرها على المعرفة القديمة، وتدمج موديلات، وتشغّل حلقة تحسين ذاتي لا تقبل الجيل الجديد إلا بإثبات إحصائي. كل حاجة فيها متقارنة بمكتبات مرجعية حقيقية، وكل عملية عليها وسم صريح: دقيقة / تقريبية / إحصائية / متعلّمة / مقترحة.

**بصراحة:** النواة NumPy (بطيئة عمداً علشان تتراجع)، والأدلة على نطاق صغير، ولسه ما اتجربتش على أوزان حقيقية من PyTorch. هي مش بديل عن PyTorch ولا Hugging Face، هي الأداة اللي بتستخدمها لما عايز **تفهم وتغيّر وتتحقق**.

</div>
