yrrhall LH-Tech-AI commited on
Commit
f21e4a8
·
0 Parent(s):

Duplicate from SupraLabs/Supra-Mini-v2-0.1M

Browse files

Co-authored-by: LH-Tech AI <[email protected]>

.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ datasets:
4
+ - HuggingFaceFW/fineweb-edu
5
+ language:
6
+ - en
7
+ pipeline_tag: text-generation
8
+ library_name: transformers
9
+ tags:
10
+ - small
11
+ - cpu
12
+ - supra
13
+ - v2
14
+ - tiny
15
+ - mini
16
+ - open
17
+ - open-source
18
+ new_version: SupraLabs/Supra-Mini-v4-2M
19
+ ---
20
+
21
+ # 🦅 Supra Mini v2 0.1M
22
+ Supra Mini **v2** 0.1M is a very, and we mean very small base model trained on 700 million tokens of Fineweb-Edu for 3 epochs as the **second version** of our Supra Mini series.
23
+
24
+ ## Model Config
25
+
26
+ - Parameters: 167,760 (0.1M)
27
+ - Architecture: Llama
28
+ - Vocab size with custom BPE tokenizer: 2048
29
+ - Hidden Size: 48
30
+ - Intermediate Size: 96
31
+ - Hidden Layers: 3
32
+ - Attention Heads: 4
33
+ - Max Position Embeddings: 256
34
+ - Learning rate: 6e-4
35
+ - Weight Decay: 0.01
36
+
37
+ ## Final Loss
38
+ This model reached a final train loss of **4.413**.
39
+
40
+ ## Benchmarks
41
+
42
+ All benchmarks were executed using `lm-eval`.
43
+
44
+ | Task | Value | Random level |
45
+ | :------------ | :----------: | -----------: |
46
+ | Arc_Easy | 0.2677 | 0.25 (25%) |
47
+ | Wikitext | 7.7940 | - |
48
+ | BLiMP | 0.5354 | 0.5 (50%) |
49
+
50
+ ## Examples
51
+ **Prompt:** "Artificial intelligence is "<br>
52
+ **Output:**: *"Artificial intelligence is irreciously, and the diet of a battery.
53
+ These are also known as the following:
54
+ \- Foods, in the most commonly used to be taken by the priority of the South African American Modela, which was nothing for the first time. The federal government has been a wall of the world’s two moisture and the came on the national range of the Great Department of Amazonia, and the Politary Society of the Carli. This is that the Letters were the first third of the Building S"*
55
+ <br><br>
56
+ **Prompt:** "The main concept of physics is "<br>
57
+ **Output:**: *"The main concept of physics is utilized in the most commonly used to be achieved.
58
+ Chotos, an efficient for a dietary pathogene, and that are also known as a source of the molecularly. The failure wastered in the national categories of the California, and the Modela’s brought by the Florida. In the world's this time, it is not only on the sense of the first-metrial gardens, but they can be living in the task of the Political School of History (professed"*
59
+ <br><br>
60
+ **Prompt:** "Once upon a time, "<br>
61
+ **Output:**: *"Once upon a time, utilizing the fire.
62
+ The Samboard is that the lot of the bill.
63
+ After the day to be a widely money and in the world’s a harmful force.
64
+ Despite the size of the Bradese, and his owner, and he was noted by the Department of Management, and the Lord of Petersonia and the Council, which had been a destroyed on the tree, but the giving a came from the Hiska. The Great Marius and Jewish Amazon's Rich"*
65
+
66
+ ## Usage
67
+ To use our model, just run this code using HF Transformers to execute the model:
68
+ ```python3
69
+ from transformers import pipeline
70
+ import torch
71
+
72
+ print("[*] Loading Supra Mini v2 0.1M model from Hugging Face Hub...")
73
+ pipe = pipeline(
74
+ "text-generation",
75
+ model="SupraLabs/Supra-Mini-v2-0.1M",
76
+ device_map="auto",
77
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
78
+ )
79
+
80
+ def generate_text(prompt, max_length=150):
81
+ result = pipe(
82
+ prompt,
83
+ max_new_tokens=max_length,
84
+ do_sample=True,
85
+ temperature=0.5,
86
+ top_k=25,
87
+ top_p=0.9,
88
+ repetition_penalty=1.2,
89
+ pad_token_id=pipe.tokenizer.pad_token_id,
90
+ eos_token_id=pipe.tokenizer.eos_token_id
91
+ )
92
+ return result[0]['generated_text']
93
+
94
+ test_prompt = "The importance of education is"
95
+ print(f"\nPrompt: {test_prompt}")
96
+ print("-" * 30)
97
+ print("\nOutput:\n" + generate_text(test_prompt))
98
+ ```
99
+
100
+ ## Use cases
101
+
102
+ 1. Educational research
103
+ 2. deployment or testing/fine-tuning on edge environments
104
+ 3. Or more simply, for fun
105
+
106
+ ## Limitations
107
+
108
+ 1. Cannot reason, chat, or code
109
+ 2. Incoherent more often than not
110
+ 3. Mostly unfactual
111
+
112
+ ## Training guide
113
+ We trained Supra Mini v2 0.1M on a single T4 GPU in ~2 hours for 3 epochs.<br>
114
+ The full training code can be found in this repo as `run.sh` (easily run the complete pipeline), `train_tokenizer.py` (train costum BPE tokenizer with vocab size of 2048), `train.py` (train the model) and `inference.py` (test the model).<br>
115
+ The model was trained on the first 700 million tokens of Sample-10BT from Fineweb-Edu using streaming tokenization.
116
+
117
+ ## Final thoughts
118
+ As this is the second version of the Supra Mini series, we are very proud to release it today!<br>
119
+ *But:* stay tuned for more models and follow us to support our open-source work! 😊
benchmarks.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ | Tasks |Version|Filter|n-shot| Metric | | Value | |Stderr|
2
+ |------------------------------------------------------------|------:|------|-----:|---------------|---|---------:|---|------|
3
+ |blimp | 2|none | 0|acc |↑ | 0.5354|± |0.0017|
4
+ | - blimp_adjunct_island | 1|none | 0|acc |↑ | 0.5980|± |0.0155|
5
+ | - blimp_anaphor_gender_agreement | 1|none | 0|acc |↑ | 0.3130|± |0.0147|
6
+ | - blimp_anaphor_number_agreement | 1|none | 0|acc |↑ | 0.5090|± |0.0158|
7
+ | - blimp_animate_subject_passive | 1|none | 0|acc |↑ | 0.5750|± |0.0156|
8
+ | - blimp_animate_subject_trans | 1|none | 0|acc |↑ | 0.7470|± |0.0138|
9
+ | - blimp_causative | 1|none | 0|acc |↑ | 0.4810|± |0.0158|
10
+ | - blimp_complex_NP_island | 1|none | 0|acc |↑ | 0.4880|± |0.0158|
11
+ | - blimp_coordinate_structure_constraint_complex_left_branch| 1|none | 0|acc |↑ | 0.1420|± |0.0110|
12
+ | - blimp_coordinate_structure_constraint_object_extraction | 1|none | 0|acc |↑ | 0.5820|± |0.0156|
13
+ | - blimp_determiner_noun_agreement_1 | 1|none | 0|acc |↑ | 0.6580|± |0.0150|
14
+ | - blimp_determiner_noun_agreement_2 | 1|none | 0|acc |↑ | 0.6320|± |0.0153|
15
+ | - blimp_determiner_noun_agreement_irregular_1 | 1|none | 0|acc |↑ | 0.5150|± |0.0158|
16
+ | - blimp_determiner_noun_agreement_irregular_2 | 1|none | 0|acc |↑ | 0.6980|± |0.0145|
17
+ | - blimp_determiner_noun_agreement_with_adj_2 | 1|none | 0|acc |↑ | 0.5780|± |0.0156|
18
+ | - blimp_determiner_noun_agreement_with_adj_irregular_1 | 1|none | 0|acc |↑ | 0.4220|± |0.0156|
19
+ | - blimp_determiner_noun_agreement_with_adj_irregular_2 | 1|none | 0|acc |↑ | 0.5170|± |0.0158|
20
+ | - blimp_determiner_noun_agreement_with_adjective_1 | 1|none | 0|acc |↑ | 0.6070|± |0.0155|
21
+ | - blimp_distractor_agreement_relational_noun | 1|none | 0|acc |↑ | 0.3120|± |0.0147|
22
+ | - blimp_distractor_agreement_relative_clause | 1|none | 0|acc |↑ | 0.3110|± |0.0146|
23
+ | - blimp_drop_argument | 1|none | 0|acc |↑ | 0.7270|± |0.0141|
24
+ | - blimp_ellipsis_n_bar_1 | 1|none | 0|acc |↑ | 0.2180|± |0.0131|
25
+ | - blimp_ellipsis_n_bar_2 | 1|none | 0|acc |↑ | 0.3480|± |0.0151|
26
+ | - blimp_existential_there_object_raising | 1|none | 0|acc |↑ | 0.6860|± |0.0147|
27
+ | - blimp_existential_there_quantifiers_1 | 1|none | 0|acc |↑ | 0.8100|± |0.0124|
28
+ | - blimp_existential_there_quantifiers_2 | 1|none | 0|acc |↑ | 0.2950|± |0.0144|
29
+ | - blimp_existential_there_subject_raising | 1|none | 0|acc |↑ | 0.6880|± |0.0147|
30
+ | - blimp_expletive_it_object_raising | 1|none | 0|acc |↑ | 0.6570|± |0.0150|
31
+ | - blimp_inchoative | 1|none | 0|acc |↑ | 0.3850|± |0.0154|
32
+ | - blimp_intransitive | 1|none | 0|acc |↑ | 0.5170|± |0.0158|
33
+ | - blimp_irregular_past_participle_adjectives | 1|none | 0|acc |↑ | 0.6620|± |0.0150|
34
+ | - blimp_irregular_past_participle_verbs | 1|none | 0|acc |↑ | 0.5050|± |0.0158|
35
+ | - blimp_irregular_plural_subject_verb_agreement_1 | 1|none | 0|acc |↑ | 0.5880|± |0.0156|
36
+ | - blimp_irregular_plural_subject_verb_agreement_2 | 1|none | 0|acc |↑ | 0.5860|± |0.0156|
37
+ | - blimp_left_branch_island_echo_question | 1|none | 0|acc |↑ | 0.9020|± |0.0094|
38
+ | - blimp_left_branch_island_simple_question | 1|none | 0|acc |↑ | 0.2310|± |0.0133|
39
+ | - blimp_matrix_question_npi_licensor_present | 1|none | 0|acc |↑ | 0.0380|± |0.0060|
40
+ | - blimp_npi_present_1 | 1|none | 0|acc |↑ | 0.6520|± |0.0151|
41
+ | - blimp_npi_present_2 | 1|none | 0|acc |↑ | 0.6390|± |0.0152|
42
+ | - blimp_only_npi_licensor_present | 1|none | 0|acc |↑ | 0.0400|± |0.0062|
43
+ | - blimp_only_npi_scope | 1|none | 0|acc |↑ | 0.0020|± |0.0014|
44
+ | - blimp_passive_1 | 1|none | 0|acc |↑ | 0.6520|± |0.0151|
45
+ | - blimp_passive_2 | 1|none | 0|acc |↑ | 0.6280|± |0.0153|
46
+ | - blimp_principle_A_c_command | 1|none | 0|acc |↑ | 0.6890|± |0.0146|
47
+ | - blimp_principle_A_case_1 | 1|none | 0|acc |↑ | 0.9990|± |0.0010|
48
+ | - blimp_principle_A_case_2 | 1|none | 0|acc |↑ | 0.4450|± |0.0157|
49
+ | - blimp_principle_A_domain_1 | 1|none | 0|acc |↑ | 0.8820|± |0.0102|
50
+ | - blimp_principle_A_domain_2 | 1|none | 0|acc |↑ | 0.5450|± |0.0158|
51
+ | - blimp_principle_A_domain_3 | 1|none | 0|acc |↑ | 0.4690|± |0.0158|
52
+ | - blimp_principle_A_reconstruction | 1|none | 0|acc |↑ | 0.3830|± |0.0154|
53
+ | - blimp_regular_plural_subject_verb_agreement_1 | 1|none | 0|acc |↑ | 0.6890|± |0.0146|
54
+ | - blimp_regular_plural_subject_verb_agreement_2 | 1|none | 0|acc |↑ | 0.5760|± |0.0156|
55
+ | - blimp_sentential_negation_npi_licensor_present | 1|none | 0|acc |↑ | 0.9990|± |0.0010|
56
+ | - blimp_sentential_negation_npi_scope | 1|none | 0|acc |↑ | 0.4590|± |0.0158|
57
+ | - blimp_sentential_subject_island | 1|none | 0|acc |↑ | 0.2760|± |0.0141|
58
+ | - blimp_superlative_quantifiers_1 | 1|none | 0|acc |↑ | 0.3040|± |0.0146|
59
+ | - blimp_superlative_quantifiers_2 | 1|none | 0|acc |↑ | 0.3620|± |0.0152|
60
+ | - blimp_tough_vs_raising_1 | 1|none | 0|acc |↑ | 0.3310|± |0.0149|
61
+ | - blimp_tough_vs_raising_2 | 1|none | 0|acc |↑ | 0.6970|± |0.0145|
62
+ | - blimp_transitive | 1|none | 0|acc |↑ | 0.6560|± |0.0150|
63
+ | - blimp_wh_island | 1|none | 0|acc |↑ | 0.5110|± |0.0158|
64
+ | - blimp_wh_questions_object_gap | 1|none | 0|acc |↑ | 0.6180|± |0.0154|
65
+ | - blimp_wh_questions_subject_gap | 1|none | 0|acc |↑ | 0.9480|± |0.0070|
66
+ | - blimp_wh_questions_subject_gap_long_distance | 1|none | 0|acc |↑ | 0.8930|± |0.0098|
67
+ | - blimp_wh_vs_that_no_gap | 1|none | 0|acc |↑ | 0.9960|± |0.0020|
68
+ | - blimp_wh_vs_that_no_gap_long_distance | 1|none | 0|acc |↑ | 0.9910|± |0.0030|
69
+ | - blimp_wh_vs_that_with_gap | 1|none | 0|acc |↑ | 0.0090|± |0.0030|
70
+ | - blimp_wh_vs_that_with_gap_long_distance | 1|none | 0|acc |↑ | 0.0040|± |0.0020|
71
+ |arc_easy | 1|none | 0|acc |↑ | 0.2677|± |0.0091|
72
+ | | |none | 0|acc_norm |↑ | 0.2841|± |0.0093|
73
+ |wikitext | 2|none | 0|bits_per_byte |↓ | 2.9624|± | N/A|
74
+ | | |none | 0|byte_perplexity|↓ | 7.7940|± | N/A|
75
+ | | |none | 0|word_perplexity|↓ |58699.2441|± | N/A|
76
+
77
+ |Groups|Version|Filter|n-shot|Metric| |Value | |Stderr|
78
+ |------|------:|------|-----:|------|---|-----:|---|-----:|
79
+ |blimp | 2|none | 0|acc |↑ |0.5354|± |0.0017|
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LlamaForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "dtype": "float32",
9
+ "eos_token_id": 2,
10
+ "head_dim": 12,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 48,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 96,
15
+ "max_position_embeddings": 256,
16
+ "mlp_bias": false,
17
+ "model_type": "llama",
18
+ "num_attention_heads": 4,
19
+ "num_hidden_layers": 3,
20
+ "num_key_value_heads": 4,
21
+ "pad_token_id": 1,
22
+ "pretraining_tp": 1,
23
+ "rms_norm_eps": 1e-06,
24
+ "rope_parameters": {
25
+ "rope_theta": 10000.0,
26
+ "rope_type": "default"
27
+ },
28
+ "tie_word_embeddings": true,
29
+ "transformers_version": "5.0.0",
30
+ "use_cache": false,
31
+ "vocab_size": 2048
32
+ }
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 2,
5
+ "output_attentions": false,
6
+ "output_hidden_states": false,
7
+ "pad_token_id": 1,
8
+ "transformers_version": "5.0.0",
9
+ "use_cache": true
10
+ }
inference.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ print("[*] Loading libraries...")
2
+ import torch
3
+ from transformers import LlamaForCausalLM, PreTrainedTokenizerFast
4
+
5
+ model_path = "./Supra-Mini-v2-0.1m-FINAL"
6
+
7
+ print("[*] Loading tokenizer...")
8
+ tokenizer = PreTrainedTokenizerFast.from_pretrained(model_path)
9
+
10
+ print("[*] Loading model...")
11
+ model = LlamaForCausalLM.from_pretrained(model_path)
12
+ model.eval()
13
+
14
+ prompt = "The main concept of physics is "
15
+ print(f"[*] Prompt: {prompt!r}")
16
+
17
+ inputs = tokenizer(prompt, return_tensors="pt")
18
+
19
+ with torch.no_grad():
20
+ outputs = model.generate(
21
+ input_ids=inputs["input_ids"],
22
+ attention_mask=inputs["attention_mask"],
23
+ max_new_tokens=150,
24
+ do_sample=True,
25
+ temperature=0.35,
26
+ top_p=0.85,
27
+ repetition_penalty=1.2,
28
+ pad_token_id=tokenizer.pad_token_id,
29
+ eos_token_id=tokenizer.eos_token_id,
30
+ )
31
+
32
+ print("[*] Output:", tokenizer.decode(outputs[0], skip_special_tokens=True))
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2903fbf80d221058f5b6280e1f9bc8832eda5a4d5da0d5f5d54b5d5f81376164
3
+ size 674032
run.sh ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ pip install -q transformers datasets sentencepiece accelerate
2
+ python3 train_tokenizer.py
3
+ python3 train_model.py
4
+ python3 inference.py
5
+ sed -i 's/"max_position_embeddings": 256/"max_position_embeddings": 1024/' Supra-Mini-v2-0.1m-FINAL/config.json
6
+ pip install lm-eval
7
+ lm_eval --model hf --model_args pretrained=./Supra-Mini-v2-0.1m-FINAL,max_length=1024 --tasks arc_easy,wikitext,blimp --device cuda --batch_size 16
8
+ sed -i 's/"max_position_embeddings": 1024/"max_position_embeddings": 256/' Supra-Mini-v2-0.1m-FINAL/config.json
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<s>",
4
+ "eos_token": "</s>",
5
+ "model_max_length": 1000000000000000019884624838656,
6
+ "pad_token": "<pad>",
7
+ "tokenizer_class": "TokenizersBackend",
8
+ "unk_token": "<unk>"
9
+ }
train_model.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ["PYTORCH_ALLOC_CONF"] = "expandable_segments:True"
3
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
4
+
5
+ print("[*] Loading libraries...")
6
+ import torch
7
+ import math
8
+ import numpy as np
9
+ from datasets import load_dataset
10
+ from tokenizers import ByteLevelBPETokenizer
11
+ from transformers import (
12
+ LlamaConfig,
13
+ LlamaForCausalLM,
14
+ PreTrainedTokenizerFast,
15
+ Trainer,
16
+ TrainingArguments,
17
+ )
18
+ from torch.utils.data import Dataset
19
+ from tqdm import tqdm
20
+
21
+ print("[*] Loading tokenizer...")
22
+ fast_tokenizer = ByteLevelBPETokenizer(
23
+ "./custom_llama_tokenizer-vocab.json",
24
+ "./custom_llama_tokenizer-merges.txt"
25
+ )
26
+ tokenizer = PreTrainedTokenizerFast(
27
+ tokenizer_object=fast_tokenizer,
28
+ bos_token="<s>",
29
+ eos_token="</s>",
30
+ unk_token="<unk>",
31
+ pad_token="<pad>",
32
+ )
33
+
34
+ TOKEN_BIN = "/kaggle/working/tokens.bin"
35
+ TARGET_TOKENS = 700_000_000
36
+ SEQ_LEN = 256
37
+ BATCH_TEXTS = 1000
38
+ FLUSH_EVERY = 1_000_000
39
+
40
+
41
+ def build_token_bin(fast_tokenizer, path=TOKEN_BIN, target_tokens=TARGET_TOKENS):
42
+ if os.path.exists(path) and os.path.getsize(path) >= target_tokens * 2:
43
+ print(f"[=] Reusing existing token file: {path}")
44
+ return
45
+
46
+ print(f"[*] Streaming + tokenizing {target_tokens:,} tokens → {path}")
47
+ mm = np.memmap(path, dtype=np.uint16, mode="w+", shape=(target_tokens,))
48
+
49
+ dataset = load_dataset(
50
+ "HuggingFaceFW/fineweb-edu", "sample-10BT",
51
+ split="train", streaming=True
52
+ )
53
+
54
+ written = 0
55
+ buf = []
56
+ texts = []
57
+ pbar = tqdm(total=target_tokens, desc="[*] Gathering tokens", unit="tok")
58
+
59
+ def flush_buf():
60
+ nonlocal written, buf
61
+ if not buf:
62
+ return False
63
+ n = min(len(buf), target_tokens - written)
64
+ mm[written:written + n] = np.asarray(buf[:n], dtype=np.uint16)
65
+ written += n
66
+ pbar.update(n)
67
+ del buf[:n]
68
+ return written >= target_tokens
69
+
70
+ for example in dataset:
71
+ texts.append(example["text"])
72
+ if len(texts) >= BATCH_TEXTS:
73
+ encs = fast_tokenizer.encode_batch(texts)
74
+ texts.clear()
75
+ for e in encs:
76
+ buf.extend(e.ids)
77
+ if len(buf) >= FLUSH_EVERY:
78
+ if flush_buf():
79
+ break
80
+
81
+ if written < target_tokens and texts:
82
+ encs = fast_tokenizer.encode_batch(texts)
83
+ for e in encs:
84
+ buf.extend(e.ids)
85
+ if written < target_tokens:
86
+ flush_buf()
87
+
88
+ pbar.close()
89
+ mm.flush()
90
+ del mm
91
+ print(f"[+] Wrote {written:,} tokens to {path} "
92
+ f"({os.path.getsize(path)/1e6:.1f} MB)")
93
+
94
+
95
+ class MemmapDataset(Dataset):
96
+ def __init__(self, path, total_tokens, seq_len=SEQ_LEN):
97
+ self.path = path
98
+ self.seq_len = seq_len
99
+ self.n_chunks = total_tokens // seq_len
100
+ self._data = None # lazy open (Multiprocessing-safe)
101
+
102
+ @property
103
+ def data(self):
104
+ if self._data is None:
105
+ self._data = np.memmap(
106
+ self.path, dtype=np.uint16, mode="r",
107
+ shape=(self.n_chunks * self.seq_len,)
108
+ )
109
+ return self._data
110
+
111
+ def __len__(self):
112
+ return self.n_chunks
113
+
114
+ def __getitem__(self, idx):
115
+ s = idx * self.seq_len
116
+ arr = np.asarray(self.data[s:s + self.seq_len], dtype=np.int64)
117
+ ids = torch.from_numpy(arr)
118
+ return {"input_ids": ids, "labels": ids.clone()}
119
+
120
+
121
+ def collate_fn(batch):
122
+ input_ids = torch.stack([b["input_ids"] for b in batch])
123
+ labels = torch.stack([b["labels"] for b in batch])
124
+ return {"input_ids": input_ids, "labels": labels}
125
+
126
+
127
+ print(f"[*] Preparing {TARGET_TOKENS:,} tokens (streaming, memmap-backed)...")
128
+ build_token_bin(fast_tokenizer, TOKEN_BIN, TARGET_TOKENS)
129
+ dataset = MemmapDataset(TOKEN_BIN, TARGET_TOKENS, seq_len=SEQ_LEN)
130
+ print(f"[+] Dataset ready: {len(dataset):,} chunks of {SEQ_LEN} tokens")
131
+
132
+ print("[*] Setting up model...")
133
+ config = LlamaConfig(
134
+ vocab_size=len(tokenizer.get_vocab()),
135
+ hidden_size=48,
136
+ intermediate_size=96,
137
+ num_hidden_layers=3,
138
+ num_attention_heads=4,
139
+ max_position_embeddings=256,
140
+ tie_word_embeddings=True,
141
+ pad_token_id=tokenizer.pad_token_id,
142
+ bos_token_id=tokenizer.bos_token_id,
143
+ eos_token_id=tokenizer.eos_token_id,
144
+ )
145
+ model = LlamaForCausalLM(config)
146
+ print(f"[*] Model parameters: {model.num_parameters():,}")
147
+
148
+ print("[*] Defining training arguments...")
149
+ training_args = TrainingArguments(
150
+ output_dir="./Supra-Mini-v2-0.1m",
151
+ num_train_epochs=3,
152
+ per_device_train_batch_size=1024,
153
+ gradient_accumulation_steps=1,
154
+ save_steps=500,
155
+ save_total_limit=2,
156
+ logging_steps=100,
157
+ weight_decay=0.01,
158
+ fp16=torch.cuda.is_available(),
159
+ push_to_hub=False,
160
+ report_to="none",
161
+ dataloader_num_workers=2,
162
+ dataloader_pin_memory=True,
163
+ learning_rate=6e-4,
164
+ lr_scheduler_type="cosine",
165
+ warmup_ratio=0.05,
166
+ )
167
+
168
+ trainer = Trainer(
169
+ model=model,
170
+ args=training_args,
171
+ train_dataset=dataset,
172
+ data_collator=collate_fn,
173
+ )
174
+
175
+ print("[*] Starting training...")
176
+ trainer.train()
177
+ trainer.save_model("./Supra-Mini-v2-0.1m-FINAL")
178
+ tokenizer.save_pretrained("./Supra-Mini-v2-0.1m-FINAL")
179
+ print("[*] Training finished.")
train_tokenizer.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ print("[*] Loading libraries...")
2
+ from datasets import load_dataset
3
+ from tokenizers import ByteLevelBPETokenizer
4
+
5
+ dataset = load_dataset("HuggingFaceFW/fineweb-edu", "sample-10BT", split="train", streaming=True)
6
+ def get_training_corpus():
7
+ dataset_iter = iter(dataset)
8
+ for _ in range(50000):
9
+ yield next(dataset_iter)["text"]
10
+
11
+ tokenizer = ByteLevelBPETokenizer()
12
+
13
+ print("[*] Training tokenizer...")
14
+
15
+ tokenizer.train_from_iterator(
16
+ get_training_corpus(),
17
+ vocab_size=2048,
18
+ min_frequency=2,
19
+ special_tokens=["<s>", "<pad>", "</s>", "<unk>", "<mask>"]
20
+ )
21
+
22
+ tokenizer.save_model(".", "custom_llama_tokenizer")
23
+ print("[*] Tokenizer training complete!")
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:475e4bde8bedd30ee7a419e297d7166e343668fec0ee93cf9fa1436fc10e0a96
3
+ size 5201