Metadata-Version: 2.4
Name: gbra
Version: 0.1.4
Summary: GBRA (Gember-Berke Rank Adaptation): DoRA-style fine-tuning with a Gram-formula weight norm (lazy, exact or full-gradient), plus Turkish .gbra training scripts.
Author: Berke T. Adanc
License-Expression: MIT
Keywords: lora,dora,qlora,qdora,peft,fine-tuning,llm,quantization,hqq,turkish,turkce
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
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: 8bit
Requires-Dist: bitsandbytes>=0.43; extra == "8bit"
Provides-Extra: hqq
Requires-Dist: hqq>=0.2; extra == "hqq"
Provides-Extra: quanto
Requires-Dist: optimum-quanto>=0.2; extra == "quanto"
Provides-Extra: torchao
Requires-Dist: torchao>=0.10; extra == "torchao"
Provides-Extra: nicem
Requires-Dist: bitsandbytes>=0.43; extra == "nicem"
Requires-Dist: hqq>=0.2; extra == "nicem"
Requires-Dist: optimum-quanto>=0.2; extra == "nicem"
Requires-Dist: torchao>=0.10; extra == "nicem"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: transformers>=4.40; extra == "test"
Requires-Dist: peft>=0.12; extra == "test"
Dynamic: license-file

# 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 / 8-bit (bitsandbytes) base models
pip install "gbra[hqq]"      # + HQQ 1/2/3/4/8-bit base models
pip install "gbra[quanto]"   # + optimum-quanto int2/int4/int8/float8
pip install "gbra[torchao]"  # + torchao int8/float8
pip install "gbra[nicem]"    # all quantization libraries above
```

## 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.4: fused forward / backward

Nothing to change in your code: `GBRALinear` now runs as **one fused autograd node**. It computes the same formula as before. The explicit forward is kept as `GBRALinear.ileri_acik` (English: `explicit_forward`), and the tests compare the two in every norm mode (float64: outputs and all gradients equal to 1e-10; PEFT DoRA equality still holds). What changed:

- **Fewer passes over the activations.** The LoRA product is added inside the base matmul (`addmm`), the scale `m/n` and the bias in one more kernel: 1 pass over the `tokens × out` output in the forward instead of 3–4, about 2 instead of about 5 in the backward. `dL/dx` comes out of one fused matmul (`dL/dpre·W + dL/d(xAᵀ)·A`).
- **Less activation memory.** Bias-free layers save their *output* for the backward instead of a second `tokens × out` tensor (`dL/dm = Σ g·y / m`, `dL/dn = −Σ g·y / n`). The next op usually keeps that same tensor (SiLU after `gate_proj`, the product after `up_proj`), so it is shared instead of doubled. Per layer, GBRA now keeps as much as a plain frozen layer.
- **Less CPU work.** One autograd node per layer (`m/n` is formed inside), and `A`, `B` are cast to bf16 once per optimizer step instead of once per micro-batch. On a 0.5B model the training step is CPU-bound (Python and kernel launches), so this is real speed.
- **More accurate gradients.** `dL/dA` and `dL/dB` leave the matmul in float32 (no bf16 rounding of the gradient), and `dL/dm`, `dL/dn` are summed in float32.
- **Quantized bases too** (bnb 4/8-bit, HQQ, ...): their own forward gives `x·Wᵀ`, and everything after it is fused.

```python
model = apply_gbra(model, r=16)                     # fused (default)
model = apply_gbra(model, r=16, fused=False)        # explicit forward (no fusion)
model = apply_gbra(model, r=16, save_output=False)  # only if your model changes a wrapped layer's output in place
```

With `save_output=True`, an in-place change of a bias-free layer's output makes autograd raise an error in the backward. The gradients are never silently wrong. The fused node does not support double backward (`create_graph=True` through a GBRA layer); use `fused=False` for that.

Measured on an RTX 5060 8 GB (Windows, torch 2.11), Qwen2.5-0.5B-Instruct, bf16, r=16, all 7 projections, batch 2 × 4 accumulation × 512 tokens (random tokens), median of 3 × 8 steps. Same machine and script for both; *explicit* is the forward of the first 0.1.4 build (now `fused=False`), measured from a copy of that code (`bench/bench_014.py --src`):

| Method | explicit s/step | fused s/step | speed-up | vs LoRA (fused) | explicit peak GB | fused peak GB |
|---|---|---|---|---|---|---|
| LoRA (PEFT) | 0.908 | 0.918 | – | 1.00× | 5.94 | 5.94 |
| GBRA lazy | 1.002 | **0.871** | 1.15× | **0.95×** | 5.97 | **5.47** |
| GBRA exact (= DoRA) | 1.025 | **0.893** | 1.15× | **0.97×** | 5.97 | **5.48** |
| GBRA full | 1.101 | **0.951** | 1.16× | 1.04× | 6.03 | **5.54** |
| DoRA (PEFT) | 2.41* | 2.70* | – | 2.95× | 7.89 | 7.89 |

\* PEFT DoRA filled the 8 GB card here (Windows then spills into system memory), so its time is not reliable. LoRA's own time varied by about 3% between runs (0.89–0.92 s).

Two more settings, same script:

| Setting | GBRA lazy explicit → fused | exact | full | LoRA (PEFT) | DoRA (PEFT) | peak GB, lazy explicit → fused |
|---|---|---|---|---|---|---|
| batch 1 × 8 accumulation × 512 (as in `kiyas_014`) | 1.936 → **1.652 s** (1.17×) | 1.929 → **1.647** (1.17×) | 2.046 → **1.721** (1.19×) | 1.708 | 2.632 | 3.60 → **3.34** (LoRA 3.56, DoRA 4.52) |
| 4-bit nf4 base (QLoRA / QDoRA style), batch 2 × 4 × 512 | 1.165 → **1.098 s** (1.06×) | 1.226 → **1.148** (1.07×) | 1.316 → **1.235** (1.07×) | 1.042 | 2.60* | 5.65 → **5.17** (LoRA 5.42) |

At batch 1 × 8, `exact` (the same model as PEFT DoRA) is now **1.60× faster than PEFT DoRA** and uses 1.18 GB less memory. With a 4-bit base the gain is smaller, because the base matmul and its backward run in bitsandbytes' own code and only the part after it is fused. All tables and raw numbers: `bench/SONUCLAR.md`, `bench/bench_*.json`.

### New in 0.1.4: every bit width (1 to 32)

GBRA trains on top of any quantized base layer. 0.1.4 recognises and dequantizes every common format itself, and `gbra.nicemle` (English: `gbra.quantize_model`) quantizes a model's linear layers in place with any of them:

```python
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.bfloat16)
gbra.nicemle(model, bit=3)                           # HQQ 3-bit, layer by layer onto the GPU
gbra.nicemle(model, bit=4, yontem="fp4")             # or: "nf4", "int8", "hqq", "quanto", "torchao", "float8"
model = apply_gbra(model, r=16)                      # then train as usual; export_merged gives a plain model
```

Models loaded quantized by transformers (`BitsAndBytesConfig`, `QuantoConfig`, `TorchAoConfig`) work directly. Tested end to end on an RTX 5060 with Qwen2.5-0.5B-Instruct (load, attach GBRA, start norm = norm of the dequantized weight, fused = explicit path, 8 training steps, save/load gives the identical output, merge gives a plain bf16 model; `bench/bit_tarama.py`, `tests/test_bit.py`):

| bit | method (`yontem`) | library | default for this bit width |
|---|---|---|---|
| 8 | `int8` (LLM.int8), `hqq`, `quanto`, `torchao`, `float8` | bitsandbytes / hqq / optimum-quanto / torchao | `int8` |
| 4 | `nf4`, `fp4` (with or without double quantization), `hqq`, `quanto` | bitsandbytes / hqq / optimum-quanto | `nf4` (QLoRA) |
| 3 | `hqq` | hqq | `hqq` |
| 2 | `hqq`, `quanto` | hqq / optimum-quanto | `hqq` |
| 1 | `hqq` | hqq | `hqq` |
| 16 / 32 | no quantization | – | – |

In `.gbra` files: `bit: 4`, `nicemleme: hqq`, `çift nicemleme: evet` (bnb 4-bit double quantization), `grup boyutu: 64` (HQQ / torchao). `dört bit: evet` still works (= `bit: 4`). Impossible combinations are reported before anything is loaded, with the line number and what to write instead:

```
Hata: egitim.gbra dosyasında 1 hata var:
  satır 9: 'nf4' 3-bit yapamaz (4 bit yapabilir). 3-bit için: nicemleme: hqq
