andreaparker commited on
Commit
84b5548
·
1 Parent(s): fe776d1

Initial commit

Browse files
README.md ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license:
5
+ - apache-2.0
6
+ - bsd-3-clause
7
+ tags:
8
+ - summarization
9
+ - led
10
+ - summary
11
+ - longformer
12
+ - booksum
13
+ - long-document
14
+ - long-form
15
+ datasets:
16
+ - kmfoda/booksum
17
+ metrics:
18
+ - rouge
19
+ widget:
20
+ - text: large earthquakes along a given fault segment do not occur at random intervals
21
+ because it takes time to accumulate the strain energy for the rupture. The rates
22
+ at which tectonic plates move and accumulate strain at their boundaries are approximately
23
+ uniform. Therefore, in first approximation, one may expect that large ruptures
24
+ of the same fault segment will occur at approximately constant time intervals.
25
+ If subsequent main shocks have different amounts of slip across the fault, then
26
+ the recurrence time may vary, and the basic idea of periodic mainshocks must be
27
+ modified. For great plate boundary ruptures the length and slip often vary by
28
+ a factor of 2. Along the southern segment of the San Andreas fault the recurrence
29
+ interval is 145 years with variations of several decades. The smaller the standard
30
+ deviation of the average recurrence interval, the more specific could be the long
31
+ term prediction of a future mainshock.
32
+ example_title: earthquakes
33
+ - text: ' A typical feed-forward neural field algorithm. Spatiotemporal coordinates
34
+ are fed into a neural network that predicts values in the reconstructed domain.
35
+ Then, this domain is mapped to the sensor domain where sensor measurements are
36
+ available as supervision. Class and Section Problems Addressed Generalization
37
+ (Section 2) Inverse problems, ill-posed problems, editability; symmetries. Hybrid
38
+ Representations (Section 3) Computation & memory efficiency, representation capacity,
39
+ editability: Forward Maps (Section 4) Inverse problems Network Architecture (Section
40
+ 5) Spectral bias, integration & derivatives. Manipulating Neural Fields (Section
41
+ 6) Edit ability, constraints, regularization. Table 2: The five classes of techniques
42
+ in the neural field toolbox each addresses problems that arise in learning, inference,
43
+ and control. (Section 3). We can supervise reconstruction via differentiable forward
44
+ maps that transform Or project our domain (e.g, 3D reconstruction via 2D images;
45
+ Section 4) With appropriate network architecture choices, we can overcome neural
46
+ network spectral biases (blurriness) and efficiently compute derivatives and integrals
47
+ (Section 5). Finally, we can manipulate neural fields to add constraints and regularizations,
48
+ and to achieve editable representations (Section 6). Collectively, these classes
49
+ constitute a ''toolbox'' of techniques to help solve problems with neural fields
50
+ There are three components in a conditional neural field: (1) An encoder or inference
51
+ function € that outputs the conditioning latent variable 2 given an observation
52
+ 0 E(0) =2. 2 is typically a low-dimensional vector, and is often referred to aS
53
+ a latent code Or feature code_ (2) A mapping function 4 between Z and neural field
54
+ parameters O: Y(z) = O; (3) The neural field itself $. The encoder € finds the
55
+ most probable z given the observations O: argmaxz P(2/0). The decoder maximizes
56
+ the inverse conditional probability to find the most probable 0 given Z: arg-
57
+ max P(Olz). We discuss different encoding schemes with different optimality guarantees
58
+ (Section 2.1.1), both global and local conditioning (Section 2.1.2), and different
59
+ mapping functions Y (Section 2.1.3) 2. Generalization Suppose we wish to estimate
60
+ a plausible 3D surface shape given a partial or noisy point cloud. We need a suitable
61
+ prior over the sur- face in its reconstruction domain to generalize to the partial
62
+ observations. A neural network expresses a prior via the function space of its
63
+ architecture and parameters 0, and generalization is influenced by the inductive
64
+ bias of this function space (Section 5).'
65
+ example_title: scientific paper
66
+ - text: ' the big variety of data coming from diverse sources is one of the key properties
67
+ of the big data phenomenon. It is, therefore, beneficial to understand how data
68
+ is generated in various environments and scenarios, before looking at what should
69
+ be done with this data and how to design the best possible architecture to accomplish
70
+ this The evolution of IT architectures, described in Chapter 2, means that the
71
+ data is no longer processed by a few big monolith systems, but rather by a group
72
+ of services In parallel to the processing layer, the underlying data storage has
73
+ also changed and became more distributed This, in turn, required a significant
74
+ paradigm shift as the traditional approach to transactions (ACID) could no longer
75
+ be supported. On top of this, cloud computing is becoming a major approach with
76
+ the benefits of reducing costs and providing on-demand scalability but at the
77
+ same time introducing concerns about privacy, data ownership, etc In the meantime
78
+ the Internet continues its exponential growth: Every day both structured and unstructured
79
+ data is published and available for processing: To achieve competitive advantage
80
+ companies have to relate their corporate resources to external services, e.g.
81
+ financial markets, weather forecasts, social media, etc While several of the sites
82
+ provide some sort of API to access the data in a more orderly fashion; countless
83
+ sources require advanced web mining and Natural Language Processing (NLP) processing
84
+ techniques: Advances in science push researchers to construct new instruments
85
+ for observing the universe O conducting experiments to understand even better
86
+ the laws of physics and other domains. Every year humans have at their disposal
87
+ new telescopes, space probes, particle accelerators, etc These instruments generate
88
+ huge streams of data, which need to be stored and analyzed. The constant drive
89
+ for efficiency in the industry motivates the introduction of new automation techniques
90
+ and process optimization: This could not be done without analyzing the precise
91
+ data that describe these processes. As more and more human tasks are automated,
92
+ machines provide rich data sets, which can be analyzed in real-time to drive efficiency
93
+ to new levels. Finally, it is now evident that the growth of the Internet of Things
94
+ is becoming a major source of data. More and more of the devices are equipped
95
+ with significant computational power and can generate a continuous data stream
96
+ from their sensors. In the subsequent sections of this chapter, we will look at
97
+ the domains described above to see what they generate in terms of data sets. We
98
+ will compare the volumes but will also look at what is characteristic and important
99
+ from their respective points of view. 3.1 The Internet is undoubtedly the largest
100
+ database ever created by humans. While several well described; cleaned, and structured
101
+ data sets have been made available through this medium, most of the resources
102
+ are of an ambiguous, unstructured, incomplete or even erroneous nature. Still,
103
+ several examples in the areas such as opinion mining, social media analysis, e-governance,
104
+ etc, clearly show the potential lying in these resources. Those who can successfully
105
+ mine and interpret the Internet data can gain unique insight and competitive advantage
106
+ in their business An important area of data analytics on the edge of corporate
107
+ IT and the Internet is Web Analytics.'
108
+ example_title: data science textbook
109
+ - text: 'Transformer-based models have shown to be very useful for many NLP tasks.
110
+ However, a major limitation of transformers-based models is its O(n^2)O(n 2) time
111
+ & memory complexity (where nn is sequence length). Hence, it''s computationally
112
+ very expensive to apply transformer-based models on long sequences n > 512n>512.
113
+ Several recent papers, e.g. Longformer, Performer, Reformer, Clustered attention
114
+ try to remedy this problem by approximating the full attention matrix. You can
115
+ checkout 🤗''s recent blog post in case you are unfamiliar with these models.
116
+
117
+ BigBird (introduced in paper) is one of such recent models to address this issue.
118
+ BigBird relies on block sparse attention instead of normal attention (i.e. BERT''s
119
+ attention) and can handle sequences up to a length of 4096 at a much lower computational
120
+ cost compared to BERT. It has achieved SOTA on various tasks involving very long
121
+ sequences such as long documents summarization, question-answering with long contexts.
122
+
123
+ BigBird RoBERTa-like model is now available in 🤗Transformers. The goal of this
124
+ post is to give the reader an in-depth understanding of big bird implementation
125
+ & ease one''s life in using BigBird with 🤗Transformers. But, before going into
126
+ more depth, it is important to remember that the BigBird''s attention is an approximation
127
+ of BERT''s full attention and therefore does not strive to be better than BERT''s
128
+ full attention, but rather to be more efficient. It simply allows to apply transformer-based
129
+ models to much longer sequences since BERT''s quadratic memory requirement quickly
130
+ becomes unbearable. Simply put, if we would have ∞ compute & ∞ time, BERT''s attention
131
+ would be preferred over block sparse attention (which we are going to discuss
132
+ in this post).
133
+
134
+ If you wonder why we need more compute when working with longer sequences, this
135
+ blog post is just right for you!
136
+
137
+ Some of the main questions one might have when working with standard BERT-like
138
+ attention include:
139
+
140
+ Do all tokens really have to attend to all other tokens? Why not compute attention
141
+ only over important tokens? How to decide what tokens are important? How to attend
142
+ to just a few tokens in a very efficient way? In this blog post, we will try to
143
+ answer those questions.
144
+
145
+ What tokens should be attended to? We will give a practical example of how attention
146
+ works by considering the sentence ''BigBird is now available in HuggingFace for
147
+ extractive question answering''. In BERT-like attention, every word would simply
148
+ attend to all other tokens.
149
+
150
+ Let''s think about a sensible choice of key tokens that a queried token actually
151
+ only should attend to by writing some pseudo-code. Will will assume that the token
152
+ available is queried and build a sensible list of key tokens to attend to.
153
+
154
+ >>> # let''s consider following sentence as an example >>> example = [''BigBird'',
155
+ ''is'', ''now'', ''available'', ''in'', ''HuggingFace'', ''for'', ''extractive'',
156
+ ''question'', ''answering'']
157
+
158
+ >>> # further let''s assume, we''re trying to understand the representation of
159
+ ''available'' i.e. >>> query_token = ''available'' >>> # We will initialize an
160
+ empty `set` and fill up the tokens of our interest as we proceed in this section.
161
+ >>> key_tokens = [] # => currently ''available'' token doesn''t have anything
162
+ to attend Nearby tokens should be important because, in a sentence (sequence of
163
+ words), the current word is highly dependent on neighboring past & future tokens.
164
+ This intuition is the idea behind the concept of sliding attention.'
165
+ example_title: bigbird blog intro
166
+ - text: 'The majority of available text summarization datasets include short-form
167
+ source documents that lack long-range causal and temporal dependencies, and often
168
+ contain strong layout and stylistic biases. While relevant, such datasets will
169
+ offer limited challenges for future generations of text summarization systems.
170
+ We address these issues by introducing BookSum, a collection of datasets for long-form
171
+ narrative summarization. Our dataset covers source documents from the literature
172
+ domain, such as novels, plays and stories, and includes highly abstractive, human
173
+ written summaries on three levels of granularity of increasing difficulty: paragraph-,
174
+ chapter-, and book-level. The domain and structure of our dataset poses a unique
175
+ set of challenges for summarization systems, which include: processing very long
176
+ documents, non-trivial causal and temporal dependencies, and rich discourse structures.
177
+ To facilitate future work, we trained and evaluated multiple extractive and abstractive
178
+ summarization models as baselines for our dataset.'
179
+ example_title: BookSum Abstract
180
+ inference:
181
+ parameters:
182
+ max_length: 64
183
+ min_length: 8
184
+ no_repeat_ngram_size: 3
185
+ early_stopping: true
186
+ repetition_penalty: 3.5
187
+ length_penalty: 0.3
188
+ encoder_no_repeat_ngram_size: 3
189
+ num_beams: 4
190
+ model-index:
191
+ - name: pszemraj/led-large-book-summary
192
+ results:
193
+ - task:
194
+ type: summarization
195
+ name: Summarization
196
+ dataset:
197
+ name: kmfoda/booksum
198
+ type: kmfoda/booksum
199
+ config: kmfoda--booksum
200
+ split: test
201
+ metrics:
202
+ - type: rouge
203
+ value: 31.7308
204
+ name: ROUGE-1
205
+ verified: true
206
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiNjJmZjMxYTY0OGU3MzNjNmIzNmYyODNlNDg2ZGRhZDAzNTMwMDM5YWMxODc1OTc1ZWE3MzM2OTg1ODFhZDBkNCIsInZlcnNpb24iOjF9.B8BCKgySYVZW910_1zP0LfCpQYJbAe6loyWut76JlgZb2kV1_x9ybqtNESX0ka-lNqhYyXUNDpuS-7pTmsJVDg
207
+ - type: rouge
208
+ value: 5.3311
209
+ name: ROUGE-2
210
+ verified: true
211
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiYzViMmY4ODFjYTc5ODk5MmRhMDQ3ZDRiYWQwMDg0OTk3ZTA4NDAxYTNiNDgyMmI4NDA3ZDMwYWViOTBkODBjNyIsInZlcnNpb24iOjF9.MOhJLDcgvv93mVFL1igIgIiTAH3b2Xa4gmBObq7RF44Mmu8Kxtd1KP7rOlDVFOrtrsooGPGsyE1GMCQ2kqeMDg
212
+ - type: rouge
213
+ value: 16.1465
214
+ name: ROUGE-L
215
+ verified: true
216
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiNzNjMzEwMTliZGE3ZmQ4M2UxMDAyMTY3YzJjZmMyMDYyN2YyNDM0N2VhNzI1MDc1YTg4MTRjMmEzNjVkNTk1NCIsInZlcnNpb24iOjF9.XLJ-DVKiYLlbw5E5rWADKbzUzf5fNHhlTCWPCC5dU4NI9Yeh76aR7TPt36ZzLDwTBknnR8KHqlaF8F8YAvBUAg
217
+ - type: rouge
218
+ value: 29.0883
219
+ name: ROUGE-LSUM
220
+ verified: true
221
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiMTcwNzEwMmE5NjQxZTkzYmQyZDZmNzllYzYyNGI5OTMyNWMwNjdiM2I2YmM5YjdmY2E5OWQ3OTk3ZDA1MTc3YyIsInZlcnNpb24iOjF9.d6rFxjCB6RJNI_pn2DNNSjuZe4rdvj0RatkaTJRp5lP0F_AFfU5Zn9zRWzZJV7V-xMauIc4UhfdoLp9r_-CABA
222
+ - type: loss
223
+ value: 4.815707206726074
224
+ name: loss
225
+ verified: true
226
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiNTMwMTgxMmJkODY3MjkzOWJhMzJhOTIxMWVkODhjZmM0MWUzMWQ1N2JkZjRhOTQxNmU1YWVjYzQ0MDNlZWI3OSIsInZlcnNpb24iOjF9.mkBQHYhYFfDV6F4klXGJ1dSsF-pbCs-6F9zcw6IYznwmXUjtk7m5J4Zt4JAju5LKz4YizvEcUCl_L0WddnfvDA
227
+ - type: gen_len
228
+ value: 154.9036
229
+ name: gen_len
230
+ verified: true
231
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiMTc0ZmM1ZDM4MDE0MzY3MDM3OWJhNDkzZjJkZDdkMjU5M2JmMDJjYTIxODA1OTllNmY5ZWQzZDlmNWFiYzk4NiIsInZlcnNpb24iOjF9.VQ_O_xSTz870tnM08PJXQOwg9OsNNwI_HVX4S7AuW57_FzGGyRaWSuGE5SWzRS4Tur9YP0QxV4VV0Yoaoi3IAA
232
+ - task:
233
+ type: summarization
234
+ name: Summarization
235
+ dataset:
236
+ name: samsum
237
+ type: samsum
238
+ config: samsum
239
+ split: test
240
+ metrics:
241
+ - type: rouge
242
+ value: 33.4484
243
+ name: ROUGE-1
244
+ verified: true
245
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiNTk4Yjg1YTc4YmY0MzBiZDU4ZjFhNzI4MjZkMWU1MzBlOWNlMjQ5ODMzY2YzYzRhYjJkMGUzNmI3ZjdkMzIzZSIsInZlcnNpb24iOjF9.AqS8A1OUiM0IZFBEGirv5F3Novk8lSUYSfPc3bYWLA6t-W7wgup3qA207eGbE5j9CkDWZ7QrSG1U6Z9A0sOqAA
246
+ - type: rouge
247
+ value: 10.4249
248
+ name: ROUGE-2
249
+ verified: true
250
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiN2U4NjUyNTFmOGM5OTlhZDMyMTlmM2E4OWI2NGFiMDAyMGJjMzRjNWNlMGEyYWFmNTE5ZWMxM2I0ZGZmNWNmOCIsInZlcnNpb24iOjF9.SgJcHJ4qoRWXFvFiwv1PUutWktvsxQNynVPEv-GtBgxd6WI7o561ONyco5U-5tcyE_1SbSCJzz-L-R-q3cvoDA
251
+ - type: rouge
252
+ value: 24.5802
253
+ name: ROUGE-L
254
+ verified: true
255
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiZmQ5MDI5MzdiNGE5NDM0MmU5OThmZTBkNjkxMzg5N2IxNGVlODdhZTZhNjg3NzFjYWEyMzA3MTQxNjMyMjRkOCIsInZlcnNpb24iOjF9.Bg5dHqCcJjmxa-xGWNR5lD9g3quX7lKkH0pjiTd2xE5WiPoLLN2c0mYa2GovdW7__WnYwhhHC7es03jmvyZbCw
256
+ - type: rouge
257
+ value: 29.8226
258
+ name: ROUGE-LSUM
259
+ verified: true
260
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiNGFhOTEwNGM1MmZkNDk2ZjQ1Y2MyNjM3MGI5MGY3MWVkM2I0MjU2NWFiYmEwMjE4MTJlZWIwOGQ2MjQ3YjgzYSIsInZlcnNpb24iOjF9.W_aQKs10oXQdKEczJBGM3iiwJgb-VaXTpyA3sGof5WbhHf9vITAQA-xvynh5LgKtXQ1zjx737hnHgjEsu_Y0Cw
261
+ - type: loss
262
+ value: 4.176078796386719
263
+ name: loss
264
+ verified: true
265
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiN2JhODQ5YTZkNDZkZGYyNGU2MzkxMWU5MTEwMGM2YmVjZTA5YzI5NTMxMDNhYjhlOTAxMzFiMDYwYmM0MjEzZCIsInZlcnNpb24iOjF9.OvZrPBOR5jhkoTGBgsInkH7j3_xpacXHDoT7UIXEnyXzadfBO-O-K6fjalLNZw8wSkbjHIFcL_6S_qTTxPsNAQ
266
+ - type: gen_len
267
+ value: 65.4005
268
+ name: gen_len
269
+ verified: true
270
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiM2NhYjc3ZjQzNDEwYmMzOTM0ODkyZTJhZWNhNzZhYmEyZTYxMzA2YTYzMWFjOTA5ZjlhYWMzODg3NzY1ZTUwYSIsInZlcnNpb24iOjF9.vk9bgmtQFeRwdY3VXjtrJr_5wUCIeoAkI3kO0cHxhxmJo6RvUnyXiut72FuB-mlLZvqgiNkaZ-u_bh0Z3DjuCw
271
+ - task:
272
+ type: summarization
273
+ name: Summarization
274
+ dataset:
275
+ name: billsum
276
+ type: billsum
277
+ config: default
278
+ split: test
279
+ metrics:
280
+ - type: rouge
281
+ value: 40.5843
282
+ name: ROUGE-1
283
+ verified: true
284
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiNTVjMDkyMWZjYTQ0NzgzNGUxZjNiMTg3NjU1MWJlNTQ2MWQ1NjE1MDk1OTU4ZjJiNGQ5ODg3Y2VlMWUyMzllNyIsInZlcnNpb24iOjF9.OhqBcVIuHk7fzmdrsWMvUe1bLeVMZVstZUoZpP7C1vR-3aIDl7r6eBmPrt5w-KcNq5p4teNPBsq7oKzbd5ZgDQ
285
+ - type: rouge
286
+ value: 17.3401
287
+ name: ROUGE-2
288
+ verified: true
289
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiNGQxYmQzMmE0OTcyNTM5NmMwNjIxNzYxZDcwMDFkYzJkOWY4YWY3NTdhZGRhZDdlMDAxNzcwODQ5OGM3Mzc1MCIsInZlcnNpb24iOjF9.Pksn25EEqvmx757N7Swrd4yXc_xU7-AMN9yNe8lrbBa-l1LoI_2PUASvnjML4f705cfuyMAfb0FkFp5WfER2AA
290
+ - type: rouge
291
+ value: 25.1256
292
+ name: ROUGE-L
293
+ verified: true
294
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiMjhjYzI5MDBiMjk2NTY3MDNmZTdiOGYwMTRlYjIwZjAwMjdlNTAyYzdhYTJlODQ4MjYzYmQ3MjRlYTA2YzhhZSIsInZlcnNpb24iOjF9.1jPepsweS2bzIqDverQzzhmhFGch7gpoEGFGqQ8zW7K10aUKWFX8lt-uZAmTa1Z5ZhzyXGBzc3dReFPhWRRJBg
295
+ - type: rouge
296
+ value: 34.6619
297
+ name: ROUGE-LSUM
298
+ verified: true
299
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiM2VkZDIxNWJjOTA0NzFjOTIwOTdjYjc1M2EyNDVjZjY2ZjY3MjIxNDk3YTc5YWExNzAwN2FhOTc1NjVhYjBkYiIsInZlcnNpb24iOjF9.8opqHSUckPohoSF9jfPTpXDz2AtDwvdMqOdIXx2kE1tkOcbLPbOBfcc8RhRR98y8S26yC6EYFhFnf03CV2ejAQ
300
+ - type: loss
301
+ value: 4.792657375335693
302
+ name: loss
303
+ verified: true
304
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiYTY5ZTRkMGU3OGVkODMzMDU5OWE1NTM5YjA4NDliZDlmNzc2NzZjNjFmNTA3M2EwY2NmN2E0MWJmZjQ5ZDliMiIsInZlcnNpb24iOjF9.KCKdk8xt2NWcMmYKV3-9eVEsFm9MqGllSMu9QCFJFIQlnyNXllHKdBLouoaGQz8IRYXvZKH8_TLDPIQx-31jAg
305
+ - type: gen_len
306
+ value: 163.9394
307
+ name: gen_len
308
+ verified: true
309
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiYzdkZDYyZGUzYmFkZmI2NjUwYmQ0MzZjMmIyZjI1YTFiMzM4OThiZjBiMzljOTVkZTgwMjA0NTE5OGM2YmFjMiIsInZlcnNpb24iOjF9.XyMZLUdkUIF32KTJMuv_bJswQCx_Tfg4Fx823cURUixSeoIKps8_a634AreZ3Z8kb7bfE_sFGh3rM9KWsMxlDw
310
+ - task:
311
+ type: summarization
312
+ name: Summarization
313
+ dataset:
314
+ name: multi_news
315
+ type: multi_news
316
+ config: default
317
+ split: test
318
+ metrics:
319
+ - type: rouge
320
+ value: 39.0834
321
+ name: ROUGE-1
322
+ verified: true
323
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiNjYzMmVlMDM4MTNkMTI4MjAyMTU2YTg1ZWQwNTI1MmJlNGUwZmE1NTRmYTljZTQwY2RlMjcxOTgyZGMyYTc0ZiIsInZlcnNpb24iOjF9.6yuSr7UmsFatwqQ-mEO4gmsEtWI05kGB5Ib2pnl05H1OiPT2uUwmqdUytUw8KTx9u1jv9q0cTF1cL-n2kPEJAA
324
+ - type: rouge
325
+ value: 11.4043
326
+ name: ROUGE-2
327
+ verified: true
328
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiMWI5N2U2ZWI1ODM2MWUwOTIzYTAzNmRhNDA2OWEzZWRjMGEzMjBmY2EwN2YyYzU1NWE0YjIyZDE3MWE0MmMxZCIsInZlcnNpb24iOjF9.wonuxbBl25TzEaHUH_E816nHJ1OSXKfkaq7eJzbLpsfeGwcDklxUSxZxRO7VBiBMaY3Qttf9ywmEIPp40HnpBA
329
+ - type: rouge
330
+ value: 19.1813
331
+ name: ROUGE-L
332
+ verified: true
333
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiZjU1NDZhN2NkMzZiZGJkODE4NDZiYjViOTZkNGMyNDlkNjBlZmFjYzU1N2IzMjFjYjY1MDU1Zjk2MzA0M2U4NyIsInZlcnNpb24iOjF9.bTCRzv3J9NiCh4aV23tAWGTvrdQCv_RS40zGwC4AJXtGS40cY7tJHYwBf9U9_rCetDBxqfjJpdaUbCAOglxLAA
334
+ - type: rouge
335
+ value: 35.1581
336
+ name: ROUGE-LSUM
337
+ verified: true
338
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiMDNhNTUyZjE4NjYxYjIzYThmMDM2YWNhM2QwYzY1ODI2ZTE3NmNjMmVhOTAzZjZlOWQwYzc1NzU2NDNjNzIxMyIsInZlcnNpb24iOjF9.cWlSbEBgrMN5D-fV_yL9geNMyMkIItcVO3wehNJPzFi3E0v1-4q8pnX-UgjLzto8X7JLi6as2V_HtZE4-C-CDw
339
+ - type: loss
340
+ value: 4.654905319213867
341
+ name: loss
342
+ verified: true
343
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiYTc5Nzk0ODhiNWUzNTAxNzk2YzZmMjU2NDliY2UzOTYyYTdmZGEyYjI5NDNhOTE0MGUxOTgxMGVjMmNhM2UyMSIsInZlcnNpb24iOjF9.eBBAebcl3AwkrjR6a8BvoSjDfpw8LWTRFjyIFHVzspvoOKVfnO8_NB_UeR_K127OwXyoZ70Z7X_aKJOe-2kTDA
344
+ - type: gen_len
345
+ value: 186.2494
346
+ name: gen_len
347
+ verified: true
348
+ verifyToken: eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJoYXNoIjoiOWI2NjVlYjgwYWJiMjcyMDUzMzEwNDNjZTMxMDM0MjAzMzk1ZmIwY2Q1ZDQ2Y2M5NDBlMDEzYzFkNWEyNzJmNiIsInZlcnNpb24iOjF9.iZ1Iy7FuWL4GH7LS5EylVj5eZRC3L2ZsbYQapAkMNzR_VXPoMGvoM69Hp-kU7gW55tmz2V4Qxhvoz9cM8fciBA
349
+ ---
350
+
351
+ # Longformer Encoder-Decoder (LED) for Narrative-Esque Long Text Summarization
352
+
353
+ <a href="https://colab.research.google.com/gist/pszemraj/3eba944ddc9fc9a4a1bfb21e83b57620/summarization-token-batching.ipynb">
354
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
355
+ </a>
356
+
357
+ A fine-tuned version of [allenai/led-large-16384](https://huggingface.co/allenai/led-large-16384) on the `BookSum` dataset.
358
+
359
+ Goal: a model that can generalize well and is useful in summarizing long text in academic and daily usage. The result works well on lots of text and can handle 16384 tokens/batch (_if you have the GPU memory to handle that_)
360
+
361
+ - See the Colab demo linked above or try the [demo on Spaces](https://huggingface.co/spaces/pszemraj/summarize-long-text)
362
+
363
+
364
+ > Note: the API is set to generate a max of 64 tokens for runtime reasons, so the summaries may be truncated (depending on the length of input text). For best results use python as below.
365
+
366
+ ---
367
+
368
+ # Usage - Basic
369
+
370
+ - use `encoder_no_repeat_ngram_size=3` when calling the pipeline object to improve summary quality.
371
+ - this forces the model to use new vocabulary and create an abstractive summary, otherwise it may compile the best _extractive_ summary from the input provided.
372
+
373
+ Load the model into a pipeline object:
374
+
375
+ ```python
376
+ import torch
377
+ from transformers import pipeline
378
+
379
+ hf_name = 'pszemraj/led-large-book-summary'
380
+
381
+ summarizer = pipeline(
382
+ "summarization",
383
+ hf_name,
384
+ device=0 if torch.cuda.is_available() else -1,
385
+ )
386
+ ```
387
+
388
+ - put words into the pipeline object:
389
+
390
+ ```python
391
+ wall_of_text = "your words here"
392
+
393
+ result = summarizer(
394
+ wall_of_text,
395
+ min_length=16,
396
+ max_length=256,
397
+ no_repeat_ngram_size=3,
398
+ encoder_no_repeat_ngram_size=3,
399
+ repetition_penalty=3.5,
400
+ num_beams=4,
401
+ early_stopping=True,
402
+ )
403
+ ```
404
+
405
+
406
+ **Important:** To generate the best quality summaries, you should use the global attention mask when decoding, as demonstrated in [this community notebook here](https://colab.research.google.com/drive/12INTTR6n64TzS4RrXZxMSXfrOd9Xzamo?usp=sharing), see the definition of `generate_answer(batch)`.
407
+
408
+ If having computing constraints, try the base version [`pszemraj/led-base-book-summary`](https://huggingface.co/pszemraj/led-base-book-summary)
409
+ - all the parameters for generation on the API here are the same as [the base model](https://huggingface.co/pszemraj/led-base-book-summary) for easy comparison between versions.
410
+
411
+ ## Training and evaluation data
412
+
413
+ - the [booksum](https://arxiv.org/abs/2105.08209) dataset (this is what adds the `bsd-3-clause` license)
414
+ - During training, the input text was the text of the `chapter`, and the output was `summary_text`
415
+ - Eval results can be found [here](https://huggingface.co/datasets/autoevaluate/autoeval-staging-eval-project-kmfoda__booksum-79c1c0d8-10905463) with metrics on the sidebar.
416
+
417
+ ## Training procedure
418
+
419
+ - Training completed on the BookSum dataset for 13 total epochs
420
+ - **The final four epochs combined the training and validation sets as 'train' in an effort to increase generalization.**
421
+
422
+ ### Training hyperparameters
423
+
424
+ #### Initial Three Epochs
425
+
426
+ The following hyperparameters were used during training:
427
+ - learning_rate: 5e-05
428
+ - train_batch_size: 1
429
+ - eval_batch_size: 1
430
+ - seed: 42
431
+ - distributed_type: multi-GPU
432
+ - gradient_accumulation_steps: 4
433
+ - total_train_batch_size: 4
434
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
435
+ - lr_scheduler_type: linear
436
+ - num_epochs: 3
437
+
438
+ #### In-between Epochs
439
+
440
+ Unfortunately, don't have all records on-hand for middle epochs; the following should be representative:
441
+
442
+ - learning_rate: 4e-05
443
+ - train_batch_size: 2
444
+ - eval_batch_size: 2
445
+ - seed: 42
446
+ - distributed_type: multi-GPU
447
+ - gradient_accumulation_steps: 16
448
+ - total_train_batch_size: 32
449
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
450
+ - lr_scheduler_type: cosine
451
+ - lr_scheduler_warmup_ratio: 0.05
452
+ - num_epochs: 6 (in addition to prior model)
453
+
454
+ #### Final Two Epochs
455
+
456
+ The following hyperparameters were used during training:
457
+ - learning_rate: 2e-05
458
+ - train_batch_size: 1
459
+ - eval_batch_size: 1
460
+ - seed: 42
461
+ - distributed_type: multi-GPU
462
+ - gradient_accumulation_steps: 16
463
+ - total_train_batch_size: 16
464
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
465
+ - lr_scheduler_type: cosine
466
+ - lr_scheduler_warmup_ratio: 0.03
467
+ - num_epochs: 2 (in addition to prior model)
468
+
469
+
470
+ ### Framework versions
471
+
472
+ - Transformers 4.19.2
473
+ - Pytorch 1.11.0+cu113
474
+ - Datasets 2.2.2
475
+ - Tokenizers 0.12.1
config.json ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "pszemraj/led-large-book-summary",
3
+ "_num_labels": 3,
4
+ "activation_dropout": 0.0,
5
+ "activation_function": "gelu",
6
+ "architectures": [
7
+ "LEDForConditionalGeneration"
8
+ ],
9
+ "attention_dropout": 0.0,
10
+ "attention_window": [
11
+ 1024,
12
+ 1024,
13
+ 1024,
14
+ 1024,
15
+ 1024,
16
+ 1024,
17
+ 1024,
18
+ 1024,
19
+ 1024,
20
+ 1024,
21
+ 1024,
22
+ 1024
23
+ ],
24
+ "bos_token_id": 0,
25
+ "classif_dropout": 0.0,
26
+ "classifier_dropout": 0.0,
27
+ "d_model": 1024,
28
+ "decoder_attention_heads": 16,
29
+ "decoder_ffn_dim": 4096,
30
+ "decoder_layerdrop": 0.0,
31
+ "decoder_layers": 12,
32
+ "decoder_start_token_id": 2,
33
+ "dropout": 0.1,
34
+ "early_stopping": true,
35
+ "encoder_attention_heads": 16,
36
+ "encoder_ffn_dim": 4096,
37
+ "encoder_layerdrop": 0.0,
38
+ "encoder_layers": 12,
39
+ "eos_token_id": 2,
40
+ "id2label": {
41
+ "0": "LABEL_0",
42
+ "1": "LABEL_1",
43
+ "2": "LABEL_2"
44
+ },
45
+ "init_std": 0.02,
46
+ "is_encoder_decoder": true,
47
+ "label2id": {
48
+ "LABEL_0": 0,
49
+ "LABEL_1": 1,
50
+ "LABEL_2": 2
51
+ },
52
+ "length_penalty": 0.8,
53
+ "max_decoder_position_embeddings": 1024,
54
+ "max_encoder_position_embeddings": 16384,
55
+ "max_length": 1024,
56
+ "min_length": 8,
57
+ "model_type": "led",
58
+ "no_repeat_ngram_size": 3,
59
+ "num_beams": 4,
60
+ "num_hidden_layers": 12,
61
+ "output_past": false,
62
+ "pad_token_id": 1,
63
+ "prefix": " ",
64
+ "repetition_penalty": 3.5,
65
+ "torch_dtype": "float32",
66
+ "transformers_version": "4.19.2",
67
+ "use_cache": false,
68
+ "vocab_size": 50265
69
+ }
ds_config_zero2.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "amp": {
3
+ "enabled": "auto",
4
+ "opt_level": "auto"
5
+ },
6
+
7
+ "optimizer": {
8
+ "type": "AdamW",
9
+ "params": {
10
+ "lr": "auto",
11
+ "betas": "auto",
12
+ "eps": "auto",
13
+ "weight_decay": "auto"
14
+ }
15
+ },
16
+
17
+
18
+ "zero_optimization": {
19
+ "stage": 2,
20
+ "offload_optimizer": {
21
+ "device": "cpu",
22
+ "pin_memory": true
23
+ },
24
+ "allgather_partitions": true,
25
+ "allgather_bucket_size": 2e8,
26
+ "overlap_comm": true,
27
+ "reduce_scatter": true,
28
+ "reduce_bucket_size": 2e8,
29
+ "round_robin_gradients": true,
30
+ "contiguous_gradients": true
31
+ },
32
+
33
+ "gradient_accumulation_steps": "auto",
34
+ "gradient_clipping": "auto",
35
+ "steps_per_print": 4000,
36
+ "train_batch_size": "auto",
37
+ "train_micro_batch_size_per_gpu": "auto",
38
+ "wall_clock_breakdown": false
39
+ }
latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step296
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6591dc2bafd2bdca9f277d71524cb86a3a637793dc8661e08957b5dd2b52ff15
3
+ size 135
rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58f013dc79528514b3c1cce2c180b789f59730e3d4dce985927ddda73bae54d2
3
+ size 130
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "eos_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "unk_token": {"content": "<unk>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "sep_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "pad_token": {"content": "<pad>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "cls_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": true}}
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"errors": "replace", "bos_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "eos_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "sep_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "cls_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "unk_token": {"content": "<unk>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "pad_token": {"content": "<pad>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "add_prefix_space": false, "trim_offsets": true, "model_max_length": 16384, "special_tokens_map_file": "/root/.cache/huggingface/transformers/2ad921573d53ebf0c0450d63a211e61d8e328324e84830c365abff01f2d115f1.cb2244924ab24d706b02fd7fcedaea4531566537687a539ebb94db511fd122a0", "name_or_path": "pszemraj/led-large-book-summary", "tokenizer_class": "LEDTokenizer"}
trainer_state.json ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 2.9914638001896936,
5
+ "global_step": 294,
6
+ "is_hyper_param_search": false,
7
+ "is_local_process_zero": true,
8
+ "is_world_process_zero": true,
9
+ "log_history": [
10
+ {
11
+ "epoch": 0.05,
12
+ "learning_rate": 7.5e-06,
13
+ "loss": 0.481,
14
+ "step": 5
15
+ },
16
+ {
17
+ "epoch": 0.1,
18
+ "learning_rate": 1.5e-05,
19
+ "loss": 0.5091,
20
+ "step": 10
21
+ },
22
+ {
23
+ "epoch": 0.15,
24
+ "learning_rate": 2.25e-05,
25
+ "loss": 0.4303,
26
+ "step": 15
27
+ },
28
+ {
29
+ "epoch": 0.2,
30
+ "learning_rate": 3e-05,
31
+ "loss": 0.4055,
32
+ "step": 20
33
+ },
34
+ {
35
+ "epoch": 0.25,
36
+ "learning_rate": 2.998662940889891e-05,
37
+ "loss": 0.4338,
38
+ "step": 25
39
+ },
40
+ {
41
+ "epoch": 0.3,
42
+ "learning_rate": 2.9946541471956496e-05,
43
+ "loss": 0.4793,
44
+ "step": 30
45
+ },
46
+ {
47
+ "epoch": 0.35,
48
+ "learning_rate": 2.9879807655761145e-05,
49
+ "loss": 0.4291,
50
+ "step": 35
51
+ },
52
+ {
53
+ "epoch": 0.4,
54
+ "learning_rate": 2.9786546929722055e-05,
55
+ "loss": 0.4908,
56
+ "step": 40
57
+ },
58
+ {
59
+ "epoch": 0.46,
60
+ "learning_rate": 2.966692555397705e-05,
61
+ "loss": 0.463,
62
+ "step": 45
63
+ },
64
+ {
65
+ "epoch": 0.51,
66
+ "learning_rate": 2.9521156782993066e-05,
67
+ "loss": 0.528,
68
+ "step": 50
69
+ },
70
+ {
71
+ "epoch": 0.56,
72
+ "learning_rate": 2.9349500485387718e-05,
73
+ "loss": 0.5178,
74
+ "step": 55
75
+ },
76
+ {
77
+ "epoch": 0.61,
78
+ "learning_rate": 2.9152262680649704e-05,
79
+ "loss": 0.4602,
80
+ "step": 60
81
+ },
82
+ {
83
+ "epoch": 0.66,
84
+ "learning_rate": 2.8929794993583937e-05,
85
+ "loss": 0.5044,
86
+ "step": 65
87
+ },
88
+ {
89
+ "epoch": 0.71,
90
+ "learning_rate": 2.8682494027454e-05,
91
+ "loss": 0.4217,
92
+ "step": 70
93
+ },
94
+ {
95
+ "epoch": 0.76,
96
+ "learning_rate": 2.8410800656939512e-05,
97
+ "loss": 0.502,
98
+ "step": 75
99
+ },
100
+ {
101
+ "epoch": 0.81,
102
+ "learning_rate": 2.811519924216873e-05,
103
+ "loss": 0.4549,
104
+ "step": 80
105
+ },
106
+ {
107
+ "epoch": 0.86,
108
+ "learning_rate": 2.779621676522777e-05,
109
+ "loss": 0.5692,
110
+ "step": 85
111
+ },
112
+ {
113
+ "epoch": 0.91,
114
+ "learning_rate": 2.7454421890685647e-05,
115
+ "loss": 0.4312,
116
+ "step": 90
117
+ },
118
+ {
119
+ "epoch": 0.96,
120
+ "learning_rate": 2.709042395181008e-05,
121
+ "loss": 0.4938,
122
+ "step": 95
123
+ },
124
+ {
125
+ "epoch": 1.02,
126
+ "learning_rate": 2.6704871864281377e-05,
127
+ "loss": 0.5433,
128
+ "step": 100
129
+ },
130
+ {
131
+ "epoch": 1.07,
132
+ "learning_rate": 2.6298452969340952e-05,
133
+ "loss": 0.3459,
134
+ "step": 105
135
+ },
136
+ {
137
+ "epoch": 1.12,
138
+ "learning_rate": 2.58718918084368e-05,
139
+ "loss": 0.3739,
140
+ "step": 110
141
+ },
142
+ {
143
+ "epoch": 1.17,
144
+ "learning_rate": 2.5425948831550528e-05,
145
+ "loss": 0.375,
146
+ "step": 115
147
+ },
148
+ {
149
+ "epoch": 1.22,
150
+ "learning_rate": 2.496141904150859e-05,
151
+ "loss": 0.3809,
152
+ "step": 120
153
+ },
154
+ {
155
+ "epoch": 1.27,
156
+ "learning_rate": 2.447913057669456e-05,
157
+ "loss": 0.4183,
158
+ "step": 125
159
+ },
160
+ {
161
+ "epoch": 1.32,
162
+ "learning_rate": 2.3979943234689226e-05,
163
+ "loss": 0.4207,
164
+ "step": 130
165
+ },
166
+ {
167
+ "epoch": 1.37,
168
+ "learning_rate": 2.3464746939470288e-05,
169
+ "loss": 0.3767,
170
+ "step": 135
171
+ },
172
+ {
173
+ "epoch": 1.42,
174
+ "learning_rate": 2.2934460154904436e-05,
175
+ "loss": 0.4248,
176
+ "step": 140
177
+ },
178
+ {
179
+ "epoch": 1.48,
180
+ "learning_rate": 2.2390028247360042e-05,
181
+ "loss": 0.3374,
182
+ "step": 145
183
+ },
184
+ {
185
+ "epoch": 1.53,
186
+ "learning_rate": 2.183242180035951e-05,
187
+ "loss": 0.4582,
188
+ "step": 150
189
+ },
190
+ {
191
+ "epoch": 1.58,
192
+ "learning_rate": 2.1262634884275948e-05,
193
+ "loss": 0.4153,
194
+ "step": 155
195
+ },
196
+ {
197
+ "epoch": 1.63,
198
+ "learning_rate": 2.068168328415864e-05,
199
+ "loss": 0.409,
200
+ "step": 160
201
+ },
202
+ {
203
+ "epoch": 1.68,
204
+ "learning_rate": 2.0090602688846884e-05,
205
+ "loss": 0.4023,
206
+ "step": 165
207
+ },
208
+ {
209
+ "epoch": 1.73,
210
+ "learning_rate": 1.9490446844600375e-05,
211
+ "loss": 0.3426,
212
+ "step": 170
213
+ },
214
+ {
215
+ "epoch": 1.78,
216
+ "learning_rate": 1.888228567653781e-05,
217
+ "loss": 0.4059,
218
+ "step": 175
219
+ },
220
+ {
221
+ "epoch": 1.83,
222
+ "learning_rate": 1.8267203381232774e-05,
223
+ "loss": 0.4449,
224
+ "step": 180
225
+ },
226
+ {
227
+ "epoch": 1.88,
228
+ "learning_rate": 1.764629649386713e-05,
229
+ "loss": 0.4362,
230
+ "step": 185
231
+ },
232
+ {
233
+ "epoch": 1.93,
234
+ "learning_rate": 1.7020671933387917e-05,
235
+ "loss": 0.4874,
236
+ "step": 190
237
+ },
238
+ {
239
+ "epoch": 1.98,
240
+ "learning_rate": 1.63914450291526e-05,
241
+ "loss": 0.3326,
242
+ "step": 195
243
+ },
244
+ {
245
+ "epoch": 2.04,
246
+ "learning_rate": 1.5633197410233404e-05,
247
+ "loss": 0.4035,
248
+ "step": 200
249
+ },
250
+ {
251
+ "epoch": 2.09,
252
+ "learning_rate": 1.5e-05,
253
+ "loss": 0.3291,
254
+ "step": 205
255
+ },
256
+ {
257
+ "epoch": 2.14,
258
+ "learning_rate": 1.4366802589766598e-05,
259
+ "loss": 0.353,
260
+ "step": 210
261
+ },
262
+ {
263
+ "epoch": 2.19,
264
+ "learning_rate": 1.373473400935433e-05,
265
+ "loss": 0.319,
266
+ "step": 215
267
+ },
268
+ {
269
+ "epoch": 2.24,
270
+ "learning_rate": 1.3104921076168065e-05,
271
+ "loss": 0.341,
272
+ "step": 220
273
+ },
274
+ {
275
+ "epoch": 2.29,
276
+ "learning_rate": 1.247848658636778e-05,
277
+ "loss": 0.3276,
278
+ "step": 225
279
+ },
280
+ {
281
+ "epoch": 2.34,
282
+ "learning_rate": 1.185654731320877e-05,
283
+ "loss": 0.3628,
284
+ "step": 230
285
+ },
286
+ {
287
+ "epoch": 2.39,
288
+ "learning_rate": 1.124021201611919e-05,
289
+ "loss": 0.2727,
290
+ "step": 235
291
+ },
292
+ {
293
+ "epoch": 2.45,
294
+ "learning_rate": 1.0630579464064182e-05,
295
+ "loss": 0.3466,
296
+ "step": 240
297
+ },
298
+ {
299
+ "epoch": 2.5,
300
+ "learning_rate": 1.0028736476720464e-05,
301
+ "loss": 0.3187,
302
+ "step": 245
303
+ },
304
+ {
305
+ "epoch": 2.55,
306
+ "learning_rate": 9.435755986953485e-06,
307
+ "loss": 0.3837,
308
+ "step": 250
309
+ },
310
+ {
311
+ "epoch": 2.6,
312
+ "learning_rate": 8.852695128051192e-06,
313
+ "loss": 0.2955,
314
+ "step": 255
315
+ },
316
+ {
317
+ "epoch": 2.65,
318
+ "learning_rate": 8.280593349124432e-06,
319
+ "loss": 0.3793,
320
+ "step": 260
321
+ },
322
+ {
323
+ "epoch": 2.7,
324
+ "learning_rate": 7.720470562033787e-06,
325
+ "loss": 0.3443,
326
+ "step": 265
327
+ },
328
+ {
329
+ "epoch": 2.75,
330
+ "learning_rate": 7.17332532314626e-06,
331
+ "loss": 0.2915,
332
+ "step": 270
333
+ },
334
+ {
335
+ "epoch": 2.8,
336
+ "learning_rate": 6.640133053163455e-06,
337
+ "loss": 0.3514,
338
+ "step": 275
339
+ },
340
+ {
341
+ "epoch": 2.85,
342
+ "learning_rate": 6.12184429819474e-06,
343
+ "loss": 0.3221,
344
+ "step": 280
345
+ },
346
+ {
347
+ "epoch": 2.9,
348
+ "learning_rate": 5.619383035175448e-06,
349
+ "loss": 0.2903,
350
+ "step": 285
351
+ },
352
+ {
353
+ "epoch": 2.95,
354
+ "learning_rate": 5.133645024651171e-06,
355
+ "loss": 0.3397,
356
+ "step": 290
357
+ }
358
+ ],
359
+ "max_steps": 392,
360
+ "num_train_epochs": 4,
361
+ "total_flos": 1.821325738775675e+17,
362
+ "trial_name": null,
363
+ "trial_params": null
364
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:401745ea2f5f8bc223616c82c7bae7b501398125eba6ecd872c79ffcc7abc266
3
+ size 129
vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
zero_to_fp32.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # This script extracts fp32 consolidated weights from a zero 2 and 3 DeepSpeed checkpoints. It gets
4
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
5
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
6
+ # application.
7
+ #
8
+ # example: python zero_to_fp32.py . pytorch_model.bin
9
+
10
+ import argparse
11
+ import torch
12
+ import glob
13
+ import math
14
+ import os
15
+ import re
16
+ from collections import OrderedDict
17
+
18
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
19
+ # DeepSpeed data structures it has to be available in the current python environment.
20
+ import deepspeed
21
+ from deepspeed.utils import logger
22
+ from deepspeed.checkpoint.constants import (DS_VERSION,
23
+ OPTIMIZER_STATE_DICT,
24
+ PARAM_SHAPES,
25
+ SINGLE_PARTITION_OF_FP32_GROUPS,
26
+ FP32_FLAT_GROUPS,
27
+ ZERO_STAGE,
28
+ PARTITION_COUNT,
29
+ PARAM_SHAPES,
30
+ BUFFER_NAMES)
31
+
32
+ debug = 0
33
+
34
+ # load to cpu
35
+ device = torch.device('cpu')
36
+
37
+
38
+ def atoi(text):
39
+ return int(text) if text.isdigit() else text
40
+
41
+
42
+ def natural_keys(text):
43
+ '''
44
+ alist.sort(key=natural_keys) sorts in human order
45
+ http://nedbatchelder.com/blog/200712/human_sorting.html
46
+ (See Toothy's implementation in the comments)
47
+ '''
48
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
49
+
50
+
51
+ def get_model_state_file(checkpoint_dir, zero_stage):
52
+ if not os.path.isdir(checkpoint_dir):
53
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
54
+
55
+ # there should be only one file
56
+ if zero_stage == 2:
57
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
58
+ elif zero_stage == 3:
59
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
60
+
61
+ if not os.path.exists(file):
62
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
63
+
64
+ return file
65
+
66
+
67
+ def get_optim_files(checkpoint_dir):
68
+ # XXX: need to test that this simple glob rule works for multi-node setup too
69
+ optim_files = sorted(glob.glob(os.path.join(checkpoint_dir,
70
+ "*_optim_states.pt")),
71
+ key=natural_keys)
72
+
73
+ if len(optim_files) == 0:
74
+ raise FileNotFoundError(
75
+ f"can't find '*_optim_states.pt' files in directory '{checkpoint_dir}'")
76
+
77
+ return optim_files
78
+
79
+
80
+ def parse_model_state(file):
81
+ state_dict = torch.load(file, map_location=device)
82
+
83
+ if BUFFER_NAMES not in state_dict:
84
+ raise ValueError(f"{file} is not a model state checkpoint")
85
+ buffer_names = state_dict[BUFFER_NAMES]
86
+ if debug:
87
+ print("Found buffers:", buffer_names)
88
+
89
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
90
+ buffers = {
91
+ k: v.float()
92
+ for k,
93
+ v in state_dict["module"].items() if k in buffer_names
94
+ }
95
+ param_shapes = state_dict[PARAM_SHAPES]
96
+
97
+ ds_version = state_dict.get(DS_VERSION, None)
98
+
99
+ return buffers, param_shapes, ds_version
100
+
101
+
102
+ def parse_optim_states(files, ds_checkpoint_dir):
103
+
104
+ total_files = len(files)
105
+ state_dicts = []
106
+ for f in files:
107
+ state_dicts.append(torch.load(f, map_location=device))
108
+
109
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
110
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
111
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
112
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
113
+
114
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
115
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
116
+ # use the max of the partition_count to get the dp world_size.
117
+
118
+ if type(world_size) is list:
119
+ world_size = max(world_size)
120
+
121
+ if world_size != total_files:
122
+ raise ValueError(
123
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
124
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
125
+ )
126
+
127
+ # the groups are named differently in each stage
128
+ if zero_stage == 2:
129
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
130
+ elif zero_stage == 3:
131
+ fp32_groups_key = FP32_FLAT_GROUPS
132
+ else:
133
+ raise ValueError(f"unknown zero stage {zero_stage}")
134
+
135
+ if zero_stage == 2:
136
+ fp32_flat_groups = [
137
+ state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key]
138
+ for i in range(len(state_dicts))
139
+ ]
140
+ elif zero_stage == 3:
141
+ # if there is more than one param group, there will be multiple flattened tensors - one
142
+ # flattened tensor per group - for simplicity merge them into a single tensor
143
+ #
144
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
145
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
146
+
147
+ fp32_flat_groups = [
148
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key],
149
+ 0) for i in range(len(state_dicts))
150
+ ]
151
+
152
+ return zero_stage, world_size, fp32_flat_groups
153
+
154
+
155
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir):
156
+ """
157
+ Returns fp32 state_dict reconstructed from ds checkpoint
158
+
159
+ Args:
160
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
161
+
162
+ """
163
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
164
+
165
+ optim_files = get_optim_files(ds_checkpoint_dir)
166
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
167
+ print(
168
+ f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
169
+
170
+ model_file = get_model_state_file(ds_checkpoint_dir, zero_stage)
171
+ buffers, param_shapes, ds_version = parse_model_state(model_file)
172
+ print(f'Parsing checkpoint created by deepspeed=={ds_version}')
173
+
174
+ if zero_stage == 2:
175
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size,
176
+ param_shapes,
177
+ fp32_flat_groups,
178
+ buffers)
179
+ elif zero_stage == 3:
180
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size,
181
+ param_shapes,
182
+ fp32_flat_groups,
183
+ buffers)
184
+
185
+
186
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size,
187
+ param_shapes,
188
+ fp32_flat_groups,
189
+ buffers):
190
+
191
+ # Reconstruction protocol:
192
+ #
193
+ # XXX: document this
194
+
195
+ if debug:
196
+ for i in range(world_size):
197
+ for j in range(len(fp32_flat_groups[0])):
198
+ print(
199
+ f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
200
+
201
+ # XXX: memory usage doubles here (zero2)
202
+ num_param_groups = len(fp32_flat_groups[0])
203
+ merged_single_partition_of_fp32_groups = []
204
+ for i in range(num_param_groups):
205
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
206
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
207
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
208
+ avail_numel = sum([
209
+ full_single_fp32_vector.numel()
210
+ for full_single_fp32_vector in merged_single_partition_of_fp32_groups
211
+ ])
212
+
213
+ if debug:
214
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
215
+ wanted_numel = sum(
216
+ [sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
217
+ # not asserting if there is a mismatch due to possible padding
218
+ print(f"Have {avail_numel} numels to process.")
219
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
220
+
221
+ state_dict = OrderedDict()
222
+
223
+ # buffers
224
+ state_dict.update(buffers)
225
+ if debug:
226
+ print(f"added {len(buffers)} buffers")
227
+
228
+ # params
229
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
230
+ # out-of-core computing solution
231
+ total_numel = 0
232
+ total_params = 0
233
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
234
+ offset = 0
235
+ avail_numel = full_single_fp32_vector.numel()
236
+ for name, shape in shapes.items():
237
+
238
+ unpartitioned_numel = shape.numel()
239
+ total_numel += unpartitioned_numel
240
+ total_params += 1
241
+
242
+ if debug:
243
+ print(
244
+ f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} "
245
+ )
246
+ state_dict[name] = full_single_fp32_vector.narrow(
247
+ 0,
248
+ offset,
249
+ unpartitioned_numel).view(shape)
250
+ offset += unpartitioned_numel
251
+
252
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
253
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
254
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
255
+ # live optimizer object, so we are checking that the numbers are within the right range
256
+ align_to = 2 * world_size
257
+
258
+ def zero2_align(x):
259
+ return align_to * math.ceil(x / align_to)
260
+
261
+ if debug:
262
+ print(f"original offset={offset}, avail_numel={avail_numel}")
263
+
264
+ offset = zero2_align(offset)
265
+ avail_numel = zero2_align(avail_numel)
266
+
267
+ if debug:
268
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
269
+
270
+ # Sanity check
271
+ if offset != avail_numel:
272
+ raise ValueError(
273
+ f"consumed {offset} numels out of {avail_numel} - something is wrong")
274
+
275
+ print(
276
+ f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements"
277
+ )
278
+
279
+ return state_dict
280
+
281
+
282
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
283
+ remainder = unpartitioned_numel % world_size
284
+ padding_numel = (world_size - remainder) if remainder else 0
285
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
286
+ return partitioned_numel, padding_numel
287
+
288
+
289
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size,
290
+ param_shapes,
291
+ fp32_flat_groups,
292
+ buffers):
293
+
294
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
295
+ # param, re-consolidating each param, while dealing with padding if any
296
+
297
+ avail_numel = fp32_flat_groups[0].numel() * world_size
298
+ # merge list of dicts, preserving order
299
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
300
+
301
+ if debug:
302
+ for i in range(world_size):
303
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
304
+
305
+ wanted_params = len(param_shapes)
306
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
307
+ # not asserting if there is a mismatch due to possible padding
308
+ print(f"Have {avail_numel} numels to process.")
309
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
310
+
311
+ state_dict = OrderedDict()
312
+
313
+ # buffers
314
+ state_dict.update(buffers)
315
+ if debug:
316
+ print(f"added {len(buffers)} buffers")
317
+
318
+ # params
319
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
320
+ # out-of-core computing solution
321
+ offset = 0
322
+ total_numel = 0
323
+ total_params = 0
324
+ for name, shape in param_shapes.items():
325
+
326
+ unpartitioned_numel = shape.numel()
327
+ total_numel += unpartitioned_numel
328
+ total_params += 1
329
+
330
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
331
+
332
+ if debug:
333
+ print(
334
+ f"{total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
335
+ )
336
+
337
+ # XXX: memory usage doubles here
338
+ state_dict[name] = torch.cat(
339
+ tuple(fp32_flat_groups[i].narrow(0,
340
+ offset,
341
+ partitioned_numel)
342
+ for i in range(world_size)),
343
+ 0).narrow(0,
344
+ 0,
345
+ unpartitioned_numel).view(shape)
346
+ offset += partitioned_numel
347
+
348
+ offset *= world_size
349
+
350
+ # Sanity check
351
+ if offset != avail_numel:
352
+ raise ValueError(
353
+ f"consumed {offset} numels out of {avail_numel} - something is wrong")
354
+
355
+ print(
356
+ f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements"
357
+ )
358
+
359
+ return state_dict
360
+
361
+
362
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None):
363
+ """
364
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
365
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
366
+ via a model hub.
367
+
368
+ Args:
369
+ - ``checkpoint_dir``: path to the desired checkpoint folder
370
+ - ``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``
371
+
372
+ Returns:
373
+ - pytorch ``state_dict``
374
+
375
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
376
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
377
+ the checkpoint.
378
+
379
+ A typical usage might be ::
380
+
381
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
382
+ # do the training and checkpoint saving
383
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
384
+ model = model.cpu() # move to cpu
385
+ model.load_state_dict(state_dict)
386
+ # submit to model hub or save the model to share with others
387
+
388
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
389
+ application. i.e. you will need to re-initialize the deepspeed engine, since
390
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
391
+
392
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
393
+
394
+ """
395
+ if tag is None:
396
+ latest_path = os.path.join(checkpoint_dir, 'latest')
397
+ if os.path.isfile(latest_path):
398
+ with open(latest_path, 'r') as fd:
399
+ tag = fd.read().strip()
400
+ else:
401
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
402
+
403
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
404
+
405
+ if not os.path.isdir(ds_checkpoint_dir):
406
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
407
+
408
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir)
409
+
410
+
411
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None):
412
+ """
413
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
414
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
415
+
416
+ Args:
417
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
418
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
419
+ - ``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``
420
+ """
421
+
422
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
423
+ print(f"Saving fp32 state dict to {output_file}")
424
+ torch.save(state_dict, output_file)
425
+
426
+
427
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
428
+ """
429
+ 1. Put the provided model to cpu
430
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
431
+ 3. Load it into the provided model
432
+
433
+ Args:
434
+ - ``model``: the model object to update
435
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
436
+ - ``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``
437
+
438
+ Returns:
439
+ - ``model`: modified model
440
+
441
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
442
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
443
+ conveniently placed for you in the checkpoint folder.
444
+
445
+ A typical usage might be ::
446
+
447
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
448
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
449
+ # submit to model hub or save the model to share with others
450
+
451
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
452
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
453
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
454
+
455
+ """
456
+ logger.info(f"Extracting fp32 weights")
457
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
458
+
459
+ logger.info(f"Overwriting model with fp32 weights")
460
+ model = model.cpu()
461
+ model.load_state_dict(state_dict, strict=False)
462
+
463
+ return model
464
+
465
+
466
+ if __name__ == "__main__":
467
+
468
+ parser = argparse.ArgumentParser()
469
+ parser.add_argument(
470
+ "checkpoint_dir",
471
+ type=str,
472
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
473
+ parser.add_argument(
474
+ "output_file",
475
+ type=str,
476
+ help=
477
+ "path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)"
478
+ )
479
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
480
+ args = parser.parse_args()
481
+
482
+ debug = args.debug
483
+
484
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file)