This view is limited to 50 files because it contains too many changes.  See the raw diff here.
Files changed (50) hide show
  1. README.md +127 -0
  2. added_tokens.json +40 -0
  3. all_results.json +21 -0
  4. checkpoint-5000/added_tokens.json +40 -0
  5. checkpoint-5000/config.json +34 -0
  6. checkpoint-5000/configuration_phi.py +193 -0
  7. checkpoint-5000/generation_config.json +4 -0
  8. checkpoint-5000/global_step5000/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
  9. checkpoint-5000/global_step5000/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
  10. checkpoint-5000/global_step5000/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt +3 -0
  11. checkpoint-5000/global_step5000/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt +3 -0
  12. checkpoint-5000/global_step5000/zero_pp_rank_0_mp_rank_00_model_states.pt +3 -0
  13. checkpoint-5000/global_step5000/zero_pp_rank_1_mp_rank_00_model_states.pt +3 -0
  14. checkpoint-5000/global_step5000/zero_pp_rank_2_mp_rank_00_model_states.pt +3 -0
  15. checkpoint-5000/global_step5000/zero_pp_rank_3_mp_rank_00_model_states.pt +3 -0
  16. checkpoint-5000/latest +1 -0
  17. checkpoint-5000/merges.txt +0 -0
  18. checkpoint-5000/model.safetensors +3 -0
  19. checkpoint-5000/modeling_phi.py +1369 -0
  20. checkpoint-5000/rng_state_0.pth +3 -0
  21. checkpoint-5000/rng_state_1.pth +3 -0
  22. checkpoint-5000/rng_state_2.pth +3 -0
  23. checkpoint-5000/rng_state_3.pth +3 -0
  24. checkpoint-5000/scheduler.pt +3 -0
  25. checkpoint-5000/special_tokens_map.json +18 -0
  26. checkpoint-5000/tokenizer.json +0 -0
  27. checkpoint-5000/tokenizer_config.json +325 -0
  28. checkpoint-5000/trainer_state.json +0 -0
  29. checkpoint-5000/training_args.bin +3 -0
  30. checkpoint-5000/vocab.json +0 -0
  31. checkpoint-5000/zero_to_fp32.py +587 -0
  32. checkpoint-5500/added_tokens.json +40 -0
  33. checkpoint-5500/config.json +34 -0
  34. checkpoint-5500/configuration_phi.py +193 -0
  35. checkpoint-5500/generation_config.json +4 -0
  36. checkpoint-5500/global_step5500/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
  37. checkpoint-5500/global_step5500/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
  38. checkpoint-5500/global_step5500/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt +3 -0
  39. checkpoint-5500/global_step5500/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt +3 -0
  40. checkpoint-5500/global_step5500/zero_pp_rank_0_mp_rank_00_model_states.pt +3 -0
  41. checkpoint-5500/global_step5500/zero_pp_rank_1_mp_rank_00_model_states.pt +3 -0
  42. checkpoint-5500/global_step5500/zero_pp_rank_2_mp_rank_00_model_states.pt +3 -0
  43. checkpoint-5500/global_step5500/zero_pp_rank_3_mp_rank_00_model_states.pt +3 -0
  44. checkpoint-5500/latest +1 -0
  45. checkpoint-5500/merges.txt +0 -0
  46. checkpoint-5500/model.safetensors +3 -0
  47. checkpoint-5500/modeling_phi.py +1369 -0
  48. checkpoint-5500/rng_state_0.pth +3 -0
  49. checkpoint-5500/rng_state_1.pth +3 -0
  50. checkpoint-5500/rng_state_2.pth +3 -0
