YADAV0206 commited on
Commit
c57b29e
·
verified ·
1 Parent(s): c85ff53

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +368 -0
README.md ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ ---
4
+
5
+ # instinct.4B
6
+
7
+ **[autonomousX/instinct-1.4B on Hugging Face](https://huggingface.co/autonomousX)**
8
+
9
+ **[Training scripts and Logs on GITHUB](https://github.com/YADAV1825/AutonomousX-Instinct)**
10
+
11
+ *instinct-1.4B is a fully reproducible, from-scratch trained 1.4B parameter language model trained on 70B tokens using TPU v4 infrastructure.*
12
+
13
+ **instinct-1.4B** is a 1.4B parameter Large Language Model built entirely from scratch under the **AutonomousX** organization.
14
+
15
+ Compute for this project was supported by **[Google's TRC Program (TPU Research Cloud)](https://sites.research.google/trc/about/)**.
16
+
17
+ ---
18
+
19
+ ### 👨‍💻 Author Information
20
+ **Rohit Yadav** B.Tech 3rd Year
21
+ Dr. B.R. Ambedkar National Institute of Technology (NIT) Jalandhar, India
22
+ **E-mail:** [yrohit1825@gmail.com](mailto:yrohit1825@gmail.com)
23
+ **LinkedIn:** [Rohit Yadav](https://www.linkedin.com/in/rohit-yadav-25535b256/)
24
+ **GitHub:** [YADAV1825](https://github.com/YADAV1825)
25
+
26
+ **Research interests include:** Large Language Models, MultiModal Pipelines, Systems Programming, AI Infrastructure, Distributed Training.
27
+
28
+ ---
29
+ # About AutonomousX
30
+
31
+ AutonomousX focuses on open-source contributions aimed at building Large Language Models from scratch using custom training pipelines. Our work explores different training configurations including optimizers, datasets, and scalable TPU training using JAX and pmap. The goal is to provide transparent and reproducible implementations so that researchers, students, and developers can understand how modern LLMs are trained end-to-end.
32
+
33
+ Due to the current scarcity of complete beginner-friendly guides for training LLMs on TPUs, especially using JAX, AutonomousX aims to bridge this gap by publishing full training pipelines, scripts, and documentation for the open-source community.
34
+
35
+ Maintained by: Rohit Yadav | B.Tech NIT Jalandhar | yrohit1825@gmail.com | [Hugging_Face](https://huggingface.co/autonomousX)
36
+
37
+ ---
38
+
39
+ ### ⚠️ Disclaimer
40
+ **This is a base model, not an SFT (Supervised Fine-Tuned) or RLHF (Reinforcement Learning from Human Feedback) model.** As a raw completion model, it may output undesired, biased, or nonsensical text. It is intended primarily for research and educational purposes.
41
+
42
+ ---
43
+
44
+ ### 📊 Model Overview
45
+
46
+ | Attribute | Value |
47
+ | :--- | :--- |
48
+ | **Model Name** | instinct-1.4B |
49
+ | **Organization** | AutonomousX |
50
+ | **Parameters** | 1.4B |
51
+ | **Vocabulary Size** | 50,304 |
52
+ | **Dataset** | DOLMA |
53
+ | **Tokenizer** | Pythia Tokenizer / BPE |
54
+ | **Tokens Seen** | 70B |
55
+ | **Training Hardware** | TPU v4-8 |
56
+ | **Optimizer** | Lion |
57
+ | **Architecture** | v-4 (128) pmap |
58
+ | **Positional Embeddings**| RoPE |
59
+
60
+ ---
61
+
62
+ ### 🧠 Training Details
63
+
64
+ instinct-1.4B was trained completely **from scratch** using **JAX/Flax on TPU v4-8 hardware**.
65
+
66
+ The training pipeline includes:
67
+ * Dataset streaming from **DOLMA**.
68
+ * **Pythia Tokenizer** with a 50,304 vocabulary size.
69
+ * TPU optimized **JAX / Flax** training loop.
70
+ * **Lion** optimizer for stable convergence.
71
+ * Checkpointing and validation during training.
72
+ * Rolling validation shard evaluation.
73
+
74
+ #### 🔄 Training Workflow
75
+
76
+ ```mermaid
77
+ graph TD
78
+ %% Dataset and Preparation
79
+ Data["Dataset: DOLMA\nRaw Text Data"]
80
+ Tokenizer["BPE Tokenizer\nVocabulary Construction"]
81
+ TokenizedData["Tokenized Data\nReady for Training"]
82
+
83
+ %% Model Architecture
84
+ Model["v-4 (128) pmap\nTransformer Decoder\n1.4B Parameters"]
85
+ RoPE["RoPE Positional Embeddings"]
86
+
87
+ %% Training Pipeline
88
+ Optimizer["Optimizer: Lion"]
89
+ ForwardPass["Forward Pass\nCompute Loss"]
90
+ BackwardPass["Backward Pass\nCompute Gradients"]
91
+ Update["Parameter Update"]
92
+
93
+ %% Logging and Checkpoints
94
+ Checkpoints["Model Checkpoints\nSaved up to 70B tokens"]
95
+ Logs["Training Logs\nLoss & Perplexity"]
96
+
97
+ %% Connections
98
+ Data --> Tokenizer
99
+ Tokenizer --> TokenizedData
100
+ TokenizedData --> ForwardPass
101
+
102
+ Model --> ForwardPass
103
+ RoPE -.-> Model
104
+
105
+ ForwardPass --> BackwardPass
106
+ BackwardPass --> Optimizer
107
+ Optimizer --> Update
108
+ Update --> Model
109
+
110
+ Update --> Checkpoints
111
+ Update --> Logs
112
+ ```
113
+
114
+ #### 📈 Training Curves
115
+ The loss curves are saved in `training_log.txt` and `val_perplexity.txt`. Below is the visualization of the training progress:
116
+
117
+ ![image](https://cdn-uploads.huggingface.co/production/uploads/68bf07a31d80a360f1405b72/sWC0DlPjaqPoM6dsqNrA1.png)
118
+
119
+ ---
120
+
121
+ ### 🔄 Reproducibility
122
+
123
+ The entire pipeline used to train the model is fully reproducible. This includes the dataset pipeline, tokenizer creation, model architecture, TPU training loop, and checkpointing system.
124
+
125
+ **Full training pipeline repository:** [train.py](https://github.com/YADAV1825/instinct.4B/blob/main/train.py) (Example link format)
126
+
127
+ ---
128
+
129
+ ### 🚀 Run Inference (Colab TPU/GPU)
130
+
131
+ The trained LLM inference script and model weights are available at: [autonomousX/instinct-1.4B on Hugging Face](https://huggingface.co/autonomousX).
132
+
133
+ ⚠️ **Disclaimer:** *This is a sample inference script originally written for the 0.5B (40B) variants. Please adjust parameters like `N_LAYERS`, `D_MODEL`, `N_HEADS`, `D_HEAD`, `D_FF`, etc., according to this specific model's architecture (1.4B) to run inference successfully.*
134
+
135
+ A ready-to-run Google Colab TPU/GPU inference script is provided below. Simply open a notebook, set your runtime to TPU or GPU, and run it. *(Please be patient, it may take around 20 mins to run the model initialization).*
136
+
137
+ <details>
138
+ <summary>Click here to view the full Inference Code</summary>
139
+
140
+ ```python
141
+ #please be patient It may take 20 mins to run the model
142
+ # Install huggingface_hub if not installed
143
+ !pip install -q huggingface_hub
144
+
145
+ from huggingface_hub import snapshot_download
146
+
147
+ repo_id = "autonomousX/instinct-1.4B"
148
+
149
+ # Download entire repository
150
+ local_path = snapshot_download(
151
+ repo_id=repo_id,
152
+ repo_type="model",
153
+ local_dir="TPU_1.4B",
154
+ local_dir_use_symlinks=False
155
+ )
156
+
157
+ print("Download complete!")
158
+ print("Saved to:", local_path)
159
+
160
+ # =========================
161
+ # FAST 1.4B INFERENCE CELL
162
+ # =========================
163
+
164
+ import os
165
+ import math
166
+ import jax
167
+ import jax.numpy as jnp
168
+ from flax import linen as nn
169
+ from flax.training import train_state, checkpoints
170
+ import optax
171
+ from transformers import AutoTokenizer
172
+
173
+ # ---------------- CONFIG ----------------
174
+ SEQ_LEN = 1024
175
+ VOCAB_SIZE = 50304
176
+
177
+ # NOTE: Adjust these parameters for your specific 1.4B architecture!
178
+ N_LAYERS = 32
179
+ D_MODEL = 1024
180
+ N_HEADS = 16
181
+ D_HEAD = 64
182
+ D_FF = 4096
183
+ ROTARY_PCT = 0.25
184
+
185
+ CKPT_PATH = os.path.abspath("TPU_1.4B/checkpoint_0")
186
+
187
+ # ---------------- RoPE ----------------
188
+ def build_rope_cache(seq_len, head_dim, rotary_pct):
189
+ dim = int(head_dim * rotary_pct)
190
+ freqs = 1.0 / (10000 ** (jnp.arange(0, dim, 2) / dim))
191
+ pos = jnp.arange(seq_len)
192
+ angles = jnp.einsum("i,j->ij", pos, freqs)
193
+ return jnp.sin(angles), jnp.cos(angles)
194
+
195
+ ROPE_SIN, ROPE_COS = build_rope_cache(SEQ_LEN, D_HEAD, ROTARY_PCT)
196
+
197
+ def apply_rope(q, k):
198
+ dim = int(D_HEAD * ROTARY_PCT)
199
+ T = q.shape[1]
200
+
201
+ sin = ROPE_SIN[:T][None, :, None, :]
202
+ cos = ROPE_COS[:T][None, :, None, :]
203
+
204
+ q_rot, q_pass = q[..., :dim], q[..., dim:]
205
+ k_rot, k_pass = k[..., :dim], k[..., dim:]
206
+
207
+ q1, q2 = q_rot[..., ::2], q_rot[..., 1::2]
208
+ k1, k2 = k_rot[..., ::2], k_rot[..., 1::2]
209
+
210
+ q_rot = jnp.concatenate(
211
+ [q1 * cos - q2 * sin,
212
+ q1 * sin + q2 * cos],
213
+ axis=-1
214
+ )
215
+
216
+ k_rot = jnp.concatenate(
217
+ [k1 * cos - k2 * sin,
218
+ k1 * sin + k2 * cos],
219
+ axis=-1
220
+ )
221
+
222
+ return (
223
+ jnp.concatenate([q_rot, q_pass], axis=-1),
224
+ jnp.concatenate([k_rot, k_pass], axis=-1),
225
+ )
226
+
227
+ # ---------------- MODEL ----------------
228
+ class RMSNorm(nn.Module):
229
+ dim: int
230
+ eps: float = 1e-6
231
+ @nn.compact
232
+ def __call__(self, x):
233
+ scale = self.param("scale", nn.initializers.ones, (self.dim,))
234
+ norm = jnp.sqrt(jnp.mean(x**2, axis=-1, keepdims=True) + self.eps)
235
+ return x * (scale / norm)
236
+
237
+ class Attention(nn.Module):
238
+ @nn.compact
239
+ def __call__(self, x, mask):
240
+ B, T, C = x.shape
241
+ qkv = nn.Dense(3 * C, use_bias=False, dtype=jnp.bfloat16)(x)
242
+ qkv = qkv.reshape(B, T, 3, N_HEADS, D_HEAD)
243
+
244
+ q = qkv[:, :, 0]
245
+ k = qkv[:, :, 1]
246
+ v = qkv[:, :, 2]
247
+
248
+ q, k = apply_rope(q, k)
249
+
250
+ att = jnp.einsum("bthd,bshd->bhts", q, k)
251
+ att = att / math.sqrt(D_HEAD)
252
+
253
+ mask = mask.astype(jnp.float32)
254
+ mask = (1.0 - mask) * -1e10
255
+ att = att + mask
256
+
257
+ att = nn.softmax(att.astype(jnp.float32), axis=-1)
258
+ att = att.astype(jnp.bfloat16)
259
+
260
+ out = jnp.einsum("bhts,bshd->bthd", att, v)
261
+ out = out.reshape(B, T, C)
262
+
263
+ return nn.Dense(C, use_bias=False, dtype=jnp.bfloat16)(out)
264
+
265
+ class Block(nn.Module):
266
+ @nn.compact
267
+ def __call__(self, x, mask):
268
+ h = RMSNorm(D_MODEL)(x)
269
+ h = Attention()(h, mask)
270
+ x = x + h
271
+
272
+ h = RMSNorm(D_MODEL)(x)
273
+ h = nn.Dense(D_FF, dtype=jnp.bfloat16)(h)
274
+ h = nn.gelu(h)
275
+ h = nn.Dense(D_MODEL, dtype=jnp.bfloat16)(h)
276
+
277
+ return x + h
278
+
279
+ class GPT(nn.Module):
280
+ @nn.compact
281
+ def __call__(self, input_ids):
282
+ batch, seq_len = input_ids.shape
283
+ mask = nn.attention.make_causal_mask(
284
+ jnp.ones((batch, seq_len), dtype=jnp.bool_)
285
+ )
286
+
287
+ x = nn.Embed(
288
+ VOCAB_SIZE,
289
+ D_MODEL,
290
+ embedding_init=nn.initializers.normal(0.02),
291
+ dtype=jnp.bfloat16,
292
+ )(input_ids)
293
+
294
+ RematBlock = nn.remat(Block)
295
+
296
+ for _ in range(N_LAYERS):
297
+ x = RematBlock()(x, mask)
298
+
299
+ x = RMSNorm(D_MODEL)(x)
300
+
301
+ return nn.Dense(
302
+ VOCAB_SIZE,
303
+ use_bias=False,
304
+ dtype=jnp.bfloat16
305
+ )(x)
306
+ # ---------------- LOAD CHECKPOINT ----------------
307
+ def create_state():
308
+ model = GPT()
309
+ rng = jax.random.PRNGKey(0)
310
+ params = model.init(rng, jnp.ones((1, SEQ_LEN), dtype=jnp.int32))
311
+ return train_state.TrainState.create(
312
+ apply_fn=model.apply,
313
+ params=params,
314
+ tx=optax.adamw(1e-4),
315
+ )
316
+
317
+ state = create_state()
318
+ state = checkpoints.restore_checkpoint(CKPT_PATH, state)
319
+ params = state.params
320
+ model = GPT()
321
+
322
+ print("Checkpoint loaded.")
323
+
324
+ @jax.jit
325
+ def forward(params, input_ids):
326
+ return model.apply(params, input_ids)
327
+
328
+ import jax.random as random
329
+
330
+ def generate(params, input_ids, max_new_tokens=30, temperature=0.9, top_k=40):
331
+ rng = random.PRNGKey(0)
332
+
333
+ for _ in range(max_new_tokens):
334
+
335
+ logits = model.apply(params, input_ids)
336
+ logits = logits[:, -1, :]
337
+ logits = logits.astype(jnp.float32)
338
+
339
+ logits = logits / temperature
340
+
341
+ top_k_logits, top_k_indices = jax.lax.top_k(logits, top_k)
342
+ probs = jax.nn.softmax(top_k_logits, axis=-1)
343
+
344
+ rng, subkey = random.split(rng)
345
+ next_token_idx = random.categorical(subkey, jnp.log(probs))
346
+
347
+ next_token = jnp.take_along_axis(
348
+ top_k_indices,
349
+ next_token_idx[:, None],
350
+ axis=-1
351
+ )
352
+
353
+ input_ids = jnp.concatenate([input_ids, next_token], axis=1)
354
+
355
+ return input_ids
356
+ # ---------------- RUN ----------------
357
+ tokenizer = AutoTokenizer.from_pretrained("autonomousX/instinct-1.4B")
358
+
359
+ prompt = "I am John,"
360
+ tokens = tokenizer(prompt, return_tensors="np")
361
+ input_ids = jnp.array(tokens["input_ids"], dtype=jnp.int32)
362
+
363
+ output_ids = generate(params, input_ids, 200)
364
+
365
+ print("\n=== GENERATED TEXT ===\n")
366
+ print(tokenizer.decode(output_ids[0].tolist()))
367
+ ```
368
+ </details>