Upload folder using huggingface_hub (#1)
Browse files- fff44dfcafde861149d9bf64d649d8dd8d1a25f995a4c8a7552b966d6cefb04f (290940f35c1185bcefd671de6a360fcf6ec0e4c8)
- 39751589bd66c056919eb677eef672e361899ffd50028d020b6c69d547b34289 (e82902f30d46f6d687ec3164b9c95555859bd15b)
- 5453bc0bc51075419410b74ffc0d566e778975883ec8dc2cf71fc4538159a72d (bd9508b7f6525330d6be5bef354040c2c778fdf7)
- .gitattributes +1 -0
- .locks/models--distributed--optimized-gpt2-1b/664ab0cd267a979f4248ecbb313a8279ec06e21b.lock +0 -0
- .locks/models--distributed--optimized-gpt2-1b/84bd38785e135d735130cb4633155169b1046946034dff6dd9275ef96649e85a.lock +0 -0
- .locks/models--distributed--optimized-gpt2-500m/03f1227b29a7a2051f79adb38cc603d8ab6a730b.lock +0 -0
- .locks/models--distributed--optimized-gpt2-500m/953c04829583cb1b5475c05e153bd1946e944cf6.lock +0 -0
- README.md +85 -0
- config.json +54 -0
- configuration_gpt_optimized.py +22 -0
- model.safetensors +3 -0
- models--distributed--optimized-gpt2-1b/.no_exist/fba79423a8549ee57e7ae92c54c57628e4a3b012/adapter_config.json +0 -0
- models--distributed--optimized-gpt2-1b/blobs/664ab0cd267a979f4248ecbb313a8279ec06e21b +37 -0
- models--distributed--optimized-gpt2-1b/blobs/84bd38785e135d735130cb4633155169b1046946034dff6dd9275ef96649e85a +3 -0
- models--distributed--optimized-gpt2-1b/refs/main +1 -0
- models--distributed--optimized-gpt2-1b/snapshots/fba79423a8549ee57e7ae92c54c57628e4a3b012/config.json +37 -0
- models--distributed--optimized-gpt2-1b/snapshots/fba79423a8549ee57e7ae92c54c57628e4a3b012/model.safetensors +3 -0
- models--distributed--optimized-gpt2-500m/blobs/03f1227b29a7a2051f79adb38cc603d8ab6a730b +22 -0
- models--distributed--optimized-gpt2-500m/blobs/953c04829583cb1b5475c05e153bd1946e944cf6 +200 -0
- models--distributed--optimized-gpt2-500m/refs/main +1 -0
- models--distributed--optimized-gpt2-500m/snapshots/9bd57ae4e2ba48cf4c123cdc9eab01af3845ba28/configuration_gpt_optimized.py +22 -0
- models--distributed--optimized-gpt2-500m/snapshots/9bd57ae4e2ba48cf4c123cdc9eab01af3845ba28/modeling_gpt_optimized.py +200 -0
- smash_config.json +37 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
models--distributed--optimized-gpt2-1b/blobs/84bd38785e135d735130cb4633155169b1046946034dff6dd9275ef96649e85a filter=lfs diff=lfs merge=lfs -text
|
.locks/models--distributed--optimized-gpt2-1b/664ab0cd267a979f4248ecbb313a8279ec06e21b.lock
ADDED
File without changes
|
.locks/models--distributed--optimized-gpt2-1b/84bd38785e135d735130cb4633155169b1046946034dff6dd9275ef96649e85a.lock
ADDED
File without changes
|
.locks/models--distributed--optimized-gpt2-500m/03f1227b29a7a2051f79adb38cc603d8ab6a730b.lock
ADDED
File without changes
|
.locks/models--distributed--optimized-gpt2-500m/953c04829583cb1b5475c05e153bd1946e944cf6.lock
ADDED
File without changes
|
README.md
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
thumbnail: "https://assets-global.website-files.com/646b351987a8d8ce158d1940/64ec9e96b4334c0e1ac41504_Logo%20with%20white%20text.svg"
|
3 |
+
base_model: distributed/optimized-gpt2-1b
|
4 |
+
metrics:
|
5 |
+
- memory_disk
|
6 |
+
- memory_inference
|
7 |
+
- inference_latency
|
8 |
+
- inference_throughput
|
9 |
+
- inference_CO2_emissions
|
10 |
+
- inference_energy_consumption
|
11 |
+
tags:
|
12 |
+
- pruna-ai
|
13 |
+
---
|
14 |
+
<!-- header start -->
|
15 |
+
<!-- 200823 -->
|
16 |
+
<div style="width: auto; margin-left: auto; margin-right: auto">
|
17 |
+
<a href="https://www.pruna.ai/" target="_blank" rel="noopener noreferrer">
|
18 |
+
<img src="https://i.imgur.com/eDAlcgk.png" alt="PrunaAI" style="width: 100%; min-width: 400px; display: block; margin: auto;">
|
19 |
+
</a>
|
20 |
+
</div>
|
21 |
+
<!-- header end -->
|
22 |
+
|
23 |
+
[![Twitter](https://img.shields.io/twitter/follow/PrunaAI?style=social)](https://twitter.com/PrunaAI)
|
24 |
+
[![GitHub](https://img.shields.io/github/followers/PrunaAI?label=Follow%20%40PrunaAI&style=social)](https://github.com/PrunaAI)
|
25 |
+
[![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue)](https://www.linkedin.com/company/93832878/admin/feed/posts/?feedType=following)
|
26 |
+
[![Discord](https://img.shields.io/badge/Discord-Join%20Us-blue?style=social&logo=discord)](https://discord.gg/rskEr4BZJx)
|
27 |
+
|
28 |
+
# Simply make AI models cheaper, smaller, faster, and greener!
|
29 |
+
|
30 |
+
- Give a thumbs up if you like this model!
|
31 |
+
- Contact us and tell us which model to compress next [here](https://www.pruna.ai/contact).
|
32 |
+
- Request access to easily compress your *own* AI models [here](https://z0halsaff74.typeform.com/pruna-access?typeform-source=www.pruna.ai).
|
33 |
+
- Read the documentations to know more [here](https://pruna-ai-pruna.readthedocs-hosted.com/en/latest/)
|
34 |
+
- Join Pruna AI community on Discord [here](https://discord.gg/CP4VSgck) to share feedback/suggestions or get help.
|
35 |
+
|
36 |
+
## Results
|
37 |
+
|
38 |
+
![image info](./plots.png)
|
39 |
+
|
40 |
+
**Frequently Asked Questions**
|
41 |
+
- ***How does the compression work?*** The model is compressed with llm-int8.
|
42 |
+
- ***How does the model quality change?*** The quality of the model output might vary compared to the base model.
|
43 |
+
- ***How is the model efficiency evaluated?*** These results were obtained with configuration described in `model/smash_config.json` and are obtained after a hardware warmup. The smashed model is directly compared to the original base model. Efficiency results may vary in other settings (e.g. other hardware, image size, batch size, ...). We recommend to directly run them in the use-case conditions to know if the smashed model can benefit you.
|
44 |
+
- ***What is the model format?*** We use safetensors.
|
45 |
+
- ***What calibration data has been used?*** If needed by the compression method, we used WikiText as the calibration data.
|
46 |
+
- ***What is the naming convention for Pruna Huggingface models?*** We take the original model name and append "turbo", "tiny", or "green" if the smashed model has a measured inference speed, inference memory, or inference energy consumption which is less than 90% of the original base model.
|
47 |
+
- ***How to compress my own models?*** You can request premium access to more compression methods and tech support for your specific use-cases [here](https://z0halsaff74.typeform.com/pruna-access?typeform-source=www.pruna.ai).
|
48 |
+
- ***What are "first" metrics?*** Results mentioning "first" are obtained after the first run of the model. The first run might take more memory or be slower than the subsequent runs due cuda overheads.
|
49 |
+
- ***What are "Sync" and "Async" metrics?*** "Sync" metrics are obtained by syncing all GPU processes and stop measurement when all of them are executed. "Async" metrics are obtained without syncing all GPU processes and stop when the model output can be used by the CPU. We provide both metrics since both could be relevant depending on the use-case. We recommend to test the efficiency gains directly in your use-cases.
|
50 |
+
|
51 |
+
## Setup
|
52 |
+
|
53 |
+
You can run the smashed model with these steps:
|
54 |
+
|
55 |
+
0. Check requirements from the original repo distributed/optimized-gpt2-1b installed. In particular, check python, cuda, and transformers versions.
|
56 |
+
1. Make sure that you have installed quantization related packages.
|
57 |
+
```bash
|
58 |
+
pip install transformers accelerate bitsandbytes>0.37.0
|
59 |
+
```
|
60 |
+
2. Load & run the model.
|
61 |
+
```python
|
62 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
63 |
+
|
64 |
+
|
65 |
+
model = AutoModelForCausalLM.from_pretrained("PrunaAI/distributed-optimized-gpt2-1b-bnb-smashed", trust_remote_code=True, device_map='auto')
|
66 |
+
tokenizer = AutoTokenizer.from_pretrained("distributed/optimized-gpt2-1b")
|
67 |
+
|
68 |
+
input_ids = tokenizer("What is the color of prunes?,", return_tensors='pt').to(model.device)["input_ids"]
|
69 |
+
|
70 |
+
outputs = model.generate(input_ids, max_new_tokens=216)
|
71 |
+
tokenizer.decode(outputs[0])
|
72 |
+
```
|
73 |
+
|
74 |
+
## Configurations
|
75 |
+
|
76 |
+
The configuration info are in `smash_config.json`.
|
77 |
+
|
78 |
+
## Credits & License
|
79 |
+
|
80 |
+
The license of the smashed model follows the license of the original model. Please check the license of the original model distributed/optimized-gpt2-1b before using this model which provided the base model. The license of the `pruna-engine` is [here](https://pypi.org/project/pruna-engine/) on Pypi.
|
81 |
+
|
82 |
+
## Want to compress other models?
|
83 |
+
|
84 |
+
- Contact us and tell us which model to compress next [here](https://www.pruna.ai/contact).
|
85 |
+
- Request access to easily compress your own AI models [here](https://z0halsaff74.typeform.com/pruna-access?typeform-source=www.pruna.ai).
|
config.json
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/covalent/.cache/models/tmpk1t5rgu6v17wvlsb",
|
3 |
+
"activation_function": "gelu_new",
|
4 |
+
"architectures": [
|
5 |
+
"GPTOptim"
|
6 |
+
],
|
7 |
+
"attn_pdrop": 0.1,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_gpt_optimized.GPTOptimConfig",
|
10 |
+
"AutoModelForCausalLM": "distributed/optimized-gpt2-500m--modeling_gpt_optimized.GPTOptim"
|
11 |
+
},
|
12 |
+
"block_size": 1024,
|
13 |
+
"bos_token_id": 50256,
|
14 |
+
"embd_pdrop": 0.1,
|
15 |
+
"eos_token_id": 50256,
|
16 |
+
"initializer_range": 0.02,
|
17 |
+
"layer_norm_epsilon": 1e-05,
|
18 |
+
"model_type": "gpt_optimized",
|
19 |
+
"n_embd": 1280,
|
20 |
+
"n_head": 32,
|
21 |
+
"n_inner": null,
|
22 |
+
"n_layer": 48,
|
23 |
+
"n_positions": 1024,
|
24 |
+
"quantization_config": {
|
25 |
+
"_load_in_4bit": false,
|
26 |
+
"_load_in_8bit": true,
|
27 |
+
"bnb_4bit_compute_dtype": "bfloat16",
|
28 |
+
"bnb_4bit_quant_storage": "uint8",
|
29 |
+
"bnb_4bit_quant_type": "fp4",
|
30 |
+
"bnb_4bit_use_double_quant": false,
|
31 |
+
"llm_int8_enable_fp32_cpu_offload": false,
|
32 |
+
"llm_int8_has_fp16_weight": false,
|
33 |
+
"llm_int8_skip_modules": [
|
34 |
+
"lm_head"
|
35 |
+
],
|
36 |
+
"llm_int8_threshold": 6.0,
|
37 |
+
"load_in_4bit": false,
|
38 |
+
"load_in_8bit": true,
|
39 |
+
"quant_method": "bitsandbytes"
|
40 |
+
},
|
41 |
+
"reorder_and_upcast_attn": false,
|
42 |
+
"resid_pdrop": 0.1,
|
43 |
+
"scale_attn_by_inverse_layer_idx": false,
|
44 |
+
"scale_attn_weights": true,
|
45 |
+
"summary_activation": null,
|
46 |
+
"summary_first_dropout": 0.1,
|
47 |
+
"summary_proj_to_labels": true,
|
48 |
+
"summary_type": "cls_index",
|
49 |
+
"summary_use_proj": true,
|
50 |
+
"torch_dtype": "float16",
|
51 |
+
"transformers_version": "4.46.1",
|
52 |
+
"use_cache": true,
|
53 |
+
"vocab_size": 50257
|
54 |
+
}
|
configuration_gpt_optimized.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig, GPT2Config
|
2 |
+
from typing import List
|
3 |
+
|
4 |
+
|
5 |
+
class GPTOptimConfig(GPT2Config):
|
6 |
+
model_type = "gpt_optimized"
|
7 |
+
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
block_size: int = 1024, # max sequence length
|
11 |
+
vocab_size: int = 50257, # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
|
12 |
+
n_layer: int = 16, # number of layers
|
13 |
+
n_head: int = 16, # number of heads
|
14 |
+
n_embd: int = 1024, # embedding dimension
|
15 |
+
**kwargs,
|
16 |
+
):
|
17 |
+
super().__init__(**kwargs)
|
18 |
+
self.block_size = block_size
|
19 |
+
self.vocab_size = vocab_size
|
20 |
+
self.n_layer = n_layer
|
21 |
+
self.n_head = n_head
|
22 |
+
self.n_embd = n_embd
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7a9316cb534bf66e7e13d432916c9d943119734ba5ed1df39a00f821c9fa3380
|
3 |
+
size 1207575528
|
models--distributed--optimized-gpt2-1b/.no_exist/fba79423a8549ee57e7ae92c54c57628e4a3b012/adapter_config.json
ADDED
File without changes
|
models--distributed--optimized-gpt2-1b/blobs/664ab0cd267a979f4248ecbb313a8279ec06e21b
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "distributed/optimized-gpt2-1b",
|
3 |
+
"activation_function": "gelu_new",
|
4 |
+
"architectures": [
|
5 |
+
"GPTOptim"
|
6 |
+
],
|
7 |
+
"attn_pdrop": 0.1,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "distributed/optimized-gpt2-500m--configuration_gpt_optimized.GPTOptimConfig",
|
10 |
+
"AutoModelForCausalLM": "distributed/optimized-gpt2-500m--modeling_gpt_optimized.GPTOptim"
|
11 |
+
},
|
12 |
+
"block_size": 1024,
|
13 |
+
"bos_token_id": 50256,
|
14 |
+
"embd_pdrop": 0.1,
|
15 |
+
"eos_token_id": 50256,
|
16 |
+
"initializer_range": 0.02,
|
17 |
+
"layer_norm_epsilon": 1e-05,
|
18 |
+
"model_type": "gpt_optimized",
|
19 |
+
"n_embd": 1280,
|
20 |
+
"n_head": 32,
|
21 |
+
"n_inner": null,
|
22 |
+
"n_layer": 48,
|
23 |
+
"n_positions": 1024,
|
24 |
+
"reorder_and_upcast_attn": false,
|
25 |
+
"resid_pdrop": 0.1,
|
26 |
+
"scale_attn_by_inverse_layer_idx": false,
|
27 |
+
"scale_attn_weights": true,
|
28 |
+
"summary_activation": null,
|
29 |
+
"summary_first_dropout": 0.1,
|
30 |
+
"summary_proj_to_labels": true,
|
31 |
+
"summary_type": "cls_index",
|
32 |
+
"summary_use_proj": true,
|
33 |
+
"torch_dtype": "float32",
|
34 |
+
"transformers_version": "4.39.3",
|
35 |
+
"use_cache": true,
|
36 |
+
"vocab_size": 50257
|
37 |
+
}
|
models--distributed--optimized-gpt2-1b/blobs/84bd38785e135d735130cb4633155169b1046946034dff6dd9275ef96649e85a
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:84bd38785e135d735130cb4633155169b1046946034dff6dd9275ef96649e85a
|
3 |
+
size 4040701744
|
models--distributed--optimized-gpt2-1b/refs/main
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
fba79423a8549ee57e7ae92c54c57628e4a3b012
|
models--distributed--optimized-gpt2-1b/snapshots/fba79423a8549ee57e7ae92c54c57628e4a3b012/config.json
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "distributed/optimized-gpt2-1b",
|
3 |
+
"activation_function": "gelu_new",
|
4 |
+
"architectures": [
|
5 |
+
"GPTOptim"
|
6 |
+
],
|
7 |
+
"attn_pdrop": 0.1,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "distributed/optimized-gpt2-500m--configuration_gpt_optimized.GPTOptimConfig",
|
10 |
+
"AutoModelForCausalLM": "distributed/optimized-gpt2-500m--modeling_gpt_optimized.GPTOptim"
|
11 |
+
},
|
12 |
+
"block_size": 1024,
|
13 |
+
"bos_token_id": 50256,
|
14 |
+
"embd_pdrop": 0.1,
|
15 |
+
"eos_token_id": 50256,
|
16 |
+
"initializer_range": 0.02,
|
17 |
+
"layer_norm_epsilon": 1e-05,
|
18 |
+
"model_type": "gpt_optimized",
|
19 |
+
"n_embd": 1280,
|
20 |
+
"n_head": 32,
|
21 |
+
"n_inner": null,
|
22 |
+
"n_layer": 48,
|
23 |
+
"n_positions": 1024,
|
24 |
+
"reorder_and_upcast_attn": false,
|
25 |
+
"resid_pdrop": 0.1,
|
26 |
+
"scale_attn_by_inverse_layer_idx": false,
|
27 |
+
"scale_attn_weights": true,
|
28 |
+
"summary_activation": null,
|
29 |
+
"summary_first_dropout": 0.1,
|
30 |
+
"summary_proj_to_labels": true,
|
31 |
+
"summary_type": "cls_index",
|
32 |
+
"summary_use_proj": true,
|
33 |
+
"torch_dtype": "float32",
|
34 |
+
"transformers_version": "4.39.3",
|
35 |
+
"use_cache": true,
|
36 |
+
"vocab_size": 50257
|
37 |
+
}
|
models--distributed--optimized-gpt2-1b/snapshots/fba79423a8549ee57e7ae92c54c57628e4a3b012/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:84bd38785e135d735130cb4633155169b1046946034dff6dd9275ef96649e85a
|
3 |
+
size 4040701744
|
models--distributed--optimized-gpt2-500m/blobs/03f1227b29a7a2051f79adb38cc603d8ab6a730b
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig, GPT2Config
|
2 |
+
from typing import List
|
3 |
+
|
4 |
+
|
5 |
+
class GPTOptimConfig(GPT2Config):
|
6 |
+
model_type = "gpt_optimized"
|
7 |
+
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
block_size: int = 1024, # max sequence length
|
11 |
+
vocab_size: int = 50257, # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
|
12 |
+
n_layer: int = 16, # number of layers
|
13 |
+
n_head: int = 16, # number of heads
|
14 |
+
n_embd: int = 1024, # embedding dimension
|
15 |
+
**kwargs,
|
16 |
+
):
|
17 |
+
super().__init__(**kwargs)
|
18 |
+
self.block_size = block_size
|
19 |
+
self.vocab_size = vocab_size
|
20 |
+
self.n_layer = n_layer
|
21 |
+
self.n_head = n_head
|
22 |
+
self.n_embd = n_embd
|
models--distributed--optimized-gpt2-500m/blobs/953c04829583cb1b5475c05e153bd1946e944cf6
ADDED
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from torch.nn import CrossEntropyLoss, functional as F
|
4 |
+
from transformers import PreTrainedModel, GPT2PreTrainedModel
|
5 |
+
from .configuration_gpt_optimized import GPTOptimConfig
|
6 |
+
from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions, BaseModelOutputWithPastAndCrossAttentions
|
7 |
+
from transformers.utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
|
8 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask_for_sdpa
|
9 |
+
from typing import Optional, Tuple, Union
|
10 |
+
|
11 |
+
_CHECKPOINT_FOR_DOC = "openai-community/gpt2"
|
12 |
+
_CONFIG_FOR_DOC = "GPT2Config"
|
13 |
+
|
14 |
+
GPT2_INPUTS_DOCSTRING = r"""
|
15 |
+
Args:
|
16 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
17 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
18 |
+
`past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
|
19 |
+
sequence tokens in the vocabulary.
|
20 |
+
|
21 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
22 |
+
`input_ids`.
|
23 |
+
|
24 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
25 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
26 |
+
|
27 |
+
[What are input IDs?](../glossary#input-ids)
|
28 |
+
past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
|
29 |
+
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
|
30 |
+
`past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
|
31 |
+
their past given to this model should not be passed as `input_ids` as they have already been computed.
|
32 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
33 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
34 |
+
|
35 |
+
- 1 for tokens that are **not masked**,
|
36 |
+
- 0 for tokens that are **masked**.
|
37 |
+
|
38 |
+
If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
|
39 |
+
`past_key_values`. In other words, the `attention_mask` always has to have the length:
|
40 |
+
`len(past_key_values) + len(input_ids)`
|
41 |
+
|
42 |
+
[What are attention masks?](../glossary#attention-mask)
|
43 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
|
44 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
45 |
+
1]`:
|
46 |
+
|
47 |
+
- 0 corresponds to a *sentence A* token,
|
48 |
+
- 1 corresponds to a *sentence B* token.
|
49 |
+
|
50 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
51 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
52 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
53 |
+
config.max_position_embeddings - 1]`.
|
54 |
+
|
55 |
+
[What are position IDs?](../glossary#position-ids)
|
56 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
57 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
58 |
+
|
59 |
+
- 1 indicates the head is **not masked**,
|
60 |
+
- 0 indicates the head is **masked**.
|
61 |
+
|
62 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
63 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
64 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
65 |
+
model's internal embedding lookup matrix.
|
66 |
+
|
67 |
+
If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
|
68 |
+
`past_key_values`).
|
69 |
+
use_cache (`bool`, *optional*):
|
70 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
71 |
+
`past_key_values`).
|
72 |
+
output_attentions (`bool`, *optional*):
|
73 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
74 |
+
tensors for more detail.
|
75 |
+
output_hidden_states (`bool`, *optional*):
|
76 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
77 |
+
more detail.
|
78 |
+
return_dict (`bool`, *optional*):
|
79 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
80 |
+
"""
|
81 |
+
|
82 |
+
class CausalSelfAttention(nn.Module):
|
83 |
+
|
84 |
+
def __init__(self, config):
|
85 |
+
super().__init__()
|
86 |
+
assert config.n_embd % config.n_head == 0
|
87 |
+
# key, query, value projections for all heads, but in a batch
|
88 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
89 |
+
# output projection
|
90 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
91 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
92 |
+
# regularization
|
93 |
+
self.n_head = config.n_head
|
94 |
+
self.n_embd = config.n_embd
|
95 |
+
|
96 |
+
def forward(self, x):
|
97 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
98 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
99 |
+
# nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
|
100 |
+
# e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
|
101 |
+
qkv = self.c_attn(x)
|
102 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
103 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
104 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
105 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
106 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True) # flash attention
|
107 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
108 |
+
# output projection
|
109 |
+
y = self.c_proj(y)
|
110 |
+
return y
|
111 |
+
|
112 |
+
class MLP(nn.Module):
|
113 |
+
|
114 |
+
def __init__(self, config):
|
115 |
+
super().__init__()
|
116 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
|
117 |
+
self.gelu = nn.GELU(approximate='tanh')
|
118 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
|
119 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
120 |
+
|
121 |
+
def forward(self, x):
|
122 |
+
x = self.c_fc(x)
|
123 |
+
x = self.gelu(x)
|
124 |
+
x = self.c_proj(x)
|
125 |
+
return x
|
126 |
+
|
127 |
+
class Block(nn.Module):
|
128 |
+
|
129 |
+
def __init__(self, config):
|
130 |
+
super().__init__()
|
131 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
132 |
+
self.attn = CausalSelfAttention(config)
|
133 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
134 |
+
self.mlp = MLP(config)
|
135 |
+
|
136 |
+
def forward(self, x):
|
137 |
+
x = x + self.attn(self.ln_1(x))
|
138 |
+
x = x + self.mlp(self.ln_2(x))
|
139 |
+
return x
|
140 |
+
|
141 |
+
class GPT(nn.Module):
|
142 |
+
|
143 |
+
def __init__(self, config):
|
144 |
+
super().__init__()
|
145 |
+
self.config = config
|
146 |
+
|
147 |
+
self.transformer = nn.ModuleDict(dict(
|
148 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
149 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
150 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
151 |
+
ln_f = nn.LayerNorm(config.n_embd),
|
152 |
+
))
|
153 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
154 |
+
|
155 |
+
# weight sharing scheme
|
156 |
+
self.transformer.wte.weight = self.lm_head.weight
|
157 |
+
|
158 |
+
# init params
|
159 |
+
self.apply(self._init_weights)
|
160 |
+
|
161 |
+
def _init_weights(self, module):
|
162 |
+
if isinstance(module, nn.Linear):
|
163 |
+
std = 0.02
|
164 |
+
if hasattr(module, 'NANOGPT_SCALE_INIT'):
|
165 |
+
std *= (2 * self.config.n_layer) ** -0.5
|
166 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
167 |
+
if module.bias is not None:
|
168 |
+
torch.nn.init.zeros_(module.bias)
|
169 |
+
elif isinstance(module, nn.Embedding):
|
170 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
171 |
+
|
172 |
+
class GPTOptim(GPT2PreTrainedModel):
|
173 |
+
config_class = GPTOptimConfig
|
174 |
+
|
175 |
+
def __init__(self, config):
|
176 |
+
super().__init__(config)
|
177 |
+
self.model = GPT(
|
178 |
+
config
|
179 |
+
)
|
180 |
+
self.config = config
|
181 |
+
|
182 |
+
def forward(self, input_ids, labels=None):
|
183 |
+
# input_ids is of shape (B, T)
|
184 |
+
B, T = input_ids.size()
|
185 |
+
assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
|
186 |
+
# forward the token and posisition embeddings
|
187 |
+
pos = torch.arange(0, T, dtype=torch.long, device=input_ids.device) # shape (T)
|
188 |
+
pos_emb = self.model.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
|
189 |
+
tok_emb = self.model.transformer.wte(input_ids) # token embeddings of shape (B, T, n_embd)
|
190 |
+
x = tok_emb + pos_emb
|
191 |
+
# forward the blocks of the transformer
|
192 |
+
for block in self.model.transformer.h:
|
193 |
+
x = block(x)
|
194 |
+
# forward the final layernorm and the classifier
|
195 |
+
x = self.model.transformer.ln_f(x)
|
196 |
+
logits = self.model.lm_head(x) # (B, T, vocab_size)
|
197 |
+
loss = None
|
198 |
+
if labels is not None:
|
199 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=self.config.eos_token_id)
|
200 |
+
return logits, loss
|
models--distributed--optimized-gpt2-500m/refs/main
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
9bd57ae4e2ba48cf4c123cdc9eab01af3845ba28
|
models--distributed--optimized-gpt2-500m/snapshots/9bd57ae4e2ba48cf4c123cdc9eab01af3845ba28/configuration_gpt_optimized.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig, GPT2Config
|
2 |
+
from typing import List
|
3 |
+
|
4 |
+
|
5 |
+
class GPTOptimConfig(GPT2Config):
|
6 |
+
model_type = "gpt_optimized"
|
7 |
+
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
block_size: int = 1024, # max sequence length
|
11 |
+
vocab_size: int = 50257, # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
|
12 |
+
n_layer: int = 16, # number of layers
|
13 |
+
n_head: int = 16, # number of heads
|
14 |
+
n_embd: int = 1024, # embedding dimension
|
15 |
+
**kwargs,
|
16 |
+
):
|
17 |
+
super().__init__(**kwargs)
|
18 |
+
self.block_size = block_size
|
19 |
+
self.vocab_size = vocab_size
|
20 |
+
self.n_layer = n_layer
|
21 |
+
self.n_head = n_head
|
22 |
+
self.n_embd = n_embd
|
models--distributed--optimized-gpt2-500m/snapshots/9bd57ae4e2ba48cf4c123cdc9eab01af3845ba28/modeling_gpt_optimized.py
ADDED
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from torch.nn import CrossEntropyLoss, functional as F
|
4 |
+
from transformers import PreTrainedModel, GPT2PreTrainedModel
|
5 |
+
from .configuration_gpt_optimized import GPTOptimConfig
|
6 |
+
from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions, BaseModelOutputWithPastAndCrossAttentions
|
7 |
+
from transformers.utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
|
8 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask_for_sdpa
|
9 |
+
from typing import Optional, Tuple, Union
|
10 |
+
|
11 |
+
_CHECKPOINT_FOR_DOC = "openai-community/gpt2"
|
12 |
+
_CONFIG_FOR_DOC = "GPT2Config"
|
13 |
+
|
14 |
+
GPT2_INPUTS_DOCSTRING = r"""
|
15 |
+
Args:
|
16 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
17 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
18 |
+
`past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
|
19 |
+
sequence tokens in the vocabulary.
|
20 |
+
|
21 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
22 |
+
`input_ids`.
|
23 |
+
|
24 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
25 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
26 |
+
|
27 |
+
[What are input IDs?](../glossary#input-ids)
|
28 |
+
past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
|
29 |
+
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
|
30 |
+
`past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
|
31 |
+
their past given to this model should not be passed as `input_ids` as they have already been computed.
|
32 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
33 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
34 |
+
|
35 |
+
- 1 for tokens that are **not masked**,
|
36 |
+
- 0 for tokens that are **masked**.
|
37 |
+
|
38 |
+
If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
|
39 |
+
`past_key_values`. In other words, the `attention_mask` always has to have the length:
|
40 |
+
`len(past_key_values) + len(input_ids)`
|
41 |
+
|
42 |
+
[What are attention masks?](../glossary#attention-mask)
|
43 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
|
44 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
45 |
+
1]`:
|
46 |
+
|
47 |
+
- 0 corresponds to a *sentence A* token,
|
48 |
+
- 1 corresponds to a *sentence B* token.
|
49 |
+
|
50 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
51 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
52 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
53 |
+
config.max_position_embeddings - 1]`.
|
54 |
+
|
55 |
+
[What are position IDs?](../glossary#position-ids)
|
56 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
57 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
58 |
+
|
59 |
+
- 1 indicates the head is **not masked**,
|
60 |
+
- 0 indicates the head is **masked**.
|
61 |
+
|
62 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
63 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
64 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
65 |
+
model's internal embedding lookup matrix.
|
66 |
+
|
67 |
+
If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
|
68 |
+
`past_key_values`).
|
69 |
+
use_cache (`bool`, *optional*):
|
70 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
71 |
+
`past_key_values`).
|
72 |
+
output_attentions (`bool`, *optional*):
|
73 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
74 |
+
tensors for more detail.
|
75 |
+
output_hidden_states (`bool`, *optional*):
|
76 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
77 |
+
more detail.
|
78 |
+
return_dict (`bool`, *optional*):
|
79 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
80 |
+
"""
|
81 |
+
|
82 |
+
class CausalSelfAttention(nn.Module):
|
83 |
+
|
84 |
+
def __init__(self, config):
|
85 |
+
super().__init__()
|
86 |
+
assert config.n_embd % config.n_head == 0
|
87 |
+
# key, query, value projections for all heads, but in a batch
|
88 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
89 |
+
# output projection
|
90 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
91 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
92 |
+
# regularization
|
93 |
+
self.n_head = config.n_head
|
94 |
+
self.n_embd = config.n_embd
|
95 |
+
|
96 |
+
def forward(self, x):
|
97 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
98 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
99 |
+
# nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
|
100 |
+
# e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
|
101 |
+
qkv = self.c_attn(x)
|
102 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
103 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
104 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
105 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
106 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True) # flash attention
|
107 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
108 |
+
# output projection
|
109 |
+
y = self.c_proj(y)
|
110 |
+
return y
|
111 |
+
|
112 |
+
class MLP(nn.Module):
|
113 |
+
|
114 |
+
def __init__(self, config):
|
115 |
+
super().__init__()
|
116 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
|
117 |
+
self.gelu = nn.GELU(approximate='tanh')
|
118 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
|
119 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
120 |
+
|
121 |
+
def forward(self, x):
|
122 |
+
x = self.c_fc(x)
|
123 |
+
x = self.gelu(x)
|
124 |
+
x = self.c_proj(x)
|
125 |
+
return x
|
126 |
+
|
127 |
+
class Block(nn.Module):
|
128 |
+
|
129 |
+
def __init__(self, config):
|
130 |
+
super().__init__()
|
131 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
132 |
+
self.attn = CausalSelfAttention(config)
|
133 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
134 |
+
self.mlp = MLP(config)
|
135 |
+
|
136 |
+
def forward(self, x):
|
137 |
+
x = x + self.attn(self.ln_1(x))
|
138 |
+
x = x + self.mlp(self.ln_2(x))
|
139 |
+
return x
|
140 |
+
|
141 |
+
class GPT(nn.Module):
|
142 |
+
|
143 |
+
def __init__(self, config):
|
144 |
+
super().__init__()
|
145 |
+
self.config = config
|
146 |
+
|
147 |
+
self.transformer = nn.ModuleDict(dict(
|
148 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
149 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
150 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
151 |
+
ln_f = nn.LayerNorm(config.n_embd),
|
152 |
+
))
|
153 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
154 |
+
|
155 |
+
# weight sharing scheme
|
156 |
+
self.transformer.wte.weight = self.lm_head.weight
|
157 |
+
|
158 |
+
# init params
|
159 |
+
self.apply(self._init_weights)
|
160 |
+
|
161 |
+
def _init_weights(self, module):
|
162 |
+
if isinstance(module, nn.Linear):
|
163 |
+
std = 0.02
|
164 |
+
if hasattr(module, 'NANOGPT_SCALE_INIT'):
|
165 |
+
std *= (2 * self.config.n_layer) ** -0.5
|
166 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
167 |
+
if module.bias is not None:
|
168 |
+
torch.nn.init.zeros_(module.bias)
|
169 |
+
elif isinstance(module, nn.Embedding):
|
170 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
171 |
+
|
172 |
+
class GPTOptim(GPT2PreTrainedModel):
|
173 |
+
config_class = GPTOptimConfig
|
174 |
+
|
175 |
+
def __init__(self, config):
|
176 |
+
super().__init__(config)
|
177 |
+
self.model = GPT(
|
178 |
+
config
|
179 |
+
)
|
180 |
+
self.config = config
|
181 |
+
|
182 |
+
def forward(self, input_ids, labels=None):
|
183 |
+
# input_ids is of shape (B, T)
|
184 |
+
B, T = input_ids.size()
|
185 |
+
assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
|
186 |
+
# forward the token and posisition embeddings
|
187 |
+
pos = torch.arange(0, T, dtype=torch.long, device=input_ids.device) # shape (T)
|
188 |
+
pos_emb = self.model.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
|
189 |
+
tok_emb = self.model.transformer.wte(input_ids) # token embeddings of shape (B, T, n_embd)
|
190 |
+
x = tok_emb + pos_emb
|
191 |
+
# forward the blocks of the transformer
|
192 |
+
for block in self.model.transformer.h:
|
193 |
+
x = block(x)
|
194 |
+
# forward the final layernorm and the classifier
|
195 |
+
x = self.model.transformer.ln_f(x)
|
196 |
+
logits = self.model.lm_head(x) # (B, T, vocab_size)
|
197 |
+
loss = None
|
198 |
+
if labels is not None:
|
199 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=self.config.eos_token_id)
|
200 |
+
return logits, loss
|
smash_config.json
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"comp_cgenerate_active": false,
|
3 |
+
"comp_ctranslate_active": false,
|
4 |
+
"comp_cwhisper_active": false,
|
5 |
+
"comp_diffusers2_active": false,
|
6 |
+
"comp_ifw_active": false,
|
7 |
+
"comp_onediff_active": false,
|
8 |
+
"comp_step_caching_active": false,
|
9 |
+
"comp_torch_compile_active": false,
|
10 |
+
"comp_ws2t_active": false,
|
11 |
+
"comp_x-fast_active": false,
|
12 |
+
"prune_torch-structured_active": false,
|
13 |
+
"quant_aqlm_active": false,
|
14 |
+
"quant_awq_active": false,
|
15 |
+
"quant_gptq_active": false,
|
16 |
+
"quant_half_active": false,
|
17 |
+
"quant_hqq_active": false,
|
18 |
+
"quant_llm-int8_active": true,
|
19 |
+
"quant_quanto_active": false,
|
20 |
+
"quant_torch_dynamic_active": false,
|
21 |
+
"quant_torch_static_active": false,
|
22 |
+
"quant_llm-int8_compute_dtype": "bfloat16",
|
23 |
+
"quant_llm-int8_double_quant": false,
|
24 |
+
"quant_llm-int8_enable_fp32_cpu_offload": false,
|
25 |
+
"quant_llm-int8_has_fp16_weight": false,
|
26 |
+
"quant_llm-int8_quant_type": "fp4",
|
27 |
+
"quant_llm-int8_threshold": 6.0,
|
28 |
+
"quant_llm-int8_weight_bits": 8,
|
29 |
+
"max_batch_size": 1,
|
30 |
+
"device": "cuda",
|
31 |
+
"cache_dir": "/covalent/.cache/models/tmpk1t5rgu6",
|
32 |
+
"task": "",
|
33 |
+
"save_load_fn": "bitsandbytes",
|
34 |
+
"save_load_fn_args": {
|
35 |
+
"weight_quantization_bits": "param.dtype"
|
36 |
+
}
|
37 |
+
}
|