aigencydev commited on
Commit
782e1d6
·
verified ·
1 Parent(s): 84fac55

Standart yukleme: auto_map + ErkLinearForCausalLM

Browse files
Files changed (1) hide show
  1. modeling_erk_linear.py +97 -22
modeling_erk_linear.py CHANGED
@@ -1,21 +1,29 @@
1
  """
2
  Erk-Linear — Erk-14B'nin 8 dikkat katmanini Gated DeltaNet'e damitan %20-lineer hibrit.
3
 
4
- Yukleme:
5
- # gerekli: pip install torch transformers flash-linear-attention safetensors huggingface_hub
6
- from modeling_erk_linear import load_erk_linear
7
- model, tokenizer = load_erk_linear() # Erk-14B tabanini + GDN agirliklarini indirir
8
- out = model.generate(**tokenizer("Merhaba", return_tensors="pt").to(model.device))
9
-
10
- Model, Qwen3-14B mimarisine dayanir; 8 katmanin softmax dikkati subquadratic Gated DeltaNet ile
11
- degistirilmis, kalan 32 katman softmax "cipa" olarak korunmustur. Ayrinti: teknik rapor / GitHub.
 
 
 
12
  """
13
  import torch
14
  import torch.nn as nn
15
- from transformers import AutoModelForCausalLM, AutoTokenizer
16
  from safetensors.torch import load_file
17
  from huggingface_hub import hf_hub_download
18
 
 
 
 
 
 
19
  BASE_MODEL = "ecloudtech/Erk-14B" # Qwen3-14B temelli Turkce model
20
  REPO_ID = "ecloudtech/Erk-Linear"
21
  GDN_LAYERS = [1, 3, 5, 7, 10, 36, 38, 39] # %20 lineer, yayilmis yerlesim
@@ -27,6 +35,7 @@ class _GDNStateCache:
27
  FLA'nin recurrent_state + conv_state'ini tek katman icin saklar; boylece cache'li uretim
28
  sirasinda GDN gecmis durumu adimlar arasi devreder.
29
  """
 
30
  def __init__(self):
31
  self._layers = []
32
 
@@ -54,6 +63,7 @@ class _GDNAttention(nn.Module):
54
  (use_cache=False) ile sayisal gurultuye kadar ayni olur. Referans amacli tek-dizi
55
  kullanim icindir (es zamanli/batch-paylasimli servis icin ayri durum yonetimi gerekir).
56
  """
 
57
  def __init__(self, gdn):
58
  super().__init__()
59
  gdn.layer_idx = 0
@@ -76,26 +86,91 @@ class _GDNAttention(nn.Module):
76
  return (y, None)
77
 
78
 
79
- def load_erk_linear(device="cuda", dtype=torch.bfloat16,
80
- base_model=BASE_MODEL, repo_id=REPO_ID):
81
- """Erk-Linear hibridini kurar ve (model, tokenizer) doner."""
82
- from fla.layers import GatedDeltaNet # flash-linear-attention
83
 
84
- model = AutoModelForCausalLM.from_pretrained(base_model, torch_dtype=dtype).to(device).eval()
85
  H = model.config.hidden_size
86
-
87
- gdn_path = hf_hub_download(repo_id=repo_id, filename="gdn_weights.safetensors")
88
- state = load_file(gdn_path)
89
-
90
- for li in GDN_LAYERS:
91
- gdn = GatedDeltaNet(hidden_size=H, head_dim=128, num_heads=40,
92
- use_gate=True, use_short_conv=True, mode="chunk")
 
 
93
  prefix = f"L{li}."
94
- layer_sd = {k[len(prefix):]: v for k, v in state.items() if k.startswith(prefix)}
 
 
95
  gdn.load_state_dict(layer_sd)
96
  gdn = gdn.to(device).to(dtype).eval()
97
  model.model.layers[li].self_attn = _GDNAttention(gdn).to(device).to(dtype)
 
 
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  tokenizer = AutoTokenizer.from_pretrained(base_model)
100
  return model, tokenizer
101
 
 
1
  """
2
  Erk-Linear — Erk-14B'nin 8 dikkat katmanini Gated DeltaNet'e damitan %20-lineer hibrit.
3
 
4
+ Yukleme (standart yol):
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer
6
+ model = AutoModelForCausalLM.from_pretrained("ecloudtech/Erk-Linear", trust_remote_code=True)
7
+ tok = AutoTokenizer.from_pretrained("ecloudtech/Erk-Linear")
8
+
9
+ Gereksinimler: torch, transformers, flash-linear-attention, safetensors, huggingface_hub
10
+
11
+ Model Qwen3-14B mimarisine dayanir; 8 katmanin softmax dikkati subquadratic Gated DeltaNet
12
+ ile degistirilmis, kalan 32 katman softmax "cipa" olarak korunmustur. Govde agirliklari
13
+ `config.base_model` deposundan, GDN agirliklari bu depodan yuklenir; from_pretrained
14
+ ikisini birlestirip calisir bir nedensel dil modeli doner.
15
  """
16
  import torch
17
  import torch.nn as nn
18
+ from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedModel
19
  from safetensors.torch import load_file
20
  from huggingface_hub import hf_hub_download
21
 
22
+ try: # HF uzak kod (paket icinde)
23
+ from .configuration_erk_linear import ErkLinearConfig
24
+ except ImportError: # yerel kullanim (dosya yan yana)
25
+ from configuration_erk_linear import ErkLinearConfig
26
+
27
  BASE_MODEL = "ecloudtech/Erk-14B" # Qwen3-14B temelli Turkce model
28
  REPO_ID = "ecloudtech/Erk-Linear"
