ffurfaro commited on
Commit
fa25776
·
verified ·
1 Parent(s): af0bcfc

Upload model + init tptt code

Browse files
README.md CHANGED
@@ -48,19 +48,19 @@ print(tokenizer.decode(outputs, skip_special_tokens=True))
48
  - **Platform:** Kaggle
49
  - **Hardware:** NVIDIA 2xT4
50
  - **Batch size:** 3
51
- - **Epochs:** 2.0
52
- - **Learning rate (final):** 8.928571428571428e-06
53
- - **Loss (final):** 1.5266
54
- - **Training runtime:** 476.5978 sec
55
- - **Samples per second:** 2.098
56
- - **Steps per second:** 0.352
57
- - **Total FLOPs:** 1560788336640000.0
58
- - **Gradient norm (final):** 0.55694580078125
59
 
60
  ## Evaluation
61
 
62
  - **Metrics:** Training loss only (no eval yet, table soon : PiQA, ARC, Hella, Wino, GSM8K, MMLU)
63
- - **Results:** Final training loss: 1.5266
64
 
65
 
66
  ## Citation & Contact
 
48
  - **Platform:** Kaggle
49
  - **Hardware:** NVIDIA 2xT4
50
  - **Batch size:** 3
51
+ - **Epochs:** 5.0
52
+ - **Learning rate (final):** 1.1904761904761906e-06
53
+ - **Loss (final):** 1.3188
54
+ - **Training runtime:** 1651.0658 sec
55
+ - **Samples per second:** 1.514
56
+ - **Steps per second:** 0.254
57
+ - **Total FLOPs:** 5852956262400000.0
58
+ - **Gradient norm (final):** 0.7039350271224976
59
 
60
  ## Evaluation
61
 
62
  - **Metrics:** Training loss only (no eval yet, table soon : PiQA, ARC, Hella, Wino, GSM8K, MMLU)
63
+ - **Results:** Final training loss: 1.3188
64
 
65
 
66
  ## Citation & Contact
__init__.py CHANGED
@@ -1,13 +1,8 @@
1
  __version__ = "0.1.0"
2
 
3
  from .configuration_tptt import TpttConfig, generate_model_card
4
- from .modeling_tptt import (
5
- AttentionOperator,
6
- LCache,
7
- LiZAttention,
8
- TpttModel,
9
- get_tptt_model,
10
- )
11
  from .pipeline_tptt import TpttPipeline
12
  from .train_tptt import AdjustMaGWeightCallback
13
 
 
1
  __version__ = "0.1.0"
2
 
3
  from .configuration_tptt import TpttConfig, generate_model_card
4
+ from .modeling_tptt import (AttentionOperator, LCache, LiZAttention, TpttModel,
5
+ get_tptt_model)
 
 
 
 
 
6
  from .pipeline_tptt import TpttPipeline
7
  from .train_tptt import AdjustMaGWeightCallback
8
 
adapter_model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2b0c35dce9003bc09e72dee902ac4f9a50be489a82a4f2fd22ac2991c7a128e1
3
  size 7147336
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b737bf259d8fc690514703e45a728f035539c0bf45f0403a4ccbb1d5094993f9
3
  size 7147336
config.json CHANGED
@@ -1,4 +1,5 @@
1
  {
 
2
  "architectures": [
3
  "TpttModel"
4
  ],
@@ -7,6 +8,40 @@
7
  "AutoModelForCausalLM": "modeling_tptt.TpttModel"
8
  },
9
  "base_model_name": "apple/OpenELM-1_1B",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  "lora_config": {
11
  "alpha_pattern": {},
12
  "auto_mapping": null,
@@ -41,14 +76,89 @@
41
  },
42
  "mag_weight": 0.5,
43
  "max_chunk_size": 64,
 
44
  "max_self_attn_length": 8192,
 
45
  "model_type": "tptt",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  "operator_mode": "delta_rule",
 
 
 
 
 
 
 
