piyushgrover commited on
Commit
46ed6bb
1 Parent(s): 3f5588e

added init files

Browse files
app.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import gradio as gr
4
+ from tsai_gpt.tokenizer import Tokenizer
5
+ import lightning as L
6
+ from lightning.fabric.loggers import CSVLogger
7
+ from pathlib import Path
8
+ from tsai_gpt.utils import num_parameters, load_checkpoint, get_default_supported_precision
9
+ from tsai_gpt.model import GPT, Block, Config
10
+
11
+ model_name = "pythia-160m"
12
+ name = "redpajama"
13
+ out_dir = Path("out") / name
14
+ log_interval = 100
15
+
16
+ precision = get_default_supported_precision(False)
17
+ logger = CSVLogger("out", name, flush_logs_every_n_steps=log_interval)
18
+ fabric = L.Fabric(devices=1, strategy="auto", precision=precision, loggers=logger)
19
+
20
+ config = Config.from_name(model_name)
21
+
22
+
23
+ def _init_weights(module: nn.Module) -> None:
24
+ """Meant to be used with `gpt.apply(gpt._init_weights)`."""
25
+ if isinstance(module, nn.Linear):
26
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
27
+ if module.bias is not None:
28
+ torch.nn.init.zeros_(module.bias)
29
+ elif isinstance(module, nn.Embedding):
30
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
31
+
32
+
33
+ with fabric.init_module(empty_init=True):
34
+ model = GPT(config)
35
+ model.apply(_init_weights)
36
+ model.apply(_init_weights)
37
+
38
+ checkpoint_path = Path("out/redpajama/iter-025000-ckpt.pth")
39
+
40
+ load_checkpoint(fabric, model, checkpoint_path)
41
+
42
+ # print(model.transformer.h[0].mlp.fc.weight)
43
+
44
+ # fabric.print(f"Time to instantiate model: {time.perf_counter() - t0:.02f} seconds.")
45
+ # fabric.print(f"Total parameters {num_parameters(model):,}")
46
+
47
+ weight_decay = 1e-1
48
+ beta1 = 0.9
49
+ beta2 = 0.95
50
+ learning_rate = 6e-3
51
+ hparams = {k: v for k, v in locals().items() if isinstance(v, (int, float, str)) and not k.startswith("_")}
52
+
53
+ model = fabric.setup(model)
54
+ optimizer = torch.optim.AdamW(
55
+ model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2), foreach=False
56
+ )
57
+
58
+ # model_copy = model
59
+
60
+ optimizer = fabric.setup_optimizers(optimizer)
61
+
62
+ state = {"model": model, "optimizer": optimizer, "hparams": hparams, "iter_num": 0, "step_count": 0}
63
+
64
+ resume = max(out_dir.glob("*.pth"), key=lambda p: int(p.name.split("-")[1]))
65
+ if resume:
66
+ fabric.print(f"Loading model from {resume}")
67
+ fabric.load(resume, state)
68
+
69
+ deviceType = 'cuda' if torch.cuda.is_available() else 'cpu'
70
+ m = model.to(deviceType)
71
+ tokenizer_gpt = Tokenizer(checkpoint_dir=Path("checkpoints/meta-llama/Llama-2-7b-chat-hf"))
72
+
73
+
74
+ def fn_query_on_load():
75
+ return "Biofuels would disrupt"
76
+
77
+
78
+ def generate_output(prompt, max_new_tokens=200, temperature=0.8, top_k=50):
79
+ m.eval()
80
+ encoded_text = tokenizer_gpt.encode(prompt)
81
+ # print('--------------------encoded text = ',encoded_text)
82
+
83
+ reshaped_tensor = torch.unsqueeze(encoded_text, 0).to(deviceType)
84
+ # print('--------------------reshaped_tensor = ',reshaped_tensor)
85
+ out_text = tokenizer_gpt.decode(
86
+ m.generate(reshaped_tensor, max_new_tokens=max_new_tokens, temperature=0.8, top_k=50)[0])
87
+
88
+ m.train()
89
+ return {
90
+ output: out_text
91
+ }
92
+
93
+
94
+ with gr.Blocks() as app:
95
+ with gr.Row():
96
+ gr.Markdown(
97
+ """
98
+ # MiniGPT - GPT Training on LLaMa with redpajama dataset
99
+ ### Enter a context to generate automated text "
100
+ """)
101
+
102
+ with gr.Row(visible=True):
103
+ search_text = gr.Textbox(value=fn_query_on_load, placeholder='Enter prompt..', label='Enter Prompt')
104
+
105
+ with gr.Row():
106
+ submit_btn = gr.Button("Submit", variant='primary')
107
+ clear_btn = gr.ClearButton()
108
+ with gr.Row():
109
+ with gr.Row():
110
+ output = gr.Textbox(lines=15, interactive=False, label='Out Box')
111
+
112
+ def clear_data():
113
+ return {
114
+ output: None,
115
+ search_text: None
116
+ }
117
+
118
+ clear_btn.click(clear_data, None, [output, search_text])
119
+
120
+
121
+ submit_btn.click(
122
+ generate_output,
123
+ search_text,
124
+ output
125
+ )
126
+
127
+
128
+ '''
129
+ Launch the app
130
+ '''
131
+ app.queue().launch()
checkpoints/.DS_Store ADDED
Binary file (6.15 kB). View file
 
checkpoints/generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "do_sample": true,
4
+ "eos_token_id": 2,
5
+ "max_length": 4096,
6
+ "pad_token_id": 0,
7
+ "temperature": 0.6,
8
+ "top_p": 0.9,
9
+ "transformers_version": "4.32.0.dev0"
10
+ }
checkpoints/lit_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"name": "Llama-2-7b-chat-hf", "hf_config": {"org": "meta-llama", "name": "Llama-2-7b-chat-hf"}, "block_size": 4096, "vocab_size": 32000, "padding_multiple": 64, "padded_vocab_size": 32000, "n_layer": 32, "n_head": 32, "n_embd": 4096, "rotary_percentage": 1.0, "parallel_residual": false, "bias": false, "lm_head_bias": false, "n_query_groups": 32, "shared_attention_norm": false, "_norm_class": "RMSNorm", "norm_eps": 1e-05, "_mlp_class": "LLaMAMLP", "gelu_approximate": "none", "intermediate_size": 11008, "rope_condense_ratio": 1, "rope_base": 10000}
checkpoints/meta-llama/Llama-2-7b-chat-hf/generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "do_sample": true,
4
+ "eos_token_id": 2,
5
+ "max_length": 4096,
6
+ "pad_token_id": 0,
7
+ "temperature": 0.6,
8
+ "top_p": 0.9,
9
+ "transformers_version": "4.32.0.dev0"
10
+ }
checkpoints/meta-llama/Llama-2-7b-chat-hf/lit_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"name": "Llama-2-7b-chat-hf", "hf_config": {"org": "meta-llama", "name": "Llama-2-7b-chat-hf"}, "block_size": 4096, "vocab_size": 32000, "padding_multiple": 64, "padded_vocab_size": 32000, "n_layer": 32, "n_head": 32, "n_embd": 4096, "rotary_percentage": 1.0, "parallel_residual": false, "bias": false, "lm_head_bias": false, "n_query_groups": 32, "shared_attention_norm": false, "_norm_class": "RMSNorm", "norm_eps": 1e-05, "_mlp_class": "LLaMAMLP", "gelu_approximate": "none", "intermediate_size": 11008, "rope_condense_ratio": 1, "rope_base": 10000}
checkpoints/meta-llama/Llama-2-7b-chat-hf/pytorch_model.bin.index.json ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 13476839424
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00002-of-00002.bin",
7
+ "model.embed_tokens.weight": "pytorch_model-00001-of-00002.bin",
8
+ "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
9
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
10
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
11
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
12
+ "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
13
+ "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
14
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
15
+ "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
16
+ "model.layers.0.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
17
+ "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
18
+ "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
19
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
20
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
21
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
22
+ "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
23
+ "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
24
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
25
+ "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
26
+ "model.layers.1.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
27
+ "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
28
+ "model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
29
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
30
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
31
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
32
+ "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
33
+ "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
34
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
35
+ "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
36
+ "model.layers.10.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
37
+ "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
38
+ "model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
39
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
40
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
41
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
42
+ "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
43
+ "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
44
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
45
+ "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
46
+ "model.layers.11.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
47
+ "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
48
+ "model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
49
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
50
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
51
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
52
+ "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
53
+ "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
54
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
55
+ "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
56
+ "model.layers.12.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
57
+ "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
58
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
59
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
60
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
61
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
62
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
63
+ "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
64
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
65
+ "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
66
+ "model.layers.13.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
67
+ "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
68
+ "model.layers.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
69
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
70
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
71
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
72
+ "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
73
+ "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
74
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
75
+ "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
76
+ "model.layers.14.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
77
+ "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
78
+ "model.layers.15.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
79
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
80
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
81
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
82
+ "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
83
+ "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
84
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
85
+ "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
86
+ "model.layers.15.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
87
+ "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
88
+ "model.layers.16.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
89
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
90
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
91
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
92
+ "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
93
+ "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
94
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
95
+ "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
96
+ "model.layers.16.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
97
+ "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
98
+ "model.layers.17.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
99
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
100
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
101
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
102
+ "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
103
+ "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
104
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
105
+ "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
106
+ "model.layers.17.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
107
+ "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
108
+ "model.layers.18.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
109
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
110
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
111
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
112
+ "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
113
+ "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
114
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
115
+ "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
116
+ "model.layers.18.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
117
+ "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
118
+ "model.layers.19.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
119
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
120
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
121
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
122
+ "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
123
+ "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
124
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
125
+ "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
126
+ "model.layers.19.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
127
+ "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
128
+ "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
129
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
130
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
131
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
132
+ "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
133
+ "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
134
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
135
+ "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
136
+ "model.layers.2.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
137
+ "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
138
+ "model.layers.20.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
139
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
140
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
141
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
142
+ "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
143
+ "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
144
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
145
+ "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
146
+ "model.layers.20.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
147
+ "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
148
+ "model.layers.21.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
149
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
150
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
151
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
152
+ "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
153
+ "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
154
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
155
+ "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
156
+ "model.layers.21.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
157
+ "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
158
+ "model.layers.22.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
159
+ "model.layers.22.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
160
+ "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
161
+ "model.layers.22.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
162
+ "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
163
+ "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
164
+ "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
165
+ "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
166
+ "model.layers.22.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
167
+ "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
168
+ "model.layers.23.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
169
+ "model.layers.23.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
170
+ "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
171
+ "model.layers.23.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
172
+ "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
173
+ "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
174
+ "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
175
+ "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
176
+ "model.layers.23.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
177
+ "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
178
+ "model.layers.24.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
179
+ "model.layers.24.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
180
+ "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
181
+ "model.layers.24.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
182
+ "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
183
+ "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
184
+ "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
185
+ "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
186
+ "model.layers.24.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
187
+ "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
188
+ "model.layers.25.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
189
+ "model.layers.25.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
190
+ "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
191
+ "model.layers.25.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
192
+ "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
193
+ "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
194
+ "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
195
+ "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
196
+ "model.layers.25.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
197
+ "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
198
+ "model.layers.26.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
199
+ "model.layers.26.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
200
+ "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
201
+ "model.layers.26.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
202
+ "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
203
+ "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
204
+ "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
205
+ "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
206
+ "model.layers.26.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
207
+ "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
208
+ "model.layers.27.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
209
+ "model.layers.27.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
210
+ "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
211
+ "model.layers.27.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
212
+ "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
213
+ "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
214
+ "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
215
+ "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
216
+ "model.layers.27.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
217
+ "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
218
+ "model.layers.28.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
219
+ "model.layers.28.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
220
+ "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
221
+ "model.layers.28.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
222
+ "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
223
+ "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
224
+ "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
225
+ "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
226
+ "model.layers.28.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
227
+ "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
228
+ "model.layers.29.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
229
+ "model.layers.29.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
230
+ "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
231
+ "model.layers.29.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
232
+ "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
233
+ "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
234
+ "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
235
+ "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
236
+ "model.layers.29.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
237
+ "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
238
+ "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
239
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
240
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
241
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
242
+ "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
243
+ "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
244
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
245
+ "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
246
+ "model.layers.3.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
247
+ "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
248
+ "model.layers.30.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
249
+ "model.layers.30.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
250
+ "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
251
+ "model.layers.30.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
252
+ "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
253
+ "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
254
+ "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
255
+ "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
256
+ "model.layers.30.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
257
+ "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
258
+ "model.layers.31.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
259
+ "model.layers.31.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
260
+ "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
261
+ "model.layers.31.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
262
+ "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
263
+ "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
264
+ "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
265
+ "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
266
+ "model.layers.31.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
267
+ "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
268
+ "model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
269
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
270
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
271
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
272
+ "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
273
+ "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
274
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
275
+ "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
276
+ "model.layers.4.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
277
+ "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
278
+ "model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
279
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
280
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
281
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
282
+ "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
283
+ "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
284
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
285
+ "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
286
+ "model.layers.5.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
287
+ "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
288
+ "model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
289
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
290
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
291
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
292
+ "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
293
+ "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
294
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
295
+ "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
296
+ "model.layers.6.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
297
+ "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
298
+ "model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
299
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
300
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
301
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
302
+ "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
303
+ "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
304
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
305
+ "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
306
+ "model.layers.7.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
307
+ "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
308
+ "model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
309
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
310
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
311
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
312
+ "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
313
+ "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
314
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
315
+ "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
316
+ "model.layers.8.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
317
+ "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
318
+ "model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
319
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
320
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
321
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
322
+ "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
323
+ "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
324
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
325
+ "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
326
+ "model.layers.9.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
327
+ "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
328
+ "model.norm.weight": "pytorch_model-00002-of-00002.bin"
329
+ }
330
+ }
checkpoints/meta-llama/Llama-2-7b-chat-hf/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoints/meta-llama/Llama-2-7b-chat-hf/tokenizer.model ADDED
Binary file (500 kB). View file
 
checkpoints/meta-llama/Llama-2-7b-chat-hf/tokenizer_config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "chat_template": "{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<<SYS>>\\n' + system_message + '\\n<</SYS>>\\n\\n' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}",
13
+ "clean_up_tokenization_spaces": false,
14
+ "eos_token": {
15
+ "__type": "AddedToken",
16
+ "content": "</s>",
17
+ "lstrip": false,
18
+ "normalized": false,
19
+ "rstrip": false,
20
+ "single_word": false
21
+ },
22
+ "legacy": false,
23
+ "model_max_length": 1000000000000000019884624838656,
24
+ "pad_token": null,
25
+ "padding_side": "right",
26
+ "sp_model_kwargs": {},
27
+ "tokenizer_class": "LlamaTokenizer",
28
+ "unk_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ }
36
+ }
checkpoints/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoints/tokenizer.model ADDED
Binary file (500 kB). View file
 