```

Fixes found on the way: `export_merged` / the `.gbra` `birleştir.` command failed for bitsandbytes models with transformers 5 (*"You cannot cast a bitsandbytes model in a new dtype"*); merging a quantized base now keeps the model's dtype (bnb 8-bit layers became fp16 in a bf16 model); bnb 8-bit weights are dequantized exactly from their int8 codes and scales (1.0% weight error vs. 14.8% when rebuilt through the int8 matmul, as before).

Not covered: torchao int4 (needs the `mslk` / fbgemm kernels, not available on Windows); GPTQ / AWQ checkpoints (not tested; they work if their layers support a backward pass to the input). HQQ is applied with `gbra.nicemle`, because transformers 5 cannot load HQQ models yet. Very low bit widths cost quality: on the test model the start loss rose from 2.6 (bf16) to 4.6 (3-bit), 8.9 (2-bit) and 15.9 (1-bit), and GBRA has to recover that.

### New in 0.1.4: three norm modes, one formula

The Gram formula (Berke T. Adanç) computes the exact row norm from small tensors only:

```
‖v_i‖² = ‖w_i‖² + 2s·(W·Aᵀ)_i·b_i + s²·b_i·(A·Aᵀ)·b_iᵀ        (W·Aᵀ is r×out, A·Aᵀ is r×r)
```

It is cheap enough to use at every step, and it is differentiable without ever building the `out × in` matrix. 0.1.4 uses it for three modes:

| `norm_mode` | Turkish | What the forward divides by | Same model as |
|---|---|---|---|
| `"lazy"` (default) | `"tembel"` | buffer `n`, refreshed every K steps | GBRA ≤ 0.1.3 |
| `"exact"` | `"kesin"` | exact norm, **detached**, cached once per optimizer step | PEFT DoRA (verified in the tests: outputs and all gradients match PEFT 0.22 to 1e-10) |
| `"full"` | `"tam"` | exact norm **with its gradient** | DoRA's Eq. 5 *without* the detach approximation of the DoRA paper (Sec. 4.3) |

Why `"full"` matters: DoRA's motivation is that the gradient w.r.t. the direction `V = W + s·BA` is projected orthogonally to `V`, so magnitude and direction are learned separately. The usual detach (PEFT, the DoRA paper's memory trick) breaks that projection; `"full"` restores it exactly (tested: cosine between gradient and `V` is ~1e-16 vs. up to 0.7 with the detach), at the cost of one small extra pass over `W` per optimizer step. **Whether this improves quality has not been measured yet.**

```python
model = apply_gbra(model, r=16, norm_mode="full")

