fusion-bench 0.2.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (727) hide show
  1. fusion_bench/__init__.py +20 -0
  2. fusion_bench/__main__.py +4 -0
  3. fusion_bench/compat/__init__.py +0 -0
  4. fusion_bench/compat/method/__init__.py +109 -0
  5. fusion_bench/compat/method/base_algorithm.py +58 -0
  6. fusion_bench/compat/modelpool/AutoModelForSeq2SeqLM.py +34 -0
  7. fusion_bench/compat/modelpool/__init__.py +116 -0
  8. fusion_bench/compat/modelpool/base_pool.py +328 -0
  9. fusion_bench/compat/modelpool/huggingface_clip_vision.py +178 -0
  10. fusion_bench/compat/taskpool/__init__.py +95 -0
  11. fusion_bench/compat/taskpool/base_pool.py +111 -0
  12. fusion_bench/compat/taskpool/clip_image_classification.py +210 -0
  13. fusion_bench/compat/taskpool/flan_t5_glue_text_generation.py +175 -0
  14. fusion_bench/constants/__init__.py +2 -0
  15. fusion_bench/constants/paths.py +18 -0
  16. fusion_bench/dataset/__init__.py +29 -0
  17. fusion_bench/dataset/arc_agi/__init__.py +6 -0
  18. fusion_bench/dataset/arc_agi/arc.py +308 -0
  19. fusion_bench/dataset/arc_agi/arc_agi.py +365 -0
  20. fusion_bench/dataset/arc_agi/augmenters.py +1036 -0
  21. fusion_bench/dataset/arc_agi/messagers.py +1355 -0
  22. fusion_bench/dataset/arc_agi/np_cache.py +168 -0
  23. fusion_bench/dataset/arc_agi/preprocess.py +298 -0
  24. fusion_bench/dataset/arc_agi/representers.py +1019 -0
  25. fusion_bench/dataset/clip_dataset.py +71 -0
  26. fusion_bench/dataset/fer2013.py +12 -0
  27. fusion_bench/dataset/gpt2_glue.py +300 -0
  28. fusion_bench/dataset/gsm8k.py +60 -0
  29. fusion_bench/dataset/image_dataset.py +55 -0
  30. fusion_bench/dataset/imdb.py +11 -0
  31. fusion_bench/dataset/llama/__init__.py +1 -0
  32. fusion_bench/dataset/llama/alpaca.py +232 -0
  33. fusion_bench/dataset/llama/collate.py +120 -0
  34. fusion_bench/dataset/llama/metamathqa.py +50 -0
  35. fusion_bench/dataset/llama/openai.py +160 -0
  36. fusion_bench/dataset/llama/preference_700k.py +70 -0
  37. fusion_bench/dataset/llama/sharegpt.py +141 -0
  38. fusion_bench/dataset/llama/squad.py +125 -0
  39. fusion_bench/dataset/llama/stanford_shp.py +90 -0
  40. fusion_bench/dataset/llama/ultrachat.py +58 -0
  41. fusion_bench/dataset/llama/utils/__init__.py +0 -0
  42. fusion_bench/dataset/llama/wikitext.py +89 -0
  43. fusion_bench/dataset/nyuv2.py +119 -0
  44. fusion_bench/method/__init__.py +177 -0
  45. fusion_bench/method/ada_svd/__init__.py +2 -0
  46. fusion_bench/method/ada_svd/clip_vision.py +319 -0
  47. fusion_bench/method/adamerging/__init__.py +6 -0
  48. fusion_bench/method/adamerging/clip_layer_wise_adamerging.py +46 -0
  49. fusion_bench/method/adamerging/clip_task_wise_adamerging.py +187 -0
  50. fusion_bench/method/adamerging/entropy_loss.py +25 -0
  51. fusion_bench/method/adamerging/flan_t5_layer_wise_adamerging.py +332 -0
  52. fusion_bench/method/adamerging/gpt2_layer_wise_adamerging.py +351 -0
  53. fusion_bench/method/adamerging/layer_wise_adamerging.py +252 -0
  54. fusion_bench/method/adamerging/llama_adamerging.py +335 -0
  55. fusion_bench/method/adamerging/min_norm_solvers.py +227 -0
  56. fusion_bench/method/adamerging/task_wise_adamerging.py +174 -0
  57. fusion_bench/method/adamerging/utils.py +15 -0
  58. fusion_bench/method/analysis/__init__.py +2 -0
  59. fusion_bench/method/analysis/task_vector_cos_similarity.py +172 -0
  60. fusion_bench/method/analysis/task_vector_violin_plot.py +205 -0
  61. fusion_bench/method/base_algorithm.py +44 -0
  62. fusion_bench/method/classification/__init__.py +3 -0
  63. fusion_bench/method/classification/clip_finetune.py +444 -0
  64. fusion_bench/method/classification/continual_clip_finetune.py +297 -0
  65. fusion_bench/method/concrete_subspace/__init__.py +6 -0
  66. fusion_bench/method/concrete_subspace/clip_concrete_adamerging.py +595 -0
  67. fusion_bench/method/concrete_subspace/clip_concrete_task_arithmetic.py +263 -0
  68. fusion_bench/method/dare/__init__.py +4 -0
  69. fusion_bench/method/dare/simple_average.py +31 -0
  70. fusion_bench/method/dare/task_arithmetic.py +82 -0
  71. fusion_bench/method/dare/ties_merging.py +100 -0
  72. fusion_bench/method/dare/utils.py +87 -0
  73. fusion_bench/method/dawe/__init__.py +2 -0
  74. fusion_bench/method/dawe/dawe_for_clip.py +274 -0
  75. fusion_bench/method/dawe/warppers/__init__.py +13 -0
  76. fusion_bench/method/dawe/warppers/dawe_model.py +256 -0
  77. fusion_bench/method/depth_upscaling/__init__.py +3 -0
  78. fusion_bench/method/depth_upscaling/depth_upscaling.py +89 -0
  79. fusion_bench/method/depth_upscaling/depth_upscaling_for_llama.py +57 -0
  80. fusion_bench/method/dummy.py +35 -0
  81. fusion_bench/method/ensemble.py +98 -0
  82. fusion_bench/method/fisher_merging/__init__.py +4 -0
  83. fusion_bench/method/fisher_merging/clip_fisher_merging.py +191 -0
  84. fusion_bench/method/fisher_merging/fisher_merging.py +484 -0
  85. fusion_bench/method/fisher_merging/gpt2_fisher_merging.py +193 -0
  86. fusion_bench/method/linear/__init__.py +6 -0
  87. fusion_bench/method/linear/expo.py +118 -0
  88. fusion_bench/method/linear/linear_interpolation.py +60 -0
  89. fusion_bench/method/linear/llama_expo.py +229 -0
  90. fusion_bench/method/linear/simple_average_for_llama.py +54 -0
  91. fusion_bench/method/linear/task_arithmetic_for_llama.py +57 -0
  92. fusion_bench/method/lm_finetune/__init__.py +3 -0
  93. fusion_bench/method/lm_finetune/bradley_terry_rm.py +432 -0
  94. fusion_bench/method/lm_finetune/causal_lm_pretrain.py +7 -0
  95. fusion_bench/method/lm_finetune/fullfinetune_sft.py +375 -0
  96. fusion_bench/method/lm_finetune/peftfinetune_sft.py +370 -0
  97. fusion_bench/method/mixture_of_experts/__init__.py +7 -0
  98. fusion_bench/method/mixture_of_experts/mixtral_merging.py +112 -0
  99. fusion_bench/method/mixture_of_experts/mixtral_upcycling.py +329 -0
  100. fusion_bench/method/model_recombination.py +121 -0
  101. fusion_bench/method/opcm/__init__.py +4 -0
  102. fusion_bench/method/opcm/opcm.py +277 -0
  103. fusion_bench/method/opcm/task_arithmetic.py +115 -0
  104. fusion_bench/method/opcm/ties_merging.py +156 -0
  105. fusion_bench/method/opcm/utils.py +73 -0
  106. fusion_bench/method/opcm/weight_average.py +120 -0
  107. fusion_bench/method/pruning/__init__.py +5 -0
  108. fusion_bench/method/pruning/llama_magnitude_prune.py +202 -0
  109. fusion_bench/method/pruning/llama_random_prune.py +143 -0
  110. fusion_bench/method/pruning/llama_wanda_prune.py +359 -0
  111. fusion_bench/method/pruning/magnitude_diff_pruning.py +180 -0
  112. fusion_bench/method/pruning/prune_utils.py +165 -0
  113. fusion_bench/method/pruning/wanda_utils/__init__.py +7 -0
  114. fusion_bench/method/pruning/wanda_utils/ablate.py +188 -0
  115. fusion_bench/method/pruning/wanda_utils/data.py +135 -0
  116. fusion_bench/method/pruning/wanda_utils/eval.py +245 -0
  117. fusion_bench/method/pruning/wanda_utils/layerwrapper.py +61 -0
  118. fusion_bench/method/pruning/wanda_utils/prune.py +581 -0
  119. fusion_bench/method/pruning/wanda_utils/prune_opt.py +539 -0
  120. fusion_bench/method/pruning/wanda_utils/sparsegpt.py +165 -0
  121. fusion_bench/method/pwe_moe/__init__.py +5 -0
  122. fusion_bench/method/pwe_moe/clip_pwe_moe.py +315 -0
  123. fusion_bench/method/pwe_moe/module.py +316 -0
  124. fusion_bench/method/pwe_moe/phn/__init__.py +2 -0
  125. fusion_bench/method/pwe_moe/phn/solvers.py +195 -0
  126. fusion_bench/method/pwe_moe/utils.py +43 -0
  127. fusion_bench/method/rankone_moe/__init__.py +3 -0
  128. fusion_bench/method/rankone_moe/clip_rankone_moe.py +160 -0
  129. fusion_bench/method/rankone_moe/rankone_moe.py +249 -0
  130. fusion_bench/method/regmean/__init__.py +4 -0
  131. fusion_bench/method/regmean/clip_regmean.py +131 -0
  132. fusion_bench/method/regmean/gpt2_regmean.py +147 -0
  133. fusion_bench/method/regmean/regmean.py +375 -0
  134. fusion_bench/method/simple_average.py +112 -0
  135. fusion_bench/method/slerp/__init__.py +2 -0
  136. fusion_bench/method/slerp/slerp.py +101 -0
  137. fusion_bench/method/slerp/slerp_utils.py +107 -0
  138. fusion_bench/method/smile_upscaling/__init__.py +3 -0
  139. fusion_bench/method/smile_upscaling/singular_projection_merging.py +198 -0
  140. fusion_bench/method/smile_upscaling/smile_mistral_upscaling.py +331 -0
  141. fusion_bench/method/smile_upscaling/smile_upscaling.py +573 -0
  142. fusion_bench/method/sparse_we_moe/__init__.py +2 -0
  143. fusion_bench/method/sparse_we_moe/sparse_clip_we_moe.py +248 -0
  144. fusion_bench/method/sparse_we_moe/sparse_we_moe.py +301 -0
  145. fusion_bench/method/sparselo/__init__.py +2 -0
  146. fusion_bench/method/sparselo/sparselo.py +955 -0
  147. fusion_bench/method/surgery/__init__.py +1 -0
  148. fusion_bench/method/surgery/clip_layer_wise_adamerging_surgery.py +157 -0
  149. fusion_bench/method/tall_mask/__init__.py +0 -0
  150. fusion_bench/method/tall_mask/utils.py +234 -0
  151. fusion_bench/method/task_arithmetic/__init__.py +2 -0
  152. fusion_bench/method/task_arithmetic/task_arithmetic.py +151 -0
  153. fusion_bench/method/task_singular_vector/TSVC.py +16 -0
  154. fusion_bench/method/task_singular_vector/TSVM.py +63 -0
  155. fusion_bench/method/task_singular_vector/__init__.py +9 -0
  156. fusion_bench/method/task_singular_vector/utils/TSVC_utils.py +50 -0
  157. fusion_bench/method/task_singular_vector/utils/TSVM_utils.py +640 -0
  158. fusion_bench/method/task_singular_vector/utils/__init__.py +7 -0
  159. fusion_bench/method/ties_merging/__init__.py +2 -0
  160. fusion_bench/method/ties_merging/ties_merging.py +117 -0
  161. fusion_bench/method/ties_merging/ties_merging_utils.py +331 -0
  162. fusion_bench/method/trust_region/__init__.py +2 -0
  163. fusion_bench/method/trust_region/clip_task_arithmetic.py +205 -0
  164. fusion_bench/method/trust_region/utils.py +58 -0
  165. fusion_bench/method/we_moe/__init__.py +2 -0
  166. fusion_bench/method/we_moe/clip_we_moe.py +161 -0
  167. fusion_bench/method/we_moe/we_moe.py +247 -0
  168. fusion_bench/method/weighted_average/__init__.py +3 -0
  169. fusion_bench/method/weighted_average/llama.py +113 -0
  170. fusion_bench/method/weighted_average/weighted_average.py +102 -0
  171. fusion_bench/metrics/__init__.py +0 -0
  172. fusion_bench/metrics/continual_learning/backward_transfer.py +22 -0
  173. fusion_bench/metrics/nyuv2/__init__.py +11 -0
  174. fusion_bench/metrics/nyuv2/depth.py +45 -0
  175. fusion_bench/metrics/nyuv2/loss.py +31 -0
  176. fusion_bench/metrics/nyuv2/noise.py +16 -0
  177. fusion_bench/metrics/nyuv2/normal.py +48 -0
  178. fusion_bench/metrics/nyuv2/segmentation.py +43 -0
  179. fusion_bench/metrics/text_to_image_generation/__init__.py +9 -0
  180. fusion_bench/metrics/text_to_image_generation/aesthetic_scorer.py +123 -0
  181. fusion_bench/metrics/text_to_image_generation/compressibility.py +49 -0
  182. fusion_bench/metrics/text_to_image_generation/pickscore_scorer.py +95 -0
  183. fusion_bench/mixins/__init__.py +28 -0
  184. fusion_bench/mixins/clip_classification.py +252 -0
  185. fusion_bench/mixins/fabric_training.py +320 -0
  186. fusion_bench/mixins/lightning_fabric.py +174 -0
  187. fusion_bench/mixins/optim/__init__.py +0 -0
  188. fusion_bench/mixins/optim/adamw_with_warmup.py +42 -0
  189. fusion_bench/mixins/rich_live.py +21 -0
  190. fusion_bench/mixins/serialization.py +132 -0
  191. fusion_bench/mixins/simple_profiler.py +79 -0
  192. fusion_bench/modelpool/PeftModelForSeq2SeqLM.py +49 -0
  193. fusion_bench/modelpool/__init__.py +42 -0
  194. fusion_bench/modelpool/base_pool.py +268 -0
  195. fusion_bench/modelpool/causal_lm/__init__.py +2 -0
  196. fusion_bench/modelpool/causal_lm/causal_lm.py +139 -0
  197. fusion_bench/modelpool/clip_vision/__init__.py +1 -0
  198. fusion_bench/modelpool/clip_vision/modelpool.py +145 -0
  199. fusion_bench/modelpool/huggingface_automodel.py +20 -0
  200. fusion_bench/modelpool/huggingface_gpt2_classification.py +63 -0
  201. fusion_bench/modelpool/nyuv2_modelpool.py +40 -0
  202. fusion_bench/modelpool/seq2seq_lm/__init__.py +2 -0
  203. fusion_bench/modelpool/seq2seq_lm/modelpool.py +65 -0
  204. fusion_bench/modelpool/seq_classification_lm/__init__.py +2 -0
  205. fusion_bench/modelpool/seq_classification_lm/reward_model.py +15 -0
  206. fusion_bench/modelpool/seq_classification_lm/seq_classification_lm.py +98 -0
  207. fusion_bench/models/__init__.py +3 -0
  208. fusion_bench/models/chat_templates/__init__.py +1 -0
  209. fusion_bench/models/chat_templates/llama_3_Instruct.py +1 -0
  210. fusion_bench/models/chat_templates/load_tokenizer.py +43 -0
  211. fusion_bench/models/hf_clip.py +199 -0
  212. fusion_bench/models/linearized/__init__.py +0 -0
  213. fusion_bench/models/linearized/linearized_model_utils.py +91 -0
  214. fusion_bench/models/linearized/vision_model.py +122 -0
  215. fusion_bench/models/llama/__init__.py +16 -0
  216. fusion_bench/models/llama/model_utils/__init__.py +0 -0
  217. fusion_bench/models/llama/model_utils/embedding.py +87 -0
  218. fusion_bench/models/llama/model_utils/liger_kernel.py +86 -0
  219. fusion_bench/models/llama/model_utils/misc.py +112 -0
  220. fusion_bench/models/llama/model_utils/mod.py +52 -0
  221. fusion_bench/models/llama/model_utils/visual.py +241 -0
  222. fusion_bench/models/llama/patcher.py +78 -0
  223. fusion_bench/models/llama/tokenizer_loader.py +153 -0
  224. fusion_bench/models/masks/__init__.py +2 -0
  225. fusion_bench/models/masks/mask_model.py +160 -0
  226. fusion_bench/models/modeling_losparse_llama/__init__.py +4 -0
  227. fusion_bench/models/modeling_losparse_llama/configuration_losparse_llama.py +205 -0
  228. fusion_bench/models/modeling_losparse_llama/losparse_linear.py +67 -0
  229. fusion_bench/models/modeling_losparse_llama/modeling_losparse_llama.py +1825 -0
  230. fusion_bench/models/modeling_losparse_llama/register.py +8 -0
  231. fusion_bench/models/modeling_losparse_llama/utils.py +60 -0
  232. fusion_bench/models/modeling_smile_mistral/__init__.py +48 -0
  233. fusion_bench/models/modeling_smile_mistral/configuration_smile_mistral.py +21 -0
  234. fusion_bench/models/modeling_smile_mistral/modeling_smile_mistral.py +1034 -0
  235. fusion_bench/models/modeling_smile_mistral/register.py +8 -0
  236. fusion_bench/models/nyuv2/__init__.py +0 -0
  237. fusion_bench/models/nyuv2/aspp.py +82 -0
  238. fusion_bench/models/nyuv2/lightning_module.py +176 -0
  239. fusion_bench/models/nyuv2/resnet.py +405 -0
  240. fusion_bench/models/nyuv2/resnet_dilated.py +99 -0
  241. fusion_bench/models/parameter_dict.py +75 -0
  242. fusion_bench/models/rankone_moe.py +410 -0
  243. fusion_bench/models/separate_io.py +105 -0
  244. fusion_bench/models/smile_moe/__init__.py +0 -0
  245. fusion_bench/models/smile_moe/linear.py +256 -0
  246. fusion_bench/models/sparse_we_moe.py +459 -0
  247. fusion_bench/models/surgery/__init__.py +1 -0
  248. fusion_bench/models/surgery/surgerymodelwrapper.py +158 -0
  249. fusion_bench/models/utils.py +80 -0
  250. fusion_bench/models/we_moe.py +247 -0
  251. fusion_bench/models/wrappers/__init__.py +0 -0
  252. fusion_bench/models/wrappers/ensemble.py +183 -0
  253. fusion_bench/models/wrappers/layer_wise_fusion.py +336 -0
  254. fusion_bench/models/wrappers/task_wise_fusion.py +249 -0
  255. fusion_bench/optim/__init__.py +2 -0
  256. fusion_bench/optim/exception.py +47 -0
  257. fusion_bench/optim/lr_scheduler/__init__.py +1 -0
  258. fusion_bench/optim/lr_scheduler/linear_warmup.py +222 -0
  259. fusion_bench/optim/lr_scheduler/utils/__init__.py +1 -0
  260. fusion_bench/optim/lr_scheduler/utils/visualization.py +119 -0
  261. fusion_bench/optim/mezo.py +118 -0
  262. fusion_bench/programs/__init__.py +20 -0
  263. fusion_bench/programs/base_program.py +9 -0
  264. fusion_bench/programs/fabric_fusion_program.py +299 -0
  265. fusion_bench/scripts/__init__.py +0 -0
  266. fusion_bench/scripts/cli.py +43 -0
  267. fusion_bench/scripts/clip/__init__.py +0 -0
  268. fusion_bench/scripts/clip/convert_checkpoint.py +39 -0
  269. fusion_bench/scripts/imgui.py +218 -0
  270. fusion_bench/scripts/nyuv2_mtl_train.py +137 -0
  271. fusion_bench/scripts/webui.py +405 -0
  272. fusion_bench/taskpool/__init__.py +39 -0
  273. fusion_bench/taskpool/base_pool.py +35 -0
  274. fusion_bench/taskpool/clip_vision/__init__.py +4 -0
  275. fusion_bench/taskpool/clip_vision/clip_rankone_moe_taskpool.py +112 -0
  276. fusion_bench/taskpool/clip_vision/clip_sparse_wemoe_taskpool.py +120 -0
  277. fusion_bench/taskpool/clip_vision/taskpool.py +392 -0
  278. fusion_bench/taskpool/dummy.py +58 -0
  279. fusion_bench/taskpool/gpt2_text_classification.py +149 -0
  280. fusion_bench/taskpool/llama/__init__.py +1 -0
  281. fusion_bench/taskpool/llama/reward_model.py +157 -0
  282. fusion_bench/taskpool/llama/test_generation.py +185 -0
  283. fusion_bench/taskpool/nyuv2_taskpool.py +65 -0
  284. fusion_bench/tasks/__init__.py +2 -0
  285. fusion_bench/tasks/base_task.py +18 -0
  286. fusion_bench/tasks/classification.py +75 -0
  287. fusion_bench/tasks/clip_classification/__init__.py +183 -0
  288. fusion_bench/tasks/clip_classification/cifar10.py +33 -0
  289. fusion_bench/tasks/clip_classification/cifar100.py +146 -0
  290. fusion_bench/tasks/clip_classification/clip_dataset.py +1 -0
  291. fusion_bench/tasks/clip_classification/cub_200_2011.py +208 -0
  292. fusion_bench/tasks/clip_classification/dtd.py +60 -0
  293. fusion_bench/tasks/clip_classification/emnist_letters.py +31 -0
  294. fusion_bench/tasks/clip_classification/emnist_mnist.py +5 -0
  295. fusion_bench/tasks/clip_classification/eurosat.py +18 -0
  296. fusion_bench/tasks/clip_classification/fashion_mnist.py +18 -0
  297. fusion_bench/tasks/clip_classification/fer2013.py +18 -0
  298. fusion_bench/tasks/clip_classification/flower102.py +106 -0
  299. fusion_bench/tasks/clip_classification/food101.py +105 -0
  300. fusion_bench/tasks/clip_classification/gtsrb.py +51 -0
  301. fusion_bench/tasks/clip_classification/imagenet.py +2103 -0
  302. fusion_bench/tasks/clip_classification/kmnist.py +17 -0
  303. fusion_bench/tasks/clip_classification/mnist.py +5 -0
  304. fusion_bench/tasks/clip_classification/mongo_leaf_disease.py +19 -0
  305. fusion_bench/tasks/clip_classification/oxford_iiit_pet.py +41 -0
  306. fusion_bench/tasks/clip_classification/pcam.py +5 -0
  307. fusion_bench/tasks/clip_classification/rendered_sst2.py +3 -0
  308. fusion_bench/tasks/clip_classification/resisc45.py +68 -0
  309. fusion_bench/tasks/clip_classification/stanford_cars.py +209 -0
  310. fusion_bench/tasks/clip_classification/stl10.py +17 -0
  311. fusion_bench/tasks/clip_classification/sun397.py +404 -0
  312. fusion_bench/tasks/clip_classification/svhn.py +5 -0
  313. fusion_bench/tasks/clip_classification/tiny_imagenet.py +208 -0
  314. fusion_bench/tasks/flan_t5_text_generation/__init__.py +0 -0
  315. fusion_bench/tasks/flan_t5_text_generation/datasets_preprocess.py +71 -0
  316. fusion_bench/tasks/flan_t5_text_generation/glue_evaluation.py +132 -0
  317. fusion_bench/tasks/flan_t5_text_generation/glue_load_dataset.py +64 -0
  318. fusion_bench/tasks/flan_t5_text_generation/glue_preprocessors.py +379 -0
  319. fusion_bench/tasks/flan_t5_text_generation/glue_prompt_templates.py +52 -0
  320. fusion_bench/utils/__init__.py +14 -0
  321. fusion_bench/utils/auto.py +31 -0
  322. fusion_bench/utils/cache_utils.py +58 -0
  323. fusion_bench/utils/data.py +165 -0
  324. fusion_bench/utils/devices.py +231 -0
  325. fusion_bench/utils/dict.py +43 -0
  326. fusion_bench/utils/dtype.py +146 -0
  327. fusion_bench/utils/expr.py +90 -0
  328. fusion_bench/utils/fabric.py +17 -0
  329. fusion_bench/utils/functools.py +37 -0
  330. fusion_bench/utils/hydra_utils.py +28 -0
  331. fusion_bench/utils/instantiate.py +450 -0
  332. fusion_bench/utils/json.py +93 -0
  333. fusion_bench/utils/lazy_imports.py +74 -0
  334. fusion_bench/utils/misc.py +18 -0
  335. fusion_bench/utils/packages.py +84 -0
  336. fusion_bench/utils/parameters.py +323 -0
  337. fusion_bench/utils/path.py +22 -0
  338. fusion_bench/utils/plot/__init__.py +0 -0
  339. fusion_bench/utils/plot/color_data.py +1726 -0
  340. fusion_bench/utils/plot/token.py +52 -0
  341. fusion_bench/utils/plot/token_notebook.py +127 -0
  342. fusion_bench/utils/pylogger.py +55 -0
  343. fusion_bench/utils/rich_utils.py +201 -0
  344. fusion_bench/utils/set.py +8 -0
  345. fusion_bench/utils/state_dict_arithmetic.py +297 -0
  346. fusion_bench/utils/strenum/__init__.py +326 -0
  347. fusion_bench/utils/strenum/_name_mangler.py +127 -0
  348. fusion_bench/utils/strenum/_version.py +556 -0
  349. fusion_bench/utils/tensorboard.py +51 -0
  350. fusion_bench/utils/timer.py +49 -0
  351. fusion_bench/utils/type.py +34 -0
  352. fusion_bench-0.2.9.dist-info/LICENSE +21 -0
  353. fusion_bench-0.2.9.dist-info/METADATA +258 -0
  354. fusion_bench-0.2.9.dist-info/RECORD +727 -0
  355. fusion_bench-0.2.9.dist-info/WHEEL +5 -0
  356. fusion_bench-0.2.9.dist-info/entry_points.txt +3 -0
  357. fusion_bench-0.2.9.dist-info/top_level.txt +1 -0
  358. fusion_bench_config/README.md +12 -0
  359. fusion_bench_config/clip-vit-base-patch32_robustness_corrupted.yaml +23 -0
  360. fusion_bench_config/dataset/image_classification/README.md +6 -0
  361. fusion_bench_config/dataset/image_classification/test/TALL14.yaml +20 -0
  362. fusion_bench_config/dataset/image_classification/test/TALL20.yaml +28 -0
  363. fusion_bench_config/dataset/image_classification/test/cifar10.yaml +4 -0
  364. fusion_bench_config/dataset/image_classification/test/cifar100.yaml +4 -0
  365. fusion_bench_config/dataset/image_classification/test/cub-200-2011.yaml +4 -0
  366. fusion_bench_config/dataset/image_classification/test/dtd.yaml +4 -0
  367. fusion_bench_config/dataset/image_classification/test/emnist_letters.yaml +5 -0
  368. fusion_bench_config/dataset/image_classification/test/emnist_mnist.yaml +4 -0
  369. fusion_bench_config/dataset/image_classification/test/eurosat.yaml +4 -0
  370. fusion_bench_config/dataset/image_classification/test/fashion_mnist.yaml +4 -0
  371. fusion_bench_config/dataset/image_classification/test/fer2013.yaml +3 -0
  372. fusion_bench_config/dataset/image_classification/test/food101.yaml +4 -0
  373. fusion_bench_config/dataset/image_classification/test/gtsrb.yaml +4 -0
  374. fusion_bench_config/dataset/image_classification/test/kmnist.yaml +4 -0
  375. fusion_bench_config/dataset/image_classification/test/mango-leaf-disease.yaml +4 -0
  376. fusion_bench_config/dataset/image_classification/test/mnist.yaml +4 -0
  377. fusion_bench_config/dataset/image_classification/test/oxford-iiit-pet.yaml +4 -0
  378. fusion_bench_config/dataset/image_classification/test/oxford_flowers102.yaml +4 -0
  379. fusion_bench_config/dataset/image_classification/test/pcam.yaml +4 -0
  380. fusion_bench_config/dataset/image_classification/test/rendered-sst2.yaml +4 -0
  381. fusion_bench_config/dataset/image_classification/test/resisc45.yaml +4 -0
  382. fusion_bench_config/dataset/image_classification/test/stanford-cars.yaml +4 -0
  383. fusion_bench_config/dataset/image_classification/test/stl10.yaml +4 -0
  384. fusion_bench_config/dataset/image_classification/test/sun397.yaml +4 -0
  385. fusion_bench_config/dataset/image_classification/test/svhn.yaml +6 -0
  386. fusion_bench_config/dataset/image_classification/test/the_eight_tasks.yaml +9 -0
  387. fusion_bench_config/dataset/image_classification/test/tiny-imagenet.yaml +4 -0
  388. fusion_bench_config/dataset/image_classification/train/TALL14.yaml +20 -0
  389. fusion_bench_config/dataset/image_classification/train/TALL20.yaml +28 -0
  390. fusion_bench_config/dataset/image_classification/train/cifar10.yaml +4 -0
  391. fusion_bench_config/dataset/image_classification/train/cifar100.yaml +4 -0
  392. fusion_bench_config/dataset/image_classification/train/cub-200-2011.yaml +4 -0
  393. fusion_bench_config/dataset/image_classification/train/dtd.yaml +4 -0
  394. fusion_bench_config/dataset/image_classification/train/emnist_letters.yaml +4 -0
  395. fusion_bench_config/dataset/image_classification/train/emnist_mnist.yaml +4 -0
  396. fusion_bench_config/dataset/image_classification/train/eurosat.yaml +4 -0
  397. fusion_bench_config/dataset/image_classification/train/fashion_mnist.yaml +4 -0
  398. fusion_bench_config/dataset/image_classification/train/fer2013.yaml +3 -0
  399. fusion_bench_config/dataset/image_classification/train/food101.yaml +4 -0
  400. fusion_bench_config/dataset/image_classification/train/gtsrb.yaml +4 -0
  401. fusion_bench_config/dataset/image_classification/train/kmnist.yaml +4 -0
  402. fusion_bench_config/dataset/image_classification/train/mango-leaf-disease.yaml +4 -0
  403. fusion_bench_config/dataset/image_classification/train/mnist.yaml +4 -0
  404. fusion_bench_config/dataset/image_classification/train/oxford-iiit-pet.yaml +4 -0
  405. fusion_bench_config/dataset/image_classification/train/oxford_flowers102.yaml +4 -0
  406. fusion_bench_config/dataset/image_classification/train/pcam.yaml +4 -0
  407. fusion_bench_config/dataset/image_classification/train/rendered-sst2.yaml +4 -0
  408. fusion_bench_config/dataset/image_classification/train/resisc45.yaml +4 -0
  409. fusion_bench_config/dataset/image_classification/train/stanford-cars.yaml +4 -0
  410. fusion_bench_config/dataset/image_classification/train/stl10.yaml +4 -0
  411. fusion_bench_config/dataset/image_classification/train/sun397.yaml +4 -0
  412. fusion_bench_config/dataset/image_classification/train/svhn.yaml +6 -0
  413. fusion_bench_config/dataset/image_classification/train/the_eight_tasks.yaml +9 -0
  414. fusion_bench_config/dataset/image_classification/train/tiny-imagenet.yaml +4 -0
  415. fusion_bench_config/dataset/image_classification/val/dtd.yaml +10 -0
  416. fusion_bench_config/dataset/image_classification/val/eurosat.yaml +10 -0
  417. fusion_bench_config/dataset/image_classification/val/gtsrb.yaml +10 -0
  418. fusion_bench_config/dataset/image_classification/val/mnist.yaml +10 -0
  419. fusion_bench_config/dataset/image_classification/val/resisc45.yaml +10 -0
  420. fusion_bench_config/dataset/image_classification/val/stanford-cars.yaml +10 -0
  421. fusion_bench_config/dataset/image_classification/val/sun397.yaml +10 -0
  422. fusion_bench_config/dataset/image_classification/val/svhn.yaml +12 -0
  423. fusion_bench_config/dataset/image_classification/val/the_eight_tasks.yaml +9 -0
  424. fusion_bench_config/dataset/llm_sft/alpaca_cleaned.yaml +6 -0
  425. fusion_bench_config/dataset/llm_sft/ultrachat_200k.yaml +3 -0
  426. fusion_bench_config/dataset/question_answering/search_qa.yaml +6 -0
  427. fusion_bench_config/dataset/question_answering/test/search_qa.yaml +7 -0
  428. fusion_bench_config/dataset/question_answering/train/MetaMathQA.yaml +4 -0
  429. fusion_bench_config/dataset/question_answering/train/search_qa.yaml +7 -0
  430. fusion_bench_config/dataset/question_answering/val/search_qa.yaml +7 -0
  431. fusion_bench_config/dataset/summarization/test/xsum.yaml +4 -0
  432. fusion_bench_config/dataset/summarization/train/xsum.yaml +4 -0
  433. fusion_bench_config/dataset/summarization/val/xsum.yaml +4 -0
  434. fusion_bench_config/dataset/summarization/xsum.yaml +3 -0
  435. fusion_bench_config/dataset/text_generation/test/gsm-hard.yaml +4 -0
  436. fusion_bench_config/dataset/text_generation/test/gsm8k.yaml +5 -0
  437. fusion_bench_config/dataset/text_generation/test/gsm8k_question_label.yaml +3 -0
  438. fusion_bench_config/dataset/text_generation/train/CodeAlpaca-20k.yaml +4 -0
  439. fusion_bench_config/dataset/text_generation/train/gsm8k.yaml +5 -0
  440. fusion_bench_config/dataset/text_generation/train/gsm8k_question_label.yaml +3 -0
  441. fusion_bench_config/fabric/auto.yaml +16 -0
  442. fusion_bench_config/fabric/llama_ddp.yaml +18 -0
  443. fusion_bench_config/fabric/llama_fsdp.yaml +16 -0
  444. fusion_bench_config/fabric/llama_peft_fsdp.yaml +16 -0
  445. fusion_bench_config/fabric/loggers/csv_logger.yaml +11 -0
  446. fusion_bench_config/fabric/loggers/tensorboard_logger.yaml +11 -0
  447. fusion_bench_config/fabric/loggers/wandb_logger.yaml +2 -0
  448. fusion_bench_config/fabric/strategy/deepspeed.yaml +10 -0
  449. fusion_bench_config/fabric/strategy/llama_fsdp.yaml +8 -0
  450. fusion_bench_config/fabric/strategy/llama_peft_fsdp.yaml +9 -0
  451. fusion_bench_config/fabric_model_fusion.yaml +20 -0
  452. fusion_bench_config/hydra/default.yaml +8 -0
  453. fusion_bench_config/hydra/help/fusion_bench_help.yaml +47 -0
  454. fusion_bench_config/hydra/job_logging/rich_logging.yaml +20 -0
  455. fusion_bench_config/llama_full_finetune.yaml +19 -0
  456. fusion_bench_config/llama_magnitude_pruning.yaml +16 -0
  457. fusion_bench_config/llama_model_fusion.yaml +17 -0
  458. fusion_bench_config/method/ada_svd/clip_vision.yaml +9 -0
  459. fusion_bench_config/method/adamerging/clip.yaml +23 -0
  460. fusion_bench_config/method/adamerging/layer_wise_flan_t5.yaml +23 -0
  461. fusion_bench_config/method/adamerging/layer_wise_gpt2.yaml +23 -0
  462. fusion_bench_config/method/adamerging/llama_sft.yaml +33 -0
  463. fusion_bench_config/method/adamerging.yaml +23 -0
  464. fusion_bench_config/method/analysis/task_vector_cos_similarity.yaml +6 -0
  465. fusion_bench_config/method/analysis/task_vector_violin_plot.yaml +6 -0
  466. fusion_bench_config/method/classification/clip_continual_finetune.yaml +28 -0
  467. fusion_bench_config/method/classification/clip_finetune.yaml +26 -0
  468. fusion_bench_config/method/clip_finetune.yaml +26 -0
  469. fusion_bench_config/method/concrete_subspace/clip_concrete_layer_wise_adamerging.yaml +27 -0
  470. fusion_bench_config/method/concrete_subspace/clip_concrete_task_arithmetic.yaml +25 -0
  471. fusion_bench_config/method/concrete_subspace/clip_concrete_task_wise_adamerging.yaml +27 -0
  472. fusion_bench_config/method/dare/simple_average.yaml +5 -0
  473. fusion_bench_config/method/dare/task_arithmetic.yaml +6 -0
  474. fusion_bench_config/method/dare/ties_merging.yaml +15 -0
  475. fusion_bench_config/method/dawe/dawe_for_clip.yaml +32 -0
  476. fusion_bench_config/method/depth_upscaling.yaml +5 -0
  477. fusion_bench_config/method/dummy.yaml +1 -0
  478. fusion_bench_config/method/ensemble/max_model_predictor.yaml +1 -0
  479. fusion_bench_config/method/ensemble/simple_ensemble.yaml +2 -0
  480. fusion_bench_config/method/ensemble/weighted_ensemble.yaml +6 -0
  481. fusion_bench_config/method/fisher_merging/clip_fisher_merging.yaml +13 -0
  482. fusion_bench_config/method/fisher_merging/fisher_merging.yaml +9 -0
  483. fusion_bench_config/method/fisher_merging/gpt2_fisher_merging.yaml +12 -0
  484. fusion_bench_config/method/linear/expo.yaml +8 -0
  485. fusion_bench_config/method/linear/linear_interpolation.yaml +3 -0
  486. fusion_bench_config/method/linear/llama_expo.yaml +19 -0
  487. fusion_bench_config/method/linear/llama_expo_with_dare.yaml +19 -0
  488. fusion_bench_config/method/linear/simple_average_for_llama.yaml +5 -0
  489. fusion_bench_config/method/linear/task_arithmetic_for_llama.yaml +4 -0
  490. fusion_bench_config/method/linear/weighted_average.yaml +6 -0
  491. fusion_bench_config/method/linear/weighted_average_for_llama.yaml +12 -0
  492. fusion_bench_config/method/lm_finetune/bradley_terry_rm.yaml +47 -0
  493. fusion_bench_config/method/lm_finetune/fullfinetune_sft.yaml +47 -0
  494. fusion_bench_config/method/lm_finetune/peftfinetune_sft.yaml +63 -0
  495. fusion_bench_config/method/mixtral_moe_merging.yaml +4 -0
  496. fusion_bench_config/method/mixtral_moe_upscaling.yaml +7 -0
  497. fusion_bench_config/method/model_recombination.yaml +4 -0
  498. fusion_bench_config/method/opcm/opcm.yaml +12 -0
  499. fusion_bench_config/method/opcm/task_arithmetic.yaml +12 -0
  500. fusion_bench_config/method/opcm/ties_merging.yaml +18 -0
  501. fusion_bench_config/method/opcm/weight_average.yaml +10 -0
  502. fusion_bench_config/method/pruning/llama_magnitude_pruning.yaml +14 -0
  503. fusion_bench_config/method/pruning/llama_random_pruning.yaml +9 -0
  504. fusion_bench_config/method/pruning/llama_wanda_pruning.yaml +16 -0
  505. fusion_bench_config/method/pruning/magnitude_diff_pruning.yaml +5 -0
  506. fusion_bench_config/method/pwe_moe_ls_for_clip.yaml +22 -0
  507. fusion_bench_config/method/rankone_moe/rankone_moe.yaml +26 -0
  508. fusion_bench_config/method/regmean/clip_regmean.yaml +11 -0
  509. fusion_bench_config/method/regmean/gpt2_regmean.yaml +12 -0
  510. fusion_bench_config/method/regmean/regmean.yaml +4 -0
  511. fusion_bench_config/method/simple_average.yaml +1 -0
  512. fusion_bench_config/method/slerp/slerp.yaml +6 -0
  513. fusion_bench_config/method/smile_upscaling/singular_projection_merging.yaml +8 -0
  514. fusion_bench_config/method/smile_upscaling/smile_mistral_upscaling.yaml +10 -0
  515. fusion_bench_config/method/smile_upscaling/smile_upscaling.yaml +14 -0
  516. fusion_bench_config/method/sparselo_pruning/llama_iterative_sparselo.yaml +20 -0
  517. fusion_bench_config/method/sparselo_pruning/llama_pcp_sparselo.yaml +20 -0
  518. fusion_bench_config/method/sparselo_pruning/llama_sparselo.yaml +19 -0
  519. fusion_bench_config/method/surgery/adamerging_surgery.yaml +27 -0
  520. fusion_bench_config/method/task_arithmetic.yaml +2 -0
  521. fusion_bench_config/method/task_singular_vector/TaskSingularVectorMerging.yaml +2 -0
  522. fusion_bench_config/method/ties_merging.yaml +8 -0
  523. fusion_bench_config/method/trust_region/clip_task_arithmetic.yaml +7 -0
  524. fusion_bench_config/method/wemoe/sparse_weight_ensembling_moe.yaml +39 -0
  525. fusion_bench_config/method/wemoe/weight_ensembling_moe.yaml +20 -0
  526. fusion_bench_config/model/clip-vit/README.md +38 -0
  527. fusion_bench_config/model/clip-vit/clip-vit-base-patch16.yaml +1 -0
  528. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_TALL14.yaml +22 -0
  529. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_TALL20.yaml +29 -0
  530. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_cifar10.yaml +1 -0
  531. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_cifar100.yaml +1 -0
  532. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_dtd.yaml +1 -0
  533. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_eight_tasks.yaml +10 -0
  534. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_emnist_letters.yaml +1 -0
  535. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_eurosat.yaml +1 -0
  536. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_fashion_mnist.yaml +1 -0
  537. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_fer2013.yaml +1 -0
  538. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_food101.yaml +1 -0
  539. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_gtsrb.yaml +1 -0
  540. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_kmnist.yaml +1 -0
  541. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_mnist.yaml +1 -0
  542. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_oxford-iiit-pet.yaml +1 -0
  543. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_oxford_flowers102.yaml +1 -0
  544. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_pcam.yaml +1 -0
  545. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_rendered-sst2.yaml +1 -0
  546. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_resisc45.yaml +1 -0
  547. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_stanford-cars.yaml +1 -0
  548. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_stl10.yaml +1 -0
  549. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_sun397.yaml +1 -0
  550. fusion_bench_config/model/clip-vit/clip-vit-base-patch16_svhn.yaml +1 -0
  551. fusion_bench_config/model/clip-vit/clip-vit-base-patch32.yaml +1 -0
  552. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_TALL14.yaml +22 -0
  553. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_TALL20.yaml +29 -0
  554. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_cifar10.yaml +1 -0
  555. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_cifar100.yaml +1 -0
  556. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_dtd.yaml +1 -0
  557. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_eight_tasks.yaml +11 -0
  558. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_emnist_letters.yaml +1 -0
  559. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_eurosat.yaml +1 -0
  560. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_fashion_mnist.yaml +1 -0
  561. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_fer2013.yaml +1 -0
  562. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_food101.yaml +1 -0
  563. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_gtsrb.yaml +1 -0
  564. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_kmnist.yaml +1 -0
  565. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_mnist.yaml +1 -0
  566. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_oxford-iiit-pet.yaml +1 -0
  567. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_oxford_flowers102.yaml +1 -0
  568. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_pcam.yaml +1 -0
  569. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_rendered-sst2.yaml +1 -0
  570. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_resisc45.yaml +1 -0
  571. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_stanford-cars.yaml +1 -0
  572. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_stl10.yaml +1 -0
  573. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_sun397.yaml +1 -0
  574. fusion_bench_config/model/clip-vit/clip-vit-base-patch32_svhn.yaml +1 -0
  575. fusion_bench_config/model/clip-vit/clip-vit-large-patch14.yaml +1 -0
  576. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_TALL14.yaml +22 -0
  577. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_TALL20.yaml +29 -0
  578. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_cifar10.yaml +1 -0
  579. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_cifar100.yaml +1 -0
  580. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_dtd.yaml +1 -0
  581. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_eight_tasks.yaml +10 -0
  582. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_emnist_letters.yaml +1 -0
  583. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_eurosat.yaml +1 -0
  584. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_fashion_mnist.yaml +1 -0
  585. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_fer2013.yaml +1 -0
  586. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_food101.yaml +1 -0
  587. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_gtsrb.yaml +1 -0
  588. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_kmnist.yaml +1 -0
  589. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_mnist.yaml +1 -0
  590. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_oxford-iiit-pet.yaml +1 -0
  591. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_oxford_flowers102.yaml +1 -0
  592. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_pcam.yaml +1 -0
  593. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_rendered-sst2.yaml +1 -0
  594. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_resisc45.yaml +1 -0
  595. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_stanford-cars.yaml +1 -0
  596. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_stl10.yaml +1 -0
  597. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_sun397.yaml +1 -0
  598. fusion_bench_config/model/clip-vit/clip-vit-large-patch14_svhn.yaml +1 -0
  599. fusion_bench_config/model/clip-vit/download_TALL20_models.sh +6 -0
  600. fusion_bench_config/model/clip-vit/generate_vit_model_config.sh +23 -0
  601. fusion_bench_config/model/flan-t5/flan-t5-base.yaml +3 -0
  602. fusion_bench_config/model/flan-t5/flan-t5-base_glue-cola.yaml +3 -0
  603. fusion_bench_config/model/flan-t5/flan-t5-base_glue-cola_lora-16.yaml +4 -0
  604. fusion_bench_config/model/flan-t5/flan-t5-base_glue-mnli.yaml +3 -0
  605. fusion_bench_config/model/flan-t5/flan-t5-base_glue-mnli_lora-16.yaml +4 -0
  606. fusion_bench_config/model/flan-t5/flan-t5-base_glue-mrpc.yaml +3 -0
  607. fusion_bench_config/model/flan-t5/flan-t5-base_glue-mrpc_lora-16.yaml +4 -0
  608. fusion_bench_config/model/flan-t5/flan-t5-base_glue-qnli.yaml +3 -0
  609. fusion_bench_config/model/flan-t5/flan-t5-base_glue-qnli_lora-16.yaml +4 -0
  610. fusion_bench_config/model/flan-t5/flan-t5-base_glue-qqp.yaml +3 -0
  611. fusion_bench_config/model/flan-t5/flan-t5-base_glue-qqp_lora-16.yaml +4 -0
  612. fusion_bench_config/model/flan-t5/flan-t5-base_glue-rte.yaml +3 -0
  613. fusion_bench_config/model/flan-t5/flan-t5-base_glue-rte_lora-16.yaml +4 -0
  614. fusion_bench_config/model/flan-t5/flan-t5-base_glue-sst2.yaml +3 -0
  615. fusion_bench_config/model/flan-t5/flan-t5-base_glue-sst2_lora-16.yaml +4 -0
  616. fusion_bench_config/model/flan-t5/flan-t5-base_glue-stsb.yaml +3 -0
  617. fusion_bench_config/model/flan-t5/flan-t5-base_glue-stsb_lora-16.yaml +4 -0
  618. fusion_bench_config/model/flan-t5/flan-t5-large.yaml +3 -0
  619. fusion_bench_config/model/flan-t5/flan-t5-large_glue-cola_lora-16.yaml +4 -0
  620. fusion_bench_config/model/flan-t5/flan-t5-large_glue-mnli_lora-16.yaml +4 -0
  621. fusion_bench_config/model/flan-t5/flan-t5-large_glue-mrpc_lora-16.yaml +4 -0
  622. fusion_bench_config/model/flan-t5/flan-t5-large_glue-qnli_lora-16.yaml +4 -0
  623. fusion_bench_config/model/flan-t5/flan-t5-large_glue-qqp_lora-16.yaml +4 -0
  624. fusion_bench_config/model/flan-t5/flan-t5-large_glue-rte_lora-16.yaml +4 -0
  625. fusion_bench_config/model/flan-t5/flan-t5-large_glue-sst2_lora-16.yaml +4 -0
  626. fusion_bench_config/model/flan-t5/flan-t5-large_glue-stsb_lora-16.yaml +4 -0
  627. fusion_bench_config/model/flan-t5/generate_flan-t5.sh +38 -0
  628. fusion_bench_config/modelpool/CLIPVisionModelPool/_template.yaml +12 -0
  629. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch16_TA8.yaml +8 -0
  630. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch16_TA8_lora.yaml +53 -0
  631. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch16_TA8_model_only.yaml +6 -0
  632. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch16_TALL14.yaml +11 -0
  633. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch16_TALL14_model_only.yaml +9 -0
  634. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch16_TALL20.yaml +11 -0
  635. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch16_TALL20_model_only.yaml +9 -0
  636. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch16_individual.yaml +19 -0
  637. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch16_individual_lora.yaml +14 -0
  638. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_TA8.yaml +5 -0
  639. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_TA8_control_task.yaml +24 -0
  640. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_TA8_model_only.yaml +3 -0
  641. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_TALL14.yaml +8 -0
  642. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_TALL14_model_only.yaml +6 -0
  643. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_TALL20.yaml +8 -0
  644. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_TALL20_model_only.yaml +6 -0
  645. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_generalization_exp1.yaml +24 -0
  646. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_generalization_exp2.yaml +24 -0
  647. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_individual.yaml +13 -0
  648. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_mtl.yaml +5 -0
  649. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_robustness_clean.yaml +18 -0
  650. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_robustness_corrupted.yaml +29 -0
  651. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_single_finetuned.yaml +5 -0
  652. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_single_task_projection.yaml +15 -0
  653. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_svhn_and_mnist.yaml +6 -0
  654. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-base-patch32_two_tasks_control_task.yaml +18 -0
  655. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-large-patch14_TA8.yaml +8 -0
  656. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-large-patch14_TA8_model_only.yaml +6 -0
  657. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-large-patch14_TALL14.yaml +11 -0
  658. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-large-patch14_TALL14_model_only.yaml +9 -0
  659. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-large-patch14_TALL20.yaml +11 -0
  660. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-large-patch14_TALL20_model_only.yaml +9 -0
  661. fusion_bench_config/modelpool/CLIPVisionModelPool/clip-vit-large-patch14_individual.yaml +19 -0
  662. fusion_bench_config/modelpool/CausalLMPool/llama_alpaca_cleaned.yaml +21 -0
  663. fusion_bench_config/modelpool/CausalLMPool/llama_codealpaca.yaml +21 -0
  664. fusion_bench_config/modelpool/CausalLMPool/llama_for_causallm.yaml +20 -0
  665. fusion_bench_config/modelpool/CausalLMPool/llama_metamathqa.yaml +19 -0
  666. fusion_bench_config/modelpool/CausalLMPool/llama_ultrachat.yaml +18 -0
  667. fusion_bench_config/modelpool/CausalLMPool/simle_mixtral_exp_v4.yaml +21 -0
  668. fusion_bench_config/modelpool/CausalLMPool/single_llama_model.yaml +17 -0
  669. fusion_bench_config/modelpool/Seq2SeqLMPool/_template.yaml +8 -0
  670. fusion_bench_config/modelpool/Seq2SeqLMPool/flan-t5-base_glue.yaml +13 -0
  671. fusion_bench_config/modelpool/Seq2SeqLMPool/flan-t5-base_glue_lora16.yaml +41 -0
  672. fusion_bench_config/modelpool/Seq2SeqLMPool/flan-t5-base_glue_lora16_tta.yaml +68 -0
  673. fusion_bench_config/modelpool/Seq2SeqLMPool/flan-t5-base_individual.yaml +7 -0
  674. fusion_bench_config/modelpool/Seq2SeqLMPool/flan-t5-large_glue_lora16.yaml +45 -0
  675. fusion_bench_config/modelpool/SeqenceClassificationModelPool/llama_preference700k.yaml +23 -0
  676. fusion_bench_config/modelpool/SeqenceClassificationModelPool/single_reward_model.yaml +14 -0
  677. fusion_bench_config/modelpool/automodelpool.yaml +12 -0
  678. fusion_bench_config/modelpool/gpt-2_glue.yaml +64 -0
  679. fusion_bench_config/modelpool/mixtral_moe_merging.yaml +14 -0
  680. fusion_bench_config/modelpool/mixtral_moe_upscaling.yaml +6 -0
  681. fusion_bench_config/modelpool/nyuv2_modelpool.yaml +26 -0
  682. fusion_bench_config/modelpool/smile_mistral_exp_v1.yaml +9 -0
  683. fusion_bench_config/modelpool/smile_mistral_exp_v2.yaml +9 -0
  684. fusion_bench_config/modelpool/smile_mistral_exp_v3.yaml +9 -0
  685. fusion_bench_config/modelpool/smile_mistral_exp_v4.yaml +13 -0
  686. fusion_bench_config/nyuv2_config.yaml +17 -0
  687. fusion_bench_config/nyuv2_mtl_train.yaml +32 -0
  688. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/_template.yaml +31 -0
  689. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-base-patch32_robustness_corrupted.yaml +27 -0
  690. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-classification_TA8.yaml +11 -0
  691. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-classification_TA8_B16.yaml +31 -0
  692. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-classification_TA8_L14.yaml +12 -0
  693. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-classification_TA8_val.yaml +12 -0
  694. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-classification_TA8_with_control_task.yaml +12 -0
  695. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-classification_TALL14.yaml +19 -0
  696. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-classification_TALL20.yaml +26 -0
  697. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_cifar10.yaml +3 -0
  698. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_cifar100.yaml +3 -0
  699. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_dtd.yaml +3 -0
  700. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_emnist_letters.yaml +3 -0
  701. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_eurosat.yaml +3 -0
  702. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_fashion_mnist.yaml +3 -0
  703. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_fer2013.yaml +3 -0
  704. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_food101.yaml +3 -0
  705. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_gtsrb.yaml +3 -0
  706. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_kmnist.yaml +3 -0
  707. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_mnist.yaml +3 -0
  708. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_oxford-iiit-pet.yaml +3 -0
  709. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_oxford_flowers102.yaml +3 -0
  710. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_oxford_flowers102_val.yaml +3 -0
  711. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_pcam.yaml +3 -0
  712. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_rendered-sst2.yaml +3 -0
  713. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_resisc45.yaml +3 -0
  714. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_stanford-cars.yaml +3 -0
  715. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_stl10.yaml +3 -0
  716. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_sun397.yaml +3 -0
  717. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip-vit-single-task_svhn.yaml +3 -0
  718. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip_rankone_wemoe_clip-vit-classification_TA8.yaml +18 -0
  719. fusion_bench_config/taskpool/CLIPVisionModelTaskPool/clip_sparse_wemoe_clip-vit-classification_TA8.yaml +18 -0
  720. fusion_bench_config/taskpool/clip-vit-base-patch32_robustness_clean.yaml +24 -0
  721. fusion_bench_config/taskpool/clip-vit-base-patch32_robustness_corrupted.yaml +27 -0
  722. fusion_bench_config/taskpool/clip-vit-base-patch32_svhn_and_mnist.yaml +22 -0
  723. fusion_bench_config/taskpool/dummy.yaml +2 -0
  724. fusion_bench_config/taskpool/flan-t5_glue_text_generation.yaml +44 -0
  725. fusion_bench_config/taskpool/gpt-2_glue.yaml +39 -0
  726. fusion_bench_config/taskpool/nyuv2_taskpool.yaml +9 -0
  727. fusion_bench_config/taskpool/reward_model_evaluation.yaml +18 -0