47
  "target_modules_names": [
48
  "attn",
49
  "self_attn",
50
  "attention"
51
  ],
52
  "torch_dtype": "bfloat16",
53
- "transformers_version": "4.49.0"
 
 
54
  }
 
1
  {
2
+ "activation_fn_name": "swish",
3
  "architectures": [
4
  "TpttModel"
5
  ],
 
8
  "AutoModelForCausalLM": "modeling_tptt.TpttModel"
9
  },
10
  "base_model_name": "apple/OpenELM-1_1B",
11
+ "ffn_dim_divisor": 256,
12
+ "ffn_multipliers": [
13
+ 0.5,
14
+ 0.63,
15
+ 0.76,
16
+ 0.89,
17
+ 1.02,
18
+ 1.15,
19
+ 1.28,
20
+ 1.41,
21
+ 1.54,
22
+ 1.67,
23
+ 1.8,
24
+ 1.93,
25
+ 2.06,
26
+ 2.19,
27
+ 2.31,
28
+ 2.44,
29
+ 2.57,
30
+ 2.7,
31
+ 2.83,
32
+ 2.96,
33
+ 3.09,
34
+ 3.22,
35
+ 3.35,
36
+ 3.48,
37
+ 3.61,
38
+ 3.74,
39
+ 3.87,
40
+ 4.0
41
+ ],
42
+ "ffn_with_glu": true,
43
+ "head_dim": 64,
44
+ "initializer_range": 0.02,
45
  "lora_config": {
46
  "alpha_pattern": {},
47
  "auto_mapping": null,
 
76
  },
77
  "mag_weight": 0.5,
78
  "max_chunk_size": 64,
79
+ "max_context_length": 2048,
80
  "max_self_attn_length": 8192,
81
+ "model_dim": 2048,
82
  "model_type": "tptt",
83
+ "normalization_layer_name": "rms_norm",
84
+ "normalize_qk_projections": true,
85
+ "num_gqa_groups": 4,
86
+ "num_kv_heads": [
87
+ 4,
88
+ 4,
89
+ 4,
90
+ 5,
91
+ 5,
92
+ 5,
93
+ 5,
94
+ 5,
95
+ 5,
96
+ 5,
97
+ 6,
98
+ 6,
99
+ 6,
100
+ 6,
101
+ 6,
102
+ 6,
103
+ 6,
104
+ 6,
105
+ 7,
106
+ 7,
107
+ 7,
108
+ 7,
109
+ 7,
110
+ 7,
111
+ 8,
112
+ 8,
113
+ 8,
114
+ 8
115
+ ],
116
+ "num_query_heads": [
117
+ 16,
118
+ 16,
119
+ 16,
120
+ 20,
121
+ 20,
122
+ 20,
123
+ 20,
124
+ 20,
125
+ 20,
126
+ 20,
127
+ 24,
128
+ 24,
129
+ 24,
130
+ 24,
131
+ 24,
132
+ 24,
133
+ 24,
134
+ 24,
135
+ 28,
136
+ 28,
137
+ 28,
138
+ 28,
139
+ 28,
140
+ 28,
141
+ 32,
142
+ 32,
143
+ 32,
144
+ 32
145
+ ],
146
+ "num_transformer_layers": 28,
147
  "operator_mode": "delta_rule",
148
+ "qkv_multipliers": [
149
+ 0.5,
150
+ 1.0
151
+ ],
152
+ "rope_freq_constant": 10000,
153
+ "rope_max_length": 4096,
154
+ "share_input_output_layers": true,
155
  "target_modules_names": [
156
  "attn",
157
  "self_attn",
158
  "attention"
159
  ],
160
  "torch_dtype": "bfloat16",
161
+ "transformers_version": "4.51.3",
162
+ "use_cache": true,
163
+ "vocab_size": 32000
164
  }
configuration_tptt.py CHANGED
@@ -35,29 +35,29 @@ class TpttConfig(PretrainedConfig):
35
 