for step in range(steps):
    with gbra.norm_step(model):                  # Turkish: gbra.norm_adimi(model)
        for batch in micro_batches:              # gradient accumulation
            (model(**batch).loss / len(micro_batches)).backward()
    torch.nn.utils.clip_grad_norm_(params, 1.0)  # after the block
    optimizer.step(); optimizer.zero_grad()
```

`norm_step` computes all exact / full norms at the start of the step **in batches of same-shape layers** (168 layers of Qwen2.5-0.5B become 6 groups) and builds each norm graph **once per optimizer step** and backpropagates the accumulated `dL/dn` through it once when the block ends, so the cost does not grow with the number of micro-batches (gradients are identical to the per-forward version, tested). Counted on a Qwen2.5-0.5B-shaped model, the extra operations per step for the norm dropped from 2,856 to 240 (`exact`) and from 3,024 to 584 (`full`). Without the block, `"full"` simply rebuilds the small norm graph in every forward, which is always correct. With the HF `Trainer`, use `"full"` without `norm_step`: the Trainer clips gradients before its last callback hook, so there is no safe place to finish the deferred backward.

**Precise norm (`precise_norm=True`, default).** For bf16/fp16 weights, `W·Aᵀ` is now computed with float32 accuracy: `A` is split into two half-precision parts multiplied in one matmul with a float32 output (`torch.mm(..., out_dtype=torch.float32)`), or `W` is upcast block by block where that is not available. Measured relative norm error in bf16 (CPU emulation, 1024×1024, r=16):

| Update size vs. ‖W‖ | PEFT DoRA (bf16 dense) | GBRA 0.1.3 | GBRA 0.1.4 |
|---|---|---|---|
| 1% | 2.9e-4 | 2.3e-6 | 1.5e-7 |
| 10% | 3.0e-4 | 2.7e-5 | 1.4e-7 |
| 50% | 3.4e-4 | 1.1e-4 | 1.4e-7 |
| strong cancellation (BA ≈ −W) | 3.0e-4 | 3.7e-4 | 1.6e-7 |

This is a robustness property; a 3e-4 norm error may well be harmless for training.

**Turkish `.gbra` training scripts.** Train without writing Python (see *Türkçe .gbra dosyaları* below):

```
model: Qwen/Qwen2.5-0.5B-Instruct
veri: sohbetler.jsonl
tur: 3
egit.
dene: "Merhaba!"
```

```bash
gbra calistir egitimim.gbra      # run      (also: python -m gbra calistir ...)
gbra kontrol egitimim.gbra       # check only, no training
gbra ornek                       # write an example file
```

Or in plain Turkish, without `ad: değer` lines: a `.gbra` file may contain sentences, and `gbra yap "..."` runs one directly. A rule-based parser (no AI model, no internet) turns them into settings and commands and shows what it understood before running; typos like `C/desktop` or `.jhson` are fixed and reported, and anything it does not understand is an error, never a guess:

```
https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct
bu modeli 4 bit yapıp gbra tam ile masaüstündeki model klasöründeki veri.json ile eğit,
sonra "Merhaba!" diye sor ve birleştir.
```

```bash
gbra yap "Qwen/Qwen2.5-0.5B-Instruct modelini veri.jsonl ile 3 tur eğit"
gbra cevir egitimim.gbra yeni.gbra     # write the sentences as ad: değer lines
```

### 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; for end-to-end training steps see *New in 0.1.4: fused forward / backward* and `bench/bench_014.py`.

## 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.
- Quantized bases: speed was measured for bnb 4-bit only (`bench/SONUCLAR.md`); the other formats were tested for correctness, not speed.
- GBRA's fused node is built from standard PyTorch ops (cuBLAS matmuls); it does not use custom Triton/CUDA kernels such as Unsloth's.
- **0.1.4:** the quality effect of `norm_mode="full"` is **not measured yet**. The `out_dtype` matmul of the precise norm now runs and is tested on a real GPU (RTX 5060, `tests/test_birlesik.py`); on GPUs without it, the block-upcast fallback is used. The precise path covers plain (bf16/fp16/fp32) layers; quantized layers keep the 0.1.3 computation.
- **0.1.4, speed:** the numbers come from one GPU (RTX 5060, Windows) and one model size end to end (0.5B); 7B shapes were measured on single layers only. The 0.5B step is CPU-bound, so a faster CPU or a larger model shifts the ratios. PEFT ran with its defaults (float32 adapter weights, no autocast), so its LoRA path computes in float32; under autocast the LoRA comparison can differ. In bf16 the fused path is not bit-identical to the explicit forward (fewer roundings), only equal up to bf16 precision.

## 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.4**: `norm_mode="lazy" | "exact" | "full"` (Turkish: `tembel` / `kesin` / `tam`), all on the Gram formula; `"exact"` equals PEFT DoRA and caches the norm per optimizer step; `"full"` adds the gradient through the norm (DoRA without the detach approximation); `gbra.norm_step(model)` / `gbra.norm_adimi(model)` for a deferred norm backward with gradient accumulation; `precise_norm=True`: float32-accurate `W·Aᵀ` for half-precision weights; Turkish `.gbra` training scripts with a `gbra` command (`calistir`, `kontrol`, `ornek`, `yap`, `cevir`), also in plain Turkish sentences (`gbra.dogal`, rule-based; shows what it understood before running) and `gbra.kolay.Oturum` (train / save / load / try / merge / compare against PEFT DoRA and LoRA); `norm_step` computes exact / full norms in batches of same-shape layers (batched float32-accurate `W·Aᵀ` with one hi/lo split per group); `kiyasla` with several seeds (`tohumlar`, mean ± std); ChatML `text` data trains on the assistant turns only, and the loss runs `lm_head` on the learned tokens only; fix: float64 base layers now keep a float64 norm; fix: `normu_esitle` / `refresh_on_end` no longer rescale `m` in exact/full mode. fused forward/backward for every GBRA layer (one autograd node: LoRA product inside the base matmul, one elementwise pass for scale and bias, one fused matmul for `dL/dx`); bias-free layers save their output instead of a second activation (activation memory per layer halved); `A`/`B` cast to the compute dtype once per optimizer step; float32 `dL/dA`, `dL/dB`, `dL/dm`; quantized bases fused after their own forward. 0.5B training step 1.15× faster than the explicit forward in all three norm modes, peak memory −0.5 GB. Options `fused` / `save_output` (`apply_gbra` and `GBRALinear`); the explicit forward stays as `GBRALinear.ileri_acik`. `bench/bench_014.py` (layer and training benchmark, any gbra version via `--src`) and `bench/karsilastir.py`. GPU tests for bnb 4-bit and the float32-output matmul. Every bit width: `gbra.nicemle` / `quantize_model` (bnb nf4 / fp4 / double quant / int8, HQQ 1–8 bit, quanto int2/int4/int8/float8, torchao int8/float8), quantized tensor subclasses (quanto, torchao) recognised and dequantized, exact bnb 8-bit dequantization, `.gbra` settings `bit`, `nicemleme`, `cift_nicemleme`, `grup_boyutu` (checked before loading), the base quantization recorded in `gbra_config.json`, `bench/bit_tarama.py`; fix: `export_merged` / `birleştir.` with bitsandbytes on transformers 5; fix: merging a quantized base keeps the model dtype. `norm_mode` and `precise_norm` are saved with the adapter; 0.1.x adapters load unchanged (as `"lazy"`).
- **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.

**0.1.4'te yeni:** Gram formülü artık üç modda kullanılıyor. `norm_mode="tembel"` eski davranış (norm K adımda bir yenilenir). `"kesin"` her adımda tam doğru normu kullanır ve PEFT'in DoRA'sıyla birebir aynı modeldir (testlerde PEFT'in kendisiyle karşılaştırıldı: çıktılar ve bütün gradyanlar 1e-10 hassasiyetle aynı). `"tam"` ise norma gradyan da akıtır, yani DoRA makalesindeki yaklaşım (detach) olmadan DoRA'nın tam halidir. Bu, ancak Gram formülü sayesinde ucuz: dev `W + s·BA` matrisi hiç kurulmuyor. Gradient birikimiyle `with gbra.norm_adimi(model):` bloğu, norm grafiğini adım başına bir kez kurar. bf16 katmanlarda norm artık float32 hassasiyetinde hesaplanıyor (PEFT'ten ~2000 kat, 0.1.3'ten 15–2300 kat daha isabetli). `"tam"` modun kaliteye etkisi henüz ölçülmedi.

**0.1.4'te ayrıca: birleşik ileri/geri geçiş.** Kodunda hiçbir şey değiştirmen gerekmiyor. GBRA katmanı artık ileri ve geri geçişi **tek bir birleşik adımda** yapıyor. Formül aynı: eski açık hali `GBRALinear.ileri_acik` olarak duruyor ve testler ikisini her norm modunda karşılaştırıyor (float64'te çıktılar ve bütün gradyanlar 1e-10 hassasiyetle aynı). LoRA çarpımı ana matris çarpımının içine katılıyor, ölçek ve bias tek işlemde ekleniyor. Bias'sız katmanlar geri geçiş için ikinci bir aktivasyon kopyası yerine çıktının kendisini saklıyor, yani katman başına aktivasyon belleği yarıya indi. A ve B bf16'ya her mikro-partide değil, optimizer adımı başına bir kez çevriliyor. A/B gradyanları float32 çıkıyor. 4-bit (bnb) katmanlar da birleşik yoldan geçiyor. RTX 5060'ta Qwen2.5-0.5B eğitim adımı üç modda da açık (eski) ileri geçişten **1.15 kat hızlı**, tepe bellek 0.5 GB az. Bu ölçümde tembel ve kesin mod PEFT LoRA'dan bile biraz hızlı çıktı (0.95× ve 0.97×). Eski davranış için `apply_gbra(..., fused=False)` kullanabilirsin. Ölçüm betiği: `bench/bench_014.py`, hepsi birden: `bench/hepsini_olc.ps1`.

**0.1.4'te ayrıca: her bit genişliği.** GBRA artık 1'den 32'ye kadar her bitte nicemlenmiş bir taban model üzerinde eğitim yapabiliyor. `.gbra` dosyasında `bit: 4` yazman yeterli. Yöntemi de seçebilirsin: `nicemleme: hqq`. Python'dan `gbra.nicemle(model, bit=3)` ile aynı şey yapılır.

| bit | yöntemler (`nicemleme:`) | varsayılan |
|---|---|---|
| 8 | `int8` (bitsandbytes), `hqq`, `quanto`, `torchao`, `float8` | `int8` |
| 4 | `nf4`, `fp4` (+ `çift nicemleme: evet`), `hqq`, `quanto` | `nf4` (QLoRA) |
| 3 | `hqq` | `hqq` |
| 2 | `hqq`, `quanto` | `hqq` |
| 1 | `hqq` | `hqq` |

Hepsi RTX 5060'ta gerçek Qwen2.5-0.5B ile uçtan uca denendi: yükle, eğit, kaydet/yükle (birebir aynı çıktı), `birleştir.` (düz bf16 model). Olmayan bir kombinasyonu (ör. `bit: 3` + `nicemleme: nf4`) model yüklenmeden, satır numarası ve öneriyle söyler. Yol üstünde iki hata da düzeldi: 4-bit/8-bit modelde `birleştir.` transformers 5 ile çöküyordu, ve 8-bit ağırlıklar artık int8 kodlarından birebir açılıyor (önceki yöntemde %14.8 hata, şimdi %1.0). torchao int4 Windows'ta çalışmıyor (`mslk` gerekiyor). Bit azaldıkça kalite düşer: denemede başlangıç kaybı bf16'da 2.6, 3-bit'te 4.6, 2-bit'te 8.9, 1-bit'te 15.9 idi; GBRA bunu eğitimle geri kazanmaya çalışır.

### Türkçe .gbra dosyaları

Python bilmeden model eğitmek için. Bir metin dosyasına (`egitimim.gbra`) ayarları ve komutları yaz:

```
# '#' ile başlayan satırlar açıklamadır.
model: Qwen/Qwen2.5-0.5B-Instruct    # Hugging Face model adı ya da klasör
veri: sohbetler.jsonl                 # {"soru": "...", "cevap": "..."} satırları
çıktı: benim_modelim
tur: 3
parti: 4
öğrenme hızı: 0,0002
norm modu: tembel                     # tembel / kesin / tam

