windsornguyen commited on
Commit
93d11ff
·
verified ·
1 Parent(s): eaac3b2

Upload FlashSTU

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +27 -0
  3. config.py +40 -0
  4. model.py +138 -0
  5. pytorch_model.bin +3 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "FlashSTU"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "config.FlashSTUConfig",
7
+ "AutoModel": "model.FlashSTU"
8
+ },
9
+ "bias": false,
10
+ "bsz": 8,
11
+ "dropout": 0.0,
12
+ "mlp_scale": 4,
13
+ "model_type": "FlashSTU",
14
+ "n_embd": 768,
15
+ "n_heads": 12,
16
+ "n_layers": 12,
17
+ "num_eigh": 16,
18
+ "seq_len": 4096,
19
+ "softcap": 50.0,
20
+ "torch_dtype": "float32",
21
+ "transformers_version": "4.44.0",
22
+ "use_approx": true,
23
+ "use_flash_fft": true,
24
+ "use_hankel_L": false,
25
+ "vocab_size": 200064,
26
+ "window_size": 64
27
+ }
config.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class FlashSTUConfig(PretrainedConfig):
4
+ model_type = "FlashSTU"
5
+
6
+ def __init__(
7
+ self,
8
+ bsz: int = 8,
9
+ n_embd: int = 768,
10
+ n_heads: int = 12,
11
+ n_layers: int = 12,
12
+ seq_len: int = 4096,
13
+ window_size: int = 64,
14
+ vocab_size: int = 200064,
15
+ mlp_scale: int = 4,
16
+ bias: bool = False,
17
+ dropout: float = 0.0,
18
+ num_eigh: int = 16,
19
+ use_hankel_L: bool = False,
20
+ use_flash_fft: bool = True,
21
+ use_approx: bool = True,
22
+ softcap: float = 50.0,
23
+ **kwargs,
24
+ ):
25
+ super().__init__(**kwargs)
26
+ self.bsz = bsz
27
+ self.n_embd = n_embd
28
+ self.n_heads = n_heads
29
+ self.n_layers = n_layers
30
+ self.seq_len = seq_len
31
+ self.window_size = window_size
32
+ self.vocab_size = vocab_size
33
+ self.mlp_scale = mlp_scale
34
+ self.bias = bias
35
+ self.dropout = dropout
36
+ self.num_eigh = num_eigh
37
+ self.use_hankel_L = use_hankel_L
38
+ self.use_flash_fft = use_flash_fft
39
+ self.use_approx = use_approx
40
+ self.softcap = softcap
model.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ from transformers import PreTrainedModel
6
+
7
+ from stu import STU
8
+ from modules import Attention
9
+ from utils import get_spectral_filters, nearest_power_of_two
10
+ from flash_stu.config import FlashSTUConfig
11
+
12
+ try:
13
+ from flashfftconv import FlashFFTConv
14
+ flash_fft_available = True
15
+ except ImportError as e:
16
+ print(f"Unable to import FlashFFTConv: {e}. Falling back to PyTorch implementation.")
17
+ flash_fft_available = False
18
+
19
+ try:
20
+ from flash_attn.modules.mlp import GatedMlp as MLP
21
+ triton_mlp = True
22
+ except ImportError as e:
23
+ print(f"Unable to import Triton-based MLP: {e}. Falling back to vanilla SwiGLU MLP instead.")
24
+ from modules import MLP
25
+ triton_mlp = False
26
+
27
+ try:
28
+ from flash_attn.ops.triton.layer_norm import RMSNorm
29
+ except ImportError as e:
30
+ print(f"Unable to import Triton-based RMSNorm: {e}. Falling back to PyTorch implementation.")
31
+ from torch.nn import RMSNorm
32
+
33
+ try:
34
+ from flash_attn.losses.cross_entropy import CrossEntropyLoss
35
+ except ImportError as e:
36
+ print(f"Unable to import Triton-based cross entropy loss: {e}. Falling back to PyTorch implementation.")
37
+ from torch.nn import CrossEntropyLoss
38
+
39
+ class Block(nn.Module):
40
+ def __init__(self, config, phi, n, flash_fft) -> None:
41
+ super(Block, self).__init__()
42
+ # For more complex %-split arrangements, see https://arxiv.org/pdf/2406.07887
43
+ self.rn_1 = RMSNorm(config.n_embd)
44
+ self.stu = STU(config, phi, n, flash_fft)
45
+ self.rn_2 = RMSNorm(config.n_embd)
46
+ self.attn = Attention(config)
47
+ self.rn_3 = RMSNorm(config.n_embd)
48
+ self.mlp = MLP(
49
+ config.n_embd,
50
+ config.n_embd * config.mlp_scale,
51
+ activation=F.silu, # Use SwiGLU
52
+ bias1=config.bias,
53
+ bias2=config.bias,
54
+ ) if triton_mlp else MLP(config)
55
+ self.rn_4 = RMSNorm(config.n_embd)
56
+
57
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
58
+ x = x + self.stu(self.rn_1(x))
59
+ x = x + self.mlp(self.rn_2(x))
60
+ x = x + self.attn(self.rn_3(x))
61
+ x = x + self.mlp(self.rn_4(x))
62
+ return x
63
+
64
+ class FlashSTU(PreTrainedModel):
65
+ config_class = FlashSTUConfig
66
+
67
+ def __init__(self, config) -> None:
68
+ super(FlashSTU, self).__init__(config)
69
+ self.config = config
70
+ self.n_layers = config.n_layers
71
+ self.n_embd = config.n_embd
72
+ self.mlp_scale = config.mlp_scale
73
+ self.seq_len = config.seq_len
74
+ self.n = nearest_power_of_two(self.seq_len * 2 - 1, round_up=True)
75
+ self.vocab_size = config.vocab_size
76
+ self.K = config.num_eigh
77
+ self.use_hankel_L = config.use_hankel_L
78
+ self.phi = get_spectral_filters(self.seq_len, self.K, self.use_hankel_L)
79
+ self.use_approx = config.use_approx
80
+ self.flash_fft = (
81
+ FlashFFTConv(self.n, dtype=torch.bfloat16)
82
+ if config.use_flash_fft and flash_fft_available
83
+ else None
84
+ )
85
+ self.dropout = config.dropout
86
+ self.bias = config.bias
87
+ self.loss_fn = CrossEntropyLoss()
88
+
89
+ self.flash_stu = nn.ModuleDict(
90
+ dict(
91
+ tok_emb=nn.Embedding(self.vocab_size, self.n_embd),
92
+ dropout=nn.Dropout(self.dropout),
93
+ hidden=nn.ModuleList(
94
+ [
95
+ Block(self.config, self.phi, self.n, self.flash_fft)
96
+ for _ in range(self.n_layers)
97
+ ]
98
+ ),
99
+ rn_f=RMSNorm(config.n_embd)
100
+ )
101
+ )
102
+ self.lm_head = nn.Linear(self.n_embd, self.vocab_size, bias=self.bias)
103
+
104
+ self.std = (self.n_embd) ** -0.5
105
+ self.apply(self._init_weights)
106
+ print("Model Parameter Count: %.2fM\n" % (self._get_num_params() / 1e6,))
107
+
108
+ def forward(self, x: torch.Tensor) -> torch.tensor:
109
+ tok_emb = self.flash_stu.tok_emb(x)
110
+ x = self.flash_stu.dropout(tok_emb)
111
+
112
+ for block in self.flash_stu.hidden:
113
+ x = block(x)
114
+ x = self.flash_stu.rn_f(x)
115
+
116
+ y_hat = self.lm_head(x)
117
+ return y_hat
118
+
119
+ def _get_num_params(self):
120
+ n_params = sum(p.numel() for p in self.parameters())
121
+ return n_params
122
+
123
+ def _init_weights(self, module):
124
+ if isinstance(module, nn.Linear):
125
+ if hasattr(module, "SCALE_INIT"):
126
+ self.std *= (2 * self.n_layers) ** -0.5
127
+ torch.nn.init.normal_(module.weight, mean=0.0, std=self.std)
128
+ if module.bias is not None:
129
+ torch.nn.init.zeros_(module.bias)
130
+ elif isinstance(module, nn.Embedding):
131
+ torch.nn.init.normal_(module.weight, mean=0.0, std=self.std)
132
+ elif isinstance(module, STU):
133
+ if self.use_approx:
134
+ torch.nn.init.xavier_normal_(module.M_inputs)
135
+ torch.nn.init.xavier_normal_(module.M_filters)
136
+ else:
137
+ torch.nn.init.xavier_normal_(module.M_phi_plus)
138
+ torch.nn.init.xavier_normal_(module.M_phi_minus)
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e4cc22a082a4d026cc4d4d0c83bff51eaa5b4d4ae3befbc9d195c944ecd07e5
3
+ size 1711361814