@@ -0,0 +1,1825 @@
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
+ import math
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
30
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
31
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutputWithPast,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_greater_or_equal_2_10,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+
50
+ from .configuration_losparse_llama import LoSparseLlamaConfig
51
+ from .losparse_linear import LoSparseLinear
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CONFIG_FOR_DOC = "LlamaConfig"
56
+
57
+
58
+ def _prepare_4d_causal_attention_mask_with_cache_position(
59
+ attention_mask: torch.Tensor,
60
+ sequence_length: int,
61
+ target_length: int,
62
+ dtype: torch.dtype,
63
+ device: torch.device,
64
+ min_dtype: float,
65
+ cache_position: torch.Tensor,
66
+ batch_size: int,
67
+ ):
68
+ """
69
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
70
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
71
+
72
+ Args:
73
+ attention_mask (`torch.Tensor`):
74
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
75
+ sequence_length (`int`):
76
+ The sequence length being processed.
77
+ target_length (`int`):
78
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
79
+ dtype (`torch.dtype`):
80
+ The dtype to use for the 4D attention mask.
81
+ device (`torch.device`):
82
+ The device to plcae the 4D attention mask on.
83
+ min_dtype (`float`):
84
+ The minimum value representable with the dtype `dtype`.
85
+ cache_position (`torch.Tensor`):
86
+ Indices depicting the position of the input sequence tokens in the sequence.
87
+ batch_size (`torch.Tensor`):
88
+ Batch size.
89
+ """
90
+ if attention_mask is not None and attention_mask.dim() == 4:
91
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
92
+ causal_mask = attention_mask
93
+ else:
94
+ causal_mask = torch.full(
95
+ (sequence_length, target_length),
96
+ fill_value=min_dtype,
97
+ dtype=dtype,
98
+ device=device,
99
+ )
100
+ if sequence_length != 1:
101
+ causal_mask = torch.triu(causal_mask, diagonal=1)
102
+ causal_mask *= torch.arange(
103
+ target_length, device=device
104
+ ) > cache_position.reshape(-1, 1)
105
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
106
+ if attention_mask is not None:
107
+ causal_mask = (
108
+ causal_mask.clone()
109
+ ) # copy to contiguous memory for in-place edit
110
+ mask_length = attention_mask.shape[-1]
111
+ padding_mask = (
112
+ causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
113
+ )
114
+ padding_mask = padding_mask == 0
115
+ causal_mask[:, :, :, :mask_length] = causal_mask[
116
+ :, :, :, :mask_length
117
+ ].masked_fill(padding_mask, min_dtype)
118
+
119
+ return causal_mask
120
+
121
+
122
+ class LlamaRMSNorm(nn.Module):
123
+ def __init__(self, hidden_size, eps=1e-6):
124
+ """
125
+ LlamaRMSNorm is equivalent to T5LayerNorm
126
+ """
127
+ super().__init__()
128
+ self.weight = nn.Parameter(torch.ones(hidden_size))
129
+ self.variance_epsilon = eps
130
+
131
+ def forward(self, hidden_states):
132
+ input_dtype = hidden_states.dtype
133
+ hidden_states = hidden_states.to(torch.float32)
134
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
135
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
136
+ return self.weight * hidden_states.to(input_dtype)
137
+
138
+ def extra_repr(self):
139
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
140
+
141
+
142
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
143
+
144
+
145
+ class LlamaRotaryEmbedding(nn.Module):
146
+ def __init__(
147
+ self,
148
+ dim=None,
149
+ max_position_embeddings=2048,
150
+ base=10000,
151
+ device=None,
152
+ scaling_factor=1.0,
153
+ rope_type="default",
154
+ config: Optional[LoSparseLlamaConfig] = None,
155
+ ):
156
+ super().__init__()
157
+ # TODO (joao): remove the `if` below, only used for BC
158
+ self.rope_kwargs = {}
159
+ if config is None:
160
+ logger.warning_once(
161
+ "`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
162
+ "`config` argument. All other arguments will be removed in v4.45"
163
+ )
164
+ self.rope_kwargs = {
165
+ "rope_type": rope_type,
166
+ "factor": scaling_factor,
167
+ "dim": dim,
168
+ "base": base,
169
+ "max_position_embeddings": max_position_embeddings,
170
+ }
171
+ self.rope_type = rope_type
172
+ self.max_seq_len_cached = max_position_embeddings
173
+ self.original_max_seq_len = max_position_embeddings
174
+ else:
175
+ # BC: "rope_type" was originally "type"
176
+ if config.rope_scaling is not None:
177
+ self.rope_type = config.rope_scaling.get(
178
+ "rope_type", config.rope_scaling.get("type")
179
+ )
180
+ else:
181
+ self.rope_type = "default"
182
+ self.max_seq_len_cached = config.max_position_embeddings
183
+ self.original_max_seq_len = config.max_position_embeddings
184
+
185
+ self.config = config
186
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
187
+
188
+ inv_freq, self.attention_scaling = self.rope_init_fn(
189
+ self.config, device, **self.rope_kwargs
190
+ )
191
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
192
+ self.original_inv_freq = self.inv_freq
193
+
194
+ def _dynamic_frequency_update(self, position_ids, device):
195
+ """
196
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
197
+ 1 - growing beyond the cached sequence length (allow scaling)
198
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
199
+ """
200
+ seq_len = torch.max(position_ids) + 1
201
+ if seq_len > self.max_seq_len_cached: # growth
202
+ inv_freq, self.attention_scaling = self.rope_init_fn(
203
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
204
+ )
205
+ self.register_buffer(
206
+ "inv_freq", inv_freq, persistent=False
207
+ ) # TODO joao: may break with compilation
208
+ self.max_seq_len_cached = seq_len
209
+
210
+ if (
211
+ seq_len < self.original_max_seq_len
212
+ and self.max_seq_len_cached > self.original_max_seq_len
213
+ ): # reset
214
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
215
+ self.max_seq_len_cached = self.original_max_seq_len
216
+
217
+ @torch.no_grad()
218
+ def forward(self, x, position_ids):
219
+ if "dynamic" in self.rope_type:
220
+ self._dynamic_frequency_update(position_ids, device=x.device)
221
+
222
+ # Core RoPE block
223
+ inv_freq_expanded = (
224
+ self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
225
+ )
226
+ position_ids_expanded = position_ids[:, None, :].float()
227
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
228
+ device_type = x.device.type
229
+ device_type = (
230
+ device_type
231
+ if isinstance(device_type, str) and device_type != "mps"
232
+ else "cpu"
233
+ )
234
+ with torch.autocast(device_type=device_type, enabled=False):
235
+ freqs = (
236
+ inv_freq_expanded.float() @ position_ids_expanded.float()
237
+ ).transpose(1, 2)
238
+ emb = torch.cat((freqs, freqs), dim=-1)
239
+ cos = emb.cos()
240
+ sin = emb.sin()
241
+
242
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
243
+ cos = cos * self.attention_scaling
244
+ sin = sin * self.attention_scaling
245
+
246
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
247
+
248
+
249
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
250
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
251
+
252
+ def __init__(self, *args, **kwargs):
253
+ logger.warning_once(
254
+ "`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
255
+ "`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
256
+ )
257
+ kwargs["rope_type"] = "linear"
258
+ super().__init__(*args, **kwargs)
259
+
260
+
261
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
262
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
263
+
264
+ def __init__(self, *args, **kwargs):
265
+ logger.warning_once(
266
+ "`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
267
+ "`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
268
+ "__init__)."
269
+ )
270
+ kwargs["rope_type"] = "dynamic"
271
+ super().__init__(*args, **kwargs)
272
+
273
+
274
+ def rotate_half(x):
275
+ """Rotates half the hidden dims of the input."""
276
+ x1 = x[..., : x.shape[-1] // 2]
277
+ x2 = x[..., x.shape[-1] // 2 :]
278
+ return torch.cat((-x2, x1), dim=-1)
279
+
280
+
281
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
282
+ """Applies Rotary Position Embedding to the query and key tensors.
283
+
284
+ Args:
285
+ q (`torch.Tensor`): The query tensor.
286
+ k (`torch.Tensor`): The key tensor.
287
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
288
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
289
+ position_ids (`torch.Tensor`, *optional*):
290
+ Deprecated and unused.
291
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
292
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
293
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
294
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
295
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
296
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
297
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
298
+ Returns:
299
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
300
+ """
301
+ cos = cos.unsqueeze(unsqueeze_dim)
302
+ sin = sin.unsqueeze(unsqueeze_dim)
303
+ q_embed = (q * cos) + (rotate_half(q) * sin)
304
+ k_embed = (k * cos) + (rotate_half(k) * sin)
305
+ return q_embed, k_embed
306
+
307
+
308
+ class LoSparseLlamaMLP(nn.Module):
309
+ def __init__(self, config):
310
+ super().__init__()
311
+ self.config = config
312
+ self.hidden_size = config.hidden_size
313
+ self.intermediate_size = config.intermediate_size
314
+ self.gate_proj = LoSparseLinear(
315
+ self.hidden_size,
316
+ self.intermediate_size,
317
+ rank=config.rank,
318
+ bias=config.mlp_bias,
319
+ )
320
+ self.up_proj = LoSparseLinear(
321
+ self.hidden_size,
322
+ self.intermediate_size,
323
+ rank=config.rank,
324
+ bias=config.mlp_bias,
325
+ )
326
+ self.down_proj = LoSparseLinear(
327
+ self.intermediate_size,
328
+ self.hidden_size,
329
+ rank=config.rank,
330
+ bias=config.mlp_bias,
331
+ )
332
+ self.act_fn = ACT2FN[config.hidden_act]
333
+
334
+ def forward(self, x):
335
+ if self.config.pretraining_tp > 1:
336
+ slice = self.intermediate_size // self.config.pretraining_tp
337
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
338
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
339
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
340
+
341
+ gate_proj = torch.cat(
342
+ [
343
+ F.linear(x, gate_proj_slices[i])
344
+ for i in range(self.config.pretraining_tp)
345
+ ],
346
+ dim=-1,
347
+ )
348
+ up_proj = torch.cat(
349
+ [
350
+ F.linear(x, up_proj_slices[i])
351
+ for i in range(self.config.pretraining_tp)
352
+ ],
353
+ dim=-1,
354
+ )
355
+
356
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
357
+ down_proj = [
358
+ F.linear(intermediate_states[i], down_proj_slices[i])
359
+ for i in range(self.config.pretraining_tp)
360
+ ]
361
+ down_proj = sum(down_proj)
362
+ else:
363
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
364
+
365
+ return down_proj
366
+
367
+
368
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
369
+ """
370
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
371
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
372
+ """
373
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
374
+ if n_rep == 1:
375
+ return hidden_states
376
+ hidden_states = hidden_states[:, :, None, :, :].expand(
377
+ batch, num_key_value_heads, n_rep, slen, head_dim
378
+ )
379
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
380
+
381
+
382
+ class LoSparseLlamaAttention(nn.Module):
383
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
384
+
385
+ def __init__(self, config: LoSparseLlamaConfig, layer_idx: Optional[int] = None):
386
+ super().__init__()
387
+ self.config = config
388
+ self.layer_idx = layer_idx
389
+ if layer_idx is None:
390
+ logger.warning_once(
391
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
392
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
393
+ "when creating this class."
394
+ )
395
+
396
+ self.attention_dropout = config.attention_dropout
397
+ self.hidden_size = config.hidden_size
398
+ self.num_heads = config.num_attention_heads
399
+ self.head_dim = self.hidden_size // self.num_heads
400
+ self.num_key_value_heads = config.num_key_value_heads
401
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
402
+ self.max_position_embeddings = config.max_position_embeddings
403
+ self.rope_theta = config.rope_theta
404
+ self.is_causal = True
405
+
406
+ if (self.head_dim * self.num_heads) != self.hidden_size:
407
+ raise ValueError(
408
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
409
+ f" and `num_heads`: {self.num_heads})."
410
+ )
411
+
412
+ self.q_proj = LoSparseLinear(
413
+ self.hidden_size,
414
+ self.num_heads * self.head_dim,
415
+ rank=config.rank,
416
+ bias=config.attention_bias,
417
+ )
418
+ self.k_proj = LoSparseLinear(
419
+ self.hidden_size,
420
+ self.num_key_value_heads * self.head_dim,
421
+ rank=config.rank,
422
+ bias=config.attention_bias,
423
+ )
424
+ self.v_proj = LoSparseLinear(
425
+ self.hidden_size,
426
+ self.num_key_value_heads * self.head_dim,
427
+ rank=config.rank,
428
+ bias=config.attention_bias,
429
+ )
430
+ self.o_proj = LoSparseLinear(
431
+ self.hidden_size,
432
+ self.hidden_size,
433
+ rank=config.rank,
434
+ bias=config.attention_bias,
435
+ )
436
+
437
+ # TODO (joao): remove in v4.45 (RoPE is computed in the model, not in the decoder layers)
438
+ self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
439
+
440
+ def forward(
441
+ self,
442
+ hidden_states: torch.Tensor,
443
+ attention_mask: Optional[torch.Tensor] = None,
444
+ position_ids: Optional[torch.LongTensor] = None,
445
+ past_key_value: Optional[Cache] = None,
446
+ output_attentions: bool = False,
447
+ use_cache: bool = False,
448
+ cache_position: Optional[torch.LongTensor] = None,
449
+ position_embeddings: Optional[
450
+ Tuple[torch.Tensor, torch.Tensor]
451
+ ] = None, # will become mandatory in v4.45
452
+ **kwargs,
453
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
454
+ bsz, q_len, _ = hidden_states.size()
455
+
456
+ if self.config.pretraining_tp > 1:
457
+ key_value_slicing = (
458
+ self.num_key_value_heads * self.head_dim
459
+ ) // self.config.pretraining_tp
460
+ query_slices = self.q_proj.weight.split(
461
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
462
+ )
463
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
464
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
465
+
466
+ query_states = [
467
+ F.linear(hidden_states, query_slices[i])
468
+ for i in range(self.config.pretraining_tp)
469
+ ]
470
+ query_states = torch.cat(query_states, dim=-1)
471
+
472
+ key_states = [
473
+ F.linear(hidden_states, key_slices[i])
474
+ for i in range(self.config.pretraining_tp)
475
+ ]
476
+ key_states = torch.cat(key_states, dim=-1)
477
+
478
+ value_states = [
479
+ F.linear(hidden_states, value_slices[i])
480
+ for i in range(self.config.pretraining_tp)
481
+ ]
482
+ value_states = torch.cat(value_states, dim=-1)
483
+
484
+ else:
485
+ query_states = self.q_proj(hidden_states)
486
+ key_states = self.k_proj(hidden_states)
487
+ value_states = self.v_proj(hidden_states)
488
+
489
+ query_states = query_states.view(
490
+ bsz, q_len, self.num_heads, self.head_dim
491
+ ).transpose(1, 2)
492
+ key_states = key_states.view(
493
+ bsz, q_len, self.num_key_value_heads, self.head_dim
494
+ ).transpose(1, 2)
495
+ value_states = value_states.view(
496
+ bsz, q_len, self.num_key_value_heads, self.head_dim
497
+ ).transpose(1, 2)
498
+
499
+ if position_embeddings is None:
500
+ logger.warning_once(
501
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
502
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
503
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
504
+ "removed and `position_embeddings` will be mandatory."
505
+ )
506
+ cos, sin = self.rotary_emb(value_states, position_ids)
507
+ else:
508
+ cos, sin = position_embeddings
509
+ query_states, key_states = apply_rotary_pos_emb(
510
+ query_states, key_states, cos, sin
511
+ )
512
+
513
+ if past_key_value is not None:
514
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
515
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
516
+ key_states, value_states = past_key_value.update(
517
+ key_states, value_states, self.layer_idx, cache_kwargs
518
+ )
519
+
520
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
521
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
522
+
523
+ attn_weights = torch.matmul(
524
+ query_states, key_states.transpose(2, 3)
525
+ ) / math.sqrt(self.head_dim)
526
+
527
+ if attention_mask is not None: # no matter the length, we just slice it
528
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
529
+ attn_weights = attn_weights + causal_mask
530
+
531
+ # upcast attention to fp32
532
+ attn_weights = nn.functional.softmax(
533
+ attn_weights, dim=-1, dtype=torch.float32
534
+ ).to(query_states.dtype)
535
+ attn_weights = nn.functional.dropout(
536
+ attn_weights, p=self.attention_dropout, training=self.training
537
+ )
538
+ attn_output = torch.matmul(attn_weights, value_states)
539
+
540
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
541
+ raise ValueError(
542
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
543
+ f" {attn_output.size()}"
544
+ )
545
+
546
+ attn_output = attn_output.transpose(1, 2).contiguous()
547
+
548
+ attn_output = attn_output.reshape(bsz, q_len, -1)
549
+
550
+ if self.config.pretraining_tp > 1:
551
+ attn_output = attn_output.split(
552
+ self.hidden_size // self.config.pretraining_tp, dim=2
553
+ )
554
+ o_proj_slices = self.o_proj.weight.split(
555
+ self.hidden_size // self.config.pretraining_tp, dim=1
556
+ )
557
+ attn_output = sum(
558
+ [
559
+ F.linear(attn_output[i], o_proj_slices[i])
560
+ for i in range(self.config.pretraining_tp)
561
+ ]
562
+ )
563
+ else:
564
+ attn_output = self.o_proj(attn_output)
565
+
566
+ if not output_attentions:
567
+ attn_weights = None
568
+
569
+ return attn_output, attn_weights, past_key_value
570
+
571
+
572
+ class LlamaFlashAttention2(LoSparseLlamaAttention):
573
+ """
574
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
575
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
576
+ flash attention and deal with padding tokens in case the input contains any of them.
577
+ """
578
+
579
+ def __init__(self, *args, **kwargs):
580
+ super().__init__(*args, **kwargs)
581
+
582
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
583
+ # 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.
584
+ # 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).
585
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
586
+
587
+ def forward(
588
+ self,
589
+ hidden_states: torch.Tensor,
590
+ attention_mask: Optional[torch.LongTensor] = None,
591
+ position_ids: Optional[torch.LongTensor] = None,
592
+ past_key_value: Optional[Cache] = None,
593
+ output_attentions: bool = False,
594
+ use_cache: bool = False,
595
+ cache_position: Optional[torch.LongTensor] = None,
596
+ position_embeddings: Optional[
597
+ Tuple[torch.Tensor, torch.Tensor]
598
+ ] = None, # will become mandatory in v4.45
599
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
600
+ if isinstance(past_key_value, StaticCache):
601
+ raise ValueError(
602
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
603
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
604
+ )
605
+
606
+ output_attentions = False
607
+
608
+ bsz, q_len, _ = hidden_states.size()
609
+
610
+ query_states = self.q_proj(hidden_states)
611
+ key_states = self.k_proj(hidden_states)
612
+ value_states = self.v_proj(hidden_states)
613
+
614
+ # Flash attention requires the input to have the shape
615
+ # batch_size x seq_length x head_dim x hidden_dim
616
+ # therefore we just need to keep the original shape
617
+ query_states = query_states.view(
618
+ bsz, q_len, self.num_heads, self.head_dim
619
+ ).transpose(1, 2)
620
+ key_states = key_states.view(
621
+ bsz, q_len, self.num_key_value_heads, self.head_dim
622
+ ).transpose(1, 2)
623
+ value_states = value_states.view(
624
+ bsz, q_len, self.num_key_value_heads, self.head_dim
625
+ ).transpose(1, 2)
626
+
627
+ if position_embeddings is None:
628
+ logger.warning_once(
629
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
630
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
631
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
632
+ "removed and `position_embeddings` will be mandatory."
633
+ )
634
+ cos, sin = self.rotary_emb(value_states, position_ids)
635
+ else:
636
+ cos, sin = position_embeddings
637
+ query_states, key_states = apply_rotary_pos_emb(
638
+ query_states, key_states, cos, sin
639
+ )
640
+
641
+ if past_key_value is not None:
642
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
643
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
644
+ key_states, value_states = past_key_value.update(
645
+ key_states, value_states, self.layer_idx, cache_kwargs
646
+ )
647
+
648
+ # 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
649
+ # to be able to avoid many of these transpose/reshape/view.
650
+ query_states = query_states.transpose(1, 2)
651
+ key_states = key_states.transpose(1, 2)
652
+ value_states = value_states.transpose(1, 2)
653
+
654
+ dropout_rate = self.attention_dropout if self.training else 0.0
655
+
656
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
657
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
658
+ # cast them back in the correct dtype just to be sure everything works as expected.
659
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
660
+ # in fp32. (LlamaRMSNorm handles it correctly)
661
+
662
+ input_dtype = query_states.dtype
663
+ if input_dtype == torch.float32:
664
+ if torch.is_autocast_enabled():
665
+ target_dtype = torch.get_autocast_gpu_dtype()
666
+ # Handle the case where the model is quantized
667
+ elif hasattr(self.config, "_pre_quantization_dtype"):
668
+ target_dtype = self.config._pre_quantization_dtype
669
+ else:
670
+ target_dtype = self.q_proj.weight.dtype
671
+
672
+ logger.warning_once(
673
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
674
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
675
+ f" {target_dtype}."
676
+ )
677
+
678
+ query_states = query_states.to(target_dtype)
679
+ key_states = key_states.to(target_dtype)
680
+ value_states = value_states.to(target_dtype)
681
+
682
+ attn_output = _flash_attention_forward(
683
+ query_states,
684
+ key_states,
685
+ value_states,
686
+ attention_mask,
687
+ q_len,
688
+ position_ids=position_ids,
689
+ dropout=dropout_rate,
690
+ sliding_window=getattr(self, "sliding_window", None),
691
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
692
+ is_causal=self.is_causal,
693
+ )
694
+
695
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
696
+ attn_output = self.o_proj(attn_output)
697
+
698
+ if not output_attentions:
699
+ attn_weights = None
700
+
701
+ return attn_output, attn_weights, past_key_value
702
+
703
+
704
+ class LlamaSdpaAttention(LoSparseLlamaAttention):
705
+ """
706
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
707
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
708
+ SDPA API.
709
+ """
710
+
711
+ # Adapted from LlamaAttention.forward
712
+ def forward(
713
+ self,
714
+ hidden_states: torch.Tensor,
715
+ attention_mask: Optional[torch.Tensor] = None,
716
+ position_ids: Optional[torch.LongTensor] = None,
717
+ past_key_value: Optional[Cache] = None,
718
+ output_attentions: bool = False,
719
+ use_cache: bool = False,
720
+ cache_position: Optional[torch.LongTensor] = None,
721
+ position_embeddings: Optional[
722
+ Tuple[torch.Tensor, torch.Tensor]
723
+ ] = None, # will become mandatory in v4.45
724
+ **kwargs,
725
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
726
+ if output_attentions:
727
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
728
+ logger.warning_once(
729
+ "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, "
730
+ '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.'
731
+ )
732
+ return super().forward(
733
+ hidden_states=hidden_states,
734
+ attention_mask=attention_mask,
735
+ position_ids=position_ids,
736
+ past_key_value=past_key_value,
737
+ output_attentions=output_attentions,
738
+ use_cache=use_cache,
739
+ cache_position=cache_position,
740
+ position_embeddings=position_embeddings,
741
+ )
742
+
743
+ bsz, q_len, _ = hidden_states.size()
744
+
745
+ query_states = self.q_proj(hidden_states)
746
+ key_states = self.k_proj(hidden_states)
747
+ value_states = self.v_proj(hidden_states)
748
+
749
+ query_states = query_states.view(
750
+ bsz, q_len, self.num_heads, self.head_dim
751
+ ).transpose(1, 2)
752
+ key_states = key_states.view(
753
+ bsz, q_len, self.num_key_value_heads, self.head_dim
754
+ ).transpose(1, 2)
755
+ value_states = value_states.view(
756
+ bsz, q_len, self.num_key_value_heads, self.head_dim
757
+ ).transpose(1, 2)
758
+
759
+ if position_embeddings is None:
760
+ logger.warning_once(
761
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
762
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
763
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
764
+ "removed and `position_embeddings` will be mandatory."
765
+ )
766
+ cos, sin = self.rotary_emb(value_states, position_ids)
767
+ else:
768
+ cos, sin = position_embeddings
769
+ query_states, key_states = apply_rotary_pos_emb(
770
+ query_states, key_states, cos, sin
771
+ )
772
+
773
+ if past_key_value is not None:
774
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
775
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
776
+ key_states, value_states = past_key_value.update(
777
+ key_states, value_states, self.layer_idx, cache_kwargs
778
+ )
779
+
780
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
781
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
782
+
783
+ causal_mask = attention_mask
784
+ if attention_mask is not None:
785
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
786
+
787
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
788
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
789
+ if query_states.device.type == "cuda" and causal_mask is not None:
790
+ query_states = query_states.contiguous()
791
+ key_states = key_states.contiguous()
792
+ value_states = value_states.contiguous()
793
+
794
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
795
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
796
+ is_causal = True if causal_mask is None and q_len > 1 else False
797
+
798
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
799
+ query_states,
800
+ key_states,
801
+ value_states,
802
+ attn_mask=causal_mask,
803
+ dropout_p=self.attention_dropout if self.training else 0.0,
804
+ is_causal=is_causal,
805
+ )
806
+
807
+ attn_output = attn_output.transpose(1, 2).contiguous()
808
+ attn_output = attn_output.view(bsz, q_len, -1)
809
+
810
+ attn_output = self.o_proj(attn_output)
811
+
812
+ return attn_output, None, past_key_value
813
+
814
+
815
+ LOSPARSE_LLAMA_ATTENTION_CLASSES = {
816
+ "eager": LoSparseLlamaAttention,
817
+ "flash_attention_2": LlamaFlashAttention2,
818
+ "sdpa": LlamaSdpaAttention,
819
+ }
820
+
821
+
822
+ class LoSparseLlamaDecoderLayer(nn.Module):
823
+ def __init__(self, config: LoSparseLlamaConfig, layer_idx: int):
824
+ super().__init__()
825
+ self.hidden_size = config.hidden_size
826
+
827
+ self.self_attn = LOSPARSE_LLAMA_ATTENTION_CLASSES[config._attn_implementation](
828
+ config=config, layer_idx=layer_idx
829
+ )
830
+
831
+ self.mlp = LoSparseLlamaMLP(config)
832
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
833
+ self.post_attention_layernorm = LlamaRMSNorm(
834
+ config.hidden_size, eps=config.rms_norm_eps
835
+ )
836
+
837
+ def forward(
838
+ self,
839
+ hidden_states: torch.Tensor,
840
+ attention_mask: Optional[torch.Tensor] = None,
841
+ position_ids: Optional[torch.LongTensor] = None,
842
+ past_key_value: Optional[Cache] = None,
843
+ output_attentions: Optional[bool] = False,
844
+ use_cache: Optional[bool] = False,
845
+ cache_position: Optional[torch.LongTensor] = None,
846
+ position_embeddings: Optional[
847
+ Tuple[torch.Tensor, torch.Tensor]
848
+ ] = None, # will become mandatory in v4.45
849
+ **kwargs,
850
+ ) -> Tuple[
851
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
852
+ ]:
853
+ """
854
+ Args:
855
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
856
+ attention_mask (`torch.FloatTensor`, *optional*):
857
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
858
+ query_sequence_length, key_sequence_length)` if default attention is used.
859
+ output_attentions (`bool`, *optional*):
860
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
861
+ returned tensors for more detail.
862
+ use_cache (`bool`, *optional*):
863
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
864
+ (see `past_key_values`).
865
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
866
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
867
+ Indices depicting the position of the input sequence tokens in the sequence
868
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
869
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
870
+ with `head_dim` being the embedding dimension of each attention head.
871
+ kwargs (`dict`, *optional*):
872
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
873
+ into the model
874
+ """
875
+ residual = hidden_states
876
+
877
+ hidden_states = self.input_layernorm(hidden_states)
878
+
879
+ # Self Attention
880
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
881
+ hidden_states=hidden_states,
882
+ attention_mask=attention_mask,
883
+ position_ids=position_ids,
884
+ past_key_value=past_key_value,
885
+ output_attentions=output_attentions,
886
+ use_cache=use_cache,
887
+ cache_position=cache_position,
888
+ position_embeddings=position_embeddings,
889
+ **kwargs,
890
+ )
891
+ hidden_states = residual + hidden_states
892
+
893
+ # Fully Connected
894
+ residual = hidden_states
895
+ hidden_states = self.post_attention_layernorm(hidden_states)
896
+ hidden_states = self.mlp(hidden_states)
897
+ hidden_states = residual + hidden_states
898
+
899
+ outputs = (hidden_states,)
900
+
901
+ if output_attentions:
902
+ outputs += (self_attn_weights,)
903
+
904
+ if use_cache:
905
+ outputs += (present_key_value,)
906
+
907
+ return outputs
908
+
909
+
910
+ LOSPARSE_LLAMA_START_DOCSTRING = r"""
911
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
912
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
913
+ etc.)
914
+
915
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
916
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
917
+ and behavior.
918
+
919
+ Parameters:
920
+ config ([`LlamaConfig`]):
921
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
922
+ load the weights associated with the model, only the configuration. Check out the
923
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
924
+ """
925
+
926
+
927
+ @add_start_docstrings(
928
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
929
+ LOSPARSE_LLAMA_START_DOCSTRING,
930
+ )
931
+ class LoSparseLlamaPreTrainedModel(PreTrainedModel):
932
+ config_class = LoSparseLlamaConfig
933
+ base_model_prefix = "model"
934
+ supports_gradient_checkpointing = True
935
+ _no_split_modules = ["LoSparseLlamaDecoderLayer"]
936
+ _skip_keys_device_placement = ["past_key_values"]
937
+ _supports_flash_attn_2 = True
938
+ _supports_sdpa = True
939
+ _supports_cache_class = True
940
+ _supports_quantized_cache = True
941
+ _supports_static_cache = True
942
+
943
+ def _init_weights(self, module):
944
+ std = self.config.initializer_range
945
+ if isinstance(module, nn.Linear):
946
+ module.weight.data.normal_(mean=0.0, std=std)
947
+ if module.bias is not None:
948
+ module.bias.data.zero_()
949
+ elif isinstance(module, nn.Embedding):
950
+ module.weight.data.normal_(mean=0.0, std=std)
951
+ if module.padding_idx is not None:
952
+ module.weight.data[module.padding_idx].zero_()
953
+
954
+
955
+ LOSPARSE_LLAMA_INPUTS_DOCSTRING = r"""
956
+ Args:
957
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
958
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
959
+ it.
960
+
961
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
962
+ [`PreTrainedTokenizer.__call__`] for details.
963
+
964
+ [What are input IDs?](../glossary#input-ids)
965
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
966
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
967
+
968
+ - 1 for tokens that are **not masked**,
969
+ - 0 for tokens that are **masked**.
970
+
971
+ [What are attention masks?](../glossary#attention-mask)
972
+
973
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
974
+ [`PreTrainedTokenizer.__call__`] for details.
975
+
976
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
977
+ `past_key_values`).
978
+
979
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
980
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
981
+ information on the default strategy.
982
+
983
+ - 1 indicates the head is **not masked**,
984
+ - 0 indicates the head is **masked**.
985
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
986
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
987
+ config.n_positions - 1]`.
988
+
989
+ [What are position IDs?](../glossary#position-ids)
990
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
991
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
992
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
993
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
994
+
995
+ Two formats are allowed:
996
+ - a [`~cache_utils.Cache`] instance;
997
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
998
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
999
+ cache format.
1000
+
1001
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1002
+ legacy cache format will be returned.
1003
+
1004
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1005
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1006
+ of shape `(batch_size, sequence_length)`.
1007
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1008
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1009
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1010
+ model's internal embedding lookup matrix.
1011
+ use_cache (`bool`, *optional*):
1012
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1013
+ `past_key_values`).
1014
+ output_attentions (`bool`, *optional*):
1015
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1016
+ tensors for more detail.
1017
+ output_hidden_states (`bool`, *optional*):
1018
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1019
+ more detail.
1020
+ return_dict (`bool`, *optional*):
1021
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1022
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1023
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1024
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1025
+ the complete sequence length.
1026
+ """
1027
+
1028
+
1029
+ @add_start_docstrings(
1030
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
1031
+ LOSPARSE_LLAMA_START_DOCSTRING,
1032
+ )
1033
+ class LoSparseLlamaModel(LoSparseLlamaPreTrainedModel):
1034
+ """
1035
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
1036
+
1037
+ Args:
1038
+ config: LlamaConfig
1039
+ """
1040
+
1041
+ def __init__(self, config: LoSparseLlamaConfig):
1042
+ super().__init__(config)
1043
+ self.padding_idx = config.pad_token_id
1044
+ self.vocab_size = config.vocab_size
1045
+
1046
+ self.embed_tokens = nn.Embedding(
1047
+ config.vocab_size, config.hidden_size, self.padding_idx
1048
+ )
1049
+ self.layers = nn.ModuleList(
1050
+ [
1051
+ LoSparseLlamaDecoderLayer(config, layer_idx)
1052
+ for layer_idx in range(config.num_hidden_layers)
1053
+ ]
1054
+ )
1055
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1056
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
1057
+ self.gradient_checkpointing = False
1058
+
1059
+ # Initialize weights and apply final processing
1060
+ self.post_init()
1061
+
1062
+ def get_input_embeddings(self):
1063
+ return self.embed_tokens
1064
+
1065
+ def set_input_embeddings(self, value):
1066
+ self.embed_tokens = value
1067
+
1068
+ @add_start_docstrings_to_model_forward(LOSPARSE_LLAMA_INPUTS_DOCSTRING)
1069
+ def forward(
1070
+ self,
1071
+ input_ids: torch.LongTensor = None,
1072
+ attention_mask: Optional[torch.Tensor] = None,
1073
+ position_ids: Optional[torch.LongTensor] = None,
1074
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1075
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1076
+ use_cache: Optional[bool] = None,
1077
+ output_attentions: Optional[bool] = None,
1078
+ output_hidden_states: Optional[bool] = None,
1079
+ return_dict: Optional[bool] = None,
1080
+ cache_position: Optional[torch.LongTensor] = None,
1081
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1082
+ output_attentions = (
1083
+ output_attentions
1084
+ if output_attentions is not None
1085
+ else self.config.output_attentions
1086
+ )
1087
+ output_hidden_states = (
1088
+ output_hidden_states
1089
+ if output_hidden_states is not None
1090
+ else self.config.output_hidden_states
1091
+ )
1092
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1093
+ return_dict = (
1094
+ return_dict if return_dict is not None else self.config.use_return_dict
1095
+ )
1096
+
1097
+ if (input_ids is None) ^ (inputs_embeds is not None):
1098
+ raise ValueError(
1099
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1100
+ )
1101
+
1102
+ if self.gradient_checkpointing and self.training and use_cache:
1103
+ logger.warning_once(
1104
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1105
+ )
1106
+ use_cache = False
1107
+
1108
+ if inputs_embeds is None:
1109
+ inputs_embeds = self.embed_tokens(input_ids)
1110
+
1111
+ return_legacy_cache = False
1112
+ if (
1113
+ use_cache and not isinstance(past_key_values, Cache) and not self.training
1114
+ ): # kept for BC (non `Cache` `past_key_values` inputs)
1115
+ return_legacy_cache = True
1116
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1117
+ logger.warning_once(
1118
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
1119
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
1120
+ )
1121
+
1122
+ if cache_position is None:
1123
+ past_seen_tokens = (
1124
+ past_key_values.get_seq_length() if past_key_values is not None else 0
1125
+ )
1126
+ cache_position = torch.arange(
1127
+ past_seen_tokens,
1128
+ past_seen_tokens + inputs_embeds.shape[1],
1129
+ device=inputs_embeds.device,
1130
+ )
1131
+ if position_ids is None:
1132
+ position_ids = cache_position.unsqueeze(0)
1133
+
1134
+ causal_mask = self._update_causal_mask(
1135
+ attention_mask,
1136
+ inputs_embeds,
1137
+ cache_position,
1138
+ past_key_values,
1139
+ output_attentions,
1140
+ )
1141
+ hidden_states = inputs_embeds
1142
+
1143
+ # create position embeddings to be shared across the decoder layers
1144
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1145
+
1146
+ # decoder layers
1147
+ all_hidden_states = () if output_hidden_states else None
1148
+ all_self_attns = () if output_attentions else None
1149
+ next_decoder_cache = None
1150
+
1151
+ for decoder_layer in self.layers:
1152
+ if output_hidden_states:
1153
+ all_hidden_states += (hidden_states,)
1154
+
1155
+ if self.gradient_checkpointing and self.training:
1156
+ layer_outputs = self._gradient_checkpointing_func(
1157
+ decoder_layer.__call__,
1158
+ hidden_states,
1159
+ causal_mask,
1160
+ position_ids,
1161
+ past_key_values,
1162
+ output_attentions,
1163
+ use_cache,
1164
+ cache_position,
1165
+ position_embeddings,
1166
+ )
1167
+ else:
1168
+ layer_outputs = decoder_layer(
1169
+ hidden_states,
1170
+ attention_mask=causal_mask,
1171
+ position_ids=position_ids,
1172
+ past_key_value=past_key_values,
1173
+ output_attentions=output_attentions,
1174
+ use_cache=use_cache,
1175
+ cache_position=cache_position,
1176
+ position_embeddings=position_embeddings,
1177
+ )
1178
+
1179
+ hidden_states = layer_outputs[0]
1180
+
1181
+ if use_cache:
1182
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1183
+
1184
+ if output_attentions:
1185
+ all_self_attns += (layer_outputs[1],)
1186
+
1187
+ hidden_states = self.norm(hidden_states)
1188
+
1189
+ # add hidden states from the last decoder layer
1190
+ if output_hidden_states:
1191
+ all_hidden_states += (hidden_states,)
1192
+
1193
+ next_cache = next_decoder_cache if use_cache else None
1194
+ if return_legacy_cache:
1195
+ next_cache = next_cache.to_legacy_cache()
1196
+
1197
+ if not return_dict:
1198
+ return tuple(
1199
+ v
1200
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1201
+ if v is not None
1202
+ )
1203
+ return BaseModelOutputWithPast(
1204
+ last_hidden_state=hidden_states,
1205
+ past_key_values=next_cache,
1206
+ hidden_states=all_hidden_states,
1207
+ attentions=all_self_attns,
1208
+ )
1209
+
1210
+ def _update_causal_mask(
1211
+ self,
1212
+ attention_mask: torch.Tensor,
1213
+ input_tensor: torch.Tensor,
1214
+ cache_position: torch.Tensor,
1215
+ past_key_values: Cache,
1216
+ output_attentions: bool,
1217
+ ):
1218
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1219
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1220
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1221
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1222
+
1223
+ if self.config._attn_implementation == "flash_attention_2":
1224
+ if attention_mask is not None and 0.0 in attention_mask:
1225
+ return attention_mask
1226
+ return None
1227
+
1228
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1229
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1230
+ # to infer the attention mask.
1231
+ past_seen_tokens = (
1232
+ past_key_values.get_seq_length() if past_key_values is not None else 0
1233
+ )
1234
+ using_static_cache = isinstance(past_key_values, StaticCache)
1235
+
1236
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1237
+ if (
1238
+ self.config._attn_implementation == "sdpa"
1239
+ and not using_static_cache
1240
+ and not output_attentions
1241
+ ):
1242
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1243
+ attention_mask,
1244
+ inputs_embeds=input_tensor,
1245
+ past_key_values_length=past_seen_tokens,
1246
+ is_training=self.training,
1247
+ ):
1248
+ return None
1249
+
1250
+ dtype, device = input_tensor.dtype, input_tensor.device
1251
+ min_dtype = torch.finfo(dtype).min
1252
+ sequence_length = input_tensor.shape[1]
1253
+ if using_static_cache:
1254
+ target_length = past_key_values.get_max_length()
1255
+ else:
1256
+ target_length = (
1257
+ attention_mask.shape[-1]
1258
+ if isinstance(attention_mask, torch.Tensor)
1259
+ else past_seen_tokens + sequence_length + 1
1260
+ )
1261
+
1262
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1263
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1264
+ attention_mask,
1265
+ sequence_length=sequence_length,
1266
+ target_length=target_length,
1267
+ dtype=dtype,
1268
+ device=device,
1269
+ min_dtype=min_dtype,
1270
+ cache_position=cache_position,
1271
+ batch_size=input_tensor.shape[0],
1272
+ )
1273
+
1274
+ if (
1275
+ self.config._attn_implementation == "sdpa"
1276
+ and attention_mask is not None
1277
+ and attention_mask.device.type == "cuda"
1278
+ and not output_attentions
1279
+ ):
1280
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1281
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1282
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1283
+ causal_mask = AttentionMaskConverter._unmask_unattended(
1284
+ causal_mask, min_dtype
1285
+ )
1286
+
1287
+ return causal_mask
1288
+
1289
+
1290
+ class LoSparseLlamaForCausalLM(LoSparseLlamaPreTrainedModel):
1291
+ _tied_weights_keys = ["lm_head.weight"]
1292
+
1293
+ def __init__(self, config):
1294
+ super().__init__(config)
1295
+ self.model = LoSparseLlamaModel(config)
1296
+ self.vocab_size = config.vocab_size
1297
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1298
+
1299
+ # Initialize weights and apply final processing
1300
+ self.post_init()
1301
+
1302
+ def get_input_embeddings(self):
1303
+ return self.model.embed_tokens
1304
+
1305
+ def set_input_embeddings(self, value):
1306
+ self.model.embed_tokens = value
1307
+
1308
+ def get_output_embeddings(self):
1309
+ return self.lm_head
1310
+
1311
+ def set_output_embeddings(self, new_embeddings):
1312
+ self.lm_head = new_embeddings
1313
+
1314
+ def set_decoder(self, decoder):
1315
+ self.model = decoder
1316
+
1317
+ def get_decoder(self):
1318
+ return self.model
1319
+
1320
+ @add_start_docstrings_to_model_forward(LOSPARSE_LLAMA_INPUTS_DOCSTRING)
1321
+ @replace_return_docstrings(
1322
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1323
+ )
1324
+ def forward(
1325
+ self,
1326
+ input_ids: torch.LongTensor = None,
1327
+ attention_mask: Optional[torch.Tensor] = None,
1328
+ position_ids: Optional[torch.LongTensor] = None,
1329
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1330
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1331
+ labels: Optional[torch.LongTensor] = None,
1332
+ use_cache: Optional[bool] = None,
1333
+ output_attentions: Optional[bool] = None,
1334
+ output_hidden_states: Optional[bool] = None,
1335
+ return_dict: Optional[bool] = None,
1336
+ cache_position: Optional[torch.LongTensor] = None,
1337
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1338
+ r"""
1339
+ Args:
1340
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1341
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1342
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1343
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1344
+
1345
+ Returns:
1346
+
1347
+ Example:
1348
+
1349
+ ```python
1350
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1351
+
1352
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1353
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1354
+
1355
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1356
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1357
+
1358
+ >>> # Generate
1359
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1360
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1361
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1362
+ ```"""
1363
+ output_attentions = (
1364
+ output_attentions
1365
+ if output_attentions is not None
1366
+ else self.config.output_attentions
1367
+ )
1368
+ output_hidden_states = (
1369
+ output_hidden_states
1370
+ if output_hidden_states is not None
1371
+ else self.config.output_hidden_states
1372
+ )
1373
+ return_dict = (
1374
+ return_dict if return_dict is not None else self.config.use_return_dict
1375
+ )
1376
+
1377
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1378
+ outputs = self.model(
1379
+ input_ids=input_ids,
1380
+ attention_mask=attention_mask,
1381
+ position_ids=position_ids,
1382
+ past_key_values=past_key_values,
1383
+ inputs_embeds=inputs_embeds,
1384
+ use_cache=use_cache,
1385
+ output_attentions=output_attentions,
1386
+ output_hidden_states=output_hidden_states,
1387
+ return_dict=return_dict,
1388
+ cache_position=cache_position,
1389
+ )
1390
+
1391
+ hidden_states = outputs[0]
1392
+ if self.config.pretraining_tp > 1:
1393
+ lm_head_slices = self.lm_head.weight.split(
1394
+ self.vocab_size // self.config.pretraining_tp, dim=0
1395
+ )
1396
+ logits = [
1397
+ F.linear(hidden_states, lm_head_slices[i])
1398
+ for i in range(self.config.pretraining_tp)
1399
+ ]
1400
+ logits = torch.cat(logits, dim=-1)
1401
+ else:
1402
+ logits = self.lm_head(hidden_states)
1403
+ logits = logits.float()
1404
+
1405
+ loss = None
1406
+ if labels is not None:
1407
+ # Shift so that tokens < n predict n
1408
+ shift_logits = logits[..., :-1, :].contiguous()
1409
+ shift_labels = labels[..., 1:].contiguous()
1410
+ # Flatten the tokens
1411
+ loss_fct = CrossEntropyLoss()
1412
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1413
+ shift_labels = shift_labels.view(-1)
1414
+ # Enable model parallelism
1415
+ shift_labels = shift_labels.to(shift_logits.device)
1416
+ loss = loss_fct(shift_logits, shift_labels)
1417
+
1418
+ if not return_dict:
1419
+ output = (logits,) + outputs[1:]
1420
+ return (loss,) + output if loss is not None else output
1421
+
1422
+ return CausalLMOutputWithPast(
1423
+ loss=loss,
1424
+ logits=logits,
1425
+ past_key_values=outputs.past_key_values,
1426
+ hidden_states=outputs.hidden_states,
1427
+ attentions=outputs.attentions,
1428
+ )
1429
+
1430
+ def prepare_inputs_for_generation(
1431
+ self,
1432
+ input_ids,
1433
+ past_key_values=None,
1434
+ attention_mask=None,
1435
+ inputs_embeds=None,
1436
+ cache_position=None,
1437
+ position_ids=None,
1438
+ use_cache=True,
1439
+ **kwargs,
1440
+ ):
1441
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1442
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1443
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1444
+ if past_key_values is not None:
1445
+ if inputs_embeds is not None: # Exception 1
1446
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1447
+ elif (
1448
+ input_ids.shape[1] != cache_position.shape[0]
1449
+ ): # Default case (the "else", a no op, is Exception 2)
1450
+ input_ids = input_ids[:, cache_position]
1451
+
1452
+ if attention_mask is not None and position_ids is None:
1453
+ # create position_ids on the fly for batch generation
1454
+ position_ids = attention_mask.long().cumsum(-1) - 1
1455
+ position_ids.masked_fill_(attention_mask == 0, 1)
1456
+ if past_key_values:
1457
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1458
+
1459
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1460
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1461
+
1462
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1463
+ if inputs_embeds is not None and cache_position[0] == 0:
1464
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1465
+ else:
1466
+ # The clone here is for the same reason as for `position_ids`.
1467
+ model_inputs = {
1468
+ "input_ids": input_ids.clone(memory_format=torch.contiguous_format),
1469
+ "inputs_embeds": None,
1470
+ }
1471
+
1472
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1473
+ if model_inputs["inputs_embeds"] is not None:
1474
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1475
+ device = model_inputs["inputs_embeds"].device
1476
+ else:
1477
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1478
+ device = model_inputs["input_ids"].device
1479
+
1480
+ dtype = self.lm_head.weight.dtype
1481
+ min_dtype = torch.finfo(dtype).min
1482
+
1483
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1484
+ attention_mask,
1485
+ sequence_length=sequence_length,
1486
+ target_length=past_key_values.get_max_length(),
1487
+ dtype=dtype,
1488
+ device=device,
1489
+ min_dtype=min_dtype,
1490
+ cache_position=cache_position,
1491
+ batch_size=batch_size,
1492
+ )
1493
+
1494
+ model_inputs.update(
1495
+ {
1496
+ "position_ids": position_ids,
1497
+ "cache_position": cache_position,
1498
+ "past_key_values": past_key_values,
1499
+ "use_cache": use_cache,
1500
+ "attention_mask": attention_mask,
1501
+ }
1502
+ )
1503
+ return model_inputs
1504
+
1505
+
1506
+ @add_start_docstrings(
1507
+ """
1508
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1509
+
1510
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1511
+ (e.g. GPT-2) do.
1512
+
1513
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1514
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1515
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1516
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1517
+ each row of the batch).
1518
+ """,
1519
+ LOSPARSE_LLAMA_START_DOCSTRING,
1520
+ )
1521
+ class LoSparseLlamaForSequenceClassification(LoSparseLlamaPreTrainedModel):
1522
+ def __init__(self, config):
1523
+ super().__init__(config)
1524
+ self.num_labels = config.num_labels
1525
+ self.model = LoSparseLlamaModel(config)
1526
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1527
+
1528
+ # Initialize weights and apply final processing
1529
+ self.post_init()
1530
+
1531
+ def get_input_embeddings(self):
1532
+ return self.model.embed_tokens
1533
+
1534
+ def set_input_embeddings(self, value):
1535
+ self.model.embed_tokens = value
1536
+
1537
+ @add_start_docstrings_to_model_forward(LOSPARSE_LLAMA_INPUTS_DOCSTRING)
1538
+ def forward(
1539
+ self,
1540
+ input_ids: Optional[torch.LongTensor] = None,
1541
+ attention_mask: Optional[torch.Tensor] = None,
1542
+ position_ids: Optional[torch.LongTensor] = None,
1543
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1544
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1545
+ labels: Optional[torch.LongTensor] = None,
1546
+ use_cache: Optional[bool] = None,
1547
+ output_attentions: Optional[bool] = None,
1548
+ output_hidden_states: Optional[bool] = None,
1549
+ return_dict: Optional[bool] = None,
1550
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1551
+ r"""
1552
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1553
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1554
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1555
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1556
+ """
1557
+ return_dict = (
1558
+ return_dict if return_dict is not None else self.config.use_return_dict
1559
+ )
1560
+
1561
+ transformer_outputs = self.model(
1562
+ input_ids,
1563
+ attention_mask=attention_mask,
1564
+ position_ids=position_ids,
1565
+ past_key_values=past_key_values,
1566
+ inputs_embeds=inputs_embeds,
1567
+ use_cache=use_cache,
1568
+ output_attentions=output_attentions,
1569
+ output_hidden_states=output_hidden_states,
1570
+ return_dict=return_dict,
1571
+ )
1572
+ hidden_states = transformer_outputs[0]
1573
+ logits = self.score(hidden_states)
1574
+
1575
+ if input_ids is not None:
1576
+ batch_size = input_ids.shape[0]
1577
+ else:
1578
+ batch_size = inputs_embeds.shape[0]
1579
+
1580
+ if self.config.pad_token_id is None and batch_size != 1:
1581
+ raise ValueError(
1582
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1583
+ )
1584
+ if self.config.pad_token_id is None:
1585
+ sequence_lengths = -1
1586
+ else:
1587
+ if input_ids is not None:
1588
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1589
+ sequence_lengths = (
1590
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1591
+ )
1592
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1593
+ sequence_lengths = sequence_lengths.to(logits.device)
1594
+ else:
1595
+ sequence_lengths = -1
1596
+
1597
+ pooled_logits = logits[
1598
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1599
+ ]
1600
+
1601
+ loss = None
1602
+ if labels is not None:
1603
+ labels = labels.to(logits.device)
1604
+ if self.config.problem_type is None:
1605
+ if self.num_labels == 1:
1606
+ self.config.problem_type = "regression"
1607
+ elif self.num_labels > 1 and (
1608
+ labels.dtype == torch.long or labels.dtype == torch.int
1609
+ ):
1610
+ self.config.problem_type = "single_label_classification"
1611
+ else:
1612
+ self.config.problem_type = "multi_label_classification"
1613
+
1614
+ if self.config.problem_type == "regression":
1615
+ loss_fct = MSELoss()
1616
+ if self.num_labels == 1:
1617
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1618
+ else:
1619
+ loss = loss_fct(pooled_logits, labels)
1620
+ elif self.config.problem_type == "single_label_classification":
1621
+ loss_fct = CrossEntropyLoss()
1622
+ loss = loss_fct(
1623
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1624
+ )
1625
+ elif self.config.problem_type == "multi_label_classification":
1626
+ loss_fct = BCEWithLogitsLoss()
1627
+ loss = loss_fct(pooled_logits, labels)
1628
+ if not return_dict:
1629
+ output = (pooled_logits,) + transformer_outputs[1:]
1630
+ return ((loss,) + output) if loss is not None else output
1631
+
1632
+ return SequenceClassifierOutputWithPast(
1633
+ loss=loss,
1634
+ logits=pooled_logits,
1635
+ past_key_values=transformer_outputs.past_key_values,
1636
+ hidden_states=transformer_outputs.hidden_states,
1637
+ attentions=transformer_outputs.attentions,
1638
+ )
1639
+
1640
+
1641
+ @add_start_docstrings(
1642
+ """
1643
+ The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
1644
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1645
+ """,
1646
+ LOSPARSE_LLAMA_START_DOCSTRING,
1647
+ )
1648
+ class LoSparseLlamaForQuestionAnswering(LoSparseLlamaPreTrainedModel):
1649
+ base_model_prefix = "transformer"
1650
+
1651
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
1652
+ def __init__(self, config):
1653
+ super().__init__(config)
1654
+ self.transformer = LoSparseLlamaModel(config)
1655
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1656
+
1657
+ # Initialize weights and apply final processing
1658
+ self.post_init()
1659
+
1660
+ def get_input_embeddings(self):
1661
+ return self.transformer.embed_tokens
1662
+
1663
+ def set_input_embeddings(self, value):
1664
+ self.transformer.embed_tokens = value
1665
+
1666
+ @add_start_docstrings_to_model_forward(LOSPARSE_LLAMA_INPUTS_DOCSTRING)
1667
+ def forward(
1668
+ self,
1669
+ input_ids: Optional[torch.LongTensor] = None,
1670
+ attention_mask: Optional[torch.FloatTensor] = None,
1671
+ position_ids: Optional[torch.LongTensor] = None,
1672
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1673
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1674
+ start_positions: Optional[torch.LongTensor] = None,
1675
+ end_positions: Optional[torch.LongTensor] = None,
1676
+ output_attentions: Optional[bool] = None,
1677
+ output_hidden_states: Optional[bool] = None,
1678
+ return_dict: Optional[bool] = None,
1679
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1680
+ r"""
1681
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1682
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1683
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1684
+ are not taken into account for computing the loss.
1685
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1686
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1687
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1688
+ are not taken into account for computing the loss.
1689
+ """
1690
+ return_dict = (
1691
+ return_dict if return_dict is not None else self.config.use_return_dict
1692
+ )
1693
+
1694
+ outputs = self.transformer(
1695
+ input_ids,
1696
+ attention_mask=attention_mask,
1697
+ position_ids=position_ids,
1698
+ past_key_values=past_key_values,
1699
+ inputs_embeds=inputs_embeds,
1700
+ output_attentions=output_attentions,
1701
+ output_hidden_states=output_hidden_states,
1702
+ return_dict=return_dict,
1703
+ )
1704
+
1705
+ sequence_output = outputs[0]
1706
+
1707
+ logits = self.qa_outputs(sequence_output)
1708
+ start_logits, end_logits = logits.split(1, dim=-1)
1709
+ start_logits = start_logits.squeeze(-1).contiguous()
1710
+ end_logits = end_logits.squeeze(-1).contiguous()
1711
+
1712
+ total_loss = None
1713
+ if start_positions is not None and end_positions is not None:
1714
+ # If we are on multi-GPU, split add a dimension
1715
+ if len(start_positions.size()) > 1:
1716
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1717
+ if len(end_positions.size()) > 1:
1718
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1719
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1720
+ ignored_index = start_logits.size(1)
1721
+ start_positions = start_positions.clamp(0, ignored_index)
1722
+ end_positions = end_positions.clamp(0, ignored_index)
1723
+
1724
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1725
+ start_loss = loss_fct(start_logits, start_positions)
1726
+ end_loss = loss_fct(end_logits, end_positions)
1727
+ total_loss = (start_loss + end_loss) / 2
1728
+
1729
+ if not return_dict:
1730
+ output = (start_logits, end_logits) + outputs[2:]
1731
+ return ((total_loss,) + output) if total_loss is not None else output
1732
+
1733
+ return QuestionAnsweringModelOutput(
1734
+ loss=total_loss,
1735
+ start_logits=start_logits,
1736
+ end_logits=end_logits,
1737
+ hidden_states=outputs.hidden_states,
1738
+ attentions=outputs.attentions,
1739
+ )
1740
+
1741
+
1742
+ @add_start_docstrings(
1743
+ """
1744
+ The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1745
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1746
+ """,
1747
+ LOSPARSE_LLAMA_START_DOCSTRING,
1748
+ )
1749
+ class LoSparseLlamaForTokenClassification(LoSparseLlamaPreTrainedModel):
1750
+ def __init__(self, config):
1751
+ super().__init__(config)
1752
+ self.num_labels = config.num_labels
1753
+ self.model = LoSparseLlamaModel(config)
1754
+ if getattr(config, "classifier_dropout", None) is not None:
1755
+ classifier_dropout = config.classifier_dropout
1756
+ elif getattr(config, "hidden_dropout", None) is not None:
1757
+ classifier_dropout = config.hidden_dropout
1758
+ else:
1759
+ classifier_dropout = 0.1
1760
+ self.dropout = nn.Dropout(classifier_dropout)
1761
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1762
+
1763
+ # Initialize weights and apply final processing
1764
+ self.post_init()
1765
+
1766
+ def get_input_embeddings(self):
1767
+ return self.model.embed_tokens
1768
+
1769
+ def set_input_embeddings(self, value):
1770
+ self.model.embed_tokens = value
1771
+
1772
+ @add_start_docstrings_to_model_forward(LOSPARSE_LLAMA_INPUTS_DOCSTRING)
1773
+ def forward(
1774
+ self,
1775
+ input_ids: Optional[torch.LongTensor] = None,
1776
+ attention_mask: Optional[torch.Tensor] = None,
1777
+ position_ids: Optional[torch.LongTensor] = None,
1778
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1779
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1780
+ labels: Optional[torch.LongTensor] = None,
1781
+ use_cache: Optional[bool] = None,
1782
+ output_attentions: Optional[bool] = None,
1783
+ output_hidden_states: Optional[bool] = None,
1784
+ return_dict: Optional[bool] = None,
1785
+ ) -> Union[Tuple, TokenClassifierOutput]:
1786
+ r"""
1787
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1788
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1789
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1790
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1791
+ """
1792
+ return_dict = (
1793
+ return_dict if return_dict is not None else self.config.use_return_dict
1794
+ )
1795
+
1796
+ outputs = self.model(
1797
+ input_ids,
1798
+ attention_mask=attention_mask,
1799
+ position_ids=position_ids,
1800
+ past_key_values=past_key_values,
1801
+ inputs_embeds=inputs_embeds,
1802
+ use_cache=use_cache,
1803
+ output_attentions=output_attentions,
1804
+ output_hidden_states=output_hidden_states,
1805
+ return_dict=return_dict,
1806
+ )
1807
+ sequence_output = outputs[0]
1808
+ sequence_output = self.dropout(sequence_output)
1809
+ logits = self.score(sequence_output)
1810
+
1811
+ loss = None
1812
+ if labels is not None:
1813
+ loss_fct = CrossEntropyLoss()
1814
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1815
+
1816
+ if not return_dict:
1817
+ output = (logits,) + outputs[2:]
1818
+ return ((loss,) + output) if loss is not None else output
1819
+
1820
+ return TokenClassifierOutput(
1821
+ loss=loss,
1822
+ logits=logits,
1823
+ hidden_states=outputs.hidden_states,
1824
+ attentions=outputs.attentions,
1825
+ )