Shankhdhar commited on
Commit
ce4ce86
1 Parent(s): 19358e0

Saving weights and logs of step 100

Browse files
.ipynb_checkpoints/Untitled-checkpoint.ipynb ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [],
3
+ "metadata": {},
4
+ "nbformat": 4,
5
+ "nbformat_minor": 5
6
+ }
Lilgpt.txt ADDED
The diff for this file is too large to render. See raw diff
 
Untitled.ipynb ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 12,
6
+ "id": "81fd300c",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import pandas as pd\n"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": 13,
16
+ "id": "1237ddf7",
17
+ "metadata": {},
18
+ "outputs": [
19
+ {
20
+ "name": "stdout",
21
+ "output_type": "stream",
22
+ "text": [
23
+ "3418\n"
24
+ ]
25
+ }
26
+ ],
27
+ "source": [
28
+ "with open(\"Lilgpt.txt\",'r') as file:\n",
29
+ " data = file.read()\n",
30
+ "List = data.split(\"<EOS>\")\n",
31
+ "print(len(List))"
32
+ ]
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "execution_count": 14,
37
+ "id": "18b93c2e",
38
+ "metadata": {},
39
+ "outputs": [
40
+ {
41
+ "name": "stdout",
42
+ "output_type": "stream",
43
+ "text": [
44
+ "\n",
45
+ "<BOS>\n",
46
+ "3 Headed Goat[Intro]\n",
47
+ "(Aviator)\n",
48
+ "\n",
49
+ "[Chorus: Lil Baby]\n",
50
+ "These ain't no Guess jeans\n",
51
+ "I dropped out of school, I'm still good at math, but, nigga, don't test me\n",
52
+ "I played to the left, they went to the right, they tried to finesse me\n",
53
+ "Still riding 'round with that blicky, I hope they don't catch me\n",
54
+ "Police had raided our spot, so we went to the next street\n",
55
+ "Play like I'm dumb, as soon as it pop, I'm goin' retarded\n",
56
+ "He say I'm hard and he say I'm garbage, I'm rich regardless\n",
57
+ "We in Miami in the middle of the winter, and we on them jet skis\n",
58
+ "If we in Atlanta, I'm runnin' the 'Cat and I'm workin' the red key\n",
59
+ "\n",
60
+ "[Verse 1: Lil Durk]\n",
61
+ "I cannot mention my homies inside of my song 'cause I know they be trappin' a lot\n",
62
+ "I can't keep takin' these pills, when I'm in the trenches, they say I be cappin' a lot\n",
63
+ "I know a nigga who say he got rich off the dope, but I know he be actin' a lot\n",
64
+ "I know some niggas who said that they took down the city, but niggas be lackin' a lot\n",
65
+ "Yeah\n",
66
+ "That shit was awful, nigga had that dog food\n",
67
+ "That day they shot you, I slid on a Mongoose\n",
68
+ "You cannot come back around me, you turned your back on me, I cannot forget\n",
69
+ "The police was lyin', they say that they caught you, but nigga, they made you admit\n",
70
+ "Your name was found, you put in that work, they took your stick, you a bitch\n",
71
+ "Fuck my opps, they be on my dick, they all be mad we rich (Turn up)\n",
72
+ "[Verse 2: Lil Baby]\n",
73
+ "Only twenty-five, livin' like a boss, ridin' 'round with a chauffeur\n",
74
+ "I don't sell drugs, still be paranoid, keep lookin' over my shoulder\n",
75
+ "Niggas lyin' like I'm stealin' swag, boy, that's my shit like I wrote it\n",
76
+ "\n",
77
+ "[Verse 3: Polo G]\n",
78
+ "Uh\n",
79
+ "These rappers really nice as hell\n",
80
+ "I'm a different nigga when I'm pissed off\n",
81
+ "Man, he say he gon' press up on who?\n",
82
+ "I'ma get the steel like I'm Chris Paul\n",
83
+ "Back to back suburbans, I'm a big dawg\n",
84
+ "I was in the slums servin' Fentanyl\n",
85
+ "Zombieland, junkies havin' withdrawals\n",
86
+ "I been gettin' to it, lotta missed calls\n",
87
+ "Turn it off, what the fuck is he talking 'bout?\n",
88
+ "I should slap you for sayin' he hot as me\n",
89
+ "I don't know who could fuck with me honestly\n",
90
+ "They know I'm the man, so they watchin' me\n",
91
+ "Different color bands like Monopoly\n",
92
+ "Man, he must not be usin' his head\n",
93
+ "If he thinkin' I don't keep a Glock with me\n",
94
+ "That's like suicide if you play with us\n",
95
+ "Got a better chance at the lottery\n",
96
+ "Call an ambulance when that chopper sweep\n",
97
+ "Make the crowd dance, choreography\n",
98
+ "Once I got a plan, ain't no stoppin' me\n",
99
+ "Three-car garage, million-dollar crib\n",
100
+ "With a foreign bitch ridin' on top of me\n",
101
+ "Lot of people done said I wouldn't be shit\n",
102
+ "Well, I guess they owe me an apology\n",
103
+ "[Chorus: Lil Baby]\n",
104
+ "These ain't no Guess jeans\n",
105
+ "I dropped out of school, I'm still good at math, but, nigga, don't test me\n",
106
+ "I played to the left, they went to the right, they tried to finesse me\n",
107
+ "Still riding 'round with that blicky, I hope they don't catch me\n",
108
+ "Police had raided our spot, so we went to the next street\n",
109
+ "Play like I'm dumb, as soon as it pop, I'm goin' retarded\n",
110
+ "He say I'm hard and he say I'm garbage, I'm rich regardless\n",
111
+ "We in Miami in the middle of the winter, and we on them jet skis\n",
112
+ "If we in Atlanta, I'm runnin' the 'Cat and I'm workin' the red key35EmbedShare URLCopyEmbedCopy\n",
113
+ "\n"
114
+ ]
115
+ }
116
+ ],
117
+ "source": [
118
+ "print(List[1])\n"
119
+ ]
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "execution_count": 15,
124
+ "id": "9c7698db",
125
+ "metadata": {},
126
+ "outputs": [
127
+ {
128
+ "name": "stdout",
129
+ "output_type": "stream",
130
+ "text": [
131
+ "\n",
132
+ "<BOS>\n",
133
+ "3 Headed Goat[Intro]\n",
134
+ "(Aviator)\n",
135
+ "\n",
136
+ "[Chorus: Lil Baby]\n",
137
+ "These ain't no Guess jeans\n",
138
+ "I dropped out of school, I'm still good at math, but, nigga, don't test me\n",
139
+ "I played to the left, they went to the right, they tried to finesse me\n",
140
+ "Still riding 'round with that blicky, I hope they don't catch me\n",
141
+ "Police had raided our spot, so we went to the next street\n",
142
+ "Play like I'm dumb, as soon as it pop, I'm goin' retarded\n",
143
+ "He say I'm hard and he say I'm garbage, I'm rich regardless\n",
144
+ "We in Miami in the middle of the winter, and we on them jet skis\n",
145
+ "If we in Atlanta, I'm runnin' the 'Cat and I'm workin' the red key\n",
146
+ "\n",
147
+ "[Verse 1: Lil Durk]\n",
148
+ "I cannot mention my homies inside of my song 'cause I know they be trappin' a lot\n",
149
+ "I can't keep takin' these pills, when I'm in the trenches, they say I be cappin' a lot\n",
150
+ "I know a nigga who say he got rich off the dope, but I know he be actin' a lot\n",
151
+ "I know some niggas who said that they took down the city, but niggas be lackin' a lot\n",
152
+ "Yeah\n",
153
+ "That shit was awful, nigga had that dog food\n",
154
+ "That day they shot you, I slid on a Mongoose\n",
155
+ "You cannot come back around me, you turned your back on me, I cannot forget\n",
156
+ "The police was lyin', they say that they caught you, but nigga, they made you admit\n",
157
+ "Your name was found, you put in that work, they took your stick, you a bitch\n",
158
+ "Fuck my opps, they be on my dick, they all be mad we rich (Turn up)\n",
159
+ "[Verse 2: Lil Baby]\n",
160
+ "Only twenty-five, livin' like a boss, ridin' 'round with a chauffeur\n",
161
+ "I don't sell drugs, still be paranoid, keep lookin' over my shoulder\n",
162
+ "Niggas lyin' like I'm stealin' swag, boy, that's my shit like I wrote it\n",
163
+ "\n",
164
+ "[Verse 3: Polo G]\n",
165
+ "Uh\n",
166
+ "These rappers really nice as hell\n",
167
+ "I'm a different nigga when I'm pissed off\n",
168
+ "Man, he say he gon' press up on who?\n",
169
+ "I'ma get the steel like I'm Chris Paul\n",
170
+ "Back to back suburbans, I'm a big dawg\n",
171
+ "I was in the slums servin' Fentanyl\n",
172
+ "Zombieland, junkies havin' withdrawals\n",
173
+ "I been gettin' to it, lotta missed calls\n",
174
+ "Turn it off, what the fuck is he talking 'bout?\n",
175
+ "I should slap you for sayin' he hot as me\n",
176
+ "I don't know who could fuck with me honestly\n",
177
+ "They know I'm the man, so they watchin' me\n",
178
+ "Different color bands like Monopoly\n",
179
+ "Man, he must not be usin' his head\n",
180
+ "If he thinkin' I don't keep a Glock with me\n",
181
+ "That's like suicide if you play with us\n",
182
+ "Got a better chance at the lottery\n",
183
+ "Call an ambulance when that chopper sweep\n",
184
+ "Make the crowd dance, choreography\n",
185
+ "Once I got a plan, ain't no stoppin' me\n",
186
+ "Three-car garage, million-dollar crib\n",
187
+ "With a foreign bitch ridin' on top of me\n",
188
+ "Lot of people done said I wouldn't be shit\n",
189
+ "Well, I guess they owe me an apology\n",
190
+ "[Chorus: Lil Baby]\n",
191
+ "These ain't no Guess jeans\n",
192
+ "I dropped out of school, I'm still good at math, but, nigga, don't test me\n",
193
+ "I played to the left, they went to the right, they tried to finesse me\n",
194
+ "Still riding 'round with that blicky, I hope they don't catch me\n",
195
+ "Police had raided our spot, so we went to the next street\n",
196
+ "Play like I'm dumb, as soon as it pop, I'm goin' retarded\n",
197
+ "He say I'm hard and he say I'm garbage, I'm rich regardless\n",
198
+ "We in Miami in the middle of the winter, and we on them jet skis\n",
199
+ "If we in Atlanta, I'm runnin' the 'Cat and I'm workin' the red key35EmbedShare URLCopyEmbedCopy\n",
200
+ "<EOS>\n"
201
+ ]
202
+ }
203
+ ],
204
+ "source": [
205
+ "NewList = []\n",
206
+ "for l in List:\n",
207
+ " n = l+\"<EOS>\"\n",
208
+ " NewList.append(n)\n",
209
+ "print(NewList[1])"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "execution_count": 16,
215
+ "id": "f31e28d8",
216
+ "metadata": {},
217
+ "outputs": [
218
+ {
219
+ "name": "stdout",
220
+ "output_type": "stream",
221
+ "text": [
222
+ "330\n",
223
+ "3088\n"
224
+ ]
225
+ }
226
+ ],
227
+ "source": [
228
+ "counter = 0\n",
229
+ "List_val = []\n",
230
+ "List_train = []\n",
231
+ "for l in List:\n",
232
+ " n = l+\"<EOS>\"\n",
233
+ " if counter<330:\n",
234
+ " List_val.append(n)\n",
235
+ " else:\n",
236
+ " List_train.append(n)\n",
237
+ " counter += 1\n",
238
+ "print(len(List_val))\n",
239
+ "print(len(List_train))"
240
+ ]
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "execution_count": 17,
245
+ "id": "9efd0b25",
246
+ "metadata": {},
247
+ "outputs": [
248
+ {
249
+ "name": "stdout",
250
+ "output_type": "stream",
251
+ "text": [
252
+ "<BOS>\n",
253
+ "My Beyoncé[Chorus: Lil Durk]\n",
254
+ "Ooh, I like the way she move\n",
255
+ "Shorty my baby, my everything, she the truth\n",
256
+ "Together we cool, me and her can't lose\n",
257
+ "Keep 'em on their feet, baby, I know they so confused\n",
258
+ "Shorty my Beyoncé\n",
259
+ "Durk and DeJ, Durk and DeJ, Durk and DeJ\n",
260
+ "Shorty my Beyoncé\n",
261
+ "Durk and DeJ, Durk and DeJ, Durk and DeJ\n",
262
+ "My Beyoncé\n",
263
+ "\n",
264
+ "[Verse 1: Lil Durk]\n",
265
+ "Trippin' on that drank, but I know she worth it\n",
266
+ "Independent baby, I know she workin'\n",
267
+ "Adriana's serving drinks, 20 bottles, urgent\n",
268
+ "I know it can be better but nobody's perfect\n",
269
+ "We flirted for a minute, DeJ, that's my baby\n",
270
+ "I ain't trippin', I'm like Henny, yeah I'm in her kidneys\n",
271
+ "She like to play her songs to the way I'm hittin' it\n",
272
+ "Turn around like, \"Damn Durk, I like the way you hittin' it\"\n",
273
+ "Don't believe the rumors, girl\n",
274
+ "You know I'll do you, girl\n",
275
+ "I don't wanna hear the shit about the niggas\n",
276
+ "That tried to do you, girl\n",
277
+ "Fuck the past right now\n",
278
+ "Shawty got you right now\n",
279
+ "And you hot right now\n",
280
+ "You can get it right now, baby\n",
281
+ "[Chorus: Lil Durk]\n",
282
+ "Ooh, I like the way she move\n",
283
+ "Shorty my baby, my everything, she the truth\n",
284
+ "Together we cool, me and her can't lose\n",
285
+ "Keep 'em on their feet, baby, I know they so confused\n",
286
+ "Shorty my Beyoncé\n",
287
+ "Durk and DeJ, Durk and DeJ, Durk and DeJ\n",
288
+ "Shorty my Beyoncé\n",
289
+ "Durk and DeJ, Durk and DeJ, Durk and DeJ\n",
290
+ "My Beyoncé\n",
291
+ "[Verse 2: DeJ Loaf]\n",
292
+ "I let him get it when he want it, knock it down and push up on it\n",
293
+ "I was plottin' for a while, now I got him where I want him\n",
294
+ "They didn't understand none of this was planned\n",
295
+ "99 problems but a bitch better not be none\n",
296
+ "Na na, na na, yeah yeah\n",
297
+ "This ain't what he want, I told him that\n",
298
+ "Leave your girl, be through with that\n",
299
+ "Get with DeJ, he ain't ever goin' back\n",
300
+ "He was shy when I seen him, now he smile\n",
301
+ "Heard a few rumors but they ain't my style\n",
302
+ "I be hatin' when he out of town\n",
303
+ "Hotel, I FaceTime you, no towel\n",
304
+ "They ain't get it but they ain't our problem\n",
305
+ "What the fuck can they do about it?\n",
306
+ "Durk and DeJ\n",
307
+ "I'm thinkin' 'bout changin' my last name\n",
308
+ "[Chorus: Lil Durk]\n",
309
+ "Ooh, I like the way she move\n",
310
+ "Shorty my baby, my everything, she the truth\n",
311
+ "Together we cool, me and her can't lose\n",
312
+ "Keep 'em on their feet, baby, I know they so confused\n",
313
+ "Shorty my Beyoncé\n",
314
+ "Durk and DeJ, Durk and DeJ, Durk and DeJ\n",
315
+ "Shorty my Beyoncé\n",
316
+ "Durk and DeJ, Durk and DeJ, Durk and DeJ\n",
317
+ "My Beyoncé\n",
318
+ "\n",
319
+ "[Verse 3: Lil Durk]\n",
320
+ "You and I\n",
321
+ "White dress, flowers, and a suit and tie\n",
322
+ "Me and you like Bonnie and Clyde\n",
323
+ "No beat the case, we're do or die\n",
324
+ "Who am I to say you ain't natural?\n",
325
+ "Your haters my haters, ain't switchin' up, baby, I got you\n",
326
+ "I'm with her like a tattoo\n",
327
+ "The way you wear that dress, they gon' attack you\n",
328
+ "The way you look at me, baby, I got you\n",
329
+ "I hit it from the front, I like the back too\n",
330
+ "She say, \"Lay down so I can ride you\"\n",
331
+ "I know that she fiending\n",
332
+ "She scratchin' my back, I like how she screamin'\n",
333
+ "I fuck her and leave her, she fiending\n",
334
+ "Shawty my Beyoncé\n",
335
+ "[Chorus: Lil Durk]\n",
336
+ "Ooh, I like the way she move\n",
337
+ "Shorty my baby, my everything, she the truth\n",
338
+ "Together we cool, me and her can't lose\n",
339
+ "Keep 'em on their feet, baby, I know they so confused\n",
340
+ "Shorty my Beyoncé\n",
341
+ "Durk and DeJ, Durk and DeJ, Durk and DeJ\n",
342
+ "Shorty my Beyoncé\n",
343
+ "Durk and DeJ, Durk and DeJ, Durk and DeJ\n",
344
+ "My Beyoncé\n",
345
+ "\n",
346
+ "[Outro: Lil Durk]\n",
347
+ "Ooh, ooh\n",
348
+ "Durk and DeJ, Durk and DeJ, Durk and DeJ\n",
349
+ "Ooh, ooh43EmbedShare URLCopyEmbedCopy\n",
350
+ "<EOS>\n"
351
+ ]
352
+ }
353
+ ],
354
+ "source": [
355
+ "print(List_val[0])"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "code",
360
+ "execution_count": 18,
361
+ "id": "5dfecab1",
362
+ "metadata": {},
363
+ "outputs": [],
364
+ "source": [
365
+ "val_set =List_val[0]\n",
366
+ "for i in range(1,len(List_val)):\n",
367
+ " val_set = val_set+List_val[i]"
368
+ ]
369
+ },
370
+ {
371
+ "cell_type": "code",
372
+ "execution_count": 19,
373
+ "id": "3a895d2f",
374
+ "metadata": {},
375
+ "outputs": [],
376
+ "source": [
377
+ "train_set =List_train[0]\n",
378
+ "for i in range(1,len(List_train)):\n",
379
+ " train_set = train_set+List_train[i]"
380
+ ]
381
+ },
382
+ {
383
+ "cell_type": "code",
384
+ "execution_count": 20,
385
+ "id": "74ea6efc",
386
+ "metadata": {},
387
+ "outputs": [],
388
+ "source": [
389
+ "file1 = open(\"train.txt\",\"w+\")\n",
390
+ "file1.write(train_set)\n",
391
+ "file1.close()"
392
+ ]
393
+ },
394
+ {
395
+ "cell_type": "code",
396
+ "execution_count": 21,
397
+ "id": "3416e6da",
398
+ "metadata": {},
399
+ "outputs": [],
400
+ "source": [
401
+ "file2 = open(\"val.txt\",\"w+\")\n",
402
+ "file2.write(val_set)\n",
403
+ "file2.close()"
404
+ ]
405
+ },
406
+ {
407
+ "cell_type": "code",
408
+ "execution_count": null,
409
+ "id": "1bd0ca86",
410
+ "metadata": {},
411
+ "outputs": [],
412
+ "source": []
413
+ }
414
+ ],
415
+ "metadata": {
416
+ "kernelspec": {
417
+ "display_name": "Python 3 (ipykernel)",
418
+ "language": "python",
419
+ "name": "python3"
420
+ },
421
+ "language_info": {
422
+ "codemirror_mode": {
423
+ "name": "ipython",
424
+ "version": 3
425
+ },
426
+ "file_extension": ".py",
427
+ "mimetype": "text/x-python",
428
+ "name": "python",
429
+ "nbconvert_exporter": "python",
430
+ "pygments_lexer": "ipython3",
431
+ "version": "3.8.10"
432
+ }
433
+ },
434
+ "nbformat": 4,
435
+ "nbformat_minor": 5
436
+ }
config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_function": "gelu_new",
3
+ "architectures": [
4
+ "GPT2LMHeadModel"
5
+ ],
6
+ "attn_pdrop": 0.1,
7
+ "bos_token_id": 50256,
8
+ "embd_pdrop": 0.1,
9
+ "eos_token_id": 50256,
10
+ "gradient_checkpointing": false,
11
+ "initializer_range": 0.02,
12
+ "layer_norm_epsilon": 1e-05,
13
+ "model_type": "gpt2",
14
+ "n_ctx": 1024,
15
+ "n_embd": 768,
16
+ "n_head": 12,
17
+ "n_inner": null,
18
+ "n_layer": 12,
19
+ "n_positions": 1024,
20
+ "resid_pdrop": 0.1,
21
+ "scale_attn_weights": true,
22
+ "summary_activation": null,
23
+ "summary_first_dropout": 0.1,
24
+ "summary_proj_to_labels": true,
25
+ "summary_type": "cls_index",
26
+ "summary_use_proj": true,
27
+ "task_specific_params": {
28
+ "text-generation": {
29
+ "do_sample": true,
30
+ "max_length": 50
31
+ }
32
+ },
33
+ "transformers_version": "4.9.0.dev0",
34
+ "use_cache": true,
35
+ "vocab_size": 50257
36
+ }
flax_model.msgpack ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e12947417fc788cb2b8252765ca2297987abde75ee501fbb7dfa41a2e5a4d68
3
+ size 497764120
jere.sh ADDED
File without changes
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
run.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/env bash
2
+ python3 run_clm_flax.py \
3
+ --output_dir="./" \
4
+ --model_type="gpt2" \
5
+ --config_name="./" \
6
+ --tokenizer_name="./" \
7
+ --train_file="/home/anantshankhdhar/gpt2-rap-lyric-generator/train.txt" \
8
+ --validation_file="/home/anantshankhdhar/gpt2-rap-lyric-generator/val.txt" \
9
+ --do_train \
10
+ --do_eval \
11
+ --block_size="512" \
12
+ --per_device_train_batch_size="64" \
13
+ --per_device_eval_batch_size="32" \
14
+ --learning_rate="5e-3" \
15
+ --adam_beta1="0.9" --adam_beta2="0.98" --weight_decay="0.01" \
16
+ --overwrite_output_dir \
17
+ --num_train_epochs="50" \
18
+ --save_steps="100" \
19
+ --eval_steps="100" \
20
+ --push_to_hub
run_clm_flax.py ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Team All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Pre-training/Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset.
18
+
19
+ Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
20
+ https://huggingface.co/models?filter=causal-lm
21
+ """
22
+ # You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.
23
+
24
+ import logging
25
+ import math
26
+ import os
27
+ import sys
28
+ import time
29
+ from dataclasses import dataclass, field
30
+ from pathlib import Path
31
+ from typing import Callable, Optional
32
+
33
+ import datasets
34
+ from datasets import Dataset, load_dataset
35
+ from tqdm import tqdm
36
+
37
+ import jax
38
+ import jax.numpy as jnp
39
+ import optax
40
+ import transformers
41
+ from flax import jax_utils, traverse_util
42
+ from flax.jax_utils import unreplicate
43
+ from flax.training import train_state
44
+ from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key
45
+ from transformers import (
46
+ CONFIG_MAPPING,
47
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
48
+ AutoConfig,
49
+ AutoTokenizer,
50
+ FlaxAutoModelForCausalLM,
51
+ HfArgumentParser,
52
+ TrainingArguments,
53
+ is_tensorboard_available,
54
+ )
55
+ from transformers.testing_utils import CaptureLogger
56
+
57
+
58
+ logger = logging.getLogger(__name__)
59
+
60
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_CAUSAL_LM_MAPPING.keys())
61
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
62
+
63
+
64
+ @dataclass
65
+ class ModelArguments:
66
+ """
67
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
68
+ """
69
+
70
+ model_name_or_path: Optional[str] = field(
71
+ default=None,
72
+ metadata={
73
+ "help": "The model checkpoint for weights initialization."
74
+ "Don't set if you want to train a model from scratch."
75
+ },
76
+ )
77
+ model_type: Optional[str] = field(
78
+ default=None,
79
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
80
+ )
81
+ config_name: Optional[str] = field(
82
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
83
+ )
84
+ tokenizer_name: Optional[str] = field(
85
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
86
+ )
87
+ cache_dir: Optional[str] = field(
88
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
89
+ )
90
+ use_fast_tokenizer: bool = field(
91
+ default=True,
92
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
93
+ )
94
+ dtype: Optional[str] = field(
95
+ default="float32",
96
+ metadata={
97
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
98
+ },
99
+ )
100
+
101
+
102
+ @dataclass
103
+ class DataTrainingArguments:
104
+ """
105
+ Arguments pertaining to what data we are going to input our model for training and eval.
106
+ """
107
+
108
+ dataset_name: Optional[str] = field(
109
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
110
+ )
111
+ dataset_config_name: Optional[str] = field(
112
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
113
+ )
114
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
115
+ validation_file: Optional[str] = field(
116
+ default=None,
117
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
118
+ )
119
+ max_train_samples: Optional[int] = field(
120
+ default=None,
121
+ metadata={
122
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
123
+ "value if set."
124
+ },
125
+ )
126
+ max_eval_samples: Optional[int] = field(
127
+ default=None,
128
+ metadata={
129
+ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
130
+ "value if set."
131
+ },
132
+ )
133
+ overwrite_cache: bool = field(
134
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
135
+ )
136
+ validation_split_percentage: Optional[int] = field(
137
+ default=5,
138
+ metadata={
139
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
140
+ },
141
+ )
142
+ block_size: Optional[int] = field(
143
+ default=None,
144
+ metadata={
145
+ "help": "Optional input sequence length after tokenization. "
146
+ "The training dataset will be truncated in block of this size for training. "
147
+ "Default to the model max input length for single sentence inputs (take into account special tokens)."
148
+ },
149
+ )
150
+ overwrite_cache: bool = field(
151
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
152
+ )
153
+ preprocessing_num_workers: Optional[int] = field(
154
+ default=None,
155
+ metadata={"help": "The number of processes to use for the preprocessing."},
156
+ )
157
+
158
+ def __post_init__(self):
159
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
160
+ raise ValueError("Need either a dataset name or a training/validation file.")
161
+ else:
162
+ if self.train_file is not None:
163
+ extension = self.train_file.split(".")[-1]
164
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
165
+ if self.validation_file is not None:
166
+ extension = self.validation_file.split(".")[-1]
167
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
168
+
169
+
170
+ class TrainState(train_state.TrainState):
171
+ dropout_rng: jnp.ndarray
172
+
173
+ def replicate(self):
174
+ return jax_utils.replicate(self).replace(dropout_rng=shard_prng_key(self.dropout_rng))
175
+
176
+
177
+ def data_loader(rng: jax.random.PRNGKey, dataset: Dataset, batch_size: int, shuffle: bool = False):
178
+ """
179
+ Returns batches of size `batch_size` from truncated `dataset`, sharded over all local devices.
180
+ Shuffle batches if `shuffle` is `True`.
181
+ """
182
+ steps_per_epoch = len(dataset) // batch_size
183
+
184
+ if shuffle:
185
+ batch_idx = jax.random.permutation(rng, len(dataset))
186
+ else:
187
+ batch_idx = jnp.arange(len(dataset))
188
+
189
+ batch_idx = batch_idx[: steps_per_epoch * batch_size] # Skip incomplete batch.
190
+ batch_idx = batch_idx.reshape((steps_per_epoch, batch_size))
191
+
192
+ for idx in batch_idx:
193
+ batch = dataset[idx]
194
+ batch = {k: jnp.array(v) for k, v in batch.items()}
195
+
196
+ batch = shard(batch)
197
+
198
+ yield batch
199
+
200
+
201
+ def write_train_metric(summary_writer, train_metrics, train_time, step):
202
+ summary_writer.scalar("train_time", train_time, step)
203
+
204
+ train_metrics = get_metrics(train_metrics)
205
+ for key, vals in train_metrics.items():
206
+ tag = f"train_{key}"
207
+ for i, val in enumerate(vals):
208
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
209
+
210
+
211
+ def write_eval_metric(summary_writer, eval_metrics, step):
212
+ for metric_name, value in eval_metrics.items():
213
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
214
+
215
+
216
+ def create_learning_rate_fn(
217
+ train_ds_size: int, train_batch_size: int, num_train_epochs: int, num_warmup_steps: int, learning_rate: float
218
+ ) -> Callable[[int], jnp.array]:
219
+ """Returns a linear warmup, linear_decay learning rate function."""
220
+ steps_per_epoch = train_ds_size // train_batch_size
221
+ num_train_steps = steps_per_epoch * num_train_epochs
222
+ warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps)
223
+ decay_fn = optax.linear_schedule(
224
+ init_value=learning_rate, end_value=0, transition_steps=num_train_steps - num_warmup_steps
225
+ )
226
+ schedule_fn = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[num_warmup_steps])
227
+ return schedule_fn
228
+
229
+
230
+ def main():
231
+ # See all possible arguments in src/transformers/training_args.py
232
+ # or by passing the --help flag to this script.
233
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
234
+
235
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
236
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
237
+ # If we pass only one argument to the script and it's the path to a json file,
238
+ # let's parse it to get our arguments.
239
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
240
+ else:
241
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
242
+
243
+ if (
244
+ os.path.exists(training_args.output_dir)
245
+ and os.listdir(training_args.output_dir)
246
+ and training_args.do_train
247
+ and not training_args.overwrite_output_dir
248
+ ):
249
+ raise ValueError(
250
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
251
+ "Use --overwrite_output_dir to overcome."
252
+ )
253
+
254
+ # Make one log on every process with the configuration for debugging.
255
+ logging.basicConfig(
256
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
257
+ datefmt="%m/%d/%Y %H:%M:%S",
258
+ level=logging.INFO,
259
+ )
260
+ # Setup logging, we only want one process per machine to log things on the screen.
261
+ logger.setLevel(logging.INFO if jax.process_index() == 0 else logging.ERROR)
262
+ if jax.process_index() == 0:
263
+ datasets.utils.logging.set_verbosity_warning()
264
+ transformers.utils.logging.set_verbosity_info()
265
+ else:
266
+ datasets.utils.logging.set_verbosity_error()
267
+ transformers.utils.logging.set_verbosity_error()
268
+
269
+ # Set the verbosity to info of the Transformers logger (on main process only):
270
+ logger.info(f"Training/evaluation parameters {training_args}")
271
+
272
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
273
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
274
+ # (the dataset will be downloaded automatically from the datasets Hub).
275
+ #
276
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
277
+ # 'text' is found. You can easily tweak this behavior (see below).
278
+ #
279
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
280
+ # download the dataset.
281
+ if data_args.dataset_name is not None:
282
+ # Downloading and loading a dataset from the hub.
283
+ dataset = load_dataset(
284
+ data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, keep_in_memory=False
285
+ )
286
+
287
+ if "validation" not in dataset.keys():
288
+ dataset["validation"] = load_dataset(
289
+ data_args.dataset_name,
290
+ data_args.dataset_config_name,
291
+ split=f"train[:{data_args.validation_split_percentage}%]",
292
+ cache_dir=model_args.cache_dir,
293
+ )
294
+ dataset["train"] = load_dataset(
295
+ data_args.dataset_name,
296
+ data_args.dataset_config_name,
297
+ split=f"train[{data_args.validation_split_percentage}%:]",
298
+ cache_dir=model_args.cache_dir,
299
+ )
300
+ else:
301
+ data_files = {}
302
+ if data_args.train_file is not None:
303
+ data_files["train"] = data_args.train_file
304
+ if data_args.validation_file is not None:
305
+ data_files["validation"] = data_args.validation_file
306
+ extension = data_args.train_file.split(".")[-1]
307
+ if extension == "txt":
308
+ extension = "text"
309
+ dataset = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
310
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
311
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
312
+
313
+ # Load pretrained model and tokenizer
314
+
315
+ # Distributed training:
316
+ # The .from_pretrained methods guarantee that only one local process can concurrently
317
+ # download model & vocab.
318
+ if model_args.config_name:
319
+ config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
320
+ elif model_args.model_name_or_path:
321
+ config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
322
+ else:
323
+ config = CONFIG_MAPPING[model_args.model_type]()
324
+ logger.warning("You are instantiating a new config instance from scratch.")
325
+
326
+ if model_args.tokenizer_name:
327
+ tokenizer = AutoTokenizer.from_pretrained(
328
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
329
+ )
330
+ elif model_args.model_name_or_path:
331
+ tokenizer = AutoTokenizer.from_pretrained(
332
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
333
+ )
334
+ else:
335
+ raise ValueError(
336
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
337
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
338
+ )
339
+
340
+ if model_args.model_name_or_path:
341
+ model = FlaxAutoModelForCausalLM.from_pretrained(
342
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
343
+ )
344
+ else:
345
+ model = FlaxAutoModelForCausalLM.from_config(
346
+ config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
347
+ )
348
+
349
+ # Preprocessing the datasets.
350
+ # First we tokenize all the texts.
351
+ if training_args.do_train:
352
+ column_names = dataset["train"].column_names
353
+ else:
354
+ column_names = dataset["validation"].column_names
355
+ text_column_name = "text" if "text" in column_names else column_names[0]
356
+
357
+ # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function
358
+ tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base")
359
+
360
+ def tokenize_function(examples):
361
+ with CaptureLogger(tok_logger) as cl:
362
+ output = tokenizer(examples[text_column_name])
363
+ # clm input could be much much longer than block_size
364
+ if "Token indices sequence length is longer than the" in cl.out:
365
+ tok_logger.warning(
366
+ "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits before being passed to the model."
367
+ )
368
+ return output
369
+
370
+ tokenized_datasets = dataset.map(
371
+ tokenize_function,
372
+ batched=True,
373
+ num_proc=data_args.preprocessing_num_workers,
374
+ remove_columns=column_names,
375
+ load_from_cache_file=not data_args.overwrite_cache,
376
+ )
377
+
378
+ if data_args.block_size is None:
379
+ block_size = tokenizer.model_max_length
380
+ if block_size > config.max_position_embeddings:
381
+ logger.warning(
382
+ f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
383
+ "Picking 1024 instead. You can change that default value by passing --block_size xxx."
384
+ )
385
+ block_size = 1024
386
+ else:
387
+ if data_args.block_size > tokenizer.model_max_length:
388
+ logger.warning(
389
+ f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model"
390
+ f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
391
+ )
392
+ block_size = min(data_args.block_size, tokenizer.model_max_length)
393
+
394
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
395
+ def group_texts(examples):
396
+ # Concatenate all texts.
397
+ concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
398
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
399
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
400
+ # customize this part to your needs.
401
+ total_length = (total_length // block_size) * block_size
402
+ # Split by chunks of max_len.
403
+ result = {
404
+ k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
405
+ for k, t in concatenated_examples.items()
406
+ }
407
+ result["labels"] = result["input_ids"].copy()
408
+ return result
409
+
410
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
411
+ # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
412
+ # to preprocess.
413
+ #
414
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
415
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
416
+
417
+ lm_datasets = tokenized_datasets.map(
418
+ group_texts,
419
+ batched=True,
420
+ num_proc=data_args.preprocessing_num_workers,
421
+ load_from_cache_file=not data_args.overwrite_cache,
422
+ )
423
+
424
+ if training_args.do_train:
425
+ if "train" not in tokenized_datasets:
426
+ raise ValueError("--do_train requires a train dataset")
427
+ train_dataset = lm_datasets["train"]
428
+ if data_args.max_train_samples is not None:
429
+ train_dataset = train_dataset.select(range(data_args.max_train_samples))
430
+
431
+ if training_args.do_eval:
432
+ if "validation" not in tokenized_datasets:
433
+ raise ValueError("--do_eval requires a validation dataset")
434
+ eval_dataset = lm_datasets["validation"]
435
+ if data_args.max_eval_samples is not None:
436
+ eval_dataset = eval_dataset.select(range(data_args.max_eval_samples))
437
+
438
+ # Enable tensorboard only on the master node
439
+ has_tensorboard = is_tensorboard_available()
440
+ if has_tensorboard and jax.process_index() == 0:
441
+ try:
442
+ from flax.metrics.tensorboard import SummaryWriter
443
+
444
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
445
+ except ImportError as ie:
446
+ has_tensorboard = False
447
+ logger.warning(
448
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
449
+ )
450
+ else:
451
+ logger.warning(
452
+ "Unable to display metrics through TensorBoard because the package is not installed: "
453
+ "Please run pip install tensorboard to enable."
454
+ )
455
+
456
+ # Initialize our training
457
+ rng = jax.random.PRNGKey(training_args.seed)
458
+ rng, dropout_rng = jax.random.split(rng)
459
+
460
+ # Store some constant
461
+ num_epochs = int(training_args.num_train_epochs)
462
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
463
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
464
+ steps_per_epoch = len(train_dataset) // train_batch_size
465
+ total_train_steps = steps_per_epoch * num_epochs
466
+
467
+ # Create learning rate schedule
468
+ linear_decay_lr_schedule_fn = create_learning_rate_fn(
469
+ len(train_dataset),
470
+ train_batch_size,
471
+ training_args.num_train_epochs,
472
+ training_args.warmup_steps,
473
+ training_args.learning_rate,
474
+ )
475
+
476
+ # We use Optax's "masking" functionality to not apply weight decay
477
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
478
+ # mask boolean with the same structure as the parameters.
479
+ # The mask is True for parameters that should be decayed.
480
+ # Note that this mask is specifically adapted for FlaxGPT2.
481
+ # For other models, one should correct the layer norm parameter naming
482
+ # accordingly.
483
+ def decay_mask_fn(params):
484
+ flat_params = traverse_util.flatten_dict(params)
485
+ flat_mask = {
486
+ path: (path[-1] != "bias" and path[-2:] not in [("ln_1", "scale"), ("ln_2", "scale"), ("ln_f", "scale")])
487
+ for path in flat_params
488
+ }
489
+ return traverse_util.unflatten_dict(flat_mask)
490
+
491
+ # create adam optimizer
492
+ if training_args.adafactor:
493
+ # We use the default parameters here to initialize adafactor,
494
+ # For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
495
+ optimizer = optax.adafactor(
496
+ learning_rate=linear_decay_lr_schedule_fn,
497
+ )
498
+ else:
499
+ optimizer = optax.adamw(
500
+ learning_rate=linear_decay_lr_schedule_fn,
501
+ b1=training_args.adam_beta1,
502
+ b2=training_args.adam_beta2,
503
+ eps=training_args.adam_epsilon,
504
+ weight_decay=training_args.weight_decay,
505
+ mask=decay_mask_fn,
506
+ )
507
+
508
+ # Setup train state
509
+ state = TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer, dropout_rng=dropout_rng)
510
+
511
+ def loss_fn(logits, labels):
512
+ shift_logits = logits[..., :-1, :]
513
+ shift_labels = labels[..., 1:]
514
+ loss = optax.softmax_cross_entropy(shift_logits, onehot(shift_labels, shift_logits.shape[-1]))
515
+ return loss.mean()
516
+
517
+ # Define gradient update step fn
518
+ def train_step(state, batch):
519
+ dropout_rng, new_dropout_rng = jax.random.split(state.dropout_rng)
520
+
521
+ def compute_loss(params):
522
+ labels = batch.pop("labels")
523
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
524
+ loss = loss_fn(logits, labels)
525
+ return loss
526
+
527
+ grad_fn = jax.value_and_grad(compute_loss)
528
+ loss, grad = grad_fn(state.params)
529
+ grad = jax.lax.pmean(grad, "batch")
530
+
531
+ new_state = state.apply_gradients(grads=grad, dropout_rng=new_dropout_rng)
532
+
533
+ metrics = {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}
534
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
535
+
536
+ return new_state, metrics
537
+
538
+ # Define eval fn
539
+ def eval_step(params, batch):
540
+ labels = batch.pop("labels")
541
+ logits = model(**batch, params=params, train=False)[0]
542
+ loss = loss_fn(logits, labels)
543
+
544
+ # summarize metrics
545
+ metrics = {"loss": loss}
546
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
547
+ return metrics
548
+
549
+ # Create parallel version of the train and eval step
550
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
551
+ p_eval_step = jax.pmap(eval_step, "batch")
552
+
553
+ # Replicate the train state on each device
554
+ state = state.replicate()
555
+
556
+ logger.info("***** Running training *****")
557
+ logger.info(f" Num examples = {len(train_dataset)}")
558
+ logger.info(f" Num Epochs = {num_epochs}")
559
+ logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}")
560
+ logger.info(f" Total train batch size (w. parallel & distributed) = {train_batch_size}")
561
+ logger.info(f" Total optimization steps = {total_train_steps}")
562
+
563
+ train_time = 0
564
+ train_metrics = []
565
+ epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
566
+ for epoch in epochs:
567
+ # ======================== Training ================================
568
+ train_start = time.time()
569
+
570
+ # Create sampling rng
571
+ rng, input_rng = jax.random.split(rng)
572
+
573
+ # Generate an epoch by shuffling sampling indices from the train dataset
574
+ train_loader = data_loader(input_rng, train_dataset, train_batch_size, shuffle=True)
575
+ steps_per_epoch = len(train_dataset) // train_batch_size
576
+ # train
577
+ for step in tqdm(range(steps_per_epoch), desc="Training...", position=1, leave=False):
578
+ batch = next(train_loader)
579
+ state, train_metric = p_train_step(state, batch)
580
+ train_metrics.append(train_metric)
581
+
582
+ cur_step = epoch * (len(train_dataset) // train_batch_size) + step
583
+
584
+ if cur_step % training_args.logging_steps == 0 and cur_step > 0:
585
+ # Save metrics
586
+ train_metric = unreplicate(train_metric)
587
+ train_time += time.time() - train_start
588
+ if has_tensorboard and jax.process_index() == 0:
589
+ write_train_metric(summary_writer, train_metrics, train_time, cur_step)
590
+
591
+ epochs.write(
592
+ f"Step... ({cur_step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
593
+ )
594
+
595
+ train_metrics = []
596
+
597
+ if cur_step % training_args.eval_steps == 0 and cur_step > 0:
598
+ # ======================== Evaluating ==============================
599
+ eval_metrics = []
600
+ eval_loader = data_loader(input_rng, eval_dataset, eval_batch_size)
601
+ eval_steps = len(eval_dataset) // eval_batch_size
602
+ for _ in tqdm(range(eval_steps), desc="Evaluating...", position=2, leave=False):
603
+ # Model forward
604
+ batch = next(eval_loader)
605
+ metrics = p_eval_step(state.params, batch)
606
+ eval_metrics.append(metrics)
607
+
608
+ # normalize eval metrics
609
+ eval_metrics = get_metrics(eval_metrics)
610
+ eval_metrics = jax.tree_map(jnp.mean, eval_metrics)
611
+
612
+ try:
613
+ eval_metrics["perplexity"] = math.exp(eval_metrics["loss"])
614
+ except OverflowError:
615
+ eval_metrics["perplexity"] = float("inf")
616
+
617
+ # Print metrics and update progress bar
618
+ desc = f"Step... ({cur_step} | Eval Loss: {eval_metrics['loss']} | Eval Perplexity: {eval_metrics['perplexity']})"
619
+ epochs.write(desc)
620
+ epochs.desc = desc
621
+
622
+ # Save metrics
623
+ if has_tensorboard and jax.process_index() == 0:
624
+ cur_step = epoch * (len(train_dataset) // train_batch_size)
625
+ write_eval_metric(summary_writer, eval_metrics, cur_step)
626
+
627
+ if cur_step % training_args.save_steps == 0 and cur_step > 0:
628
+ # save checkpoint after each epoch and push checkpoint to the hub
629
+ if jax.process_index() == 0:
630
+ params = jax.device_get(unreplicate(state.params))
631
+ model.save_pretrained(
632
+ training_args.output_dir,
633
+ params=params,
634
+ push_to_hub=training_args.push_to_hub,
635
+ commit_message=f"Saving weights and logs of step {cur_step}",
636
+ )
637
+
638
+
639
+ if __name__ == "__main__":
640
+ main()
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
train.txt ADDED
The diff for this file is too large to render. See raw diff
 
val.txt ADDED
The diff for this file is too large to render. See raw diff
 
vocab.json ADDED
The diff for this file is too large to render. See raw diff