dophys commited on
Commit
1f0b6ea
1 Parent(s): 49ad8eb

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 1024,
3
+ "pooling_mode_cls_token": true,
4
+ "pooling_mode_mean_tokens": false,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
README.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ datasets: []
3
+ language: []
4
+ library_name: sentence-transformers
5
+ pipeline_tag: sentence-similarity
6
+ tags:
7
+ - sentence-transformers
8
+ - sentence-similarity
9
+ - feature-extraction
10
+ widget: []
11
+ ---
12
+
13
+ # SentenceTransformer
14
+
15
+ This is a [sentence-transformers](https://www.SBERT.net) model trained. It maps sentences & paragraphs to a 1024-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, text classification, clustering, and more.
16
+
17
+ ## Model Details
18
+
19
+ ### Model Description
20
+ - **Model Type:** Sentence Transformer
21
+ <!-- - **Base model:** [Unknown](https://huggingface.co/unknown) -->
22
+ - **Maximum Sequence Length:** 8192 tokens
23
+ - **Output Dimensionality:** 1024 tokens
24
+ - **Similarity Function:** Cosine Similarity
25
+ <!-- - **Training Dataset:** Unknown -->
26
+ <!-- - **Language:** Unknown -->
27
+ <!-- - **License:** Unknown -->
28
+
29
+ ### Model Sources
30
+
31
+ - **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
32
+ - **Repository:** [Sentence Transformers on GitHub](https://github.com/UKPLab/sentence-transformers)
33
+ - **Hugging Face:** [Sentence Transformers on Hugging Face](https://huggingface.co/models?library=sentence-transformers)
34
+
35
+ ### Full Model Architecture
36
+
37
+ ```
38
+ SentenceTransformer(
39
+ (0): Transformer({'max_seq_length': 8192, 'do_lower_case': False}) with Transformer model: XLMRobertaModel
40
+ (1): Pooling({'word_embedding_dimension': 1024, 'pooling_mode_cls_token': True, 'pooling_mode_mean_tokens': False, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})
41
+ (2): Normalize()
42
+ )
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ ### Direct Usage (Sentence Transformers)
48
+
49
+ First install the Sentence Transformers library:
50
+
51
+ ```bash
52
+ pip install -U sentence-transformers
53
+ ```
54
+
55
+ Then you can load this model and run inference.
56
+ ```python
57
+ from sentence_transformers import SentenceTransformer
58
+
59
+ # Download from the 🤗 Hub
60
+ model = SentenceTransformer("sentence_transformers_model_id")
61
+ # Run inference
62
+ sentences = [
63
+ 'The weather is lovely today.',
64
+ "It's so sunny outside!",
65
+ 'He drove to the stadium.',
66
+ ]
67
+ embeddings = model.encode(sentences)
68
+ print(embeddings.shape)
69
+ # [3, 1024]
70
+
71
+ # Get the similarity scores for the embeddings
72
+ similarities = model.similarity(embeddings, embeddings)
73
+ print(similarities.shape)
74
+ # [3, 3]
75
+ ```
76
+
77
+ <!--
78
+ ### Direct Usage (Transformers)
79
+
80
+ <details><summary>Click to see the direct usage in Transformers</summary>
81
+
82
+ </details>
83
+ -->
84
+
85
+ <!--
86
+ ### Downstream Usage (Sentence Transformers)
87
+
88
+ You can finetune this model on your own dataset.
89
+
90
+ <details><summary>Click to expand</summary>
91
+
92
+ </details>
93
+ -->
94
+
95
+ <!--
96
+ ### Out-of-Scope Use
97
+
98
+ *List how the model may foreseeably be misused and address what users ought not to do with the model.*
99
+ -->
100
+
101
+ <!--
102
+ ## Bias, Risks and Limitations
103
+
104
+ *What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
105
+ -->
106
+
107
+ <!--
108
+ ### Recommendations
109
+
110
+ *What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
111
+ -->
112
+
113
+ ## Training Details
114
+
115
+ ### Framework Versions
116
+ - Python: 3.12.3
117
+ - Sentence Transformers: 3.0.1
118
+ - Transformers: 4.42.1
119
+ - PyTorch: 2.3.0+cu121
120
+ - Accelerate: 0.31.0
121
+ - Datasets: 2.20.0
122
+ - Tokenizers: 0.19.1
123
+
124
+ ## Citation
125
+
126
+ ### BibTeX
127
+
128
+ <!--
129
+ ## Glossary
130
+
131
+ *Clearly define terms in order to be accessible across audiences.*
132
+ -->
133
+
134
+ <!--
135
+ ## Model Card Authors
136
+
137
+ *Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
138
+ -->
139
+
140
+ <!--
141
+ ## Model Card Contact
142
+
143
+ *Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
144
+ -->
config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/root/autodl-tmp/finetuned/checkpoint-13459",
3
+ "architectures": [
4
+ "XLMRobertaModel"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": 0,
8
+ "classifier_dropout": null,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "gelu",
11
+ "hidden_dropout_prob": 0.1,
12
+ "hidden_size": 1024,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 4096,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 8194,
17
+ "model_type": "xlm-roberta",
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 24,
20
+ "output_past": true,
21
+ "pad_token_id": 1,
22
+ "position_embedding_type": "absolute",
23
+ "torch_dtype": "float32",
24
+ "transformers_version": "4.42.1",
25
+ "type_vocab_size": 1,
26
+ "use_cache": true,
27
+ "vocab_size": 250002
28
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "3.0.1",
4
+ "transformers": "4.42.1",
5
+ "pytorch": "2.3.0+cu121"
6
+ },
7
+ "prompts": {},
8
+ "default_prompt_name": null,
9
+ "similarity_fn_name": null
10
+ }
latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step13459
modules.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ },
14
+ {
15
+ "idx": 2,
16
+ "name": "2",
17
+ "path": "2_Normalize",
18
+ "type": "sentence_transformers.models.Normalize"
19
+ }
20
+ ]
pushtohub.ipynb ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 4,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "ename": "AttributeError",
10
+ "evalue": "'BGEM3FlagModel' object has no attribute 'push_to_hub'",
11
+ "output_type": "error",
12
+ "traceback": [
13
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
14
+ "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
15
+ "Cell \u001b[0;32mIn[4], line 8\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mFlagEmbedding\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m BGEM3FlagModel\n\u001b[1;32m 4\u001b[0m model \u001b[38;5;241m=\u001b[39m BGEM3FlagModel(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m/data/models/bge-m3_finetuned\u001b[39m\u001b[38;5;124m'\u001b[39m, \n\u001b[1;32m 5\u001b[0m use_fp16\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m) \u001b[38;5;66;03m# Setting use_fp16 to True speeds up computation with a slight performance degradation\u001b[39;00m\n\u001b[0;32m----> 8\u001b[0m \u001b[43mmodel\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mpush_to_hub\u001b[49m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mdophys/bge-m3_finetuned\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
16
+ "\u001b[0;31mAttributeError\u001b[0m: 'BGEM3FlagModel' object has no attribute 'push_to_hub'"
17
+ ]
18
+ }
19
+ ],
20
+ "source": [
21
+ "from transformers import BertConfig, BertModel\n",
22
+ "from FlagEmbedding import BGEM3FlagModel\n",
23
+ "\n",
24
+ "model = BGEM3FlagModel('/data/models/bge-m3_finetuned', \n",
25
+ " use_fp16=True) # Setting use_fp16 to True speeds up computation with a slight performance degradation\n",
26
+ "\n",
27
+ "\n",
28
+ "model.push_to_hub(\"dophys/bge-m3_finetuned\")"
29
+ ]
30
+ }
31
+ ],
32
+ "metadata": {
33
+ "kernelspec": {
34
+ "display_name": "base",
35
+ "language": "python",
36
+ "name": "python3"
37
+ },
38
+ "language_info": {
39
+ "codemirror_mode": {
40
+ "name": "ipython",
41
+ "version": 3
42
+ },
43
+ "file_extension": ".py",
44
+ "mimetype": "text/x-python",
45
+ "name": "python",
46
+ "nbconvert_exporter": "python",
47
+ "pygments_lexer": "ipython3",
48
+ "version": "3.11.5"
49
+ }
50
+ },
51
+ "nbformat": 4,
52
+ "nbformat_minor": 2
53
+ }
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c2c5a27ebc66c5d36aadfa726ba305bcbed94f83fe938c77f9f2b540217a928
3
+ size 2271069306
rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:317e86fb49958a7dabc1380ad7673bc892f672c4805f29d1457b325094026c3a
3
+ size 14180
sentence_bert_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 8192,
3
+ "do_lower_case": false
4
+ }
sentencepiece.bpe.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfc8146abe2a0488e9e2a0c56de7952f7c11ab059eca145a0a727afce0db2865
3
+ size 5069051
special_tokens_map.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "<s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "<mask>",
25
+ "lstrip": true,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "sep_token": {
38
+ "content": "</s>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ "unk_token": {
45
+ "content": "<unk>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ }
51
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b74659c780d49afad7a7b9799868f75cbd3014fb6c34956e85a793028d38094a
3
+ size 17098251
tokenizer_config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "250001": {
36
+ "content": "<mask>",
37
+ "lstrip": true,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "bos_token": "<s>",
45
+ "clean_up_tokenization_spaces": true,
46
+ "cls_token": "<s>",
47
+ "eos_token": "</s>",
48
+ "mask_token": "<mask>",
49
+ "model_max_length": 8192,
50
+ "pad_token": "<pad>",
51
+ "sep_token": "</s>",
52
+ "sp_model_kwargs": {},
53
+ "tokenizer_class": "XLMRobertaTokenizer",
54
+ "unk_token": "<unk>"
55
+ }
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:685ad5b2432f58e764d0e56be91aba42f250e0d27edef293c151d1441add95dd
3
+ size 6776
zero_to_fp32.py ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ zero_stage = 0
153
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
154
+
155
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
156
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
157
+ # use the max of the partition_count to get the dp world_size.
158
+
159
+ if type(world_size) is list:
160
+ world_size = max(world_size)
161
+
162
+ if world_size != total_files:
163
+ raise ValueError(
164
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
165
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
166
+ )
167
+
168
+ # the groups are named differently in each stage
169
+ if zero_stage <= 2:
170
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
171
+ elif zero_stage == 3:
172
+ fp32_groups_key = FP32_FLAT_GROUPS
173
+ else:
174
+ raise ValueError(f"unknown zero stage {zero_stage}")
175
+
176
+ if zero_stage <= 2:
177
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
178
+ elif zero_stage == 3:
179
+ # if there is more than one param group, there will be multiple flattened tensors - one
180
+ # flattened tensor per group - for simplicity merge them into a single tensor
181
+ #
182
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
183
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
184
+
185
+ fp32_flat_groups = [
186
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
187
+ ]
188
+
189
+ return zero_stage, world_size, fp32_flat_groups
190
+
191
+
192
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
193
+ """
194
+ Returns fp32 state_dict reconstructed from ds checkpoint
195
+
196
+ Args:
197
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
198
+
199
+ """
200
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
201
+
202
+ optim_files = get_optim_files(ds_checkpoint_dir)
203
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
204
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
205
+
206
+ model_files = get_model_state_files(ds_checkpoint_dir)
207
+
208
+ zero_model_states = parse_model_states(model_files)
209
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
210
+
211
+ if zero_stage <= 2:
212
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
213
+ exclude_frozen_parameters)
214
+ elif zero_stage == 3:
215
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
216
+ exclude_frozen_parameters)
217
+
218
+
219
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
220
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
221
+ return
222
+
223
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
224
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
225
+
226
+ if debug:
227
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
228
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
229
+
230
+ wanted_params = len(frozen_param_shapes)
231
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
232
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
233
+ print(f'Frozen params: Have {avail_numel} numels to process.')
234
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
235
+
236
+ total_params = 0
237
+ total_numel = 0
238
+ for name, shape in frozen_param_shapes.items():
239
+ total_params += 1
240
+ unpartitioned_numel = shape.numel()
241
+ total_numel += unpartitioned_numel
242
+
243
+ state_dict[name] = frozen_param_fragments[name]
244
+
245
+ if debug:
246
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
247
+
248
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
249
+
250
+
251
+ def _has_callable(obj, fn):
252
+ attr = getattr(obj, fn, None)
253
+ return callable(attr)
254
+
255
+
256
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
257
+ param_shapes = zero_model_states[0].param_shapes
258
+
259
+ # Reconstruction protocol:
260
+ #
261
+ # XXX: document this
262
+
263
+ if debug:
264
+ for i in range(world_size):
265
+ for j in range(len(fp32_flat_groups[0])):
266
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
267
+
268
+ # XXX: memory usage doubles here (zero2)
269
+ num_param_groups = len(fp32_flat_groups[0])
270
+ merged_single_partition_of_fp32_groups = []
271
+ for i in range(num_param_groups):
272
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
273
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
274
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
275
+ avail_numel = sum(
276
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
277
+
278
+ if debug:
279
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
280
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
281
+ # not asserting if there is a mismatch due to possible padding
282
+ print(f"Have {avail_numel} numels to process.")
283
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
284
+
285
+ # params
286
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
287
+ # out-of-core computing solution
288
+ total_numel = 0
289
+ total_params = 0
290
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
291
+ offset = 0
292
+ avail_numel = full_single_fp32_vector.numel()
293
+ for name, shape in shapes.items():
294
+
295
+ unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
296
+ total_numel += unpartitioned_numel
297
+ total_params += 1
298
+
299
+ if debug:
300
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
301
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
302
+ offset += unpartitioned_numel
303
+
304
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
305
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
306
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
307
+ # live optimizer object, so we are checking that the numbers are within the right range
308
+ align_to = 2 * world_size
309
+
310
+ def zero2_align(x):
311
+ return align_to * math.ceil(x / align_to)
312
+
313
+ if debug:
314
+ print(f"original offset={offset}, avail_numel={avail_numel}")
315
+
316
+ offset = zero2_align(offset)
317
+ avail_numel = zero2_align(avail_numel)
318
+
319
+ if debug:
320
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
321
+
322
+ # Sanity check
323
+ if offset != avail_numel:
324
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
325
+
326
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
327
+
328
+
329
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
330
+ exclude_frozen_parameters):
331
+ state_dict = OrderedDict()
332
+
333
+ # buffers
334
+ buffers = zero_model_states[0].buffers
335
+ state_dict.update(buffers)
336
+ if debug:
337
+ print(f"added {len(buffers)} buffers")
338
+
339
+ if not exclude_frozen_parameters:
340
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
341
+
342
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
343
+
344
+ # recover shared parameters
345
+ for pair in zero_model_states[0].shared_params:
346
+ if pair[1] in state_dict:
347
+ state_dict[pair[0]] = state_dict[pair[1]]
348
+
349
+ return state_dict
350
+
351
+
352
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
353
+ remainder = unpartitioned_numel % world_size
354
+ padding_numel = (world_size - remainder) if remainder else 0
355
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
356
+ return partitioned_numel, padding_numel
357
+
358
+
359
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
360
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
361
+ return
362
+
363
+ if debug:
364
+ for i in range(world_size):
365
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
366
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
367
+
368
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
369
+ wanted_params = len(frozen_param_shapes)
370
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
371
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
372
+ print(f'Frozen params: Have {avail_numel} numels to process.')
373
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
374
+
375
+ total_params = 0
376
+ total_numel = 0
377
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
378
+ total_params += 1
379
+ unpartitioned_numel = shape.numel()
380
+ total_numel += unpartitioned_numel
381
+
382
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
383
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
384
+
385
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
386
+
387
+ if debug:
388
+ print(
389
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
390
+ )
391
+
392
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
393
+
394
+
395
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
396
+ param_shapes = zero_model_states[0].param_shapes
397
+ avail_numel = fp32_flat_groups[0].numel() * world_size
398
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
399
+ # param, re-consolidating each param, while dealing with padding if any
400
+
401
+ # merge list of dicts, preserving order
402
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
403
+
404
+ if debug:
405
+ for i in range(world_size):
406
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
407
+
408
+ wanted_params = len(param_shapes)
409
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
410
+ # not asserting if there is a mismatch due to possible padding
411
+ avail_numel = fp32_flat_groups[0].numel() * world_size
412
+ print(f"Trainable params: Have {avail_numel} numels to process.")
413
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
414
+
415
+ # params
416
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
417
+ # out-of-core computing solution
418
+ offset = 0
419
+ total_numel = 0
420
+ total_params = 0
421
+ for name, shape in param_shapes.items():
422
+
423
+ unpartitioned_numel = shape.numel()
424
+ total_numel += unpartitioned_numel
425
+ total_params += 1
426
+
427
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
428
+
429
+ if debug:
430
+ print(
431
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
432
+ )
433
+
434
+ # XXX: memory usage doubles here
435
+ state_dict[name] = torch.cat(
436
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
437
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
438
+ offset += partitioned_numel
439
+
440
+ offset *= world_size
441
+
442
+ # Sanity check
443
+ if offset != avail_numel:
444
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
445
+
446
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
447
+
448
+
449
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
450
+ exclude_frozen_parameters):
451
+ state_dict = OrderedDict()
452
+
453
+ # buffers
454
+ buffers = zero_model_states[0].buffers
455
+ state_dict.update(buffers)
456
+ if debug:
457
+ print(f"added {len(buffers)} buffers")
458
+
459
+ if not exclude_frozen_parameters:
460
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
461
+
462
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
463
+
464
+ # recover shared parameters
465
+ for pair in zero_model_states[0].shared_params:
466
+ if pair[1] in state_dict:
467
+ state_dict[pair[0]] = state_dict[pair[1]]
468
+
469
+ return state_dict
470
+
471
+
472
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False):
473
+ """
474
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
475
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
476
+ via a model hub.
477
+
478
+ Args:
479
+ - ``checkpoint_dir``: path to the desired checkpoint folder
480
+ - ``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``
481
+ - ``exclude_frozen_parameters``: exclude frozen parameters
482
+
483
+ Returns:
484
+ - pytorch ``state_dict``
485
+
486
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
487
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
488
+ the checkpoint.
489
+
490
+ A typical usage might be ::
491
+
492
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
493
+ # do the training and checkpoint saving
494
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
495
+ model = model.cpu() # move to cpu
496
+ model.load_state_dict(state_dict)
497
+ # submit to model hub or save the model to share with others
498
+
499
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
500
+ application. i.e. you will need to re-initialize the deepspeed engine, since
501
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
502
+
503
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
504
+
505
+ """
506
+ if tag is None:
507
+ latest_path = os.path.join(checkpoint_dir, 'latest')
508
+ if os.path.isfile(latest_path):
509
+ with open(latest_path, 'r') as fd:
510
+ tag = fd.read().strip()
511
+ else:
512
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
513
+
514
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
515
+
516
+ if not os.path.isdir(ds_checkpoint_dir):
517
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
518
+
519
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
520
+
521
+
522
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False):
523
+ """
524
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
525
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
526
+
527
+ Args:
528
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
529
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
530
+ - ``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``
531
+ - ``exclude_frozen_parameters``: exclude frozen parameters
532
+ """
533
+
534
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters)
535
+ print(f"Saving fp32 state dict to {output_file}")
536
+ torch.save(state_dict, output_file)
537
+
538
+
539
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
540
+ """
541
+ 1. Put the provided model to cpu
542
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
543
+ 3. Load it into the provided model
544
+
545
+ Args:
546
+ - ``model``: the model object to update
547
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
548
+ - ``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``
549
+
550
+ Returns:
551
+ - ``model`: modified model
552
+
553
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
554
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
555
+ conveniently placed for you in the checkpoint folder.
556
+
557
+ A typical usage might be ::
558
+
559
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
560
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
561
+ # submit to model hub or save the model to share with others
562
+
563
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
564
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
565
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
566
+
567
+ """
568
+ logger.info(f"Extracting fp32 weights")
569
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
570
+
571
+ logger.info(f"Overwriting model with fp32 weights")
572
+ model = model.cpu()
573
+ model.load_state_dict(state_dict, strict=False)
574
+
575
+ return model
576
+
577
+
578
+ if __name__ == "__main__":
579
+
580
+ parser = argparse.ArgumentParser()
581
+ parser.add_argument("checkpoint_dir",
582
+ type=str,
583
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
584
+ parser.add_argument(
585
+ "output_file",
586
+ type=str,
587
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
588
+ parser.add_argument("-t",
589
+ "--tag",
590
+ type=str,
591
+ default=None,
592
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
593
+ parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
594
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
595
+ args = parser.parse_args()
596
+
597
+ debug = args.debug
598
+
599
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
600
+ args.output_file,
601
+ tag=args.tag,
602
+ exclude_frozen_parameters=args.exclude_frozen_parameters)