Metadata-Version: 2.4
Name: gbra
Version: 0.1.3
Summary: GBRA (Gember-Berke Rank Adaptation): DoRA-style fine-tuning with a buffered, lazily refreshed weight norm.
Author: Berke T. Adanc
License: MIT
Keywords: lora,dora,peft,fine-tuning,llm
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: torch>=2.0
Requires-Dist: safetensors>=0.4
Provides-Extra: hf
Requires-Dist: transformers>=4.40; extra == "hf"
Provides-Extra: 4bit
Requires-Dist: bitsandbytes>=0.43; extra == "4bit"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: transformers>=4.40; extra == "test"

# GBRA: Gember-Berke Rank Adaptation

*Pronounced "Gember RA". A GEMBER && Apex Logiç Studio project by Berke T. Adanç.*

GBRA is a DoRA-style parameter-efficient fine-tuning method. It keeps DoRA's split of each weight into a learned **magnitude** and a low-rank-updated **direction**, but **buffers the weight norm** instead of recomputing it in every forward pass.

```
DoRA:  W' = m · (W + s·BA) / ‖W + s·BA‖     ← norm recomputed every forward (and again during gradient-checkpoint recompute)
GBRA:  W' = m · (W + s·BA) / n               ← n is a stored buffer, refreshed every K optimizer steps
```

**Why it helps:** With gradient accumulation, the weights only change once per optimizer step. Recomputing the norm for every micro-batch repeats the same work many times. GBRA computes it once and reuses it.

## Install

```bash
pip install gbra             # core
pip install "gbra[hf]"       # + Hugging Face Trainer callback
pip install "gbra[4bit]"     # + 4-bit (bitsandbytes) base models
```

## Usage

```python
from transformers import AutoModelForCausalLM, Trainer
from gbra import apply_gbra, GBRACallback, save_gbra, merge_gbra

model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
model = apply_gbra(model, r=16, alpha=16)          # wraps q/k/v/o/gate/up/down projections

trainer = Trainer(model=model, ..., callbacks=[GBRACallback(refresh_every=10)])
trainer.train()

save_gbra(model, "my_adapter")                     # small adapter (A, B, m, n)
merge_gbra(model)                                  # fold into plain nn.Linear for export
```

Turkish aliases are also available: `gbra_ekle`, `tum_normlari_yenile`, `gbra_kaydet`, `gbra_yukle`, `gbra_birlestir`, `gbra_param_gruplari`, `birlestir_yeniden_baslat`.

### New in 0.1.3

```python
from gbra import apply_gbra, refresh_norms, export_gguf

# multimodal models (e.g. Gemma 4 E4B): adapt only the language model
model = apply_gbra(model, targets="auto", exclude=("vision_tower", "audio_tower"))

# ... train ...

# one call: merge GBRA -> HF -> GGUF -> Q4_K_M (opens in LM Studio / Ollama / llama.cpp)
export_gguf(model, "out", tokenizer, llama_cpp="C:/llama.cpp", quant="Q4_K_M")
```

```bash
# or from the command line, with a saved adapter
python -m gbra.gguf --base google/gemma-4-E4B-it --adapter my_adapter --out out --llama-cpp C:/llama.cpp --quant Q4_K_M
```

- **`export_gguf` / `gguf_olarak_kaydet`.** Merges GBRA, saves a plain HF model, runs llama.cpp's `convert_hf_to_gguf.py` and `llama-quantize`, and removes the large intermediate files (`keep_intermediate=True` keeps them). `quant=None` or `"f16"` writes an unquantized GGUF. Needs a llama.cpp checkout (`git clone https://github.com/ggml-org/llama.cpp`, `pip install -r requirements.txt`) and the `llama-quantize` program; the path can also come from the `LLAMA_CPP` environment variable.
- **`exclude`.** Names or regexes of layers that are never wrapped. A name also skips everything inside it, so `exclude=("vision_tower",)` leaves the whole vision tower untouched. Saved in the adapter config.
- **Fix: `merge_gbra` keeps the base dtype.** Bias-free layers (e.g. `o_proj`, `gate_proj`, `up_proj`, `down_proj` in Qwen/Gemma/Llama) used to become float32, which broke bf16/fp16 models after merging.
- **Fix: the end-of-training refresh no longer changes the model.** `GBRACallback(refresh_on_end=True)` now uses `refresh_norms(model, keep_output=True)`: n is set to the real norm and m is rescaled by n_new/n_old, so the output stays exactly the trained one. Before, a final plain refresh changed the model (a lot with `refresh_every=None`).

### New in 0.1.2