eğit.
dene: "Merhaba, kendini tanıtır mısın?"
```

Sonra terminalde:

```bash
gbra calistir egitimim.gbra      # çalıştır
gbra kontrol egitimim.gbra       # sadece kontrol et (eğitim yapmadan)
gbra ornek                       # örnek bir dosya oluştur
gbra yap "X modelini veri.jsonl ile eğit"   # dosyasız, düz Türkçe tek cümle
gbra cevir egitimim.gbra yeni.gbra       # düz Türkçe cümleleri ayar satırlarına çevir
```

- **Ayarlar** `ad: değer`, **komutlar** `komut.` şeklinde yazılır. Türkçe karakterli ya da karaktersiz, büyük ya da küçük harf fark etmez (`öğrenme hızı` = `ogrenme_hizi`). Ondalık sayılar virgülle de yazılabilir (`0,0002`).
- **Komutlar:** `egit.` (eğit ve kaydet), `dene: "metin"` (cevap üret), `kaydet.`, `yukle: klasör` (kaydedilmiş adaptörü yükle), `birlestir.` (tam model olarak kaydet), `kiyasla: gbra, kesin, tam, dora, lora` (aynı veri ve tohumlarla hız / bellek / kayıp tablosu, `kiyas_sonuclari.md`; `tohumlar: 0, 1, 2` ile her yöntem 3 kez koşar ve tablo ortalama ± sapma gösterir). Not: `kesin` ile DoRA aynı modeldir, ama adaptörün rastgele başlangıcı farklı çekildiği için kayıpları birebir aynı çıkmaz; bu yüzden birkaç tohumun ortalamasını karşılaştır.
- **Veri biçimleri:** `.jsonl`, `.json`, `.csv`, `.txt`. Alanlar: `text` / `metin`, `soru` + `cevap`, `instruction` + `output` (Alpaca), `talimat` + `çıktı`, `prompt` + `completion`, ya da `messages` (sohbet). Soru-cevap verisinde ve `text` alanı hazır bir ChatML sohbeti olduğunda (`<|im_start|>assistant ...`) varsayılan olarak sadece asistanın cevaplarından öğrenilir (`sadece_cevap: hayır` ile kapatılır). Kayıp sadece bu token'lar üzerinden hesaplanır, kelime tahmini de sadece onlar için yapılır (152 bin kelimelik Qwen sözlüğünde büyük bellek ve hız kazancı).
- **Dosyanın tamamı eğitimden önce kontrol edilir.** Hatalar satır numarası ve öneriyle gösterilir, böylece 10. satırdaki bir yazım hatası bir saatlik eğitimi boşa harcatmaz:

```
Hata: egitimim.gbra dosyasında 2 hata var:
  satır 2: 'modl' diye bir ayar yok. Bunu mu demek istedin: 'model'?
  satır 5: 'parti' bir tam sayı olmalı (örnek: parti: 3), ama 'dört' yazılmış.
