autonomousX
/

YADAV0206 commited on
Commit
f13d77f
·
verified ·
1 Parent(s): 292c5f4

Create README.md

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