```python
from gbra import (apply_gbra, gbra_param_groups, merge_and_restart, refresh_norms,
                  AutoRefresh, GBRACallback, export_peft, export_merged)

# any model, any linear format: every linear layer except output heads; per-layer ranks
model = apply_gbra(model, targets="auto", r=16, alpha=16,
                   rank_pattern={"down_proj": 8}, rslora=True)      # rsLoRA scale alpha/sqrt(r)

opt = torch.optim.AdamW(gbra_param_groups(model, lr=1e-4, b_lr_ratio=4))   # B learns faster (LoRA+ idea)

refresh_norms(model)                       # batched: same-shape layers refreshed together
auto = AutoRefresh(model, tol=1e-3)        # "smart K": refresh only when the norms drifted
...                                        # after each optimizer step: auto.step()
# or with the HF Trainer: callbacks=[GBRACallback(refresh_every="auto")]

merge_and_restart(model, optimizer=opt)    # experimental (ReLoRA-style), non-quantized models only

export_peft(model, "adapter_dora")         # PEFT DoRA format: loads with peft.PeftModel.from_pretrained
export_merged(model, "merged", tokenizer)  # plain fp16 HF model, ready for llama.cpp -> GGUF
```

- **Any linear format.** GBRA only calls the base layer's `forward`, so it also works on bnb 8-bit, HQQ and other quantized linears (the start norm is found by probing the layer, without a float copy of W). bnb 4-bit is dequantized only where that is faster.
- **`targets="auto"`** wraps every linear layer except output heads (`lm_head`, `score`, `classifier`, ...). `rank_pattern` / `alpha_pattern` set per-layer values (exact name, suffix or regex, like PEFT).
- **Batched refresh.** `refresh_norms(model)` groups same-shape layers and refreshes each group with batched matmuls, which removes most per-layer GPU launch overhead.
- **`AutoRefresh` / `refresh_every="auto"`.** Each step it re-computes the exact norm of one layer (round robin, ~1/L of a full refresh) and refreshes everything only if that layer's buffered norm had drifted more than `tol` (or after `max_every` steps).
- **`export_peft`.** Writes a PEFT DoRA adapter. It reproduces the GBRA model exactly, even between refreshes (the exported magnitude is `m·‖W+sBA‖/n`). Train with GBRA, then use the adapter anywhere PEFT DoRA runs.
- **`export_merged`.** Merges GBRA, dequantizes the remaining quantized layers, removes the quantization config and saves a plain Hugging Face model: `python convert_hf_to_gguf.py merged --outtype f16`.

**Cheaper norm refresh (Gram trick).** The buffered norm is now refreshed without ever building the dense `W + s·BA` matrix:

```
‖vᵢ‖² = ‖wᵢ‖² + 2s·(W·Aᵀ)ᵢ·bᵢ + s²·bᵢ·(A·Aᵀ)·bᵢᵀ
```

`‖wᵢ‖²` is cached once (W is frozen) and `W·Aᵀ` is computed by running the frozen base layer on `A`. The result is the same norm (checked against the old method in the tests).

Measured so far (one refresh, r=32 unless noted):

| Setting | Gram vs direct | Extra memory (Gram / direct) |
|---|---|---|
| GPU (RTX 5060), 4-bit, Qwen2.5-7B shapes | **2.7–11.9× faster** | 1.4–7.4 MB / 157–818 MB |
| GPU (RTX 5060), fp16, Qwen2.5-7B shapes | **3.4–13.0× faster** | 1.4–7.4 MB / 157–818 MB |
| CPU, fp32, Qwen2.5-7B shapes | **5.5–6.7× faster** | ~100× less |
| GPU (RTX 5060), 4-bit, Qwen2.5-0.5B (all 168 layers, r=16) | 0.5× (slower: 84 vs 42 ms) | – |

On small layers the extra kernel launches dominate, so `norm_method="auto"` (default) uses Gram everywhere except 4-bit layers with fewer than 8M weights, which keep the direct method. You can force either with `apply_gbra(..., norm_method="gram" | "direct")`. Benchmark script: `bench_gpu_7b.py` (random weights, layer shapes only). These numbers cover the *refresh only*, not a full training step; end-to-end GPU training speed is not measured yet.

## Preliminary results

Qwen2.5-0.5B-Instruct, 3,000 Turkish chat/tool-use examples, 375 optimizer steps (batch 1 × 8 accumulation), r=16, single Kaggle T4, fp16 autocast. Same data, seed and hyper-parameters for every method. DoRA and LoRA via 🤗 PEFT.

| Method | s / step | vs LoRA | Peak memory | Val. loss |
|---|---|---|---|---|
| LoRA | **5.77** | 1.00× | 8.11 GB | 1.6376 |
| DoRA (PEFT) | 9.10 | 1.58× | 8.11 GB | 1.6285 |
| **GBRA K=10** | 6.47 | 1.12× | 8.11 GB | **1.6249** |
| GBRA K=100 | 6.47 | 1.12× | 8.11 GB | 1.6253 |
| GBRA K=never | 6.46 | 1.12× | 8.11 GB | 1.6263 |

**In this run, GBRA was ~29% faster than DoRA per step, with equal or slightly lower validation loss.** A shorter 125-step run gave the same speed ratio.

### Limitations (please read)