checkpoints/tokenizer_config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "chat_template": "{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<<SYS>>\\n' + system_message + '\\n<</SYS>>\\n\\n' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}",
13
+ "clean_up_tokenization_spaces": false,
14
+ "eos_token": {
15
+ "__type": "AddedToken",
16
+ "content": "</s>",
17
+ "lstrip": false,
18
+ "normalized": false,
19
+ "rstrip": false,
20
+ "single_word": false
21
+ },
22
+ "legacy": false,
23
+ "model_max_length": 1000000000000000019884624838656,
24
+ "pad_token": null,
25
+ "padding_side": "right",
26
+ "sp_model_kwargs": {},
27
+ "tokenizer_class": "LlamaTokenizer",
28
+ "unk_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ }
36
+ }
main.ipynb ADDED
@@ -0,0 +1,1418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 2,
6
+ "metadata": {
7
+ "tags": []
8
+ },
9
+ "outputs": [
10
+ {
11
+ "name": "stdout",
12
+ "output_type": "stream",
13
+ "text": [
14
+ "Requirement already satisfied: pip in /opt/conda/lib/python3.10/site-packages (23.3.1)\n",
15
+ "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
16
+ "\u001b[0mLooking in indexes: https://download.pytorch.org/whl/cu118\n",
17
+ "Requirement already satisfied: torch in /opt/conda/lib/python3.10/site-packages (2.1.1+cu118)\n",
18
+ "Requirement already satisfied: torchaudio in /opt/conda/lib/python3.10/site-packages (2.1.1+cu118)\n",
19
+ "Requirement already satisfied: torchvision in /opt/conda/lib/python3.10/site-packages (0.16.1+cu118)\n",
20
+ "Requirement already satisfied: filelock in /opt/conda/lib/python3.10/site-packages (from torch) (3.12.2)\n",
21
+ "Requirement already satisfied: typing-extensions in /opt/conda/lib/python3.10/site-packages (from torch) (4.7.1)\n",
22
+ "Requirement already satisfied: sympy in /opt/conda/lib/python3.10/site-packages (from torch) (1.12)\n",
23
+ "Requirement already satisfied: networkx in /opt/conda/lib/python3.10/site-packages (from torch) (3.1)\n",
24
+ "Requirement already satisfied: jinja2 in /opt/conda/lib/python3.10/site-packages (from torch) (3.1.2)\n",
25
+ "Requirement already satisfied: fsspec in /opt/conda/lib/python3.10/site-packages (from torch) (2023.6.0)\n",
26
+ "Requirement already satisfied: triton==2.1.0 in /opt/conda/lib/python3.10/site-packages (from torch) (2.1.0)\n",
27
+ "Requirement already satisfied: numpy in /opt/conda/lib/python3.10/site-packages (from torchvision) (1.24.4)\n",
28
+ "Requirement already satisfied: requests in /opt/conda/lib/python3.10/site-packages (from torchvision) (2.31.0)\n",
29
+ "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /opt/conda/lib/python3.10/site-packages (from torchvision) (10.0.0)\n",
30
+ "Requirement already satisfied: MarkupSafe>=2.0 in /opt/conda/lib/python3.10/site-packages (from jinja2->torch) (2.1.3)\n",
31
+ "Requirement already satisfied: charset-normalizer<4,>=2 in /opt/conda/lib/python3.10/site-packages (from requests->torchvision) (3.1.0)\n",
32
+ "Requirement already satisfied: idna<4,>=2.5 in /opt/conda/lib/python3.10/site-packages (from requests->torchvision) (3.4)\n",
33
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /opt/conda/lib/python3.10/site-packages (from requests->torchvision) (1.26.15)\n",
34
+ "Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.10/site-packages (from requests->torchvision) (2023.7.22)\n",
35
+ "Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.10/site-packages (from sympy->torch) (1.3.0)\n",
36
+ "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
37
+ "\u001b[0mCollecting lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395 (from -r requirements.txt (line 1))\n",
38
+ " Using cached lightning-2.2.0.dev0-py3-none-any.whl\n",
39
+ "Requirement already satisfied: huggingface_hub in /opt/conda/lib/python3.10/site-packages (0.19.4)\n",
40
+ "Requirement already satisfied: tokenizers in /opt/conda/lib/python3.10/site-packages (0.15.0)\n",
41
+ "Requirement already satisfied: sentencepiece in /opt/conda/lib/python3.10/site-packages (0.1.99)\n",
42
+ "Requirement already satisfied: jsonargparse[signatures] in /opt/conda/lib/python3.10/site-packages (from -r requirements.txt (line 2)) (4.27.0)\n",
43
+ "Requirement already satisfied: filelock in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (3.12.2)\n",
44
+ "Requirement already satisfied: fsspec>=2023.5.0 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (2023.6.0)\n",
45
+ "Requirement already satisfied: requests in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (2.31.0)\n",
46
+ "Requirement already satisfied: tqdm>=4.42.1 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (4.65.0)\n",
47
+ "Requirement already satisfied: pyyaml>=5.1 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (6.0.1)\n",
48
+ "Requirement already satisfied: typing-extensions>=3.7.4.3 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (4.7.1)\n",
49
+ "Requirement already satisfied: packaging>=20.9 in /opt/conda/lib/python3.10/site-packages (from huggingface_hub) (23.1)\n",
50
+ "Requirement already satisfied: lightning-utilities<2.0,>=0.8.0 in /opt/conda/lib/python3.10/site-packages (from lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (0.10.0)\n",
51
+ "Requirement already satisfied: numpy<3.0,>=1.17.2 in /opt/conda/lib/python3.10/site-packages (from lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (1.24.4)\n",
52
+ "Requirement already satisfied: torch<4.0,>=1.12.0 in /opt/conda/lib/python3.10/site-packages (from lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (2.1.1+cu118)\n",
53
+ "Requirement already satisfied: torchmetrics<3.0,>=0.7.0 in /opt/conda/lib/python3.10/site-packages (from lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (1.2.0)\n",
54
+ "Requirement already satisfied: pytorch-lightning in /opt/conda/lib/python3.10/site-packages (from lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (2.1.2)\n",
55
+ "Requirement already satisfied: docstring-parser>=0.15 in /opt/conda/lib/python3.10/site-packages (from jsonargparse[signatures]->-r requirements.txt (line 2)) (0.15)\n",
56
+ "Requirement already satisfied: typeshed-client>=2.1.0 in /opt/conda/lib/python3.10/site-packages (from jsonargparse[signatures]->-r requirements.txt (line 2)) (2.4.0)\n",
57
+ "Requirement already satisfied: aiohttp!=4.0.0a0,!=4.0.0a1 in /opt/conda/lib/python3.10/site-packages (from fsspec[http]<2025.0,>2021.06.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (3.8.6)\n",
58
+ "Requirement already satisfied: setuptools in /opt/conda/lib/python3.10/site-packages (from lightning-utilities<2.0,>=0.8.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (65.6.3)\n",
59
+ "Requirement already satisfied: sympy in /opt/conda/lib/python3.10/site-packages (from torch<4.0,>=1.12.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (1.12)\n",
60
+ "Requirement already satisfied: networkx in /opt/conda/lib/python3.10/site-packages (from torch<4.0,>=1.12.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (3.1)\n",
61
+ "Requirement already satisfied: jinja2 in /opt/conda/lib/python3.10/site-packages (from torch<4.0,>=1.12.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (3.1.2)\n",
62
+ "Requirement already satisfied: triton==2.1.0 in /opt/conda/lib/python3.10/site-packages (from torch<4.0,>=1.12.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (2.1.0)\n",
63
+ "Requirement already satisfied: importlib-resources>=1.4.0 in /opt/conda/lib/python3.10/site-packages (from typeshed-client>=2.1.0->jsonargparse[signatures]->-r requirements.txt (line 2)) (6.1.1)\n",
64
+ "Requirement already satisfied: charset-normalizer<4,>=2 in /opt/conda/lib/python3.10/site-packages (from requests->huggingface_hub) (3.1.0)\n",
65
+ "Requirement already satisfied: idna<4,>=2.5 in /opt/conda/lib/python3.10/site-packages (from requests->huggingface_hub) (3.4)\n",
66
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /opt/conda/lib/python3.10/site-packages (from requests->huggingface_hub) (1.26.15)\n",
67
+ "Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.10/site-packages (from requests->huggingface_hub) (2023.7.22)\n",
68
+ "Requirement already satisfied: attrs>=17.3.0 in /opt/conda/lib/python3.10/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<2025.0,>2021.06.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (23.1.0)\n",
69
+ "Requirement already satisfied: multidict<7.0,>=4.5 in /opt/conda/lib/python3.10/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<2025.0,>2021.06.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (6.0.4)\n",
70
+ "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /opt/conda/lib/python3.10/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<2025.0,>2021.06.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (4.0.3)\n",
71
+ "Requirement already satisfied: yarl<2.0,>=1.0 in /opt/conda/lib/python3.10/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<2025.0,>2021.06.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (1.9.2)\n",
72
+ "Requirement already satisfied: frozenlist>=1.1.1 in /opt/conda/lib/python3.10/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<2025.0,>2021.06.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (1.4.0)\n",
73
+ "Requirement already satisfied: aiosignal>=1.1.2 in /opt/conda/lib/python3.10/site-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<2025.0,>2021.06.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (1.3.1)\n",
74
+ "Requirement already satisfied: MarkupSafe>=2.0 in /opt/conda/lib/python3.10/site-packages (from jinja2->torch<4.0,>=1.12.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (2.1.3)\n",
75
+ "Requirement already satisfied: mpmath>=0.19 in /opt/conda/lib/python3.10/site-packages (from sympy->torch<4.0,>=1.12.0->lightning@ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395->-r requirements.txt (line 1)) (1.3.0)\n",
76
+ "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
77
+ "\u001b[0m"
78
+ ]
79
+ }
80
+ ],
81
+ "source": [
82
+ "!pip install --upgrade pip\n",
83
+ "!pip install torch torchaudio torchvision --upgrade --index-url https://download.pytorch.org/whl/cu118\n",
84
+ "!pip install huggingface_hub tokenizers sentencepiece -r requirements.txt"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "execution_count": 3,
90
+ "metadata": {
91
+ "tags": []
92
+ },
93
+ "outputs": [
94
+ {
95
+ "data": {
96
+ "text/plain": [
97
+ "True"
98
+ ]
99
+ },
100
+ "execution_count": 3,
101
+ "metadata": {},
102
+ "output_type": "execute_result"
103
+ }
104
+ ],
105
+ "source": [
106
+ "import torch\n",
107
+ "torch.cuda.is_available()"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": 4,
113
+ "metadata": {
114
+ "tags": []
115
+ },
116
+ "outputs": [],
117
+ "source": [
118
+ "import glob\n",
119
+ "import math\n",
120
+ "import sys\n",
121
+ "import time\n",
122
+ "from pathlib import Path\n",
123
+ "from typing import Optional, Tuple, Union\n",
124
+ "\n",
125
+ "import lightning as L\n",
126
+ "import torch\n",
127
+ "from lightning.fabric.loggers import CSVLogger\n",
128
+ "from lightning.fabric.strategies import FSDPStrategy\n",
129
+ "from torch.utils.data import DataLoader\n",
130
+ "\n",
131
+ "# # support running without installing as a package\n",
132
+ "# wd = Path(__file__).parent.parent.resolve()\n",
133
+ "# sys.path.append(str(wd))\n",
134
+ "\n",
135
+ "from tsai_gpt.model import GPT, Block, Config\n",
136
+ "from tsai_gpt.packed_dataset import CombinedDataset, PackedDataset\n",
137
+ "from tsai_gpt.speed_monitor import SpeedMonitorBase, estimate_flops, measure_flops\n",
138
+ "from tsai_gpt.speed_monitor import SpeedMonitorFabric as SpeedMonitor\n",
139
+ "from tsai_gpt.utils import chunked_cross_entropy, get_default_supported_precision, num_parameters, load_checkpoint"
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "execution_count": 5,
145
+ "metadata": {
146
+ "tags": []
147
+ },
148
+ "outputs": [],
149
+ "source": [
150
+ "model_name = \"pythia-160m\"\n",
151
+ "name = \"redpajama\"\n",
152
+ "out_dir = Path(\"out\") / name\n",
153
+ "save_interval = 100\n",
154
+ "eval_interval = 1000\n",
155
+ "eval_iters = 100\n",
156
+ "log_interval = 100"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "execution_count": 6,
162
+ "metadata": {
163
+ "tags": []
164
+ },
165
+ "outputs": [],
166
+ "source": [
167
+ "# Hyperparameters\n",
168
+ "learning_rate = 6e-3\n",
169
+ "batch_size = 32\n",
170
+ "micro_batch_size = 4\n",
171
+ "gradient_accumulation_steps = batch_size // micro_batch_size\n",
172
+ "assert gradient_accumulation_steps > 0\n",
173
+ "#max_iters = 600000 # num_epochs * (epoch_size // micro_batch_size) // devices\n",
174
+ "max_iters = 25000\n",
175
+ "weight_decay = 1e-1\n",
176
+ "beta1 = 0.9\n",
177
+ "beta2 = 0.95\n",
178
+ "grad_clip = 1.0\n",
179
+ "decay_lr = True\n",
180
+ "warmup_iters = 6000\n",
181
+ "lr_decay_iters = max_iters\n",
182
+ "min_lr = 6e-4"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "execution_count": 7,
188
+ "metadata": {
189
+ "tags": []
190
+ },
191
+ "outputs": [],
192
+ "source": [
193
+ "# Data proportions from https://arxiv.org/pdf/2302.13971.pdf Table 1\n",
194
+ "data_config = [\n",
195
+ " (\"arxiv\", 2.5),\n",
196
+ " (\"book\", 4.5),\n",
197
+ " (\"c4\", 15.0),\n",
198
+ " (\"cc\", 67.0),\n",
199
+ " (\"github\", 4.5),\n",
200
+ " (\"stackexchange\", 2.0),\n",
201
+ " (\"wikipedia\", 4.5),\n",
202
+ "]"
203
+ ]
204
+ },
205
+ {
206
+ "cell_type": "code",
207
+ "execution_count": 8,
208
+ "metadata": {
209
+ "tags": []
210
+ },
211
+ "outputs": [],
212
+ "source": [
213
+ "hparams = {k: v for k, v in locals().items() if isinstance(v, (int, float, str)) and not k.startswith(\"_\")}\n",
214
+ "logger = CSVLogger(\"out\", name, flush_logs_every_n_steps=log_interval)\n",
215
+ "\n",
216
+ "\n",
217
+ "def setup(\n",
218
+ " devices: int = 4,\n",
219
+ " train_data_dir: Path = Path(\"data/redpajama_sample\"),\n",
220
+ " val_data_dir: Optional[Path] = None,\n",
221
+ " precision: Optional[str] = None,\n",
222
+ " resume: Union[bool, Path] = False,\n",
223
+ ") -> None:\n",
224
+ " precision = precision or get_default_supported_precision(training=True)\n",
225
+ "\n",
226
+ " if devices > 1:\n",
227
+ " strategy = FSDPStrategy(\n",
228
+ " auto_wrap_policy={Block},\n",
229
+ " activation_checkpointing_policy={Block},\n",
230
+ " state_dict_type=\"full\",\n",
231
+ " limit_all_gathers=True,\n",
232
+ " cpu_offload=False,\n",
233
+ " )\n",
234
+ " else:\n",
235
+ " strategy = \"auto\"\n",
236
+ "\n",
237
+ " fabric = L.Fabric(devices=devices, strategy=strategy, precision=precision, loggers=logger)\n",
238
+ " fabric.print(hparams)\n",
239
+ " fabric.launch(main, train_data_dir, val_data_dir, resume)"
240
+ ]
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "execution_count": 9,
245
+ "metadata": {
246
+ "tags": []
247
+ },
248
+ "outputs": [],
249
+ "source": [
250
+ "model_copy = None"
251
+ ]
252
+ },
253
+ {
254
+ "cell_type": "code",
255
+ "execution_count": 10,
256
+ "metadata": {
257
+ "tags": []
258
+ },
259
+ "outputs": [],
260
+ "source": [
261
+ "def main(fabric: L.Fabric, train_data_dir: Path, val_data_dir: Path, resume: Union[bool, Path]) -> None:\n",
262
+ " global model_copy\n",
263
+ " speed_monitor = SpeedMonitor(fabric, window_size=50, time_unit=\"seconds\")\n",
264
+ "\n",
265
+ " if fabric.global_rank == 0:\n",
266
+ " out_dir.mkdir(parents=True, exist_ok=True)\n",
267
+ "\n",
268
+ " config = Config.from_name(model_name)\n",
269
+ "\n",
270
+ " train_dataloader, val_dataloader = create_dataloaders(\n",
271
+ " batch_size=micro_batch_size,\n",
272
+ " block_size=config.block_size,\n",
273
+ " fabric=fabric,\n",
274
+ " train_data_dir=train_data_dir,\n",
275
+ " val_data_dir=val_data_dir,\n",
276
+ " seed=(1337 + fabric.global_rank),\n",
277
+ " )\n",
278
+ " if val_dataloader is None:\n",
279
+ " train_dataloader = fabric.setup_dataloaders(train_dataloader)\n",
280
+ " else:\n",
281
+ " train_dataloader, val_dataloader = fabric.setup_dataloaders(train_dataloader, val_dataloader)\n",
282
+ "\n",
283
+ " fabric.seed_everything(1337) # same seed for every process to init model (FSDP)\n",
284
+ "\n",
285
+ " fabric.print(f\"Loading model with {config.__dict__}\")\n",
286
+ " t0 = time.perf_counter()\n",
287
+ " import torch\n",
288
+ " import torch.nn as nn\n",
289
+ " def _init_weights(module: nn.Module) -> None:\n",
290
+ " \"\"\"Meant to be used with `gpt.apply(gpt._init_weights)`.\"\"\"\n",
291
+ " if isinstance(module, nn.Linear):\n",
292
+ " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",
293
+ " if module.bias is not None:\n",
294
+ " torch.nn.init.zeros_(module.bias)\n",
295
+ " elif isinstance(module, nn.Embedding):\n",
296
+ " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",
297
+ " \n",
298
+ " with fabric.init_module(empty_init=True):\n",
299
+ " model = GPT(config)\n",
300
+ " model.apply(_init_weights)\n",
301
+ " model.apply(_init_weights)\n",
302
+ "\n",
303
+ " \n",
304
+ " # checkpoint_path = Path(\"out/redpajama/iter-000999-ckpt.pth\")\n",
305
+ "\n",
306
+ " # load_checkpoint(fabric, model, checkpoint_path)\n",
307
+ " \n",
308
+ " # print(model.transformer.h[0].mlp.fc.weight)\n",
309
+ "\n",
310
+ " fabric.print(f\"Time to instantiate model: {time.perf_counter() - t0:.02f} seconds.\")\n",
311
+ " fabric.print(f\"Total parameters {num_parameters(model):,}\")\n",
312
+ "\n",
313
+ " model = fabric.setup(model)\n",
314
+ " optimizer = torch.optim.AdamW(\n",
315
+ " model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2), foreach=False\n",
316
+ " )\n",
317
+ "\n",
318
+ " #model_copy = model\n",
319
+ "\n",
320
+ " optimizer = fabric.setup_optimizers(optimizer)\n",
321
+ "\n",
322
+ " state = {\"model\": model, \"optimizer\": optimizer, \"hparams\": hparams, \"iter_num\": 0, \"step_count\": 0}\n",
323
+ "\n",
324
+ " if resume is True:\n",
325
+ " resume = max(out_dir.glob(\"*.pth\"), key=lambda p: int(p.name.split(\"-\")[1]))\n",
326
+ " if resume:\n",
327
+ " fabric.print(f\"Resuming training from {resume}\")\n",
328
+ " fabric.load(resume, state)\n",
329
+ "\n",
330
+ " train_time = time.perf_counter()\n",
331
+ " train(fabric, state, train_dataloader, val_dataloader, speed_monitor)\n",
332
+ " fabric.print(f\"Training time: {(time.perf_counter()-train_time):.2f}s\")\n",
333
+ " if fabric.device.type == \"cuda\":\n",
334
+ " fabric.print(f\"Memory used: {torch.cuda.max_memory_allocated() / 1e9:.02f} GB\")\n",
335
+ "\n"
336
+ ]
337
+ },
338
+ {
339
+ "cell_type": "code",
340
+ "execution_count": 11,
341
+ "metadata": {
342
+ "tags": []
343
+ },
344
+ "outputs": [],
345
+ "source": [
346
+ "def train(\n",
347
+ " fabric: L.Fabric,\n",
348
+ " state: dict,\n",
349
+ " train_dataloader: DataLoader,\n",
350
+ " val_dataloader: DataLoader,\n",
351
+ " speed_monitor: SpeedMonitorBase,\n",
352
+ ") -> None:\n",
353
+ " model = state[\"model\"]\n",
354
+ " optimizer = state[\"optimizer\"]\n",
355
+ "\n",
356
+ " if val_dataloader is not None:\n",
357
+ " validate(fabric, model, val_dataloader) # sanity check\n",
358
+ "\n",
359
+ " with torch.device(\"meta\"):\n",
360
+ " meta_model = GPT(model.config)\n",
361
+ " # \"estimated\" is not as precise as \"measured\". Estimated is optimistic but widely used in the wild.\n",
362
+ " # When comparing MFU or FLOP numbers with other projects that use estimated FLOPs,\n",
363
+ " # consider passing `SpeedMonitor(flops_per_batch=estimated_flops)` instead\n",
364
+ " estimated_flops = estimate_flops(meta_model) * micro_batch_size\n",
365
+ " fabric.print(f\"Estimated TFLOPs: {estimated_flops * fabric.world_size / 1e12:.2f}\")\n",
366
+ " x = torch.randint(0, 1, (micro_batch_size, model.max_seq_length))\n",
367
+ " measured_flops = measure_flops(meta_model, x)\n",
368
+ " fabric.print(f\"Measured TFLOPs: {measured_flops * fabric.world_size / 1e12:.2f}\")\n",
369
+ " del meta_model, x\n",
370
+ "\n",
371
+ " total_lengths = 0\n",
372
+ " total_t0 = time.perf_counter()\n",
373
+ "\n",
374
+ " for state[\"iter_num\"], train_data in enumerate(train_dataloader, state[\"iter_num\"]):\n",
375
+ " if state[\"iter_num\"] >= max_iters:\n",
376
+ " checkpoint_path = out_dir / f\"iter-{state['iter_num']:06d}-ckpt.pth\"\n",
377
+ " fabric.print(f\"Saving checkpoint to {str(checkpoint_path)!r}\")\n",
378
+ " fabric.save(checkpoint_path, state)\n",
379
+ " break\n",
380
+ "\n",
381
+ " # determine and set the learning rate for this iteration\n",
382
+ " lr = get_lr(state[\"iter_num\"]) if decay_lr else learning_rate\n",
383
+ " for param_group in optimizer.param_groups:\n",
384
+ " param_group[\"lr\"] = lr\n",
385
+ "\n",
386
+ " iter_t0 = time.perf_counter()\n",
387
+ "\n",
388
+ " input_ids = train_data[:, 0 : model.max_seq_length].contiguous()\n",
389
+ " targets = train_data[:, 1 : model.max_seq_length + 1].contiguous()\n",
390
+ "\n",
391
+ " is_accumulating = (state[\"iter_num\"] + 1) % gradient_accumulation_steps != 0\n",
392
+ " with fabric.no_backward_sync(model, enabled=is_accumulating):\n",
393
+ " logits = model(input_ids)\n",
394
+ " loss = chunked_cross_entropy(logits, targets, chunk_size=0)\n",
395
+ " fabric.backward(loss / gradient_accumulation_steps)\n",
396
+ " \n",
397
+ " # return \n",
398
+ "\n",
399
+ " if not is_accumulating:\n",
400
+ " fabric.clip_gradients(model, optimizer, max_norm=grad_clip)\n",
401
+ " optimizer.step()\n",
402
+ " optimizer.zero_grad()\n",
403
+ " state[\"step_count\"] += 1\n",
404
+ "\n",
405
+ " t1 = time.perf_counter()\n",
406
+ " total_lengths += input_ids.size(1)\n",
407
+ " speed_monitor.on_train_batch_end(\n",
408
+ " (state[\"iter_num\"] + 1) * micro_batch_size,\n",
409
+ " t1 - total_t0,\n",
410
+ " # this assumes that device FLOPs are the same and that all devices have the same batch size\n",
411
+ " fabric.world_size,\n",
412
+ " flops_per_batch=measured_flops,\n",
413
+ " lengths=total_lengths,\n",
414
+ " )\n",
415
+ " if state[\"iter_num\"] % log_interval == 0:\n",
416
+ " fabric.print(\n",
417
+ " f\"iter {state['iter_num']} step {state['step_count']}: loss {loss.item():.4f}, LR: {lr:.6f}, iter time:\"\n",
418
+ " f\" {(t1 - iter_t0) * 1000:.2f}ms{' (optimizer.step)' if not is_accumulating else ''}\"\n",
419
+ " )\n",
420
+ "\n",
421
+ " if val_dataloader is not None and not is_accumulating and state[\"step_count\"] % eval_interval == 0:\n",
422
+ " t0 = time.perf_counter()\n",
423
+ " val_loss = validate(fabric, model, val_dataloader)\n",
424
+ " t1 = time.perf_counter() - t0\n",
425
+ " speed_monitor.eval_end(t1)\n",
426
+ " fabric.print(f\"step {state['iter_num']}: val loss {val_loss.item():.4f}, val time: {t1 * 1000:.2f}ms\")\n",
427
+ " fabric.barrier()\n",
428
+ " if not is_accumulating and (state[\"step_count\"]+1) % save_interval == 0:\n",
429
+ " checkpoint_path = out_dir / f\"iter-{state['iter_num']:06d}-ckpt.pth\"\n",
430
+ " fabric.print(f\"Saving checkpoint to {str(checkpoint_path)!r}\")\n",
431
+ " fabric.save(checkpoint_path, state)\n",
432
+ " \n",
433
+ " '''if loss.item() <= 4.0 and state['iter_num'] >= 2000:\n",
434
+ " fabric.print(\n",
435
+ " f\"iter {state['iter_num']} step {state['step_count']}: loss {loss.item():.4f}, LR: {lr:.6f}, iter time:\"\n",
436
+ " f\" {(t1 - iter_t0) * 1000:.2f}ms{' (optimizer.step)' if not is_accumulating else ''}\"\n",
437
+ " )\n",
438
+ " checkpoint_path = out_dir / f\"iter-{state['iter_num']:06d}-ckpt.pth\"\n",
439
+ " fabric.print(f\"Saving checkpoint to {str(checkpoint_path)!r}\")\n",
440
+ " fabric.save(checkpoint_path, state)\n",
441
+ " break'''"
442
+ ]
443
+ },
444
+ {
445
+ "cell_type": "code",
446
+ "execution_count": 12,
447
+ "metadata": {
448
+ "tags": []
449
+ },
450
+ "outputs": [],
451
+ "source": [
452
+ "@torch.inference_mode()\n",
453
+ "def validate(fabric: L.Fabric, model: torch.nn.Module, val_dataloader: DataLoader) -> torch.Tensor:\n",
454
+ " fabric.print(\"Validating ...\")\n",
455
+ " model.eval()\n",
456
+ "\n",
457
+ " losses = torch.zeros(eval_iters, device=fabric.device)\n",
458
+ " for k, val_data in enumerate(val_dataloader):\n",
459
+ " input_ids = val_data[:, 0 : model.max_seq_length].contiguous()\n",
460
+ " targets = val_data[:, 1 : model.max_seq_length + 1].contiguous()\n",
461
+ " logits = model(input_ids)\n",
462
+ " losses[k] = chunked_cross_entropy(logits, targets, chunk_size=0)\n",
463
+ " out = losses.mean()\n",
464
+ "\n",
465
+ " model.train()\n",
466
+ " return out"
467
+ ]
468
+ },
469
+ {
470
+ "cell_type": "code",
471
+ "execution_count": 13,
472
+ "metadata": {
473
+ "tags": []
474
+ },
475
+ "outputs": [],
476
+ "source": [
477
+ "def create_dataloader(\n",
478
+ " batch_size: int, block_size: int, data_dir: Path, fabric: L.Fabric, shuffle: bool = True, seed: int = 12345\n",
479
+ ") -> DataLoader:\n",
480
+ " datasets = []\n",
481
+ " for prefix, _ in data_config:\n",
482
+ " filenames = glob.glob(str(data_dir / f\"{prefix}*\"))\n",
483
+ " dataset = PackedDataset(\n",
484
+ " filenames,\n",
485
+ " n_chunks=4,\n",
486
+ " block_size=block_size,\n",
487
+ " shuffle=shuffle,\n",
488
+ " seed=seed,\n",
489
+ " num_processes=fabric.world_size,\n",
490
+ " process_rank=fabric.global_rank,\n",
491
+ " )\n",
492
+ " datasets.append(dataset)\n",
493
+ "\n",
494
+ " if not datasets:\n",
495
+ " raise RuntimeError(\n",
496
+ " f\"No data found at {data_dir}. Make sure you ran prepare_redpajama.py to create the dataset.\"\n",
497
+ " )\n",
498
+ "\n",
499
+ " weights = [weight for _, weight in data_config]\n",
500
+ " sum_weights = sum(weights)\n",
501
+ " weights = [el / sum_weights for el in weights]\n",
502
+ "\n",
503
+ " combined_dataset = CombinedDataset(datasets=datasets, seed=seed, weights=weights)\n",
504
+ "\n",
505
+ " return DataLoader(combined_dataset, batch_size=batch_size, shuffle=False, pin_memory=True)\n"
506
+ ]
507
+ },
508
+ {
509
+ "cell_type": "code",
510
+ "execution_count": 14,
511
+ "metadata": {
512
+ "tags": []
513
+ },
514
+ "outputs": [],
515
+ "source": [
516
+ "def create_dataloaders(\n",
517
+ " batch_size: int,\n",
518
+ " block_size: int,\n",
519
+ " fabric: L.Fabric,\n",
520
+ " train_data_dir: Path = Path(\"data/redpajama_sample\"),\n",
521
+ " val_data_dir: Optional[Path] = None,\n",
522
+ " seed: int = 12345,\n",
523
+ ") -> Tuple[DataLoader, DataLoader]:\n",
524
+ " # Increase by one because we need the next word as well\n",
525
+ " effective_block_size = block_size + 1\n",
526
+ " train_dataloader = create_dataloader(\n",
527
+ " batch_size=batch_size,\n",
528
+ " block_size=effective_block_size,\n",
529
+ " fabric=fabric,\n",
530
+ " data_dir=train_data_dir,\n",
531
+ " shuffle=True,\n",
532
+ " seed=seed,\n",
533
+ " )\n",
534
+ " val_dataloader = (\n",
535
+ " create_dataloader(\n",
536
+ " batch_size=batch_size,\n",
537
+ " block_size=effective_block_size,\n",
538
+ " fabric=fabric,\n",
539
+ " data_dir=val_data_dir,\n",
540
+ " shuffle=False,\n",
541
+ " seed=seed,\n",
542
+ " )\n",
543
+ " if val_data_dir\n",
544
+ " else None\n",
545
+ " )\n",
546
+ " return train_dataloader, val_dataloader"
547
+ ]
548
+ },
549
+ {
550
+ "cell_type": "code",
551
+ "execution_count": 15,
552
+ "metadata": {
553
+ "tags": []
554
+ },
555
+ "outputs": [],
556
+ "source": [
557
+ "def get_lr(it: int) -> float:\n",
558
+ " # 1) linear warmup for warmup_iters steps\n",
559
+ " if it < warmup_iters:\n",
560
+ " return learning_rate * it / warmup_iters\n",
561
+ " # 2) if it > lr_decay_iters, return min learning rate\n",
562
+ " if it > lr_decay_iters:\n",
563
+ " return min_lr\n",
564
+ " # 3) in between, use cosine decay down to min learning rate\n",
565
+ " decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)\n",
566
+ " assert 0 <= decay_ratio <= 1\n",
567
+ " coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff ranges 0..1\n",
568
+ " return min_lr + coeff * (learning_rate - min_lr)"
569
+ ]
570
+ },
571
+ {
572
+ "cell_type": "code",
573
+ "execution_count": 16,
574
+ "metadata": {
575
+ "tags": []
576
+ },
577
+ "outputs": [
578
+ {
579
+ "name": "stderr",
580
+ "output_type": "stream",
581
+ "text": [
582
+ "Using 16-bit Automatic Mixed Precision (AMP)\n",
583
+ "Seed set to 1337\n"
584
+ ]
585
+ },
586
+ {
587
+ "name": "stdout",
588
+ "output_type": "stream",
589
+ "text": [
590
+ "{'model_name': 'pythia-160m', 'name': 'redpajama', 'save_interval': 100, 'eval_interval': 1000, 'eval_iters': 100, 'log_interval': 100, 'learning_rate': 0.006, 'batch_size': 32, 'micro_batch_size': 4, 'gradient_accumulation_steps': 8, 'max_iters': 25000, 'weight_decay': 0.1, 'beta1': 0.9, 'beta2': 0.95, 'grad_clip': 1.0, 'decay_lr': True, 'warmup_iters': 6000, 'lr_decay_iters': 25000, 'min_lr': 0.0006}\n",
591
+ "Loading model with {'name': 'pythia-160m', 'hf_config': {'org': 'EleutherAI', 'name': 'pythia-160m-deduped'}, 'block_size': 2048, 'vocab_size': 50254, 'padding_multiple': 128, 'padded_vocab_size': 50304, 'n_layer': 12, 'n_head': 12, 'n_embd': 768, 'rotary_percentage': 0.25, 'parallel_residual': True, 'bias': True, 'lm_head_bias': False, 'n_query_groups': 12, 'shared_attention_norm': False, '_norm_class': 'LayerNorm', 'norm_eps': 1e-05, '_mlp_class': 'GptNeoxMLP', 'gelu_approximate': 'none', 'intermediate_size': 3072, 'rope_condense_ratio': 1, 'rope_base': 10000, 'head_size': 64, 'rope_n_elem': 16}\n",
592
+ "Time to instantiate model: 1.85 seconds.\n",
593
+ "Total parameters 162,322,944\n",
594
+ "Resuming training from out/redpajama/iter-025000-ckpt.pth\n"
595
+ ]
596
+ },
597
+ {
598
+ "ename": "KeyboardInterrupt",
599
+ "evalue": "",
600
+ "traceback": [
601
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
602
+ "\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)",
603
+ "Cell \u001b[0;32mIn[16], line 2\u001b[0m\n\u001b[1;32m 1\u001b[0m torch\u001b[38;5;241m.\u001b[39mset_float32_matmul_precision(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmedium\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m----> 2\u001b[0m \u001b[43msetup\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 3\u001b[0m \u001b[43m \u001b[49m\u001b[43mdevices\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[43m \u001b[49m\u001b[43mtrain_data_dir\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mPath\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mdata/lit-redpajama-sample\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 5\u001b[0m \u001b[43m \u001b[49m\u001b[43mresume\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\n\u001b[1;32m 6\u001b[0m \u001b[43m)\u001b[49m\n",
604
+ "Cell \u001b[0;32mIn[8], line 27\u001b[0m, in \u001b[0;36msetup\u001b[0;34m(devices, train_data_dir, val_data_dir, precision, resume)\u001b[0m\n\u001b[1;32m 25\u001b[0m fabric \u001b[38;5;241m=\u001b[39m L\u001b[38;5;241m.\u001b[39mFabric(devices\u001b[38;5;241m=\u001b[39mdevices, strategy\u001b[38;5;241m=\u001b[39mstrategy, precision\u001b[38;5;241m=\u001b[39mprecision, loggers\u001b[38;5;241m=\u001b[39mlogger)\n\u001b[1;32m 26\u001b[0m fabric\u001b[38;5;241m.\u001b[39mprint(hparams)\n\u001b[0;32m---> 27\u001b[0m \u001b[43mfabric\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mlaunch\u001b[49m\u001b[43m(\u001b[49m\u001b[43mmain\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtrain_data_dir\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mval_data_dir\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mresume\u001b[49m\u001b[43m)\u001b[49m\n",
605
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/lightning/fabric/fabric.py:834\u001b[0m, in \u001b[0;36mFabric.launch\u001b[0;34m(self, function, *args, **kwargs)\u001b[0m\n\u001b[1;32m 829\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstrategy\u001b[38;5;241m.\u001b[39mlauncher, (_MultiProcessingLauncher, _XLALauncher)):\n\u001b[1;32m 830\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\n\u001b[1;32m 831\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mTo use the `\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mtype\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstrategy)\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__name__\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m` strategy, `.launch()` needs to be called with a function\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 832\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m that contains the code to launch in processes.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 833\u001b[0m )\n\u001b[0;32m--> 834\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_wrap_and_launch\u001b[49m\u001b[43m(\u001b[49m\u001b[43mfunction\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
606
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/lightning/fabric/fabric.py:920\u001b[0m, in \u001b[0;36mFabric._wrap_and_launch\u001b[0;34m(self, to_run, *args, **kwargs)\u001b[0m\n\u001b[1;32m 918\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m (launcher \u001b[38;5;241m:=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_strategy\u001b[38;5;241m.\u001b[39mlauncher) \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 919\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m launcher\u001b[38;5;241m.\u001b[39mlaunch(to_run, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[0;32m--> 920\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mto_run\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
607
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/lightning/fabric/fabric.py:925\u001b[0m, in \u001b[0;36mFabric._wrap_with_setup\u001b[0;34m(self, to_run, *args, **kwargs)\u001b[0m\n\u001b[1;32m 923\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_strategy\u001b[38;5;241m.\u001b[39msetup_environment()\n\u001b[1;32m 924\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m _replace_dunder_methods(DataLoader, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mdataset\u001b[39m\u001b[38;5;124m\"\u001b[39m), _replace_dunder_methods(BatchSampler):\n\u001b[0;32m--> 925\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mto_run\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
608
+ "Cell \u001b[0;32mIn[10], line 68\u001b[0m, in \u001b[0;36mmain\u001b[0;34m(fabric, train_data_dir, val_data_dir, resume)\u001b[0m\n\u001b[1;32m 66\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m resume:\n\u001b[1;32m 67\u001b[0m fabric\u001b[38;5;241m.\u001b[39mprint(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mResuming training from \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mresume\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m---> 68\u001b[0m \u001b[43mfabric\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mload\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresume\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstate\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 70\u001b[0m train_time \u001b[38;5;241m=\u001b[39m time\u001b[38;5;241m.\u001b[39mperf_counter()\n\u001b[1;32m 71\u001b[0m train(fabric, state, train_dataloader, val_dataloader, speed_monitor)\n",
609
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/lightning/fabric/fabric.py:764\u001b[0m, in \u001b[0;36mFabric.load\u001b[0;34m(self, path, state, strict)\u001b[0m\n\u001b[1;32m 747\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Load a checkpoint from a file and restore the state of objects (modules, optimizers, etc.)\u001b[39;00m\n\u001b[1;32m 748\u001b[0m \n\u001b[1;32m 749\u001b[0m \u001b[38;5;124;03mHow and which processes load gets determined by the `strategy`.\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 761\u001b[0m \n\u001b[1;32m 762\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m 763\u001b[0m unwrapped_state \u001b[38;5;241m=\u001b[39m _unwrap_objects(state)\n\u001b[0;32m--> 764\u001b[0m remainder \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_strategy\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mload_checkpoint\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpath\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mpath\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstate\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43munwrapped_state\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstrict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mstrict\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 765\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mbarrier()\n\u001b[1;32m 766\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m state \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 767\u001b[0m \u001b[38;5;66;03m# We need to unwrap objects (see above) but this creates a new dictionary. In-place updates\u001b[39;00m\n\u001b[1;32m 768\u001b[0m \u001b[38;5;66;03m# (for user metadata) wouldn't show up in the original dict, so we need to copy the data back.\u001b[39;00m\n",
610
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/lightning/fabric/strategies/strategy.py:333\u001b[0m, in \u001b[0;36mStrategy.load_checkpoint\u001b[0;34m(self, path, state, strict)\u001b[0m\n\u001b[1;32m 314\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Load the contents from a checkpoint and restore the state of the given objects.\u001b[39;00m\n\u001b[1;32m 315\u001b[0m \n\u001b[1;32m 316\u001b[0m \u001b[38;5;124;03mArgs:\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 330\u001b[0m \n\u001b[1;32m 331\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m 332\u001b[0m torch\u001b[38;5;241m.\u001b[39mcuda\u001b[38;5;241m.\u001b[39mempty_cache()\n\u001b[0;32m--> 333\u001b[0m checkpoint \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcheckpoint_io\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mload_checkpoint\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpath\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 334\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m state:\n\u001b[1;32m 335\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m checkpoint\n",
611
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/lightning/fabric/plugins/io/torch_io.py:79\u001b[0m, in \u001b[0;36mTorchCheckpointIO.load_checkpoint\u001b[0;34m(self, path, map_location)\u001b[0m\n\u001b[1;32m 76\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m fs\u001b[38;5;241m.\u001b[39mexists(path):\n\u001b[1;32m 77\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mFileNotFoundError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCheckpoint file not found: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpath\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m---> 79\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mpl_load\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpath\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mmap_location\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmap_location\u001b[49m\u001b[43m)\u001b[49m\n",
612
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/lightning/fabric/utilities/cloud_io.py:55\u001b[0m, in \u001b[0;36m_load\u001b[0;34m(path_or_url, map_location)\u001b[0m\n\u001b[1;32m 53\u001b[0m fs \u001b[38;5;241m=\u001b[39m get_filesystem(path_or_url)\n\u001b[1;32m 54\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m fs\u001b[38;5;241m.\u001b[39mopen(path_or_url, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrb\u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;28;01mas\u001b[39;00m f:\n\u001b[0;32m---> 55\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mtorch\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mload\u001b[49m\u001b[43m(\u001b[49m\u001b[43mf\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mmap_location\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmap_location\u001b[49m\u001b[43m)\u001b[49m\n",
613
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/torch/serialization.py:1014\u001b[0m, in \u001b[0;36mload\u001b[0;34m(f, map_location, pickle_module, weights_only, mmap, **pickle_load_args)\u001b[0m\n\u001b[1;32m 1012\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mRuntimeError\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 1013\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m pickle\u001b[38;5;241m.\u001b[39mUnpicklingError(UNSAFE_MESSAGE \u001b[38;5;241m+\u001b[39m \u001b[38;5;28mstr\u001b[39m(e)) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[0;32m-> 1014\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43m_load\u001b[49m\u001b[43m(\u001b[49m\u001b[43mopened_zipfile\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1015\u001b[0m \u001b[43m \u001b[49m\u001b[43mmap_location\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1016\u001b[0m \u001b[43m \u001b[49m\u001b[43mpickle_module\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1017\u001b[0m \u001b[43m \u001b[49m\u001b[43moverall_storage\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43moverall_storage\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1018\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mpickle_load_args\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1019\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m mmap:\n\u001b[1;32m 1020\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mRuntimeError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmmap can only be used with files saved with \u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m 1021\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m`torch.save(_use_new_zipfile_serialization=True), \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 1022\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mplease torch.save your checkpoint with this option in order to use mmap.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
614
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/torch/serialization.py:1422\u001b[0m, in \u001b[0;36m_load\u001b[0;34m(zip_file, map_location, pickle_module, pickle_file, overall_storage, **pickle_load_args)\u001b[0m\n\u001b[1;32m 1420\u001b[0m unpickler \u001b[38;5;241m=\u001b[39m UnpicklerWrapper(data_file, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mpickle_load_args)\n\u001b[1;32m 1421\u001b[0m unpickler\u001b[38;5;241m.\u001b[39mpersistent_load \u001b[38;5;241m=\u001b[39m persistent_load\n\u001b[0;32m-> 1422\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[43munpickler\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mload\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1424\u001b[0m torch\u001b[38;5;241m.\u001b[39m_utils\u001b[38;5;241m.\u001b[39m_validate_loaded_sparse_tensors()\n\u001b[1;32m 1425\u001b[0m torch\u001b[38;5;241m.\u001b[39m_C\u001b[38;5;241m.\u001b[39m_log_api_usage_metadata(\n\u001b[1;32m 1426\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtorch.load.metadata\u001b[39m\u001b[38;5;124m\"\u001b[39m, {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mserialization_id\u001b[39m\u001b[38;5;124m\"\u001b[39m: zip_file\u001b[38;5;241m.\u001b[39mserialization_id()}\n\u001b[1;32m 1427\u001b[0m )\n",
615
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/torch/serialization.py:1392\u001b[0m, in \u001b[0;36m_load.<locals>.persistent_load\u001b[0;34m(saved_id)\u001b[0m\n\u001b[1;32m 1390\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 1391\u001b[0m nbytes \u001b[38;5;241m=\u001b[39m numel \u001b[38;5;241m*\u001b[39m torch\u001b[38;5;241m.\u001b[39m_utils\u001b[38;5;241m.\u001b[39m_element_size(dtype)\n\u001b[0;32m-> 1392\u001b[0m typed_storage \u001b[38;5;241m=\u001b[39m \u001b[43mload_tensor\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdtype\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mnbytes\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m_maybe_decode_ascii\u001b[49m\u001b[43m(\u001b[49m\u001b[43mlocation\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1394\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m typed_storage\n",
616
+ "File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/torch/serialization.py:1357\u001b[0m, in \u001b[0;36m_load.<locals>.load_tensor\u001b[0;34m(dtype, numel, key, location)\u001b[0m\n\u001b[1;32m 1355\u001b[0m storage \u001b[38;5;241m=\u001b[39m overall_storage[storage_offset:storage_offset \u001b[38;5;241m+\u001b[39m numel]\n\u001b[1;32m 1356\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m-> 1357\u001b[0m storage \u001b[38;5;241m=\u001b[39m \u001b[43mzip_file\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_storage_from_record\u001b[49m\u001b[43m(\u001b[49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mnumel\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtorch\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mUntypedStorage\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241m.\u001b[39m_typed_storage()\u001b[38;5;241m.\u001b[39m_untyped_storage\n\u001b[1;32m 1358\u001b[0m \u001b[38;5;66;03m# swap here if byteswapping is needed\u001b[39;00m\n\u001b[1;32m 1359\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m byteorderdata \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n",
617
+ "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
618
+ ],
619
+ "output_type": "error"
620
+ }
621
+ ],
622
+ "source": [
623
+ "torch.set_float32_matmul_precision(\"medium\")\n",
624
+ "setup(\n",
625
+ " devices=1,\n",
626
+ " train_data_dir=Path(\"data/lit-redpajama-sample\"),\n",
627
+ " resume=True\n",
628
+ ")"
629
+ ]
630
+ },
631
+ {
632
+ "cell_type": "code",
633
+ "execution_count": 20,
634
+ "metadata": {
635
+ "tags": []
636
+ },
637
+ "outputs": [
638
+ {
639
+ "name": "stdout",
640
+ "output_type": "stream",
641
+ "text": [
642
+ "generation_config.json\tmeta-llama\ttokenizer.model\n",
643
+ "lit_config.json\t\ttokenizer.json\ttokenizer_config.json\n"
644
+ ]
645
+ }
646
+ ],
647
+ "source": [
648
+ "!ls checkpoints"
649
+ ]
650
+ },
651
+ {
652
+ "cell_type": "code",
653
+ "execution_count": 17,
654
+ "metadata": {},
655
+ "outputs": [
656
+ {
657
+ "name": "stdout",
658
+ "output_type": "stream",
659
+ "text": [
660
+ "Loading model from out/redpajama/iter-025000-ckpt.pth\n",
661
+ "The main reason for the financial 16 taxpayer tax increase, the number of individuals working in the first quarter of 2018 to take interest rates and it is very likely that an employee might receive that amount and the amount paid back income of his assets in the third quarter of 2018.\n",
662
+ "It is not easy to give credit to the first quarter of 2018 to give the same amount that they can sell, as the amount paid back, and the amount paid back income of the shares of the ear pay will not be paid until the retirement is in 2019.\n",
663
+ "The more than the more the amount paid back in the quarter of 2018 to be paying a year and a pay back income of the year the tax return of the dividend will be paid back. RSS 600 605 50th Anniversary\n",
664
+ "The G200 605 603 \n",
665
+ "--------------\n",
666
+ "\n",
667
+ "Covid19 pandemic gave the world new 1965 results to the National Public Health Protection Agency (SCO), the largest provider of scientific medical care program, the latest one of the scientific community news agency, and the National Public Health Protection Agency (SCO), is an investment cap.\n",
668
+ "The National Public Health Protection Agency (SCO), one of the largest provider of scientific medical care available for the scientific community.\n",
669
+ "The National Public Health Protection Agency (SCO) is a leading provider of clinical research from all medical staff and doctoral research to the National Public Health Protection Agency (SCO), a leading provider of medical care facilities and hospitals, a new patient care center for patients, and a medical care center for approximately 10,000 patients.\n",
670
+ "The National Public Health Protection Agency (SCO) is a state-wide program providing evidence for Medicare patients to treat patients with chronic pain and death risk for patients.\n",
671
+ "We hope to work\n",
672
+ "--------------\n",
673
+ "\n",
674
+ "Biofuels can be used 100% of electric vehicles (KA13669) or 0.5% of electric vehicles. The power to maintain electric vehicles is always a great source of electric vehicles. It can also be used to install vehicle charging via vehicle charging. It also is used to produce a vehicle charging cable that can be used to operate it. It can be used on vehicle charging and charging.\n",
675
+ "The vehicles can be used to protect the fuel and fuel consumption and are used to produce a fuel fuel efficiency.\n",
676
+ "The device is used to protect the vehicle from the vehicle from the vehicle from the vehicle without the car from the vehicle from the vehicle from the vehicle at the vehicle. It also can also be used to store the vehicle from the vehicle from the vehicle from the vehicle from the vehicle from the vehicle from the vehicle from being the vehicle from the vehicle from the vehicle from the vehicle from the vehicle from the vehicle from the vehicle from the vehicle from the vehicle\n",
677
+ "--------------\n",
678
+ "\n",
679
+ "You believe it or not but the fact is that it is an important place for people that are not alone. This is a simple way to deal with people who are the only ones in the country that can be very different from the internet.\n",
680
+ "Anywhere that can be created is that you have to be successful.\n",
681
+ "A lot of people have to have to be able to put people on the Internet, people, as you are now having to use them. If we are working at the time of the year then, we will have to do that as soon as you have to be ready to work on a site. I am no longer looking to know how to improve the work of a site or an Internet site on the site.\n",
682
+ "If you are planning a project or not, you will be ready to work with a site and would make it work as the site.\n",
683
+ "How can I do that? It is a huge challenge for people who want to be in and that have been working the way they have to share in the\n",
684
+ "--------------\n",
685
+ "\n"
686
+ ]
687
+ }
688
+ ],
689
+ "source": [
690
+ "import torch.nn as nn\n",
691
+ "from tsai_gpt.tokenizer import Tokenizer\n",
692
+ "precision = get_default_supported_precision(False)\n",
693
+ "logger = CSVLogger(\"out\", name, flush_logs_every_n_steps=log_interval)\n",
694
+ "fabric = L.Fabric(devices=1, strategy=\"auto\", precision=precision, loggers=logger)\n",
695
+ "\n",
696
+ "config = Config.from_name(model_name)\n",
697
+ "\n",
698
+ "def _init_weights(module: nn.Module) -> None:\n",
699
+ " \"\"\"Meant to be used with `gpt.apply(gpt._init_weights)`.\"\"\"\n",
700
+ " if isinstance(module, nn.Linear):\n",
701
+ " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",
702
+ " if module.bias is not None:\n",
703
+ " torch.nn.init.zeros_(module.bias)\n",
704
+ " elif isinstance(module, nn.Embedding):\n",
705
+ " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",
706
+ " \n",
707
+ "with fabric.init_module(empty_init=True):\n",
708
+ " model = GPT(config)\n",
709
+ " model.apply(_init_weights)\n",
710
+ "model.apply(_init_weights)\n",
711
+ "\n",
712
+ "checkpoint_path = Path(\"out/redpajama/iter-025000-ckpt.pth\")\n",
713
+ "\n",
714
+ "load_checkpoint(fabric, model, checkpoint_path)\n",
715
+ " \n",
716
+ "#print(model.transformer.h[0].mlp.fc.weight)\n",
717
+ "\n",
718
+ "#fabric.print(f\"Time to instantiate model: {time.perf_counter() - t0:.02f} seconds.\")\n",
719
+ "#fabric.print(f\"Total parameters {num_parameters(model):,}\")\n",
720
+ "\n",
721
+ "weight_decay = 1e-1\n",
722
+ "beta1 = 0.9\n",
723
+ "beta2 = 0.95\n",
724
+ "learning_rate = 6e-3\n",
725
+ "hparams = {k: v for k, v in locals().items() if isinstance(v, (int, float, str)) and not k.startswith(\"_\")}\n",
726
+ "\n",
727
+ "model = fabric.setup(model)\n",
728
+ "optimizer = torch.optim.AdamW(\n",
729
+ " model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2), foreach=False\n",
730
+ ")\n",
731
+ "\n",
732
+ "# model_copy = model\n",
733
+ "\n",
734
+ "optimizer = fabric.setup_optimizers(optimizer)\n",
735
+ "\n",
736
+ "state = {\"model\": model, \"optimizer\": optimizer, \"hparams\": hparams, \"iter_num\": 0, \"step_count\": 0}\n",
737
+ "\n",
738
+ "resume = max(out_dir.glob(\"*.pth\"), key=lambda p: int(p.name.split(\"-\")[1]))\n",
739
+ "if resume:\n",
740
+ " fabric.print(f\"Loading model from {resume}\")\n",
741
+ " fabric.load(resume, state)\n",
742
+ "\n",
743
+ "deviceType = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
744
+ "m = model.to(deviceType)\n",
745
+ "tokenizer_gpt = Tokenizer(checkpoint_dir=Path(\"checkpoints/meta-llama/Llama-2-7b-chat-hf\")) \n",
746
+ " \n",
747
+ "def generate_predictions(prompt, max_new_tokens=200, temperature=0.8, top_k=50):\n",
748
+ " m.eval()\n",
749
+ " encoded_text = tokenizer_gpt.encode(prompt)\n",
750
+ " #print('--------------------encoded text = ',encoded_text)\n",
751
+ " \n",
752
+ " reshaped_tensor = torch.unsqueeze(encoded_text, 0).to(deviceType) \n",
753
+ " #print('--------------------reshaped_tensor = ',reshaped_tensor)\n",
754
+ " out_text = tokenizer_gpt.decode(m.generate(reshaped_tensor, max_new_tokens=max_new_tokens, temperature=0.8, top_k=50)[0])\n",
755
+ " m.train()\n",
756
+ " return out_text\n",
757
+ "\n",
758
+ "\n",
759
+ "print(\n",
760
+ " generate_predictions(\n",
761
+ " \"The main reason for the financial \"\n",
762
+ " )\n",
763
+ ")\n",
764
+ "print(\"--------------\\n\")\n",
765
+ "\n",
766
+ "print(\n",
767
+ " generate_predictions(\n",
768
+ " \"Covid19 pandemic gave the world new \"\n",
769
+ " )\n",
770
+ ")\n",
771
+ "print(\"--------------\\n\")\n",
772
+ "\n",
773
+ "print(\n",
774
+ " generate_predictions(\n",
775
+ " \"Biofuels can be used \"\n",
776
+ " )\n",
777
+ ")\n",
778
+ "print(\"--------------\\n\")\n",
779
+ "\n",
780
+ "print(\n",
781
+ " generate_predictions(\n",
782
+ " \"You believe it or not but the fact is\"\n",
783
+ " )\n",
784
+ ")\n",
785
+ "print(\"--------------\\n\")"
786
+ ]
787
+ },
788
+ {
789
+ "cell_type": "code",
790
+ "execution_count": 46,
791
+ "metadata": {
792
+ "tags": []
793
+ },
794
+ "outputs": [],
795
+ "source": [
796
+ "import gc\n",
797
+ "gc.collect()\n",
798
+ "torch.cuda.empty_cache()"
799
+ ]
800
+ },
801
+ {
802
+ "cell_type": "code",
803
+ "execution_count": 45,
804
+ "metadata": {
805
+ "tags": []
806
+ },
807
+ "outputs": [],
808
+ "source": [
809
+ "import os\n",
810
+ "os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"max_split_size_mb:2048\""
811
+ ]
812
+ },
813
+ {
814
+ "cell_type": "code",
815
+ "execution_count": null,
816
+ "metadata": {},
817
+ "outputs": [],
818
+ "source": []
819
+ }
820
+ ],
821
+ "metadata": {
822
+ "availableInstances": [
823
+ {
824
+ "_defaultOrder": 0.0,
825
+ "_isFastLaunch": true,
826
+ "category": "General purpose",
827
+ "gpuNum": 0.0,
828
+ "hideHardwareSpecs": false,
829
+ "memoryGiB": 4.0,
830
+ "name": "ml.t3.medium",
831
+ "vcpuNum": 2.0
832
+ },
833
+ {
834
+ "_defaultOrder": 1.0,
835
+ "_isFastLaunch": false,
836
+ "category": "General purpose",
837
+ "gpuNum": 0.0,
838
+ "hideHardwareSpecs": false,
839
+ "memoryGiB": 8.0,
840
+ "name": "ml.t3.large",
841
+ "vcpuNum": 2.0
842
+ },
843
+ {
844
+ "_defaultOrder": 2.0,
845
+ "_isFastLaunch": false,
846
+ "category": "General purpose",
847
+ "gpuNum": 0.0,
848
+ "hideHardwareSpecs": false,
849
+ "memoryGiB": 16.0,
850
+ "name": "ml.t3.xlarge",
851
+ "vcpuNum": 4.0
852
+ },
853
+ {
854
+ "_defaultOrder": 3.0,
855
+ "_isFastLaunch": false,
856
+ "category": "General purpose",
857
+ "gpuNum": 0.0,
858
+ "hideHardwareSpecs": false,
859
+ "memoryGiB": 32.0,
860
+ "name": "ml.t3.2xlarge",
861
+ "vcpuNum": 8.0
862
+ },
863
+ {
864
+ "_defaultOrder": 4.0,
865
+ "_isFastLaunch": true,
866
+ "category": "General purpose",
867
+ "gpuNum": 0.0,
868
+ "hideHardwareSpecs": false,
869
+ "memoryGiB": 8.0,
870
+ "name": "ml.m5.large",
871
+ "vcpuNum": 2.0
872
+ },
873
+ {
874
+ "_defaultOrder": 5.0,
875
+ "_isFastLaunch": false,
876
+ "category": "General purpose",
877
+ "gpuNum": 0.0,
878
+ "hideHardwareSpecs": false,
879
+ "memoryGiB": 16.0,
880
+ "name": "ml.m5.xlarge",
881
+ "vcpuNum": 4.0
882
+ },
883
+ {
884
+ "_defaultOrder": 6.0,
885
+ "_isFastLaunch": false,
886
+ "category": "General purpose",
887
+ "gpuNum": 0.0,
888
+ "hideHardwareSpecs": false,
889
+ "memoryGiB": 32.0,
890
+ "name": "ml.m5.2xlarge",
891
+ "vcpuNum": 8.0
892
+ },
893
+ {
894
+ "_defaultOrder": 7.0,
895
+ "_isFastLaunch": false,
896
+ "category": "General purpose",
897
+ "gpuNum": 0.0,
898
+ "hideHardwareSpecs": false,
899
+ "memoryGiB": 64.0,
900
+ "name": "ml.m5.4xlarge",
901
+ "vcpuNum": 16.0
902
+ },
903
+ {
904
+ "_defaultOrder": 8.0,
905
+ "_isFastLaunch": false,
906
+ "category": "General purpose",
907
+ "gpuNum": 0.0,
908
+ "hideHardwareSpecs": false,
909
+ "memoryGiB": 128.0,
910
+ "name": "ml.m5.8xlarge",
911
+ "vcpuNum": 32.0
912
+ },
913
+ {
914
+ "_defaultOrder": 9.0,
915
+ "_isFastLaunch": false,
916
+ "category": "General purpose",
917
+ "gpuNum": 0.0,
918
+ "hideHardwareSpecs": false,
919
+ "memoryGiB": 192.0,
920
+ "name": "ml.m5.12xlarge",
921
+ "vcpuNum": 48.0
922
+ },
923
+ {
924
+ "_defaultOrder": 10.0,
925
+ "_isFastLaunch": false,
926
+ "category": "General purpose",
927
+ "gpuNum": 0.0,
928
+ "hideHardwareSpecs": false,
929
+ "memoryGiB": 256.0,
930
+ "name": "ml.m5.16xlarge",
931
+ "vcpuNum": 64.0
932
+ },
933
+ {
934
+ "_defaultOrder": 11.0,
935
+ "_isFastLaunch": false,
936
+ "category": "General purpose",
937
+ "gpuNum": 0.0,
938
+ "hideHardwareSpecs": false,
939
+ "memoryGiB": 384.0,
940
+ "name": "ml.m5.24xlarge",
941
+ "vcpuNum": 96.0
942
+ },
943
+ {
944
+ "_defaultOrder": 12.0,
945
+ "_isFastLaunch": false,
946
+ "category": "General purpose",
947
+ "gpuNum": 0.0,
948
+ "hideHardwareSpecs": false,
949
+ "memoryGiB": 8.0,
950
+ "name": "ml.m5d.large",
951
+ "vcpuNum": 2.0
952
+ },
953
+ {
954
+ "_defaultOrder": 13.0,
955
+ "_isFastLaunch": false,
956
+ "category": "General purpose",
957
+ "gpuNum": 0.0,
958
+ "hideHardwareSpecs": false,
959
+ "memoryGiB": 16.0,
960
+ "name": "ml.m5d.xlarge",
961
+ "vcpuNum": 4.0
962
+ },
963
+ {
964
+ "_defaultOrder": 14.0,
965
+ "_isFastLaunch": false,
966
+ "category": "General purpose",
967
+ "gpuNum": 0.0,
968
+ "hideHardwareSpecs": false,
969
+ "memoryGiB": 32.0,
970
+ "name": "ml.m5d.2xlarge",
971
+ "vcpuNum": 8.0
972
+ },
973
+ {
974
+ "_defaultOrder": 15.0,
975
+ "_isFastLaunch": false,
976
+ "category": "General purpose",
977
+ "gpuNum": 0.0,
978
+ "hideHardwareSpecs": false,
979
+ "memoryGiB": 64.0,
980
+ "name": "ml.m5d.4xlarge",
981
+ "vcpuNum": 16.0
982
+ },
983
+ {
984
+ "_defaultOrder": 16.0,
985
+ "_isFastLaunch": false,
986
+ "category": "General purpose",
987
+ "gpuNum": 0.0,
988
+ "hideHardwareSpecs": false,
989
+ "memoryGiB": 128.0,
990
+ "name": "ml.m5d.8xlarge",
991
+ "vcpuNum": 32.0
992
+ },
993
+ {
994
+ "_defaultOrder": 17.0,
995
+ "_isFastLaunch": false,
996
+ "category": "General purpose",
997
+ "gpuNum": 0.0,
998
+ "hideHardwareSpecs": false,
999
+ "memoryGiB": 192.0,
1000
+ "name": "ml.m5d.12xlarge",
1001
+ "vcpuNum": 48.0
1002
+ },
1003
+ {
1004
+ "_defaultOrder": 18.0,
1005
+ "_isFastLaunch": false,
1006
+ "category": "General purpose",
1007
+ "gpuNum": 0.0,
1008
+ "hideHardwareSpecs": false,
1009
+ "memoryGiB": 256.0,
1010
+ "name": "ml.m5d.16xlarge",
1011
+ "vcpuNum": 64.0
1012
+ },
1013
+ {
1014
+ "_defaultOrder": 19.0,
1015
+ "_isFastLaunch": false,
1016
+ "category": "General purpose",
1017
+ "gpuNum": 0.0,
1018
+ "hideHardwareSpecs": false,
1019
+ "memoryGiB": 384.0,
1020
+ "name": "ml.m5d.24xlarge",
1021
+ "vcpuNum": 96.0
1022
+ },
1023
+ {
1024
+ "_defaultOrder": 20.0,
1025
+ "_isFastLaunch": false,
1026
+ "category": "General purpose",
1027
+ "gpuNum": 0.0,
1028
+ "hideHardwareSpecs": true,
1029
+ "memoryGiB": 0.0,
1030
+ "name": "ml.geospatial.interactive",
1031
+ "supportedImageNames": [
1032
+ "sagemaker-geospatial-v1-0"
1033
+ ],
1034
+ "vcpuNum": 0.0
1035
+ },
1036
+ {
1037
+ "_defaultOrder": 21.0,
1038
+ "_isFastLaunch": true,
1039
+ "category": "Compute optimized",
1040
+ "gpuNum": 0.0,
1041
+ "hideHardwareSpecs": false,
1042
+ "memoryGiB": 4.0,
1043
+ "name": "ml.c5.large",
1044
+ "vcpuNum": 2.0
1045
+ },
1046
+ {
1047
+ "_defaultOrder": 22.0,
1048
+ "_isFastLaunch": false,
1049
+ "category": "Compute optimized",
1050
+ "gpuNum": 0.0,
1051
+ "hideHardwareSpecs": false,
1052
+ "memoryGiB": 8.0,
1053
+ "name": "ml.c5.xlarge",
1054
+ "vcpuNum": 4.0
1055
+ },
1056
+ {
1057
+ "_defaultOrder": 23.0,
1058
+ "_isFastLaunch": false,
1059
+ "category": "Compute optimized",
1060
+ "gpuNum": 0.0,
1061
+ "hideHardwareSpecs": false,
1062
+ "memoryGiB": 16.0,
1063
+ "name": "ml.c5.2xlarge",
1064
+ "vcpuNum": 8.0
1065
+ },
1066
+ {
1067
+ "_defaultOrder": 24.0,
1068
+ "_isFastLaunch": false,
1069
+ "category": "Compute optimized",
1070
+ "gpuNum": 0.0,
1071
+ "hideHardwareSpecs": false,
1072
+ "memoryGiB": 32.0,
1073
+ "name": "ml.c5.4xlarge",
1074
+ "vcpuNum": 16.0
1075
+ },
1076
+ {
1077
+ "_defaultOrder": 25.0,
1078
+ "_isFastLaunch": false,
1079
+ "category": "Compute optimized",
1080
+ "gpuNum": 0.0,
1081
+ "hideHardwareSpecs": false,
1082
+ "memoryGiB": 72.0,
1083
+ "name": "ml.c5.9xlarge",
1084
+ "vcpuNum": 36.0
1085
+ },
1086
+ {
1087
+ "_defaultOrder": 26.0,
1088
+ "_isFastLaunch": false,
1089
+ "category": "Compute optimized",
1090
+ "gpuNum": 0.0,
1091
+ "hideHardwareSpecs": false,
1092
+ "memoryGiB": 96.0,
1093
+ "name": "ml.c5.12xlarge",
1094
+ "vcpuNum": 48.0
1095
+ },
1096
+ {
1097
+ "_defaultOrder": 27.0,
1098
+ "_isFastLaunch": false,
1099
+ "category": "Compute optimized",
1100
+ "gpuNum": 0.0,
1101
+ "hideHardwareSpecs": false,
1102
+ "memoryGiB": 144.0,
1103
+ "name": "ml.c5.18xlarge",
1104
+ "vcpuNum": 72.0
1105
+ },
1106
+ {
1107
+ "_defaultOrder": 28.0,
1108
+ "_isFastLaunch": false,
1109
+ "category": "Compute optimized",
1110
+ "gpuNum": 0.0,
1111
+ "hideHardwareSpecs": false,
1112
+ "memoryGiB": 192.0,
1113
+ "name": "ml.c5.24xlarge",
1114
+ "vcpuNum": 96.0
1115
+ },
1116
+ {
1117
+ "_defaultOrder": 29.0,
1118
+ "_isFastLaunch": true,
1119
+ "category": "Accelerated computing",
1120
+ "gpuNum": 1.0,
1121
+ "hideHardwareSpecs": false,
1122
+ "memoryGiB": 16.0,
1123
+ "name": "ml.g4dn.xlarge",
1124
+ "vcpuNum": 4.0
1125
+ },
1126
+ {
1127
+ "_defaultOrder": 30.0,
1128
+ "_isFastLaunch": false,
1129
+ "category": "Accelerated computing",
1130
+ "gpuNum": 1.0,
1131
+ "hideHardwareSpecs": false,
1132
+ "memoryGiB": 32.0,
1133
+ "name": "ml.g4dn.2xlarge",
1134
+ "vcpuNum": 8.0
1135
+ },
1136
+ {
1137
+ "_defaultOrder": 31.0,
1138
+ "_isFastLaunch": false,
1139
+ "category": "Accelerated computing",
1140
+ "gpuNum": 1.0,
1141
+ "hideHardwareSpecs": false,
1142
+ "memoryGiB": 64.0,
1143
+ "name": "ml.g4dn.4xlarge",
1144
+ "vcpuNum": 16.0
1145
+ },
1146
+ {
1147
+ "_defaultOrder": 32.0,
1148
+ "_isFastLaunch": false,
1149
+ "category": "Accelerated computing",
1150
+ "gpuNum": 1.0,
1151
+ "hideHardwareSpecs": false,
1152
+ "memoryGiB": 128.0,
1153
+ "name": "ml.g4dn.8xlarge",
1154
+ "vcpuNum": 32.0
1155
+ },
1156
+ {
1157
+ "_defaultOrder": 33.0,
1158
+ "_isFastLaunch": false,
1159
+ "category": "Accelerated computing",
1160
+ "gpuNum": 4.0,
1161
+ "hideHardwareSpecs": false,
1162
+ "memoryGiB": 192.0,
1163
+ "name": "ml.g4dn.12xlarge",
1164
+ "vcpuNum": 48.0
1165
+ },
1166
+ {
1167
+ "_defaultOrder": 34.0,
1168
+ "_isFastLaunch": false,
1169
+ "category": "Accelerated computing",
1170
+ "gpuNum": 1.0,
1171
+ "hideHardwareSpecs": false,
1172
+ "memoryGiB": 256.0,
1173
+ "name": "ml.g4dn.16xlarge",
1174
+ "vcpuNum": 64.0
1175
+ },
1176
+ {
1177
+ "_defaultOrder": 35.0,
1178
+ "_isFastLaunch": false,
1179
+ "category": "Accelerated computing",
1180
+ "gpuNum": 1.0,
1181
+ "hideHardwareSpecs": false,
1182
+ "memoryGiB": 61.0,
1183
+ "name": "ml.p3.2xlarge",
1184
+ "vcpuNum": 8.0
1185
+ },
1186
+ {
1187
+ "_defaultOrder": 36.0,
1188
+ "_isFastLaunch": false,
1189
+ "category": "Accelerated computing",
1190
+ "gpuNum": 4.0,
1191
+ "hideHardwareSpecs": false,
1192
+ "memoryGiB": 244.0,
1193
+ "name": "ml.p3.8xlarge",
1194
+ "vcpuNum": 32.0
1195
+ },
1196
+ {
1197
+ "_defaultOrder": 37.0,
1198
+ "_isFastLaunch": false,
1199
+ "category": "Accelerated computing",
1200
+ "gpuNum": 8.0,
1201
+ "hideHardwareSpecs": false,
1202
+ "memoryGiB": 488.0,
1203
+ "name": "ml.p3.16xlarge",
1204
+ "vcpuNum": 64.0
1205
+ },
1206
+ {
1207
+ "_defaultOrder": 38.0,
1208
+ "_isFastLaunch": false,
1209
+ "category": "Accelerated computing",
1210
+ "gpuNum": 8.0,
1211
+ "hideHardwareSpecs": false,
1212
+ "memoryGiB": 768.0,
1213
+ "name": "ml.p3dn.24xlarge",
1214
+ "vcpuNum": 96.0
1215
+ },
1216
+ {
1217
+ "_defaultOrder": 39.0,
1218
+ "_isFastLaunch": false,
1219
+ "category": "Memory Optimized",
1220
+ "gpuNum": 0.0,
1221
+ "hideHardwareSpecs": false,
1222
+ "memoryGiB": 16.0,
1223
+ "name": "ml.r5.large",
1224
+ "vcpuNum": 2.0
1225
+ },
1226
+ {
1227
+ "_defaultOrder": 40.0,
1228
+ "_isFastLaunch": false,
1229
+ "category": "Memory Optimized",
1230
+ "gpuNum": 0.0,
1231
+ "hideHardwareSpecs": false,
1232
+ "memoryGiB": 32.0,
1233
+ "name": "ml.r5.xlarge",
1234
+ "vcpuNum": 4.0
1235
+ },
1236
+ {
1237
+ "_defaultOrder": 41.0,
1238
+ "_isFastLaunch": false,
1239
+ "category": "Memory Optimized",
1240
+ "gpuNum": 0.0,
1241
+ "hideHardwareSpecs": false,
1242
+ "memoryGiB": 64.0,
1243
+ "name": "ml.r5.2xlarge",
1244
+ "vcpuNum": 8.0
1245
+ },
1246
+ {
1247
+ "_defaultOrder": 42.0,
1248
+ "_isFastLaunch": false,
1249
+ "category": "Memory Optimized",
1250
+ "gpuNum": 0.0,
1251
+ "hideHardwareSpecs": false,
1252
+ "memoryGiB": 128.0,
1253
+ "name": "ml.r5.4xlarge",
1254
+ "vcpuNum": 16.0
1255
+ },
1256
+ {
1257
+ "_defaultOrder": 43.0,
1258
+ "_isFastLaunch": false,
1259
+ "category": "Memory Optimized",
1260
+ "gpuNum": 0.0,
1261
+ "hideHardwareSpecs": false,
1262
+ "memoryGiB": 256.0,
1263
+ "name": "ml.r5.8xlarge",
1264
+ "vcpuNum": 32.0
1265
+ },
1266
+ {
1267
+ "_defaultOrder": 44.0,
1268
+ "_isFastLaunch": false,
1269
+ "category": "Memory Optimized",
1270
+ "gpuNum": 0.0,
1271
+ "hideHardwareSpecs": false,
1272
+ "memoryGiB": 384.0,
1273
+ "name": "ml.r5.12xlarge",
1274
+ "vcpuNum": 48.0
1275
+ },
1276
+ {
1277
+ "_defaultOrder": 45.0,
1278
+ "_isFastLaunch": false,
1279
+ "category": "Memory Optimized",
1280
+ "gpuNum": 0.0,
1281
+ "hideHardwareSpecs": false,
1282
+ "memoryGiB": 512.0,
1283
+ "name": "ml.r5.16xlarge",
1284
+ "vcpuNum": 64.0
1285
+ },
1286
+ {
1287
+ "_defaultOrder": 46.0,
1288
+ "_isFastLaunch": false,
1289
+ "category": "Memory Optimized",
1290
+ "gpuNum": 0.0,
1291
+ "hideHardwareSpecs": false,
1292
+ "memoryGiB": 768.0,
1293
+ "name": "ml.r5.24xlarge",
1294
+ "vcpuNum": 96.0
1295
+ },
1296
+ {
1297
+ "_defaultOrder": 47.0,
1298
+ "_isFastLaunch": false,
1299
+ "category": "Accelerated computing",
1300
+ "gpuNum": 1.0,
1301
+ "hideHardwareSpecs": false,
1302
+ "memoryGiB": 16.0,
1303
+ "name": "ml.g5.xlarge",
1304
+ "vcpuNum": 4.0
1305
+ },
1306
+ {
1307
+ "_defaultOrder": 48.0,
1308
+ "_isFastLaunch": false,
1309
+ "category": "Accelerated computing",
1310
+ "gpuNum": 1.0,
1311
+ "hideHardwareSpecs": false,
1312
+ "memoryGiB": 32.0,
1313
+ "name": "ml.g5.2xlarge",
1314
+ "vcpuNum": 8.0
1315
+ },
1316
+ {
1317
+ "_defaultOrder": 49.0,
1318
+ "_isFastLaunch": false,
1319
+ "category": "Accelerated computing",
1320
+ "gpuNum": 1.0,
1321
+ "hideHardwareSpecs": false,
1322
+ "memoryGiB": 64.0,
1323
+ "name": "ml.g5.4xlarge",
1324
+ "vcpuNum": 16.0
1325
+ },
1326
+ {
1327
+ "_defaultOrder": 50.0,
1328
+ "_isFastLaunch": false,
1329
+ "category": "Accelerated computing",
1330
+ "gpuNum": 1.0,
1331
+ "hideHardwareSpecs": false,
1332
+ "memoryGiB": 128.0,
1333
+ "name": "ml.g5.8xlarge",
1334
+ "vcpuNum": 32.0
1335
+ },
1336
+ {
1337
+ "_defaultOrder": 51.0,
1338
+ "_isFastLaunch": false,
1339
+ "category": "Accelerated computing",
1340
+ "gpuNum": 1.0,
1341
+ "hideHardwareSpecs": false,
1342
+ "memoryGiB": 256.0,
1343
+ "name": "ml.g5.16xlarge",
1344
+ "vcpuNum": 64.0
1345
+ },
1346
+ {
1347
+ "_defaultOrder": 52.0,
1348
+ "_isFastLaunch": false,
1349
+ "category": "Accelerated computing",
1350
+ "gpuNum": 4.0,
1351
+ "hideHardwareSpecs": false,
1352
+ "memoryGiB": 192.0,
1353
+ "name": "ml.g5.12xlarge",
1354
+ "vcpuNum": 48.0
1355
+ },
1356
+ {
1357
+ "_defaultOrder": 53.0,
1358
+ "_isFastLaunch": false,
1359
+ "category": "Accelerated computing",
1360
+ "gpuNum": 4.0,
1361
+ "hideHardwareSpecs": false,
1362
+ "memoryGiB": 384.0,
1363
+ "name": "ml.g5.24xlarge",
1364
+ "vcpuNum": 96.0
1365
+ },
1366
+ {
1367
+ "_defaultOrder": 54.0,
1368
+ "_isFastLaunch": false,
1369
+ "category": "Accelerated computing",
1370
+ "gpuNum": 8.0,
1371
+ "hideHardwareSpecs": false,
1372
+ "memoryGiB": 768.0,
1373
+ "name": "ml.g5.48xlarge",
1374
+ "vcpuNum": 192.0
1375
+ },
1376
+ {
1377
+ "_defaultOrder": 55.0,
1378
+ "_isFastLaunch": false,
1379
+ "category": "Accelerated computing",
1380
+ "gpuNum": 8.0,
1381
+ "hideHardwareSpecs": false,
1382
+ "memoryGiB": 1152.0,
1383
+ "name": "ml.p4d.24xlarge",
1384
+ "vcpuNum": 96.0
1385
+ },
1386
+ {
1387
+ "_defaultOrder": 56.0,
1388
+ "_isFastLaunch": false,
1389
+ "category": "Accelerated computing",
1390
+ "gpuNum": 8.0,
1391
+ "hideHardwareSpecs": false,
1392
+ "memoryGiB": 1152.0,
1393
+ "name": "ml.p4de.24xlarge",
1394
+ "vcpuNum": 96.0
1395
+ }
1396
+ ],
1397
+ "instance_type": "ml.g4dn.2xlarge",
1398
+ "kernelspec": {
1399
+ "display_name": "Python 3 (PyTorch 2.0.1 Python 3.10 GPU Optimized)",
1400
+ "language": "python",
1401
+ "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:ap-south-1:394103062818:image/pytorch-2.0.1-gpu-py310"
1402
+ },
1403
+ "language_info": {
1404
+ "codemirror_mode": {
1405
+ "name": "ipython",
1406
+ "version": 3
1407
+ },
1408
+ "file_extension": ".py",
1409
+ "mimetype": "text/x-python",
1410
+ "name": "python",
1411
+ "nbconvert_exporter": "python",
1412
+ "pygments_lexer": "ipython3",
1413
+ "version": "3.10.8"
1414
+ }
1415
+ },
1416
+ "nbformat": 4,
1417
+ "nbformat_minor": 4
1418
+ }
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchaudio
3
+ torchvision
4
+ huggingface_hub
5
+ tokenizers
6
+ sentencepiece
7
+ lightning @ git+https://github.com/Lightning-AI/lightning@532c723c8584903dc719458d0ad52861d51bc395
8
+ jsonargparse[signatures]
tsai_gpt/.DS_Store ADDED
Binary file (6.15 kB). View file
 
tsai_gpt/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tsai_gpt.model import GPT
2
+ from tsai_gpt.config import Config
3
+ from tsai_gpt.tokenizer import Tokenizer
4
+
5
+ from lightning_utilities.core.imports import RequirementCache
6
+
7
+ _LIGHTNING_AVAILABLE = RequirementCache("lightning>=2.1.0.dev0")
8
+ if not bool(_LIGHTNING_AVAILABLE):
9
+ raise ImportError(
10
+ "Lit-GPT requires lightning==2.1. Please run:\n"
11
+ f" pip uninstall -y lightning; pip install -r requirements.txt\n{str(_LIGHTNING_AVAILABLE)}"
12
+ )
13
+
14
+
15
+ __all__ = ["GPT", "Config", "Tokenizer"]
tsai_gpt/config.py ADDED
@@ -0,0 +1,1181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from copy import deepcopy
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from typing import Any, Literal, Optional, Type, Union
6
+
7
+ import torch
8
+ from typing_extensions import Self
9
+
10
+ import tsai_gpt.model
11
+ from tsai_gpt.utils import find_multiple
12
+
13
+
14
+ @dataclass
15
+ class Config:
16
+ name: str = ""
17
+ hf_config: dict = field(default_factory=dict)
18
+ block_size: int = 4096
19
+ vocab_size: int = 50254
20
+ padding_multiple: int = 512
21
+ padded_vocab_size: Optional[int] = None
22
+ n_layer: int = 16
23
+ n_head: int = 32
24
+ n_embd: int = 4096
25
+ rotary_percentage: float = 0.25
26
+ parallel_residual: bool = True
27
+ bias: bool = True
28
+ lm_head_bias: bool = False
29
+ # to use multi-head attention (MHA), set this to `n_head` (default)
30
+ # to use multi-query attention (MQA), set this to 1
31
+ # to use grouped-query attention (GQA), set this to a value in between
32
+ # Example with `n_head=4`
33
+ # ┌───┐┌───┐┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐
34
+ # │ v ││ v ││ v ││ v │ │ v │ │ v │ │ v │
35
+ # └───┘└───┘└───┘└───┘ └───┘ └───┘ └───┘
36
+ # │ │ │ │ │ │ │
37
+ # ┌───┐┌───┐┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐
38
+ # │ k ││ k ││ k ││ k │ │ k │ │ k │ │ k │
39
+ # └───┘└───┘└───┘└───┘ └───┘ └───┘ └───┘
40
+ # │ │ │ │ ┌──┴──┐ ┌──┴──┐ ┌────┬──┴─┬────┐
41
+ # ┌───┐┌───┐┌───┐┌───┐ ┌───┐┌───┐┌───┐┌───┐ ┌───┐┌───┐┌───┐┌───┐
42
+ # │ q ││ q ││ q ││ q │ │ q ││ q ││ q ││ q │ │ q ││ q ││ q ││ q │
43
+ # └───┘└───┘└───┘└───┘ └───┘└───┘└───┘└───┘ └───┘└───┘└───┘└───┘
44
+ # ◀──────────────────▶ ◀──────────────────▶ ◀──────────────────▶
45
+ # MHA GQA MQA
46
+ # n_query_groups=4 n_query_groups=2 n_query_groups=1
47
+ #
48
+ # credit https://arxiv.org/pdf/2305.13245.pdf
49
+ n_query_groups: Optional[int] = None
50
+ shared_attention_norm: bool = False
51
+ _norm_class: Literal["LayerNorm", "RMSNorm"] = "LayerNorm"
52
+ norm_eps: float = 1e-5
53
+ _mlp_class: Literal["GptNeoxMLP", "LLaMAMLP"] = "GptNeoxMLP"
54
+ gelu_approximate: str = "none"
55
+ intermediate_size: Optional[int] = None
56
+ rope_condense_ratio: int = 1
57
+ rope_base: int = 10000
58
+
59
+ def __post_init__(self):
60
+ if not self.name:
61
+ self.name = self.hf_config.get("name", self.name)
62
+
63
+ assert self.n_embd % self.n_head == 0
64
+ self.head_size = self.n_embd // self.n_head
65
+
66
+ # vocab size should be a power of 2 to be optimal on hardware. compute the closest value
67
+ if self.padded_vocab_size is None:
68
+ self.padded_vocab_size = find_multiple(self.vocab_size, self.padding_multiple)
69
+ else:
70
+ # vocab size shouldn't be larger than padded vocab size
71
+ self.vocab_size = min(self.vocab_size, self.padded_vocab_size)
72
+
73
+ # compute the number of query groups
74
+ if self.n_query_groups is not None:
75
+ assert self.n_head % self.n_query_groups == 0
76
+ else:
77
+ self.n_query_groups = self.n_head
78
+
79
+ # compute the intermediate size for MLP if not set
80
+ if self.intermediate_size is None:
81
+ if self._mlp_class == "LLaMAMLP":
82
+ raise ValueError("The config needs to set the `intermediate_size`")
83
+ self.intermediate_size = 4 * self.n_embd
84
+
85
+ self.rope_n_elem = int(self.rotary_percentage * self.head_size)
86
+
87
+ @classmethod
88
+ def from_name(cls, name: str, **kwargs: Any) -> Self:
89
+ if name not in name_to_config:
90
+ # search through all `config['hf_config']['name']`
91
+ conf_dict = next(config for config in configs if name == config["hf_config"]["name"])
92
+ else:
93
+ conf_dict = name_to_config[name]
94
+
95
+ conf_dict = conf_dict.copy()
96
+ if "condense_ratio" in kwargs: # legacy name
97
+ kwargs["rope_condense_ratio"] = kwargs.pop("condense_ratio")
98
+ conf_dict.update(kwargs)
99
+ return cls(**conf_dict)
100
+
101
+ @classmethod
102
+ def from_json(cls, path: Union[str, Path], **kwargs: Any) -> Self:
103
+ with open(path, encoding="utf-8") as fp:
104
+ json_kwargs = json.load(fp)
105
+ if "condense_ratio" in json_kwargs: # legacy name
106
+ json_kwargs["rope_condense_ratio"] = json_kwargs.pop("condense_ratio")
107
+ if "condense_ratio" in kwargs: # legacy name
108
+ kwargs["rope_condense_ratio"] = kwargs.pop("condense_ratio")
109
+ if "org" in json_kwargs: # legacy name
110
+ json_kwargs["hf_config"] = {"name": json_kwargs["name"], "org": json_kwargs.pop("org")}
111
+ if "org" in kwargs: # legacy name
112
+ kwargs["hf_config"] = {"name": kwargs.get("name", json_kwargs["name"]), "org": kwargs.pop("org")}
113
+ json_kwargs.update(kwargs)
114
+ return cls(**json_kwargs)
115
+
116
+ @property
117
+ def mlp_class(self) -> Type:
118
+ # `self._mlp_class` cannot be the type to keep the config json serializable
119
+ return getattr(tsai_gpt.model, self._mlp_class)
120
+
121
+ @property
122
+ def norm_class(self) -> Type:
123
+ # `self._norm_class` cannot be the type to keep the config json serializable
124
+ if self._norm_class == "RMSNorm":
125
+ from tsai_gpt.rmsnorm import RMSNorm
126
+
127
+ return RMSNorm
128
+ return getattr(torch.nn, self._norm_class)
129
+
130
+
131
+ ########################
132
+ # Stability AI StableLM
133
+ ########################
134
+ configs = [
135
+ # https://huggingface.co/stabilityai/stablelm-base-alpha-3b/blob/main/config.json
136
+ dict(name="stablelm-base-alpha-3b", hf_config=dict(org="stabilityai", name="stablelm-base-alpha-3b")),
137
+ # https://huggingface.co/stabilityai/stablelm-base-alpha-7b/blob/main/config.json
138
+ dict(
139
+ name="stablelm-base-alpha-7b",
140
+ hf_config=dict(org="stabilityai", name="stablelm-base-alpha-7b"),
141
+ n_head=48,
142
+ n_embd=6144,
143
+ padding_multiple=256,
144
+ ),
145
+ # https://huggingface.co/stabilityai/stablelm-tuned-alpha-3b/blob/main/config.json
146
+ dict(name="stablelm-tuned-alpha-3b", hf_config=dict(org="stabilityai", name="stablelm-tuned-alpha-3b"), n_head=32),
147
+ # https://huggingface.co/stabilityai/stablelm-tuned-alpha-7b/blob/main/config.json
148
+ dict(
149
+ name="stablelm-tuned-alpha-7b",
150
+ hf_config=dict(org="stabilityai", name="stablelm-tuned-alpha-7b"),
151
+ n_head=48,
152
+ n_embd=6144,
153
+ padding_multiple=256,
154
+ ),
155
+ ]
156
+
157
+ ####################
158
+ # EleutherAI Pythia
159
+ ####################
160
+ pythia = [
161
+ # https://huggingface.co/EleutherAI/pythia-70m/blob/main/config.json
162
+ dict(
163
+ name="pythia-70m",
164
+ hf_config=dict(org="EleutherAI", name="pythia-70m"),
165
+ block_size=2048,
166
+ n_layer=6,
167
+ n_embd=512,
168
+ n_head=8,
169
+ padding_multiple=128,
170
+ ),
171
+ # https://huggingface.co/EleutherAI/pythia-160m/blob/main/config.json
172
+ dict(
173
+ name="pythia-160m",
174
+ hf_config=dict(org="EleutherAI", name="pythia-160m"),
175
+ block_size=2048,
176
+ n_layer=12,
177
+ n_embd=768,
178
+ n_head=12,
179
+ padding_multiple=128,
180
+ ),
181
+ # https://huggingface.co/EleutherAI/pythia-410m/blob/main/config.json
182
+ dict(
183
+ name="pythia-410m",
184
+ hf_config=dict(org="EleutherAI", name="pythia-410m"),
185
+ block_size=2048,
186
+ n_layer=24,
187
+ n_embd=1024,
188
+ n_head=16,
189
+ padding_multiple=128,
190
+ ),
191
+ # https://huggingface.co/EleutherAI/pythia-1b/blob/main/config.json
192
+ dict(
193
+ name="pythia-1b",
194
+ hf_config=dict(org="EleutherAI", name="pythia-1b"),
195
+ block_size=2048,
196
+ n_embd=2048,
197
+ n_head=8,
198
+ padding_multiple=128,
199
+ ),
200
+ # https://huggingface.co/EleutherAI/pythia-1.4b/blob/main/config.json
201
+ dict(
202
+ name="pythia-1.4b",
203
+ hf_config=dict(org="EleutherAI", name="pythia-1.4b"),
204
+ block_size=2048,
205
+ n_layer=24,
206
+ n_embd=2048,
207
+ n_head=16,
208
+ padding_multiple=128,
209
+ ),
210
+ # https://huggingface.co/EleutherAI/pythia-2.8b/blob/main/config.json
211
+ dict(
212
+ name="pythia-2.8b",
213
+ hf_config=dict(org="EleutherAI", name="pythia-2.8b"),
214
+ block_size=2048,
215
+ n_layer=32,
216
+ n_embd=2560,
217
+ padding_multiple=128,
218
+ ),
219
+ # https://huggingface.co/EleutherAI/pythia-6.9b/blob/main/config.json
220
+ dict(
221
+ name="pythia-6.9b",
222
+ hf_config=dict(org="EleutherAI", name="pythia-6.9b"),
223
+ block_size=2048,
224
+ n_layer=32,
225
+ padding_multiple=256,
226
+ ),
227
+ # https://huggingface.co/EleutherAI/pythia-12b/blob/main/config.json
228
+ dict(
229
+ name="pythia-12b",
230
+ hf_config=dict(org="EleutherAI", name="pythia-12b"),
231
+ block_size=2048,
232
+ n_layer=36,
233
+ n_embd=5120,
234
+ n_head=40,
235
+ ),
236
+ ]
237
+ configs.extend(pythia)
238
+ for c in pythia:
239
+ copy = c.copy()
240
+ copy["name"] = f"{c['name']}-deduped"
241
+ copy["hf_config"]["name"] = f"{c['hf_config']['name']}-deduped"
242
+ configs.append(copy)
243
+
244
+
245
+ ####################################
246
+ # togethercomputer RedPajama INCITE
247
+ ####################################
248
+ redpajama_incite = [
249
+ # https://huggingface.co/togethercomputer/RedPajama-INCITE-Base-3B-v1/blob/main/config.json
250
+ dict(
251
+ name="RedPajama-INCITE-{}-3B-v1",
252
+ hf_config=dict(org="togethercomputer", name="RedPajama-INCITE-{}-3B-v1"),
253
+ block_size=2048,
254
+ n_layer=32,
255
+ n_embd=2560,
256
+ padding_multiple=256,
257
+ rotary_percentage=1.0,
258
+ parallel_residual=False,
259
+ ),
260
+ # https://huggingface.co/togethercomputer/RedPajama-INCITE-7B-Base/blob/main/config.json
261
+ dict(
262
+ name="RedPajama-INCITE-7B-{}",
263
+ hf_config=dict(org="togethercomputer", name="RedPajama-INCITE-7B-{}"),
264
+ block_size=2048,
265
+ n_layer=32,
266
+ padding_multiple=256,
267
+ rotary_percentage=1.0,
268
+ parallel_residual=False,
269
+ ),
270
+ # this redirects to the checkpoint above. kept for those who had the old weights already downloaded
271
+ dict(
272
+ name="RedPajama-INCITE-{}-7B-v0.1",
273
+ hf_config=dict(org="togethercomputer", name="RedPajama-INCITE-{}-7B-v0.1"),
274
+ block_size=2048,
275
+ n_layer=32,
276
+ padding_multiple=256,
277
+ rotary_percentage=1.0,
278
+ parallel_residual=False,
279
+ ),
280
+ ]
281
+ for c in redpajama_incite:
282
+ for kind in ("Base", "Chat", "Instruct"):
283
+ copy = c.copy()
284
+ copy["name"] = c["name"].format(kind)
285
+ copy["hf_config"]["name"] = c["hf_config"]["name"].format(kind)
286
+ configs.append(copy)
287
+
288
+
289
+ #################
290
+ # TII UAE Falcon
291
+ #################
292
+ falcon = [
293
+ # https://huggingface.co/tiiuae/falcon-7b/blob/main/config.json
294
+ dict(
295
+ name="falcon-7b{}",
296
+ hf_config=dict(org="tiiuae", name="falcon-7b{}"),
297
+ block_size=2048,
298
+ vocab_size=65024,
299
+ padded_vocab_size=65024,
300
+ n_layer=32,
301
+ n_head=71,
302
+ n_embd=4544,
303
+ rotary_percentage=1.0,
304
+ n_query_groups=1,
305
+ bias=False,
306
+ # this is not in the config, but in the original model implementation, only for this config
307
+ shared_attention_norm=True,
308
+ ),
309
+ # https://huggingface.co/tiiuae/falcon-40b/blob/main/config.json
310
+ dict(
311
+ name="falcon-40b{}",
312
+ hf_config=dict(org="tiiuae", name="falcon-40b{}"),
313
+ block_size=2048,
314
+ vocab_size=65024,
315
+ padded_vocab_size=65024,
316
+ n_layer=60,
317
+ n_head=128,
318
+ n_embd=8192,
319
+ rotary_percentage=1.0,
320
+ n_query_groups=8,
321
+ bias=False,
322
+ ),
323
+ ]
324
+ for c in falcon:
325
+ for kind in ("", "-instruct"):
326
+ copy = c.copy()
327
+ copy["name"] = c["name"].format(kind)
328
+ copy["hf_config"]["name"] = c["hf_config"]["name"].format(kind)
329
+ configs.append(copy)
330
+
331
+ # https://huggingface.co/tiiuae/falcon-180b/blob/main/config.json
332
+ falcon180b = dict(
333
+ name="falcon-180B{}",
334
+ hf_config=dict(org="tiiuae", name="falcon-180B{}"),
335
+ block_size=2048,
336
+ vocab_size=65024,
337
+ padded_vocab_size=65024,
338
+ n_layer=80,
339
+ n_head=232,
340
+ n_embd=14848,
341
+ rotary_percentage=1.0,
342
+ n_query_groups=8,
343
+ bias=False,
344
+ )
345
+
346
+ for kind in ("", "-chat"):
347
+ copy = falcon180b.copy()
348
+ copy["name"] = falcon180b["name"].format(kind)
349
+ copy["hf_config"]["name"] = falcon180b["hf_config"]["name"].format(kind)
350
+ configs.append(copy)
351
+
352
+
353
+ #############################
354
+ # OpenLM Research Open LLaMA
355
+ #############################
356
+ open_LLaMA = [
357
+ # https://huggingface.co/openlm-research/open_llama_3b/blob/main/config.json
358
+ dict(
359
+ name="open_llama_3b",
360
+ hf_config=dict(org="openlm-research", name="open_llama_3b"),
361
+ block_size=2048,
362
+ vocab_size=32000,
363
+ padding_multiple=64,
364
+ n_layer=26,
365
+ n_embd=3200,
366
+ rotary_percentage=1.0,
367
+ parallel_residual=False,
368
+ bias=False,
369
+ _norm_class="RMSNorm",
370
+ norm_eps=1e-6,
371
+ _mlp_class="LLaMAMLP",
372
+ intermediate_size=8640,
373
+ ),
374
+ # https://huggingface.co/openlm-research/open_llama_7b/blob/main/config.json
375
+ dict(
376
+ name="open_llama_7b",
377
+ hf_config=dict(org="openlm-research", name="open_llama_7b"),
378
+ block_size=2048,
379
+ vocab_size=32000,
380
+ padding_multiple=64,
381
+ n_layer=32,
382
+ rotary_percentage=1.0,
383
+ parallel_residual=False,
384
+ bias=False,
385
+ _norm_class="RMSNorm",
386
+ norm_eps=1e-6,
387
+ _mlp_class="LLaMAMLP",
388
+ intermediate_size=11008,
389
+ ),
390
+ # https://huggingface.co/openlm-research/open_llama_13b/blob/main/config.json
391
+ dict(
392
+ name="open_llama_13b",
393
+ hf_config=dict(org="openlm-research", name="open_llama_13b"),
394
+ block_size=2048,
395
+ vocab_size=32000,
396
+ padding_multiple=64,
397
+ n_layer=40,
398
+ n_head=40,
399
+ n_embd=5120,
400
+ rotary_percentage=1.0,
401
+ parallel_residual=False,
402
+ bias=False,
403
+ _norm_class="RMSNorm",
404
+ norm_eps=1e-6,
405
+ _mlp_class="LLaMAMLP",
406
+ intermediate_size=13824,
407
+ ),
408
+ ]
409
+ configs.extend(open_LLaMA)
410
+
411
+
412
+ ###############
413
+ # LMSYS Vicuna
414
+ ###############
415
+ vicuna = [
416
+ # https://huggingface.co/lmsys/vicuna-7b-v1.3/blob/main/config.json
417
+ dict(
418
+ name="vicuna-7b-v1.3",
419
+ hf_config=dict(org="lmsys", name="vicuna-7b-v1.3"),
420
+ block_size=2048,
421
+ vocab_size=32000,
422
+ padding_multiple=64,
423
+ n_layer=32,
424
+ rotary_percentage=1.0,
425
+ parallel_residual=False,
426
+ bias=False,
427
+ _norm_class="RMSNorm",
428
+ norm_eps=1e-6,
429
+ _mlp_class="LLaMAMLP",
430
+ intermediate_size=11008,
431
+ ),
432
+ # https://huggingface.co/lmsys/vicuna-13b-v1.3/blob/main/config.json
433
+ dict(
434
+ name="vicuna-13b-v1.3",
435
+ hf_config=dict(org="lmsys", name="vicuna-13b-v1.3"),
436
+ block_size=2048,
437
+ vocab_size=32000,
438
+ padding_multiple=64,
439
+ n_layer=40,
440
+ n_head=40,
441
+ n_embd=5120,
442
+ rotary_percentage=1.0,
443
+ parallel_residual=False,
444
+ bias=False,
445
+ _norm_class="RMSNorm",
446
+ norm_eps=1e-6,
447
+ _mlp_class="LLaMAMLP",
448
+ intermediate_size=13824,
449
+ ),
450
+ # https://huggingface.co/lmsys/vicuna-33b-v1.3/blob/main/config.json
451
+ dict(
452
+ name="vicuna-33b-v1.3",
453
+ hf_config=dict(org="lmsys", name="vicuna-33b-v1.3"),
454
+ block_size=2048,
455
+ vocab_size=32000,
456
+ padding_multiple=64,
457
+ n_layer=60,
458
+ n_head=52,
459
+ n_embd=6656,
460
+ rotary_percentage=1.0,
461
+ parallel_residual=False,
462
+ bias=False,
463
+ _norm_class="RMSNorm",
464
+ norm_eps=1e-6,
465
+ _mlp_class="LLaMAMLP",
466
+ intermediate_size=17920,
467
+ ),
468
+ # https://huggingface.co/lmsys/vicuna-7b-v1.5/blob/main/config.json
469
+ dict(
470
+ name="vicuna-7b-v1.5",
471
+ hf_config=dict(org="lmsys", name="vicuna-7b-v1.5"),
472
+ vocab_size=32000,
473
+ padding_multiple=64,
474
+ n_layer=32,
475
+ rotary_percentage=1.0,
476
+ parallel_residual=False,
477
+ bias=False,
478
+ _norm_class="RMSNorm",
479
+ _mlp_class="LLaMAMLP",
480
+ intermediate_size=11008,
481
+ ),
482
+ # https://huggingface.co/lmsys/vicuna-7b-v1.5-16k/blob/main/config.json
483
+ dict(
484
+ name="vicuna-7b-v1.5-16k",
485
+ hf_config=dict(org="lmsys", name="vicuna-7b-v1.5-16k"),
486
+ block_size=16384,
487
+ vocab_size=32000,
488
+ padding_multiple=64,
489
+ n_layer=32,
490
+ rotary_percentage=1.0,
491
+ parallel_residual=False,
492
+ bias=False,
493
+ _norm_class="RMSNorm",
494
+ _mlp_class="LLaMAMLP",
495
+ intermediate_size=11008,
496
+ rope_condense_ratio=4,
497
+ ),
498
+ # https://huggingface.co/lmsys/vicuna-13b-v1.5/blob/main/config.json
499
+ dict(
500
+ name="vicuna-13b-v1.5",
501
+ hf_config=dict(org="lmsys", name="vicuna-13b-v1.5"),
502
+ vocab_size=32000,
503
+ padding_multiple=64,
504
+ n_layer=40,
505
+ n_head=40,
506
+ n_embd=5120,
507
+ rotary_percentage=1.0,
508
+ parallel_residual=False,
509
+ bias=False,
510
+ _norm_class="RMSNorm",
511
+ _mlp_class="LLaMAMLP",
512
+ intermediate_size=13824,
513
+ ),
514
+ # https://huggingface.co/lmsys/vicuna-13b-v1.5-16k/blob/main/config.json
515
+ dict(
516
+ name="vicuna-13b-v1.5-16k",
517
+ hf_config=dict(org="lmsys", name="vicuna-13b-v1.5-16k"),
518
+ block_size=16384,
519
+ vocab_size=32000,
520
+ padding_multiple=64,
521
+ n_layer=40,
522
+ n_head=40,
523
+ n_embd=5120,
524
+ rotary_percentage=1.0,
525
+ parallel_residual=False,
526
+ bias=False,
527
+ _norm_class="RMSNorm",
528
+ _mlp_class="LLaMAMLP",
529
+ intermediate_size=13824,
530
+ rope_condense_ratio=4,
531
+ ),
532
+ ]
533
+ configs.extend(vicuna)
534
+
535
+
536
+ #################
537
+ # LMSYS LongChat
538
+ #################
539
+ long_chat = [
540
+ # https://huggingface.co/lmsys/longchat-7b-16k/blob/main/config.json
541
+ dict(
542
+ name="longchat-7b-16k",
543
+ hf_config=dict(org="lmsys", name="longchat-7b-16k"),
544
+ block_size=16384,
545
+ vocab_size=32000,
546
+ padding_multiple=64,
547
+ n_layer=32,
548
+ rotary_percentage=1.0,
549
+ parallel_residual=False,
550
+ bias=False,
551
+ _norm_class="RMSNorm",
552
+ norm_eps=1e-6,
553
+ _mlp_class="LLaMAMLP",
554
+ intermediate_size=11008,
555
+ rope_condense_ratio=8,
556
+ ),
557
+ # https://huggingface.co/lmsys/longchat-13b-16k/blob/main/config.json
558
+ dict(
559
+ name="longchat-13b-16k",
560
+ hf_config=dict(org="lmsys", name="longchat-13b-16k"),
561
+ block_size=16384,
562
+ vocab_size=32000,
563
+ padding_multiple=64,
564
+ n_layer=40,
565
+ n_head=40,
566
+ n_embd=5120,
567
+ rotary_percentage=1.0,
568
+ parallel_residual=False,
569
+ bias=False,
570
+ _norm_class="RMSNorm",
571
+ norm_eps=1e-6,
572
+ _mlp_class="LLaMAMLP",
573
+ intermediate_size=13824,
574
+ rope_condense_ratio=8,
575
+ ),
576
+ ]
577
+ configs.extend(long_chat)
578
+
579
+
580
+ ######################
581
+ # NousResearch Hermes
582
+ ######################
583
+ nous_research = [
584
+ # https://huggingface.co/NousResearch/Nous-Hermes-llama-2-7b/blob/main/config.json
585
+ dict(
586
+ name="Nous-Hermes-llama-2-7b",
587
+ hf_config=dict(org="NousResearch", name="Nous-Hermes-llama-2-7b"),
588
+ padded_vocab_size=32000,
589
+ n_layer=32,
590
+ rotary_percentage=1.0,
591
+ parallel_residual=False,
592
+ bias=False,
593
+ _norm_class="RMSNorm",
594
+ norm_eps=1e-05,
595
+ _mlp_class="LLaMAMLP",
596
+ intermediate_size=11008,
597
+ ),
598
+ # https://huggingface.co/NousResearch/Nous-Hermes-13B/blob/main/config.json
599
+ dict(
600
+ name="Nous-Hermes-13b",
601
+ hf_config=dict(org="NousResearch", name="Nous-Hermes-13b"),
602
+ block_size=2048,
603
+ vocab_size=32000,
604
+ padded_vocab_size=32001,
605
+ n_layer=40,
606
+ n_head=40,
607
+ n_embd=5120,
608
+ rotary_percentage=1.0,
609
+ parallel_residual=False,
610
+ bias=False,
611
+ _norm_class="RMSNorm",
612
+ norm_eps=1e-6,
613
+ _mlp_class="LLaMAMLP",
614
+ intermediate_size=13824,
615
+ ),
616
+ # https://huggingface.co/NousResearch/Nous-Hermes-Llama2-13b
617
+ dict(
618
+ name="Nous-Hermes-Llama2-13b",
619
+ hf_config=dict(org="NousResearch", name="Nous-Hermes-Llama2-13b"),
620
+ vocab_size=32000,
621
+ padded_vocab_size=32032,
622
+ n_layer=40,
623
+ n_head=40,
624
+ n_embd=5120,
625
+ rotary_percentage=1.0,
626
+ parallel_residual=False,
627
+ bias=False,
628
+ _norm_class="RMSNorm",
629
+ norm_eps=1e-05,
630
+ _mlp_class="LLaMAMLP",
631
+ intermediate_size=13824,
632
+ ),
633
+ ]
634
+ configs.extend(nous_research)
635
+
636
+
637
+ ###############
638
+ # Meta LLaMA 2
639
+ ###############
640
+ llama_2 = [
641
+ # https://huggingface.co/meta-llama/Llama-2-7b-hf/blob/main/config.json
642
+ dict(
643
+ name="Llama-2-7b{}-hf",
644
+ hf_config=dict(org="meta-llama", name="Llama-2-7b{}-hf"),
645
+ vocab_size=32000,
646
+ padding_multiple=64,
647
+ n_layer=32,
648
+ rotary_percentage=1.0,
649
+ parallel_residual=False,
650
+ bias=False,
651
+ _norm_class="RMSNorm",
652
+ _mlp_class="LLaMAMLP",
653
+ intermediate_size=11008,
654
+ ),
655
+ # https://huggingface.co/meta-llama/Llama-2-13b-hf/blob/main/config.json
656
+ dict(
657
+ name="Llama-2-13b{}-hf",
658
+ hf_config=dict(org="meta-llama", name="Llama-2-13b{}-hf"),
659
+ vocab_size=32000,
660
+ padding_multiple=64,
661
+ n_layer=40,
662
+ n_head=40,
663
+ n_embd=5120,
664
+ rotary_percentage=1.0,
665
+ parallel_residual=False,
666
+ bias=False,
667
+ _norm_class="RMSNorm",
668
+ _mlp_class="LLaMAMLP",
669
+ intermediate_size=13824,
670
+ ),
671
+ # https://huggingface.co/meta-llama/Llama-2-70b-hf/blob/main/config.json
672
+ dict(
673
+ name="Llama-2-70b{}-hf",
674
+ hf_config=dict(org="meta-llama", name="Llama-2-70b{}-hf"),
675
+ vocab_size=32000,
676
+ padding_multiple=64,
677
+ n_layer=80,
678
+ n_head=64,
679
+ n_embd=8192,
680
+ n_query_groups=8,
681
+ rotary_percentage=1.0,
682
+ parallel_residual=False,
683
+ bias=False,
684
+ _norm_class="RMSNorm",
685
+ _mlp_class="LLaMAMLP",
686
+ intermediate_size=28672,
687
+ ),
688
+ ]
689
+ for c in llama_2:
690
+ for kind in ("", "-chat"):
691
+ copy = c.copy()
692
+ copy["name"] = c["name"].format(kind)
693
+ copy["hf_config"]["name"] = c["hf_config"]["name"].format(kind)
694
+ configs.append(copy)
695
+
696
+
697
+ ##########################
698
+ # Stability AI FreeWilly2
699
+ ##########################
700
+ freewilly_2 = [
701
+ # https://huggingface.co/stabilityai/FreeWilly2/blob/main/config.json
702
+ dict(
703
+ name="FreeWilly2",
704
+ hf_config=dict(org="stabilityai", name="FreeWilly2"),
705
+ vocab_size=32000,
706
+ padding_multiple=64,
707
+ n_layer=80,
708
+ n_head=64,
709
+ n_embd=8192,
710
+ n_query_groups=8,
711
+ rotary_percentage=1.0,
712
+ parallel_residual=False,
713
+ bias=False,
714
+ _norm_class="RMSNorm",
715
+ _mlp_class="LLaMAMLP",
716
+ intermediate_size=28672,
717
+ )
718
+ ]
719
+ configs.extend(freewilly_2)
720
+
721
+
722
+ ##################
723
+ # Meta Code Llama
724
+ ##################
725
+ code_llama = [
726
+ # https://huggingface.co/codellama/CodeLlama-7b-hf/blob/main/config.json
727
+ dict(
728
+ name="CodeLlama-7b-hf",
729
+ hf_config=dict(org="codellama", name="CodeLlama-7b-hf"),
730
+ block_size=16384,
731
+ vocab_size=32016,
732
+ padding_multiple=16,
733
+ n_layer=32,
734
+ rotary_percentage=1.0,
735
+ parallel_residual=False,
736
+ bias=False,
737
+ _norm_class="RMSNorm",
738
+ norm_eps=1e-05,
739
+ _mlp_class="LLaMAMLP",
740
+ intermediate_size=11008,
741
+ rope_base=1000000,
742
+ ),
743
+ # https://huggingface.co/codellama/CodeLlama-13b-hf/blob/main/config.json
744
+ dict(
745
+ name="CodeLlama-13b-hf",
746
+ hf_config=dict(org="codellama", name="CodeLlama-13b-hf"),
747
+ block_size=16384,
748
+ vocab_size=32016,
749
+ padding_multiple=16,
750
+ n_layer=40,
751
+ n_head=40,
752
+ n_embd=5120,
753
+ rotary_percentage=1.0,
754
+ parallel_residual=False,
755
+ bias=False,
756
+ _norm_class="RMSNorm",
757
+ norm_eps=1e-05,
758
+ _mlp_class="LLaMAMLP",
759
+ intermediate_size=13824,
760
+ rope_base=1000000,
761
+ ),
762
+ # https://huggingface.co/codellama/CodeLlama-34b-hf/blob/main/config.json
763
+ dict(
764
+ name="CodeLlama-34b-hf",
765
+ hf_config=dict(org="codellama", name="CodeLlama-34b-hf"),
766
+ block_size=16384,
767
+ vocab_size=32000,
768
+ padding_multiple=64,
769
+ n_layer=48,
770
+ n_head=64,
771
+ n_embd=8192,
772
+ n_query_groups=8,
773
+ rotary_percentage=1.0,
774
+ parallel_residual=False,
775
+ bias=False,
776
+ _norm_class="RMSNorm",
777
+ norm_eps=1e-05,
778
+ _mlp_class="LLaMAMLP",
779
+ intermediate_size=22016,
780
+ rope_base=1000000,
781
+ ),
782
+ # https://huggingface.co/codellama/CodeLlama-7b-Python-hf/blob/main/config.json
783
+ dict(
784
+ name="CodeLlama-7b-Python-hf",
785
+ hf_config=dict(org="codellama", name="CodeLlama-7b-Python-hf"),
786
+ block_size=16384,
787
+ vocab_size=32000,
788
+ padding_multiple=64,
789
+ n_layer=32,
790
+ rotary_percentage=1.0,
791
+ parallel_residual=False,
792
+ bias=False,
793
+ _norm_class="RMSNorm",
794
+ norm_eps=1e-05,
795
+ _mlp_class="LLaMAMLP",
796
+ intermediate_size=11008,
797
+ rope_base=1000000,
798
+ ),
799
+ # https://huggingface.co/codellama/CodeLlama-13b-Python-hf/blob/main/config.json
800
+ dict(
801
+ name="CodeLlama-13b-Python-hf",
802
+ hf_config=dict(org="codellama", name="CodeLlama-13b-Python-hf"),
803
+ block_size=16384,
804
+ vocab_size=32000,
805
+ padding_multiple=64,
806
+ n_layer=40,
807
+ n_head=40,
808
+ n_embd=5120,
809
+ rotary_percentage=1.0,
810
+ parallel_residual=False,
811
+ bias=False,
812
+ _norm_class="RMSNorm",
813
+ norm_eps=1e-05,
814
+ _mlp_class="LLaMAMLP",
815
+ intermediate_size=13824,
816
+ rope_base=1000000,
817
+ ),
818
+ # https://huggingface.co/codellama/CodeLlama-34b-Python-hf/blob/main/config.json
819
+ dict(
820
+ name="CodeLlama-34b-Python-hf",
821
+ hf_config=dict(org="codellama", name="CodeLlama-34b-Python-hf"),
822
+ block_size=16384,
823
+ vocab_size=32000,
824
+ padding_multiple=64,
825
+ n_layer=48,
826
+ n_head=64,
827
+ n_embd=8192,
828
+ n_query_groups=8,
829
+ rotary_percentage=1.0,
830
+ parallel_residual=False,
831
+ bias=False,
832
+ _norm_class="RMSNorm",
833
+ norm_eps=1e-05,
834
+ _mlp_class="LLaMAMLP",
835
+ intermediate_size=22016,
836
+ rope_base=1000000,
837
+ ),
838
+ # https://huggingface.co/codellama/CodeLlama-7b-Instruct-hf/tree/main/config.json
839
+ dict(
840
+ name="CodeLlama-7b-Instruct-hf",
841
+ hf_config=dict(org="codellama", name="CodeLlama-7b-Instruct-hf"),
842
+ block_size=16384,
843
+ vocab_size=32016,
844
+ padding_multiple=16,
845
+ n_layer=32,
846
+ rotary_percentage=1.0,
847
+ parallel_residual=False,
848
+ bias=False,
849
+ _norm_class="RMSNorm",
850
+ norm_eps=1e-05,
851
+ _mlp_class="LLaMAMLP",
852
+ intermediate_size=11008,
853
+ rope_base=1000000,
854
+ ),
855
+ # https://huggingface.co/codellama/CodeLlama-13b-Instruct-hf/blob/main/config.json
856
+ dict(
857
+ name="CodeLlama-13b-Instruct-hf",
858
+ hf_config=dict(org="codellama", name="CodeLlama-13b-Instruct-hf"),
859
+ block_size=2048,
860
+ vocab_size=32016,
861
+ padding_multiple=16,
862
+ n_layer=40,
863
+ n_head=40,
864
+ n_embd=5120,
865
+ rotary_percentage=1.0,
866
+ parallel_residual=False,
867
+ bias=False,
868
+ _norm_class="RMSNorm",
869
+ norm_eps=1e-05,
870
+ _mlp_class="LLaMAMLP",
871
+ intermediate_size=13824,
872
+ rope_base=1000000,
873
+ ),
874
+ # https://huggingface.co/codellama/CodeLlama-34b-Instruct-hf/blob/main/config.json
875
+ dict(
876
+ name="CodeLlama-34b-Instruct-hf",
877
+ hf_config=dict(org="codellama", name="CodeLlama-34b-Instruct-hf"),
878
+ block_size=16384,
879
+ vocab_size=32000,
880
+ padding_multiple=64,
881
+ n_layer=48,
882
+ n_head=64,
883
+ n_embd=8192,
884
+ n_query_groups=8,
885
+ rotary_percentage=1.0,
886
+ parallel_residual=False,
887
+ bias=False,
888
+ _norm_class="RMSNorm",
889
+ norm_eps=1e-05,
890
+ _mlp_class="LLaMAMLP",
891
+ intermediate_size=22016,
892
+ rope_base=1000000,
893
+ ),
894
+ ]
895
+ configs.extend(code_llama)
896
+
897
+
898
+ ########################
899
+ # garage-bAInd Platypus
900
+ ########################
901
+ platypus = [
902
+ # https://huggingface.co/garage-bAInd/Platypus-30B/blob/main/config.json
903
+ dict(
904
+ name="Platypus-30B",
905
+ hf_config=dict(org="garage-bAInd", name="Platypus-30B"),
906
+ block_size=2048,
907
+ padded_vocab_size=32000,
908
+ n_layer=60,
909
+ n_head=52,
910
+ n_embd=6656,
911
+ rotary_percentage=1.0,
912
+ parallel_residual=False,
913
+ bias=False,
914
+ _norm_class="RMSNorm",
915
+ norm_eps=1e-06,
916
+ _mlp_class="LLaMAMLP",
917
+ intermediate_size=17920,
918
+ ),
919
+ # https://huggingface.co/garage-bAInd/Platypus2-7B/blob/main/config.json
920
+ dict(
921
+ name="Platypus2-7B",
922
+ hf_config=dict(org="garage-bAInd", name="Platypus2-7B"),
923
+ padded_vocab_size=32000,
924
+ n_layer=32,
925
+ rotary_percentage=1.0,
926
+ parallel_residual=False,
927
+ bias=False,
928
+ _norm_class="RMSNorm",
929
+ norm_eps=1e-05,
930
+ _mlp_class="LLaMAMLP",
931
+ intermediate_size=11008,
932
+ ),
933
+ # https://huggingface.co/garage-bAInd/Platypus2-13B/blob/main/config.json
934
+ dict(
935
+ name="Platypus2-13B",
936
+ hf_config=dict(org="garage-bAInd", name="Platypus2-13B"),
937
+ padded_vocab_size=32000,
938
+ n_layer=40,
939
+ n_head=40,
940
+ n_embd=5120,
941
+ rotary_percentage=1.0,
942
+ parallel_residual=False,
943
+ bias=False,
944
+ _norm_class="RMSNorm",
945
+ norm_eps=1e-05,
946
+ _mlp_class="LLaMAMLP",
947
+ intermediate_size=13824,
948
+ ),
949
+ # https://huggingface.co/garage-bAInd/Platypus2-70B/blob/main/config.json
950
+ dict(
951
+ name="Platypus2-70B",
952
+ hf_config=dict(org="garage-bAInd", name="Platypus2-70B"),
953
+ padded_vocab_size=32000,
954
+ n_layer=80,
955
+ n_head=64,
956
+ n_embd=8192,
957
+ rotary_percentage=1.0,
958
+ parallel_residual=False,
959
+ bias=False,
960
+ _norm_class="RMSNorm",
961
+ _mlp_class="LLaMAMLP",
962
+ intermediate_size=28672,
963
+ ),
964
+ # https://huggingface.co/garage-bAInd/Camel-Platypus2-13B/blob/main/config.json
965
+ dict(
966
+ name="Camel-Platypus2-13B",
967
+ hf_config=dict(org="garage-bAInd", name="Camel-Platypus2-13B"),
968
+ padded_vocab_size=32000,
969
+ n_layer=40,
970
+ n_head=40,
971
+ n_embd=5120,
972
+ rotary_percentage=1.0,
973
+ parallel_residual=False,
974
+ bias=False,
975
+ _norm_class="RMSNorm",
976
+ _mlp_class="LLaMAMLP",
977
+ intermediate_size=13824,
978
+ ),
979
+ # https://huggingface.co/garage-bAInd/Camel-Platypus2-70B/blob/main/config.json
980
+ dict(
981
+ name="Camel-Platypus2-70B",
982
+ hf_config=dict(org="garage-bAInd", name="Camel-Platypus2-70B"),
983
+ padded_vocab_size=32000,
984
+ n_layer=80,
985
+ n_head=64,
986
+ n_embd=8192,
987
+ n_query_groups=8,
988
+ rotary_percentage=1.0,
989
+ parallel_residual=False,
990
+ bias=False,
991
+ _norm_class="RMSNorm",
992
+ _mlp_class="LLaMAMLP",
993
+ intermediate_size=28672,
994
+ ),
995
+ # https://huggingface.co/garage-bAInd/Stable-Platypus2-13B/blob/main/config.json
996
+ dict(
997
+ name="Stable-Platypus2-13B",
998
+ hf_config=dict(org="garage-bAInd", name="Stable-Platypus2-13B"),
999
+ padded_vocab_size=32000,
1000
+ n_layer=40,
1001
+ n_head=40,
1002
+ n_embd=5120,
1003
+ rotary_percentage=1.0,
1004
+ parallel_residual=False,
1005
+ bias=False,
1006
+ _norm_class="RMSNorm",
1007
+ _mlp_class="LLaMAMLP",
1008
+ intermediate_size=13824,
1009
+ ),
1010
+ # https://huggingface.co/garage-bAInd/Platypus2-70B-instruct/blob/main/config.json
1011
+ dict(
1012
+ name="Platypus2-70B-instruct",
1013
+ hf_config=dict(org="garage-bAInd", name="Platypus2-70B-instruct"),
1014
+ padded_vocab_size=32000,
1015
+ n_layer=80,
1016
+ n_head=64,
1017
+ n_embd=8192,
1018
+ n_query_groups=8,
1019
+ rotary_percentage=1.0,
1020
+ parallel_residual=False,
1021
+ bias=False,
1022
+ _norm_class="RMSNorm",
1023
+ _mlp_class="LLaMAMLP",
1024
+ intermediate_size=28672,
1025
+ ),
1026
+ ]
1027
+ configs.extend(platypus)
1028
+
1029
+
1030
+ ##########################
1031
+ # Stability AI StableCode
1032
+ ##########################
1033
+ stablecode = [
1034
+ # https://huggingface.co/stabilityai/stablecode-completion-alpha-3b/blob/main/config.json
1035
+ dict(
1036
+ name="stablecode-completion-alpha-3b",
1037
+ hf_config=dict(org="stabilityai", name="stablecode-completion-alpha-3b"),
1038
+ block_size=16384,
1039
+ vocab_size=49152,
1040
+ n_layer=32,
1041
+ n_embd=2560,
1042
+ ),
1043
+ # https://huggingface.co/stabilityai/stablecode-completion-alpha-3b-4k/blob/main/config.json
1044
+ dict(
1045
+ name="stablecode-completion-alpha-3b-4k",
1046
+ hf_config=dict(org="stabilityai", name="stablecode-completion-alpha-3b-4k"),
1047
+ vocab_size=49152,
1048
+ n_layer=32,
1049
+ n_embd=2560,
1050
+ ),
1051
+ # https://huggingface.co/stabilityai/stablecode-instruct-alpha-3b/blob/main/config.json
1052
+ dict(
1053
+ name="stablecode-instruct-alpha-3b",
1054
+ hf_config=dict(org="stabilityai", name="stablecode-instruct-alpha-3b"),
1055
+ vocab_size=49152,
1056
+ n_layer=32,
1057
+ n_embd=2560,
1058
+ ),
1059
+ ]
1060
+ configs.extend(stablecode)
1061
+
1062
+
1063
+ ##################################
1064
+ # togethercomputer LLaMA-2-7B-32K
1065
+ ##################################
1066
+ together_llama2_32k = [
1067
+ # https://huggingface.co/togethercomputer/LLaMA-2-7B-32K/blob/main/config.json
1068
+ dict(
1069
+ name="LLaMA-2-7B-32K",
1070
+ hf_config=dict(org="togethercomputer", name="LLaMA-2-7B-32K"),
1071
+ vocab_size=32000,
1072
+ padding_multiple=64,
1073
+ n_layer=32,
1074
+ rotary_percentage=1.0,
1075
+ parallel_residual=False,
1076
+ bias=False,
1077
+ _norm_class="RMSNorm",
1078
+ _mlp_class="LLaMAMLP",
1079
+ intermediate_size=11008,
1080
+ rope_condense_ratio=8,
1081
+ )
1082
+ ]
1083
+ configs.extend(together_llama2_32k)
1084
+
1085
+
1086
+ ################
1087
+ # Microsoft Phi
1088
+ ################
1089
+ phi = [
1090
+ # https://huggingface.co/microsoft/phi-1_5/blob/main/config.json
1091
+ dict(
1092
+ name="phi-1_5",
1093
+ hf_config=dict(org="microsoft", name="phi-1_5"),
1094
+ vocab_size=50257,
1095
+ padded_vocab_size=51200,
1096
+ block_size=2048,
1097
+ n_embd=2048,
1098
+ n_layer=24,
1099
+ rotary_percentage=0.5, # 32 / (n_embd / n_head) = 32 / 64
1100
+ shared_attention_norm=True,
1101
+ lm_head_bias=True,
1102
+ gelu_approximate="tanh",
1103
+ )
1104
+ ]
1105
+ configs.extend(phi)
1106
+
1107
+
1108
+ #############
1109
+ # Mistral AI
1110
+ #############
1111
+ mistral = [
1112
+ # https://huggingface.co/mistralai/Mistral-7B-v0.1/blob/main/config.json
1113
+ dict(
1114
+ name="Mistral-7B-{}v0.1",
1115
+ hf_config=dict(org="mistralai", name="Mistral-7B-{}v0.1"),
1116
+ padded_vocab_size=32000,
1117
+ block_size=4096, # should be 32768 but sliding window attention is not implemented
1118
+ n_layer=32,
1119
+ n_query_groups=8,
1120
+ rotary_percentage=1.0,
1121
+ parallel_residual=False,
1122
+ bias=False,
1123
+ _norm_class="RMSNorm",
1124
+ norm_eps=1e-05,
1125
+ _mlp_class="LLaMAMLP",
1126
+ intermediate_size=14336,
1127
+ )
1128
+ ]
1129
+ for c in mistral:
1130
+ for kind in ("", "Instruct-"):
1131
+ copy = c.copy()
1132
+ copy["name"] = c["name"].format(kind)
1133
+ copy["hf_config"]["name"] = c["hf_config"]["name"].format(kind)
1134
+ configs.append(copy)
1135
+
1136
+
1137
+ ############
1138
+ # TinyLlama
1139
+ ############
1140
+ tiny_llama = [
1141
+ dict(
1142
+ name="tiny-llama-1.1b",
1143
+ hf_config=dict(org="PY007", name="TinyLlama-1.1B-intermediate-step-480k-1T"),
1144
+ block_size=2048,
1145
+ vocab_size=32000,
1146
+ padding_multiple=64,
1147
+ n_layer=22,
1148
+ n_head=32,
1149
+ n_embd=2048,
1150
+ rotary_percentage=1.0,
1151
+ parallel_residual=False,
1152
+ bias=False,
1153
+ _norm_class="RMSNorm", # original TinyLlama uses FusedRMSNorm
1154
+ norm_eps=1e-5,
1155
+ _mlp_class="LLaMAMLP",
1156
+ intermediate_size=5632,
1157
+ n_query_groups=4,
1158
+ ),
1159
+ dict(
1160
+ name="tiny-llama-new",
1161
+ hf_config=dict(org="PY007", name="TinyLlama-1.1B-intermediate-step-480k-1T"),
1162
+ block_size=768,
1163
+ vocab_size=32000,
1164
+ padding_multiple=64,
1165
+ n_layer=18,
1166
+ n_head=32,
1167
+ n_embd=1024,
1168
+ rotary_percentage=1.0,
1169
+ parallel_residual=False,
1170
+ bias=False,
1171
+ _norm_class="RMSNorm", # original TinyLlama uses FusedRMSNorm
1172
+ norm_eps=1e-5,
1173
+ _mlp_class="LLaMAMLP",
1174
+ intermediate_size=5632,
1175
+ n_query_groups=4,
1176
+ ),
1177
+ ]
1178
+ configs.extend(tiny_llama)
1179
+
1180
+
1181
+ name_to_config = {config["name"]: config for config in configs}
tsai_gpt/model.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full definition of a GPT NeoX Language Model, all of it in this single file.
2
+
3
+ Based on the nanoGPT implementation: https://github.com/karpathy/nanoGPT and
4
+ https://github.com/EleutherAI/gpt-neox/tree/main/megatron/model.
5
+ """
6
+ import math
7
+ from typing import Any, Optional, Tuple
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from typing_extensions import Self
12
+
13
+ from tsai_gpt.config import Config
14
+ from torch.nn import functional as F
15
+
16
+
17
+ class GPT(nn.Module):
18
+ def __init__(self, config: Config) -> None:
19
+ super().__init__()
20
+ assert config.padded_vocab_size is not None
21
+ self.config = config
22
+
23
+ self.lm_head = nn.Linear(config.n_embd, config.padded_vocab_size, bias=config.lm_head_bias)
24
+ self.transformer = nn.ModuleDict(
25
+ dict(
26
+ wte=nn.Embedding(config.padded_vocab_size, config.n_embd),
27
+ h=nn.ModuleList(Block(config) for _ in range(config.n_layer)),
28
+ ln_f=config.norm_class(config.n_embd, eps=config.norm_eps),
29
+ )
30
+ )
31
+ self.max_seq_length = self.config.block_size
32
+ self.mask_cache: Optional[torch.Tensor] = None
33
+
34
+ @property
35
+ def max_seq_length(self) -> int:
36
+ return self._max_seq_length
37
+
38
+ @max_seq_length.setter
39
+ def max_seq_length(self, value: int) -> None:
40
+ """
41
+ When doing inference, the sequences used might be shorter than the model's context length.
42
+ This allows setting a smaller number to avoid allocating unused memory
43
+ """
44
+ if value > self.config.block_size:
45
+ raise ValueError(f"Cannot attend to {value}, block size is only {self.config.block_size}")
46
+ self._max_seq_length = value
47
+ if not hasattr(self, "cos"):
48
+ # first call
49
+ cos, sin = self.rope_cache()
50
+ self.register_buffer("cos", cos, persistent=False)
51
+ self.register_buffer("sin", sin, persistent=False)
52
+ elif value != self.cos.size(0):
53
+ # override
54
+ self.cos, self.sin = self.rope_cache(device=self.cos.device)
55
+ # the mask and kv cache size will get updated on `set_kv_cache`. we cannot update it here because we don't know
56
+ # if the kv cache is expected
57
+
58
+ def reset_parameters(self) -> None:
59
+ # Trigger resetting the rope-cache
60
+ self.max_seq_length = self.config.block_size
61
+
62
+ def _init_weights(self, module: nn.Module) -> None:
63
+ """Meant to be used with `gpt.apply(gpt._init_weights)`."""
64
+ if isinstance(module, nn.Linear):
65
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
66
+ if module.bias is not None:
67
+ torch.nn.init.zeros_(module.bias)
68
+ elif isinstance(module, nn.Embedding):
69
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
70
+
71
+ def forward(self, idx: torch.Tensor, input_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
72
+ T = idx.size(1)
73
+ if self.max_seq_length < T:
74
+ raise ValueError(f"Cannot forward sequence of length {T}, max seq length is only {self.max_seq_length}.")
75
+
76
+ if input_pos is not None: # use the kv cache
77
+ cos = self.cos.index_select(0, input_pos)
78
+ sin = self.sin.index_select(0, input_pos)
79
+ if self.mask_cache is None:
80
+ raise TypeError("You need to call `gpt.set_kv_cache()`")
81
+ mask = self.mask_cache.index_select(2, input_pos)
82
+ else:
83
+ cos = self.cos[:T]
84
+ sin = self.sin[:T]
85
+ mask = None
86
+
87
+ x = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
88
+ for block in self.transformer.h:
89
+ x = block(x, cos, sin, mask, input_pos)
90
+ x = self.transformer.ln_f(x)
91
+ return self.lm_head(x) # (b, t, vocab_size)
92
+
93
+ @classmethod
94
+ def from_name(cls, name: str, **kwargs: Any) -> Self:
95
+ return cls(Config.from_name(name, **kwargs))
96
+
97
+ def rope_cache(self, device: Optional[torch.device] = None) -> Tuple[torch.Tensor, torch.Tensor]:
98
+ return build_rope_cache(
99
+ seq_len=self.max_seq_length,
100
+ n_elem=self.config.rope_n_elem,
101
+ device=device,
102
+ condense_ratio=self.config.rope_condense_ratio,
103
+ base=self.config.rope_base,
104
+ )
105
+
106
+ def set_kv_cache(
107
+ self,
108
+ batch_size: int,
109
+ rope_cache_length: Optional[int] = None,
110
+ device: Optional[torch.device] = None,
111
+ dtype: Optional[torch.dtype] = None,
112
+ ) -> None:
113
+ if rope_cache_length is None:
114
+ rope_cache_length = self.cos.size(-1)
115
+ max_seq_length = self.max_seq_length
116
+
117
+ # initialize the kv cache for all blocks
118
+ for block in self.transformer.h:
119
+ block.attn.kv_cache = block.attn.build_kv_cache(
120
+ batch_size, max_seq_length, rope_cache_length, device, dtype
121
+ )
122
+
123
+ if self.mask_cache is None or self.mask_cache.size(3) != max_seq_length:
124
+ # passing `attn_mask` to SDPA downgrades it to use the inefficient implementation. since we only need the mask
125
+ # for the kv-cache support (only during inference), we only create it in that situation
126
+ # this will be resolved by https://github.com/pytorch/pytorch/issues/96099
127
+ ones = torch.ones((max_seq_length, max_seq_length), device=device, dtype=torch.bool)
128
+ self.mask_cache = torch.tril(ones).unsqueeze(0).unsqueeze(0)
129
+
130
+ def clear_kv_cache(self) -> None:
131
+ self.mask_cache = None
132
+ for block in self.transformer.h:
133
+ block.attn.kv_cache = None
134
+
135
+
136
+ @torch.no_grad()
137
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
138
+ """
139
+ Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
140
+ the sequence max_new_tokens times, feeding the predictions back into the model each time.
141
+ Most likely you'll want to make sure to be in model.eval() mode of operation for this.
142
+ """
143
+ for _ in range(max_new_tokens):
144
+ # if the sequence context is growing too long we must crop it at block_size
145
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
146
+ # forward the model to get the logits for the index in the sequence
147
+ logits = self(idx_cond)
148
+ # pluck the logits at the final step and scale by desired temperature
149
+ logits = logits[:, -1, :] / temperature
150
+ # optionally crop the logits to only the top k options
151
+ if top_k is not None:
152
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
153
+ logits[logits < v[:, [-1]]] = -float('Inf')
154
+ # apply softmax to convert logits to (normalized) probabilities
155
+ probs = F.softmax(logits, dim=-1)
156
+ # sample from the distribution
157
+ idx_next = torch.multinomial(probs, num_samples=1)
158
+ # append sampled index to the running sequence and continue
159
+ idx = torch.cat((idx, idx_next), dim=1)
160
+
161
+ return idx
162
+
163
+
164
+ class Block(nn.Module):
165
+ def __init__(self, config: Config) -> None:
166
+ super().__init__()
167
+ self.norm_1 = config.norm_class(config.n_embd, eps=config.norm_eps)
168
+ self.attn = CausalSelfAttention(config)
169
+ self.norm_2 = None if config.shared_attention_norm else config.norm_class(config.n_embd, eps=config.norm_eps)
170
+ self.mlp = config.mlp_class(config)
171
+
172
+ self.config = config
173
+
174
+ def forward(
175
+ self,
176
+ x: torch.Tensor,
177
+ cos: torch.Tensor,
178
+ sin: torch.Tensor,
179
+ mask: Optional[torch.Tensor] = None,
180
+ input_pos: Optional[torch.Tensor] = None,
181
+ ) -> torch.Tensor:
182
+ n_1 = self.norm_1(x)
183
+ h = self.attn(n_1, cos, sin, mask, input_pos)
184
+ if self.config.parallel_residual:
185
+ n_2 = n_1 if self.config.shared_attention_norm else self.norm_2(x)
186
+ x = self.mlp(n_2) + h + x
187
+ else:
188
+ if self.config.shared_attention_norm:
189
+ raise NotImplementedError(
190
+ "No checkpoint amongst the ones we support uses this configuration"
191
+ " (non-parallel residual and shared attention norm)."
192
+ )
193
+ x = h + x
194
+ x = self.mlp(self.norm_2(x)) + x
195
+ return x
196
+
197
+
198
+ class CausalSelfAttention(nn.Module):
199
+ def __init__(self, config: Config) -> None:
200
+ super().__init__()
201
+ shape = (config.n_head + 2 * config.n_query_groups) * config.head_size
202
+ # key, query, value projections for all heads, but in a batch
203
+ self.attn = nn.Linear(config.n_embd, shape, bias=config.bias)
204
+ # output projection
205
+ self.proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
206
+ # disabled by default
207
+ self.kv_cache: Optional[KVCache] = None
208
+
209
+ self.config = config
210
+
211
+ def forward(
212
+ self,
213
+ x: torch.Tensor,
214
+ cos: torch.Tensor,
215
+ sin: torch.Tensor,
216
+ mask: Optional[torch.Tensor] = None,
217
+ input_pos: Optional[torch.Tensor] = None,
218
+ ) -> torch.Tensor:
219
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
220
+
221
+ qkv = self.attn(x)
222
+
223
+ # assemble into a number of query groups to support MHA, MQA and GQA together (see `config.n_query_groups`)
224
+ q_per_kv = self.config.n_head // self.config.n_query_groups
225
+ total_qkv = q_per_kv + 2 # each group has 1+ queries, 1 key, and 1 value
226
+ qkv = qkv.view(B, T, self.config.n_query_groups, total_qkv, self.config.head_size)
227
+ qkv = qkv.permute(0, 2, 3, 1, 4) # (B, n_query_groups, total_qkv, T, hs)
228
+
229
+ # split batched computation into three
230
+ q, k, v = qkv.split((q_per_kv, 1, 1), dim=2)
231
+
232
+ # maybe repeat k and v if for the non multi-head attention cases
233
+ # training: flash attention requires it
234
+ # inference: multi-query would require a full kv cache so avoid it to limit its memory usage
235
+ if self.config.n_query_groups != self.config.n_head and (input_pos is None or self.config.n_query_groups != 1):
236
+ k = k.expand(B, self.config.n_query_groups, q_per_kv, T, self.config.head_size)
237
+ v = v.expand(B, self.config.n_query_groups, q_per_kv, T, self.config.head_size)
238
+
239
+ q = q.reshape(B, -1, T, self.config.head_size) # (B, nh_q, T, hs)
240
+ k = k.reshape(B, -1, T, self.config.head_size) # (B, nh_k, T, hs)
241
+ v = v.reshape(B, -1, T, self.config.head_size) # (B, nh_v, T, hs)
242
+
243
+ q_roped = apply_rope(q[..., : self.config.rope_n_elem], cos, sin)
244
+ k_roped = apply_rope(k[..., : self.config.rope_n_elem], cos, sin)
245
+ q = torch.cat((q_roped, q[..., self.config.rope_n_elem :]), dim=-1)
246
+ k = torch.cat((k_roped, k[..., self.config.rope_n_elem :]), dim=-1)
247
+
248
+ if input_pos is not None:
249
+ if not isinstance(self.kv_cache, KVCache):
250
+ raise TypeError("You need to call `gpt.set_kv_cache()`")
251
+ k, v = self.kv_cache(input_pos, k, v)
252
+
253
+ y = self.scaled_dot_product_attention(q, k, v, mask)
254
+
255
+ y = y.reshape(B, T, C) # re-assemble all head outputs side by side
256
+
257
+ # output projection
258
+ return self.proj(y)
259
+
260
+ def scaled_dot_product_attention(
261
+ self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: Optional[torch.Tensor] = None
262
+ ) -> torch.Tensor:
263
+ scale = 1.0 / math.sqrt(self.config.head_size)
264
+ y = torch.nn.functional.scaled_dot_product_attention(
265
+ q, k, v, attn_mask=mask, dropout_p=0.0, scale=scale, is_causal=mask is None
266
+ )
267
+ return y.transpose(1, 2)
268
+
269
+ def build_kv_cache(
270
+ self,
271
+ batch_size: int,
272
+ max_seq_length: int,
273
+ rope_cache_length: Optional[int] = None,
274
+ device: Optional[torch.device] = None,
275
+ dtype: Optional[torch.dtype] = None,
276
+ ) -> "KVCache":
277
+ heads = 1 if self.config.n_query_groups == 1 else self.config.n_head
278
+ v_shape = (batch_size, heads, max_seq_length, self.config.head_size)
279
+ if rope_cache_length is None:
280
+ if self.config.rotary_percentage != 1.0:
281
+ raise TypeError("Please pass the `rope_cache_length=gpt.cos.size(-1)` value")
282
+ k_shape = v_shape
283
+ else:
284
+ k_shape = (
285
+ batch_size,
286
+ heads,
287
+ max_seq_length,
288
+ rope_cache_length + self.config.head_size - self.config.rope_n_elem,
289
+ )
290
+ return KVCache(k_shape, v_shape, device=device, dtype=dtype)
291
+
292
+
293
+ class GptNeoxMLP(nn.Module):
294
+ def __init__(self, config: Config) -> None:
295
+ super().__init__()
296
+ self.fc = nn.Linear(config.n_embd, config.intermediate_size, bias=config.bias)
297
+ self.proj = nn.Linear(config.intermediate_size, config.n_embd, bias=config.bias)
298
+
299
+ self.config = config
300
+
301
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
302
+ x = self.fc(x)
303
+ x = torch.nn.functional.gelu(x, approximate=self.config.gelu_approximate)
304
+ return self.proj(x)
305
+
306
+
307
+ class LLaMAMLP(nn.Module):
308
+ def __init__(self, config: Config) -> None:
309
+ super().__init__()
310
+ self.fc_1 = nn.Linear(config.n_embd, config.intermediate_size, bias=config.bias)
311
+ self.fc_2 = nn.Linear(config.n_embd, config.intermediate_size, bias=config.bias)
312
+ self.proj = nn.Linear(config.intermediate_size, config.n_embd, bias=config.bias)
313
+
314
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
315
+ x_fc_1 = self.fc_1(x)
316
+ x_fc_2 = self.fc_2(x)
317
+ x = torch.nn.functional.silu(x_fc_1) * x_fc_2
318
+ return self.proj(x)
319
+
320
+
321
+ def build_rope_cache(
322
+ seq_len: int, n_elem: int, device: Optional[torch.device] = None, base: int = 10000, condense_ratio: int = 1
323
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
324
+ """Enhanced Transformer with Rotary Position Embedding.
325
+
326
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
327
+ transformers/rope/__init__.py. MIT License:
328
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
329
+ """
330
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
331
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, device=device).float() / n_elem))
332
+
333
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
334
+ seq_idx = torch.arange(seq_len, device=device) / condense_ratio
335
+
336
+ # Calculate the product of position index and $\theta_i$
337
+ idx_theta = torch.outer(seq_idx, theta).repeat(1, 2)
338
+
339
+ return torch.cos(idx_theta), torch.sin(idx_theta)
340
+
341
+
342
+ def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
343
+ head_size = x.size(-1)
344
+ x1 = x[..., : head_size // 2] # (B, nh, T, hs/2)
345
+ x2 = x[..., head_size // 2 :] # (B, nh, T, hs/2)
346
+ rotated = torch.cat((-x2, x1), dim=-1) # (B, nh, T, hs)
347
+ roped = (x * cos) + (rotated * sin)
348
+ return roped.type_as(x)
349
+
350
+
351
+ class KVCache(nn.Module):
352
+ def __init__(
353
+ self,
354
+ k_shape: Tuple[int, int, int, int],
355
+ v_shape: Tuple[int, int, int, int],
356
+ device: Optional[torch.device] = None,
357
+ dtype: Optional[torch.dtype] = None,
358
+ ) -> None:
359
+ super().__init__()
360
+ self.register_buffer("k", torch.zeros(k_shape, device=device, dtype=dtype), persistent=False)
361
+ self.register_buffer("v", torch.zeros(v_shape, device=device, dtype=dtype), persistent=False)
362
+
363
+ def forward(self, input_pos: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
364
+ # move the buffer to the activation dtype for when AMP is used
365
+ self.k = self.k.to(k.dtype)
366
+ self.v = self.v.to(v.dtype)
367
+ # update the cache
368
+ k = self.k.index_copy_(2, input_pos, k)
369
+ v = self.v.index_copy_(2, input_pos, v)
370
+ return k, v
tsai_gpt/packed_dataset.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Very loosely inspired by indexed_dataset in Fairseq, Megatron
2
+ # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/data/indexed_dataset.py
3
+
4
+
5
+ import os
6
+ import random
7
+ import struct
8
+
9
+ import numpy as np
10
+ import torch
11
+ from torch.utils.data import IterableDataset, get_worker_info
12
+
13
+ dtypes = {1: np.uint8, 2: np.int8, 3: np.int16, 4: np.int32, 5: np.int64, 6: np.float32, 7: np.float64, 8: np.uint16}
14
+
15
+
16
+ def code(dtype):
17
+ for k in dtypes:
18
+ if dtypes[k] == dtype:
19
+ return k
20
+ raise ValueError(dtype)
21
+
22
+
23
+ HDR_MAGIC = b"LITPKDS"
24
+ HDR_SIZE = 24 # bytes
25
+
26
+
27
+ class PackedDataset(IterableDataset):
28
+ def __init__(
29
+ self, filenames, n_chunks, block_size, seed=12345, shuffle=True, wrap=False, num_processes=1, process_rank=0
30
+ ):
31
+ self._filenames = filenames
32
+ self._n_chunks = n_chunks
33
+ self._block_size = block_size
34
+ self._seed = seed
35
+ self._shuffle = shuffle
36
+ self._wrap = wrap
37
+ self._num_processes = num_processes
38
+ self._process_rank = process_rank
39
+
40
+ def __iter__(self):
41
+ worker_info = get_worker_info()
42
+ num_workers = worker_info.num_workers if worker_info is not None else 1
43
+ worker_id = worker_info.id if worker_info is not None else 0
44
+ num_shards = num_workers * self._num_processes
45
+ shard_id = self._process_rank * num_workers + worker_id
46
+
47
+ max_num_files = len(self._filenames) // num_shards * num_shards
48
+ filenames = self._filenames[shard_id:max_num_files:num_shards]
49
+
50
+ return PackedDatasetIterator(
51
+ filenames=filenames,
52
+ n_chunks=self._n_chunks,
53
+ block_size=self._block_size,
54
+ seed=self._seed,
55
+ shuffle=self._shuffle,
56
+ wrap=self._wrap,
57
+ )
58
+
59
+
60
+ class PackedDatasetBuilder(object):
61
+ def __init__(self, outdir, prefix, chunk_size, sep_token, dtype="auto", vocab_size=None):
62
+ if dtype == "auto":
63
+ if vocab_size is None:
64
+ raise ValueError("vocab_size cannot be None when dtype='auto'")
65
+ if vocab_size is not None and vocab_size < 65500:
66
+ self._dtype = np.uint16
67
+ else:
68
+ self._dtype = np.int32
69
+ else:
70
+ self._dtype = dtype
71
+ self._counter = 0
72
+ self._chunk_size = chunk_size
73
+ self._outdir = outdir
74
+ self._prefix = prefix
75
+ self._sep_token = sep_token
76
+ self._arr = np.zeros(self._chunk_size, dtype=self._dtype)
77
+ self._arr.fill(self._sep_token)
78
+ self._idx = 0
79
+ self._version = 1
80
+ self._filenames = []
81
+
82
+ def _write_chunk(self):
83
+ filename = f"{self._prefix}_{self._counter:010d}.bin"
84
+ filename = os.path.join(self._outdir, filename)
85
+
86
+ with open(filename, "wb") as f:
87
+ f.write(HDR_MAGIC)
88
+ f.write(struct.pack("<Q", self._version))
89
+ f.write(struct.pack("<B", code(self._dtype)))
90
+ f.write(struct.pack("<Q", self._chunk_size))
91
+ f.write(self._arr.tobytes(order="C"))
92
+
93
+ self._filenames.append(filename)
94
+ self._counter += 1
95
+ self._arr.fill(self._sep_token)
96
+ self._idx = 0
97
+
98
+ @property
99
+ def dtype(self):
100
+ return self._dtype
101
+
102
+ @property
103
+ def filenames(self):
104
+ return self._filenames.copy()
105
+
106
+ def add_array(self, arr):
107
+ while self._idx + arr.shape[0] > self._chunk_size:
108
+ part_len = self._chunk_size - self._idx
109
+ self._arr[self._idx : self._idx + part_len] = arr[:part_len]
110
+ self._write_chunk()
111
+ arr = arr[part_len:]
112
+
113
+ arr_len = arr.shape[0]
114
+ self._arr[self._idx : self._idx + arr_len] = arr
115
+ self._idx += arr_len
116
+
117
+ def write_reminder(self):
118
+ self._write_chunk()
119
+
120
+
121
+ class PackedDatasetIterator:
122
+ def __init__(self, filenames, n_chunks, block_size, seed, shuffle, wrap):
123
+ self._seed = seed
124
+ self._shuffle = shuffle
125
+ self._rng = np.random.default_rng(seed) if shuffle else None
126
+ self._block_idxs = None
127
+
128
+ self._wrap = wrap
129
+
130
+ # TODO: instead of filenames, we could have a single text stream
131
+ # (or text file) with the sequence of all files to be
132
+ # fetched/loaded.
133
+ self._filenames = filenames
134
+ self._file_idx = 0
135
+
136
+ self._n_chunks = n_chunks
137
+
138
+ self._dtype = None
139
+ self._block_size = block_size
140
+ self._n_blocks = None
141
+
142
+ self._mmaps = []
143
+ self._buffers = []
144
+
145
+ self._block_idxs = []
146
+ self._curr_idx = 0
147
+
148
+ self._load_n_chunks()
149
+
150
+ def _read_header(self, path):
151
+ with open(path, "rb") as f:
152
+ magic = f.read(len(HDR_MAGIC))
153
+ assert magic == HDR_MAGIC, "File doesn't match expected format."
154
+ version = struct.unpack("<Q", f.read(8))
155
+ assert version == (1,)
156
+ (dtype_code,) = struct.unpack("<B", f.read(1))
157
+ dtype = dtypes[dtype_code]
158
+ (chunk_size,) = struct.unpack("<Q", f.read(8))
159
+ return dtype, chunk_size
160
+
161
+ def _close_mmaps(self):
162
+ for mmap in self._mmaps:
163
+ mmap._mmap.close()
164
+
165
+ def _load_n_chunks(self):
166
+ self._close_mmaps()
167
+ self._mmaps = []
168
+ self._buffers = []
169
+
170
+ if self._n_chunks > len(self._filenames[self._file_idx :]):
171
+ if not self._wrap:
172
+ raise StopIteration
173
+ self._file_idx = 0
174
+
175
+ for i in range(self._n_chunks):
176
+ filename = self._filenames[self._file_idx + i]
177
+ if self._dtype is None:
178
+ self._dtype, self._chunk_size = self._read_header(filename)
179
+ self._n_blocks = self._chunk_size // self._block_size
180
+ # TODO: check header matches with previous files
181
+ mmap = np.memmap(filename, mode="r", order="C", offset=HDR_SIZE)
182
+ self._mmaps.append(mmap)
183
+ self._buffers.append(memoryview(mmap))
184
+
185
+ self._file_idx += self._n_chunks
186
+ n_all_blocks = self._n_chunks * self._n_blocks
187
+
188
+ self._block_idxs = self._rng.permutation(n_all_blocks) if self._shuffle else range(n_all_blocks)
189
+
190
+ self._curr_idx = 0
191
+
192
+ def __del__(self):
193
+ self._close_mmaps()
194
+ del self._mmaps
195
+ del self._buffers
196
+
197
+ def __iter__(self):
198
+ return self
199
+
200
+ def __next__(self):
201
+ if self._curr_idx >= len(self._block_idxs):
202
+ self._load_n_chunks()
203
+ # TODO: trigger fetching next next n_chunks if remote
204
+ block_idx = self._block_idxs[self._curr_idx]
205
+ chunk_id = block_idx // self._n_blocks
206
+ buffer = self._buffers[chunk_id]
207
+ elem_id = (block_idx % self._n_blocks) * self._block_size
208
+ offset = np.dtype(self._dtype).itemsize * elem_id
209
+ arr = np.frombuffer(buffer, dtype=self._dtype, count=self._block_size, offset=offset)
210
+ self._curr_idx += 1
211
+ return torch.from_numpy(arr.astype(np.int64))
212
+
213
+
214
+ class CombinedDataset(IterableDataset):
215
+ def __init__(self, datasets, seed, weights=None):
216
+ self._seed = seed
217
+ self._datasets = datasets
218
+ self._weights = weights
219
+ n_datasets = len(datasets)
220
+ if weights is None:
221
+ self._weights = [1 / n_datasets] * n_datasets
222
+
223
+ def __iter__(self):
224
+ return CombinedDatasetIterator(self._datasets, self._seed, self._weights)
225
+
226
+
227
+ class CombinedDatasetIterator:
228
+ def __init__(self, datasets, seed, weights):
229
+ self._datasets = [iter(el) for el in datasets]
230
+ self._weights = weights
231
+ self._rng = random.Random(seed)
232
+
233
+ def __next__(self):
234
+ (dataset,) = self._rng.choices(self._datasets, weights=self._weights, k=1)
235
+ return next(dataset)
tsai_gpt/rmsnorm.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ class RMSNorm(torch.nn.Module):
5
+ """Root Mean Square Layer Normalization.
6
+
7
+ Derived from https://github.com/bzhangGo/rmsnorm/blob/master/rmsnorm_torch.py. BSD 3-Clause License:
8
+ https://github.com/bzhangGo/rmsnorm/blob/master/LICENSE.
9
+ """
10
+
11
+ def __init__(self, size: int, dim: int = -1, eps: float = 1e-5) -> None:
12
+ super().__init__()
13
+ self.weight = torch.nn.Parameter(torch.ones(size))
14
+ self.eps = eps
15
+ self.dim = dim
16
+
17
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
18
+ dtype = x.dtype
19
+ x = x.float()
20
+ # NOTE: the original RMSNorm paper implementation is not equivalent
21
+ norm_x = torch.mean(x * x, dim=self.dim, keepdim=True)
22
+ x_normed = x * torch.rsqrt(norm_x + self.eps)
23
+ return (self.weight * x_normed).to(dtype=dtype)
24
+
25
+ def reset_parameters(self) -> None:
26
+ torch.nn.init.ones_(self.weight)
tsai_gpt/speed_monitor.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from collections import deque
3
+ from contextlib import nullcontext
4
+ from typing import Any, Callable, Deque, Dict, Optional
5
+
6
+ import torch
7
+ from lightning import Callback, Fabric, LightningModule, Trainer
8
+ from lightning.fabric.accelerators.xla import _XLA_GREATER_EQUAL_2_1
9
+ from lightning.fabric.plugins import (
10
+ BitsandbytesPrecision,
11
+ DoublePrecision,
12
+ FSDPPrecision,
13
+ HalfPrecision,
14
+ MixedPrecision,
15
+ Precision,
16
+ TransformerEnginePrecision,
17
+ XLAPrecision,
18
+ )
19
+ from lightning.fabric.utilities.rank_zero import rank_zero_only as fabric_rank_zero_only
20
+ from lightning.pytorch.plugins import (
21
+ DoublePrecisionPlugin,
22
+ FSDPPrecisionPlugin,
23
+ HalfPrecisionPlugin,
24
+ MixedPrecisionPlugin,
25
+ XLAPrecisionPlugin,
26
+ )
27
+ from lightning.pytorch.utilities.rank_zero import rank_zero_only as trainer_rank_zero_only
28
+ from torch.utils.flop_counter import FlopCounterMode
29
+
30
+ from tsai_gpt import GPT
31
+ from tsai_gpt.utils import num_parameters
32
+
33
+ GPU_AVAILABLE_FLOPS = {
34
+ # source: https://resources.nvidia.com/en-us-tensor-core/nvidia-tensor-core-gpu-datasheet
35
+ # nvidia publishes spec sheet with a 2x sparsity factor
36
+ "h100-sxm": {
37
+ torch.float64: 67e12,
38
+ torch.float32: 67e12,
39
+ torch.bfloat16: 1.979e15 / 2,
40
+ torch.float16: 1.979e15 / 2,
41
+ torch.int8: 3.958e15 / 2,
42
+ },
43
+ "h100-pcie": {
44
+ torch.float64: 51e12,
45
+ torch.float32: 51e12,
46
+ torch.bfloat16: 1.513e15 / 2,
47
+ torch.float16: 1.513e15 / 2,
48
+ torch.int8: 3.026e15 / 2,
49
+ },
50
+ # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf
51
+ # sxm and pcie have same flop counts
52
+ "a100": {torch.float64: 19.5e12, torch.float32: 19.5e12, torch.bfloat16: 312e12, torch.float16: 312e12},
53
+ # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a10/pdf/a10-datasheet.pdf
54
+ "a10g": {torch.float32: 31.2e12, torch.bfloat16: 125e12, torch.float16: 125e12},
55
+ # source: https://images.nvidia.com/content/technologies/volta/pdf/volta-v100-datasheet-update-us-1165301-r5.pdf
56
+ "v100-sxm": {torch.float64: 7.8e12, torch.float32: 15.7e12, torch.float16: 125e12},
57
+ "v100-pcie": {torch.float64: 7e12, torch.float32: 14e12, torch.float16: 112e12},
58
+ "v100s-pcie": {torch.float64: 8.2e12, torch.float32: 16.4e12, torch.float16: 130e12},
59
+ # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/tesla-t4/t4-tensor-core-datasheet-951643.pdf
60
+ # sxm and pcie have same flop counts
61
+ "t4": {torch.float32: 8.1e12, torch.float16: 65e12, torch.int8: 130e12},
62
+ # https://www.nvidia.com/content/dam/en-zz/Solutions/design-visualization/quadro-product-literature/quadro-rtx-5000-data-sheet-us-nvidia-704120-r4-web.pdf
63
+ "quadro rtx 5000": {torch.float32: 11.2e12, torch.float16: 89.2e12},
64
+ }
65
+
66
+ TPU_AVAILABLE_FLOPS = {
67
+ # flop count for each TPU generation is the same for all precisions
68
+ # since bfloat16 precision is always used for performing matrix operations
69
+ # for more info: https://cloud.google.com/tpu/docs/bfloat16#choosing_bfloat16
70
+ # source: https://arxiv.org/pdf/1907.10701.pdf
71
+ "v2": 45e12,
72
+ # source: https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#tpu_v3
73
+ "v3": 123e12,
74
+ # source: https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#tpu_v4
75
+ "v4": 275e12,
76
+ # source: https://cloud.google.com/tpu/docs/v5e-training
77
+ "v5litepod": 197e12,
78
+ }
79
+
80
+
81
+ def get_flops_available(device: torch.device, dtype: torch.dtype) -> Optional[float]:
82
+ if device.type == "cuda":
83
+ device_name = torch.cuda.get_device_name(device).lower()
84
+ if "h100" in device_name and "hbm3" in device_name:
85
+ device_name = "h100-sxm"
86
+ elif "h100" in device_name and ("pcie" in device_name or "hbm2e" in device_name):
87
+ device_name = "h100-pcie"
88
+ elif "a100" in device_name:
89
+ device_name = "a100"
90
+ elif "a10g" in device_name:
91
+ device_name = "a10g"
92
+ elif "v100-sxm" in device_name:
93
+ device_name = "v100-sxm"
94
+ elif "v100-pcie" in device_name:
95
+ device_name = "v100-pcie"
96
+ elif "t4" in device_name:
97
+ device_name = "t4"
98
+ elif "quadro rtx 5000" in device_name:
99
+ device_name = "quadro rtx 5000"
100
+ else:
101
+ device_name = None
102
+
103
+ if device_name is not None:
104
+ try:
105
+ return int(GPU_AVAILABLE_FLOPS[device_name][dtype])
106
+ except KeyError:
107
+ raise KeyError(
108
+ f"flop count not found for {device_name} with dtype: {dtype}; "
109
+ "MFU cannot be calculated and reported."
110
+ )
111
+ elif device.type == "xla":
112
+ if _XLA_GREATER_EQUAL_2_1:
113
+ from torch_xla._internal import tpu
114
+ else:
115
+ from torch_xla.experimental import tpu
116
+
117
+ device_name = tpu.get_tpu_env()["TYPE"].lower()
118
+ try:
119
+ return int(TPU_AVAILABLE_FLOPS[device_name])
120
+ except KeyError:
121
+ raise KeyError(
122
+ f"flop count not found for {device_name} with dtype: {dtype}; MFU cannot be calculated and reported."
123
+ )
124
+
125
+ return None
126
+
127
+
128
+ # Adapted from https://github.com/mosaicml/composer/blob/f2a2dc820cb75023b9eb7c46fdfd25273712abd0/composer/callbacks/speed_monitor.py
129
+
130
+
131
+ class SpeedMonitorBase:
132
+ """Logs the training throughput and utilization.
133
+
134
+ +-------------------------------------+-----------------------------------------------------------+
135
+ | Key | Logged data |
136
+ +=====================================+===========================================================+
137
+ | | Rolling average (over `window_size` most recent |
138
+ | `throughput/batches_per_sec` | batches) of the number of batches processed per second |
139
+ | | |
140
+ +-------------------------------------+-----------------------------------------------------------+
141
+ | | Rolling average (over `window_size` most recent |
142
+ | `throughput/samples_per_sec` | batches) of the number of samples processed per second |
143
+ | | |
144
+ +-------------------------------------+-----------------------------------------------------------+
145
+ | | Rolling average (over `window_size` most recent |
146
+ | `throughput/tokens_per_sec` | batches) of the number of tokens processed per second. |
147
+ | | This may include padding depending on dataset |
148
+ +-------------------------------------+-----------------------------------------------------------+
149
+ | | Estimates flops by `flops_per_batch * batches_per_sec` |
150
+ | `throughput/flops_per_sec` | |
151
+ | | |
152
+ +-------------------------------------+-----------------------------------------------------------+
153
+ | `throughput/device/batches_per_sec` | `throughput/batches_per_sec` divided by world size |
154
+ +-------------------------------------+-----------------------------------------------------------+
155
+ | `throughput/device/samples_per_sec` | `throughput/samples_per_sec` divided by world size |
156
+ +-------------------------------------+-----------------------------------------------------------+
157
+ | | `throughput/tokens_per_sec` divided by world size. This |
158
+ | `throughput/device/tokens_per_sec` | may include pad tokens depending on dataset |
159
+ | | |
160
+ +-------------------------------------+-----------------------------------------------------------+
161
+ | | `throughput/flops_per_sec` divided by world size. Only |
162
+ | `throughput/device/flops_per_sec` | logged when model has attribute `flops_per_batch` |
163
+ | | |
164
+ +-------------------------------------+-----------------------------------------------------------+
165
+ | | `throughput/device/flops_per_sec` divided by world size. |
166
+ | `throughput/device/mfu` | |
167
+ | | |
168
+ +-------------------------------------+-----------------------------------------------------------+
169
+ | `time/train` | Total elapsed training time |
170
+ +-------------------------------------+-----------------------------------------------------------+
171
+ | `time/val` | Total elapsed validation time |
172
+ +-------------------------------------+-----------------------------------------------------------+
173
+ | `time/total` | Total elapsed time (time/train + time/val) |
174
+ +-------------------------------------+-----------------------------------------------------------+
175
+
176
+ Notes:
177
+ - The implementation assumes that devices are homogeneous as it normalizes by the world size.
178
+ - Tokens/sec, flops/sec and MFU do not account for padding tokens if present. We suggest using samples/sec or
179
+ batches/sec to measure throughput under this circumstance.
180
+ - Be careful when comparing MFU numbers across projects, as this will highly depend on the ``flops_per_batch``.
181
+ There is no widespread, realistic, and reliable implementation to compute them.
182
+ We suggest using our ``measure_flops`` function, but many other works will use ``estimated_flops`` which
183
+ will almost always be an overestimate when compared to the true value.
184
+
185
+ Args:
186
+ window_size (int, optional): Number of batches to use for a rolling average of throughput.
187
+ Defaults to 100.
188
+ time_unit (str, optional): Time unit to use for `time` logging. Can be one of
189
+ 'seconds', 'minutes', 'hours', or 'days'. Defaults to 'hours'.
190
+ """
191
+
192
+ def __init__(
193
+ self,
194
+ flops_available: float,
195
+ log_dict: Callable[[Dict, int], None],
196
+ window_size: int = 100,
197
+ time_unit: str = "hours",
198
+ ):
199
+ self.flops_available = flops_available
200
+ self.log_dict = log_dict
201
+
202
+ # Track the batch num samples and wct to compute throughput over a window of batches
203
+ self.history_samples: Deque[int] = deque(maxlen=window_size + 1)
204
+ self.history_wct: Deque[float] = deque(maxlen=window_size + 1)
205
+ self.history_lengths: Deque[int] = deque(maxlen=window_size + 1)
206
+ self.history_flops: Deque[int] = deque(maxlen=window_size + 1)
207
+
208
+ self.divider = 1
209
+ if time_unit == "seconds":
210
+ self.divider = 1
211
+ elif time_unit == "minutes":
212
+ self.divider = 60
213
+ elif time_unit == "hours":
214
+ self.divider = 60 * 60
215
+ elif time_unit == "days":
216
+ self.divider = 60 * 60 * 24
217
+ else:
218
+ raise ValueError(
219
+ f'Invalid time_unit: {time_unit}. Must be one of "seconds", "minutes", "hours", or "days".'
220
+ )
221
+
222
+ # Keep track of time spent evaluating
223
+ self.total_eval_wct = 0.0
224
+ self.step = -1
225
+
226
+ def on_train_batch_end(
227
+ self,
228
+ samples: int, # total samples seen (per device)
229
+ train_elapsed: float, # total training time (seconds)
230
+ world_size: int,
231
+ flops_per_batch: Optional[int] = None, # (per device)
232
+ lengths: Optional[int] = None, # total length of the samples seen (per device)
233
+ ) -> None:
234
+ self.step += 1
235
+ step = self.step
236
+ metrics = {}
237
+
238
+ self.history_samples.append(samples)
239
+ if lengths is not None:
240
+ self.history_lengths.append(lengths)
241
+ # if lengths are passed, there should be as many values as samples
242
+ assert len(self.history_samples) == len(self.history_lengths)
243
+ self.history_wct.append(train_elapsed)
244
+ if len(self.history_wct) == self.history_wct.maxlen:
245
+ elapsed_batches = len(self.history_samples) - 1
246
+ elapsed_samples = self.history_samples[-1] - self.history_samples[0]
247
+ elapsed_wct = self.history_wct[-1] - self.history_wct[0]
248
+ samples_per_sec = elapsed_samples * world_size / elapsed_wct
249
+ dev_samples_per_sec = elapsed_samples / elapsed_wct
250
+ metrics.update(
251
+ {
252
+ "throughput/batches_per_sec": elapsed_batches * world_size / elapsed_wct,
253
+ "throughput/samples_per_sec": samples_per_sec,
254
+ "throughput/device/batches_per_sec": elapsed_batches / elapsed_wct,
255
+ "throughput/device/samples_per_sec": dev_samples_per_sec,
256
+ }
257
+ )
258
+ if lengths is not None:
259
+ elapsed_lengths = int(self.history_lengths[-1]) - int(self.history_lengths[0])
260
+ avg_length = elapsed_lengths / elapsed_batches
261
+ metrics.update(
262
+ {
263
+ "throughput/tokens_per_sec": samples_per_sec * avg_length,
264
+ "throughput/device/tokens_per_sec": dev_samples_per_sec * avg_length,
265
+ }
266
+ )
267
+
268
+ if flops_per_batch is not None:
269
+ # sum of flops per batch across ranks
270
+ self.history_flops.append(flops_per_batch * world_size)
271
+ if len(self.history_flops) == self.history_flops.maxlen:
272
+ elapsed_flops = sum(self.history_flops) - self.history_flops[0]
273
+ elapsed_wct = self.history_wct[-1] - self.history_wct[0]
274
+ flops_per_sec = elapsed_flops / elapsed_wct
275
+ device_flops_per_sec = flops_per_sec / world_size
276
+ metrics.update(
277
+ {"throughput/flops_per_sec": flops_per_sec, "throughput/device/flops_per_sec": device_flops_per_sec}
278
+ )
279
+ if self.flops_available:
280
+ metrics["throughput/device/mfu"] = device_flops_per_sec / self.flops_available
281
+
282
+ metrics.update(
283
+ {
284
+ "time/train": train_elapsed / self.divider,
285
+ "time/val": self.total_eval_wct / self.divider,
286
+ "time/total": (train_elapsed + self.total_eval_wct) / self.divider,
287
+ "samples": samples,
288
+ }
289
+ )
290
+
291
+ self.log_dict(metrics, step)
292
+
293
+ def eval_end(self, eval_elapsed: float) -> None:
294
+ self.total_eval_wct += eval_elapsed # seconds
295
+
296
+
297
+ def plugin_to_compute_dtype(plugin: Precision) -> torch.dtype:
298
+ if isinstance(plugin, BitsandbytesPrecision):
299
+ return plugin.dtype
300
+ if isinstance(plugin, (HalfPrecision, MixedPrecision, HalfPrecisionPlugin)):
301
+ return plugin._desired_input_dtype
302
+ if isinstance(plugin, MixedPrecisionPlugin):
303
+ return torch.bfloat16 if plugin.precision == "bf16-mixed" else torch.half
304
+ if isinstance(plugin, (DoublePrecision, DoublePrecisionPlugin)):
305
+ return torch.double
306
+ if isinstance(plugin, (XLAPrecision, XLAPrecisionPlugin)):
307
+ return plugin._desired_dtype
308
+ if isinstance(plugin, TransformerEnginePrecision):
309
+ return torch.int8
310
+ if isinstance(plugin, (FSDPPrecision, FSDPPrecisionPlugin)):
311
+ return plugin.mixed_precision_config.reduce_dtype
312
+ if isinstance(plugin, Precision):
313
+ return torch.float32
314
+ raise NotImplementedError(plugin)
315
+
316
+
317
+ class SpeedMonitorFabric(SpeedMonitorBase):
318
+ def __init__(self, fabric: Fabric, *args: Any, **kwargs: Any) -> None:
319
+ dtype = plugin_to_compute_dtype(fabric.strategy.precision)
320
+ flops_available = get_flops_available(fabric.device, dtype)
321
+ super().__init__(flops_available, fabric.log_dict, *args, **kwargs)
322
+
323
+ @fabric_rank_zero_only
324
+ def on_train_batch_end(self, *args: Any, **kwargs: Any) -> None:
325
+ super().on_train_batch_end(*args, **kwargs)
326
+
327
+
328
+ class SpeedMonitorCallback(Callback):
329
+ def __init__(self, length_fn: Callable[[Any], int], batch_size: int, **kwargs: Any) -> None:
330
+ super().__init__()
331
+ self.speed_monitor: Optional[SpeedMonitorBase] = None
332
+ self.speed_monitor_kwargs = kwargs
333
+ self.length_fn = length_fn
334
+ self.batch_size = batch_size
335
+ self.eval_t0: int = 0
336
+ self.train_t0: int = 0
337
+ self.total_lengths: int = 0
338
+
339
+ def setup(self, trainer: Trainer, pl_module: LightningModule, stage: str) -> None:
340
+ if self.speed_monitor is not None:
341
+ return # already setup
342
+ dtype = plugin_to_compute_dtype(trainer.precision_plugin)
343
+ flops_available = get_flops_available(trainer.strategy.root_device, dtype)
344
+ self.speed_monitor = SpeedMonitorBase(flops_available, trainer.logger.log_metrics, **self.speed_monitor_kwargs)
345
+
346
+ @trainer_rank_zero_only
347
+ def on_train_start(self, trainer: Trainer, pl_module: LightningModule) -> None:
348
+ if trainer.fit_loop._should_accumulate():
349
+ return
350
+
351
+ self.train_t0 = time.perf_counter()
352
+
353
+ @trainer_rank_zero_only
354
+ def on_train_batch_end(
355
+ self, trainer: Trainer, pl_module: LightningModule, outputs: Any, batch: Any, batch_idx: int
356
+ ) -> None:
357
+ self.total_lengths += self.length_fn(batch)
358
+ if trainer.fit_loop._should_accumulate():
359
+ return
360
+ train_elapsed = time.perf_counter() - self.train_t0
361
+ assert self.speed_monitor is not None
362
+ iter_num = trainer.fit_loop.total_batch_idx
363
+ assert (measured_flops := pl_module.measured_flops) is not None
364
+ self.speed_monitor.on_train_batch_end(
365
+ (iter_num + 1) * self.batch_size,
366
+ train_elapsed,
367
+ # this assumes that device FLOPs are the same and that all devices have the same batch size
368
+ trainer.world_size,
369
+ flops_per_batch=measured_flops,
370
+ lengths=self.total_lengths,
371
+ )
372
+
373
+ @trainer_rank_zero_only
374
+ def on_validation_start(self, trainer: Trainer, pl_module: LightningModule) -> None:
375
+ self.eval_t0 = time.perf_counter()
376
+
377
+ @trainer_rank_zero_only
378
+ def on_validation_end(self, trainer: Trainer, pl_module: LightningModule) -> None:
379
+ eval_elapsed = time.perf_counter() - self.eval_t0
380
+ assert self.speed_monitor is not None
381
+ self.speed_monitor.eval_end(eval_elapsed)
382
+
383
+
384
+ def flops_per_param(max_seq_length: int, n_layer: int, n_embd: int, n_params: int) -> int:
385
+ flops_per_token = 2 * n_params # each parameter is used for a MAC (2 FLOPS) per network operation
386
+ # this assumes that all samples have a fixed length equal to the block size
387
+ # which is most likely false during finetuning
388
+ flops_per_seq = flops_per_token * max_seq_length
389
+ attn_flops_per_seq = n_layer * 2 * 2 * (n_embd * (max_seq_length**2))
390
+ return flops_per_seq + attn_flops_per_seq
391
+
392
+
393
+ def estimate_flops(model: GPT) -> int:
394
+ """Measures estimated FLOPs for MFU.
395
+
396
+ Refs:
397
+ * https://ar5iv.labs.arxiv.org/html/2205.05198#A1
398
+ * https://ar5iv.labs.arxiv.org/html/2204.02311#A2
399
+ """
400
+ # using all parameters for this is a naive over estimation because not all model parameters actually contribute to
401
+ # this FLOP computation (e.g. embedding, norm). For this reason, the result will be higher by a fixed percentage
402
+ # (~10%) compared to the measured FLOPs, making those lower but more realistic.
403
+ # For a proper estimate, this needs a more fine-grained calculation as in Appendix A of the paper.
404
+ n_trainable_params = num_parameters(model, requires_grad=True)
405
+ trainable_flops = flops_per_param(
406
+ model.max_seq_length, model.config.n_layer, model.config.n_embd, n_trainable_params
407
+ )
408
+ # forward + backward + gradients (assumes no gradient accumulation)
409
+ ops_per_step = 3 if model.training else 1
410
+ n_frozen_params = num_parameters(model, requires_grad=False)
411
+ frozen_flops = flops_per_param(model.max_seq_length, model.config.n_layer, model.config.n_embd, n_frozen_params)
412
+ # forward + backward
413
+ frozen_ops_per_step = 2 if model.training else 1
414
+ return ops_per_step * trainable_flops + frozen_ops_per_step * frozen_flops
415
+
416
+
417
+ def measure_flops(model: GPT, x: torch.Tensor) -> int:
418
+ """Measures real FLOPs for HFU"""
419
+ flop_counter = FlopCounterMode(model, display=False)
420
+ ctx = nullcontext() if model.training else torch.no_grad()
421
+ with ctx, flop_counter:
422
+ y = model(x)
423
+ if model.training:
424
+ y.sum().backward()
425
+ return flop_counter.get_total_flops()
tsai_gpt/tokenizer.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Optional
4
+
5
+ import torch
6
+
7
+
8
+ class Tokenizer:
9
+ def __init__(self, checkpoint_dir: Path) -> None:
10
+ self.use_bos = self.check_if_bos_token_used(checkpoint_dir)
11
+ self.bos_id = None
12
+ self.eos_id = None
13
+
14
+ # some checkpoints have both files, `.model` takes precedence
15
+ if (vocabulary_path := checkpoint_dir / "tokenizer.model").is_file():
16
+ from sentencepiece import SentencePieceProcessor
17
+
18
+ self.processor = SentencePieceProcessor(model_file=str(vocabulary_path))
19
+ self.backend = "sentencepiece"
20
+ self.bos_id = self.processor.bos_id()
21
+ self.eos_id = self.processor.eos_id()
22
+
23
+ elif (vocabulary_path := checkpoint_dir / "tokenizer.json").is_file():
24
+ from tokenizers import Tokenizer as HFTokenizer
25
+
26
+ self.processor = HFTokenizer.from_file(str(vocabulary_path))
27
+ self.backend = "huggingface"
28
+
29
+ if (special_tokens_path := checkpoint_dir / "tokenizer_config.json").is_file():
30
+ with open(special_tokens_path) as fp:
31
+ config = json.load(fp)
32
+ bos_token = config.get("bos_token")
33
+ self.bos_id = self.token_to_id(bos_token) if bos_token is not None else None
34
+ eos_token = config.get("eos_token")
35
+ self.eos_id = self.token_to_id(eos_token) if eos_token is not None else None
36
+ if (special_tokens_path := checkpoint_dir / "generation_config.json").is_file():
37
+ with open(special_tokens_path) as fp:
38
+ config = json.load(fp)
39
+ if self.bos_id is None:
40
+ self.bos_id = config.get("bos_token_id")
41
+ if self.eos_id is None:
42
+ self.eos_id = config.get("eos_token_id")
43
+ else:
44
+ raise NotImplementedError
45
+
46
+ @property
47
+ def vocab_size(self) -> int:
48
+ if self.backend == "huggingface":
49
+ return self.processor.get_vocab_size(with_added_tokens=False)
50
+ if self.backend == "sentencepiece":
51
+ return self.processor.vocab_size()
52
+ raise RuntimeError
53
+
54
+ def token_to_id(self, token: str) -> int:
55
+ if self.backend == "huggingface":
56
+ id_ = self.processor.token_to_id(token)
57
+ elif self.backend == "sentencepiece":
58
+ id_ = self.processor.piece_to_id(token)
59
+ else:
60
+ raise RuntimeError
61
+ if id_ is None:
62
+ raise ValueError(f"token {token!r} not found in the collection.")
63
+ return id_
64
+
65
+ def check_if_bos_token_used(self, checkpoint_dir: Path) -> bool:
66
+ if not (tokenizer_config_path := checkpoint_dir / "tokenizer_config.json").is_file():
67
+ return False
68
+ with open(tokenizer_config_path) as fp:
69
+ config = json.load(fp)
70
+ if any(config.get(check, False) for check in ("add_bos_token", "add_prefix_space")):
71
+ return True
72
+ # for examples that also use the Llama tokenizer, but do not have or set add_bos_token to True.
73
+ # ex: https://huggingface.co/stabilityai/StableBeluga2/blob/main/tokenizer_config.json#L2
74
+ return config.get("add_bos_token") is None and config.get("tokenizer_class") == "LlamaTokenizer"
75
+
76
+ def encode(
77
+ self,
78
+ string: str,
79
+ device: Optional[torch.device] = None,
80
+ bos: Optional[bool] = None,
81
+ eos: bool = False,
82
+ max_length: int = -1,
83
+ ) -> torch.Tensor:
84
+ if self.backend == "huggingface":
85
+ tokens = self.processor.encode(string).ids
86
+ elif self.backend == "sentencepiece":
87
+ tokens = self.processor.encode(string)
88
+ else:
89
+ raise RuntimeError
90
+ if bos or (bos is None and self.use_bos):
91
+ bos_id = self.bos_id
92
+ if bos_id is None:
93
+ raise NotImplementedError("This tokenizer does not have a defined a bos token")
94
+ tokens = [bos_id] + tokens
95
+ if eos:
96
+ tokens = tokens + [self.eos_id]
97
+ if max_length > 0:
98
+ tokens = tokens[:max_length]
99
+ return torch.tensor(tokens, dtype=torch.int, device=device)
100
+
101
+ def decode(self, tensor: torch.Tensor) -> str:
102
+ tokens = [tensor.item()] if tensor.ndim == 0 else tensor.tolist()
103
+ return self.processor.decode(tokens)
tsai_gpt/utils.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility functions for training and inference."""
2
+ import math
3
+ import pickle
4
+ import sys
5
+ from contextlib import nullcontext
6
+ from io import BytesIO
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, ContextManager, Dict, List, Mapping, Optional, TypeVar, Union
9
+
10
+ import lightning as L
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.utils._device
14
+ from lightning.fabric.strategies import FSDPStrategy
15
+ from lightning.fabric.utilities.load import _lazy_load as lazy_load
16
+ from torch.serialization import normalize_storage_type
17
+
18
+ if TYPE_CHECKING:
19
+ from model import GPT
20
+
21
+
22
+ def find_multiple(n: int, k: int) -> int:
23
+ assert k > 0
24
+ if n % k == 0:
25
+ return n
26
+ return n + k - (n % k)
27
+
28
+
29
+ def num_parameters(module: nn.Module, requires_grad: Optional[bool] = None) -> int:
30
+ total = 0
31
+ for p in module.parameters():
32
+ if requires_grad is None or p.requires_grad == requires_grad:
33
+ if hasattr(p, "quant_state"):
34
+ # bitsandbytes 4bit layer support
35
+ total += math.prod(p.quant_state[1])
36
+ else:
37
+ total += p.numel()
38
+ return total
39
+
40
+
41
+ def gptq_quantization(enabled: bool = False) -> ContextManager:
42
+ if not enabled:
43
+ return nullcontext()
44
+
45
+ from lightning.fabric.plugins.precision.utils import _ClassReplacementContextManager
46
+
47
+ from quantize.gptq import ColBlockQuantizedLinear
48
+
49
+ class QuantizedLinear(ColBlockQuantizedLinear):
50
+ def __init__(self, *args, **kwargs):
51
+ super().__init__(*args, bits=4, tile_cols=-1, **kwargs)
52
+
53
+ return _ClassReplacementContextManager({"torch.nn.Linear": QuantizedLinear})
54
+
55
+
56
+ def check_valid_checkpoint_dir(checkpoint_dir: Path) -> None:
57
+ files = {
58
+ "lit_model.pth": (checkpoint_dir / "lit_model.pth").is_file(),
59
+ "lit_config.json": (checkpoint_dir / "lit_config.json").is_file(),
60
+ "tokenizer.json OR tokenizer.model": (checkpoint_dir / "tokenizer.json").is_file() or (
61
+ checkpoint_dir / "tokenizer.model"
62
+ ).is_file(),
63
+ "tokenizer_config.json": (checkpoint_dir / "tokenizer_config.json").is_file(),
64
+ }
65
+ if checkpoint_dir.is_dir():
66
+ if all(files.values()):
67
+ # we're good
68
+ return
69
+ problem = f" is missing the files: {[f for f, exists in files.items() if not exists]!r}"
70
+ else:
71
+ problem = " is not a checkpoint directory"
72
+
73
+ # list locally available checkpoints
74
+ available = list(Path("checkpoints").glob("*/*"))
75
+ if available:
76
+ options = "\n --checkpoint_dir ".join([""] + [repr(str(p.resolve())) for p in available])
77
+ extra = f"\nYou have downloaded locally:{options}\n"
78
+ else:
79
+ extra = ""
80
+
81
+ error_message = (
82
+ f"--checkpoint_dir {str(checkpoint_dir.absolute())!r}{problem}."
83
+ "\nFind download instructions at https://github.com/Lightning-AI/lit-gpt/blob/main/tutorials\n"
84
+ f"{extra}\nSee all download options by running:\n python scripts/download.py"
85
+ )
86
+ print(error_message, file=sys.stderr)
87
+ raise SystemExit(1)
88
+
89
+
90
+ class SavingProxyForStorage:
91
+ def __init__(self, obj, saver, protocol_version=5):
92
+ self.protocol_version = protocol_version
93
+ self.saver = saver
94
+ if not (isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj)):
95
+ raise TypeError(f"expected storage, not {type(obj)}")
96
+
97
+ # this logic is taken from PyTorch 2.0+ torch/serialization.py
98
+ if isinstance(obj, torch.storage.TypedStorage):
99
+ # PT upstream wants to deprecate this eventually...
100
+ storage = obj._untyped_storage
101
+ storage_type_str = obj._pickle_storage_type()
102
+ storage_type = getattr(torch, storage_type_str)
103
+ storage_numel = obj._size()
104
+ else:
105
+ storage = obj
106
+ storage_type = normalize_storage_type(type(obj))
107
+ storage_numel = storage.nbytes()
108
+
109
+ storage_key = saver._write_storage_and_return_key(storage)
110
+ location = torch.serialization.location_tag(storage)
111
+
112
+ self.storage_info = ("storage", storage_type, storage_key, location, storage_numel)
113
+
114
+ def __reduce_ex__(self, protocol_version):
115
+ assert False, "this should be handled with out of band"
116
+
117
+
118
+ class SavingProxyForTensor:
119
+ def __init__(self, tensor, saver, protocol_version=5):
120
+ self.protocol_version = protocol_version
121
+ self.reduce_ret_fn, reduce_args = tensor.__reduce_ex__(protocol_version)
122
+ if reduce_args[0] == torch._utils._rebuild_tensor_v2:
123
+ # for Tensors with Python attributes
124
+ (a0, a1, (storage, *a2_other), *other_reduce_args) = reduce_args
125
+ assert isinstance(storage, torch.storage.TypedStorage), "Please check for updates"
126
+ storage_proxy = SavingProxyForStorage(storage, saver, protocol_version=protocol_version)
127
+ self.reduce_args = (a0, a1, (storage_proxy, *a2_other), *other_reduce_args)
128
+ else:
129
+ (storage, *other_reduce_args) = reduce_args
130
+ assert isinstance(storage, torch.storage.TypedStorage), "Please check for updates"
131
+ storage_proxy = SavingProxyForStorage(storage, saver, protocol_version=protocol_version)
132
+ self.reduce_args = (storage_proxy, *other_reduce_args)
133
+
134
+ def __reduce_ex__(self, protocol_version):
135
+ if protocol_version != self.protocol_version:
136
+ raise RuntimeError(f"Unexpected protocol version: expected {self.protocol_version}, got {protocol_version}")
137
+ return self.reduce_ret_fn, self.reduce_args
138
+
139
+
140
+ class IncrementalPyTorchPickler(pickle.Pickler):
141
+ def __init__(self, saver, *args, **kwargs):
142
+ super().__init__(*args, **kwargs)
143
+ self.storage_dtypes = {}
144
+ self.saver = saver
145
+ self.id_map = {}
146
+
147
+ # this logic is taken from PyTorch 2.0+ torch/serialization.py
148
+ def persistent_id(self, obj):
149
+ # FIXME: the docs say that persistent_id should only return a string
150
+ # but torch store returns tuples. This works only in the binary protocol
151
+ # see
152
+ # https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-external-objects
153
+ # https://github.com/python/cpython/blob/master/Lib/pickle.py#L527-L537
154
+ if isinstance(obj, SavingProxyForStorage):
155
+ return obj.storage_info
156
+
157
+ if isinstance(obj, torch.storage.TypedStorage) or torch.is_storage(obj):
158
+ if isinstance(obj, torch.storage.TypedStorage):
159
+ # TODO: Once we decide to break serialization FC, this case
160
+ # can be deleted
161
+ storage = obj._untyped_storage
162
+ storage_dtype = obj.dtype
163
+ storage_type_str = obj._pickle_storage_type()
164
+ storage_type = getattr(torch, storage_type_str)
165
+ storage_numel = obj._size()
166
+
167
+ else:
168
+ storage = obj
169
+ storage_dtype = torch.uint8
170
+ storage_type = normalize_storage_type(type(obj))
171
+ storage_numel = storage.nbytes()
172
+
173
+ # If storage is allocated, ensure that any other saved storages
174
+ # pointing to the same data all have the same dtype. If storage is
175
+ # not allocated, don't perform this check
176
+ if storage.data_ptr() != 0:
177
+ if storage.data_ptr() in self.storage_dtypes:
178
+ if storage_dtype != self.storage_dtypes[storage.data_ptr()]:
179
+ raise RuntimeError(
180
+ "Cannot save multiple tensors or storages that view the same data as different types"
181
+ )
182
+ else:
183
+ self.storage_dtypes[storage.data_ptr()] = storage_dtype
184
+
185
+ storage_key = self.id_map.get(storage._cdata)
186
+ if storage_key is None:
187
+ storage_key = self.saver._write_storage_and_return_key(storage)
188
+ self.id_map[storage._cdata] = storage_key
189
+ location = torch.serialization.location_tag(storage)
190
+
191
+ return ("storage", storage_type, storage_key, location, storage_numel)
192
+
193
+ return None
194
+
195
+
196
+ class incremental_save:
197
+ def __init__(self, name):
198
+ self.name = name
199
+ self.zipfile = torch._C.PyTorchFileWriter(str(name))
200
+ self.has_saved = False
201
+ self.next_key = 0
202
+
203
+ def __enter__(self):
204
+ return self
205
+
206
+ def store_early(self, tensor):
207
+ if isinstance(tensor, torch.Tensor):
208
+ return SavingProxyForTensor(tensor, self)
209
+ raise TypeError(f"can only store tensors early, not {type(tensor)}")
210
+
211
+ def save(self, obj):
212
+ if self.has_saved:
213
+ raise RuntimeError("have already saved")
214
+ # Write the pickle data for `obj`
215
+ data_buf = BytesIO()
216
+ pickler = IncrementalPyTorchPickler(self, data_buf, protocol=5)
217
+ pickler.dump(obj)
218
+ data_value = data_buf.getvalue()
219
+ self.zipfile.write_record("data.pkl", data_value, len(data_value))
220
+ self.has_saved = True
221
+
222
+ def _write_storage_and_return_key(self, storage):
223
+ if self.has_saved:
224
+ raise RuntimeError("have already saved")
225
+ key = self.next_key
226
+ self.next_key += 1
227
+ name = f"data/{key}"
228
+ if storage.device.type != "cpu":
229
+ storage = storage.cpu()
230
+ num_bytes = storage.nbytes()
231
+ self.zipfile.write_record(name, storage.data_ptr(), num_bytes)
232
+ return key
233
+
234
+ def __exit__(self, type, value, traceback):
235
+ self.zipfile.write_end_of_file()
236
+
237
+
238
+ T = TypeVar("T")
239
+
240
+
241
+ def chunked_cross_entropy(
242
+ logits: Union[torch.Tensor, List[torch.Tensor]], targets: torch.Tensor, chunk_size: int = 128
243
+ ) -> torch.Tensor:
244
+ # with large max_sequence_lengths, the beginning of `backward` allocates a large memory chunk which can dominate
245
+ # the memory usage in fine-tuning settings with low number of parameters.
246
+ # as a workaround hack, the cross entropy computation is chunked to force it to deallocate on the go, reducing
247
+ # the memory spike's magnitude
248
+
249
+ # lm_head was chunked (we are fine-tuning)
250
+ if isinstance(logits, list):
251
+ # don't want to chunk cross entropy
252
+ if chunk_size == 0:
253
+ logits = torch.cat(logits, dim=1)
254
+ logits = logits.reshape(-1, logits.size(-1))
255
+ targets = targets.reshape(-1)
256
+ return torch.nn.functional.cross_entropy(logits, targets, ignore_index=-1)
257
+
258
+ # chunk cross entropy
259
+ logit_chunks = [logit_chunk.reshape(-1, logit_chunk.size(-1)) for logit_chunk in logits]
260
+ target_chunks = [target_chunk.reshape(-1) for target_chunk in targets.split(logits[0].size(1), dim=1)]
261
+ loss_chunks = [
262
+ torch.nn.functional.cross_entropy(logit_chunk, target_chunk, ignore_index=-1, reduction="none")
263
+ for logit_chunk, target_chunk in zip(logit_chunks, target_chunks)
264
+ ]
265
+ return torch.cat(loss_chunks).mean()
266
+
267
+ # no chunking at all
268
+ logits = logits.reshape(-1, logits.size(-1))
269
+ targets = targets.reshape(-1)
270
+ if chunk_size == 0:
271
+ return torch.nn.functional.cross_entropy(logits, targets, ignore_index=-1)
272
+
273
+ # lm_head wasn't chunked, chunk cross entropy
274
+ logit_chunks = logits.split(chunk_size)
275
+ target_chunks = targets.split(chunk_size)
276
+ loss_chunks = [
277
+ torch.nn.functional.cross_entropy(logit_chunk, target_chunk, ignore_index=-1, reduction="none")
278
+ for logit_chunk, target_chunk in zip(logit_chunks, target_chunks)
279
+ ]
280
+ return torch.cat(loss_chunks).mean()
281
+
282
+
283
+ def map_old_state_dict_weights(state_dict: Dict, mapping: Mapping, prefix: str) -> Dict:
284
+ for checkpoint_name, attribute_name in mapping.items():
285
+ full_checkpoint_name = prefix + checkpoint_name
286
+ if full_checkpoint_name in state_dict:
287
+ full_attribute_name = prefix + attribute_name
288
+ state_dict[full_attribute_name] = state_dict.pop(full_checkpoint_name)
289
+ return state_dict
290
+
291
+
292
+ def get_default_supported_precision(training: bool) -> str:
293
+ """Return default precision that is supported by the hardware: either `bf16` or `16`.
294
+
295
+ Args:
296
+ training: `-mixed` or `-true` version of the precision to use
297
+
298
+ Returns:
299
+ default precision that is suitable for the task and is supported by the hardware
300
+ """
301
+ from lightning.fabric.accelerators import MPSAccelerator
302
+
303
+ if MPSAccelerator.is_available() or (torch.cuda.is_available() and not torch.cuda.is_bf16_supported()):
304
+ return "16-mixed" if training else "16-true"
305
+ return "bf16-mixed" if training else "bf16-true"
306
+
307
+
308
+ def load_checkpoint(fabric: L.Fabric, model: nn.Module, checkpoint_path: Path, strict: bool = True) -> None:
309
+ if isinstance(fabric.strategy, FSDPStrategy):
310
+ fabric.load_raw(checkpoint_path, model, strict=strict)
311
+ else:
312
+ state_dict = lazy_load(checkpoint_path)
313
+ state_dict = state_dict.get("model", state_dict)
314
+ model.load_state_dict(state_dict, strict=strict)
315
+
316
+
317
+ def flops_per_param(max_seq_length: int, n_layer: int, n_embd: int, n_params: int) -> int:
318
+ flops_per_token = 2 * n_params # each parameter is used for a MAC (2 FLOPS) per network operation
319
+ # this assumes that all samples have a fixed length equal to the block size
320
+ # which is most likely false during finetuning
321
+ flops_per_seq = flops_per_token * max_seq_length
322
+ attn_flops_per_seq = n_layer * 2 * 2 * (n_embd * (max_seq_length**2))
323
+ return flops_per_seq + attn_flops_per_seq
324
+
325
+
326
+ def estimate_flops(model: "GPT", training: bool) -> int:
327
+ """Measures estimated FLOPs for MFU.
328
+
329
+ Refs:
330
+ * https://ar5iv.labs.arxiv.org/html/2205.05198#A1
331
+ * https://ar5iv.labs.arxiv.org/html/2204.02311#A2
332
+ """
333
+ # using all parameters for this is a naive over estimation because not all model parameters actually contribute to
334
+ # this FLOP computation (e.g. embedding, norm). For this reason, the result will be higher by a fixed percentage
335
+ # (~10%) compared to the measured FLOPs, making those lower but more realistic.
336
+ # For a proper estimate, this needs a more fine-grained calculation as in Appendix A of the paper.
337
+ n_trainable_params = num_parameters(model, requires_grad=True)
338
+ trainable_flops = flops_per_param(
339
+ model.max_seq_length, model.config.n_layer, model.config.n_embd, n_trainable_params
340
+ )
341
+ # forward + backward + gradients (assumes no gradient accumulation)
342
+ ops_per_step = 3 if training else 1
343
+ n_frozen_params = num_parameters(model, requires_grad=False)
344
+ frozen_flops = flops_per_param(model.max_seq_length, model.config.n_layer, model.config.n_embd, n_frozen_params)
345
+ # forward + backward
346
+ frozen_ops_per_step = 2 if training else 1
347
+ return ops_per_step * trainable_flops + frozen_ops_per_step * frozen_flops