```

Bütün ayarlar: `model`, `veri`, `dogrulama` (oran, varsayılan 0.05), `cikti`, `tur`, `adim`, `parti`, `biriktirme`, `ogrenme_hizi`, `isinma`, `kirpma`, `rank`, `alfa`, `rslora`, `hedefler` (`varsayilan` / `hepsi` / liste), `norm_modu`, `yenileme` (tembel modda K), `hassas_norm`, `maks_uzunluk`, `sadece_cevap`, `bit` (32 / 16 / 8 / 4 / 3 / 2 / 1), `nicemleme` (otomatik / nf4 / fp4 / int8 / hqq / quanto / torchao / float8), `cift_nicemleme`, `grup_boyutu`, `dort_bit` (= `bit: 4`), `bellek_tasarrufu`, `tohum`, `tohumlar` (kiyasla için), `kayit_araligi`, `uzunluk`, `sicaklik`.

#### Düz Türkçe yazmak

Ayarları satır satır yazmak yerine konuşur gibi de yazabilirsin. Bir satır `ad: değer` ya da `komut.` biçiminde değilse cümle sayılır. Arka arkaya yazılan cümleler (aralarında boş satır yoksa) birlikte okunur, yani ilk satıra linki, altına ne yapılacağını yazabilirsin:

```
https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct
bu modeli 4 bit yapıp gbra tam ile masaüstündeki model klasöründeki veri.json ile eğit,
sonra "Merhaba, kendini tanıtır mısın?" diye sor ve birleştir.
```

Dosya bile gerekmez:

```bash
gbra yap "Qwen/Qwen2.5-0.5B-Instruct modelini veri.jsonl ile 3 tur eğit"
gbra yap --kontrol "..."            # sadece ne anlaşıldığını göster
gbra cevir egitimim.gbra yeni.gbra  # cümleleri satır satır ayarlara çevirip kaydet
```

Çalıştırmadan önce ne anlaşıldığı gösterilir (`gbra kontrol` de gösterir):

```
Şöyle anladım (satır 1-3):
    model: Qwen/Qwen2.5-0.5B-Instruct
    veri: C:\Users\sen\Desktop\model\veri.json
    bit: 4
    norm_modu: tam
    egit.
    dene: "Merhaba, kendini tanıtır mısın?"
    birlestir.