29
  GDN_LAYERS = [1, 3, 5, 7, 10, 36, 38, 39] # %20 lineer, yayilmis yerlesim
 
35
  FLA'nin recurrent_state + conv_state'ini tek katman icin saklar; boylece cache'li uretim
36
  sirasinda GDN gecmis durumu adimlar arasi devreder.
37
  """
38
+
39
  def __init__(self):
40
  self._layers = []
41
 
 
63
  (use_cache=False) ile sayisal gurultuye kadar ayni olur. Referans amacli tek-dizi
64
  kullanim icindir (es zamanli/batch-paylasimli servis icin ayri durum yonetimi gerekir).
65
  """
66
+
67
  def __init__(self, gdn):
68
  super().__init__()
69
  gdn.layer_idx = 0
 
86
  return (y, None)
87
 
88
 
89
+ def _install_gdn(model, gdn_state, cfg, device, dtype):
90
+ """Govde modelin secili self_attn katmanlarini GDN sarmalayicilariyla degistirir."""
91
+ from fla.layers import GatedDeltaNet # flash-linear-attention (triton -> GPU gerekir)
 
92
 
93
+ layers = getattr(cfg, "gdn_layers", GDN_LAYERS)
94
  H = model.config.hidden_size
95
+ for li in layers:
96
+ gdn = GatedDeltaNet(
97
+ hidden_size=H,
98
+ head_dim=getattr(cfg, "gdn_head_dim", 128),
99
+ num_heads=getattr(cfg, "gdn_num_heads", 40),
100
+ use_gate=getattr(cfg, "gdn_use_gate", True),
101
+ use_short_conv=getattr(cfg, "gdn_use_short_conv", True),
102
+ mode=getattr(cfg, "gdn_mode", "chunk"),
103
+ )
104
  prefix = f"L{li}."
105
+ layer_sd = {k[len(prefix):]: v for k, v in gdn_state.items() if k.startswith(prefix)}
106
+ if not layer_sd:
107
+ raise ValueError(f"L{li} icin GDN agirligi bulunamadi ({cfg.gdn_weights_file})")
108
  gdn.load_state_dict(layer_sd)
109
  gdn = gdn.to(device).to(dtype).eval()
110
  model.model.layers[li].self_attn = _GDNAttention(gdn).to(device).to(dtype)
111
+ return model
112
+
113
 
114
+ class ErkLinearForCausalLM(PreTrainedModel):
115
+ """%20-lineer Erk hibridi.
116
+
117
+ `from_pretrained`, govdeyi `config.base_model` deposundan yukler, bu depodaki GDN
118
+ agirliklarini secili katmanlara takar ve elde edilen **calisir nedensel dil modelini**
119
+ doner. Donen nesne standart bir transformers modelidir: `.generate()`, `.forward()`,
120
+ `use_cache` ve chat sablonu oldugu gibi calisir.
121
+ """
122
+
123
+ config_class = ErkLinearConfig
124
+ base_model_prefix = "erk_linear"
125
+
126
+ @classmethod
127
+ def from_pretrained(cls, pretrained_model_name_or_path=None, *model_args, **kwargs):
128
+ repo = pretrained_model_name_or_path or REPO_ID
129
+ cfg = kwargs.pop("config", None)
130
+ if not isinstance(cfg, ErkLinearConfig):
131
+ cfg = ErkLinearConfig.from_pretrained(repo, **{
132
+ k: kwargs[k] for k in ("revision", "token", "cache_dir") if k in kwargs
133
+ })
134
+
135
+ dtype = kwargs.pop("dtype", None) or kwargs.pop("torch_dtype", None) or torch.bfloat16
136
+ device_map = kwargs.pop("device_map", None)
137
+ kwargs.pop("trust_remote_code", None)
138
+
139
+ base_kwargs = dict(kwargs)
140
+ if device_map is not None:
141
+ base_kwargs["device_map"] = device_map
142
+ model = AutoModelForCausalLM.from_pretrained(
143
+ cfg.base_model, dtype=dtype, trust_remote_code=True, **base_kwargs
144
+ )
145
+ if device_map is None:
146
+ model = model.to("cuda" if torch.cuda.is_available() else "cpu")
147
+ model.eval()
148
+
149
+ gdn_path = hf_hub_download(
150
+ repo_id=repo,
151
+ filename=getattr(cfg, "gdn_weights_file", "gdn_weights.safetensors"),
152
+ **{k: kwargs[k] for k in ("revision", "token", "cache_dir") if k in kwargs},
153
+ )
154
+ gdn_state = load_file(gdn_path)
155
+
156
+ device = next(model.parameters()).device
157
+ model = _install_gdn(model, gdn_state, cfg, device, dtype)
158
+ model.config.erk_linear = {
159
+ "gdn_layers": cfg.gdn_layers,
160
+ "linear_ratio": cfg.linear_ratio,
161
+ "base_model": cfg.base_model,
162
+ }
163
+ return model
164
+
165
+
166
+ def load_erk_linear(device="cuda", dtype=torch.bfloat16,
167
+ base_model=BASE_MODEL, repo_id=REPO_ID):
168
+ """Geriye donuk uyumlu yardimci: (model, tokenizer) doner."""
169
+ cfg = ErkLinearConfig(base_model=base_model)
170
+ model = AutoModelForCausalLM.from_pretrained(base_model, dtype=dtype,
171
+ trust_remote_code=True).to(device).eval()
172
+ gdn_path = hf_hub_download(repo_id=repo_id, filename=cfg.gdn_weights_file)
173
+ model = _install_gdn(model, load_file(gdn_path), cfg, device, dtype)
174
  tokenizer = AutoTokenizer.from_pretrained(base_model)
175
  return model, tokenizer
176