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,955 @@
1
+ import gc
2
+ import logging
3
+ from abc import abstractmethod
4
+ from copy import deepcopy
5
+ from typing import Dict, List, Literal, Optional, Tuple, Union, cast
6
+
7
+ import lightning as L
8
+ import numpy as np
9
+ import torch
10
+ import torch.utils.hooks
11
+ from accelerate import init_empty_weights
12
+ from torch import Tensor, nn
13
+ from tqdm.auto import tqdm
14
+ from transformers import LlamaForCausalLM
15
+ from typing_extensions import override
16
+
17
+ from fusion_bench.method import BaseAlgorithm
18
+ from fusion_bench.method.pruning.llama_wanda_prune import WandaHookFn
19
+ from fusion_bench.method.pruning.prune_utils import (
20
+ PruningType,
21
+ compute_sparsity,
22
+ find_linear_layers,
23
+ semistructured_magnitude_prune_,
24
+ unstructured_magnitude_prune_,
25
+ )
26
+ from fusion_bench.method.pruning.wanda_utils.data import get_loaders
27
+ from fusion_bench.method.pruning.wanda_utils.prune import prepare_calibration_input
28
+ from fusion_bench.mixins import SimpleProfilerMixin
29
+ from fusion_bench.modelpool import CausalLMPool
30
+ from fusion_bench.models.modeling_losparse_llama import LoSparseLlamaForCausalLM
31
+ from fusion_bench.models.modeling_losparse_llama.losparse_linear import LoSparseLinear
32
+ from fusion_bench.models.modeling_losparse_llama.utils import convert_to_losparse_llama
33
+ from fusion_bench.utils import cache_to_disk, print_parameters, timeit_context
34
+ from fusion_bench.utils.devices import get_device
35
+
36
+ log = logging.getLogger(__name__)
37
+
38
+
39
+ @torch.no_grad()
40
+ def extract_low_rank_part_(linear: LoSparseLinear, rank: int):
41
+ assert isinstance(
42
+ linear, LoSparseLinear
43
+ ), f"Expected LoSparseLinear, got {type(linear)}"
44
+
45
+ u, s, vh = cast(
46
+ Tuple[Tensor, Tensor, Tensor],
47
+ torch.linalg.svd(linear.weight.float(), full_matrices=False),
48
+ )
49
+ v = vh.T
50
+ uk = u[:, :rank]
51
+ sk = s[:rank]
52
+ vk = v[:, :rank]
53
+ linear.lo_A.data = vk.T.to(linear.lo_A.dtype).contiguous()
54
+ linear.lo_B.data = (uk * sk).to(linear.lo_B.dtype).contiguous()
55
+ linear.weight.data = (linear.weight - linear.lo_B @ linear.lo_A).contiguous()
56
+ return linear
57
+
58
+
59
+ def iterative_weight_update(w, w_pruned, mask, rank):
60
+ w_diff = w - w_pruned
61
+ u, s, vh = torch.linalg.svd(w_diff.float(), full_matrices=False)
62
+ v = vh.t()
63
+ rank = min(s.size(0) - 1, rank)
64
+ uk = u[:, rank:]
65
+ sk = s[rank:]
66
+ vk = v[:, rank:]
67
+ w_pruned = w_pruned + (mask * (uk @ torch.diag(sk) @ vk.t())).to(w_pruned.dtype)
68
+ spectrum_ratio = torch.sum(s[:rank]) / torch.sum(s)
69
+ return (w_pruned, spectrum_ratio)
70
+
71
+
72
+ def pcp_loss_with_mask(w, q, mask):
73
+ _lambda = 1 / np.sqrt(np.max(w.size()))
74
+ nuclear_loss = torch.linalg.matrix_norm((w * (~mask) + q * mask).float(), ord="nuc")
75
+ l1_loss = _lambda * torch.linalg.matrix_norm((w * mask - q * mask).float(), ord=1)
76
+ return nuclear_loss + l1_loss
77
+
78
+
79
+ def PCP_search_with_mask(w, mask, T_max=1000, lr=1e-2):
80
+ q = torch.zeros_like(w).float().requires_grad_(True)
81
+ optimizer = torch.optim.AdamW([q], lr=lr)
82
+ lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
83
+ optimizer, T_max=T_max, eta_min=1e-1 * lr
84
+ )
85
+ for step_idx in tqdm(range(T_max)):
86
+ optimizer.zero_grad()
87
+ loss = pcp_loss_with_mask(w, q, mask)
88
+ loss.backward()
89
+ optimizer.step()
90
+ lr_scheduler.step()
91
+ if step_idx % (T_max // 20) == 0:
92
+ print(f"Step {step_idx}: Loss {loss.item()}")
93
+ s = (w * mask - q * mask).to(w.dtype)
94
+ return s
95
+
96
+
97
+ class SparseLoForLlama(BaseAlgorithm, SimpleProfilerMixin):
98
+ "Zero-Shot SVD Algorithm"
99
+
100
+ _variants_requires_calibration_data = ["wanda"]
101
+ _variants_hook_mapping = {"wanda": WandaHookFn}
102
+
103
+ _config_mapping = BaseAlgorithm._config_mapping | {
104
+ "nsamples": "nsamples",
105
+ "seed": "seed",
106
+ "rank": "rank",
107
+ "sparsity_ratio": "sparsity_ratio",
108
+ "prune_type": "prune_type",
109
+ "n": "n",
110
+ "m": "m",
111
+ "device": "device",
112
+ "variant": "variant",
113
+ }
114
+
115
+ def __init__(
116
+ self,
117
+ *,
118
+ nsamples: int,
119
+ variant: Literal["dense", "random", "wanda", "lowrank-only", "magnitude"],
120
+ seed: int,
121
+ rank: int,
122
+ sparsity_ratio: float,
123
+ prune_type: PruningType,
124
+ n: int,
125
+ m: int,
126
+ device: Optional[str] = None,
127
+ model_save_path: Optional[str] = None,
128
+ **kwargs,
129
+ ):
130
+ super().__init__(**kwargs)
131
+ self.nsamples = nsamples
132
+ self.variant = variant
133
+ self.seed = seed
134
+ self.rank = rank
135
+ self.sparsity_ratio = sparsity_ratio
136
+ self.prune_type = prune_type
137
+ self.device = device
138
+ self.model_save_path = model_save_path
139
+ self.n = n
140
+ self.m = m
141
+
142
+ @override
143
+ def run(self, modelpool: CausalLMPool):
144
+ if self.seed is not None:
145
+ L.seed_everything(self.seed)
146
+
147
+ # load pre-trained model or the first model in the pool
148
+ with self.profile("load_model"):
149
+ model = modelpool.load_pretrained_or_first_model()
150
+ model.seqlen = model.config.max_position_embeddings
151
+ tokenizer = modelpool.load_tokenizer(use_fast=False)
152
+
153
+ if not isinstance(model, (LlamaForCausalLM,)):
154
+ log.warning(f"Model type {type(model)} may not supported.")
155
+
156
+ if self.variant in self._variants_requires_calibration_data:
157
+ inps, outs, attention_mask, position_ids = self.prepare_calibration_data(
158
+ model, tokenizer
159
+ )
160
+
161
+ model = convert_to_losparse_llama(model, rank=self.rank)
162
+ gc.collect()
163
+ if torch.cuda.is_available():
164
+ torch.cuda.empty_cache()
165
+
166
+ for linear in find_linear_layers(model, layers=[LoSparseLinear]).values():
167
+ linear = cast(LoSparseLinear, linear)
168
+ linear.lo_A.data.zero_()
169
+ linear.lo_B.data.zero_()
170
+ linear.skip_lowrank = True
171
+
172
+ match self.variant:
173
+ case "dense":
174
+ # this variant is a no-op, just for debug the conversion
175
+ pass
176
+ case "lowrank-only":
177
+ self.extract_low_rank_parts_(model)
178
+ self.set_weights_to_zeros_(model)
179
+ case "random":
180
+ self.random_prune_(model)
181
+ case "magnitude":
182
+ self.magnitude_prune_(model)
183
+ case variant if variant in self._variants_requires_calibration_data:
184
+ self.prune_using_calibration_data_(
185
+ model,
186
+ inps=inps,
187
+ outs=outs,
188
+ attention_mask=attention_mask,
189
+ position_ids=position_ids,
190
+ )
191
+ case _:
192
+ raise ValueError(f"Invalid variant: {self.variant}")
193
+
194
+ if self.model_save_path is not None:
195
+ with timeit_context(f"Saving the model to {self.model_save_path}"):
196
+ tokenizer.save_pretrained(self.model_save_path)
197
+ model.save_pretrained(self.model_save_path)
198
+
199
+ return model
200
+
201
+ def set_weights_to_zeros_(self, model):
202
+ layers: nn.ModuleList = model.model.layers
203
+ for layer in tqdm(
204
+ list(layers),
205
+ "Pruning Layers",
206
+ dynamic_ncols=True,
207
+ ):
208
+ for name, losparse_linear in layer.named_modules():
209
+ if isinstance(losparse_linear, LoSparseLinear):
210
+ log.info(f"Pruning {name}, set weights to zeros")
211
+ losparse_linear.weight.data.zero_()
212
+
213
+ @torch.no_grad()
214
+ def extract_low_rank_parts_(self, model):
215
+ for layer in tqdm(
216
+ list(model.model.layers),
217
+ "Extract Low-Rank Parts (Layers)",
218
+ dynamic_ncols=True,
219
+ ):
220
+ for losparse_linear in layer.modules():
221
+ if isinstance(losparse_linear, LoSparseLinear):
222
+ if self.device is not None:
223
+ original_device = get_device(losparse_linear)
224
+ losparse_linear.to(self.device)
225
+ extract_low_rank_part_(losparse_linear, self.rank)
226
+ if self.device is not None:
227
+ losparse_linear.to(original_device)
228
+
229
+ def _prepare_calibration_data(self, model, tokenizer):
230
+ with timeit_context("loading calibration data"):
231
+ dataloader, _ = get_loaders(
232
+ "c4",
233
+ nsamples=self.nsamples,
234
+ seed=self.seed,
235
+ seqlen=model.seqlen,
236
+ tokenizer=tokenizer,
237
+ )
238
+
239
+ with torch.no_grad():
240
+ # collect input to the first layer
241
+ inps, outs, attention_mask, position_ids = prepare_calibration_input(
242
+ model, dataloader, self.device
243
+ )
244
+ return inps, outs, attention_mask, position_ids
245
+
246
+ def prepare_calibration_data(self, model: LlamaForCausalLM, tokenizer):
247
+
248
+ @cache_to_disk(
249
+ f"outputs/cache/{model.config.name_or_path.split('/')[-1]}/calibration_data.pkl"
250
+ )
251
+ def _prepare_calibration_data(model, tokenizer):
252
+ return self._prepare_calibration_data(model, tokenizer)
253
+
254
+ return _prepare_calibration_data(model, tokenizer)
255
+
256
+ def random_prune_(self, model):
257
+ layers: nn.ModuleList = model.model.layers
258
+ for layer in tqdm(
259
+ list(layers),
260
+ "Pruning Layers",
261
+ dynamic_ncols=True,
262
+ ):
263
+ for name, losparse_linear in layer.named_modules():
264
+ if isinstance(losparse_linear, LoSparseLinear):
265
+ log.info(f"Pruning {name}, set weights to zeros")
266
+ if self.prune_type == PruningType.UNSTRUCTURED:
267
+ _, pruned_weights = unstructured_magnitude_prune_(
268
+ losparse_linear.weight.data,
269
+ metric_function_or_scores=torch.rand_like,
270
+ sparsity_ratio=self.sparsity_ratio,
271
+ return_pruned_weight=True,
272
+ )
273
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
274
+ _, pruned_weights = semistructured_magnitude_prune_(
275
+ losparse_linear.weight.data,
276
+ metric_function_or_scores=torch.rand_like,
277
+ n=self.n,
278
+ m=self.m,
279
+ return_pruned_weight=True,
280
+ )
281
+ else:
282
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
283
+ self.check_sparsity(losparse_linear.weight)
284
+ self.extract_low_rank_part_using_pruned_(
285
+ losparse_linear, pruned_weights
286
+ )
287
+
288
+ def magnitude_prune_(self, model):
289
+ layers: nn.ModuleList = model.model.layers
290
+ for layer_idx, layer in tqdm(
291
+ enumerate(layers), "Pruning Layers", total=len(layers), dynamic_ncols=True
292
+ ):
293
+ for name, losparse_linear in layer.named_modules():
294
+ if isinstance(losparse_linear, LoSparseLinear):
295
+ log.info(f"Magnitude Pruning {name}")
296
+ if self.prune_type == PruningType.UNSTRUCTURED:
297
+ _, pruned_weights = unstructured_magnitude_prune_(
298
+ losparse_linear.weight.data,
299
+ metric_function_or_scores=torch.abs,
300
+ sparsity_ratio=self.sparsity_ratio,
301
+ return_pruned_weight=True,
302
+ )
303
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
304
+ _, pruned_weights = semistructured_magnitude_prune_(
305
+ losparse_linear.weight.data,
306
+ metric_function_or_scores=torch.abs,
307
+ n=self.n,
308
+ m=self.m,
309
+ return_pruned_weight=True,
310
+ )
311
+ else:
312
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
313
+ self.check_sparsity(losparse_linear.weight)
314
+ self.extract_low_rank_part_using_pruned_(
315
+ losparse_linear, pruned_weights
316
+ )
317
+
318
+ def prune_using_calibration_data_(
319
+ self,
320
+ model: LoSparseLlamaForCausalLM,
321
+ *,
322
+ inps: Tensor,
323
+ outs: Tensor,
324
+ attention_mask: Optional[Tensor],
325
+ position_ids: Optional[Tensor],
326
+ ):
327
+ layers = model.model.layers
328
+ for layer_idx, layer in tqdm(
329
+ enumerate(layers),
330
+ "Pruning Layers",
331
+ total=len(layers),
332
+ dynamic_ncols=True,
333
+ ):
334
+ if (
335
+ hasattr(model, "hf_device_map")
336
+ and f"model.layers.{layer_idx}" in model.hf_device_map
337
+ ): ## handle the case for llama-30B and llama-65B, when the device map has multiple GPUs;
338
+ dev = model.hf_device_map[f"model.layers.{layer_idx}"]
339
+ inps, outs, attention_mask, position_ids = (
340
+ inps.to(dev),
341
+ outs.to(dev),
342
+ attention_mask.to(dev) if attention_mask is not None else None,
343
+ position_ids.to(dev) if position_ids is not None else None,
344
+ )
345
+
346
+ # collect the importance scores
347
+ linear_layers = cast(
348
+ Dict[str, LoSparseLinear],
349
+ find_linear_layers(layer, layers=[LoSparseLinear]),
350
+ )
351
+
352
+ # register hooks to collect the importance scores
353
+ def get_hook_fn(linear: LoSparseLinear):
354
+ hook_fn = self._variants_hook_mapping[self.variant](linear)
355
+ return hook_fn
356
+
357
+ hooks = {}
358
+ handles: List[torch.utils.hooks.RemovableHandle] = []
359
+ for name, linear in linear_layers.items():
360
+ hook_fn = get_hook_fn(linear)
361
+ hooks[name] = hook_fn
362
+ handles.append(linear.register_forward_hook(hook_fn))
363
+
364
+ with torch.no_grad():
365
+ for j in range(self.nsamples):
366
+ outs[j] = layer(
367
+ inps[j].unsqueeze(0),
368
+ attention_mask=attention_mask,
369
+ position_ids=position_ids,
370
+ )[0]
371
+
372
+ # compute the importance scores and remove the hooks
373
+ metrics = {}
374
+ for name, hook in hooks.items():
375
+ metrics[name] = hook.compute()
376
+ for h in handles:
377
+ h.remove()
378
+
379
+ # prune the weights based on the importance scores
380
+ pruned_weights_dict = {}
381
+ for name, linear in linear_layers.items():
382
+ log.info(f"Pruning {name}")
383
+ if self.prune_type == PruningType.UNSTRUCTURED:
384
+ _, pruned_weights = unstructured_magnitude_prune_(
385
+ linear.weight.data,
386
+ metrics[name],
387
+ sparsity_ratio=self.sparsity_ratio,
388
+ return_pruned_weight=True,
389
+ )
390
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
391
+ _, pruned_weights = semistructured_magnitude_prune_(
392
+ linear.weight.data,
393
+ metrics[name],
394
+ n=self.n,
395
+ m=self.m,
396
+ return_pruned_weight=True,
397
+ )
398
+ else:
399
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
400
+ self.check_sparsity(linear.weight)
401
+ pruned_weights_dict[name] = pruned_weights
402
+
403
+ # compute the input to the next layer
404
+ with torch.no_grad():
405
+ for j in range(self.nsamples):
406
+ outs[j] = layer(
407
+ inps[j].unsqueeze(0),
408
+ attention_mask=attention_mask,
409
+ position_ids=position_ids,
410
+ )[0]
411
+ inps, outs = outs, inps
412
+
413
+ # extract the low-rank parts
414
+ for name, linear in linear_layers.items():
415
+ log.info(f"Extracting low-rank part for {name}")
416
+ self.extract_low_rank_part_using_pruned_(
417
+ linear, pruned_weights_dict[name]
418
+ )
419
+ linear.skip_lowrank = False
420
+
421
+ @torch.no_grad()
422
+ def extract_low_rank_part_using_pruned_(
423
+ self, linear: LoSparseLinear, pruned_weight: Tensor
424
+ ):
425
+ assert isinstance(
426
+ linear, LoSparseLinear
427
+ ), f"Expected LoSparseLinear, got {type(linear)}"
428
+
429
+ u, s, vh = cast(
430
+ Tuple[Tensor, Tensor, Tensor],
431
+ torch.linalg.svd(pruned_weight.float(), full_matrices=False),
432
+ )
433
+ v = vh.T
434
+ uk = u[:, : self.rank]
435
+ sk = s[: self.rank]
436
+ vk = v[:, : self.rank]
437
+ linear.lo_A.data = vk.T.to(linear.lo_A.dtype).contiguous()
438
+ linear.lo_B.data = (uk * sk).to(linear.lo_B.dtype).contiguous()
439
+ return linear
440
+
441
+ @torch.no_grad()
442
+ def check_sparsity(self, weight: Tensor, tol: float = 0.01):
443
+ if self.prune_type == PruningType.UNSTRUCTURED:
444
+ assert (compute_sparsity(weight) - self.sparsity_ratio).abs() < tol
445
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
446
+ assert (compute_sparsity(weight) - self.n / self.m).abs() < tol
447
+ else:
448
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
449
+
450
+
451
+ class PCPSparseLoForLlama(SparseLoForLlama):
452
+ "PCP with mask"
453
+
454
+ _config_mapping = SparseLoForLlama._config_mapping | {
455
+ "num_iterations": "num_iterations",
456
+ }
457
+
458
+ def __init__(self, num_iterations: int, **kwargs):
459
+ super().__init__(**kwargs)
460
+ self.num_iterations = num_iterations
461
+
462
+ @override
463
+ def run(self, modelpool):
464
+ if self.seed is not None:
465
+ L.seed_everything(self.seed)
466
+
467
+ # load pre-trained model or the first model in the pool
468
+ with self.profile("load_model"):
469
+ model = modelpool.load_pretrained_or_first_model()
470
+ model.seqlen = model.config.max_position_embeddings
471
+ tokenizer = modelpool.load_tokenizer(use_fast=False)
472
+
473
+ if not isinstance(model, (LlamaForCausalLM,)):
474
+ log.warning(f"Model type {type(model)} may not supported.")
475
+
476
+ if self.variant in self._variants_requires_calibration_data:
477
+ inps, outs, attention_mask, position_ids = self.prepare_calibration_data(
478
+ model, tokenizer
479
+ )
480
+
481
+ model = convert_to_losparse_llama(model, rank=self.rank)
482
+ gc.collect()
483
+ if torch.cuda.is_available():
484
+ torch.cuda.empty_cache()
485
+
486
+ for linear in find_linear_layers(model, layers=[LoSparseLinear]).values():
487
+ linear = cast(LoSparseLinear, linear)
488
+ linear.lo_A.data.zero_()
489
+ linear.lo_B.data.zero_()
490
+ linear.skip_lowrank = True
491
+
492
+ match self.variant:
493
+ case "dense":
494
+ # this variant is a no-op, just for debug the conversion
495
+ pass
496
+ case "lowrank-only":
497
+ self.extract_low_rank_parts_(model)
498
+ self.set_weights_to_zeros_(model)
499
+ case "random":
500
+ self.pcp_random_prune_(model)
501
+ case "magnitude":
502
+ self.pcp_magnitude_prune_(model)
503
+ case variant if variant in self._variants_requires_calibration_data:
504
+ self.pcp_prune_using_calibration_data_(
505
+ model,
506
+ inps=inps,
507
+ outs=outs,
508
+ attention_mask=attention_mask,
509
+ position_ids=position_ids,
510
+ )
511
+ case _:
512
+ raise ValueError(f"Invalid variant: {self.variant}")
513
+
514
+ if self.model_save_path is not None:
515
+ with timeit_context(f"Saving the model to {self.model_save_path}"):
516
+ tokenizer.save_pretrained(self.model_save_path)
517
+ model.save_pretrained(self.model_save_path)
518
+
519
+ return model
520
+
521
+ @torch.no_grad()
522
+ def pcp_random_prune_(self, model):
523
+ layers: nn.ModuleList = model.model.layers
524
+ for layer_idx, layer in tqdm(
525
+ list(enumerate(layers)),
526
+ "Pruning Layers",
527
+ dynamic_ncols=True,
528
+ ):
529
+ for name, linear in layer.named_modules():
530
+ if isinstance(linear, LoSparseLinear):
531
+ log.info(f"Pruning {name}, set weights to zeros")
532
+ W = linear.weight.data.clone()
533
+ if self.prune_type == PruningType.UNSTRUCTURED:
534
+ unstructured_magnitude_prune_(
535
+ linear.weight.data,
536
+ metric_function_or_scores=torch.rand_like,
537
+ sparsity_ratio=self.sparsity_ratio,
538
+ )
539
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
540
+ semistructured_magnitude_prune_(
541
+ linear.weight.data,
542
+ metric_function_or_scores=torch.rand_like,
543
+ n=self.n,
544
+ m=self.m,
545
+ )
546
+ else:
547
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
548
+ self.check_sparsity(linear.weight)
549
+ mask = linear.weight != 0
550
+ linear.weight.data = PCP_search_with_mask(
551
+ W, mask, T_max=self.num_iterations
552
+ )
553
+ self.extract_low_rank_part_using_pruned_(linear, W - linear.weight)
554
+
555
+ def pcp_magnitude_prune_(self, model):
556
+ layers: nn.ModuleList = model.model.layers
557
+ for layer_idx, layer in tqdm(
558
+ enumerate(layers), "Pruning Layers", total=len(layers), dynamic_ncols=True
559
+ ):
560
+ for name, linear in layer.named_modules():
561
+ if isinstance(linear, LoSparseLinear):
562
+ log.info(f"Magnitude Pruning {name}")
563
+ W = linear.weight.data.clone()
564
+ if self.prune_type == PruningType.UNSTRUCTURED:
565
+ unstructured_magnitude_prune_(
566
+ linear.weight.data,
567
+ metric_function_or_scores=torch.abs,
568
+ sparsity_ratio=self.sparsity_ratio,
569
+ )
570
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
571
+ semistructured_magnitude_prune_(
572
+ linear.weight.data,
573
+ metric_function_or_scores=torch.abs,
574
+ n=self.n,
575
+ m=self.m,
576
+ )
577
+ else:
578
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
579
+ self.check_sparsity(linear.weight)
580
+ mask = linear.weight != 0
581
+ linear.weight.data = PCP_search_with_mask(
582
+ W, mask, T_max=self.num_iterations
583
+ )
584
+ self.extract_low_rank_part_using_pruned_(linear, W - linear.weight)
585
+
586
+ def pcp_prune_using_calibration_data_(
587
+ self,
588
+ model: LoSparseLlamaForCausalLM,
589
+ *,
590
+ inps: Tensor,
591
+ outs: Tensor,
592
+ attention_mask: Optional[Tensor],
593
+ position_ids: Optional[Tensor],
594
+ ):
595
+ layers = model.model.layers
596
+ for layer_idx, layer in tqdm(
597
+ enumerate(layers),
598
+ "Pruning Layers",
599
+ total=len(layers),
600
+ dynamic_ncols=True,
601
+ ):
602
+ if (
603
+ hasattr(model, "hf_device_map")
604
+ and f"model.layers.{layer_idx}" in model.hf_device_map
605
+ ): ## handle the case for llama-30B and llama-65B, when the device map has multiple GPUs;
606
+ dev = model.hf_device_map[f"model.layers.{layer_idx}"]
607
+ inps, outs, attention_mask, position_ids = (
608
+ inps.to(dev),
609
+ outs.to(dev),
610
+ attention_mask.to(dev) if attention_mask is not None else None,
611
+ position_ids.to(dev) if position_ids is not None else None,
612
+ )
613
+
614
+ # collect the importance scores
615
+ linear_layers = cast(
616
+ Dict[str, LoSparseLinear],
617
+ find_linear_layers(layer, layers=[LoSparseLinear]),
618
+ )
619
+
620
+ # register hooks to collect the importance scores
621
+ def get_hook_fn(linear: LoSparseLinear):
622
+ hook_fn = self._variants_hook_mapping[self.variant](linear)
623
+ return hook_fn
624
+
625
+ hooks = {}
626
+ handles: List[torch.utils.hooks.RemovableHandle] = []
627
+ for name, linear in linear_layers.items():
628
+ hook_fn = get_hook_fn(linear)
629
+ hooks[name] = hook_fn
630
+ handles.append(linear.register_forward_hook(hook_fn))
631
+
632
+ with torch.no_grad():
633
+ for j in range(self.nsamples):
634
+ outs[j] = layer(
635
+ inps[j].unsqueeze(0),
636
+ attention_mask=attention_mask,
637
+ position_ids=position_ids,
638
+ )[0]
639
+
640
+ # compute the importance scores and remove the hooks
641
+ metrics = {}
642
+ for name, hook in hooks.items():
643
+ metrics[name] = hook.compute()
644
+ for h in handles:
645
+ h.remove()
646
+
647
+ # prune the weights based on the importance scores
648
+ for name, linear in linear_layers.items():
649
+ log.info(f"Pruning {name}")
650
+ W = linear.weight.data.clone()
651
+ if self.prune_type == PruningType.UNSTRUCTURED:
652
+ _, pruned_weights = unstructured_magnitude_prune_(
653
+ linear.weight.data,
654
+ metrics[name],
655
+ sparsity_ratio=self.sparsity_ratio,
656
+ return_pruned_weight=True,
657
+ )
658
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
659
+ _, pruned_weights = semistructured_magnitude_prune_(
660
+ linear.weight.data,
661
+ metrics[name],
662
+ n=self.n,
663
+ m=self.m,
664
+ return_pruned_weight=True,
665
+ )
666
+ else:
667
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
668
+ self.check_sparsity(linear.weight)
669
+ mask = linear.weight != 0
670
+ linear.weight.data = PCP_search_with_mask(
671
+ W, mask, T_max=self.num_iterations
672
+ )
673
+ self.extract_low_rank_part_using_pruned_(linear, W - linear.weight)
674
+ linear.skip_lowrank = False
675
+
676
+ # compute the input to the next layer
677
+ with torch.no_grad():
678
+ for j in range(self.nsamples):
679
+ outs[j] = layer(
680
+ inps[j].unsqueeze(0),
681
+ attention_mask=attention_mask,
682
+ position_ids=position_ids,
683
+ )[0]
684
+ inps, outs = outs, inps
685
+
686
+
687
+ class IterativeSparseLoForLlama(SparseLoForLlama):
688
+ "Iterative Weight Update"
689
+
690
+ _config_mapping = SparseLoForLlama._config_mapping | {
691
+ "num_iterations": "num_iterations",
692
+ }
693
+
694
+ def __init__(self, num_iterations: int, **kwargs):
695
+ super().__init__(**kwargs)
696
+ self.num_iterations = num_iterations
697
+
698
+ @override
699
+ def run(self, modelpool):
700
+ if self.seed is not None:
701
+ L.seed_everything(self.seed)
702
+
703
+ # load pre-trained model or the first model in the pool
704
+ with self.profile("load_model"):
705
+ model = modelpool.load_pretrained_or_first_model()
706
+ model.seqlen = model.config.max_position_embeddings
707
+ tokenizer = modelpool.load_tokenizer(use_fast=False)
708
+
709
+ if not isinstance(model, (LlamaForCausalLM,)):
710
+ log.warning(f"Model type {type(model)} may not supported.")
711
+
712
+ if self.variant in self._variants_requires_calibration_data:
713
+ inps, outs, attention_mask, position_ids = self.prepare_calibration_data(
714
+ model, tokenizer
715
+ )
716
+
717
+ model = convert_to_losparse_llama(model, rank=self.rank)
718
+ gc.collect()
719
+ if torch.cuda.is_available():
720
+ torch.cuda.empty_cache()
721
+
722
+ for linear in find_linear_layers(model, layers=[LoSparseLinear]).values():
723
+ linear = cast(LoSparseLinear, linear)
724
+ linear.lo_A.data.zero_()
725
+ linear.lo_B.data.zero_()
726
+ linear.skip_lowrank = True
727
+
728
+ match self.variant:
729
+ case "dense":
730
+ # this variant is a no-op, just for debug the conversion
731
+ pass
732
+ case "lowrank-only":
733
+ self.extract_low_rank_parts_(model)
734
+ self.set_weights_to_zeros_(model)
735
+ case "random":
736
+ self.iterative_random_prune_(model)
737
+ case "magnitude":
738
+ self.iterative_magnitude_prune_(model)
739
+ case variant if variant in self._variants_requires_calibration_data:
740
+ self.iterative_prune_using_calibration_data_(
741
+ model,
742
+ inps=inps,
743
+ outs=outs,
744
+ attention_mask=attention_mask,
745
+ position_ids=position_ids,
746
+ )
747
+ case _:
748
+ raise ValueError(f"Invalid variant: {self.variant}")
749
+
750
+ if self.model_save_path is not None:
751
+ with timeit_context(f"Saving the model to {self.model_save_path}"):
752
+ tokenizer.save_pretrained(self.model_save_path)
753
+ model.save_pretrained(self.model_save_path)
754
+
755
+ return model
756
+
757
+ @torch.no_grad()
758
+ def iterative_random_prune_(self, model):
759
+ layers: nn.ModuleList = model.model.layers
760
+ for layer_idx, layer in tqdm(
761
+ list(enumerate(layers)),
762
+ "Pruning Layers",
763
+ dynamic_ncols=True,
764
+ ):
765
+ for name, linear in layer.named_modules():
766
+ if isinstance(linear, LoSparseLinear):
767
+ log.info(f"Pruning {name}, set weights to zeros")
768
+ W = linear.weight.data.clone()
769
+ if self.prune_type == PruningType.UNSTRUCTURED:
770
+ unstructured_magnitude_prune_(
771
+ linear.weight.data,
772
+ metric_function_or_scores=torch.rand_like,
773
+ sparsity_ratio=self.sparsity_ratio,
774
+ )
775
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
776
+ semistructured_magnitude_prune_(
777
+ linear.weight.data,
778
+ metric_function_or_scores=torch.rand_like,
779
+ n=self.n,
780
+ m=self.m,
781
+ )
782
+ else:
783
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
784
+ self.check_sparsity(linear.weight)
785
+ mask = linear.weight != 0
786
+ for rank in tqdm(
787
+ np.linspace(1, self.rank, self.num_iterations, dtype=np.int64),
788
+ "Iterative Pruning",
789
+ leave=False,
790
+ dynamic_ncols=True,
791
+ ):
792
+ linear.weight.data, specturm_ratio = iterative_weight_update(
793
+ W,
794
+ linear.weight,
795
+ mask,
796
+ rank=rank,
797
+ )
798
+ if specturm_ratio > 0.99:
799
+ break
800
+ self.extract_low_rank_part_using_pruned_(linear, W - linear.weight)
801
+
802
+ @torch.no_grad()
803
+ def iterative_magnitude_prune_(self, model):
804
+ layers: nn.ModuleList = model.model.layers
805
+ for layer_idx, layer in tqdm(
806
+ enumerate(layers), "Pruning Layers", total=len(layers), dynamic_ncols=True
807
+ ):
808
+ for name, linear in layer.named_modules():
809
+ if isinstance(linear, LoSparseLinear):
810
+ log.info(f"Magnitude Pruning {name}")
811
+ W = linear.weight.data.clone()
812
+ if self.prune_type == PruningType.UNSTRUCTURED:
813
+ unstructured_magnitude_prune_(
814
+ linear.weight.data,
815
+ metric_function_or_scores=torch.abs,
816
+ sparsity_ratio=self.sparsity_ratio,
817
+ )
818
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
819
+ semistructured_magnitude_prune_(
820
+ linear.weight.data,
821
+ metric_function_or_scores=torch.abs,
822
+ n=self.n,
823
+ m=self.m,
824
+ )
825
+ else:
826
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
827
+ self.check_sparsity(linear.weight)
828
+ mask = linear.weight != 0
829
+ for rank in tqdm(
830
+ np.linspace(1, self.rank, self.num_iterations, dtype=np.int64),
831
+ "Iterative Pruning",
832
+ leave=False,
833
+ dynamic_ncols=True,
834
+ ):
835
+ linear.weight.data, specturm_ratio = iterative_weight_update(
836
+ W,
837
+ linear.weight,
838
+ mask,
839
+ rank=rank,
840
+ )
841
+ if specturm_ratio > 0.99:
842
+ break
843
+ self.extract_low_rank_part_using_pruned_(linear, W - linear.weight)
844
+
845
+ @torch.no_grad()
846
+ def iterative_prune_using_calibration_data_(
847
+ self,
848
+ model: LoSparseLlamaForCausalLM,
849
+ *,
850
+ inps: Tensor,
851
+ outs: Tensor,
852
+ attention_mask: Optional[Tensor],
853
+ position_ids: Optional[Tensor],
854
+ ):
855
+ layers = model.model.layers
856
+ for layer_idx, layer in tqdm(
857
+ enumerate(layers),
858
+ "Pruning Layers",
859
+ total=len(layers),
860
+ dynamic_ncols=True,
861
+ ):
862
+ if (
863
+ hasattr(model, "hf_device_map")
864
+ and f"model.layers.{layer_idx}" in model.hf_device_map
865
+ ): ## handle the case for llama-30B and llama-65B, when the device map has multiple GPUs;
866
+ dev = model.hf_device_map[f"model.layers.{layer_idx}"]
867
+ inps, outs, attention_mask, position_ids = (
868
+ inps.to(dev),
869
+ outs.to(dev),
870
+ attention_mask.to(dev) if attention_mask is not None else None,
871
+ position_ids.to(dev) if position_ids is not None else None,
872
+ )
873
+
874
+ # collect the importance scores
875
+ linear_layers = cast(
876
+ Dict[str, LoSparseLinear],
877
+ find_linear_layers(layer, layers=[LoSparseLinear]),
878
+ )
879
+
880
+ # register hooks to collect the importance scores
881
+ def get_hook_fn(linear: LoSparseLinear):
882
+ hook_fn = self._variants_hook_mapping[self.variant](linear)
883
+ return hook_fn
884
+
885
+ hooks = {}
886
+ handles: List[torch.utils.hooks.RemovableHandle] = []
887
+ for name, linear in linear_layers.items():
888
+ hook_fn = get_hook_fn(linear)
889
+ hooks[name] = hook_fn
890
+ handles.append(linear.register_forward_hook(hook_fn))
891
+
892
+ with torch.no_grad():
893
+ for j in range(self.nsamples):
894
+ outs[j] = layer(
895
+ inps[j].unsqueeze(0),
896
+ attention_mask=attention_mask,
897
+ position_ids=position_ids,
898
+ )[0]
899
+
900
+ # compute the importance scores and remove the hooks
901
+ metrics = {}
902
+ for name, hook in hooks.items():
903
+ metrics[name] = hook.compute()
904
+ for h in handles:
905
+ h.remove()
906
+
907
+ # prune the weights based on the importance scores
908
+ for name, linear in linear_layers.items():
909
+ log.info(f"Pruning {name}")
910
+ W = linear.weight.data.clone()
911
+ if self.prune_type == PruningType.UNSTRUCTURED:
912
+ _, pruned_weights = unstructured_magnitude_prune_(
913
+ linear.weight.data,
914
+ metrics[name],
915
+ sparsity_ratio=self.sparsity_ratio,
916
+ return_pruned_weight=True,
917
+ )
918
+ elif self.prune_type == PruningType.SEMISTRUCTURED:
919
+ _, pruned_weights = semistructured_magnitude_prune_(
920
+ linear.weight.data,
921
+ metrics[name],
922
+ n=self.n,
923
+ m=self.m,
924
+ return_pruned_weight=True,
925
+ )
926
+ else:
927
+ raise ValueError(f"Invalid pruning type: {self.prune_type}")
928
+ self.check_sparsity(linear.weight)
929
+ mask = linear.weight != 0
930
+ for rank in tqdm(
931
+ np.linspace(1, self.rank, self.num_iterations, dtype=np.int64),
932
+ "Iterative Pruning",
933
+ leave=False,
934
+ dynamic_ncols=True,
935
+ ):
936
+ linear.weight.data, specturm_ratio = iterative_weight_update(
937
+ W,
938
+ linear.weight,
939
+ mask,
940
+ rank=rank,
941
+ )
942
+ if specturm_ratio > 0.99:
943
+ break
944
+ self.extract_low_rank_part_using_pruned_(linear, W - linear.weight)
945
+ linear.skip_lowrank = False
946
+
947
+ # compute the input to the next layer
948
+ with torch.no_grad():
949
+ for j in range(self.nsamples):
950
+ outs[j] = layer(
951
+ inps[j].unsqueeze(0),
952
+ attention_mask=attention_mask,
953
+ position_ids=position_ids,
954
+ )[0]
955
+ inps, outs = outs, inps