```

Tanıdığı ifadeler:

| Ne | Nasıl yazılır (örnekler) |
|---|---|
| model | Hugging Face linki, `Qwen/Qwen2.5-0.5B-Instruct modelini`, `C:/modeller/qwen klasöründeki model` |
| veri | `veri.jsonl ile`, `deney klasöründeki veri isimli .json`, `masaüstündeki model klasöründeki veriler` (klasörde tek veri dosyası varsa onu alır) |
| bit | `4 bit`, `4bit`, `dört bitlik`, `8-bit`, `QLoRA gibi` (4), `QDoRA` (4 + kesin) |
| nicemleme | `nf4`, `fp4`, `int8`, `hqq`, `quanto`, `torchao`, `float8`, `çift nicemleme` |
| norm modu | `gbra tam`, `tam modda`, `kesin`, `DoRA gibi` (= kesin), `tembel` |
| sayılar | `3 tur` / `üç kez`, `100 adım`, `parti 2`, `biriktirme 8`, `rank 32`, `alfa 64`, `öğrenme hızı 0,0001`, `2048 token`, `tohum 1`, `%10 doğrulama`, `doğrulama yok` |
| diğer | `bellek tasarrufu` / `az bellekle`, `bütün katmanlar`, `sonucu X klasörüne kaydet` |
| komutlar | `eğit` / `eğitim yap` / `ince ayar`, `"..." diye sor` / `dene`, `birleştir` / `tam model olarak kaydet`, `lora ve dora ile karşılaştır`, `X klasöründeki adaptörü yükle` |

Yazım hataları düzeltilip not olarak gösterilir: `C/desktop` → masaüstün, `.jhson` → `.json`; klasörde `veri.json` yoksa ama `veri.jsonl` varsa onu kullanır. Anlamadığı bir cümlede tahmin yürütmez, satır numarasıyla hata verir. Cümleler ile normal satırlar aynı dosyada karışık da yazılabilir. Kural tabanlıdır: yapay zekâ modeli ya da internet gerekmez.

Aynı motor Python'dan da kullanılabilir:

```python
from gbra import Oturum
o = Oturum(model="Qwen/Qwen2.5-0.5B-Instruct", veri="sohbetler.jsonl", tur=3, norm_modu="kesin")
o.egit()
print(o.dene("Merhaba!"))
```
