Instructions to use AGENTDARS/Reviewer-14B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use AGENTDARS/Reviewer-14B with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("/home/dars/Qwen2.5-Coder/models/deepseek-14b/") model = PeftModel.from_pretrained(base_model, "AGENTDARS/Reviewer-14B") - Notebooks
- Google Colab
- Kaggle
Upload 34 files
Browse filesFiles changed (34)
- README.md+43-3
- adapter_config.jsonAdded+29
- adapter_model.safetensorsAdded+3
- global_step2000/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
- global_step2000/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
- global_step2000/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
- global_step2000/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
- global_step2000/bf16_zero_pp_rank_4_mp_rank_00_optim_states.ptAdded+3
- global_step2000/bf16_zero_pp_rank_5_mp_rank_00_optim_states.ptAdded+3
- global_step2000/bf16_zero_pp_rank_6_mp_rank_00_optim_states.ptAdded+3
- global_step2000/bf16_zero_pp_rank_7_mp_rank_00_optim_states.ptAdded+3
- global_step2000/zero_pp_rank_0_mp_rank_00_model_states.ptAdded+3
- global_step2000/zero_pp_rank_1_mp_rank_00_model_states.ptAdded+3
- global_step2000/zero_pp_rank_2_mp_rank_00_model_states.ptAdded+3
- global_step2000/zero_pp_rank_3_mp_rank_00_model_states.ptAdded+3
- global_step2000/zero_pp_rank_4_mp_rank_00_model_states.ptAdded+3
- global_step2000/zero_pp_rank_5_mp_rank_00_model_states.ptAdded+3
- global_step2000/zero_pp_rank_6_mp_rank_00_model_states.ptAdded+3
- global_step2000/zero_pp_rank_7_mp_rank_00_model_states.ptAdded+3
- latestAdded+1
- rng_state_0.pthAdded+3
- rng_state_1.pthAdded+3
- rng_state_2.pthAdded+3
- rng_state_3.pthAdded+3
- rng_state_4.pthAdded+3
- rng_state_5.pthAdded+3
- rng_state_6.pthAdded+3
- rng_state_7.pthAdded+3
- special_tokens_map.jsonAdded+27
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+223
- trainer_state.jsonAdded+653
- training_args.binAdded+3
- zero_to_fp32.pyAdded+604
123---license: cc-by-4.0---12345678910111213141516171819202122232425262728293031323334353637383940414243---base_model: deepseek-ai/DeepSeek-R1-Distill-Qwen-14Blibrary_name: peft---# Model Card for Reviewer-14B## Model Details### Model DescriptionReviewer-14B is a fine-tuned on [**DeepSeek-R1-Distill-Qwen-14B**](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-14B), optimized for selecting the best patch among multiple patches generated by our DARS agent while solving software engineering problems.### Model Sources- **Repository:** [DARS-14B Repository](https://github.com/darsagent/DARS-Agent)- **Paper:** ["DARS: Dynamic Action Re-Sampling to Enhance Coding Agent Performance by Adaptive Tree Traversal"](https://drive.google.com/file/d/1DMAZ-fkirC8uKl8819cOq9J3BQ4E7GXR/view?usp=drive_link)## How to Get Started with the ModelWe use vLLM to deploy and infer the model. Please follow this tutorial [here]((https://docs.vllm.ai/en/latest/features/lora.html)) to use our LoRA weights with vLLM.## Training Details### DatasetWe use our [code review dataset](https://huggingface.co/datasets/AGENTDARS/generated-critiques) where each instance contains several git patches with critiques for each each patch. The model learns to generate critiques for multiple patches and select the best patch.### Training Procedure| Hyperparameter | Value ||----------------------|--------------------------------------------|| Training regime | BF16 mixed precision || Optimizer | AdamW with cosine learning rate scheduler || LoRA Configuration | rank=8, alpha=32, dropout=0.1 || Batch Size | 48 || Learning Rate | 5e-6 || Sequence Length | 14K tokens || Fine-tuning Epochs | 1 || Compute Environment | DeepSpeed for memory-efficient distributed training || Compute Infrastructure | 8x H100 |## ResultsUsing this model as a reviewer with DARS trajectories generated using Claude 3.5 Sonnet V2 achieves 41.7% on SWE-Bench Lite.
1234567891011121314151617181920212223242526272829{ "alpha_pattern": {}, "auto_mapping": null, "base_model_name_or_path": "/home/dars/Qwen2.5-Coder/models/deepseek-14b/", "bias": "none", "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layer_replication": null, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 32, "lora_dropout": 0.1, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "peft_type": "LORA", "r": 8, "rank_pattern": {}, "revision": null, "target_modules": [ "q_proj", "v_proj" ], "task_type": "CAUSAL_LM", "use_dora": false, "use_rslora": false}123version https://git-lfs.github.com/spec/v1oid sha256:157c15152bce8e797dfa01f6e466d29429fa6c83df9d2278c90f23d4b64ebae9size 12608496123version https://git-lfs.github.com/spec/v1oid sha256:2f8a8aad76113e84b54cf7d3c303a9b19125ac980c9f3bc26ff48c123355f41fsize 9440912123version https://git-lfs.github.com/spec/v1oid sha256:3a92407e6c77b137b11809a3d6e3332ce01c6b44dfaf906f931ed6c37da568fbsize 9440912123version https://git-lfs.github.com/spec/v1oid sha256:d3b8fad66457b17e20b005a16d3afbbe7284aa4191b7e41d4141687f8cebb058size 9440912123version https://git-lfs.github.com/spec/v1oid sha256:d8c9401c5e7a03c7880f43bb7a862a7b82063f8bfa147b366a529d8c44eb396esize 9440912123version https://git-lfs.github.com/spec/v1oid sha256:e116b3abfbf167542dfb4cf1d05cf724f6e395d41ec236218a47882a54b3a1c1size 9440912123version https://git-lfs.github.com/spec/v1oid sha256:5027c1fa90f40b1c4b9649b6e2a7a4f9e64ac55c5845b383e4fcbf78c499c4c8size 9440912123version https://git-lfs.github.com/spec/v1oid sha256:d2b4a4f5b2c0add41f7b9471da74ca7340ae888ae11ac5ab60be2bcc1b2857b9size 9440912123version https://git-lfs.github.com/spec/v1oid sha256:2f761562e37a8fb2fc45449f1efdb2898b0ed05d1a200f27e9d6d9ec426137e5size 9440912123version https://git-lfs.github.com/spec/v1oid sha256:b3be128cab192df1962334a33f6aaab5f0b2e506c62a5a20dd9ce97c8e7b5cb4size 228398123version https://git-lfs.github.com/spec/v1oid sha256:463d30b2fb4f41dafe42c4f4bb16db903a7fb192b056f3615bc84331c7d912c9size 228398123version https://git-lfs.github.com/spec/v1oid sha256:d1969eb6fe91040b1904eeecfcf4cf5918ca5bde4906b9a453d30f3958a357b3size 228398123version https://git-lfs.github.com/spec/v1oid sha256:2315308eca50010ad291aa15be29979a4ff7517c31afaabc9965f892e6087863size 228398123version https://git-lfs.github.com/spec/v1oid sha256:329e7389a9356d81428ca5cca5914e87c2c252fa101b8dac3b0fc86bf61dbf80size 228398123version https://git-lfs.github.com/spec/v1oid sha256:d108ae6ebfd137dd064635fe64a9abf2031a45ee99359cd357c5f5359a8d5305size 228398123version https://git-lfs.github.com/spec/v1oid sha256:f6f10280fac8ea18a1b9716f90c4f21ebd1c17f3ec585294a20dee201700ff98size 228398123version https://git-lfs.github.com/spec/v1oid sha256:9a5782a01e1ef7abdf7d083035263a60a8a479ba17ec06304cbc0426ba3f45fcsize 2283981global_step2000123version https://git-lfs.github.com/spec/v1oid sha256:e832b43e588d740d3f07dc0a44d65ab5ce8a3e06e28c23014052b0ba2d54ad21size 15920123version https://git-lfs.github.com/spec/v1oid sha256:3d09ac95eeabbb6f44c57a6d15a7dab491542295abbb790c351f496fb5ad3319size 15920123version https://git-lfs.github.com/spec/v1oid sha256:53cb30810e690ff974d7d060095a4a9fb8587590bff41323eb6ee094f71c9647size 15920123version https://git-lfs.github.com/spec/v1oid sha256:06a8c290881b49fb26b7e3876ab4e6409d7506a8d64bd0d3b4e2479e976e5faesize 15920123version https://git-lfs.github.com/spec/v1oid sha256:7e3bd90ae12b6576ffc76b434c14036de3a16c05721e44bcb23fc3b67101e66asize 15920123version https://git-lfs.github.com/spec/v1oid sha256:2b59c3b71c7beadeea672b59b1f0f6c37896012b23b5763cd194fabf9fc01b41size 15920123version https://git-lfs.github.com/spec/v1oid sha256:76b9e1212c0a9b1c0778a79289f15e73c750fd9510950ae55fdd47b4db37c7a4size 15920123version https://git-lfs.github.com/spec/v1oid sha256:00814da94919dc36b80b7dc43dd9e7f49c59fd651eadb84f772bdf9598171438size 15920123456789101112131415161718192021222324252627{ "additional_special_tokens": [ { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false } ], "bos_token": { "content": "<|begin▁of▁sentence|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": "<|im_end|>", "pad_token": "<|endoftext|>"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223{ "add_bos_token": true, "add_eos_token": false, "added_tokens_decoder": { "151643": { "content": "<|end▁of▁sentence|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151644": { "content": "<|User|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151645": { "content": "<|Assistant|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151646": { "content": "<|begin▁of▁sentence|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151647": { "content": "<|EOT|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151648": { "content": "<think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151649": { "content": "</think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151650": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151651": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151652": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151653": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151654": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151655": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151656": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151657": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151658": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151659": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151660": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151661": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151662": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151663": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151664": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151665": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151666": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151667": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "<|im_end|>", "<|im_start|>" ], "bos_token": "<|begin▁of▁sentence|>", "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='') %}{%- for message in messages %}{%- if message['role'] == 'system' %}{% set ns.system_prompt = message['content'] %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{% set content = message['content'] %}{% if '</think>' in content %}{% set content = content.split('</think>')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>'}}{% endif %}", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "legacy": true, "model_max_length": 14000, "pad_token": "<|endoftext|>", "padding_side": "right", "sp_model_kwargs": {}, "tokenizer_class": "LlamaTokenizer", "truncation": true, "unk_token": null, "use_default_system_prompt": false}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653{ "best_metric": null, "best_model_checkpoint": null, "epoch": 0.5482456140350878, "eval_steps": 500, "global_step": 2000, "is_hyper_param_search": false, "is_local_process_zero": true, "is_world_process_zero": true, "log_history": [ { "epoch": 0.005482456140350877, "learning_rate": 3.2525749891599526e-06, "loss": 1.627, "step": 20 }, { "epoch": 0.010964912280701754, "learning_rate": 4.0051499783199055e-06, "loss": 1.6081, "step": 40 }, { "epoch": 0.01644736842105263, "learning_rate": 4.445378125959108e-06, "loss": 1.587, "step": 60 }, { "epoch": 0.021929824561403508, "learning_rate": 4.757724967479858e-06, "loss": 1.5592, "step": 80 }, { "epoch": 0.027412280701754384, "learning_rate": 4.9999999999999996e-06, "loss": 1.5009, "step": 100 }, { "epoch": 0.03289473684210526, "learning_rate": 4.9756410256410255e-06, "loss": 1.4438, "step": 120 }, { "epoch": 0.03837719298245614, "learning_rate": 4.95e-06, "loss": 1.3777, "step": 140 }, { "epoch": 0.043859649122807015, "learning_rate": 4.9243589743589745e-06, "loss": 1.3215, "step": 160 }, { "epoch": 0.049342105263157895, "learning_rate": 4.898717948717949e-06, "loss": 1.267, "step": 180 }, { "epoch": 0.05482456140350877, "learning_rate": 4.8730769230769235e-06, "loss": 1.2095, "step": 200 }, { "epoch": 0.06030701754385965, "learning_rate": 4.847435897435897e-06, "loss": 1.1684, "step": 220 }, { "epoch": 0.06578947368421052, "learning_rate": 4.821794871794872e-06, "loss": 1.1054, "step": 240 }, { "epoch": 0.0712719298245614, "learning_rate": 4.796153846153846e-06, "loss": 1.0593, "step": 260 }, { "epoch": 0.07675438596491228, "learning_rate": 4.770512820512821e-06, "loss": 1.0069, "step": 280 }, { "epoch": 0.08223684210526316, "learning_rate": 4.744871794871795e-06, "loss": 0.9498, "step": 300 }, { "epoch": 0.08771929824561403, "learning_rate": 4.71923076923077e-06, "loss": 0.8949, "step": 320 }, { "epoch": 0.09320175438596491, "learning_rate": 4.693589743589744e-06, "loss": 0.8369, "step": 340 }, { "epoch": 0.09868421052631579, "learning_rate": 4.667948717948718e-06, "loss": 0.8047, "step": 360 }, { "epoch": 0.10416666666666667, "learning_rate": 4.642307692307692e-06, "loss": 0.781, "step": 380 }, { "epoch": 0.10964912280701754, "learning_rate": 4.616666666666667e-06, "loss": 0.7535, "step": 400 }, { "epoch": 0.11513157894736842, "learning_rate": 4.591025641025641e-06, "loss": 0.7332, "step": 420 }, { "epoch": 0.1206140350877193, "learning_rate": 4.565384615384616e-06, "loss": 0.7171, "step": 440 }, { "epoch": 0.12609649122807018, "learning_rate": 4.53974358974359e-06, "loss": 0.7074, "step": 460 }, { "epoch": 0.13157894736842105, "learning_rate": 4.514102564102564e-06, "loss": 0.6905, "step": 480 }, { "epoch": 0.13706140350877194, "learning_rate": 4.4884615384615384e-06, "loss": 0.6812, "step": 500 }, { "epoch": 0.13706140350877194, "eval_loss": 0.6900227665901184, "eval_runtime": 7.1872, "eval_samples_per_second": 13.635, "eval_steps_per_second": 1.809, "step": 500 }, { "epoch": 0.1425438596491228, "learning_rate": 4.462820512820513e-06, "loss": 0.6753, "step": 520 }, { "epoch": 0.14802631578947367, "learning_rate": 4.437179487179487e-06, "loss": 0.6637, "step": 540 }, { "epoch": 0.15350877192982457, "learning_rate": 4.411538461538462e-06, "loss": 0.6615, "step": 560 }, { "epoch": 0.15899122807017543, "learning_rate": 4.385897435897436e-06, "loss": 0.6547, "step": 580 }, { "epoch": 0.16447368421052633, "learning_rate": 4.36025641025641e-06, "loss": 0.6487, "step": 600 }, { "epoch": 0.1699561403508772, "learning_rate": 4.3346153846153846e-06, "loss": 0.6441, "step": 620 }, { "epoch": 0.17543859649122806, "learning_rate": 4.308974358974359e-06, "loss": 0.6358, "step": 640 }, { "epoch": 0.18092105263157895, "learning_rate": 4.2833333333333335e-06, "loss": 0.636, "step": 660 }, { "epoch": 0.18640350877192982, "learning_rate": 4.257692307692308e-06, "loss": 0.6326, "step": 680 }, { "epoch": 0.19188596491228072, "learning_rate": 4.2320512820512825e-06, "loss": 0.6246, "step": 700 }, { "epoch": 0.19736842105263158, "learning_rate": 4.206410256410256e-06, "loss": 0.6237, "step": 720 }, { "epoch": 0.20285087719298245, "learning_rate": 4.180769230769231e-06, "loss": 0.6203, "step": 740 }, { "epoch": 0.20833333333333334, "learning_rate": 4.155128205128205e-06, "loss": 0.6164, "step": 760 }, { "epoch": 0.2138157894736842, "learning_rate": 4.12948717948718e-06, "loss": 0.6118, "step": 780 }, { "epoch": 0.21929824561403508, "learning_rate": 4.103846153846154e-06, "loss": 0.6101, "step": 800 }, { "epoch": 0.22478070175438597, "learning_rate": 4.078205128205129e-06, "loss": 0.6092, "step": 820 }, { "epoch": 0.23026315789473684, "learning_rate": 4.052564102564102e-06, "loss": 0.6039, "step": 840 }, { "epoch": 0.23574561403508773, "learning_rate": 4.026923076923077e-06, "loss": 0.5989, "step": 860 }, { "epoch": 0.2412280701754386, "learning_rate": 4.001282051282051e-06, "loss": 0.5979, "step": 880 }, { "epoch": 0.24671052631578946, "learning_rate": 3.975641025641026e-06, "loss": 0.5965, "step": 900 }, { "epoch": 0.25219298245614036, "learning_rate": 3.95e-06, "loss": 0.5969, "step": 920 }, { "epoch": 0.2576754385964912, "learning_rate": 3.924358974358975e-06, "loss": 0.5902, "step": 940 }, { "epoch": 0.2631578947368421, "learning_rate": 3.8987179487179484e-06, "loss": 0.5909, "step": 960 }, { "epoch": 0.26864035087719296, "learning_rate": 3.873076923076923e-06, "loss": 0.5914, "step": 980 }, { "epoch": 0.2741228070175439, "learning_rate": 3.8474358974358974e-06, "loss": 0.589, "step": 1000 }, { "epoch": 0.2741228070175439, "eval_loss": 0.5962496399879456, "eval_runtime": 6.5411, "eval_samples_per_second": 14.982, "eval_steps_per_second": 1.987, "step": 1000 }, { "epoch": 0.27960526315789475, "learning_rate": 3.821794871794872e-06, "loss": 0.5844, "step": 1020 }, { "epoch": 0.2850877192982456, "learning_rate": 3.7961538461538464e-06, "loss": 0.5819, "step": 1040 }, { "epoch": 0.2905701754385965, "learning_rate": 3.770512820512821e-06, "loss": 0.5828, "step": 1060 }, { "epoch": 0.29605263157894735, "learning_rate": 3.744871794871795e-06, "loss": 0.5816, "step": 1080 }, { "epoch": 0.30153508771929827, "learning_rate": 3.7192307692307695e-06, "loss": 0.5773, "step": 1100 }, { "epoch": 0.30701754385964913, "learning_rate": 3.693589743589744e-06, "loss": 0.5782, "step": 1120 }, { "epoch": 0.3125, "learning_rate": 3.6679487179487185e-06, "loss": 0.5774, "step": 1140 }, { "epoch": 0.31798245614035087, "learning_rate": 3.642307692307693e-06, "loss": 0.5733, "step": 1160 }, { "epoch": 0.32346491228070173, "learning_rate": 3.616666666666667e-06, "loss": 0.5722, "step": 1180 }, { "epoch": 0.32894736842105265, "learning_rate": 3.591025641025641e-06, "loss": 0.569, "step": 1200 }, { "epoch": 0.3344298245614035, "learning_rate": 3.5653846153846156e-06, "loss": 0.5699, "step": 1220 }, { "epoch": 0.3399122807017544, "learning_rate": 3.53974358974359e-06, "loss": 0.5691, "step": 1240 }, { "epoch": 0.34539473684210525, "learning_rate": 3.5141025641025646e-06, "loss": 0.5706, "step": 1260 }, { "epoch": 0.3508771929824561, "learning_rate": 3.488461538461539e-06, "loss": 0.565, "step": 1280 }, { "epoch": 0.35635964912280704, "learning_rate": 3.462820512820513e-06, "loss": 0.5652, "step": 1300 }, { "epoch": 0.3618421052631579, "learning_rate": 3.4371794871794873e-06, "loss": 0.5631, "step": 1320 }, { "epoch": 0.3673245614035088, "learning_rate": 3.4115384615384617e-06, "loss": 0.5652, "step": 1340 }, { "epoch": 0.37280701754385964, "learning_rate": 3.3858974358974362e-06, "loss": 0.5627, "step": 1360 }, { "epoch": 0.3782894736842105, "learning_rate": 3.3602564102564107e-06, "loss": 0.5662, "step": 1380 }, { "epoch": 0.38377192982456143, "learning_rate": 3.3346153846153852e-06, "loss": 0.5606, "step": 1400 }, { "epoch": 0.3892543859649123, "learning_rate": 3.3089743589743593e-06, "loss": 0.5616, "step": 1420 }, { "epoch": 0.39473684210526316, "learning_rate": 3.2833333333333334e-06, "loss": 0.5624, "step": 1440 }, { "epoch": 0.40021929824561403, "learning_rate": 3.257692307692308e-06, "loss": 0.5578, "step": 1460 }, { "epoch": 0.4057017543859649, "learning_rate": 3.2320512820512824e-06, "loss": 0.5577, "step": 1480 }, { "epoch": 0.41118421052631576, "learning_rate": 3.206410256410257e-06, "loss": 0.5586, "step": 1500 }, { "epoch": 0.41118421052631576, "eval_loss": 0.5718954801559448, "eval_runtime": 6.5348, "eval_samples_per_second": 14.997, "eval_steps_per_second": 1.989, "step": 1500 }, { "epoch": 0.4166666666666667, "learning_rate": 3.1807692307692314e-06, "loss": 0.5603, "step": 1520 }, { "epoch": 0.42214912280701755, "learning_rate": 3.1551282051282054e-06, "loss": 0.5567, "step": 1540 }, { "epoch": 0.4276315789473684, "learning_rate": 3.1294871794871795e-06, "loss": 0.5565, "step": 1560 }, { "epoch": 0.4331140350877193, "learning_rate": 3.103846153846154e-06, "loss": 0.552, "step": 1580 }, { "epoch": 0.43859649122807015, "learning_rate": 3.0782051282051285e-06, "loss": 0.5553, "step": 1600 }, { "epoch": 0.4440789473684211, "learning_rate": 3.052564102564103e-06, "loss": 0.5528, "step": 1620 }, { "epoch": 0.44956140350877194, "learning_rate": 3.0269230769230775e-06, "loss": 0.5446, "step": 1640 }, { "epoch": 0.4550438596491228, "learning_rate": 3.0012820512820516e-06, "loss": 0.5525, "step": 1660 }, { "epoch": 0.4605263157894737, "learning_rate": 2.9756410256410256e-06, "loss": 0.5504, "step": 1680 }, { "epoch": 0.46600877192982454, "learning_rate": 2.95e-06, "loss": 0.5528, "step": 1700 }, { "epoch": 0.47149122807017546, "learning_rate": 2.9243589743589746e-06, "loss": 0.5502, "step": 1720 }, { "epoch": 0.4769736842105263, "learning_rate": 2.898717948717949e-06, "loss": 0.5512, "step": 1740 }, { "epoch": 0.4824561403508772, "learning_rate": 2.8730769230769236e-06, "loss": 0.5476, "step": 1760 }, { "epoch": 0.48793859649122806, "learning_rate": 2.8474358974358977e-06, "loss": 0.5489, "step": 1780 }, { "epoch": 0.4934210526315789, "learning_rate": 2.8217948717948718e-06, "loss": 0.5522, "step": 1800 }, { "epoch": 0.49890350877192985, "learning_rate": 2.7961538461538463e-06, "loss": 0.5463, "step": 1820 }, { "epoch": 0.5043859649122807, "learning_rate": 2.7705128205128208e-06, "loss": 0.5498, "step": 1840 }, { "epoch": 0.5098684210526315, "learning_rate": 2.7448717948717953e-06, "loss": 0.5437, "step": 1860 }, { "epoch": 0.5153508771929824, "learning_rate": 2.7192307692307697e-06, "loss": 0.5477, "step": 1880 }, { "epoch": 0.5208333333333334, "learning_rate": 2.693589743589744e-06, "loss": 0.5464, "step": 1900 }, { "epoch": 0.5263157894736842, "learning_rate": 2.667948717948718e-06, "loss": 0.5421, "step": 1920 }, { "epoch": 0.5317982456140351, "learning_rate": 2.6423076923076924e-06, "loss": 0.5451, "step": 1940 }, { "epoch": 0.5372807017543859, "learning_rate": 2.616666666666667e-06, "loss": 0.545, "step": 1960 }, { "epoch": 0.5427631578947368, "learning_rate": 2.5910256410256414e-06, "loss": 0.5416, "step": 1980 }, { "epoch": 0.5482456140350878, "learning_rate": 2.565384615384616e-06, "loss": 0.5378, "step": 2000 }, { "epoch": 0.5482456140350878, "eval_loss": 0.5599762797355652, "eval_runtime": 6.5788, "eval_samples_per_second": 14.896, "eval_steps_per_second": 1.976, "step": 2000 } ], "logging_steps": 20, "max_steps": 4000, "num_input_tokens_seen": 0, "num_train_epochs": 2, "save_steps": 500, "total_flos": 4034749748215808.0, "train_batch_size": 6, "trial_name": null, "trial_params": null}123version https://git-lfs.github.com/spec/v1oid sha256:b1666fb8227e6013863ea69147019d309d9fc5bb193cba9a4f7ddb486b04d057size 7224123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604#!/usr/bin/env python
# Copyright (c) Microsoft Corporation.# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in# the future. Once extracted, the weights don't require DeepSpeed and can be used in any# application.## example: python zero_to_fp32.py . pytorch_model.bin
import argparseimport torchimport globimport mathimport osimport refrom collections import OrderedDictfrom dataclasses import dataclass
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with# DeepSpeed data structures it has to be available in the current python environment.from deepspeed.utils import loggerfrom deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS, FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES, FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
@dataclassclass zero_model_state: buffers: dict() param_shapes: dict() shared_params: list ds_version: int frozen_param_shapes: dict() frozen_param_fragments: dict()
debug = 0
# load to cpudevice = torch.device('cpu')
def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_model_state_file(checkpoint_dir, zero_stage): if not os.path.isdir(checkpoint_dir): raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
# there should be only one file if zero_stage <= 2: file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt") elif zero_stage == 3: file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
if not os.path.exists(file): raise FileNotFoundError(f"can't find model states file at '{file}'")
return file
def get_checkpoint_files(checkpoint_dir, glob_pattern): # XXX: need to test that this simple glob rule works for multi-node setup too ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
if len(ckpt_files) == 0: raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
return ckpt_files
def get_optim_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
def get_model_state_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
def parse_model_states(files): zero_model_states = [] for file in files: state_dict = torch.load(file, map_location=device)
if BUFFER_NAMES not in state_dict: raise ValueError(f"{file} is not a model state checkpoint") buffer_names = state_dict[BUFFER_NAMES] if debug: print("Found buffers:", buffer_names)
# recover just the buffers while restoring them to fp32 if they were saved in fp16 buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names} param_shapes = state_dict[PARAM_SHAPES]
# collect parameters that are included in param_shapes param_names = [] for s in param_shapes: for name in s.keys(): param_names.append(name)
# update with frozen parameters frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None) if frozen_param_shapes is not None: if debug: print(f"Found frozen_param_shapes: {frozen_param_shapes}") param_names += list(frozen_param_shapes.keys())
# handle shared params shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
ds_version = state_dict.get(DS_VERSION, None)
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
z_model_state = zero_model_state(buffers=buffers, param_shapes=param_shapes, shared_params=shared_params, ds_version=ds_version, frozen_param_shapes=frozen_param_shapes, frozen_param_fragments=frozen_param_fragments) zero_model_states.append(z_model_state)
return zero_model_states
def parse_optim_states(files, ds_checkpoint_dir):
total_files = len(files) state_dicts = [] for f in files: state_dict = torch.load(f, map_location=device) # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights # and also handle the case where it was already removed by another helper script state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None) state_dicts.append(state_dict)
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]: raise ValueError(f"{files[0]} is not a zero checkpoint") zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE] world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert # parameters can be different from data parallelism for non-expert parameters. So we can just # use the max of the partition_count to get the dp world_size.
if type(world_size) is list: world_size = max(world_size)
if world_size != total_files: raise ValueError( f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. " "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes." )
# the groups are named differently in each stage if zero_stage <= 2: fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS elif zero_stage == 3: fp32_groups_key = FP32_FLAT_GROUPS else: raise ValueError(f"unknown zero stage {zero_stage}")
if zero_stage <= 2: fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))] elif zero_stage == 3: # if there is more than one param group, there will be multiple flattened tensors - one # flattened tensor per group - for simplicity merge them into a single tensor # # XXX: could make the script more memory efficient for when there are multiple groups - it # will require matching the sub-lists of param_shapes for each param group flattened tensor
fp32_flat_groups = [ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts)) ]
return zero_stage, world_size, fp32_flat_groups
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters): """ Returns fp32 state_dict reconstructed from ds checkpoint
Args: - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
""" print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
optim_files = get_optim_files(ds_checkpoint_dir) zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir) print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
model_files = get_model_state_files(ds_checkpoint_dir)
zero_model_states = parse_model_states(model_files) print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
if zero_stage <= 2: return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters) elif zero_stage == 3: return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters)
def _zero2_merge_frozen_params(state_dict, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
frozen_param_shapes = zero_model_states[0].frozen_param_shapes frozen_param_fragments = zero_model_states[0].frozen_param_fragments
if debug: num_elem = sum(s.numel() for s in frozen_param_shapes.values()) print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in frozen_param_fragments.values()]) print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
state_dict[name] = frozen_param_fragments[name]
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _has_callable(obj, fn): attr = getattr(obj, fn, None) return callable(attr)
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes
# Reconstruction protocol: # # XXX: document this
if debug: for i in range(world_size): for j in range(len(fp32_flat_groups[0])): print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
# XXX: memory usage doubles here (zero2) num_param_groups = len(fp32_flat_groups[0]) merged_single_partition_of_fp32_groups = [] for i in range(num_param_groups): merged_partitions = [sd[i] for sd in fp32_flat_groups] full_single_fp32_vector = torch.cat(merged_partitions, 0) merged_single_partition_of_fp32_groups.append(full_single_fp32_vector) avail_numel = sum( [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
if debug: wanted_params = sum([len(shapes) for shapes in param_shapes]) wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes]) # not asserting if there is a mismatch due to possible padding print(f"Have {avail_numel} numels to process.") print(f"Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution total_numel = 0 total_params = 0 for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups): offset = 0 avail_numel = full_single_fp32_vector.numel() for name, shape in shapes.items():
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape) total_numel += unpartitioned_numel total_params += 1
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ") state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape) offset += unpartitioned_numel
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex # paddings performed in the code it's almost impossible to predict the exact numbers w/o the # live optimizer object, so we are checking that the numbers are within the right range align_to = 2 * world_size
def zero2_align(x): return align_to * math.ceil(x / align_to)
if debug: print(f"original offset={offset}, avail_numel={avail_numel}")
offset = zero2_align(offset) avail_numel = zero2_align(avail_numel)
if debug: print(f"aligned offset={offset}, avail_numel={avail_numel}")
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero2_merge_frozen_params(state_dict, zero_model_states)
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def zero3_partitioned_param_info(unpartitioned_numel, world_size): remainder = unpartitioned_numel % world_size padding_numel = (world_size - remainder) if remainder else 0 partitioned_numel = math.ceil(unpartitioned_numel / world_size) return partitioned_numel, padding_numel
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
if debug: for i in range(world_size): num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values()) print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
frozen_param_shapes = zero_model_states[0].frozen_param_shapes wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in zero_model_states[0].frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states) state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes avail_numel = fp32_flat_groups[0].numel() * world_size # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each # param, re-consolidating each param, while dealing with padding if any
# merge list of dicts, preserving order param_shapes = {k: v for d in param_shapes for k, v in d.items()}
if debug: for i in range(world_size): print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
wanted_params = len(param_shapes) wanted_numel = sum(shape.numel() for shape in param_shapes.values()) # not asserting if there is a mismatch due to possible padding avail_numel = fp32_flat_groups[0].numel() * world_size print(f"Trainable params: Have {avail_numel} numels to process.") print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution offset = 0 total_numel = 0 total_params = 0 for name, shape in param_shapes.items():
unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel total_params += 1
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
# XXX: memory usage doubles here state_dict[name] = torch.cat( tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)), 0).narrow(0, 0, unpartitioned_numel).view(shape) offset += partitioned_numel
offset *= world_size
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example via a model hub.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters
Returns: - pytorch ``state_dict``
Note: this approach may not work if your application doesn't have sufficient free CPU memory and you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with the checkpoint.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint # do the training and checkpoint saving state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() # move to cpu model.load_state_dict(state_dict) # submit to model hub or save the model to share with others
In this example the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
""" if tag is None: latest_path = os.path.join(checkpoint_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: raise ValueError(f"Unable to find 'latest' file at {latest_path}")
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
if not os.path.isdir(ds_checkpoint_dir): raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters """
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters) print(f"Saving fp32 state dict to {output_file}") torch.save(state_dict, output_file)
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None): """ 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model
Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
Returns: - ``model`: modified model
Make sure you have plenty of CPU memory available before you call this function. If you don't have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it conveniently placed for you in the checkpoint folder.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) # submit to model hub or save the model to share with others
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
""" logger.info(f"Extracting fp32 weights") state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
logger.info(f"Overwriting model with fp32 weights") model = model.cpu() model.load_state_dict(state_dict, strict=False)
return model
if __name__ == "__main__":
parser = argparse.ArgumentParser() parser.add_argument("checkpoint_dir", type=str, help="path to the desired checkpoint folder, e.g., path/checkpoint-12") parser.add_argument( "output_file", type=str, help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)") parser.add_argument("-t", "--tag", type=str, default=None, help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1") parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters") parser.add_argument("-d", "--debug", action='store_true', help="enable debug") args = parser.parse_args()
debug = args.debug
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag, exclude_frozen_parameters=args.exclude_frozen_parameters)README.md+43-3
adapter_config.jsonAdded+29
adapter_model.safetensorsAdded+3
global_step2000/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
global_step2000/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
global_step2000/bf16_zero_pp_rank_2_mp_rank_00_optim_states.ptAdded+3
global_step2000/bf16_zero_pp_rank_3_mp_rank_00_optim_states.ptAdded+3
global_step2000/bf16_zero_pp_rank_4_mp_rank_00_optim_states.ptAdded+3
global_step2000/bf16_zero_pp_rank_5_mp_rank_00_optim_states.ptAdded+3
global_step2000/bf16_zero_pp_rank_6_mp_rank_00_optim_states.ptAdded+3
global_step2000/bf16_zero_pp_rank_7_mp_rank_00_optim_states.ptAdded+3
global_step2000/zero_pp_rank_0_mp_rank_00_model_states.ptAdded+3
global_step2000/zero_pp_rank_1_mp_rank_00_model_states.ptAdded+3
global_step2000/zero_pp_rank_2_mp_rank_00_model_states.ptAdded+3
global_step2000/zero_pp_rank_3_mp_rank_00_model_states.ptAdded+3
global_step2000/zero_pp_rank_4_mp_rank_00_model_states.ptAdded+3
global_step2000/zero_pp_rank_5_mp_rank_00_model_states.ptAdded+3
global_step2000/zero_pp_rank_6_mp_rank_00_model_states.ptAdded+3
global_step2000/zero_pp_rank_7_mp_rank_00_model_states.ptAdded+3
latestAdded+1
rng_state_0.pthAdded+3
rng_state_1.pthAdded+3
rng_state_2.pthAdded+3
rng_state_3.pthAdded+3
rng_state_4.pthAdded+3
rng_state_5.pthAdded+3
rng_state_6.pthAdded+3
rng_state_7.pthAdded+3
special_tokens_map.jsonAdded+27
tokenizer.jsonAdded
tokenizer_config.jsonAdded+223
trainer_state.jsonAdded+653
training_args.binAdded+3
zero_to_fp32.pyAdded+604