zwt123home123 commited on
Commit
5f5c6a7
·
verified ·
1 Parent(s): 82d6ba7

Upload folder using huggingface_hub

Browse files
Files changed (41) hide show
  1. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/0.npy +3 -0
  2. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/1.npy +3 -0
  3. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/10.npy +3 -0
  4. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/11.npy +3 -0
  5. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/12.npy +3 -0
  6. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/13.npy +3 -0
  7. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/14.npy +3 -0
  8. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/15.npy +3 -0
  9. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/16.npy +3 -0
  10. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/17.npy +3 -0
  11. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/18.npy +3 -0
  12. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/19.npy +3 -0
  13. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/2.npy +3 -0
  14. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/20.npy +3 -0
  15. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/21.npy +3 -0
  16. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/22.npy +3 -0
  17. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/23.npy +3 -0
  18. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/24.npy +3 -0
  19. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/25.npy +3 -0
  20. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/26.npy +3 -0
  21. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/27.npy +3 -0
  22. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/28.npy +3 -0
  23. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/29.npy +3 -0
  24. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/3.npy +3 -0
  25. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/30.npy +3 -0
  26. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/31.npy +3 -0
  27. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/32.npy +3 -0
  28. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/33.npy +3 -0
  29. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/34.npy +3 -0
  30. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/35.npy +3 -0
  31. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/36.npy +3 -0
  32. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/37.npy +3 -0
  33. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/38.npy +3 -0
  34. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/39.npy +3 -0
  35. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/4.npy +3 -0
  36. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/5.npy +3 -0
  37. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/6.npy +3 -0
  38. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/7.npy +3 -0
  39. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/8.npy +3 -0
  40. centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/9.npy +3 -0
  41. modeling_llama_LUT_prerope.py +1447 -0
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/0.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b021c03b67b64a005a7b82d2448ec3fa1c0e5ead475409abe3220af8466bb056
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/1.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:559fda2c951f1c324fb0c385444ac829c031169599773f4531c0e387cfa97e7f
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/10.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84b4153c9d84c703061f3427016fdc826ebedf0eaa6ac4c14e7929cf23dcb0ad
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/11.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1595541a0c25374b4ea38fc4861416a3fb9b1408e7e95936481f3d5adc6d1d4b
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/12.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c20c68759532c9f0e52a9183878b487ddaff5a4d9d4d5f40733dca16c054928
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/13.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba43639eca13a03634c177436bc6271532f92f45fbad4f141c86d5a9ccc6d9ca
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/14.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d082ea8f7623b5cbf2ddf5c6e4a7bbb54f5b53966fad776dbd9c0ad8f8beaa84
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/15.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:758487f4ce5f1c02791f211ac197f9f72fb4112a0466ee5d08b834cf0cf1c77d
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/16.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f70eed136cb43092caae697d94d99607c41295e14cc9136ca8182f9e0d0bd8f
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/17.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d00af01629f8120104c1534581f9900619b469980a6baa9913d4cddeeddc7318
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/18.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40a7d9ff49d104827bd65af3f74b1ca52d150b227593775104c76a2ec9f3ece9
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/19.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dcab7465c36ae33cb7a2898f95637e5ae0aa926c36ae1bdb4569aab5c4956dad
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/2.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5884252a4f5fcdb2cc0624a8d8b5b4cf057a5b757f026806e7721fdf3b24cce
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/20.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a565c0e79e867986bbaf0811b3588d8e84eafbcf70976aa854d8ea400ff417a1
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/21.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8d0316431cb39f3df4e231494cbd57a97f640077f18f306e66f81f67c12be84
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/22.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a61cbdaa2a7183388156d51da2a408bb87e4e4d5c7a1f82b951c9e7ae340419
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/23.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:118ecdff233ded1b631183f52e1e92d6924c7df2a78990541ddd2e235b939f47
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/24.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b57eaa4948107a3894ecfc9f0f39c8565d73eb7014cdcd3a21628e0945381db3
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/25.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5211b68f7de27f7008c820651d047ed99304b4b178972659222e5d697d3ad0e5
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/26.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f21dfd3972309d45fcab77751d308cffeae10bf547d1296c257bede256d1157
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/27.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c2852d4170047299325f8a795aa7d4a1e9c30a3516a0861d705d725a0a7f9dd
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/28.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4dc896dff3d6ae8118f6b1c29de03064f80f7b97e6e9351e0d580c77a9a592da
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/29.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a147f4f3fd036462c6d5d0052ae884754321adb8bfb7c0d96acaede5dc0bc199
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/3.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd91acb3ffb8af46758d1b2c3ba842eb8f228e20abca56b26bc9d061b3fcfd8f
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/30.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1bb3671b3ee1754b485c72da0cdc4d31af359459acbaf16be1ff2869421d511b
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/31.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f877e01bdab232a5e257cba0908baf995eb8b530773153a6ff5ed6d93658f3c5
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/32.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8064e89e6ac585443d70d074ef0b30bcae7c9ec36243036943688334eb96de84
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/33.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bcad81b6dae4bb519acd80abc26a5a21cc8f1ba83ed477e1c36a1c1497fe2325
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/34.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1686567416ebf958339941b12d7f50060cddeea164cf37fd62b8fe3b8dd2ce1
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/35.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43f710112abf78d6e3474c597bd9288522f18443483aac6f5e2cbed33c9d8292
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/36.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6886ff28d3b53149b15f5299aaa587adf71683d9546832f2ad6b0be2bd7c6ef6
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/37.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbd1799d37c2efb0c374390b6352ea13a433d24a58e75271fc08ed82abb8bb95
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/38.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3ebaba071ffb5ab8e09c49ebf68d3d50649fe805ece53b1195d3a3d8f0bfa09
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/39.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f884d4fc002462b91f6a88a56517a1d8182e54f01d6b1940971304a565b92b2f
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/4.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:563a26a1e5bba12d7d63b12cb3391ed1d501f91028ad8b7714e9fb646ee992ef
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/5.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:53ddea2ff7948b4cf3d31f94e70bcda6e9e7d9df761ce3507d41bce3b085e5e5
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/6.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a84ccf3ba2385b4b69000f2ce3d291ee86a382612cffc516e631022020c04f5
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/7.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22e9f59aa342ee25542a306fffecd60be4b9f227b7a8b235236fd686c7b4e840
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/8.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5d00fdae708e62eb6f6309228e0082631ee0c62bd237acc11e25ec60540228a5
3
+ size 20480128
centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/9.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97b3fbadb52814921631abfaae0c3aae580a2c9615eb1bf81e2c50ac7dac2b50
3
+ size 20480128
modeling_llama_LUT_prerope.py ADDED
@@ -0,0 +1,1447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from ...activations import ACT2FN
32
+ from ...cache_utils import Cache, DynamicCache
33
+ from ...modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
40
+ from ...modeling_utils import PreTrainedModel
41
+ from ...pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
42
+ from ...utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from ...utils.import_utils import is_torch_fx_available
51
+ from .configuration_llama import LlamaConfig
52
+ import numpy as np
53
+
54
+ if is_flash_attn_2_available():
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+
58
+
59
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
60
+ # It means that the function will not be traced through and simply appear as a node in the graph.
61
+ if is_torch_fx_available():
62
+ if not is_torch_greater_or_equal_than_1_13:
63
+ import torch.fx
64
+
65
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
66
+
67
+
68
+ logger = logging.get_logger(__name__)
69
+
70
+ _CONFIG_FOR_DOC = "LlamaConfig"
71
+
72
+
73
+ def _get_unpad_data(attention_mask):
74
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
75
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
76
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
77
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
78
+ return (
79
+ indices,
80
+ cu_seqlens,
81
+ max_seqlen_in_batch,
82
+ )
83
+
84
+
85
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
86
+ warnings.warn(
87
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
88
+ )
89
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
90
+
91
+
92
+ def _make_causal_mask(
93
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
94
+ ):
95
+ warnings.warn(
96
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
97
+ )
98
+ return AttentionMaskConverter._make_causal_mask(
99
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
100
+ )
101
+
102
+
103
+ class LlamaRMSNorm(nn.Module):
104
+ def __init__(self, hidden_size, eps=1e-6):
105
+ """
106
+ LlamaRMSNorm is equivalent to T5LayerNorm
107
+ """
108
+ super().__init__()
109
+ self.weight = nn.Parameter(torch.ones(hidden_size))
110
+ self.variance_epsilon = eps
111
+
112
+ def forward(self, hidden_states):
113
+ input_dtype = hidden_states.dtype
114
+ hidden_states = hidden_states.to(torch.float32)
115
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
116
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
117
+ return self.weight * hidden_states.to(input_dtype)
118
+
119
+
120
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
121
+
122
+
123
+ class LlamaRotaryEmbedding(nn.Module):
124
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
125
+ super().__init__()
126
+
127
+ self.dim = dim
128
+ self.max_position_embeddings = max_position_embeddings
129
+ self.base = base
130
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
131
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
132
+
133
+ # Build here to make `torch.jit.trace` work.
134
+ self._set_cos_sin_cache(
135
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
136
+ )
137
+
138
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
139
+ self.max_seq_len_cached = seq_len
140
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
141
+
142
+ freqs = torch.outer(t, self.inv_freq)
143
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
146
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
147
+
148
+ def forward(self, x, seq_len=None):
149
+ # x: [bs, num_attention_heads, seq_len, head_size]
150
+ if seq_len > self.max_seq_len_cached:
151
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
152
+
153
+ return (
154
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
155
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
156
+ )
157
+
158
+
159
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
160
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
161
+
162
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
163
+ self.scaling_factor = scaling_factor
164
+ super().__init__(dim, max_position_embeddings, base, device)
165
+
166
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
167
+ self.max_seq_len_cached = seq_len
168
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
169
+ t = t / self.scaling_factor
170
+
171
+ freqs = torch.outer(t, self.inv_freq)
172
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
173
+ emb = torch.cat((freqs, freqs), dim=-1)
174
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
175
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
176
+
177
+
178
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
179
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
180
+
181
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
182
+ self.scaling_factor = scaling_factor
183
+ super().__init__(dim, max_position_embeddings, base, device)
184
+
185
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
186
+ self.max_seq_len_cached = seq_len
187
+
188
+ if seq_len > self.max_position_embeddings:
189
+ base = self.base * (
190
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
191
+ ) ** (self.dim / (self.dim - 2))
192
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
193
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
194
+
195
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
196
+
197
+ freqs = torch.outer(t, self.inv_freq)
198
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
199
+ emb = torch.cat((freqs, freqs), dim=-1)
200
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
201
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
202
+
203
+
204
+ def rotate_half(x):
205
+ """Rotates half the hidden dims of the input."""
206
+ x1 = x[..., : x.shape[-1] // 2]
207
+ x2 = x[..., x.shape[-1] // 2 :]
208
+ return torch.cat((-x2, x1), dim=-1)
209
+
210
+
211
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
212
+ """Applies Rotary Position Embedding to the query and key tensors.
213
+
214
+ Args:
215
+ q (`torch.Tensor`): The query tensor.
216
+ k (`torch.Tensor`): The key tensor.
217
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
218
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
219
+ position_ids (`torch.Tensor`):
220
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
221
+ used to pass offsetted position ids when working with a KV-cache.
222
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
223
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
224
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
225
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
226
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
227
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
228
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
229
+ Returns:
230
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
231
+ """
232
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
233
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
234
+ q_embed = (q * cos) + (rotate_half(q) * sin)
235
+ k_embed = (k * cos) + (rotate_half(k) * sin)
236
+ return q_embed, k_embed
237
+
238
+
239
+ class LlamaMLP(nn.Module):
240
+ def __init__(self, config):
241
+ super().__init__()
242
+ self.config = config
243
+ self.hidden_size = config.hidden_size
244
+ self.intermediate_size = config.intermediate_size
245
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
246
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
247
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
248
+ self.act_fn = ACT2FN[config.hidden_act]
249
+
250
+ def forward(self, x):
251
+ if self.config.pretraining_tp > 1:
252
+ slice = self.intermediate_size // self.config.pretraining_tp
253
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
254
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
255
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
256
+
257
+ gate_proj = torch.cat(
258
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
259
+ )
260
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
261
+
262
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
263
+ down_proj = [
264
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
265
+ ]
266
+ down_proj = sum(down_proj)
267
+ else:
268
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
269
+
270
+ return down_proj
271
+
272
+
273
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
274
+ """
275
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
276
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
277
+ """
278
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
279
+ if n_rep == 1:
280
+ return hidden_states
281
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
282
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
283
+
284
+
285
+ class LlamaAttention(nn.Module):
286
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
287
+
288
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
289
+ super().__init__()
290
+ self.config = config
291
+ self.layer_idx = layer_idx
292
+ if layer_idx is None:
293
+ logger.warning_once(
294
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
295
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
296
+ "when creating this class."
297
+ )
298
+
299
+ self.attention_dropout = config.attention_dropout
300
+ self.hidden_size = config.hidden_size
301
+ self.num_heads = config.num_attention_heads
302
+ self.head_dim = self.hidden_size // self.num_heads
303
+ self.num_key_value_heads = config.num_key_value_heads
304
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
305
+ self.max_position_embeddings = config.max_position_embeddings
306
+ self.rope_theta = config.rope_theta
307
+ self.is_causal = True
308
+
309
+ if (self.head_dim * self.num_heads) != self.hidden_size:
310
+ raise ValueError(
311
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
312
+ f" and `num_heads`: {self.num_heads})."
313
+ )
314
+
315
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
316
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
317
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
318
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
319
+ self._init_rope()
320
+ self.lut_layer = 40
321
+ if self.layer_idx<self.lut_layer:
322
+ self.key_states_centroid = torch.tensor(np.load("/sensei-fs-3/users/wezhao/projects/KVcache/cluster/centroids_faiss_K_c1k_bs1m_iter_20_nonorm_all_layers_prerope/"+str(self.layer_idx)+".npy")).half().cuda()
323
+
324
+ def _init_rope(self):
325
+ if self.config.rope_scaling is None:
326
+ self.rotary_emb = LlamaRotaryEmbedding(
327
+ self.head_dim,
328
+ max_position_embeddings=self.max_position_embeddings,
329
+ base=self.rope_theta,
330
+ )
331
+ else:
332
+ scaling_type = self.config.rope_scaling["type"]
333
+ scaling_factor = self.config.rope_scaling["factor"]
334
+ if scaling_type == "linear":
335
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
336
+ self.head_dim,
337
+ max_position_embeddings=self.max_position_embeddings,
338
+ scaling_factor=scaling_factor,
339
+ base=self.rope_theta,
340
+ )
341
+ elif scaling_type == "dynamic":
342
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
343
+ self.head_dim,
344
+ max_position_embeddings=self.max_position_embeddings,
345
+ scaling_factor=scaling_factor,
346
+ base=self.rope_theta,
347
+ )
348
+ else:
349
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
350
+
351
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
352
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
353
+
354
+ def forward(
355
+ self,
356
+ hidden_states: torch.Tensor,
357
+ attention_mask: Optional[torch.Tensor] = None,
358
+ position_ids: Optional[torch.LongTensor] = None,
359
+ past_key_value: Optional[Cache] = None,
360
+ output_attentions: bool = False,
361
+ use_cache: bool = False,
362
+ **kwargs,
363
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
364
+ if "padding_mask" in kwargs:
365
+ warnings.warn(
366
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
367
+ )
368
+
369
+ bsz, q_len, _ = hidden_states.size()
370
+
371
+ if self.config.pretraining_tp > 1:
372
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
373
+ query_slices = self.q_proj.weight.split(
374
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
375
+ )
376
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
377
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
378
+
379
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
380
+ query_states = torch.cat(query_states, dim=-1)
381
+
382
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
383
+ key_states = torch.cat(key_states, dim=-1)
384
+
385
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
386
+ value_states = torch.cat(value_states, dim=-1)
387
+
388
+ else:
389
+ query_states = self.q_proj(hidden_states)
390
+ key_states = self.k_proj(hidden_states)
391
+ value_states = self.v_proj(hidden_states)
392
+
393
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
394
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
395
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
396
+
397
+ kv_seq_len = key_states.shape[-2]
398
+ if past_key_value is not None:
399
+ if self.layer_idx is None:
400
+ raise ValueError(
401
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
402
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
403
+ "with a layer index."
404
+ )
405
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
406
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
407
+
408
+ # print(query_states.shape)
409
+ if self.layer_idx<self.lut_layer and query_states.shape[2] > 576:
410
+ # self.key_states_centroid
411
+ new_key_states = key_states.clone()
412
+ new_key_states = new_key_states[:,:,35:35+576,:].permute(0, 2, 1, 3)
413
+ new_key_states = new_key_states.reshape(new_key_states.shape[0], new_key_states.shape[1], 5120)
414
+ new_key_states_norm = F.normalize(new_key_states, p=2, dim=-1)
415
+ centroids_norm = F.normalize(self.key_states_centroid, p=2, dim=-1) # [10000, 5120]
416
+ B, S, D = new_key_states_norm.shape
417
+ key_states_flat = new_key_states_norm.view(B * S, D)
418
+ sim = torch.matmul(key_states_flat, centroids_norm.t())
419
+ score, indices = sim.max(dim=1)
420
+ print(self.layer_idx, score.mean(), "max", new_key_states.max(), self.key_states_centroid.max() ,"min", new_key_states.min(), self.key_states_centroid.min() )
421
+ closest_centroid = self.key_states_centroid[indices]
422
+ new_key_states = closest_centroid.view(B, S, D)
423
+ new_key_states = new_key_states.reshape(new_key_states.shape[0], new_key_states.shape[1], 40, 128)
424
+ new_key_states = new_key_states.permute(0, 2, 1, 3)
425
+ key_states_new_save = key_states.clone()
426
+ key_states_new_save[:,:,35:35+576,:]=new_key_states
427
+ # key_states = key_states_new_save
428
+ # import pdb; pdb.set_trace()
429
+
430
+ if self.layer_idx<self.lut_layer and query_states.shape[2] > 576:
431
+ _, key_states_new_save = apply_rotary_pos_emb(query_states, key_states_new_save, cos, sin, position_ids)
432
+
433
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
434
+
435
+
436
+ if past_key_value is not None:
437
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
438
+ if self.layer_idx<self.lut_layer and query_states.shape[2] > 576:
439
+ _, value_states = past_key_value.update(key_states_new_save, value_states, self.layer_idx, cache_kwargs)
440
+ else:
441
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
442
+
443
+
444
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
445
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
446
+
447
+
448
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
449
+
450
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
451
+ raise ValueError(
452
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
453
+ f" {attn_weights.size()}"
454
+ )
455
+
456
+ if attention_mask is not None:
457
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
458
+ raise ValueError(
459
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
460
+ )
461
+ attn_weights = attn_weights + attention_mask
462
+
463
+ # upcast attention to fp32
464
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
465
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
466
+ attn_output = torch.matmul(attn_weights, value_states)
467
+
468
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
469
+ raise ValueError(
470
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
471
+ f" {attn_output.size()}"
472
+ )
473
+
474
+ attn_output = attn_output.transpose(1, 2).contiguous()
475
+
476
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
477
+
478
+ if self.config.pretraining_tp > 1:
479
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
480
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
481
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
482
+ else:
483
+ attn_output = self.o_proj(attn_output)
484
+
485
+ if not output_attentions:
486
+ attn_weights = None
487
+
488
+ return attn_output, attn_weights, past_key_value
489
+
490
+
491
+ class LlamaFlashAttention2(LlamaAttention):
492
+ """
493
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
494
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
495
+ flash attention and deal with padding tokens in case the input contains any of them.
496
+ """
497
+
498
+ def __init__(self, *args, **kwargs):
499
+ super().__init__(*args, **kwargs)
500
+
501
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
502
+ # 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.
503
+ # 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).
504
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
505
+
506
+ def forward(
507
+ self,
508
+ hidden_states: torch.Tensor,
509
+ attention_mask: Optional[torch.LongTensor] = None,
510
+ position_ids: Optional[torch.LongTensor] = None,
511
+ past_key_value: Optional[Cache] = None,
512
+ output_attentions: bool = False,
513
+ use_cache: bool = False,
514
+ **kwargs,
515
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
516
+ # LlamaFlashAttention2 attention does not support output_attentions
517
+ if "padding_mask" in kwargs:
518
+ warnings.warn(
519
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
520
+ )
521
+
522
+ # overwrite attention_mask with padding_mask
523
+ attention_mask = kwargs.pop("padding_mask")
524
+
525
+ output_attentions = False
526
+
527
+ bsz, q_len, _ = hidden_states.size()
528
+
529
+ query_states = self.q_proj(hidden_states)
530
+ key_states = self.k_proj(hidden_states)
531
+ value_states = self.v_proj(hidden_states)
532
+
533
+ # Flash attention requires the input to have the shape
534
+ # batch_size x seq_length x head_dim x hidden_dim
535
+ # therefore we just need to keep the original shape
536
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
537
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
538
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
539
+
540
+ kv_seq_len = key_states.shape[-2]
541
+ if past_key_value is not None:
542
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
543
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
544
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
545
+
546
+ if past_key_value is not None:
547
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
548
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
549
+
550
+ # 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
551
+ # to be able to avoid many of these transpose/reshape/view.
552
+ query_states = query_states.transpose(1, 2)
553
+ key_states = key_states.transpose(1, 2)
554
+ value_states = value_states.transpose(1, 2)
555
+
556
+ dropout_rate = self.attention_dropout if self.training else 0.0
557
+
558
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
559
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
560
+ # cast them back in the correct dtype just to be sure everything works as expected.
561
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
562
+ # in fp32. (LlamaRMSNorm handles it correctly)
563
+
564
+ input_dtype = query_states.dtype
565
+ if input_dtype == torch.float32:
566
+ # Handle the case where the model is quantized
567
+ if hasattr(self.config, "_pre_quantization_dtype"):
568
+ target_dtype = self.config._pre_quantization_dtype
569
+ else:
570
+ target_dtype = self.q_proj.weight.dtype
571
+
572
+ logger.warning_once(
573
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
574
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
575
+ f" {target_dtype}."
576
+ )
577
+
578
+ query_states = query_states.to(target_dtype)
579
+ key_states = key_states.to(target_dtype)
580
+ value_states = value_states.to(target_dtype)
581
+
582
+ attn_output = self._flash_attention_forward(
583
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
584
+ )
585
+
586
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
587
+ attn_output = self.o_proj(attn_output)
588
+
589
+ if not output_attentions:
590
+ attn_weights = None
591
+
592
+ return attn_output, attn_weights, past_key_value
593
+
594
+ def _flash_attention_forward(
595
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
596
+ ):
597
+ """
598
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
599
+ first unpad the input, then computes the attention scores and pad the final attention scores.
600
+
601
+ Args:
602
+ query_states (`torch.Tensor`):
603
+ Input query states to be passed to Flash Attention API
604
+ key_states (`torch.Tensor`):
605
+ Input key states to be passed to Flash Attention API
606
+ value_states (`torch.Tensor`):
607
+ Input value states to be passed to Flash Attention API
608
+ attention_mask (`torch.Tensor`):
609
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
610
+ position of padding tokens and 1 for the position of non-padding tokens.
611
+ dropout (`int`, *optional*):
612
+ Attention dropout
613
+ softmax_scale (`float`, *optional*):
614
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
615
+ """
616
+ if not self._flash_attn_uses_top_left_mask:
617
+ causal = self.is_causal
618
+ else:
619
+ # 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__.
620
+ causal = self.is_causal and query_length != 1
621
+
622
+ # Contains at least one padding token in the sequence
623
+ if attention_mask is not None:
624
+ batch_size = query_states.shape[0]
625
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
626
+ query_states, key_states, value_states, attention_mask, query_length
627
+ )
628
+
629
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
630
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
631
+
632
+ attn_output_unpad = flash_attn_varlen_func(
633
+ query_states,
634
+ key_states,
635
+ value_states,
636
+ cu_seqlens_q=cu_seqlens_q,
637
+ cu_seqlens_k=cu_seqlens_k,
638
+ max_seqlen_q=max_seqlen_in_batch_q,
639
+ max_seqlen_k=max_seqlen_in_batch_k,
640
+ dropout_p=dropout,
641
+ softmax_scale=softmax_scale,
642
+ causal=causal,
643
+ )
644
+
645
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
646
+ else:
647
+ attn_output = flash_attn_func(
648
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
649
+ )
650
+
651
+ return attn_output
652
+
653
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
654
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
655
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
656
+
657
+ key_layer = index_first_axis(
658
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
659
+ )
660
+ value_layer = index_first_axis(
661
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
662
+ )
663
+ if query_length == kv_seq_len:
664
+ query_layer = index_first_axis(
665
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
666
+ )
667
+ cu_seqlens_q = cu_seqlens_k
668
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
669
+ indices_q = indices_k
670
+ elif query_length == 1:
671
+ max_seqlen_in_batch_q = 1
672
+ cu_seqlens_q = torch.arange(
673
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
674
+ ) # There is a memcpy here, that is very bad.
675
+ indices_q = cu_seqlens_q[:-1]
676
+ query_layer = query_layer.squeeze(1)
677
+ else:
678
+ # The -q_len: slice assumes left padding.
679
+ attention_mask = attention_mask[:, -query_length:]
680
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
681
+
682
+ return (
683
+ query_layer,
684
+ key_layer,
685
+ value_layer,
686
+ indices_q,
687
+ (cu_seqlens_q, cu_seqlens_k),
688
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
689
+ )
690
+
691
+
692
+ class LlamaSdpaAttention(LlamaAttention):
693
+ """
694
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
695
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
696
+ SDPA API.
697
+ """
698
+
699
+ # Adapted from LlamaAttention.forward
700
+ def forward(
701
+ self,
702
+ hidden_states: torch.Tensor,
703
+ attention_mask: Optional[torch.Tensor] = None,
704
+ position_ids: Optional[torch.LongTensor] = None,
705
+ past_key_value: Optional[Cache] = None,
706
+ output_attentions: bool = False,
707
+ use_cache: bool = False,
708
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
709
+ if output_attentions:
710
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
711
+ logger.warning_once(
712
+ "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
713
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
714
+ )
715
+ return super().forward(
716
+ hidden_states=hidden_states,
717
+ attention_mask=attention_mask,
718
+ position_ids=position_ids,
719
+ past_key_value=past_key_value,
720
+ output_attentions=output_attentions,
721
+ use_cache=use_cache,
722
+ )
723
+
724
+ bsz, q_len, _ = hidden_states.size()
725
+
726
+ query_states = self.q_proj(hidden_states)
727
+ key_states = self.k_proj(hidden_states)
728
+ value_states = self.v_proj(hidden_states)
729
+
730
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
731
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
732
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
733
+
734
+ kv_seq_len = key_states.shape[-2]
735
+ if past_key_value is not None:
736
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
737
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
738
+
739
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
740
+
741
+ if past_key_value is not None:
742
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
743
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
744
+
745
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
746
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
747
+
748
+ if attention_mask is not None:
749
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
750
+ raise ValueError(
751
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
752
+ )
753
+
754
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
755
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
756
+ if query_states.device.type == "cuda" and attention_mask is not None:
757
+ query_states = query_states.contiguous()
758
+ key_states = key_states.contiguous()
759
+ value_states = value_states.contiguous()
760
+
761
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
762
+ query_states,
763
+ key_states,
764
+ value_states,
765
+ attn_mask=attention_mask,
766
+ dropout_p=self.attention_dropout if self.training else 0.0,
767
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
768
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
769
+ )
770
+
771
+ attn_output = attn_output.transpose(1, 2).contiguous()
772
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
773
+
774
+ attn_output = self.o_proj(attn_output)
775
+
776
+ return attn_output, None, past_key_value
777
+
778
+
779
+ LLAMA_ATTENTION_CLASSES = {
780
+ "eager": LlamaAttention,
781
+ "flash_attention_2": LlamaFlashAttention2,
782
+ "sdpa": LlamaSdpaAttention,
783
+ }
784
+
785
+
786
+ class LlamaDecoderLayer(nn.Module):
787
+ def __init__(self, config: LlamaConfig, layer_idx: int):
788
+ super().__init__()
789
+ self.hidden_size = config.hidden_size
790
+ config._attn_implementation = "eager"
791
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
792
+
793
+ self.mlp = LlamaMLP(config)
794
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
795
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
796
+
797
+ def forward(
798
+ self,
799
+ hidden_states: torch.Tensor,
800
+ attention_mask: Optional[torch.Tensor] = None,
801
+ position_ids: Optional[torch.LongTensor] = None,
802
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
803
+ output_attentions: Optional[bool] = False,
804
+ use_cache: Optional[bool] = False,
805
+ **kwargs,
806
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
807
+ """
808
+ Args:
809
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
810
+ attention_mask (`torch.FloatTensor`, *optional*):
811
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
812
+ query_sequence_length, key_sequence_length)` if default attention is used.
813
+ output_attentions (`bool`, *optional*):
814
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
815
+ returned tensors for more detail.
816
+ use_cache (`bool`, *optional*):
817
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
818
+ (see `past_key_values`).
819
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
820
+ """
821
+ if "padding_mask" in kwargs:
822
+ warnings.warn(
823
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
824
+ )
825
+
826
+ residual = hidden_states
827
+
828
+ hidden_states = self.input_layernorm(hidden_states)
829
+
830
+ # Self Attention
831
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
832
+ hidden_states=hidden_states,
833
+ attention_mask=attention_mask,
834
+ position_ids=position_ids,
835
+ past_key_value=past_key_value,
836
+ output_attentions=output_attentions,
837
+ use_cache=use_cache,
838
+ **kwargs,
839
+ )
840
+ hidden_states = residual + hidden_states
841
+
842
+ # Fully Connected
843
+ residual = hidden_states
844
+ hidden_states = self.post_attention_layernorm(hidden_states)
845
+ hidden_states = self.mlp(hidden_states)
846
+ hidden_states = residual + hidden_states
847
+
848
+ outputs = (hidden_states,)
849
+
850
+ if output_attentions:
851
+ outputs += (self_attn_weights,)
852
+
853
+ if use_cache:
854
+ outputs += (present_key_value,)
855
+
856
+ return outputs
857
+
858
+
859
+ LLAMA_START_DOCSTRING = r"""
860
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
861
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
862
+ etc.)
863
+
864
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
865
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
866
+ and behavior.
867
+
868
+ Parameters:
869
+ config ([`LlamaConfig`]):
870
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
871
+ load the weights associated with the model, only the configuration. Check out the
872
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
873
+ """
874
+
875
+
876
+ @add_start_docstrings(
877
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
878
+ LLAMA_START_DOCSTRING,
879
+ )
880
+ class LlamaPreTrainedModel(PreTrainedModel):
881
+ config_class = LlamaConfig
882
+ base_model_prefix = "model"
883
+ supports_gradient_checkpointing = True
884
+ _no_split_modules = ["LlamaDecoderLayer"]
885
+ _skip_keys_device_placement = "past_key_values"
886
+ _supports_flash_attn_2 = True
887
+ _supports_sdpa = True
888
+ _supports_cache_class = True
889
+
890
+ def _init_weights(self, module):
891
+ std = self.config.initializer_range
892
+ if isinstance(module, nn.Linear):
893
+ module.weight.data.normal_(mean=0.0, std=std)
894
+ if module.bias is not None:
895
+ module.bias.data.zero_()
896
+ elif isinstance(module, nn.Embedding):
897
+ module.weight.data.normal_(mean=0.0, std=std)
898
+ if module.padding_idx is not None:
899
+ module.weight.data[module.padding_idx].zero_()
900
+
901
+
902
+ LLAMA_INPUTS_DOCSTRING = r"""
903
+ Args:
904
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
905
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
906
+ it.
907
+
908
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
909
+ [`PreTrainedTokenizer.__call__`] for details.
910
+
911
+ [What are input IDs?](../glossary#input-ids)
912
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
913
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
914
+
915
+ - 1 for tokens that are **not masked**,
916
+ - 0 for tokens that are **masked**.
917
+
918
+ [What are attention masks?](../glossary#attention-mask)
919
+
920
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
921
+ [`PreTrainedTokenizer.__call__`] for details.
922
+
923
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
924
+ `past_key_values`).
925
+
926
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
927
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
928
+ information on the default strategy.
929
+
930
+ - 1 indicates the head is **not masked**,
931
+ - 0 indicates the head is **masked**.
932
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
933
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
934
+ config.n_positions - 1]`.
935
+
936
+ [What are position IDs?](../glossary#position-ids)
937
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
938
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
939
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
940
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
941
+
942
+ Two formats are allowed:
943
+ - a [`~cache_utils.Cache`] instance;
944
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
945
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
946
+ cache format.
947
+
948
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
949
+ legacy cache format will be returned.
950
+
951
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
952
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
953
+ of shape `(batch_size, sequence_length)`.
954
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
955
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
956
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
957
+ model's internal embedding lookup matrix.
958
+ use_cache (`bool`, *optional*):
959
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
960
+ `past_key_values`).
961
+ output_attentions (`bool`, *optional*):
962
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
963
+ tensors for more detail.
964
+ output_hidden_states (`bool`, *optional*):
965
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
966
+ more detail.
967
+ return_dict (`bool`, *optional*):
968
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
969
+ """
970
+
971
+
972
+ @add_start_docstrings(
973
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
974
+ LLAMA_START_DOCSTRING,
975
+ )
976
+ class LlamaModel(LlamaPreTrainedModel):
977
+ """
978
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
979
+
980
+ Args:
981
+ config: LlamaConfig
982
+ """
983
+
984
+ def __init__(self, config: LlamaConfig):
985
+ super().__init__(config)
986
+ self.padding_idx = config.pad_token_id
987
+ self.vocab_size = config.vocab_size
988
+
989
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
990
+ self.layers = nn.ModuleList(
991
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
992
+ )
993
+ self._use_sdpa = config._attn_implementation == "sdpa"
994
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
995
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
996
+
997
+ self.gradient_checkpointing = False
998
+ # Initialize weights and apply final processing
999
+ self.post_init()
1000
+
1001
+ def get_input_embeddings(self):
1002
+ return self.embed_tokens
1003
+
1004
+ def set_input_embeddings(self, value):
1005
+ self.embed_tokens = value
1006
+
1007
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1008
+ def forward(
1009
+ self,
1010
+ input_ids: torch.LongTensor = None,
1011
+ attention_mask: Optional[torch.Tensor] = None,
1012
+ position_ids: Optional[torch.LongTensor] = None,
1013
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1014
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1015
+ use_cache: Optional[bool] = None,
1016
+ output_attentions: Optional[bool] = None,
1017
+ output_hidden_states: Optional[bool] = None,
1018
+ return_dict: Optional[bool] = None,
1019
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1020
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1021
+ output_hidden_states = (
1022
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1023
+ )
1024
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1025
+
1026
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1027
+
1028
+ # retrieve input_ids and inputs_embeds
1029
+ if input_ids is not None and inputs_embeds is not None:
1030
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1031
+ elif input_ids is not None:
1032
+ batch_size, seq_length = input_ids.shape[:2]
1033
+ elif inputs_embeds is not None:
1034
+ batch_size, seq_length = inputs_embeds.shape[:2]
1035
+ else:
1036
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1037
+
1038
+ if self.gradient_checkpointing and self.training:
1039
+ if use_cache:
1040
+ logger.warning_once(
1041
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1042
+ )
1043
+ use_cache = False
1044
+
1045
+ past_key_values_length = 0
1046
+ if use_cache:
1047
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1048
+ if use_legacy_cache:
1049
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1050
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1051
+
1052
+ if position_ids is None:
1053
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1054
+ position_ids = torch.arange(
1055
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1056
+ )
1057
+ position_ids = position_ids.unsqueeze(0)
1058
+
1059
+ if inputs_embeds is None:
1060
+ inputs_embeds = self.embed_tokens(input_ids)
1061
+
1062
+ if self._use_flash_attention_2:
1063
+ # 2d mask is passed through the layers
1064
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1065
+ elif self._use_sdpa and not output_attentions:
1066
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1067
+ # the manual implementation that requires a 4D causal mask in all cases.
1068
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1069
+ attention_mask,
1070
+ (batch_size, seq_length),
1071
+ inputs_embeds,
1072
+ past_key_values_length,
1073
+ )
1074
+ else:
1075
+ # 4d mask is passed through the layers
1076
+ attention_mask = _prepare_4d_causal_attention_mask(
1077
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1078
+ )
1079
+
1080
+ # embed positions
1081
+ hidden_states = inputs_embeds
1082
+
1083
+ # decoder layers
1084
+ all_hidden_states = () if output_hidden_states else None
1085
+ all_self_attns = () if output_attentions else None
1086
+ next_decoder_cache = None
1087
+
1088
+ for decoder_layer in self.layers:
1089
+ if output_hidden_states:
1090
+ all_hidden_states += (hidden_states,)
1091
+
1092
+ if self.gradient_checkpointing and self.training:
1093
+ layer_outputs = self._gradient_checkpointing_func(
1094
+ decoder_layer.__call__,
1095
+ hidden_states,
1096
+ attention_mask,
1097
+ position_ids,
1098
+ past_key_values,
1099
+ output_attentions,
1100
+ use_cache,
1101
+ )
1102
+ else:
1103
+ layer_outputs = decoder_layer(
1104
+ hidden_states,
1105
+ attention_mask=attention_mask,
1106
+ position_ids=position_ids,
1107
+ past_key_value=past_key_values,
1108
+ output_attentions=output_attentions,
1109
+ use_cache=use_cache,
1110
+ )
1111
+
1112
+ hidden_states = layer_outputs[0]
1113
+
1114
+ if use_cache:
1115
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1116
+
1117
+ if output_attentions:
1118
+ all_self_attns += (layer_outputs[1],)
1119
+
1120
+ hidden_states = self.norm(hidden_states)
1121
+
1122
+ # add hidden states from the last decoder layer
1123
+ if output_hidden_states:
1124
+ all_hidden_states += (hidden_states,)
1125
+
1126
+ next_cache = None
1127
+ if use_cache:
1128
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1129
+ if not return_dict:
1130
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1131
+ return BaseModelOutputWithPast(
1132
+ last_hidden_state=hidden_states,
1133
+ past_key_values=next_cache,
1134
+ hidden_states=all_hidden_states,
1135
+ attentions=all_self_attns,
1136
+ )
1137
+
1138
+
1139
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1140
+ _tied_weights_keys = ["lm_head.weight"]
1141
+
1142
+ def __init__(self, config):
1143
+ super().__init__(config)
1144
+ self.model = LlamaModel(config)
1145
+ self.vocab_size = config.vocab_size
1146
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1147
+
1148
+ # Initialize weights and apply final processing
1149
+ self.post_init()
1150
+
1151
+ def get_input_embeddings(self):
1152
+ return self.model.embed_tokens
1153
+
1154
+ def set_input_embeddings(self, value):
1155
+ self.model.embed_tokens = value
1156
+
1157
+ def get_output_embeddings(self):
1158
+ return self.lm_head
1159
+
1160
+ def set_output_embeddings(self, new_embeddings):
1161
+ self.lm_head = new_embeddings
1162
+
1163
+ def set_decoder(self, decoder):
1164
+ self.model = decoder
1165
+
1166
+ def get_decoder(self):
1167
+ return self.model
1168
+
1169
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1170
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1171
+ def forward(
1172
+ self,
1173
+ input_ids: torch.LongTensor = None,
1174
+ attention_mask: Optional[torch.Tensor] = None,
1175
+ position_ids: Optional[torch.LongTensor] = None,
1176
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1177
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1178
+ labels: Optional[torch.LongTensor] = None,
1179
+ use_cache: Optional[bool] = None,
1180
+ output_attentions: Optional[bool] = None,
1181
+ output_hidden_states: Optional[bool] = None,
1182
+ return_dict: Optional[bool] = None,
1183
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1184
+ r"""
1185
+ Args:
1186
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1187
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1188
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1189
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1190
+
1191
+ Returns:
1192
+
1193
+ Example:
1194
+
1195
+ ```python
1196
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1197
+
1198
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1199
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1200
+
1201
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1202
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1203
+
1204
+ >>> # Generate
1205
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1206
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1207
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1208
+ ```"""
1209
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1210
+ output_hidden_states = (
1211
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1212
+ )
1213
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1214
+
1215
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1216
+ outputs = self.model(
1217
+ input_ids=input_ids,
1218
+ attention_mask=attention_mask,
1219
+ position_ids=position_ids,
1220
+ past_key_values=past_key_values,
1221
+ inputs_embeds=inputs_embeds,
1222
+ use_cache=use_cache,
1223
+ output_attentions=output_attentions,
1224
+ output_hidden_states=output_hidden_states,
1225
+ return_dict=return_dict,
1226
+ )
1227
+
1228
+ hidden_states = outputs[0]
1229
+ if self.config.pretraining_tp > 1:
1230
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1231
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1232
+ logits = torch.cat(logits, dim=-1)
1233
+ else:
1234
+ logits = self.lm_head(hidden_states)
1235
+ logits = logits.float()
1236
+
1237
+ loss = None
1238
+ if labels is not None:
1239
+ # Shift so that tokens < n predict n
1240
+ shift_logits = logits[..., :-1, :].contiguous()
1241
+ shift_labels = labels[..., 1:].contiguous()
1242
+ # Flatten the tokens
1243
+ loss_fct = CrossEntropyLoss()
1244
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1245
+ shift_labels = shift_labels.view(-1)
1246
+ # Enable model parallelism
1247
+ shift_labels = shift_labels.to(shift_logits.device)
1248
+ loss = loss_fct(shift_logits, shift_labels)
1249
+
1250
+ if not return_dict:
1251
+ output = (logits,) + outputs[1:]
1252
+ return (loss,) + output if loss is not None else output
1253
+
1254
+ return CausalLMOutputWithPast(
1255
+ loss=loss,
1256
+ logits=logits,
1257
+ past_key_values=outputs.past_key_values,
1258
+ hidden_states=outputs.hidden_states,
1259
+ attentions=outputs.attentions,
1260
+ )
1261
+
1262
+ def prepare_inputs_for_generation(
1263
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1264
+ ):
1265
+ if past_key_values is not None:
1266
+ if isinstance(past_key_values, Cache):
1267
+ cache_length = past_key_values.get_seq_length()
1268
+ past_length = past_key_values.seen_tokens
1269
+ max_cache_length = past_key_values.get_max_length()
1270
+ else:
1271
+ cache_length = past_length = past_key_values[0][0].shape[2]
1272
+ max_cache_length = None
1273
+
1274
+ # Keep only the unprocessed tokens:
1275
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1276
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1277
+ # input)
1278
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1279
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1280
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1281
+ # input_ids based on the past_length.
1282
+ elif past_length < input_ids.shape[1]:
1283
+ input_ids = input_ids[:, past_length:]
1284
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1285
+
1286
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1287
+ if (
1288
+ max_cache_length is not None
1289
+ and attention_mask is not None
1290
+ and cache_length + input_ids.shape[1] > max_cache_length
1291
+ ):
1292
+ attention_mask = attention_mask[:, -max_cache_length:]
1293
+
1294
+ position_ids = kwargs.get("position_ids", None)
1295
+ if attention_mask is not None and position_ids is None:
1296
+ # create position_ids on the fly for batch generation
1297
+ position_ids = attention_mask.long().cumsum(-1) - 1
1298
+ position_ids.masked_fill_(attention_mask == 0, 1)
1299
+ if past_key_values:
1300
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1301
+
1302
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1303
+ if inputs_embeds is not None and past_key_values is None:
1304
+ model_inputs = {"inputs_embeds": inputs_embeds}
1305
+ else:
1306
+ model_inputs = {"input_ids": input_ids}
1307
+
1308
+ model_inputs.update(
1309
+ {
1310
+ "position_ids": position_ids,
1311
+ "past_key_values": past_key_values,
1312
+ "use_cache": kwargs.get("use_cache"),
1313
+ "attention_mask": attention_mask,
1314
+ }
1315
+ )
1316
+ return model_inputs
1317
+
1318
+ @staticmethod
1319
+ def _reorder_cache(past_key_values, beam_idx):
1320
+ reordered_past = ()
1321
+ for layer_past in past_key_values:
1322
+ reordered_past += (
1323
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1324
+ )
1325
+ return reordered_past
1326
+
1327
+
1328
+ @add_start_docstrings(
1329
+ """
1330
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1331
+
1332
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1333
+ (e.g. GPT-2) do.
1334
+
1335
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1336
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1337
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1338
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1339
+ each row of the batch).
1340
+ """,
1341
+ LLAMA_START_DOCSTRING,
1342
+ )
1343
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1344
+ def __init__(self, config):
1345
+ super().__init__(config)
1346
+ self.num_labels = config.num_labels
1347
+ self.model = LlamaModel(config)
1348
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1349
+
1350
+ # Initialize weights and apply final processing
1351
+ self.post_init()
1352
+
1353
+ def get_input_embeddings(self):
1354
+ return self.model.embed_tokens
1355
+
1356
+ def set_input_embeddings(self, value):
1357
+ self.model.embed_tokens = value
1358
+
1359
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1360
+ def forward(
1361
+ self,
1362
+ input_ids: torch.LongTensor = None,
1363
+ attention_mask: Optional[torch.Tensor] = None,
1364
+ position_ids: Optional[torch.LongTensor] = None,
1365
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1366
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1367
+ labels: Optional[torch.LongTensor] = None,
1368
+ use_cache: Optional[bool] = None,
1369
+ output_attentions: Optional[bool] = None,
1370
+ output_hidden_states: Optional[bool] = None,
1371
+ return_dict: Optional[bool] = None,
1372
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1373
+ r"""
1374
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1375
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1376
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1377
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1378
+ """
1379
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1380
+
1381
+ transformer_outputs = self.model(
1382
+ input_ids,
1383
+ attention_mask=attention_mask,
1384
+ position_ids=position_ids,
1385
+ past_key_values=past_key_values,
1386
+ inputs_embeds=inputs_embeds,
1387
+ use_cache=use_cache,
1388
+ output_attentions=output_attentions,
1389
+ output_hidden_states=output_hidden_states,
1390
+ return_dict=return_dict,
1391
+ )
1392
+ hidden_states = transformer_outputs[0]
1393
+ logits = self.score(hidden_states)
1394
+
1395
+ if input_ids is not None:
1396
+ batch_size = input_ids.shape[0]
1397
+ else:
1398
+ batch_size = inputs_embeds.shape[0]
1399
+
1400
+ if self.config.pad_token_id is None and batch_size != 1:
1401
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1402
+ if self.config.pad_token_id is None:
1403
+ sequence_lengths = -1
1404
+ else:
1405
+ if input_ids is not None:
1406
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1407
+ logits.device
1408
+ )
1409
+ else:
1410
+ sequence_lengths = -1
1411
+
1412
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1413
+
1414
+ loss = None
1415
+ if labels is not None:
1416
+ labels = labels.to(logits.device)
1417
+ if self.config.problem_type is None:
1418
+ if self.num_labels == 1:
1419
+ self.config.problem_type = "regression"
1420
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1421
+ self.config.problem_type = "single_label_classification"
1422
+ else:
1423
+ self.config.problem_type = "multi_label_classification"
1424
+
1425
+ if self.config.problem_type == "regression":
1426
+ loss_fct = MSELoss()
1427
+ if self.num_labels == 1:
1428
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1429
+ else:
1430
+ loss = loss_fct(pooled_logits, labels)
1431
+ elif self.config.problem_type == "single_label_classification":
1432
+ loss_fct = CrossEntropyLoss()
1433
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1434
+ elif self.config.problem_type == "multi_label_classification":
1435
+ loss_fct = BCEWithLogitsLoss()
1436
+ loss = loss_fct(pooled_logits, labels)
1437
+ if not return_dict:
1438
+ output = (pooled_logits,) + transformer_outputs[1:]
1439
+ return ((loss,) + output) if loss is not None else output
1440
+
1441
+ return SequenceClassifierOutputWithPast(
1442
+ loss=loss,
1443
+ logits=pooled_logits,
1444
+ past_key_values=transformer_outputs.past_key_values,
1445
+ hidden_states=transformer_outputs.hidden_states,
1446
+ attentions=transformer_outputs.attentions,
1447
+ )