README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: microsoft/phi-1_5
3
+ tags:
4
+ - alignment-handbook
5
+ - generated_from_trainer
6
+ datasets:
7
+ - argilla/ultrafeedback-binarized-preferences-cleaned
8
+ model-index:
9
+ - name: phi_1_5_dpo_ep6
10
+ results: []
11
+ ---
12
+
13
+ <!-- This model card has been generated automatically according to the information the Trainer had access to. You
14
+ should probably proofread and complete it, then remove this comment. -->
15
+
16
+ # phi_1_5_dpo_ep6
17
+
18
+ This model is a fine-tuned version of [/home/work/saic-llm-2023/checkpoints/microsoft/phi-1_5](https://huggingface.co//home/work/saic-llm-2023/checkpoints/microsoft/phi-1_5) on the argilla/ultrafeedback-binarized-preferences-cleaned dataset.
19
+ It achieves the following results on the evaluation set:
20
+ - Loss: 0.4748
21
+ - Rewards/chosen: -0.9135
22
+ - Rewards/rejected: -1.9448
23
+ - Rewards/accuracies: 0.7937
24
+ - Rewards/margins: 1.0313
25
+ - Logps/rejected: -618.5530
26
+ - Logps/chosen: -634.6866
27
+ - Logits/rejected: 3.4318
28
+ - Logits/chosen: 3.4052
29
+
30
+ ## Model description
31
+
32
+ More information needed
33
+
34
+ ## Intended uses & limitations
35
+
36
+ More information needed
37
+
38
+ ## Training and evaluation data
39
+
40
+ More information needed
41
+
42
+ ## Training procedure
43
+
44
+ ### Training hyperparameters
45
+
46
+ The following hyperparameters were used during training:
47
+ - learning_rate: 5e-07
48
+ - train_batch_size: 8
49
+ - eval_batch_size: 8
50
+ - seed: 42
51
+ - distributed_type: multi-GPU
52
+ - num_devices: 4
53
+ - gradient_accumulation_steps: 2
54
+ - total_train_batch_size: 64
55
+ - total_eval_batch_size: 32
56
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
57
+ - lr_scheduler_type: cosine
58
+ - lr_scheduler_warmup_steps: 100
59
+ - num_epochs: 6
60
+
61
+ ### Training results
62
+
63
+ | Training Loss | Epoch | Step | Validation Loss | Rewards/chosen | Rewards/rejected | Rewards/accuracies | Rewards/margins | Logps/rejected | Logps/chosen | Logits/rejected | Logits/chosen |
64
+ |:-------------:|:-----:|:----:|:---------------:|:--------------:|:----------------:|:------------------:|:---------------:|:--------------:|:------------:|:---------------:|:-------------:|
65
+ | 0.6881 | 0.11 | 100 | 0.6856 | 0.0468 | 0.0298 | 0.7024 | 0.0170 | -421.0949 | -538.6564 | 4.8883 | 4.6646 |
66
+ | 0.6692 | 0.22 | 200 | 0.6642 | 0.1742 | 0.0988 | 0.7123 | 0.0754 | -414.1955 | -525.9189 | 4.8718 | 4.6370 |
67
+ | 0.6368 | 0.33 | 300 | 0.6442 | 0.2557 | 0.1261 | 0.7083 | 0.1296 | -411.4657 | -517.7680 | 4.8407 | 4.5968 |
68
+ | 0.6283 | 0.43 | 400 | 0.6283 | 0.2608 | 0.0812 | 0.7083 | 0.1795 | -415.9522 | -517.2609 | 4.7629 | 4.5156 |
69
+ | 0.6052 | 0.54 | 500 | 0.6132 | 0.1429 | -0.0998 | 0.7103 | 0.2427 | -434.0545 | -529.0491 | 4.5516 | 4.3153 |
70
+ | 0.5923 | 0.65 | 600 | 0.6008 | 0.1425 | -0.1628 | 0.7123 | 0.3053 | -440.3539 | -529.0887 | 4.4588 | 4.2289 |
71
+ | 0.5899 | 0.76 | 700 | 0.5880 | 0.0755 | -0.2915 | 0.7083 | 0.3670 | -453.2271 | -535.7857 | 4.3444 | 4.1349 |
72
+ | 0.558 | 0.87 | 800 | 0.5715 | -0.0965 | -0.5304 | 0.7262 | 0.4339 | -477.1144 | -552.9822 | 4.2704 | 4.0642 |
73
+ | 0.5495 | 0.98 | 900 | 0.5552 | -0.2658 | -0.7677 | 0.7341 | 0.5019 | -500.8484 | -569.9210 | 4.1976 | 4.0015 |
74
+ | 0.5124 | 1.09 | 1000 | 0.5473 | -0.3871 | -0.9394 | 0.7321 | 0.5523 | -518.0129 | -582.0427 | 4.0959 | 3.9125 |
75
+ | 0.5322 | 1.19 | 1100 | 0.5400 | -0.3641 | -0.9463 | 0.7579 | 0.5821 | -518.7011 | -579.7518 | 4.0436 | 3.8715 |
76
+ | 0.5281 | 1.3 | 1200 | 0.5344 | -0.5340 | -1.1498 | 0.7460 | 0.6158 | -539.0579 | -596.7365 | 3.9368 | 3.7842 |
77
+ | 0.5063 | 1.41 | 1300 | 0.5297 | -0.3754 | -0.9975 | 0.7579 | 0.6221 | -523.8221 | -580.8731 | 4.0135 | 3.8499 |
78
+ | 0.5073 | 1.52 | 1400 | 0.5216 | -0.3819 | -1.0300 | 0.7758 | 0.6481 | -527.0738 | -581.5236 | 3.9401 | 3.7846 |
79
+ | 0.5156 | 1.63 | 1500 | 0.5177 | -0.5748 | -1.2824 | 0.7560 | 0.7077 | -552.3166 | -600.8123 | 3.7868 | 3.6678 |
80
+ | 0.5072 | 1.74 | 1600 | 0.5138 | -0.4973 | -1.2122 | 0.7798 | 0.7149 | -545.2914 | -593.0637 | 3.7791 | 3.6614 |
81
+ | 0.4908 | 1.85 | 1700 | 0.5077 | -0.5479 | -1.2972 | 0.7798 | 0.7493 | -553.7918 | -598.1292 | 3.7893 | 3.6696 |
82
+ | 0.5109 | 1.95 | 1800 | 0.5068 | -0.6157 | -1.3930 | 0.7758 | 0.7773 | -563.3733 | -604.9089 | 3.7679 | 3.6556 |
83
+ | 0.4779 | 2.06 | 1900 | 0.5005 | -0.6247 | -1.4169 | 0.7738 | 0.7922 | -565.7673 | -605.8088 | 3.7118 | 3.6062 |
84
+ | 0.4833 | 2.17 | 2000 | 0.4992 | -0.6841 | -1.5026 | 0.7698 | 0.8185 | -574.3334 | -611.7432 | 3.6739 | 3.5849 |
85
+ | 0.4879 | 2.28 | 2100 | 0.4967 | -0.8128 | -1.6654 | 0.7698 | 0.8526 | -590.6146 | -624.6127 | 3.5692 | 3.5030 |
86
+ | 0.4645 | 2.39 | 2200 | 0.4927 | -0.6969 | -1.5365 | 0.7857 | 0.8396 | -577.7230 | -613.0289 | 3.6647 | 3.5772 |
87
+ | 0.4587 | 2.5 | 2300 | 0.4936 | -0.6024 | -1.4533 | 0.7778 | 0.8509 | -569.4068 | -603.5743 | 3.6615 | 3.5790 |
88
+ | 0.437 | 2.61 | 2400 | 0.4921 | -0.8826 | -1.7724 | 0.7738 | 0.8897 | -601.3099 | -631.5984 | 3.4903 | 3.4343 |
89
+ | 0.4204 | 2.71 | 2500 | 0.4890 | -0.8338 | -1.7338 | 0.7758 | 0.8999 | -597.4498 | -626.7175 | 3.5447 | 3.4804 |
90
+ | 0.467 | 2.82 | 2600 | 0.4865 | -0.5910 | -1.4516 | 0.7877 | 0.8606 | -569.2333 | -602.4326 | 3.5690 | 3.5000 |
91
+ | 0.458 | 2.93 | 2700 | 0.4861 | -0.7666 | -1.6726 | 0.7837 | 0.9059 | -591.3298 | -620.0014 | 3.5208 | 3.4579 |
92
+ | 0.462 | 3.04 | 2800 | 0.4844 | -0.7109 | -1.6145 | 0.7917 | 0.9037 | -585.5269 | -614.4227 | 3.5553 | 3.4954 |
93
+ | 0.4258 | 3.15 | 2900 | 0.4888 | -0.9814 | -1.9414 | 0.7817 | 0.9600 | -618.2142 | -641.4772 | 3.4761 | 3.4227 |
94
+ | 0.4219 | 3.26 | 3000 | 0.4856 | -0.8858 | -1.8323 | 0.7937 | 0.9465 | -607.3071 | -631.9181 | 3.4895 | 3.4362 |
95
+ | 0.4295 | 3.37 | 3100 | 0.4823 | -0.8140 | -1.7651 | 0.7976 | 0.9511 | -600.5797 | -624.7327 | 3.4880 | 3.4357 |
96
+ | 0.4268 | 3.47 | 3200 | 0.4800 | -0.8592 | -1.8282 | 0.7976 | 0.9690 | -606.8929 | -629.2567 | 3.4536 | 3.4126 |
97
+ | 0.4338 | 3.58 | 3300 | 0.4785 | -0.8784 | -1.8458 | 0.7956 | 0.9674 | -608.6551 | -631.1731 | 3.4471 | 3.4096 |
98
+ | 0.4297 | 3.69 | 3400 | 0.4774 | -0.9026 | -1.8929 | 0.7956 | 0.9903 | -613.3634 | -633.5962 | 3.4710 | 3.4326 |
99
+ | 0.4133 | 3.8 | 3500 | 0.4785 | -0.9173 | -1.9072 | 0.7937 | 0.9899 | -614.7964 | -635.0674 | 3.4610 | 3.4232 |
100
+ | 0.4275 | 3.91 | 3600 | 0.4794 | -1.0209 | -2.0380 | 0.7837 | 1.0171 | -627.8748 | -645.4227 | 3.4635 | 3.4227 |
101
+ | 0.4224 | 4.02 | 3700 | 0.4784 | -0.9130 | -1.9086 | 0.7937 | 0.9955 | -614.9320 | -634.6396 | 3.4812 | 3.4400 |
102
+ | 0.4101 | 4.13 | 3800 | 0.4773 | -0.9474 | -1.9571 | 0.7877 | 1.0097 | -619.7819 | -638.0772 | 3.4569 | 3.4225 |
103
+ | 0.4295 | 4.23 | 3900 | 0.4790 | -0.9893 | -2.0096 | 0.7956 | 1.0203 | -625.0361 | -642.2666 | 3.4290 | 3.3998 |
104
+ | 0.4162 | 4.34 | 4000 | 0.4769 | -0.9682 | -1.9897 | 0.7956 | 1.0215 | -623.0465 | -640.1562 | 3.4342 | 3.4040 |
105
+ | 0.425 | 4.45 | 4100 | 0.4759 | -0.9553 | -1.9788 | 0.7917 | 1.0236 | -621.9555 | -638.8621 | 3.4580 | 3.4237 |
106
+ | 0.4155 | 4.56 | 4200 | 0.4778 | -1.0183 | -2.0573 | 0.7917 | 1.0390 | -629.8077 | -645.1696 | 3.4277 | 3.3981 |
107
+ | 0.4311 | 4.67 | 4300 | 0.4765 | -0.9712 | -2.0065 | 0.7897 | 1.0353 | -624.7266 | -640.4598 | 3.4413 | 3.4107 |
108
+ | 0.41 | 4.78 | 4400 | 0.4768 | -0.9764 | -2.0101 | 0.7917 | 1.0337 | -625.0818 | -640.9733 | 3.4387 | 3.4081 |
109
+ | 0.4127 | 4.89 | 4500 | 0.4749 | -0.9599 | -1.9994 | 0.7937 | 1.0395 | -624.0168 | -639.3277 | 3.4453 | 3.4160 |
110
+ | 0.453 | 4.99 | 4600 | 0.4748 | -0.9231 | -1.9528 | 0.7917 | 1.0297 | -619.3519 | -635.6462 | 3.4444 | 3.4142 |
111
+ | 0.4035 | 5.1 | 4700 | 0.4754 | -0.9561 | -1.9965 | 0.7897 | 1.0403 | -623.7211 | -638.9504 | 3.4293 | 3.4019 |
112
+ | 0.4225 | 5.21 | 4800 | 0.4753 | -0.9471 | -1.9855 | 0.7877 | 1.0384 | -622.6226 | -638.0461 | 3.4359 | 3.4077 |
113
+ | 0.3941 | 5.32 | 4900 | 0.4754 | -0.9579 | -1.9978 | 0.7897 | 1.0400 | -623.8593 | -639.1230 | 3.4282 | 3.4012 |
114
+ | 0.4093 | 5.43 | 5000 | 0.4748 | -0.9135 | -1.9448 | 0.7937 | 1.0313 | -618.5530 | -634.6866 | 3.4318 | 3.4052 |
115
+ | 0.3902 | 5.54 | 5100 | 0.4754 | -0.9457 | -1.9815 | 0.7956 | 1.0358 | -622.2274 | -637.9056 | 3.4281 | 3.4014 |
116
+ | 0.3795 | 5.65 | 5200 | 0.4753 | -0.9484 | -1.9852 | 0.7897 | 1.0368 | -622.5895 | -638.1724 | 3.4253 | 3.3988 |
117
+ | 0.3915 | 5.75 | 5300 | 0.4754 | -0.9571 | -1.9957 | 0.7956 | 1.0386 | -623.6450 | -639.0427 | 3.4242 | 3.3979 |
118
+ | 0.4075 | 5.86 | 5400 | 0.4756 | -0.9566 | -1.9949 | 0.7877 | 1.0383 | -623.5674 | -638.9974 | 3.4221 | 3.3962 |
119
+ | 0.4293 | 5.97 | 5500 | 0.4756 | -0.9571 | -1.9948 | 0.7897 | 1.0377 | -623.5548 | -639.0446 | 3.4230 | 3.3964 |
120
+
121
+
122
+ ### Framework versions
123
+
124
+ - Transformers 4.38.0
125
+ - Pytorch 2.1.2+cu118
126
+ - Datasets 2.17.1
127
+ - Tokenizers 0.15.0
added_tokens.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "\t\t": 50294,
3
+ "\t\t\t": 50293,
4
+ "\t\t\t\t": 50292,
5
+ "\t\t\t\t\t": 50291,
6
+ "\t\t\t\t\t\t": 50290,
7
+ "\t\t\t\t\t\t\t": 50289,
8
+ "\t\t\t\t\t\t\t\t": 50288,
9
+ "\t\t\t\t\t\t\t\t\t": 50287,
10
+ " ": 50286,
11
+ " ": 50285,
12
+ " ": 50284,
13
+ " ": 50283,
14
+ " ": 50282,
15
+ " ": 50281,
16
+ " ": 50280,
17
+ " ": 50279,
18
+ " ": 50278,
19
+ " ": 50277,
20
+ " ": 50276,
21
+ " ": 50275,
22
+ " ": 50274,
23
+ " ": 50273,
24
+ " ": 50272,
25
+ " ": 50271,
26
+ " ": 50270,
27
+ " ": 50269,
28
+ " ": 50268,
29
+ " ": 50267,
30
+ " ": 50266,
31
+ " ": 50265,
32
+ " ": 50264,
33
+ " ": 50263,
34
+ " ": 50262,
35
+ " ": 50261,
36
+ " ": 50260,
37
+ " ": 50259,
38
+ " ": 50258,
39
+ " ": 50257
40
+ }
all_results.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 6.0,
3
+ "eval_logits/chosen": 3.4052021503448486,
4
+ "eval_logits/rejected": 3.43179988861084,
5
+ "eval_logps/chosen": -634.6866455078125,
6
+ "eval_logps/rejected": -618.552978515625,
7
+ "eval_loss": 0.4747713804244995,
8
+ "eval_rewards/accuracies": 0.7936508059501648,
9
+ "eval_rewards/chosen": -0.913497269153595,
10
+ "eval_rewards/margins": 1.0312875509262085,
11
+ "eval_rewards/rejected": -1.9447849988937378,
12
+ "eval_runtime": 203.6628,
13
+ "eval_samples": 2000,
14
+ "eval_samples_per_second": 9.82,
15
+ "eval_steps_per_second": 0.309,
16
+ "train_loss": 0.4762616708060343,
17
+ "train_runtime": 91379.3933,
18
+ "train_samples": 58917,
19
+ "train_samples_per_second": 3.869,
20
+ "train_steps_per_second": 0.06
21
+ }
checkpoint-5000/added_tokens.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "\t\t": 50294,
3
+ "\t\t\t": 50293,
4
+ "\t\t\t\t": 50292,
5
+ "\t\t\t\t\t": 50291,
6
+ "\t\t\t\t\t\t": 50290,
7
+ "\t\t\t\t\t\t\t": 50289,
8
+ "\t\t\t\t\t\t\t\t": 50288,
9
+ "\t\t\t\t\t\t\t\t\t": 50287,
10
+ " ": 50286,
11
+ " ": 50285,
12
+ " ": 50284,
13
+ " ": 50283,
14
+ " ": 50282,
15
+ " ": 50281,
16
+ " ": 50280,
17
+ " ": 50279,
18
+ " ": 50278,
19
+ " ": 50277,
20
+ " ": 50276,
21
+ " ": 50275,
22
+ " ": 50274,
23
+ " ": 50273,
24
+ " ": 50272,
25
+ " ": 50271,
26
+ " ": 50270,
27
+ " ": 50269,
28
+ " ": 50268,
29
+ " ": 50267,
30
+ " ": 50266,
31
+ " ": 50265,
32
+ " ": 50264,
33
+ " ": 50263,
34
+ " ": 50262,
35
+ " ": 50261,
36
+ " ": 50260,
37
+ " ": 50259,
38
+ " ": 50258,
39
+ " ": 50257
40
+ }
checkpoint-5000/config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "microsoft/phi-1_5",
3
+ "architectures": [
4
+ "PhiForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi.PhiConfig",
9
+ "AutoModelForCausalLM": "modeling_phi.PhiForCausalLM"
10
+ },
11
+ "bos_token_id": null,
12
+ "embd_pdrop": 0.0,
13
+ "eos_token_id": null,
14
+ "hidden_act": "gelu_new",
15
+ "hidden_size": 2048,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 8192,
18
+ "layer_norm_eps": 1e-05,
19
+ "max_position_embeddings": 2048,
20
+ "model_type": "phi",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 24,
23
+ "num_key_value_heads": 32,
24
+ "partial_rotary_factor": 0.5,
25
+ "qk_layernorm": false,
26
+ "resid_pdrop": 0.0,
27
+ "rope_scaling": null,
28
+ "rope_theta": 10000.0,
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.38.0",
32
+ "use_cache": false,
33
+ "vocab_size": 51200
34
+ }
checkpoint-5000/configuration_phi.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ Phi model configuration"""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/phi-1_5": "https://huggingface.co/microsoft/phi-1_5/resolve/main/config.json",
27
+ }
28
+
29
+
30
+ class PhiConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the Phi
35
+ [microsoft/phi-1](https://huggingface.co/microsoft/phi-1).
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 51200):
42
+ Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`PhiModel`].
44
+ hidden_size (`int`, *optional*, defaults to 2048):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 8192):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 24):
49
+ Number of hidden layers in the Transformer decoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
61
+ Dropout probability for mlp outputs.
62
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
63
+ The dropout ratio for the embeddings.
64
+ attention_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio after computing the attention scores.
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
70
+ tokens.
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
74
+ The epsilon used by the rms normalization layers.
75
+ use_cache (`bool`, *optional*, defaults to `True`):
76
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
77
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ rope_scaling (`Dict`, *optional*):
83
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
84
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
85
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
86
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
87
+ these scaling strategies behave:
88
+ https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
89
+ is an experimental feature, subject to breaking API changes in future versions.
90
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
91
+ Percentage of the query and keys which will have rotary embedding.
92
+ qk_layernorm (`bool`, *optional*, defaults to `False`):
93
+ Whether or not to normalize the Queries and Keys after projecting the hidden states.
94
+ bos_token_id (`int`, *optional*, defaults to 1):
95
+ Denotes beginning of sequences token id.
96
+ eos_token_id (`int`, *optional*, defaults to 2):
97
+ Denotes end of sequences token id.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import PhiModel, PhiConfig
103
+
104
+ >>> # Initializing a Phi-1 style configuration
105
+ >>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = PhiModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=51200,
120
+ hidden_size=2048,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=24,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="gelu_new",
129
+ max_position_embeddings=2048,
130
+ initializer_range=0.02,
131
+ layer_norm_eps=1e-5,
132
+ use_cache=True,
133
+ tie_word_embeddings=False,
134
+ rope_theta=10000.0,
135
+ rope_scaling=None,
136
+ partial_rotary_factor=0.5,
137
+ qk_layernorm=False,
138
+ bos_token_id=1,
139
+ eos_token_id=2,
140
+ **kwargs,
141
+ ):
142
+ self.vocab_size = vocab_size
143
+ self.hidden_size = hidden_size
144
+ self.intermediate_size = intermediate_size
145
+ self.num_hidden_layers = num_hidden_layers
146
+ self.num_attention_heads = num_attention_heads
147
+
148
+ if num_key_value_heads is None:
149
+ num_key_value_heads = num_attention_heads
150
+
151
+ self.num_key_value_heads = num_key_value_heads
152
+ self.resid_pdrop = resid_pdrop
153
+ self.embd_pdrop = embd_pdrop
154
+ self.attention_dropout = attention_dropout
155
+ self.hidden_act = hidden_act
156
+ self.max_position_embeddings = max_position_embeddings
157
+ self.initializer_range = initializer_range
158
+ self.layer_norm_eps = layer_norm_eps
159
+ self.use_cache = use_cache
160
+ self.rope_theta = rope_theta
161
+ self.rope_scaling = rope_scaling
162
+ self.partial_rotary_factor = partial_rotary_factor
163
+ self.qk_layernorm = qk_layernorm
164
+ self._rope_scaling_validation()
165
+
166
+ super().__init__(
167
+ bos_token_id=bos_token_id,
168
+ eos_token_id=eos_token_id,
169
+ tie_word_embeddings=tie_word_embeddings,
170
+ **kwargs,
171
+ )
172
+
173
+ # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
174
+ def _rope_scaling_validation(self):
175
+ """
176
+ Validate the `rope_scaling` configuration.
177
+ """
178
+ if self.rope_scaling is None:
179
+ return
180
+
181
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
182
+ raise ValueError(
183
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
184
+ f"got {self.rope_scaling}"
185
+ )
186
+ rope_scaling_type = self.rope_scaling.get("type", None)
187
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
188
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
189
+ raise ValueError(
190
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
191
+ )
192
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
193
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
checkpoint-5000/generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.38.0"
4
+ }
checkpoint-5000/global_step5000/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:131c18061fc104f87772deb8997d19a7ac353e74cdae3f33fdfaa6ef67349946
3
+ size 4254816816
checkpoint-5000/global_step5000/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c5e5d5db65b6d6bda5957a0f69251debf3ce0503ceede2ea814fe2813d4f8c3
3
+ size 4254816816
checkpoint-5000/global_step5000/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f69679adb7e941a77ca94ed813aa162c906cd448ab095895cba84443d34a6eb4
3
+ size 4254816816
checkpoint-5000/global_step5000/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6686a494c3339e34a7e13d7f5989d769fbd6fb3c79e4afe506b92075ec9fc82
3
+ size 4254816816
checkpoint-5000/global_step5000/zero_pp_rank_0_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e40bacf01d152870ad9225df4d60e588a553ed93ce15944dbac196a12e9ff8b4
3
+ size 161935
checkpoint-5000/global_step5000/zero_pp_rank_1_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1e4eee9e0e880e3d423d03ddf81778947bdf957d1264e3a7b80af73077200b60
3
+ size 161935
checkpoint-5000/global_step5000/zero_pp_rank_2_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d398a00a4df547cd654507d8b3631d681cfc5297f62c8ce415ca8727ee28a283
3
+ size 161935
checkpoint-5000/global_step5000/zero_pp_rank_3_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68e10a68cccbb5c805702ea741aa9e44a83d57b89c6181df87519d8b1d3879fa
3
+ size 161935
checkpoint-5000/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step5000
checkpoint-5000/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-5000/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3ca39c791bf02bef5319f4a171fbcc6a308a56999f1d6f32079dd222bd442a4
3
+ size 2836579040
checkpoint-5000/modeling_phi.py ADDED
@@ -0,0 +1,1369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi model."""
17
+
18
+
19
+ import math
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache
30
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ SequenceClassifierOutputWithPast,
35
+ TokenClassifierOutput,
36
+ )
37
+ from transformers.modeling_utils import PreTrainedModel
38
+ from transformers.utils import (
39
+ add_code_sample_docstrings,
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ is_flash_attn_2_available,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_phi import PhiConfig
48
+
49
+
50
+ try: # noqa: SIM105
51
+ if is_flash_attn_2_available():
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
54
+ except ImportError:
55
+ # Workaround for https://github.com/huggingface/transformers/issues/28459,
56
+ # don't move to contextlib.suppress(ImportError)
57
+ pass
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CHECKPOINT_FOR_DOC = "microsoft/phi-1_5"
63
+ _CONFIG_FOR_DOC = "PhiConfig"
64
+
65
+ PHI_PRETRAINED_MODEL_ARCHIVE_LIST = [
66
+ "microsoft/phi-1_5",
67
+ # See all Phi models at https://huggingface.co/models?filter=phi
68
+ ]
69
+
70
+
71
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
72
+ def _get_unpad_data(attention_mask):
73
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
74
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
75
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
76
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
77
+ return (
78
+ indices,
79
+ cu_seqlens,
80
+ max_seqlen_in_batch,
81
+ )
82
+
83
+
84
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Phi
85
+ class PhiRotaryEmbedding(nn.Module):
86
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
87
+ super().__init__()
88
+
89
+ self.dim = dim
90
+ self.max_position_embeddings = max_position_embeddings
91
+ self.base = base
92
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
93
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
94
+
95
+ # Build here to make `torch.jit.trace` work.
96
+ self._set_cos_sin_cache(
97
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
98
+ )
99
+
100
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
101
+ self.max_seq_len_cached = seq_len
102
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
103
+
104
+ freqs = torch.outer(t, self.inv_freq)
105
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
106
+ emb = torch.cat((freqs, freqs), dim=-1)
107
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
108
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
109
+
110
+ def forward(self, x, seq_len=None):
111
+ # x: [bs, num_attention_heads, seq_len, head_size]
112
+ if seq_len > self.max_seq_len_cached:
113
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
114
+
115
+ return (
116
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
117
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
118
+ )
119
+
120
+
121
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Phi
122
+ class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
123
+ """PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
124
+
125
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
126
+ self.scaling_factor = scaling_factor
127
+ super().__init__(dim, max_position_embeddings, base, device)
128
+
129
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
130
+ self.max_seq_len_cached = seq_len
131
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
132
+ t = t / self.scaling_factor
133
+
134
+ freqs = torch.outer(t, self.inv_freq)
135
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
138
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
139
+
140
+
141
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Phi
142
+ class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
143
+ """PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
144
+
145
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
146
+ self.scaling_factor = scaling_factor
147
+ super().__init__(dim, max_position_embeddings, base, device)
148
+
149
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
150
+ self.max_seq_len_cached = seq_len
151
+
152
+ if seq_len > self.max_position_embeddings:
153
+ base = self.base * (
154
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
155
+ ) ** (self.dim / (self.dim - 2))
156
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
157
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
158
+
159
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
160
+
161
+ freqs = torch.outer(t, self.inv_freq)
162
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
163
+ emb = torch.cat((freqs, freqs), dim=-1)
164
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
165
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
166
+
167
+
168
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
169
+ def rotate_half(x):
170
+ """Rotates half the hidden dims of the input."""
171
+ x1 = x[..., : x.shape[-1] // 2]
172
+ x2 = x[..., x.shape[-1] // 2 :]
173
+ return torch.cat((-x2, x1), dim=-1)
174
+
175
+
176
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
177
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
178
+ """Applies Rotary Position Embedding to the query and key tensors.
179
+
180
+ Args:
181
+ q (`torch.Tensor`): The query tensor.
182
+ k (`torch.Tensor`): The key tensor.
183
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
184
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
185
+ position_ids (`torch.Tensor`):
186
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
187
+ used to pass offsetted position ids when working with a KV-cache.
188
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
189
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
190
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
191
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
192
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
193
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
194
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
195
+ Returns:
196
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
197
+ """
198
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
199
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
200
+ q_embed = (q * cos) + (rotate_half(q) * sin)
201
+ k_embed = (k * cos) + (rotate_half(k) * sin)
202
+ return q_embed, k_embed
203
+
204
+
205
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
206
+ class PhiMLP(nn.Module):
207
+ def __init__(self, config):
208
+ super().__init__()
209
+ self.config = config
210
+ self.activation_fn = ACT2FN[config.hidden_act]
211
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
212
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
213
+
214
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
215
+ hidden_states = self.fc1(hidden_states)
216
+ hidden_states = self.activation_fn(hidden_states)
217
+ hidden_states = self.fc2(hidden_states)
218
+ return hidden_states
219
+
220
+
221
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
222
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
223
+ """
224
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
225
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
226
+ """
227
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
228
+ if n_rep == 1:
229
+ return hidden_states
230
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
231
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
232
+
233
+
234
+ class PhiAttention(nn.Module):
235
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
236
+
237
+ def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
238
+ super().__init__()
239
+ self.config = config
240
+ self.layer_idx = layer_idx
241
+ if layer_idx is None:
242
+ logger.warning_once(
243
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
244
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
245
+ "when creating this class."
246
+ )
247
+
248
+ self.attention_dropout = config.attention_dropout
249
+ self.hidden_size = config.hidden_size
250
+ self.num_heads = config.num_attention_heads
251
+ self.head_dim = self.hidden_size // self.num_heads
252
+ self.num_key_value_heads = config.num_key_value_heads
253
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
254
+ self.max_position_embeddings = config.max_position_embeddings
255
+ self.rope_theta = config.rope_theta
256
+ self.partial_rotary_factor = config.partial_rotary_factor
257
+ self.is_causal = True
258
+
259
+ if (self.head_dim * self.num_heads) != self.hidden_size:
260
+ raise ValueError(
261
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
262
+ f" and `num_heads`: {self.num_heads})."
263
+ )
264
+
265
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
266
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
267
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
268
+ self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
269
+
270
+ self.qk_layernorm = config.qk_layernorm
271
+ if self.qk_layernorm:
272
+ self.q_layernorm = nn.LayerNorm(
273
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
274
+ )
275
+ self.k_layernorm = nn.LayerNorm(
276
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
277
+ )
278
+
279
+ self._init_rope()
280
+
281
+ def _init_rope(self):
282
+ if self.config.rope_scaling is None:
283
+ self.rotary_emb = PhiRotaryEmbedding(
284
+ int(self.partial_rotary_factor * self.head_dim),
285
+ max_position_embeddings=self.max_position_embeddings,
286
+ base=self.rope_theta,
287
+ )
288
+ else:
289
+ scaling_type = self.config.rope_scaling["type"]
290
+ scaling_factor = self.config.rope_scaling["factor"]
291
+ if scaling_type == "linear":
292
+ self.rotary_emb = PhiLinearScalingRotaryEmbedding(
293
+ int(self.partial_rotary_factor * self.head_dim),
294
+ max_position_embeddings=self.max_position_embeddings,
295
+ scaling_factor=scaling_factor,
296
+ base=self.rope_theta,
297
+ )
298
+ elif scaling_type == "dynamic":
299
+ self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
300
+ int(self.partial_rotary_factor * self.head_dim),
301
+ max_position_embeddings=self.max_position_embeddings,
302
+ scaling_factor=scaling_factor,
303
+ base=self.rope_theta,
304
+ )
305
+ else:
306
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
307
+
308
+ def forward(
309
+ self,
310
+ hidden_states: torch.Tensor,
311
+ attention_mask: Optional[torch.Tensor] = None,
312
+ position_ids: Optional[torch.LongTensor] = None,
313
+ past_key_value: Optional[Cache] = None,
314
+ output_attentions: bool = False,
315
+ use_cache: bool = False,
316
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
317
+ bsz, q_len, _ = hidden_states.size()
318
+
319
+ query_states = self.q_proj(hidden_states)
320
+ key_states = self.k_proj(hidden_states)
321
+ value_states = self.v_proj(hidden_states)
322
+
323
+ if self.qk_layernorm:
324
+ query_states = self.q_layernorm(query_states)
325
+ key_states = self.k_layernorm(key_states)
326
+
327
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
328
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
329
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
330
+
331
+ kv_seq_len = key_states.shape[-2]
332
+ if past_key_value is not None:
333
+ if self.layer_idx is None:
334
+ raise ValueError(
335
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
336
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
337
+ "with a layer index."
338
+ )
339
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
340
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
341
+
342
+ # Partial rotary embedding
343
+ query_rot, query_pass = (
344
+ query_states[..., : self.rotary_emb.dim],
345
+ query_states[..., self.rotary_emb.dim :],
346
+ )
347
+ key_rot, key_pass = (
348
+ key_states[..., : self.rotary_emb.dim],
349
+ key_states[..., self.rotary_emb.dim :],
350
+ )
351
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
352
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
353
+
354
+ # [batch_size, seq_length, num_heads, head_dim]
355
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
356
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
357
+
358
+ if past_key_value is not None:
359
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
360
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
361
+
362
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
363
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
364
+
365
+ # Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
366
+ attn_weights = torch.matmul(
367
+ query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
368
+ ) / math.sqrt(self.head_dim)
369
+
370
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
371
+ raise ValueError(
372
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
373
+ f" {attn_weights.size()}"
374
+ )
375
+
376
+ if attention_mask is not None:
377
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
378
+ raise ValueError(
379
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
380
+ )
381
+ attn_weights = attn_weights + attention_mask
382
+
383
+ # upcast attention to fp32
384
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
385
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
386
+
387
+ attn_output = torch.matmul(attn_weights, value_states)
388
+
389
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
390
+ raise ValueError(
391
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
392
+ f" {attn_output.size()}"
393
+ )
394
+
395
+ attn_output = attn_output.transpose(1, 2).contiguous()
396
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
397
+
398
+ attn_output = self.dense(attn_output)
399
+
400
+ if not output_attentions:
401
+ attn_weights = None
402
+
403
+ return attn_output, attn_weights, past_key_value
404
+
405
+
406
+ class PhiFlashAttention2(PhiAttention):
407
+ """
408
+ Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
409
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
410
+ flash attention and deal with padding tokens in case the input contains any of them.
411
+ """
412
+
413
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
414
+ def __init__(self, *args, **kwargs):
415
+ super().__init__(*args, **kwargs)
416
+
417
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
418
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
419
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
420
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
421
+
422
+ def forward(
423
+ self,
424
+ hidden_states: torch.Tensor,
425
+ attention_mask: Optional[torch.LongTensor] = None,
426
+ position_ids: Optional[torch.LongTensor] = None,
427
+ past_key_value: Optional[Cache] = None,
428
+ output_attentions: bool = False,
429
+ use_cache: bool = False,
430
+ **kwargs,
431
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
432
+ # PhiFlashAttention2 attention does not support output_attentions
433
+
434
+ output_attentions = False
435
+
436
+ bsz, q_len, _ = hidden_states.size()
437
+
438
+ query_states = self.q_proj(hidden_states)
439
+ key_states = self.k_proj(hidden_states)
440
+ value_states = self.v_proj(hidden_states)
441
+
442
+ if self.qk_layernorm:
443
+ query_states = self.q_layernorm(query_states)
444
+ key_states = self.k_layernorm(key_states)
445
+
446
+ # Flash attention requires the input to have the shape
447
+ # batch_size x seq_length x head_dim x hidden_dim
448
+ # therefore we just need to keep the original shape
449
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
450
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
451
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
452
+
453
+ kv_seq_len = key_states.shape[-2]
454
+ if past_key_value is not None:
455
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
456
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
457
+
458
+ # Partial rotary embedding
459
+ query_rot, query_pass = (
460
+ query_states[..., : self.rotary_emb.dim],
461
+ query_states[..., self.rotary_emb.dim :],
462
+ )
463
+ key_rot, key_pass = (
464
+ key_states[..., : self.rotary_emb.dim],
465
+ key_states[..., self.rotary_emb.dim :],
466
+ )
467
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
468
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
469
+
470
+ # [batch_size, seq_length, num_heads, head_dim]
471
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
472
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
473
+
474
+ if past_key_value is not None:
475
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
476
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
477
+
478
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
479
+ # to be able to avoid many of these transpose/reshape/view.
480
+ query_states = query_states.transpose(1, 2)
481
+ key_states = key_states.transpose(1, 2)
482
+ value_states = value_states.transpose(1, 2)
483
+
484
+ attn_dropout = self.attention_dropout if self.training else 0.0
485
+
486
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
487
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
488
+ # cast them back in the correct dtype just to be sure everything works as expected.
489
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
490
+ # in fp32.
491
+
492
+ if query_states.dtype == torch.float32:
493
+ if torch.is_autocast_enabled():
494
+ target_dtype = torch.get_autocast_gpu_dtype()
495
+ # Handle the case where the model is quantized
496
+ elif hasattr(self.config, "_pre_quantization_dtype"):
497
+ target_dtype = self.config._pre_quantization_dtype
498
+ else:
499
+ target_dtype = self.q_proj.weight.dtype
500
+
501
+ logger.warning_once(
502
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
503
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
504
+ f" {target_dtype}."
505
+ )
506
+
507
+ query_states = query_states.to(target_dtype)
508
+ key_states = key_states.to(target_dtype)
509
+ value_states = value_states.to(target_dtype)
510
+
511
+ attn_output = self._flash_attention_forward(
512
+ query_states, key_states, value_states, attention_mask, q_len, dropout=attn_dropout, softmax_scale=None
513
+ )
514
+
515
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
516
+ attn_output = self.dense(attn_output)
517
+
518
+ if not output_attentions:
519
+ attn_weights = None
520
+
521
+ return attn_output, attn_weights, past_key_value
522
+
523
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
524
+ def _flash_attention_forward(
525
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
526
+ ):
527
+ """
528
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
529
+ first unpad the input, then computes the attention scores and pad the final attention scores.
530
+
531
+ Args:
532
+ query_states (`torch.Tensor`):
533
+ Input query states to be passed to Flash Attention API
534
+ key_states (`torch.Tensor`):
535
+ Input key states to be passed to Flash Attention API
536
+ value_states (`torch.Tensor`):
537
+ Input value states to be passed to Flash Attention API
538
+ attention_mask (`torch.Tensor`):
539
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
540
+ position of padding tokens and 1 for the position of non-padding tokens.
541
+ dropout (`int`, *optional*):
542
+ Attention dropout
543
+ softmax_scale (`float`, *optional*):
544
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
545
+ """
546
+ if not self._flash_attn_uses_top_left_mask:
547
+ causal = self.is_causal
548
+ else:
549
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
550
+ causal = self.is_causal and query_length != 1
551
+
552
+ # Contains at least one padding token in the sequence
553
+ if attention_mask is not None:
554
+ batch_size = query_states.shape[0]
555
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
556
+ query_states, key_states, value_states, attention_mask, query_length
557
+ )
558
+
559
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
560
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
561
+
562
+ attn_output_unpad = flash_attn_varlen_func(
563
+ query_states,
564
+ key_states,
565
+ value_states,
566
+ cu_seqlens_q=cu_seqlens_q,
567
+ cu_seqlens_k=cu_seqlens_k,
568
+ max_seqlen_q=max_seqlen_in_batch_q,
569
+ max_seqlen_k=max_seqlen_in_batch_k,
570
+ dropout_p=dropout,
571
+ softmax_scale=softmax_scale,
572
+ causal=causal,
573
+ )
574
+
575
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
576
+ else:
577
+ attn_output = flash_attn_func(
578
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
579
+ )
580
+
581
+ return attn_output
582
+
583
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
584
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
585
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
586
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
587
+
588
+ key_layer = index_first_axis(
589
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
590
+ )
591
+ value_layer = index_first_axis(
592
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
593
+ )
594
+ if query_length == kv_seq_len:
595
+ query_layer = index_first_axis(
596
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
597
+ )
598
+ cu_seqlens_q = cu_seqlens_k
599
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
600
+ indices_q = indices_k
601
+ elif query_length == 1:
602
+ max_seqlen_in_batch_q = 1
603
+ cu_seqlens_q = torch.arange(
604
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
605
+ ) # There is a memcpy here, that is very bad.
606
+ indices_q = cu_seqlens_q[:-1]
607
+ query_layer = query_layer.squeeze(1)
608
+ else:
609
+ # The -q_len: slice assumes left padding.
610
+ attention_mask = attention_mask[:, -query_length:]
611
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
612
+
613
+ return (
614
+ query_layer,
615
+ key_layer,
616
+ value_layer,
617
+ indices_q,
618
+ (cu_seqlens_q, cu_seqlens_k),
619
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
620
+ )
621
+
622
+
623
+ PHI_ATTENTION_CLASSES = {
624
+ "eager": PhiAttention,
625
+ "flash_attention_2": PhiFlashAttention2,
626
+ }
627
+
628
+
629
+ class PhiDecoderLayer(nn.Module):
630
+ def __init__(self, config: PhiConfig, layer_idx: int):
631
+ super().__init__()
632
+ self.self_attn = PHI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
633
+ self.mlp = PhiMLP(config)
634
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
635
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
636
+
637
+ def forward(
638
+ self,
639
+ hidden_states: torch.Tensor,
640
+ attention_mask: Optional[torch.Tensor] = None,
641
+ position_ids: Optional[torch.LongTensor] = None,
642
+ output_attentions: Optional[bool] = False,
643
+ use_cache: Optional[bool] = False,
644
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
645
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
646
+ """
647
+ Args:
648
+ hidden_states (`torch.FloatTensor`):
649
+ input to the layer of shape `(batch, seq_len, embed_dim)`
650
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
651
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
652
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
653
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
654
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
655
+ output_attentions (`bool`, *optional*):
656
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
657
+ returned tensors for more detail.
658
+ use_cache (`bool`, *optional*):
659
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
660
+ (see `past_key_values`).
661
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
662
+ """
663
+
664
+ residual = hidden_states
665
+
666
+ hidden_states = self.input_layernorm(hidden_states)
667
+
668
+ # Self Attention
669
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
670
+ hidden_states=hidden_states,
671
+ attention_mask=attention_mask,
672
+ position_ids=position_ids,
673
+ past_key_value=past_key_value,
674
+ output_attentions=output_attentions,
675
+ use_cache=use_cache,
676
+ )
677
+ attn_outputs = self.resid_dropout(attn_outputs)
678
+
679
+ feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
680
+ hidden_states = attn_outputs + feed_forward_hidden_states + residual
681
+ outputs = (hidden_states,)
682
+
683
+ if output_attentions:
684
+ outputs += (self_attn_weights,)
685
+
686
+ if use_cache:
687
+ outputs += (present_key_value,)
688
+
689
+ return outputs
690
+
691
+
692
+ PHI_START_DOCSTRING = r"""
693
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
694
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
695
+ etc.)
696
+
697
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
698
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
699
+ and behavior.
700
+
701
+ Parameters:
702
+ config ([`PhiConfig`]):
703
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
704
+ load the weights associated with the model, only the configuration. Check out the
705
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
706
+ """
707
+
708
+
709
+ @add_start_docstrings(
710
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
711
+ PHI_START_DOCSTRING,
712
+ )
713
+ class PhiPreTrainedModel(PreTrainedModel):
714
+ config_class = PhiConfig
715
+ base_model_prefix = "model"
716
+ supports_gradient_checkpointing = True
717
+ _no_split_modules = ["PhiDecoderLayer"]
718
+ _skip_keys_device_placement = "past_key_values"
719
+ _supports_flash_attn_2 = True
720
+ _supports_cache_class = True
721
+
722
+ def _init_weights(self, module):
723
+ std = self.config.initializer_range
724
+ if isinstance(module, nn.Linear):
725
+ module.weight.data.normal_(mean=0.0, std=std)
726
+ if module.bias is not None:
727
+ module.bias.data.zero_()
728
+ elif isinstance(module, nn.Embedding):
729
+ module.weight.data.normal_(mean=0.0, std=std)
730
+ if module.padding_idx is not None:
731
+ module.weight.data[module.padding_idx].zero_()
732
+
733
+
734
+ PHI_INPUTS_DOCSTRING = r"""
735
+ Args:
736
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
737
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
738
+ it.
739
+
740
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
741
+ [`PreTrainedTokenizer.__call__`] for details.
742
+
743
+ [What are input IDs?](../glossary#input-ids)
744
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
745
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
746
+
747
+ - 1 for tokens that are **not masked**,
748
+ - 0 for tokens that are **masked**.
749
+
750
+ [What are attention masks?](../glossary#attention-mask)
751
+
752
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
753
+ [`PreTrainedTokenizer.__call__`] for details.
754
+
755
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
756
+ `past_key_values`).
757
+
758
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
759
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
760
+ information on the default strategy.
761
+
762
+ - 1 indicates the head is **not masked**,
763
+ - 0 indicates the head is **masked**.
764
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
765
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
766
+ config.n_positions - 1]`.
767
+
768
+ [What are position IDs?](../glossary#position-ids)
769
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
770
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
771
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
772
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
773
+
774
+ Two formats are allowed:
775
+ - a [`~cache_utils.Cache`] instance;
776
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
777
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
778
+ cache format.
779
+
780
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
781
+ legacy cache format will be returned.
782
+
783
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
784
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
785
+ of shape `(batch_size, sequence_length)`.
786
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
787
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
788
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
789
+ model's internal embedding lookup matrix.
790
+ use_cache (`bool`, *optional*):
791
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
792
+ `past_key_values`).
793
+ output_attentions (`bool`, *optional*):
794
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
795
+ tensors for more detail.
796
+ output_hidden_states (`bool`, *optional*):
797
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
798
+ more detail.
799
+ return_dict (`bool`, *optional*):
800
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
801
+ """
802
+
803
+
804
+ @add_start_docstrings(
805
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
806
+ PHI_START_DOCSTRING,
807
+ )
808
+ class PhiModel(PhiPreTrainedModel):
809
+ """
810
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
811
+
812
+ Args:
813
+ config: PhiConfig
814
+ """
815
+
816
+ def __init__(self, config: PhiConfig):
817
+ super().__init__(config)
818
+ self.padding_idx = config.pad_token_id
819
+ self.vocab_size = config.vocab_size
820
+
821
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
822
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
823
+ self.layers = nn.ModuleList(
824
+ [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
825
+ )
826
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
827
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
828
+
829
+ self.gradient_checkpointing = False
830
+ # Initialize weights and apply final processing
831
+ self.post_init()
832
+
833
+ def get_input_embeddings(self):
834
+ return self.embed_tokens
835
+
836
+ def set_input_embeddings(self, value):
837
+ self.embed_tokens = value
838
+
839
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
840
+ def forward(
841
+ self,
842
+ input_ids: torch.LongTensor = None,
843
+ attention_mask: Optional[torch.Tensor] = None,
844
+ position_ids: Optional[torch.LongTensor] = None,
845
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
846
+ inputs_embeds: Optional[torch.FloatTensor] = None,
847
+ use_cache: Optional[bool] = None,
848
+ output_attentions: Optional[bool] = None,
849
+ output_hidden_states: Optional[bool] = None,
850
+ return_dict: Optional[bool] = None,
851
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
852
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
853
+ output_hidden_states = (
854
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
855
+ )
856
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
857
+
858
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
859
+
860
+ # retrieve input_ids and inputs_embeds
861
+ if input_ids is not None and inputs_embeds is not None:
862
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
863
+ elif input_ids is not None:
864
+ batch_size, seq_length = input_ids.shape[:2]
865
+ elif inputs_embeds is not None:
866
+ batch_size, seq_length = inputs_embeds.shape[:2]
867
+ else:
868
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
869
+
870
+ past_key_values_length = 0
871
+
872
+ if self.gradient_checkpointing and self.training:
873
+ if use_cache:
874
+ logger.warning_once(
875
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
876
+ )
877
+ use_cache = False
878
+
879
+ if use_cache:
880
+ use_legacy_cache = not isinstance(past_key_values, Cache)
881
+ if use_legacy_cache:
882
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
883
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
884
+
885
+ if position_ids is None:
886
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
887
+ position_ids = torch.arange(
888
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
889
+ )
890
+ position_ids = position_ids.unsqueeze(0)
891
+
892
+ if inputs_embeds is None:
893
+ inputs_embeds = self.embed_tokens(input_ids)
894
+
895
+ inputs_embeds = self.embed_dropout(inputs_embeds)
896
+
897
+ # Attention mask.
898
+ if self._use_flash_attention_2:
899
+ # 2d mask is passed through the layers
900
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
901
+ else:
902
+ # 4d mask is passed through the layers
903
+ attention_mask = _prepare_4d_causal_attention_mask(
904
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
905
+ )
906
+
907
+ hidden_states = inputs_embeds
908
+
909
+ # decoder layers
910
+ all_hidden_states = () if output_hidden_states else None
911
+ all_self_attns = () if output_attentions else None
912
+ next_decoder_cache = None
913
+
914
+ for decoder_layer in self.layers:
915
+ if output_hidden_states:
916
+ all_hidden_states += (hidden_states,)
917
+
918
+ if self.gradient_checkpointing and self.training:
919
+ layer_outputs = self._gradient_checkpointing_func(
920
+ decoder_layer.__call__,
921
+ hidden_states,
922
+ attention_mask,
923
+ position_ids,
924
+ past_key_values,
925
+ output_attentions,
926
+ )
927
+ else:
928
+ layer_outputs = decoder_layer(
929
+ hidden_states,
930
+ attention_mask=attention_mask,
931
+ position_ids=position_ids,
932
+ past_key_value=past_key_values,
933
+ output_attentions=output_attentions,
934
+ use_cache=use_cache,
935
+ )
936
+
937
+ hidden_states = layer_outputs[0]
938
+
939
+ if use_cache:
940
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
941
+
942
+ if output_attentions:
943
+ all_self_attns += (layer_outputs[1],)
944
+
945
+ hidden_states = self.final_layernorm(hidden_states)
946
+
947
+ # add hidden states from the last decoder layer
948
+ if output_hidden_states:
949
+ all_hidden_states += (hidden_states,)
950
+
951
+ next_cache = None
952
+ if use_cache:
953
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
954
+ if not return_dict:
955
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
956
+ return BaseModelOutputWithPast(
957
+ last_hidden_state=hidden_states,
958
+ past_key_values=next_cache,
959
+ hidden_states=all_hidden_states,
960
+ attentions=all_self_attns,
961
+ )
962
+
963
+
964
+ class PhiForCausalLM(PhiPreTrainedModel):
965
+ _tied_weights_keys = ["lm_head.weight"]
966
+
967
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
968
+ def __init__(self, config):
969
+ super().__init__(config)
970
+ self.model = PhiModel(config)
971
+ self.vocab_size = config.vocab_size
972
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
973
+
974
+ # Initialize weights and apply final processing
975
+ self.post_init()
976
+
977
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
978
+ def get_input_embeddings(self):
979
+ return self.model.embed_tokens
980
+
981
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
982
+ def set_input_embeddings(self, value):
983
+ self.model.embed_tokens = value
984
+
985
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
986
+ def get_output_embeddings(self):
987
+ return self.lm_head
988
+
989
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
990
+ def set_output_embeddings(self, new_embeddings):
991
+ self.lm_head = new_embeddings
992
+
993
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
994
+ def set_decoder(self, decoder):
995
+ self.model = decoder
996
+
997
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
998
+ def get_decoder(self):
999
+ return self.model
1000
+
1001
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1002
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1003
+ def forward(
1004
+ self,
1005
+ input_ids: torch.LongTensor = None,
1006
+ attention_mask: Optional[torch.Tensor] = None,
1007
+ position_ids: Optional[torch.LongTensor] = None,
1008
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1009
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1010
+ labels: Optional[torch.LongTensor] = None,
1011
+ use_cache: Optional[bool] = None,
1012
+ output_attentions: Optional[bool] = None,
1013
+ output_hidden_states: Optional[bool] = None,
1014
+ return_dict: Optional[bool] = None,
1015
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1016
+ r"""
1017
+ Args:
1018
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1019
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1020
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1021
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1022
+
1023
+ Returns:
1024
+
1025
+ Example:
1026
+
1027
+ ```python
1028
+ >>> from transformers import AutoTokenizer, PhiForCausalLM
1029
+
1030
+ >>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
1031
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
1032
+
1033
+ >>> prompt = "This is an example script ."
1034
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1035
+
1036
+ >>> # Generate
1037
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1038
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1039
+ 'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
1040
+ ```"""
1041
+
1042
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1043
+ output_hidden_states = (
1044
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1045
+ )
1046
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1047
+
1048
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1049
+ outputs = self.model(
1050
+ input_ids=input_ids,
1051
+ attention_mask=attention_mask,
1052
+ position_ids=position_ids,
1053
+ past_key_values=past_key_values,
1054
+ inputs_embeds=inputs_embeds,
1055
+ use_cache=use_cache,
1056
+ output_attentions=output_attentions,
1057
+ output_hidden_states=output_hidden_states,
1058
+ return_dict=return_dict,
1059
+ )
1060
+
1061
+ hidden_states = outputs[0]
1062
+ logits = self.lm_head(hidden_states)
1063
+ logits = logits.float()
1064
+
1065
+ loss = None
1066
+ if labels is not None:
1067
+ # Shift so that tokens < n predict n
1068
+ shift_logits = logits[..., :-1, :].contiguous()
1069
+ shift_labels = labels[..., 1:].contiguous()
1070
+ # Flatten the tokens
1071
+ loss_fct = CrossEntropyLoss()
1072
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1073
+ shift_labels = shift_labels.view(-1)
1074
+ # Enable model parallelism
1075
+ shift_labels = shift_labels.to(shift_logits.device)
1076
+ loss = loss_fct(shift_logits, shift_labels)
1077
+
1078
+ if not return_dict:
1079
+ output = (logits,) + outputs[1:]
1080
+ return (loss,) + output if loss is not None else output
1081
+
1082
+ return CausalLMOutputWithPast(
1083
+ loss=loss,
1084
+ logits=logits,
1085
+ past_key_values=outputs.past_key_values,
1086
+ hidden_states=outputs.hidden_states,
1087
+ attentions=outputs.attentions,
1088
+ )
1089
+
1090
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1091
+ def prepare_inputs_for_generation(
1092
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1093
+ ):
1094
+ if past_key_values is not None:
1095
+ if isinstance(past_key_values, Cache):
1096
+ cache_length = past_key_values.get_seq_length()
1097
+ past_length = past_key_values.seen_tokens
1098
+ max_cache_length = past_key_values.get_max_length()
1099
+ else:
1100
+ cache_length = past_length = past_key_values[0][0].shape[2]
1101
+ max_cache_length = None
1102
+
1103
+ # Keep only the unprocessed tokens:
1104
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1105
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1106
+ # input)
1107
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1108
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1109
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1110
+ # input_ids based on the past_length.
1111
+ elif past_length < input_ids.shape[1]:
1112
+ input_ids = input_ids[:, past_length:]
1113
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1114
+
1115
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1116
+ if (
1117
+ max_cache_length is not None
1118
+ and attention_mask is not None
1119
+ and cache_length + input_ids.shape[1] > max_cache_length
1120
+ ):
1121
+ attention_mask = attention_mask[:, -max_cache_length:]
1122
+
1123
+ position_ids = kwargs.get("position_ids", None)
1124
+ if attention_mask is not None and position_ids is None:
1125
+ # create position_ids on the fly for batch generation
1126
+ position_ids = attention_mask.long().cumsum(-1) - 1
1127
+ position_ids.masked_fill_(attention_mask == 0, 1)
1128
+ if past_key_values:
1129
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1130
+
1131
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1132
+ if inputs_embeds is not None and past_key_values is None:
1133
+ model_inputs = {"inputs_embeds": inputs_embeds}
1134
+ else:
1135
+ model_inputs = {"input_ids": input_ids}
1136
+
1137
+ model_inputs.update(
1138
+ {
1139
+ "position_ids": position_ids,
1140
+ "past_key_values": past_key_values,
1141
+ "use_cache": kwargs.get("use_cache"),
1142
+ "attention_mask": attention_mask,
1143
+ }
1144
+ )
1145
+ return model_inputs
1146
+
1147
+ @staticmethod
1148
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1149
+ def _reorder_cache(past_key_values, beam_idx):
1150
+ reordered_past = ()
1151
+ for layer_past in past_key_values:
1152
+ reordered_past += (
1153
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1154
+ )
1155
+ return reordered_past
1156
+
1157
+
1158
+ @add_start_docstrings(
1159
+ """
1160
+ The PhiModel with a sequence classification head on top (linear layer).
1161
+
1162
+ [`PhiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1163
+ (e.g. GPT-2) do.
1164
+
1165
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1166
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1167
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1168
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1169
+ each row of the batch).
1170
+ """,
1171
+ PHI_START_DOCSTRING,
1172
+ )
1173
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->PHI,Llama->Phi with self.transformer->self.model, transformer_outputs->model_outputs
1174
+ class PhiForSequenceClassification(PhiPreTrainedModel):
1175
+ def __init__(self, config):
1176
+ super().__init__(config)
1177
+ self.num_labels = config.num_labels
1178
+ self.model = PhiModel(config)
1179
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1180
+
1181
+ # Initialize weights and apply final processing
1182
+ self.post_init()
1183
+
1184
+ def get_input_embeddings(self):
1185
+ return self.model.embed_tokens
1186
+
1187
+ def set_input_embeddings(self, value):
1188
+ self.model.embed_tokens = value
1189
+
1190
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1191
+ def forward(
1192
+ self,
1193
+ input_ids: torch.LongTensor = None,
1194
+ attention_mask: Optional[torch.Tensor] = None,
1195
+ position_ids: Optional[torch.LongTensor] = None,
1196
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1197
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1198
+ labels: Optional[torch.LongTensor] = None,
1199
+ use_cache: Optional[bool] = None,
1200
+ output_attentions: Optional[bool] = None,
1201
+ output_hidden_states: Optional[bool] = None,
1202
+ return_dict: Optional[bool] = None,
1203
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1204
+ r"""
1205
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1206
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1207
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1208
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1209
+ """
1210
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1211
+
1212
+ model_outputs = self.model(
1213
+ input_ids,
1214
+ attention_mask=attention_mask,
1215
+ position_ids=position_ids,
1216
+ past_key_values=past_key_values,
1217
+ inputs_embeds=inputs_embeds,
1218
+ use_cache=use_cache,
1219
+ output_attentions=output_attentions,
1220
+ output_hidden_states=output_hidden_states,
1221
+ return_dict=return_dict,
1222
+ )
1223
+ hidden_states = model_outputs[0]
1224
+ logits = self.score(hidden_states)
1225
+
1226
+ if input_ids is not None:
1227
+ batch_size = input_ids.shape[0]
1228
+ else:
1229
+ batch_size = inputs_embeds.shape[0]
1230
+
1231
+ if self.config.pad_token_id is None and batch_size != 1:
1232
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1233
+ if self.config.pad_token_id is None:
1234
+ sequence_lengths = -1
1235
+ else:
1236
+ if input_ids is not None:
1237
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1238
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1239
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1240
+ sequence_lengths = sequence_lengths.to(logits.device)
1241
+ else:
1242
+ sequence_lengths = -1
1243
+
1244
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1245
+
1246
+ loss = None
1247
+ if labels is not None:
1248
+ labels = labels.to(logits.device)
1249
+ if self.config.problem_type is None:
1250
+ if self.num_labels == 1:
1251
+ self.config.problem_type = "regression"
1252
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1253
+ self.config.problem_type = "single_label_classification"
1254
+ else:
1255
+ self.config.problem_type = "multi_label_classification"
1256
+
1257
+ if self.config.problem_type == "regression":
1258
+ loss_fct = MSELoss()
1259
+ if self.num_labels == 1:
1260
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1261
+ else:
1262
+ loss = loss_fct(pooled_logits, labels)
1263
+ elif self.config.problem_type == "single_label_classification":
1264
+ loss_fct = CrossEntropyLoss()
1265
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1266
+ elif self.config.problem_type == "multi_label_classification":
1267
+ loss_fct = BCEWithLogitsLoss()
1268
+ loss = loss_fct(pooled_logits, labels)
1269
+ if not return_dict:
1270
+ output = (pooled_logits,) + model_outputs[1:]
1271
+ return ((loss,) + output) if loss is not None else output
1272
+
1273
+ return SequenceClassifierOutputWithPast(
1274
+ loss=loss,
1275
+ logits=pooled_logits,
1276
+ past_key_values=model_outputs.past_key_values,
1277
+ hidden_states=model_outputs.hidden_states,
1278
+ attentions=model_outputs.attentions,
1279
+ )
1280
+
1281
+
1282
+ @add_start_docstrings(
1283
+ """
1284
+ PhiModel with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1285
+ Named-Entity-Recognition (NER) tasks.
1286
+ """,
1287
+ PHI_START_DOCSTRING,
1288
+ )
1289
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with MPT->PHI,Mpt->Phi,self.transformer->self.model,transformer_outputs->model_outputs
1290
+ class PhiForTokenClassification(PhiPreTrainedModel):
1291
+ def __init__(self, config: PhiConfig):
1292
+ super().__init__(config)
1293
+ self.num_labels = config.num_labels
1294
+
1295
+ self.model = PhiModel(config)
1296
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1297
+ classifier_dropout = config.classifier_dropout
1298
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1299
+ classifier_dropout = config.hidden_dropout
1300
+ else:
1301
+ classifier_dropout = 0.1
1302
+ self.dropout = nn.Dropout(classifier_dropout)
1303
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1304
+
1305
+ # Initialize weights and apply final processing
1306
+ self.post_init()
1307
+
1308
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1309
+ @add_code_sample_docstrings(
1310
+ checkpoint=_CHECKPOINT_FOR_DOC,
1311
+ output_type=TokenClassifierOutput,
1312
+ config_class=_CONFIG_FOR_DOC,
1313
+ )
1314
+ def forward(
1315
+ self,
1316
+ input_ids: Optional[torch.LongTensor] = None,
1317
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1318
+ attention_mask: Optional[torch.Tensor] = None,
1319
+ inputs_embeds: Optional[torch.Tensor] = None,
1320
+ labels: Optional[torch.Tensor] = None,
1321
+ use_cache: Optional[bool] = None,
1322
+ output_attentions: Optional[bool] = None,
1323
+ output_hidden_states: Optional[bool] = None,
1324
+ return_dict: Optional[bool] = None,
1325
+ **deprecated_arguments,
1326
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1327
+ r"""
1328
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1329
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1330
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1331
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1332
+ """
1333
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1334
+
1335
+ model_outputs = self.model(
1336
+ input_ids,
1337
+ past_key_values=past_key_values,
1338
+ attention_mask=attention_mask,
1339
+ inputs_embeds=inputs_embeds,
1340
+ use_cache=use_cache,
1341
+ output_attentions=output_attentions,
1342
+ output_hidden_states=output_hidden_states,
1343
+ return_dict=return_dict,
1344
+ )
1345
+
1346
+ hidden_states = model_outputs[0]
1347
+ hidden_states = self.dropout(hidden_states)
1348
+ logits = self.classifier(hidden_states)
1349
+
1350
+ loss = None
1351
+ if labels is not None:
1352
+ # move labels to correct device to enable model parallelism
1353
+ labels = labels.to(logits.device)
1354
+ batch_size, seq_length = labels.shape
1355
+ loss_fct = CrossEntropyLoss()
1356
+ loss = loss_fct(
1357
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1358
+ )
1359
+
1360
+ if not return_dict:
1361
+ output = (logits,) + model_outputs[2:]
1362
+ return ((loss,) + output) if loss is not None else output
1363
+
1364
+ return TokenClassifierOutput(
1365
+ loss=loss,
1366
+ logits=logits,
1367
+ hidden_states=model_outputs.hidden_states,
1368
+ attentions=model_outputs.attentions,
1369
+ )
checkpoint-5000/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5d8d3c7739f9787ea797b86ff1b3a51f9e68197835ba3178915a8a77558f67fc
3
+ size 15024
checkpoint-5000/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a22a57799bc43e59db67d9a787ed73040020c5f35990602033f4dab1318787d7
3
+ size 15024
checkpoint-5000/rng_state_2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29a624b936b77a04d6bfb6940acdd65a710bf39452e419e7ddb5c40fb2261072
3
+ size 15024
checkpoint-5000/rng_state_3.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a79306817d4440cd621149537e8cf216b60f847fc6f9531a6147426aa02bb07
3
+ size 15024
checkpoint-5000/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:847ebce0c94e50a7ff3b64df7be24dd9722c1c05a09f4c7708ee2a423548a4c8
3
+ size 1064
checkpoint-5000/special_tokens_map.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|endoftext|>",
3
+ "eos_token": {
4
+ "content": "<|endoftext|>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ "pad_token": "<|endoftext|>",
11
+ "unk_token": {
12
+ "content": "<|endoftext|>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ }
18
+ }
checkpoint-5000/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-5000/tokenizer_config.json ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "50256": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "50257": {
13
+ "content": " ",
14
+ "lstrip": false,
15
+ "normalized": true,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": false
19
+ },
20
+ "50258": {
21
+ "content": " ",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": false
27
+ },
28
+ "50259": {
29
+ "content": " ",
30
+ "lstrip": false,
31
+ "normalized": true,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": false
35
+ },
36
+ "50260": {
37
+ "content": " ",
38
+ "lstrip": false,
39
+ "normalized": true,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": false
43
+ },
44
+ "50261": {
45
+ "content": " ",
46
+ "lstrip": false,
47
+ "normalized": true,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": false
51
+ },
52
+ "50262": {
53
+ "content": " ",
54
+ "lstrip": false,
55
+ "normalized": true,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": false
59
+ },
60
+ "50263": {
61
+ "content": " ",
62
+ "lstrip": false,
63
+ "normalized": true,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": false
67
+ },
68
+ "50264": {
69
+ "content": " ",
70
+ "lstrip": false,
71
+ "normalized": true,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": false
75
+ },
76
+ "50265": {
77
+ "content": " ",
78
+ "lstrip": false,
79
+ "normalized": true,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": false
83
+ },
84
+ "50266": {
85
+ "content": " ",
86
+ "lstrip": false,
87
+ "normalized": true,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": false
91
+ },
92
+ "50267": {
93
+ "content": " ",
94
+ "lstrip": false,
95
+ "normalized": true,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": false
99
+ },
100
+ "50268": {
101
+ "content": " ",
102
+ "lstrip": false,
103
+ "normalized": true,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": false
107
+ },
108
+ "50269": {
109
+ "content": " ",
110
+ "lstrip": false,
111
+ "normalized": true,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": false
115
+ },
116
+ "50270": {
117
+ "content": " ",
118
+ "lstrip": false,
119
+ "normalized": true,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": false
123
+ },
124
+ "50271": {
125
+ "content": " ",
126
+ "lstrip": false,
127
+ "normalized": true,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": false
131
+ },
132
+ "50272": {
133
+ "content": " ",
134
+ "lstrip": false,
135
+ "normalized": true,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": false
139
+ },
140
+ "50273": {
141
+ "content": " ",
142
+ "lstrip": false,
143
+ "normalized": true,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": false
147
+ },
148
+ "50274": {
149
+ "content": " ",
150
+ "lstrip": false,
151
+ "normalized": true,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": false
155
+ },
156
+ "50275": {
157
+ "content": " ",
158
+ "lstrip": false,
159
+ "normalized": true,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": false
163
+ },
164
+ "50276": {
165
+ "content": " ",
166
+ "lstrip": false,
167
+ "normalized": true,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": false
171
+ },
172
+ "50277": {
173
+ "content": " ",
174
+ "lstrip": false,
175
+ "normalized": true,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": false
179
+ },
180
+ "50278": {
181
+ "content": " ",
182
+ "lstrip": false,
183
+ "normalized": true,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": false
187
+ },
188
+ "50279": {
189
+ "content": " ",
190
+ "lstrip": false,
191
+ "normalized": true,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": false
195
+ },
196
+ "50280": {
197
+ "content": " ",
198
+ "lstrip": false,
199
+ "normalized": true,
200
+ "rstrip": false,
201
+ "single_word": false,
202
+ "special": false
203
+ },
204
+ "50281": {
205
+ "content": " ",
206
+ "lstrip": false,
207
+ "normalized": true,
208
+ "rstrip": false,
209
+ "single_word": false,
210
+ "special": false
211
+ },
212
+ "50282": {
213
+ "content": " ",
214
+ "lstrip": false,
215
+ "normalized": true,
216
+ "rstrip": false,
217
+ "single_word": false,
218
+ "special": false
219
+ },
220
+ "50283": {
221
+ "content": " ",
222
+ "lstrip": false,
223
+ "normalized": true,
224
+ "rstrip": false,
225
+ "single_word": false,
226
+ "special": false
227
+ },
228
+ "50284": {
229
+ "content": " ",
230
+ "lstrip": false,
231
+ "normalized": true,
232
+ "rstrip": false,
233
+ "single_word": false,
234
+ "special": false
235
+ },
236
+ "50285": {
237
+ "content": " ",
238
+ "lstrip": false,
239
+ "normalized": true,
240
+ "rstrip": false,
241
+ "single_word": false,
242
+ "special": false
243
+ },
244
+ "50286": {
245
+ "content": " ",
246
+ "lstrip": false,
247
+ "normalized": true,
248
+ "rstrip": false,
249
+ "single_word": false,
250
+ "special": false
251
+ },
252
+ "50287": {
253
+ "content": "\t\t\t\t\t\t\t\t\t",
254
+ "lstrip": false,
255
+ "normalized": true,
256
+ "rstrip": false,
257
+ "single_word": false,
258
+ "special": false
259
+ },
260
+ "50288": {
261
+ "content": "\t\t\t\t\t\t\t\t",
262
+ "lstrip": false,
263
+ "normalized": true,
264
+ "rstrip": false,
265
+ "single_word": false,
266
+ "special": false
267
+ },
268
+ "50289": {
269
+ "content": "\t\t\t\t\t\t\t",
270
+ "lstrip": false,
271
+ "normalized": true,
272
+ "rstrip": false,
273
+ "single_word": false,
274
+ "special": false
275
+ },
276
+ "50290": {
277
+ "content": "\t\t\t\t\t\t",
278
+ "lstrip": false,
279
+ "normalized": true,
280
+ "rstrip": false,
281
+ "single_word": false,
282
+ "special": false
283
+ },
284
+ "50291": {
285
+ "content": "\t\t\t\t\t",
286
+ "lstrip": false,
287
+ "normalized": true,
288
+ "rstrip": false,
289
+ "single_word": false,
290
+ "special": false
291
+ },
292
+ "50292": {
293
+ "content": "\t\t\t\t",
294
+ "lstrip": false,
295
+ "normalized": true,
296
+ "rstrip": false,
297
+ "single_word": false,
298
+ "special": false
299
+ },
300
+ "50293": {
301
+ "content": "\t\t\t",
302
+ "lstrip": false,
303
+ "normalized": true,
304
+ "rstrip": false,
305
+ "single_word": false,
306
+ "special": false
307
+ },
308
+ "50294": {
309
+ "content": "\t\t",
310
+ "lstrip": false,
311
+ "normalized": true,
312
+ "rstrip": false,
313
+ "single_word": false,
314
+ "special": false
315
+ }
316
+ },
317
+ "bos_token": "<|endoftext|>",
318
+ "chat_template": "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '<|user|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'system' %}\n{{ '<|system|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'assistant' %}\n{{ '<|assistant|>\n' + message['content'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}",
319
+ "clean_up_tokenization_spaces": true,
320
+ "eos_token": "<|endoftext|>",
321
+ "model_max_length": 2048,
322
+ "pad_token": "<|endoftext|>",
323
+ "tokenizer_class": "CodeGenTokenizer",
324
+ "unk_token": "<|endoftext|>"
325
+ }
checkpoint-5000/trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-5000/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1ea0f6490ef7cbf96af04c800c892792169fb673d5bd975ce072efb251ddbf2
3
+ size 6136
checkpoint-5000/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-5000/zero_to_fp32.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
153
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
154
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
155
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
156
+
157
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
158
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
159
+ # use the max of the partition_count to get the dp world_size.
160
+
161
+ if type(world_size) is list:
162
+ world_size = max(world_size)
163
+
164
+ if world_size != total_files:
165
+ raise ValueError(
166
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
167
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
168
+ )
169
+
170
+ # the groups are named differently in each stage
171
+ if zero_stage <= 2:
172
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
173
+ elif zero_stage == 3:
174
+ fp32_groups_key = FP32_FLAT_GROUPS
175
+ else:
176
+ raise ValueError(f"unknown zero stage {zero_stage}")
177
+
178
+ if zero_stage <= 2:
179
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
180
+ elif zero_stage == 3:
181
+ # if there is more than one param group, there will be multiple flattened tensors - one
182
+ # flattened tensor per group - for simplicity merge them into a single tensor
183
+ #
184
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
185
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
186
+
187
+ fp32_flat_groups = [
188
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
189
+ ]
190
+
191
+ return zero_stage, world_size, fp32_flat_groups
192
+
193
+
194
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir):
195
+ """
196
+ Returns fp32 state_dict reconstructed from ds checkpoint
197
+
198
+ Args:
199
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
200
+
201
+ """
202
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
203
+
204
+ optim_files = get_optim_files(ds_checkpoint_dir)
205
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
206
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
207
+
208
+ model_files = get_model_state_files(ds_checkpoint_dir)
209
+
210
+ zero_model_states = parse_model_states(model_files)
211
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
212
+
213
+ if zero_stage <= 2:
214
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states)
215
+ elif zero_stage == 3:
216
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states)
217
+
218
+
219
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
220
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
221
+ return
222
+
223
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
224
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
225
+
226
+ if debug:
227
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
228
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
229
+
230
+ wanted_params = len(frozen_param_shapes)
231
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
232
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
233
+ print(f'Frozen params: Have {avail_numel} numels to process.')
234
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
235
+
236
+ total_params = 0
237
+ total_numel = 0
238
+ for name, shape in frozen_param_shapes.items():
239
+ total_params += 1
240
+ unpartitioned_numel = shape.numel()
241
+ total_numel += unpartitioned_numel
242
+
243
+ state_dict[name] = frozen_param_fragments[name]
244
+
245
+ if debug:
246
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
247
+
248
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
249
+
250
+
251
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
252
+ param_shapes = zero_model_states[0].param_shapes
253
+
254
+ # Reconstruction protocol:
255
+ #
256
+ # XXX: document this
257
+
258
+ if debug:
259
+ for i in range(world_size):
260
+ for j in range(len(fp32_flat_groups[0])):
261
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
262
+
263
+ # XXX: memory usage doubles here (zero2)
264
+ num_param_groups = len(fp32_flat_groups[0])
265
+ merged_single_partition_of_fp32_groups = []
266
+ for i in range(num_param_groups):
267
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
268
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
269
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
270
+ avail_numel = sum(
271
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
272
+
273
+ if debug:
274
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
275
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
276
+ # not asserting if there is a mismatch due to possible padding
277
+ print(f"Have {avail_numel} numels to process.")
278
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
279
+
280
+ # params
281
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
282
+ # out-of-core computing solution
283
+ total_numel = 0
284
+ total_params = 0
285
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
286
+ offset = 0
287
+ avail_numel = full_single_fp32_vector.numel()
288
+ for name, shape in shapes.items():
289
+
290
+ unpartitioned_numel = shape.numel()
291
+ total_numel += unpartitioned_numel
292
+ total_params += 1
293
+
294
+ if debug:
295
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
296
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
297
+ offset += unpartitioned_numel
298
+
299
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
300
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
301
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
302
+ # live optimizer object, so we are checking that the numbers are within the right range
303
+ align_to = 2 * world_size
304
+
305
+ def zero2_align(x):
306
+ return align_to * math.ceil(x / align_to)
307
+
308
+ if debug:
309
+ print(f"original offset={offset}, avail_numel={avail_numel}")
310
+
311
+ offset = zero2_align(offset)
312
+ avail_numel = zero2_align(avail_numel)
313
+
314
+ if debug:
315
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
316
+
317
+ # Sanity check
318
+ if offset != avail_numel:
319
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
320
+
321
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
322
+
323
+
324
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states):
325
+ state_dict = OrderedDict()
326
+
327
+ # buffers
328
+ buffers = zero_model_states[0].buffers
329
+ state_dict.update(buffers)
330
+ if debug:
331
+ print(f"added {len(buffers)} buffers")
332
+
333
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
334
+
335
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
336
+
337
+ # recover shared parameters
338
+ for pair in zero_model_states[0].shared_params:
339
+ if pair[1] in state_dict:
340
+ state_dict[pair[0]] = state_dict[pair[1]]
341
+
342
+ return state_dict
343
+
344
+
345
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
346
+ remainder = unpartitioned_numel % world_size
347
+ padding_numel = (world_size - remainder) if remainder else 0
348
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
349
+ return partitioned_numel, padding_numel
350
+
351
+
352
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
353
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
354
+ return
355
+
356
+ if debug:
357
+ for i in range(world_size):
358
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
359
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
360
+
361
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
362
+ wanted_params = len(frozen_param_shapes)
363
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
364
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
365
+ print(f'Frozen params: Have {avail_numel} numels to process.')
366
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
367
+
368
+ total_params = 0
369
+ total_numel = 0
370
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
371
+ total_params += 1
372
+ unpartitioned_numel = shape.numel()
373
+ total_numel += unpartitioned_numel
374
+
375
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
376
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
377
+
378
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
379
+
380
+ if debug:
381
+ print(
382
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
383
+ )
384
+
385
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
386
+
387
+
388
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
389
+ param_shapes = zero_model_states[0].param_shapes
390
+ avail_numel = fp32_flat_groups[0].numel() * world_size
391
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
392
+ # param, re-consolidating each param, while dealing with padding if any
393
+
394
+ # merge list of dicts, preserving order
395
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
396
+
397
+ if debug:
398
+ for i in range(world_size):
399
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
400
+
401
+ wanted_params = len(param_shapes)
402
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
403
+ # not asserting if there is a mismatch due to possible padding
404
+ avail_numel = fp32_flat_groups[0].numel() * world_size
405
+ print(f"Trainable params: Have {avail_numel} numels to process.")
406
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
407
+
408
+ # params
409
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
410
+ # out-of-core computing solution
411
+ offset = 0
412
+ total_numel = 0
413
+ total_params = 0
414
+ for name, shape in param_shapes.items():
415
+
416
+ unpartitioned_numel = shape.numel()
417
+ total_numel += unpartitioned_numel
418
+ total_params += 1
419
+
420
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
421
+
422
+ if debug:
423
+ print(
424
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
425
+ )
426
+
427
+ # XXX: memory usage doubles here
428
+ state_dict[name] = torch.cat(
429
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
430
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
431
+ offset += partitioned_numel
432
+
433
+ offset *= world_size
434
+
435
+ # Sanity check
436
+ if offset != avail_numel:
437
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
438
+
439
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
440
+
441
+
442
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states):
443
+ state_dict = OrderedDict()
444
+
445
+ # buffers
446
+ buffers = zero_model_states[0].buffers
447
+ state_dict.update(buffers)
448
+ if debug:
449
+ print(f"added {len(buffers)} buffers")
450
+
451
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
452
+
453
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
454
+
455
+ # recover shared parameters
456
+ for pair in zero_model_states[0].shared_params:
457
+ if pair[1] in state_dict:
458
+ state_dict[pair[0]] = state_dict[pair[1]]
459
+
460
+ return state_dict
461
+
462
+
463
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None):
464
+ """
465
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
466
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
467
+ via a model hub.
468
+
469
+ Args:
470
+ - ``checkpoint_dir``: path to the desired checkpoint folder
471
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
472
+
473
+ Returns:
474
+ - pytorch ``state_dict``
475
+
476
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
477
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
478
+ the checkpoint.
479
+
480
+ A typical usage might be ::
481
+
482
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
483
+ # do the training and checkpoint saving
484
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
485
+ model = model.cpu() # move to cpu
486
+ model.load_state_dict(state_dict)
487
+ # submit to model hub or save the model to share with others
488
+
489
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
490
+ application. i.e. you will need to re-initialize the deepspeed engine, since
491
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
492
+
493
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
494
+
495
+ """
496
+ if tag is None:
497
+ latest_path = os.path.join(checkpoint_dir, 'latest')
498
+ if os.path.isfile(latest_path):
499
+ with open(latest_path, 'r') as fd:
500
+ tag = fd.read().strip()
501
+ else:
502
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
503
+
504
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
505
+
506
+ if not os.path.isdir(ds_checkpoint_dir):
507
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
508
+
509
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir)
510
+
511
+
512
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None):
513
+ """
514
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
515
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
516
+
517
+ Args:
518
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
519
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
520
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
521
+ """
522
+
523
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
524
+ print(f"Saving fp32 state dict to {output_file}")
525
+ torch.save(state_dict, output_file)
526
+
527
+
528
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
529
+ """
530
+ 1. Put the provided model to cpu
531
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
532
+ 3. Load it into the provided model
533
+
534
+ Args:
535
+ - ``model``: the model object to update
536
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
537
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
538
+
539
+ Returns:
540
+ - ``model`: modified model
541
+
542
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
543
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
544
+ conveniently placed for you in the checkpoint folder.
545
+
546
+ A typical usage might be ::
547
+
548
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
549
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
550
+ # submit to model hub or save the model to share with others
551
+
552
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
553
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
554
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
555
+
556
+ """
557
+ logger.info(f"Extracting fp32 weights")
558
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
559
+
560
+ logger.info(f"Overwriting model with fp32 weights")
561
+ model = model.cpu()
562
+ model.load_state_dict(state_dict, strict=False)
563
+
564
+ return model
565
+
566
+
567
+ if __name__ == "__main__":
568
+
569
+ parser = argparse.ArgumentParser()
570
+ parser.add_argument("checkpoint_dir",
571
+ type=str,
572
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
573
+ parser.add_argument(
574
+ "output_file",
575
+ type=str,
576
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
577
+ parser.add_argument("-t",
578
+ "--tag",
579
+ type=str,
580
+ default=None,
581
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
582
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
583
+ args = parser.parse_args()
584
+
585
+ debug = args.debug
586
+
587
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag)
checkpoint-5500/added_tokens.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "\t\t": 50294,
3
+ "\t\t\t": 50293,
4
+ "\t\t\t\t": 50292,
5
+ "\t\t\t\t\t": 50291,
6
+ "\t\t\t\t\t\t": 50290,
7
+ "\t\t\t\t\t\t\t": 50289,
8
+ "\t\t\t\t\t\t\t\t": 50288,
9
+ "\t\t\t\t\t\t\t\t\t": 50287,
10
+ " ": 50286,
11
+ " ": 50285,
12
+ " ": 50284,
13
+ " ": 50283,
14
+ " ": 50282,
15
+ " ": 50281,
16
+ " ": 50280,
17
+ " ": 50279,
18
+ " ": 50278,
19
+ " ": 50277,
20
+ " ": 50276,
21
+ " ": 50275,
22
+ " ": 50274,
23
+ " ": 50273,
24
+ " ": 50272,
25
+ " ": 50271,
26
+ " ": 50270,
27
+ " ": 50269,
28
+ " ": 50268,
29
+ " ": 50267,
30
+ " ": 50266,
31
+ " ": 50265,
32
+ " ": 50264,
33
+ " ": 50263,
34
+ " ": 50262,
35
+ " ": 50261,
36
+ " ": 50260,
37
+ " ": 50259,
38
+ " ": 50258,
39
+ " ": 50257
40
+ }
checkpoint-5500/config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "microsoft/phi-1_5",
3
+ "architectures": [
4
+ "PhiForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi.PhiConfig",
9
+ "AutoModelForCausalLM": "modeling_phi.PhiForCausalLM"
10
+ },
11
+ "bos_token_id": null,
12
+ "embd_pdrop": 0.0,
13
+ "eos_token_id": null,
14
+ "hidden_act": "gelu_new",
15
+ "hidden_size": 2048,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 8192,
18
+ "layer_norm_eps": 1e-05,
19
+ "max_position_embeddings": 2048,
20
+ "model_type": "phi",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 24,
23
+ "num_key_value_heads": 32,
24
+ "partial_rotary_factor": 0.5,
25
+ "qk_layernorm": false,
26
+ "resid_pdrop": 0.0,
27
+ "rope_scaling": null,
28
+ "rope_theta": 10000.0,
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.38.0",
32
+ "use_cache": false,
33
+ "vocab_size": 51200
34
+ }
checkpoint-5500/configuration_phi.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ Phi model configuration"""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/phi-1_5": "https://huggingface.co/microsoft/phi-1_5/resolve/main/config.json",
27
+ }
28
+
29
+
30
+ class PhiConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the Phi
35
+ [microsoft/phi-1](https://huggingface.co/microsoft/phi-1).
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 51200):
42
+ Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`PhiModel`].
44
+ hidden_size (`int`, *optional*, defaults to 2048):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 8192):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 24):
49
+ Number of hidden layers in the Transformer decoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
61
+ Dropout probability for mlp outputs.
62
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
63
+ The dropout ratio for the embeddings.
64
+ attention_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio after computing the attention scores.
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
70
+ tokens.
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
74
+ The epsilon used by the rms normalization layers.
75
+ use_cache (`bool`, *optional*, defaults to `True`):
76
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
77
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ rope_scaling (`Dict`, *optional*):
83
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
84
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
85
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
86
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
87
+ these scaling strategies behave:
88
+ https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
89
+ is an experimental feature, subject to breaking API changes in future versions.
90
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
91
+ Percentage of the query and keys which will have rotary embedding.
92
+ qk_layernorm (`bool`, *optional*, defaults to `False`):
93
+ Whether or not to normalize the Queries and Keys after projecting the hidden states.
94
+ bos_token_id (`int`, *optional*, defaults to 1):
95
+ Denotes beginning of sequences token id.
96
+ eos_token_id (`int`, *optional*, defaults to 2):
97
+ Denotes end of sequences token id.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import PhiModel, PhiConfig
103
+
104
+ >>> # Initializing a Phi-1 style configuration
105
+ >>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = PhiModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=51200,
120
+ hidden_size=2048,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=24,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="gelu_new",
129
+ max_position_embeddings=2048,
130
+ initializer_range=0.02,
131
+ layer_norm_eps=1e-5,
132
+ use_cache=True,
133
+ tie_word_embeddings=False,
134
+ rope_theta=10000.0,
135
+ rope_scaling=None,
136
+ partial_rotary_factor=0.5,
137
+ qk_layernorm=False,
138
+ bos_token_id=1,
139
+ eos_token_id=2,
140
+ **kwargs,
141
+ ):
142
+ self.vocab_size = vocab_size
143
+ self.hidden_size = hidden_size
144
+ self.intermediate_size = intermediate_size
145
+ self.num_hidden_layers = num_hidden_layers
146
+ self.num_attention_heads = num_attention_heads
147
+
148
+ if num_key_value_heads is None:
149
+ num_key_value_heads = num_attention_heads
150
+
151
+ self.num_key_value_heads = num_key_value_heads
152
+ self.resid_pdrop = resid_pdrop
153
+ self.embd_pdrop = embd_pdrop
154
+ self.attention_dropout = attention_dropout
155
+ self.hidden_act = hidden_act
156
+ self.max_position_embeddings = max_position_embeddings
157
+ self.initializer_range = initializer_range
158
+ self.layer_norm_eps = layer_norm_eps
159
+ self.use_cache = use_cache
160
+ self.rope_theta = rope_theta
161
+ self.rope_scaling = rope_scaling
162
+ self.partial_rotary_factor = partial_rotary_factor
163
+ self.qk_layernorm = qk_layernorm
164
+ self._rope_scaling_validation()
165
+
166
+ super().__init__(
167
+ bos_token_id=bos_token_id,
168
+ eos_token_id=eos_token_id,
169
+ tie_word_embeddings=tie_word_embeddings,
170
+ **kwargs,
171
+ )
172
+
173
+ # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
174
+ def _rope_scaling_validation(self):
175
+ """
176
+ Validate the `rope_scaling` configuration.
177
+ """
178
+ if self.rope_scaling is None:
179
+ return
180
+
181
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
182
+ raise ValueError(
183
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
184
+ f"got {self.rope_scaling}"
185
+ )
186
+ rope_scaling_type = self.rope_scaling.get("type", None)
187
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
188
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
189
+ raise ValueError(
190
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
191
+ )
192
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
193
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
checkpoint-5500/generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.38.0"
4
+ }
checkpoint-5500/global_step5500/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e8b98e6ff23ff6cafd6221ab76dd7a822af01e157a3ac4df5aae6ded49167c3
3
+ size 4254816816
checkpoint-5500/global_step5500/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3d75b4f52a8aa7c26a6864a0333af8419a4b33788774d65d1e8f77ca3740b57d
3
+ size 4254816816
checkpoint-5500/global_step5500/bf16_zero_pp_rank_2_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a22a2003d7fc92d4e54a85d52782a61af59be3cdb55500c4a00b2129a7cdeb57
3
+ size 4254816816
checkpoint-5500/global_step5500/bf16_zero_pp_rank_3_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7566fff40c2f25c5be08126fc1432940dcb93b7935f3c7a5632b417f20ffe06d
3
+ size 4254816816
checkpoint-5500/global_step5500/zero_pp_rank_0_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f85add70596282beaf64fb38a9b4613444eb9cd78283bcf5070b283389e433c
3
+ size 161935
checkpoint-5500/global_step5500/zero_pp_rank_1_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb057680da9d9cf6a3458a8af50e3bf21515059c2d50ce3d754279f90205bfc4
3
+ size 161935
checkpoint-5500/global_step5500/zero_pp_rank_2_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5f3dca978a2e4583928010c4c732480f3ba1f2b394d9700b77dcf8428237bd5
3
+ size 161935
checkpoint-5500/global_step5500/zero_pp_rank_3_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e067ceac16932a8f652c1539e565f22cfa3130d289ad31afceddc6bcb239b024
3
+ size 161935
checkpoint-5500/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step5500
checkpoint-5500/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-5500/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ef1638eb2e4cedf8945446e599cbff4a76646c9ffd9b35fcfdef4ca3e34f995
3
+ size 2836579040
checkpoint-5500/modeling_phi.py ADDED
@@ -0,0 +1,1369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi model."""
17
+
18
+
19
+ import math
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache
30
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ SequenceClassifierOutputWithPast,
35
+ TokenClassifierOutput,
36
+ )
37
+ from transformers.modeling_utils import PreTrainedModel
38
+ from transformers.utils import (
39
+ add_code_sample_docstrings,
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ is_flash_attn_2_available,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_phi import PhiConfig
48
+
49
+
50
+ try: # noqa: SIM105
51
+ if is_flash_attn_2_available():
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
54
+ except ImportError:
55
+ # Workaround for https://github.com/huggingface/transformers/issues/28459,
56
+ # don't move to contextlib.suppress(ImportError)
57
+ pass
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CHECKPOINT_FOR_DOC = "microsoft/phi-1_5"
63
+ _CONFIG_FOR_DOC = "PhiConfig"
64
+
65
+ PHI_PRETRAINED_MODEL_ARCHIVE_LIST = [
66
+ "microsoft/phi-1_5",
67
+ # See all Phi models at https://huggingface.co/models?filter=phi
68
+ ]
69
+
70
+
71
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
72
+ def _get_unpad_data(attention_mask):
73
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
74
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
75
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
76
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
77
+ return (
78
+ indices,
79
+ cu_seqlens,
80
+ max_seqlen_in_batch,
81
+ )
82
+
83
+
84
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Phi
85
+ class PhiRotaryEmbedding(nn.Module):
86
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
87
+ super().__init__()
88
+
89
+ self.dim = dim
90
+ self.max_position_embeddings = max_position_embeddings
91
+ self.base = base
92
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
93
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
94
+
95
+ # Build here to make `torch.jit.trace` work.
96
+ self._set_cos_sin_cache(
97
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
98
+ )
99
+
100
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
101
+ self.max_seq_len_cached = seq_len
102
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
103
+
104
+ freqs = torch.outer(t, self.inv_freq)
105
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
106
+ emb = torch.cat((freqs, freqs), dim=-1)
107
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
108
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
109
+
110
+ def forward(self, x, seq_len=None):
111
+ # x: [bs, num_attention_heads, seq_len, head_size]
112
+ if seq_len > self.max_seq_len_cached:
113
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
114
+
115
+ return (
116
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
117
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
118
+ )
119
+
120
+
121
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Phi
122
+ class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
123
+ """PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
124
+
125
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
126
+ self.scaling_factor = scaling_factor
127
+ super().__init__(dim, max_position_embeddings, base, device)
128
+
129
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
130
+ self.max_seq_len_cached = seq_len
131
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
132
+ t = t / self.scaling_factor
133
+
134
+ freqs = torch.outer(t, self.inv_freq)
135
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
138
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
139
+
140
+
141
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Phi
142
+ class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
143
+ """PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
144
+
145
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
146
+ self.scaling_factor = scaling_factor
147
+ super().__init__(dim, max_position_embeddings, base, device)
148
+
149
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
150
+ self.max_seq_len_cached = seq_len
151
+
152
+ if seq_len > self.max_position_embeddings:
153
+ base = self.base * (
154
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
155
+ ) ** (self.dim / (self.dim - 2))
156
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
157
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
158
+
159
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
160
+
161
+ freqs = torch.outer(t, self.inv_freq)
162
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
163
+ emb = torch.cat((freqs, freqs), dim=-1)
164
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
165
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
166
+
167
+
168
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
169
+ def rotate_half(x):
170
+ """Rotates half the hidden dims of the input."""
171
+ x1 = x[..., : x.shape[-1] // 2]
172
+ x2 = x[..., x.shape[-1] // 2 :]
173
+ return torch.cat((-x2, x1), dim=-1)
174
+
175
+
176
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
177
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
178
+ """Applies Rotary Position Embedding to the query and key tensors.
179
+
180
+ Args:
181
+ q (`torch.Tensor`): The query tensor.
182
+ k (`torch.Tensor`): The key tensor.
183
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
184
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
185
+ position_ids (`torch.Tensor`):
186
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
187
+ used to pass offsetted position ids when working with a KV-cache.
188
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
189
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
190
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
191
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
192
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
193
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
194
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
195
+ Returns:
196
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
197
+ """
198
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
199
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
200
+ q_embed = (q * cos) + (rotate_half(q) * sin)
201
+ k_embed = (k * cos) + (rotate_half(k) * sin)
202
+ return q_embed, k_embed
203
+
204
+
205
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
206
+ class PhiMLP(nn.Module):
207
+ def __init__(self, config):
208
+ super().__init__()
209
+ self.config = config
210
+ self.activation_fn = ACT2FN[config.hidden_act]
211
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
212
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
213
+
214
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
215
+ hidden_states = self.fc1(hidden_states)
216
+ hidden_states = self.activation_fn(hidden_states)
217
+ hidden_states = self.fc2(hidden_states)
218
+ return hidden_states
219
+
220
+
221
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
222
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
223
+ """
224
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
225
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
226
+ """
227
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
228
+ if n_rep == 1:
229
+ return hidden_states
230
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
231
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
232
+
233
+
234
+ class PhiAttention(nn.Module):
235
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
236
+
237
+ def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
238
+ super().__init__()
239
+ self.config = config
240
+ self.layer_idx = layer_idx
241
+ if layer_idx is None:
242
+ logger.warning_once(
243
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
244
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
245
+ "when creating this class."
246
+ )
247
+
248
+ self.attention_dropout = config.attention_dropout
249
+ self.hidden_size = config.hidden_size
250
+ self.num_heads = config.num_attention_heads
251
+ self.head_dim = self.hidden_size // self.num_heads
252
+ self.num_key_value_heads = config.num_key_value_heads
253
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
254
+ self.max_position_embeddings = config.max_position_embeddings
255
+ self.rope_theta = config.rope_theta
256
+ self.partial_rotary_factor = config.partial_rotary_factor
257
+ self.is_causal = True
258
+
259
+ if (self.head_dim * self.num_heads) != self.hidden_size:
260
+ raise ValueError(
261
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
262
+ f" and `num_heads`: {self.num_heads})."
263
+ )
264
+
265
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
266
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
267
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
268
+ self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
269
+
270
+ self.qk_layernorm = config.qk_layernorm
271
+ if self.qk_layernorm:
272
+ self.q_layernorm = nn.LayerNorm(
273
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
274
+ )
275
+ self.k_layernorm = nn.LayerNorm(
276
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
277
+ )
278
+
279
+ self._init_rope()
280
+
281
+ def _init_rope(self):
282
+ if self.config.rope_scaling is None:
283
+ self.rotary_emb = PhiRotaryEmbedding(
284
+ int(self.partial_rotary_factor * self.head_dim),
285
+ max_position_embeddings=self.max_position_embeddings,
286
+ base=self.rope_theta,
287
+ )
288
+ else:
289
+ scaling_type = self.config.rope_scaling["type"]
290
+ scaling_factor = self.config.rope_scaling["factor"]
291
+ if scaling_type == "linear":
292
+ self.rotary_emb = PhiLinearScalingRotaryEmbedding(
293
+ int(self.partial_rotary_factor * self.head_dim),
294
+ max_position_embeddings=self.max_position_embeddings,
295
+ scaling_factor=scaling_factor,
296
+ base=self.rope_theta,
297
+ )
298
+ elif scaling_type == "dynamic":
299
+ self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
300
+ int(self.partial_rotary_factor * self.head_dim),
301
+ max_position_embeddings=self.max_position_embeddings,
302
+ scaling_factor=scaling_factor,
303
+ base=self.rope_theta,
304
+ )
305
+ else:
306
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
307
+
308
+ def forward(
309
+ self,
310
+ hidden_states: torch.Tensor,
311
+ attention_mask: Optional[torch.Tensor] = None,
312
+ position_ids: Optional[torch.LongTensor] = None,
313
+ past_key_value: Optional[Cache] = None,
314
+ output_attentions: bool = False,
315
+ use_cache: bool = False,
316
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
317
+ bsz, q_len, _ = hidden_states.size()
318
+
319
+ query_states = self.q_proj(hidden_states)
320
+ key_states = self.k_proj(hidden_states)
321
+ value_states = self.v_proj(hidden_states)
322
+
323
+ if self.qk_layernorm:
324
+ query_states = self.q_layernorm(query_states)
325
+ key_states = self.k_layernorm(key_states)
326
+
327
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
328
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
329
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
330
+
331
+ kv_seq_len = key_states.shape[-2]
332
+ if past_key_value is not None:
333
+ if self.layer_idx is None:
334
+ raise ValueError(
335
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
336
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
337
+ "with a layer index."
338
+ )
339
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
340
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
341
+
342
+ # Partial rotary embedding
343
+ query_rot, query_pass = (
344
+ query_states[..., : self.rotary_emb.dim],
345
+ query_states[..., self.rotary_emb.dim :],
346
+ )
347
+ key_rot, key_pass = (
348
+ key_states[..., : self.rotary_emb.dim],
349
+ key_states[..., self.rotary_emb.dim :],
350
+ )
351
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
352
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
353
+
354
+ # [batch_size, seq_length, num_heads, head_dim]
355
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
356
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
357
+
358
+ if past_key_value is not None:
359
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
360
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
361
+
362
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
363
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
364
+
365
+ # Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
366
+ attn_weights = torch.matmul(
367
+ query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
368
+ ) / math.sqrt(self.head_dim)
369
+
370
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
371
+ raise ValueError(
372
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
373
+ f" {attn_weights.size()}"
374
+ )
375
+
376
+ if attention_mask is not None:
377
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
378
+ raise ValueError(
379
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
380
+ )
381
+ attn_weights = attn_weights + attention_mask
382
+
383
+ # upcast attention to fp32
384
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
385
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
386
+
387
+ attn_output = torch.matmul(attn_weights, value_states)
388
+
389
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
390
+ raise ValueError(
391
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
392
+ f" {attn_output.size()}"
393
+ )
394
+
395
+ attn_output = attn_output.transpose(1, 2).contiguous()
396
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
397
+
398
+ attn_output = self.dense(attn_output)
399
+
400
+ if not output_attentions:
401
+ attn_weights = None
402
+
403
+ return attn_output, attn_weights, past_key_value
404
+
405
+
406
+ class PhiFlashAttention2(PhiAttention):
407
+ """
408
+ Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
409
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
410
+ flash attention and deal with padding tokens in case the input contains any of them.
411
+ """
412
+
413
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
414
+ def __init__(self, *args, **kwargs):
415
+ super().__init__(*args, **kwargs)
416
+
417
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
418
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
419
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
420
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
421
+
422
+ def forward(
423
+ self,
424
+ hidden_states: torch.Tensor,
425
+ attention_mask: Optional[torch.LongTensor] = None,
426
+ position_ids: Optional[torch.LongTensor] = None,
427
+ past_key_value: Optional[Cache] = None,
428
+ output_attentions: bool = False,
429
+ use_cache: bool = False,
430
+ **kwargs,
431
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
432
+ # PhiFlashAttention2 attention does not support output_attentions
433
+
434
+ output_attentions = False
435
+
436
+ bsz, q_len, _ = hidden_states.size()
437
+
438
+ query_states = self.q_proj(hidden_states)
439
+ key_states = self.k_proj(hidden_states)
440
+ value_states = self.v_proj(hidden_states)
441
+
442
+ if self.qk_layernorm:
443
+ query_states = self.q_layernorm(query_states)
444
+ key_states = self.k_layernorm(key_states)
445
+
446
+ # Flash attention requires the input to have the shape
447
+ # batch_size x seq_length x head_dim x hidden_dim
448
+ # therefore we just need to keep the original shape
449
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
450
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
451
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
452
+
453
+ kv_seq_len = key_states.shape[-2]
454
+ if past_key_value is not None:
455
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
456
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
457
+
458
+ # Partial rotary embedding
459
+ query_rot, query_pass = (
460
+ query_states[..., : self.rotary_emb.dim],
461
+ query_states[..., self.rotary_emb.dim :],
462
+ )
463
+ key_rot, key_pass = (
464
+ key_states[..., : self.rotary_emb.dim],
465
+ key_states[..., self.rotary_emb.dim :],
466
+ )
467
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
468
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
469
+
470
+ # [batch_size, seq_length, num_heads, head_dim]
471
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
472
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
473
+
474
+ if past_key_value is not None:
475
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
476
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
477
+
478
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
479
+ # to be able to avoid many of these transpose/reshape/view.
480
+ query_states = query_states.transpose(1, 2)
481
+ key_states = key_states.transpose(1, 2)
482
+ value_states = value_states.transpose(1, 2)
483
+
484
+ attn_dropout = self.attention_dropout if self.training else 0.0
485
+
486
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
487
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
488
+ # cast them back in the correct dtype just to be sure everything works as expected.
489
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
490
+ # in fp32.
491
+
492
+ if query_states.dtype == torch.float32:
493
+ if torch.is_autocast_enabled():
494
+ target_dtype = torch.get_autocast_gpu_dtype()
495
+ # Handle the case where the model is quantized
496
+ elif hasattr(self.config, "_pre_quantization_dtype"):
497
+ target_dtype = self.config._pre_quantization_dtype
498
+ else:
499
+ target_dtype = self.q_proj.weight.dtype
500
+
501
+ logger.warning_once(
502
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
503
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
504
+ f" {target_dtype}."
505
+ )
506
+
507
+ query_states = query_states.to(target_dtype)
508
+ key_states = key_states.to(target_dtype)
509
+ value_states = value_states.to(target_dtype)
510
+
511
+ attn_output = self._flash_attention_forward(
512
+ query_states, key_states, value_states, attention_mask, q_len, dropout=attn_dropout, softmax_scale=None
513
+ )
514
+
515
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
516
+ attn_output = self.dense(attn_output)
517
+
518
+ if not output_attentions:
519
+ attn_weights = None
520
+
521
+ return attn_output, attn_weights, past_key_value
522
+
523
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
524
+ def _flash_attention_forward(
525
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
526
+ ):
527
+ """
528
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
529
+ first unpad the input, then computes the attention scores and pad the final attention scores.
530
+
531
+ Args:
532
+ query_states (`torch.Tensor`):
533
+ Input query states to be passed to Flash Attention API
534
+ key_states (`torch.Tensor`):
535
+ Input key states to be passed to Flash Attention API
536
+ value_states (`torch.Tensor`):
537
+ Input value states to be passed to Flash Attention API
538
+ attention_mask (`torch.Tensor`):
539
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
540
+ position of padding tokens and 1 for the position of non-padding tokens.
541
+ dropout (`int`, *optional*):
542
+ Attention dropout
543
+ softmax_scale (`float`, *optional*):
544
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
545
+ """
546
+ if not self._flash_attn_uses_top_left_mask:
547
+ causal = self.is_causal
548
+ else:
549
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
550
+ causal = self.is_causal and query_length != 1
551
+
552
+ # Contains at least one padding token in the sequence
553
+ if attention_mask is not None:
554
+ batch_size = query_states.shape[0]
555
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
556
+ query_states, key_states, value_states, attention_mask, query_length
557
+ )
558
+
559
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
560
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
561
+
562
+ attn_output_unpad = flash_attn_varlen_func(
563
+ query_states,
564
+ key_states,
565
+ value_states,
566
+ cu_seqlens_q=cu_seqlens_q,
567
+ cu_seqlens_k=cu_seqlens_k,
568
+ max_seqlen_q=max_seqlen_in_batch_q,
569
+ max_seqlen_k=max_seqlen_in_batch_k,
570
+ dropout_p=dropout,
571
+ softmax_scale=softmax_scale,
572
+ causal=causal,
573
+ )
574
+
575
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
576
+ else:
577
+ attn_output = flash_attn_func(
578
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
579
+ )
580
+
581
+ return attn_output
582
+
583
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
584
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
585
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
586
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
587
+
588
+ key_layer = index_first_axis(
589
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
590
+ )
591
+ value_layer = index_first_axis(
592
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
593
+ )
594
+ if query_length == kv_seq_len:
595
+ query_layer = index_first_axis(
596
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
597
+ )
598
+ cu_seqlens_q = cu_seqlens_k
599
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
600
+ indices_q = indices_k
601
+ elif query_length == 1:
602
+ max_seqlen_in_batch_q = 1
603
+ cu_seqlens_q = torch.arange(
604
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
605
+ ) # There is a memcpy here, that is very bad.
606
+ indices_q = cu_seqlens_q[:-1]
607
+ query_layer = query_layer.squeeze(1)
608
+ else:
609
+ # The -q_len: slice assumes left padding.
610
+ attention_mask = attention_mask[:, -query_length:]
611
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
612
+
613
+ return (
614
+ query_layer,
615
+ key_layer,
616
+ value_layer,
617
+ indices_q,
618
+ (cu_seqlens_q, cu_seqlens_k),
619
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
620
+ )
621
+
622
+
623
+ PHI_ATTENTION_CLASSES = {
624
+ "eager": PhiAttention,
625
+ "flash_attention_2": PhiFlashAttention2,
626
+ }
627
+
628
+
629
+ class PhiDecoderLayer(nn.Module):
630
+ def __init__(self, config: PhiConfig, layer_idx: int):
631
+ super().__init__()
632
+ self.self_attn = PHI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
633
+ self.mlp = PhiMLP(config)
634
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
635
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
636
+
637
+ def forward(
638
+ self,
639
+ hidden_states: torch.Tensor,
640
+ attention_mask: Optional[torch.Tensor] = None,
641
+ position_ids: Optional[torch.LongTensor] = None,
642
+ output_attentions: Optional[bool] = False,
643
+ use_cache: Optional[bool] = False,
644
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
645
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
646
+ """
647
+ Args:
648
+ hidden_states (`torch.FloatTensor`):
649
+ input to the layer of shape `(batch, seq_len, embed_dim)`
650
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
651
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
652
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
653
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
654
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
655
+ output_attentions (`bool`, *optional*):
656
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
657
+ returned tensors for more detail.
658
+ use_cache (`bool`, *optional*):
659
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
660
+ (see `past_key_values`).
661
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
662
+ """
663
+
664
+ residual = hidden_states
665
+
666
+ hidden_states = self.input_layernorm(hidden_states)
667
+
668
+ # Self Attention
669
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
670
+ hidden_states=hidden_states,
671
+ attention_mask=attention_mask,
672
+ position_ids=position_ids,
673
+ past_key_value=past_key_value,
674
+ output_attentions=output_attentions,
675
+ use_cache=use_cache,
676
+ )
677
+ attn_outputs = self.resid_dropout(attn_outputs)
678
+
679
+ feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
680
+ hidden_states = attn_outputs + feed_forward_hidden_states + residual
681
+ outputs = (hidden_states,)
682
+
683
+ if output_attentions:
684
+ outputs += (self_attn_weights,)
685
+
686
+ if use_cache:
687
+ outputs += (present_key_value,)
688
+
689
+ return outputs
690
+
691
+
692
+ PHI_START_DOCSTRING = r"""
693
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
694
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
695
+ etc.)
696
+
697
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
698
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
699
+ and behavior.
700
+
701
+ Parameters:
702
+ config ([`PhiConfig`]):
703
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
704
+ load the weights associated with the model, only the configuration. Check out the
705
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
706
+ """
707
+
708
+
709
+ @add_start_docstrings(
710
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
711
+ PHI_START_DOCSTRING,
712
+ )
713
+ class PhiPreTrainedModel(PreTrainedModel):
714
+ config_class = PhiConfig
715
+ base_model_prefix = "model"
716
+ supports_gradient_checkpointing = True
717
+ _no_split_modules = ["PhiDecoderLayer"]
718
+ _skip_keys_device_placement = "past_key_values"
719
+ _supports_flash_attn_2 = True
720
+ _supports_cache_class = True
721
+
722
+ def _init_weights(self, module):
723
+ std = self.config.initializer_range
724
+ if isinstance(module, nn.Linear):
725
+ module.weight.data.normal_(mean=0.0, std=std)
726
+ if module.bias is not None:
727
+ module.bias.data.zero_()
728
+ elif isinstance(module, nn.Embedding):
729
+ module.weight.data.normal_(mean=0.0, std=std)
730
+ if module.padding_idx is not None:
731
+ module.weight.data[module.padding_idx].zero_()
732
+
733
+
734
+ PHI_INPUTS_DOCSTRING = r"""
735
+ Args:
736
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
737
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
738
+ it.
739
+
740
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
741
+ [`PreTrainedTokenizer.__call__`] for details.
742
+
743
+ [What are input IDs?](../glossary#input-ids)
744
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
745
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
746
+
747
+ - 1 for tokens that are **not masked**,
748
+ - 0 for tokens that are **masked**.
749
+
750
+ [What are attention masks?](../glossary#attention-mask)
751
+
752
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
753
+ [`PreTrainedTokenizer.__call__`] for details.
754
+
755
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
756
+ `past_key_values`).
757
+
758
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
759
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
760
+ information on the default strategy.
761
+
762
+ - 1 indicates the head is **not masked**,
763
+ - 0 indicates the head is **masked**.
764
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
765
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
766
+ config.n_positions - 1]`.
767
+
768
+ [What are position IDs?](../glossary#position-ids)
769
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
770
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
771
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
772
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
773
+
774
+ Two formats are allowed:
775
+ - a [`~cache_utils.Cache`] instance;
776
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
777
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
778
+ cache format.
779
+
780
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
781
+ legacy cache format will be returned.
782
+
783
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
784
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
785
+ of shape `(batch_size, sequence_length)`.
786
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
787
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
788
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
789
+ model's internal embedding lookup matrix.
790
+ use_cache (`bool`, *optional*):
791
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
792
+ `past_key_values`).
793
+ output_attentions (`bool`, *optional*):
794
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
795
+ tensors for more detail.
796
+ output_hidden_states (`bool`, *optional*):
797
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
798
+ more detail.
799
+ return_dict (`bool`, *optional*):
800
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
801
+ """
802
+
803
+
804
+ @add_start_docstrings(
805
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
806
+ PHI_START_DOCSTRING,
807
+ )
808
+ class PhiModel(PhiPreTrainedModel):
809
+ """
810
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
811
+
812
+ Args:
813
+ config: PhiConfig
814
+ """
815
+
816
+ def __init__(self, config: PhiConfig):
817
+ super().__init__(config)
818
+ self.padding_idx = config.pad_token_id
819
+ self.vocab_size = config.vocab_size
820
+
821
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
822
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
823
+ self.layers = nn.ModuleList(
824
+ [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
825
+ )
826
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
827
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
828
+
829
+ self.gradient_checkpointing = False
830
+ # Initialize weights and apply final processing
831
+ self.post_init()
832
+
833
+ def get_input_embeddings(self):
834
+ return self.embed_tokens
835
+
836
+ def set_input_embeddings(self, value):
837
+ self.embed_tokens = value
838
+
839
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
840
+ def forward(
841
+ self,
842
+ input_ids: torch.LongTensor = None,
843
+ attention_mask: Optional[torch.Tensor] = None,
844
+ position_ids: Optional[torch.LongTensor] = None,
845
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
846
+ inputs_embeds: Optional[torch.FloatTensor] = None,
847
+ use_cache: Optional[bool] = None,
848
+ output_attentions: Optional[bool] = None,
849
+ output_hidden_states: Optional[bool] = None,
850
+ return_dict: Optional[bool] = None,
851
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
852
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
853
+ output_hidden_states = (
854
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
855
+ )
856
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
857
+
858
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
859
+
860
+ # retrieve input_ids and inputs_embeds
861
+ if input_ids is not None and inputs_embeds is not None:
862
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
863
+ elif input_ids is not None:
864
+ batch_size, seq_length = input_ids.shape[:2]
865
+ elif inputs_embeds is not None:
866
+ batch_size, seq_length = inputs_embeds.shape[:2]
867
+ else:
868
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
869
+
870
+ past_key_values_length = 0
871
+
872
+ if self.gradient_checkpointing and self.training:
873
+ if use_cache:
874
+ logger.warning_once(
875
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
876
+ )
877
+ use_cache = False
878
+
879
+ if use_cache:
880
+ use_legacy_cache = not isinstance(past_key_values, Cache)
881
+ if use_legacy_cache:
882
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
883
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
884
+
885
+ if position_ids is None:
886
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
887
+ position_ids = torch.arange(
888
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
889
+ )
890
+ position_ids = position_ids.unsqueeze(0)
891
+
892
+ if inputs_embeds is None:
893
+ inputs_embeds = self.embed_tokens(input_ids)
894
+
895
+ inputs_embeds = self.embed_dropout(inputs_embeds)
896
+
897
+ # Attention mask.
898
+ if self._use_flash_attention_2:
899
+ # 2d mask is passed through the layers
900
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
901
+ else:
902
+ # 4d mask is passed through the layers
903
+ attention_mask = _prepare_4d_causal_attention_mask(
904
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
905
+ )
906
+
907
+ hidden_states = inputs_embeds
908
+
909
+ # decoder layers
910
+ all_hidden_states = () if output_hidden_states else None
911
+ all_self_attns = () if output_attentions else None
912
+ next_decoder_cache = None
913
+
914
+ for decoder_layer in self.layers:
915
+ if output_hidden_states:
916
+ all_hidden_states += (hidden_states,)
917
+
918
+ if self.gradient_checkpointing and self.training:
919
+ layer_outputs = self._gradient_checkpointing_func(
920
+ decoder_layer.__call__,
921
+ hidden_states,
922
+ attention_mask,
923
+ position_ids,
924
+ past_key_values,
925
+ output_attentions,
926
+ )
927
+ else:
928
+ layer_outputs = decoder_layer(
929
+ hidden_states,
930
+ attention_mask=attention_mask,
931
+ position_ids=position_ids,
932
+ past_key_value=past_key_values,
933
+ output_attentions=output_attentions,
934
+ use_cache=use_cache,
935
+ )
936
+
937
+ hidden_states = layer_outputs[0]
938
+
939
+ if use_cache:
940
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
941
+
942
+ if output_attentions:
943
+ all_self_attns += (layer_outputs[1],)
944
+
945
+ hidden_states = self.final_layernorm(hidden_states)
946
+
947
+ # add hidden states from the last decoder layer
948
+ if output_hidden_states:
949
+ all_hidden_states += (hidden_states,)
950
+
951
+ next_cache = None
952
+ if use_cache:
953
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
954
+ if not return_dict:
955
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
956
+ return BaseModelOutputWithPast(
957
+ last_hidden_state=hidden_states,
958
+ past_key_values=next_cache,
959
+ hidden_states=all_hidden_states,
960
+ attentions=all_self_attns,
961
+ )
962
+
963
+
964
+ class PhiForCausalLM(PhiPreTrainedModel):
965
+ _tied_weights_keys = ["lm_head.weight"]
966
+
967
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
968
+ def __init__(self, config):
969
+ super().__init__(config)
970
+ self.model = PhiModel(config)
971
+ self.vocab_size = config.vocab_size
972
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
973
+
974
+ # Initialize weights and apply final processing
975
+ self.post_init()
976
+
977
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
978
+ def get_input_embeddings(self):
979
+ return self.model.embed_tokens
980
+
981
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
982
+ def set_input_embeddings(self, value):
983
+ self.model.embed_tokens = value
984
+
985
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
986
+ def get_output_embeddings(self):
987
+ return self.lm_head
988
+
989
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
990
+ def set_output_embeddings(self, new_embeddings):
991
+ self.lm_head = new_embeddings
992
+
993
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
994
+ def set_decoder(self, decoder):
995
+ self.model = decoder
996
+
997
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
998
+ def get_decoder(self):
999
+ return self.model
1000
+
1001
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1002
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1003
+ def forward(
1004
+ self,
1005
+ input_ids: torch.LongTensor = None,
1006
+ attention_mask: Optional[torch.Tensor] = None,
1007
+ position_ids: Optional[torch.LongTensor] = None,
1008
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1009
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1010
+ labels: Optional[torch.LongTensor] = None,
1011
+ use_cache: Optional[bool] = None,
1012
+ output_attentions: Optional[bool] = None,
1013
+ output_hidden_states: Optional[bool] = None,
1014
+ return_dict: Optional[bool] = None,
1015
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1016
+ r"""
1017
+ Args:
1018
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1019
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1020
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1021
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1022
+
1023
+ Returns:
1024
+
1025
+ Example:
1026
+
1027
+ ```python
1028
+ >>> from transformers import AutoTokenizer, PhiForCausalLM
1029
+
1030
+ >>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
1031
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
1032
+
1033
+ >>> prompt = "This is an example script ."
1034
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1035
+
1036
+ >>> # Generate
1037
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1038
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1039
+ 'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
1040
+ ```"""
1041
+
1042
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1043
+ output_hidden_states = (
1044
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1045
+ )
1046
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1047
+
1048
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1049
+ outputs = self.model(
1050
+ input_ids=input_ids,
1051
+ attention_mask=attention_mask,
1052
+ position_ids=position_ids,
1053
+ past_key_values=past_key_values,
1054
+ inputs_embeds=inputs_embeds,
1055
+ use_cache=use_cache,
1056
+ output_attentions=output_attentions,
1057
+ output_hidden_states=output_hidden_states,
1058
+ return_dict=return_dict,
1059
+ )
1060
+
1061
+ hidden_states = outputs[0]
1062
+ logits = self.lm_head(hidden_states)
1063
+ logits = logits.float()
1064
+
1065
+ loss = None
1066
+ if labels is not None:
1067
+ # Shift so that tokens < n predict n
1068
+ shift_logits = logits[..., :-1, :].contiguous()
1069
+ shift_labels = labels[..., 1:].contiguous()
1070
+ # Flatten the tokens
1071
+ loss_fct = CrossEntropyLoss()
1072
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1073
+ shift_labels = shift_labels.view(-1)
1074
+ # Enable model parallelism
1075
+ shift_labels = shift_labels.to(shift_logits.device)
1076
+ loss = loss_fct(shift_logits, shift_labels)
1077
+
1078
+ if not return_dict:
1079
+ output = (logits,) + outputs[1:]
1080
+ return (loss,) + output if loss is not None else output
1081
+
1082
+ return CausalLMOutputWithPast(
1083
+ loss=loss,
1084
+ logits=logits,
1085
+ past_key_values=outputs.past_key_values,
1086
+ hidden_states=outputs.hidden_states,
1087
+ attentions=outputs.attentions,
1088
+ )
1089
+
1090
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1091
+ def prepare_inputs_for_generation(
1092
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1093
+ ):
1094
+ if past_key_values is not None:
1095
+ if isinstance(past_key_values, Cache):
1096
+ cache_length = past_key_values.get_seq_length()
1097
+ past_length = past_key_values.seen_tokens
1098
+ max_cache_length = past_key_values.get_max_length()
1099
+ else:
1100
+ cache_length = past_length = past_key_values[0][0].shape[2]
1101
+ max_cache_length = None
1102
+
1103
+ # Keep only the unprocessed tokens:
1104
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1105
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1106
+ # input)
1107
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1108
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1109
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1110
+ # input_ids based on the past_length.
1111
+ elif past_length < input_ids.shape[1]:
1112
+ input_ids = input_ids[:, past_length:]
1113
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1114
+
1115
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1116
+ if (
1117
+ max_cache_length is not None
1118
+ and attention_mask is not None
1119
+ and cache_length + input_ids.shape[1] > max_cache_length
1120
+ ):
1121
+ attention_mask = attention_mask[:, -max_cache_length:]
1122
+
1123
+ position_ids = kwargs.get("position_ids", None)
1124
+ if attention_mask is not None and position_ids is None:
1125
+ # create position_ids on the fly for batch generation
1126
+ position_ids = attention_mask.long().cumsum(-1) - 1
1127
+ position_ids.masked_fill_(attention_mask == 0, 1)
1128
+ if past_key_values:
1129
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1130
+
1131
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1132
+ if inputs_embeds is not None and past_key_values is None:
1133
+ model_inputs = {"inputs_embeds": inputs_embeds}
1134
+ else:
1135
+ model_inputs = {"input_ids": input_ids}
1136
+
1137
+ model_inputs.update(
1138
+ {
1139
+ "position_ids": position_ids,
1140
+ "past_key_values": past_key_values,
1141
+ "use_cache": kwargs.get("use_cache"),
1142
+ "attention_mask": attention_mask,
1143
+ }
1144
+ )
1145
+ return model_inputs
1146
+
1147
+ @staticmethod
1148
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1149
+ def _reorder_cache(past_key_values, beam_idx):
1150
+ reordered_past = ()
1151
+ for layer_past in past_key_values:
1152
+ reordered_past += (
1153
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1154
+ )
1155
+ return reordered_past
1156
+
1157
+
1158
+ @add_start_docstrings(
1159
+ """
1160
+ The PhiModel with a sequence classification head on top (linear layer).
1161
+
1162
+ [`PhiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1163
+ (e.g. GPT-2) do.
1164
+
1165
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1166
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1167
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1168
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1169
+ each row of the batch).
1170
+ """,
1171
+ PHI_START_DOCSTRING,
1172
+ )
1173
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->PHI,Llama->Phi with self.transformer->self.model, transformer_outputs->model_outputs
1174
+ class PhiForSequenceClassification(PhiPreTrainedModel):
1175
+ def __init__(self, config):
1176
+ super().__init__(config)
1177
+ self.num_labels = config.num_labels
1178
+ self.model = PhiModel(config)
1179
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1180
+
1181
+ # Initialize weights and apply final processing
1182
+ self.post_init()
1183
+
1184
+ def get_input_embeddings(self):
1185
+ return self.model.embed_tokens
1186
+
1187
+ def set_input_embeddings(self, value):
1188
+ self.model.embed_tokens = value
1189
+
1190
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1191
+ def forward(
1192
+ self,
1193
+ input_ids: torch.LongTensor = None,
1194
+ attention_mask: Optional[torch.Tensor] = None,
1195
+ position_ids: Optional[torch.LongTensor] = None,
1196
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1197
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1198
+ labels: Optional[torch.LongTensor] = None,
1199
+ use_cache: Optional[bool] = None,
1200
+ output_attentions: Optional[bool] = None,
1201
+ output_hidden_states: Optional[bool] = None,
1202
+ return_dict: Optional[bool] = None,
1203
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1204
+ r"""
1205
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1206
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1207
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1208
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1209
+ """
1210
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1211
+
1212
+ model_outputs = self.model(
1213
+ input_ids,
1214
+ attention_mask=attention_mask,
1215
+ position_ids=position_ids,
1216
+ past_key_values=past_key_values,
1217
+ inputs_embeds=inputs_embeds,
1218
+ use_cache=use_cache,
1219
+ output_attentions=output_attentions,
1220
+ output_hidden_states=output_hidden_states,
1221
+ return_dict=return_dict,
1222
+ )
1223
+ hidden_states = model_outputs[0]
1224
+ logits = self.score(hidden_states)
1225
+
1226
+ if input_ids is not None:
1227
+ batch_size = input_ids.shape[0]
1228
+ else:
1229
+ batch_size = inputs_embeds.shape[0]
1230
+
1231
+ if self.config.pad_token_id is None and batch_size != 1:
1232
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1233
+ if self.config.pad_token_id is None:
1234
+ sequence_lengths = -1
1235
+ else:
1236
+ if input_ids is not None:
1237
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1238
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1239
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1240
+ sequence_lengths = sequence_lengths.to(logits.device)
1241
+ else:
1242
+ sequence_lengths = -1
1243
+
1244
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1245
+
1246
+ loss = None
1247
+ if labels is not None:
1248
+ labels = labels.to(logits.device)
1249
+ if self.config.problem_type is None:
1250
+ if self.num_labels == 1:
1251
+ self.config.problem_type = "regression"
1252
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1253
+ self.config.problem_type = "single_label_classification"
1254
+ else:
1255
+ self.config.problem_type = "multi_label_classification"
1256
+
1257
+ if self.config.problem_type == "regression":
1258
+ loss_fct = MSELoss()
1259
+ if self.num_labels == 1:
1260
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1261
+ else:
1262
+ loss = loss_fct(pooled_logits, labels)
1263
+ elif self.config.problem_type == "single_label_classification":
1264
+ loss_fct = CrossEntropyLoss()
1265
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1266
+ elif self.config.problem_type == "multi_label_classification":
1267
+ loss_fct = BCEWithLogitsLoss()
1268
+ loss = loss_fct(pooled_logits, labels)
1269
+ if not return_dict:
1270
+ output = (pooled_logits,) + model_outputs[1:]
1271
+ return ((loss,) + output) if loss is not None else output
1272
+
1273
+ return SequenceClassifierOutputWithPast(
1274
+ loss=loss,
1275
+ logits=pooled_logits,
1276
+ past_key_values=model_outputs.past_key_values,
1277
+ hidden_states=model_outputs.hidden_states,
1278
+ attentions=model_outputs.attentions,
1279
+ )
1280
+
1281
+
1282
+ @add_start_docstrings(
1283
+ """
1284
+ PhiModel with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1285
+ Named-Entity-Recognition (NER) tasks.
1286
+ """,
1287
+ PHI_START_DOCSTRING,
1288
+ )
1289
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with MPT->PHI,Mpt->Phi,self.transformer->self.model,transformer_outputs->model_outputs
1290
+ class PhiForTokenClassification(PhiPreTrainedModel):
1291
+ def __init__(self, config: PhiConfig):
1292
+ super().__init__(config)
1293
+ self.num_labels = config.num_labels
1294
+
1295
+ self.model = PhiModel(config)
1296
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1297
+ classifier_dropout = config.classifier_dropout
1298
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1299
+ classifier_dropout = config.hidden_dropout
1300
+ else:
1301
+ classifier_dropout = 0.1
1302
+ self.dropout = nn.Dropout(classifier_dropout)
1303
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1304
+
1305
+ # Initialize weights and apply final processing
1306
+ self.post_init()
1307
+
1308
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1309
+ @add_code_sample_docstrings(
1310
+ checkpoint=_CHECKPOINT_FOR_DOC,
1311
+ output_type=TokenClassifierOutput,
1312
+ config_class=_CONFIG_FOR_DOC,
1313
+ )
1314
+ def forward(
1315
+ self,
1316
+ input_ids: Optional[torch.LongTensor] = None,
1317
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1318
+ attention_mask: Optional[torch.Tensor] = None,
1319
+ inputs_embeds: Optional[torch.Tensor] = None,
1320
+ labels: Optional[torch.Tensor] = None,
1321
+ use_cache: Optional[bool] = None,
1322
+ output_attentions: Optional[bool] = None,
1323
+ output_hidden_states: Optional[bool] = None,
1324
+ return_dict: Optional[bool] = None,
1325
+ **deprecated_arguments,
1326
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1327
+ r"""
1328
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1329
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1330
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1331
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1332
+ """
1333
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1334
+
1335
+ model_outputs = self.model(
1336
+ input_ids,
1337
+ past_key_values=past_key_values,
1338
+ attention_mask=attention_mask,
1339
+ inputs_embeds=inputs_embeds,
1340
+ use_cache=use_cache,
1341
+ output_attentions=output_attentions,
1342
+ output_hidden_states=output_hidden_states,
1343
+ return_dict=return_dict,
1344
+ )
1345
+
1346
+ hidden_states = model_outputs[0]
1347
+ hidden_states = self.dropout(hidden_states)
1348
+ logits = self.classifier(hidden_states)
1349
+
1350
+ loss = None
1351
+ if labels is not None:
1352
+ # move labels to correct device to enable model parallelism
1353
+ labels = labels.to(logits.device)
1354
+ batch_size, seq_length = labels.shape
1355
+ loss_fct = CrossEntropyLoss()
1356
+ loss = loss_fct(
1357
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1358
+ )
1359
+
1360
+ if not return_dict:
1361
+ output = (logits,) + model_outputs[2:]
1362
+ return ((loss,) + output) if loss is not None else output
1363
+
1364
+ return TokenClassifierOutput(
1365
+ loss=loss,
1366
+ logits=logits,
1367
+ hidden_states=model_outputs.hidden_states,
1368
+ attentions=model_outputs.attentions,
1369
+ )
checkpoint-5500/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8ac6af6ac2b73603409d1721537224310f2ce061bc8c1c1c6f959231ed2e31e
3
+ size 15024
checkpoint-5500/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:693cfdc542e1c8c319f7052d02602310660cb04e6571aa78525e03834c8b9930
3
+ size 15024
checkpoint-5500/rng_state_2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ca85a038ef549f3dd6ca18c0dadc240e57927cad9adbcbd9ff224f3da3ae003
3
+ size 15024