Metadata-Version: 2.4
Name: omgformer
Version: 2.0.0
Summary: Paralel Diffusion Dil Modeli — GQA + AdaLN-Zero + Self-Conditioning
License: Apache-2.0
Project-URL: Homepage, https://pypi.org/project/omgformer/
Project-URL: Bug Tracker, https://pypi.org/project/omgformer/
Keywords: deep-learning,diffusion,language-model,nlp,transformers,pytorch,masked-diffusion
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.2.0
Requires-Dist: transformers>=4.38.0
Requires-Dist: safetensors>=0.4.0
Provides-Extra: train
Requires-Dist: wandb>=0.16.0; extra == "train"
Requires-Dist: datasets>=2.18.0; extra == "train"
Requires-Dist: accelerate>=0.28.0; extra == "train"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: ruff>=0.4.0; extra == "dev"
Dynamic: license-file

# omgformer v2

**Paralel Diffusion Dil Modeli** — aynı anda tüm tokenleri üretir.

Klasik GPT 256 token için 256 forward pass yapar.  
omgformer aynı çıktıyı **8–10 forward pass** ile üretir.

---

## Temel Fikir

```
Adım 0: "Merhaba [MASK] [MASK] [MASK] [MASK] [MASK]"
Adım 1: "Merhaba dünya  [MASK] [MASK] [MASK] [MASK]"
Adım 2: "Merhaba dünya  nasıl  gidiyor [MASK] [MASK]"
Adım 3: "Merhaba dünya  nasıl  gidiyor  bugün   ?"
```

Her adımda tüm sequence bir forward pass'ten geçer.  
Model hem sola hem sağa bakar.  
En yüksek güvenli tokenlar açılır.  
Python for loop yok — tamamen vektörize.

---

## v2 Yenilikleri

### GQA (Grouped Query Attention)
KV head sayısını azalt, Q head sayısını koru.  
Büyük modellerde KV cache belleğini 4–8× küçültür.

```python
# 16 Q head, 4 KV head → 4× bellek tasarrufu
cfg = OMGConfig(num_heads=16, num_kv_heads=4)
```

### AdaLN-Zero
Timestep koşullandırması her katmana scale/shift/gate üçlüsüyle enjekte edilir.  
Input'a toplamak yerine — DiT mimarisinden ilham.

```
x_attn = norm(x) * (1 + scale) + shift
x = x + gate.tanh() * attention(x_attn)
```

Gate'ler sıfır başlatılır → eğitim başında blok = tam geçirgen.

### Self-Conditioning
Önceki adımın soft tahminleri bir sonraki adıma beslenir.

```
Adım N:  logits_n  = model(noisy, self_cond=None)
Adım N+1: logits_n1 = model(noisy, self_cond=soft_embed(logits_n))
```

Eğitimde %50 ihtimalle aktif edilir.  
Aynı step sayısında dramatik kalite artışı.

### Absorbing Diffusion
Sadece MASK değil, %10 random token da eklenir (BERT tarzı).  
Daha zengin training signal → daha hızlı öğrenme.

```
%80 → MASK token
%10 → rastgele başka token  ← YENİ
%10 → orijinal token kalır
```

### AMP + Gradient Accumulation
```python
TrainingConfig(
    use_amp=True,
    amp_dtype="bfloat16",   # 1.5-2× hız, yarı bellek
    grad_accum_steps=8,     # 8× büyük efektif batch
)
```

### torch.compile
```python
TrainingConfig(use_compile=True)  # ~30% ek hız
```

### Remasking
Inference'ta düşük güvenli tokenlar yeniden maskelenir.  
Ardışık adımlarda daha iyi global tutarlılık.

```python
decoder.generate(prompt, remask_prob=0.05)
```

---

## Kurulum

```bash
pip install -e ".[train,dev]"
```

---

## Hızlı Başlangıç

```python
from omgformer import OMGConfig, OMGModel, MaskScheduler, ParallelDecoder

cfg = OMGConfig.from_preset("omgformer-base")
model = OMGModel(cfg).eval()

sched = MaskScheduler(
    steps=64,
    mask_token_id=cfg.mask_token_id,
    vocab_size=cfg.vocab_size,
)
decoder = ParallelDecoder(model, sched)

prompt_ids = tokenizer.encode("İstanbul'un tarihi")
out = decoder.generate(
    prompt_ids,
    new_tokens=128,
    steps=10,
    temperature=0.9,
    top_p=0.95,
    remask_prob=0.05,
)
print(tokenizer.decode(out[0]))
```

### Pipeline

```python
from omgformer import pipeline

gen = pipeline("text-generation", model="omgformer-base")
result = gen("Yapay zeka", new_tokens=256, steps=10)
print(result["generated_text"])
```

### Eğitim

```python
from omgformer.training import Trainer, TrainingConfig

train_cfg = TrainingConfig(
    steps=100_000,
    batch_size=32,
    lr=3e-4,
    use_amp=True,
    use_compile=True,
    grad_accum_steps=4,
    self_cond_prob=0.5,
    use_wandb=True,
)

trainer = Trainer(model, sched, train_cfg, get_batch=my_data_loader)
trainer.fit()
```

### Çok GPU (FSDP)

```python
from omgformer.training import wrap_fsdp

model = wrap_fsdp(model, device_id=local_rank)
# torchrun --nproc_per_node=8 train.py
```

---

## Model Boyutları

| Preset | Katman | Hidden | Heads (Q/KV) | ~Parametre |
|--------|--------|--------|--------------|-----------|
| tiny   | 4      | 256    | 4/4          | ~14M      |
| small  | 8      | 512    | 8/4          | ~87M      |
| base   | 12     | 768    | 12/4         | ~180M     |
| large  | 24     | 1024   | 16/4         | ~600M     |
| xl     | 24     | 2048   | 16/2         | ~2.1B     |
| 3b     | 32     | 2560   | 32/8         | ~3.2B     |

---

## Hız Karşılaştırması

| Model | 256 token üretim | Yöntem |
|-------|-----------------|--------|
| GPT-2 | 256 forward pass | Otoregresif |
| omgformer (steps=10) | 10 forward pass | Paralel diffusion |
| omgformer (steps=6, SC) | 6 forward pass | + Self-conditioning |

Self-conditioning ile aynı kalite için daha az adım yeterli olur.

---

## Testler

```bash
pytest test_omgformer.py -v
```

---

## Referanslar

- [MDLM: Masked Diffusion Language Models](https://arxiv.org/abs/2406.07524)
- [DiT: Scalable Diffusion Transformers](https://arxiv.org/abs/2212.09748)
- [Self-Conditioning in Diffusion Models](https://arxiv.org/abs/2208.04202)
- [GQA: Training Generalized Multi-Query Attention](https://arxiv.org/abs/2305.13245)
- [Mercury: Ultra-Fast Language Models (Inception Labs)](https://www.inceptionlabs.ai/mercury)

---

## Lisans

Apache-2.0