36
  def __init__(
37
  self,
38
- base_model_config: Optional[Union[str, dict, PretrainedConfig]] = None,
39
  base_model_name: str = "meta-llama/Llama-3.2-1B",
40
  name_or_path: Optional[str] = None,
41
  target_modules_names: Optional[List[str]] = None,
42
  operator_mode: str = "delta_rule",
43
- max_self_attn_length: int = 4096,
44
- mag_weight: float = 0.5,
45
  max_chunk_size: int = 64,
46
  lora_config: Optional[dict] = None, # only serialized accepted
47
  **kwargs,
48
  ):
49
-
50
  if base_model_config is not None:
51
- if isinstance(base_model_config, str):
52
- # Load config from Hugging Face Hub or a local path
53
- base_model_config = AutoConfig.from_pretrained(
54
- base_model_config
55
- ).to_dict()
56
- elif isinstance(base_model_config, PretrainedConfig):
57
  base_model_config = base_model_config.to_dict()
58
- # Merge all backbone fields into this config
59
- for k, v in base_model_config.items():
60
- setattr(self, k, v)
 
 
 
 
 
61
 
62
  self.base_model_name = base_model_name
63
  self._name_or_path = (
@@ -82,7 +82,7 @@ class TpttConfig(PretrainedConfig):
82
  self.lora_config["peft_type"] = self.lora_config["peft_type"].value
83
  self.lora_config = convert_sets_to_lists(self.lora_config)
84
 
85
- super().__init__(**kwargs)
86
  # Copy class attributes to instance for serialization (save dict)
87
  self.model_type = self.__class__.model_type
88
  self.auto_map = self.__class__.auto_map
 
35
 
36
  def __init__(
37
  self,
38
+ base_model_config: Optional[Union[dict, PretrainedConfig]] = None,
39
  base_model_name: str = "meta-llama/Llama-3.2-1B",
40
  name_or_path: Optional[str] = None,
41
  target_modules_names: Optional[List[str]] = None,
42
  operator_mode: str = "delta_rule",
43
+ max_self_attn_length: int = 8192,
44
+ mag_weight: float = 0.5, # if 1.0, use only linear operator
45
  max_chunk_size: int = 64,
46
  lora_config: Optional[dict] = None, # only serialized accepted
47
  **kwargs,
48
  ):
49
+ # If base_model_config is provided, load it and merge with this config
50
  if base_model_config is not None:
51
+ if isinstance(base_model_config, PretrainedConfig):
 
 
 
 
 
52
  base_model_config = base_model_config.to_dict()
53
+ else:
54
+ # Load config from Hugging Face Hub or a local path
55
+ base_model_config = AutoConfig.from_pretrained(
56
+ base_model_name, **kwargs
57
+ ).to_dict()
58
+ # Merge all backbone fields into this config
59
+ for k, v in base_model_config.items():
60
+ setattr(self, k, v)
61
 
62
  self.base_model_name = base_model_name
63
  self._name_or_path = (
 
82
  self.lora_config["peft_type"] = self.lora_config["peft_type"].value
83
  self.lora_config = convert_sets_to_lists(self.lora_config)
84
 
85
+ super().__init__(**kwargs) # flush unconsistend pretrained parameters (?)
86
  # Copy class attributes to instance for serialization (save dict)
87
  self.model_type = self.__class__.model_type
88
  self.auto_map = self.__class__.auto_map
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:fa3bc219be684b13883a1eedf50fc757eab43a7b2890d61179a45c03af075bf9
3
  size 2166965528
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00099fe4999a6eff0257c94e59963690f76ea7a5b84817ccef0d0c1e67e397af
3
  size 2166965528
modeling_tptt.py CHANGED
@@ -3,6 +3,7 @@ This module implements the TPTT model with linear attention (LiZA) and LoRA supp
3
  Author : Fabien FURFARO
4
  """
5
 
 
6
  import os
7
  import re
8
  import shutil
@@ -35,6 +36,8 @@ def import_fla_ops():
35
 
36
  fused_chunk_gla, fused_recurrent_gla = import_fla_ops() # TODO: add all ops
37
 
 
 
38
 
39
  class LCache:
40
  """
@@ -92,7 +95,7 @@ class LiZAttention(nn.Module):
92
  base_attn: nn.Module,
93
  layer_idx: int,
94
  base_config, # Backbone Config
95
- linear_cache: LCache = None,
96
  operator_mode: str = "delta_rule",
97
  max_self_attn_length: int = 2048,
98
  mag_weight: float = 0.5,
@@ -340,7 +343,7 @@ def get_tptt_model( # pylint: disable=too-many-arguments, too-many-positional-a
340
  base_config: PretrainedConfig, # ou LlamaConfig, MistralConfig, etc.
341
  liza_attention: LiZAttention,
342
  target_modules: list,
343
- linear_cache: LCache = None,
344
  operator_mode: str = "delta_rule",
345
  mag_weight: float = 0.5,
346
  max_chunk_size: int = 64,
@@ -393,17 +396,18 @@ class TpttModel(PreTrainedModel):
393
  super().__init__(config, **kwargs)
394
  repo_or_path = getattr(config, "_base_path", None) or config._name_or_path
395
 
396
- # 1. Load backbone
397
- backbone = AutoModelForCausalLM.from_pretrained(
398
  config.base_model_name, **kwargs
399
  )
 
400
 
401
  # 2. Inject LiZA attention
402
  self.linear_cache = LCache()
403
  self.backbone, self.linear_cache = self.inject_liza_attention(
404
- backbone, config, self.linear_cache
405
  )
406
- # 3. Apply LoRA if present of configured
407
  if config.lora_config is not None:
408
  lora_config_obj = LoraConfig(**config.lora_config)
409
  self.backbone = get_peft_model(self.backbone, lora_config_obj)
@@ -502,6 +506,27 @@ class TpttModel(PreTrainedModel):
502
  dst = os.path.join(path, fname)
503
  shutil.copy2(src, dst)
504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
 
506
  TpttModel.register_for_auto_class("AutoModelForCausalLM")
507
 
@@ -557,8 +582,10 @@ class AttentionOperator(nn.Module):
557
  # Output buffer
558
  output = torch.empty_like(q_chunks)
559
  # State: [batch, num_heads, head_dim, head_dim]
560
- if initial_state is not None:
561
- state = initial_state
 
 
562
  else:
563
  state = torch.zeros(
564
  batch_size,
@@ -674,6 +701,18 @@ def extract_layer_idx(module_name: str) -> int:
674
  return -1
675
 
676
 
 
 
 
 
 
 
 
 
 
 
 
 
677
  def soft_clamp(x, min_val=-1e4, max_val=1e4):
678
  """Differentiable clamping for stability"""
679
  scale = (max_val - min_val) / 2
 
3
  Author : Fabien FURFARO
4
  """
5
 
6
+ import logging
7
  import os
8
  import re
9
  import shutil
 
36
 
37
  fused_chunk_gla, fused_recurrent_gla = import_fla_ops() # TODO: add all ops
38
 
39
+ logger = logging.getLogger(__name__) # monitoring
40
+
41
 
42
  class LCache:
43
  """
 
95
  base_attn: nn.Module,
96
  layer_idx: int,
97
  base_config, # Backbone Config
98
+ linear_cache: Optional[LCache] = None,
99
  operator_mode: str = "delta_rule",
100
  max_self_attn_length: int = 2048,
101
  mag_weight: float = 0.5,
 
343
  base_config: PretrainedConfig, # ou LlamaConfig, MistralConfig, etc.
344
  liza_attention: LiZAttention,
345
  target_modules: list,
346
+ linear_cache: Optional[LCache] = None,
347
  operator_mode: str = "delta_rule",
348
  mag_weight: float = 0.5,
349
  max_chunk_size: int = 64,
 
396
  super().__init__(config, **kwargs)
397
  repo_or_path = getattr(config, "_base_path", None) or config._name_or_path
398
 
399
+ # 1. Load backbone TODO : support no model.safetensors
400
+ self.backbone = AutoModelForCausalLM.from_pretrained(
401
  config.base_model_name, **kwargs
402
  )
403
+ self._retie_lm_after_load(**kwargs) # Force lm tie weights
404
 
405
  # 2. Inject LiZA attention
406
  self.linear_cache = LCache()
407
  self.backbone, self.linear_cache = self.inject_liza_attention(
408
+ self.backbone, config, self.linear_cache
409
  )
410
+ # 3. Apply LoRA if present and configured
411
  if config.lora_config is not None:
412
  lora_config_obj = LoraConfig(**config.lora_config)
413
  self.backbone = get_peft_model(self.backbone, lora_config_obj)
 
506
  dst = os.path.join(path, fname)
507
  shutil.copy2(src, dst)
508
 
509
+ def _retie_lm_after_load(self, **kwargs):
510
+ """Re-link lm_head after loading external weights."""
511
+ embed_lm = find_embedding_lm(self.backbone)
512
+ if embed_lm is not None and hasattr(self.backbone, "lm_head"):
513
+ if self.backbone.lm_head is None: # ensure lm_head exists
514
+ self.backbone.lm_head = nn.Linear(
515
+ embed_lm.weight.shape[1], embed_lm.weight.shape[0], bias=False
516
+ )
517
+ if kwargs.get("tie_word_embeddings", True):
518
+ self.backbone.lm_head.weight = embed_lm.weight # share weights
519
+ logger.info("Weights of lm_head have been shared with embedding.")
520
+ else:
521
+ self.backbone.lm_head.weight = nn.Parameter(embed_lm.weight.clone())
522
+ logger.info("Weights of lm_head have been cloned from the embedding.")
523
+
524
+ @classmethod
525
+ def from_pretrained(cls, *args, **kwargs):
526
+ model = super().from_pretrained(*args, **kwargs)
527
+ model._retie_lm_after_load(**kwargs)
528
+ return model
529
+
530
 
531
  TpttModel.register_for_auto_class("AutoModelForCausalLM")
532
 
 
582
  # Output buffer
583
  output = torch.empty_like(q_chunks)
584
  # State: [batch, num_heads, head_dim, head_dim]
585
+ expect_state_shape = (batch_size, num_heads, head_dim, head_dim)
586
+ if initial_state is not None and initial_state.shape == expect_state_shape:
587
+ # Use provided initial state
588
+ state = initial_state.to(device=query.device, dtype=query.dtype)
589
  else:
590
  state = torch.zeros(
591
  batch_size,
 
701
  return -1
702
 
703
 
704
+ def find_embedding_lm(module):
705
+ """Find the embedding weight in a model module."""
706
+ for _, child in module.named_modules():
707
+ if hasattr(child, "embed_tokens") and hasattr(child.embed_tokens, "weight"):
708
+ return child.embed_tokens
709
+ if hasattr(child, "token_embeddings") and hasattr(
710
+ child.token_embeddings, "weight"
711
+ ):
712
+ return child.token_embeddings
713
+ return None
714
+
715
+
716
  def soft_clamp(x, min_val=-1e4, max_val=1e4):
717
  """Differentiable clamping for stability"""
718
  scale = (max_val - min_val) / 2
runs/Jun14_12-28-48_4d9f48efb250/events.out.tfevents.1749904130.4d9f48efb250.35.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a45f679cd9e8ebae584f0f2764364193b97641efff346573c40e49f246fef41
3
+ size 24832
tokenizer.json CHANGED
@@ -2,7 +2,7 @@
2
  "version": "1.0",
3
  "truncation": {
4
  "direction": "Right",
5
- "max_length": 256,
6
  "strategy": "LongestFirst",
7
  "stride": 0
8
  },
 
2
  "version": "1.0",
3
  "truncation": {
4
  "direction": "Right",
5
+ "max_length": 384,
6
  "strategy": "LongestFirst",
7
  "stride": 0
8
  },