- **Single seed, single small model, single dataset.** The loss differences between GBRA variants and DoRA are small (≈0.001–0.004) and may be noise; repeated runs with more seeds are in progress.
- Much of the speed-up comes from **not recomputing the norm per micro-batch**. With no gradient accumulation and no gradient checkpointing, the gap to DoRA should be smaller.
- The comparison is against PEFT's DoRA implementation at the time of testing, not against every possible DoRA implementation.
- 4-bit (bitsandbytes) support is implemented but **has not yet been benchmarked**.
- Unlike PEFT LoRA, GBRA does not currently use fused kernels such as Unsloth's.

## Credits

GBRA builds directly on **DoRA** (Liu et al., 2024, *"DoRA: Weight-Decomposed Low-Rank Adaptation"*) and **LoRA** (Hu et al., 2021). Related ideas on learned scaling vectors appear in (IA)³ and VeRA. The 0.1.2 options follow **rsLoRA** (Kalajdzievski, 2023), **LoRA+** (Hayou et al., 2024) and **ReLoRA** (Lialin et al., 2023). The contribution here is the buffered / lazily refreshed norm, its cheap Gram-trick refresh, and their evaluation.

The core `forward` of `GBRALinear` and the Gram-trick norm formula code were written by Berke T. Adanç. Parts of the surrounding library and tests were developed with the help of an AI assistant.

## Changelog

- **0.1.3**: `export_gguf` (one call to a quantized GGUF, plus `python -m gbra.gguf`); `exclude` option for multimodal models; `refresh_norms(keep_output=True)` and `GBRALinear.normu_esitle()` (output-preserving refresh); fix: `merge_gbra` keeps the base dtype for bias-free layers; fix: `refresh_on_end` keeps the trained model unchanged.
- **0.1.2**: `targets="auto"`, `rank_pattern`/`alpha_pattern`; works with any quantized linear format (bnb 8-bit, HQQ, ...); batched `refresh_norms`; `AutoRefresh` and `GBRACallback(refresh_every="auto")`; `export_peft` (PEFT DoRA adapter, exact); `export_merged` (plain HF model for GGUF); Gram-trick norm refresh (no dense matrix; formula code by Berke T. Adanç), `norm_method` option (small 4-bit layers keep the direct refresh, which was faster there); mixed-precision dtype fix (a 4-bit base no longer turns the activations into fp32); `rslora=True` option; `gbra_param_groups` for separate A/B/m learning rates; experimental `merge_and_restart` (ReLoRA-style, non-quantized models). Adapters saved with 0.1.1 load unchanged.
- **0.1.1**: Python 3.9 compatibility fix in `GBRACallback`; new `refresh_on_end` option (refreshes the norm once more when training ends); README install instructions for PyPI.
- **0.1.0**: First release.

## License

MIT

---

## Türkçe özet

GBRA, DoRA'nın "büyüklük + yön" ayrımını korur, ama ağırlık normunu her adımda yeniden hesaplamak yerine **saklar** ve sadece **K optimizer adımında bir** günceller. Gradient birikimi kullanılan eğitimde ağırlıklar mini-batch'ler arasında değişmediği için DoRA aynı normu tekrar tekrar hesaplar. GBRA bu tekrarı ortadan kaldırır.

**0.1.3'te yeni:** Tek komutla GGUF (`export_gguf` / `gguf_olarak_kaydet`, ya da `python -m gbra.gguf`), çok modlu modellerde görüntü/ses kısımlarını dışarıda bırakan `exclude`, eğitim sonundaki norm yenilemesinin artık modeli değiştirmemesi (`keep_output=True`) ve `merge_gbra`'nın bias'sız katmanları float32'ye çevirme hatasının düzeltilmesi.

0.1.2'de ayrıca: Her modelde otomatik hedef seçimi (`targets="auto"`), katman başına rank, her nicemleme formatıyla çalışma (8-bit, HQQ...), toplu norm yenileme, akıllı K (`AutoRefresh`), PEFT DoRA formatında dışa aktarma (`export_peft`) ve GGUF'a hazır birleştirme (`export_merged`).

Normal (nicemlenmemiş) katmanlarda norm yenileme, dev `W + s·BA` matrisini hiç kurmadan yapılıyor (Gram hilesi). 7B katman boyutlarında CPU'da tek bir yenileme 5.5–6.7 kat daha hızlı ve ~100 kat daha az ek bellek kullandı. GPU'da (RTX 5060) 7B boyutlarında 4-bit katmanlarda 2.7–11.9 kat, fp16'da 3.4–13 kat hızlı ve yüzlerce MB yerine birkaç MB ek bellek kullanıyor. Çok küçük 4-bit katmanlarda (0.5B model) ise eski yöntem daha hızlı olduğu için, onlarda varsayılan olarak eski yöntem kullanılıyor. Ayrıca rsLoRA ölçeği, A/B/m için ayrı öğrenme hızları ve deneysel "birleştir ve yeniden başla" eklendi.

İlk deneyde (Qwen2.5-0.5B, 375 adım, tek seed) GBRA, DoRA'dan **~%29 daha hızlı** ve doğrulama loss'u aynı ya da biraz daha iyiydi. Sonuçlar tek seed'e dayandığı için **ön sonuç** olarak değerlendirilmelidir.
