Upload 10 files
Browse files- added_tokens.json +652 -0
- build_mlp.py +205 -0
- config.json +37 -0
- configuration_internlm.py +164 -0
- generation_config.json +7 -0
- modeling_internlm2.py +1332 -0
- special_tokens_map.json +6 -0
- tokenization_internlm.py +240 -0
- tokenizer.model +3 -0
- tokenizer_config.json +16 -0
added_tokens.json
ADDED
@@ -0,0 +1,652 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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<112>": 92558,
|
17 |
+
"<113>": 92559,
|
18 |
+
"<114>": 92560,
|
19 |
+
"<115>": 92561,
|
20 |
+
"<116>": 92562,
|
21 |
+
"<117>": 92563,
|
22 |
+
"<118>": 92564,
|
23 |
+
"<119>": 92565,
|
24 |
+
"<11>": 92566,
|
25 |
+
"<120>": 92567,
|
26 |
+
"<121>": 92568,
|
27 |
+
"<122>": 92569,
|
28 |
+
"<123>": 92570,
|
29 |
+
"<124>": 92571,
|
30 |
+
"<125>": 92572,
|
31 |
+
"<126>": 92573,
|
32 |
+
"<127>": 92574,
|
33 |
+
"<128>": 92575,
|
34 |
+
"<129>": 92576,
|
35 |
+
"<12>": 92577,
|
36 |
+
"<130>": 92578,
|
37 |
+
"<131>": 92579,
|
38 |
+
"<132>": 92580,
|
39 |
+
"<133>": 92581,
|
40 |
+
"<134>": 92582,
|
41 |
+
"<135>": 92583,
|
42 |
+
"<136>": 92584,
|
43 |
+
"<137>": 92585,
|
44 |
+
"<138>": 92586,
|
45 |
+
"<139>": 92587,
|
46 |
+
"<13>": 92588,
|
47 |
+
"<140>": 92589,
|
48 |
+
"<141>": 92590,
|
49 |
+
"<142>": 92591,
|
50 |
+
"<143>": 92592,
|
51 |
+
"<144>": 92593,
|
52 |
+
"<145>": 92594,
|
53 |
+
"<146>": 92595,
|
54 |
+
"<147>": 92596,
|
55 |
+
"<148>": 92597,
|
56 |
+
"<149>": 92598,
|
57 |
+
"<14>": 92599,
|
58 |
+
"<150>": 92600,
|
59 |
+
"<151>": 92601,
|
60 |
+
"<152>": 92602,
|
61 |
+
"<153>": 92603,
|
62 |
+
"<154>": 92604,
|
63 |
+
"<155>": 92605,
|
64 |
+
"<156>": 92606,
|
65 |
+
"<157>": 92607,
|
66 |
+
"<158>": 92608,
|
67 |
+
"<159>": 92609,
|
68 |
+
"<15>": 92610,
|
69 |
+
"<160>": 92611,
|
70 |
+
"<161>": 92612,
|
71 |
+
"<162>": 92613,
|
72 |
+
"<163>": 92614,
|
73 |
+
"<164>": 92615,
|
74 |
+
"<165>": 92616,
|
75 |
+
"<166>": 92617,
|
76 |
+
"<167>": 92618,
|
77 |
+
"<168>": 92619,
|
78 |
+
"<169>": 92620,
|
79 |
+
"<16>": 92621,
|
80 |
+
"<170>": 92622,
|
81 |
+
"<171>": 92623,
|
82 |
+
"<172>": 92624,
|
83 |
+
"<173>": 92625,
|
84 |
+
"<174>": 92626,
|
85 |
+
"<175>": 92627,
|
86 |
+
"<176>": 92628,
|
87 |
+
"<177>": 92629,
|
88 |
+
"<178>": 92630,
|
89 |
+
"<179>": 92631,
|
90 |
+
"<17>": 92632,
|
91 |
+
"<180>": 92633,
|
92 |
+
"<181>": 92634,
|
93 |
+
"<182>": 92635,
|
94 |
+
"<183>": 92636,
|
95 |
+
"<184>": 92637,
|
96 |
+
"<185>": 92638,
|
97 |
+
"<186>": 92639,
|
98 |
+
"<187>": 92640,
|
99 |
+
"<188>": 92641,
|
100 |
+
"<189>": 92642,
|
101 |
+
"<18>": 92643,
|
102 |
+
"<190>": 92644,
|
103 |
+
"<191>": 92645,
|
104 |
+
"<192>": 92646,
|
105 |
+
"<193>": 92647,
|
106 |
+
"<194>": 92648,
|
107 |
+
"<195>": 92649,
|
108 |
+
"<196>": 92650,
|
109 |
+
"<197>": 92651,
|
110 |
+
"<198>": 92652,
|
111 |
+
"<199>": 92653,
|
112 |
+
"<19>": 92654,
|
113 |
+
"<1>": 92655,
|
114 |
+
"<200>": 92656,
|
115 |
+
"<201>": 92657,
|
116 |
+
"<202>": 92658,
|
117 |
+
"<203>": 92659,
|
118 |
+
"<204>": 92660,
|
119 |
+
"<205>": 92661,
|
120 |
+
"<206>": 92662,
|
121 |
+
"<207>": 92663,
|
122 |
+
"<208>": 92664,
|
123 |
+
"<209>": 92665,
|
124 |
+
"<20>": 92666,
|
125 |
+
"<210>": 92667,
|
126 |
+
"<211>": 92668,
|
127 |
+
"<212>": 92669,
|
128 |
+
"<213>": 92670,
|
129 |
+
"<214>": 92671,
|
130 |
+
"<215>": 92672,
|
131 |
+
"<216>": 92673,
|
132 |
+
"<217>": 92674,
|
133 |
+
"<218>": 92675,
|
134 |
+
"<219>": 92676,
|
135 |
+
"<21>": 92677,
|
136 |
+
"<220>": 92678,
|
137 |
+
"<221>": 92679,
|
138 |
+
"<222>": 92680,
|
139 |
+
"<223>": 92681,
|
140 |
+
"<224>": 92682,
|
141 |
+
"<225>": 92683,
|
142 |
+
"<226>": 92684,
|
143 |
+
"<227>": 92685,
|
144 |
+
"<228>": 92686,
|
145 |
+
"<229>": 92687,
|
146 |
+
"<22>": 92688,
|
147 |
+
"<230>": 92689,
|
148 |
+
"<231>": 92690,
|
149 |
+
"<232>": 92691,
|
150 |
+
"<233>": 92692,
|
151 |
+
"<234>": 92693,
|
152 |
+
"<235>": 92694,
|
153 |
+
"<236>": 92695,
|
154 |
+
"<237>": 92696,
|
155 |
+
"<238>": 92697,
|
156 |
+
"<239>": 92698,
|
157 |
+
"<23>": 92699,
|
158 |
+
"<240>": 92700,
|
159 |
+
"<241>": 92701,
|
160 |
+
"<242>": 92702,
|
161 |
+
"<243>": 92703,
|
162 |
+
"<244>": 92704,
|
163 |
+
"<245>": 92705,
|
164 |
+
"<246>": 92706,
|
165 |
+
"<247>": 92707,
|
166 |
+
"<248>": 92708,
|
167 |
+
"<249>": 92709,
|
168 |
+
"<24>": 92710,
|
169 |
+
"<250>": 92711,
|
170 |
+
"<251>": 92712,
|
171 |
+
"<252>": 92713,
|
172 |
+
"<253>": 92714,
|
173 |
+
"<254>": 92715,
|
174 |
+
"<255>": 92716,
|
175 |
+
"<256>": 92717,
|
176 |
+
"<257>": 92718,
|
177 |
+
"<258>": 92719,
|
178 |
+
"<259>": 92720,
|
179 |
+
"<25>": 92721,
|
180 |
+
"<260>": 92722,
|
181 |
+
"<261>": 92723,
|
182 |
+
"<262>": 92724,
|
183 |
+
"<263>": 92725,
|
184 |
+
"<264>": 92726,
|
185 |
+
"<265>": 92727,
|
186 |
+
"<266>": 92728,
|
187 |
+
"<267>": 92729,
|
188 |
+
"<268>": 92730,
|
189 |
+
"<269>": 92731,
|
190 |
+
"<26>": 92732,
|
191 |
+
"<270>": 92733,
|
192 |
+
"<271>": 92734,
|
193 |
+
"<272>": 92735,
|
194 |
+
"<273>": 92736,
|
195 |
+
"<274>": 92737,
|
196 |
+
"<275>": 92738,
|
197 |
+
"<276>": 92739,
|
198 |
+
"<277>": 92740,
|
199 |
+
"<278>": 92741,
|
200 |
+
"<279>": 92742,
|
201 |
+
"<27>": 92743,
|
202 |
+
"<280>": 92744,
|
203 |
+
"<281>": 92745,
|
204 |
+
"<282>": 92746,
|
205 |
+
"<283>": 92747,
|
206 |
+
"<284>": 92748,
|
207 |
+
"<285>": 92749,
|
208 |
+
"<286>": 92750,
|
209 |
+
"<287>": 92751,
|
210 |
+
"<288>": 92752,
|
211 |
+
"<289>": 92753,
|
212 |
+
"<28>": 92754,
|
213 |
+
"<290>": 92755,
|
214 |
+
"<291>": 92756,
|
215 |
+
"<292>": 92757,
|
216 |
+
"<293>": 92758,
|
217 |
+
"<294>": 92759,
|
218 |
+
"<295>": 92760,
|
219 |
+
"<296>": 92761,
|
220 |
+
"<297>": 92762,
|
221 |
+
"<298>": 92763,
|
222 |
+
"<299>": 92764,
|
223 |
+
"<29>": 92765,
|
224 |
+
"<2>": 92766,
|
225 |
+
"<300>": 92767,
|
226 |
+
"<301>": 92768,
|
227 |
+
"<302>": 92769,
|
228 |
+
"<303>": 92770,
|
229 |
+
"<304>": 92771,
|
230 |
+
"<305>": 92772,
|
231 |
+
"<306>": 92773,
|
232 |
+
"<307>": 92774,
|
233 |
+
"<308>": 92775,
|
234 |
+
"<309>": 92776,
|
235 |
+
"<30>": 92777,
|
236 |
+
"<310>": 92778,
|
237 |
+
"<311>": 92779,
|
238 |
+
"<312>": 92780,
|
239 |
+
"<313>": 92781,
|
240 |
+
"<314>": 92782,
|
241 |
+
"<315>": 92783,
|
242 |
+
"<316>": 92784,
|
243 |
+
"<317>": 92785,
|
244 |
+
"<318>": 92786,
|
245 |
+
"<319>": 92787,
|
246 |
+
"<31>": 92788,
|
247 |
+
"<320>": 92789,
|
248 |
+
"<321>": 92790,
|
249 |
+
"<322>": 92791,
|
250 |
+
"<323>": 92792,
|
251 |
+
"<324>": 92793,
|
252 |
+
"<325>": 92794,
|
253 |
+
"<326>": 92795,
|
254 |
+
"<327>": 92796,
|
255 |
+
"<328>": 92797,
|
256 |
+
"<329>": 92798,
|
257 |
+
"<32>": 92799,
|
258 |
+
"<330>": 92800,
|
259 |
+
"<331>": 92801,
|
260 |
+
"<332>": 92802,
|
261 |
+
"<333>": 92803,
|
262 |
+
"<334>": 92804,
|
263 |
+
"<335>": 92805,
|
264 |
+
"<336>": 92806,
|
265 |
+
"<337>": 92807,
|
266 |
+
"<338>": 92808,
|
267 |
+
"<339>": 92809,
|
268 |
+
"<33>": 92810,
|
269 |
+
"<340>": 92811,
|
270 |
+
"<341>": 92812,
|
271 |
+
"<342>": 92813,
|
272 |
+
"<343>": 92814,
|
273 |
+
"<344>": 92815,
|
274 |
+
"<345>": 92816,
|
275 |
+
"<346>": 92817,
|
276 |
+
"<347>": 92818,
|
277 |
+
"<348>": 92819,
|
278 |
+
"<349>": 92820,
|
279 |
+
"<34>": 92821,
|
280 |
+
"<350>": 92822,
|
281 |
+
"<351>": 92823,
|
282 |
+
"<352>": 92824,
|
283 |
+
"<353>": 92825,
|
284 |
+
"<354>": 92826,
|
285 |
+
"<355>": 92827,
|
286 |
+
"<356>": 92828,
|
287 |
+
"<357>": 92829,
|
288 |
+
"<358>": 92830,
|
289 |
+
"<359>": 92831,
|
290 |
+
"<35>": 92832,
|
291 |
+
"<360>": 92833,
|
292 |
+
"<361>": 92834,
|
293 |
+
"<362>": 92835,
|
294 |
+
"<363>": 92836,
|
295 |
+
"<364>": 92837,
|
296 |
+
"<365>": 92838,
|
297 |
+
"<366>": 92839,
|
298 |
+
"<367>": 92840,
|
299 |
+
"<368>": 92841,
|
300 |
+
"<369>": 92842,
|
301 |
+
"<36>": 92843,
|
302 |
+
"<370>": 92844,
|
303 |
+
"<371>": 92845,
|
304 |
+
"<372>": 92846,
|
305 |
+
"<373>": 92847,
|
306 |
+
"<374>": 92848,
|
307 |
+
"<375>": 92849,
|
308 |
+
"<376>": 92850,
|
309 |
+
"<377>": 92851,
|
310 |
+
"<378>": 92852,
|
311 |
+
"<379>": 92853,
|
312 |
+
"<37>": 92854,
|
313 |
+
"<380>": 92855,
|
314 |
+
"<381>": 92856,
|
315 |
+
"<382>": 92857,
|
316 |
+
"<383>": 92858,
|
317 |
+
"<384>": 92859,
|
318 |
+
"<385>": 92860,
|
319 |
+
"<386>": 92861,
|
320 |
+
"<387>": 92862,
|
321 |
+
"<388>": 92863,
|
322 |
+
"<389>": 92864,
|
323 |
+
"<38>": 92865,
|
324 |
+
"<390>": 92866,
|
325 |
+
"<391>": 92867,
|
326 |
+
"<392>": 92868,
|
327 |
+
"<393>": 92869,
|
328 |
+
"<394>": 92870,
|
329 |
+
"<395>": 92871,
|
330 |
+
"<396>": 92872,
|
331 |
+
"<397>": 92873,
|
332 |
+
"<398>": 92874,
|
333 |
+
"<399>": 92875,
|
334 |
+
"<39>": 92876,
|
335 |
+
"<3>": 92877,
|
336 |
+
"<400>": 92878,
|
337 |
+
"<401>": 92879,
|
338 |
+
"<402>": 92880,
|
339 |
+
"<403>": 92881,
|
340 |
+
"<404>": 92882,
|
341 |
+
"<405>": 92883,
|
342 |
+
"<406>": 92884,
|
343 |
+
"<407>": 92885,
|
344 |
+
"<408>": 92886,
|
345 |
+
"<409>": 92887,
|
346 |
+
"<40>": 92888,
|
347 |
+
"<410>": 92889,
|
348 |
+
"<411>": 92890,
|
349 |
+
"<412>": 92891,
|
350 |
+
"<413>": 92892,
|
351 |
+
"<414>": 92893,
|
352 |
+
"<415>": 92894,
|
353 |
+
"<416>": 92895,
|
354 |
+
"<417>": 92896,
|
355 |
+
"<418>": 92897,
|
356 |
+
"<419>": 92898,
|
357 |
+
"<41>": 92899,
|
358 |
+
"<420>": 92900,
|
359 |
+
"<421>": 92901,
|
360 |
+
"<422>": 92902,
|
361 |
+
"<423>": 92903,
|
362 |
+
"<424>": 92904,
|
363 |
+
"<425>": 92905,
|
364 |
+
"<426>": 92906,
|
365 |
+
"<427>": 92907,
|
366 |
+
"<428>": 92908,
|
367 |
+
"<429>": 92909,
|
368 |
+
"<42>": 92910,
|
369 |
+
"<430>": 92911,
|
370 |
+
"<431>": 92912,
|
371 |
+
"<432>": 92913,
|
372 |
+
"<433>": 92914,
|
373 |
+
"<434>": 92915,
|
374 |
+
"<435>": 92916,
|
375 |
+
"<436>": 92917,
|
376 |
+
"<437>": 92918,
|
377 |
+
"<438>": 92919,
|
378 |
+
"<439>": 92920,
|
379 |
+
"<43>": 92921,
|
380 |
+
"<440>": 92922,
|
381 |
+
"<441>": 92923,
|
382 |
+
"<442>": 92924,
|
383 |
+
"<443>": 92925,
|
384 |
+
"<444>": 92926,
|
385 |
+
"<445>": 92927,
|
386 |
+
"<446>": 92928,
|
387 |
+
"<447>": 92929,
|
388 |
+
"<448>": 92930,
|
389 |
+
"<449>": 92931,
|
390 |
+
"<44>": 92932,
|
391 |
+
"<450>": 92933,
|
392 |
+
"<451>": 92934,
|
393 |
+
"<452>": 92935,
|
394 |
+
"<453>": 92936,
|
395 |
+
"<454>": 92937,
|
396 |
+
"<455>": 92938,
|
397 |
+
"<456>": 92939,
|
398 |
+
"<457>": 92940,
|
399 |
+
"<458>": 92941,
|
400 |
+
"<459>": 92942,
|
401 |
+
"<45>": 92943,
|
402 |
+
"<460>": 92944,
|
403 |
+
"<461>": 92945,
|
404 |
+
"<462>": 92946,
|
405 |
+
"<463>": 92947,
|
406 |
+
"<464>": 92948,
|
407 |
+
"<465>": 92949,
|
408 |
+
"<466>": 92950,
|
409 |
+
"<467>": 92951,
|
410 |
+
"<468>": 92952,
|
411 |
+
"<469>": 92953,
|
412 |
+
"<46>": 92954,
|
413 |
+
"<470>": 92955,
|
414 |
+
"<471>": 92956,
|
415 |
+
"<472>": 92957,
|
416 |
+
"<473>": 92958,
|
417 |
+
"<474>": 92959,
|
418 |
+
"<475>": 92960,
|
419 |
+
"<476>": 92961,
|
420 |
+
"<477>": 92962,
|
421 |
+
"<478>": 92963,
|
422 |
+
"<479>": 92964,
|
423 |
+
"<47>": 92965,
|
424 |
+
"<480>": 92966,
|
425 |
+
"<481>": 92967,
|
426 |
+
"<482>": 92968,
|
427 |
+
"<483>": 92969,
|
428 |
+
"<484>": 92970,
|
429 |
+
"<485>": 92971,
|
430 |
+
"<486>": 92972,
|
431 |
+
"<487>": 92973,
|
432 |
+
"<488>": 92974,
|
433 |
+
"<489>": 92975,
|
434 |
+
"<48>": 92976,
|
435 |
+
"<490>": 92977,
|
436 |
+
"<491>": 92978,
|
437 |
+
"<492>": 92979,
|
438 |
+
"<493>": 92980,
|
439 |
+
"<494>": 92981,
|
440 |
+
"<495>": 92982,
|
441 |
+
"<496>": 92983,
|
442 |
+
"<497>": 92984,
|
443 |
+
"<498>": 92985,
|
444 |
+
"<499>": 92986,
|
445 |
+
"<49>": 92987,
|
446 |
+
"<4>": 92988,
|
447 |
+
"<500>": 92989,
|
448 |
+
"<501>": 92990,
|
449 |
+
"<502>": 92991,
|
450 |
+
"<503>": 92992,
|
451 |
+
"<504>": 92993,
|
452 |
+
"<505>": 92994,
|
453 |
+
"<506>": 92995,
|
454 |
+
"<507>": 92996,
|
455 |
+
"<508>": 92997,
|
456 |
+
"<509>": 92998,
|
457 |
+
"<50>": 92999,
|
458 |
+
"<510>": 93000,
|
459 |
+
"<511>": 93001,
|
460 |
+
"<51>": 93002,
|
461 |
+
"<52>": 93003,
|
462 |
+
"<53>": 93004,
|
463 |
+
"<54>": 93005,
|
464 |
+
"<55>": 93006,
|
465 |
+
"<56>": 93007,
|
466 |
+
"<57>": 93008,
|
467 |
+
"<58>": 93009,
|
468 |
+
"<59>": 93010,
|
469 |
+
"<5>": 93011,
|
470 |
+
"<60>": 93012,
|
471 |
+
"<61>": 93013,
|
472 |
+
"<62>": 93014,
|
473 |
+
"<63>": 93015,
|
474 |
+
"<64>": 93016,
|
475 |
+
"<65>": 93017,
|
476 |
+
"<66>": 93018,
|
477 |
+
"<67>": 93019,
|
478 |
+
"<68>": 93020,
|
479 |
+
"<69>": 93021,
|
480 |
+
"<6>": 93022,
|
481 |
+
"<70>": 93023,
|
482 |
+
"<71>": 93024,
|
483 |
+
"<72>": 93025,
|
484 |
+
"<73>": 93026,
|
485 |
+
"<74>": 93027,
|
486 |
+
"<75>": 93028,
|
487 |
+
"<76>": 93029,
|
488 |
+
"<77>": 93030,
|
489 |
+
"<78>": 93031,
|
490 |
+
"<79>": 93032,
|
491 |
+
"<7>": 93033,
|
492 |
+
"<80>": 93034,
|
493 |
+
"<81>": 93035,
|
494 |
+
"<82>": 93036,
|
495 |
+
"<83>": 93037,
|
496 |
+
"<84>": 93038,
|
497 |
+
"<85>": 93039,
|
498 |
+
"<86>": 93040,
|
499 |
+
"<87>": 93041,
|
500 |
+
"<88>": 93042,
|
501 |
+
"<89>": 93043,
|
502 |
+
"<8>": 93044,
|
503 |
+
"<90>": 93045,
|
504 |
+
"<91>": 93046,
|
505 |
+
"<92>": 93047,
|
506 |
+
"<93>": 93048,
|
507 |
+
"<94>": 93049,
|
508 |
+
"<95>": 93050,
|
509 |
+
"<96>": 93051,
|
510 |
+
"<97>": 93052,
|
511 |
+
"<98>": 93053,
|
512 |
+
"<99>": 93054,
|
513 |
+
"<9>": 93055,
|
514 |
+
"<A#-1>": 93056,
|
515 |
+
"<A#0>": 93057,
|
516 |
+
"<A#1>": 93058,
|
517 |
+
"<A#2>": 93059,
|
518 |
+
"<A#3>": 93060,
|
519 |
+
"<A#4>": 93061,
|
520 |
+
"<A#5>": 93062,
|
521 |
+
"<A#6>": 93063,
|
522 |
+
"<A#7>": 93064,
|
523 |
+
"<A#8>": 93065,
|
524 |
+
"<A#9>": 93066,
|
525 |
+
"<A-1>": 93067,
|
526 |
+
"<A0>": 93068,
|
527 |
+
"<A1>": 93069,
|
528 |
+
"<A2>": 93070,
|
529 |
+
"<A3>": 93071,
|
530 |
+
"<A4>": 93072,
|
531 |
+
"<A5>": 93073,
|
532 |
+
"<A6>": 93074,
|
533 |
+
"<A7>": 93075,
|
534 |
+
"<A8>": 93076,
|
535 |
+
"<A9>": 93077,
|
536 |
+
"<B-1>": 93078,
|
537 |
+
"<B0>": 93079,
|
538 |
+
"<B1>": 93080,
|
539 |
+
"<B2>": 93081,
|
540 |
+
"<B3>": 93082,
|
541 |
+
"<B4>": 93083,
|
542 |
+
"<B5>": 93084,
|
543 |
+
"<B6>": 93085,
|
544 |
+
"<B7>": 93086,
|
545 |
+
"<B8>": 93087,
|
546 |
+
"<B9>": 93088,
|
547 |
+
"<C#-1>": 93089,
|
548 |
+
"<C#0>": 93090,
|
549 |
+
"<C#1>": 93091,
|
550 |
+
"<C#2>": 93092,
|
551 |
+
"<C#3>": 93093,
|
552 |
+
"<C#4>": 93094,
|
553 |
+
"<C#5>": 93095,
|
554 |
+
"<C#6>": 93096,
|
555 |
+
"<C#7>": 93097,
|
556 |
+
"<C#8>": 93098,
|
557 |
+
"<C#9>": 93099,
|
558 |
+
"<C-1>": 93100,
|
559 |
+
"<C0>": 93101,
|
560 |
+
"<C1>": 93102,
|
561 |
+
"<C2>": 93103,
|
562 |
+
"<C3>": 93104,
|
563 |
+
"<C4>": 93105,
|
564 |
+
"<C5>": 93106,
|
565 |
+
"<C6>": 93107,
|
566 |
+
"<C7>": 93108,
|
567 |
+
"<C8>": 93109,
|
568 |
+
"<C9>": 93110,
|
569 |
+
"<D#-1>": 93111,
|
570 |
+
"<D#0>": 93112,
|
571 |
+
"<D#1>": 93113,
|
572 |
+
"<D#2>": 93114,
|
573 |
+
"<D#3>": 93115,
|
574 |
+
"<D#4>": 93116,
|
575 |
+
"<D#5>": 93117,
|
576 |
+
"<D#6>": 93118,
|
577 |
+
"<D#7>": 93119,
|
578 |
+
"<D#8>": 93120,
|
579 |
+
"<D#9>": 93121,
|
580 |
+
"<D-1>": 93122,
|
581 |
+
"<D0>": 93123,
|
582 |
+
"<D1>": 93124,
|
583 |
+
"<D2>": 93125,
|
584 |
+
"<D3>": 93126,
|
585 |
+
"<D4>": 93127,
|
586 |
+
"<D5>": 93128,
|
587 |
+
"<D6>": 93129,
|
588 |
+
"<D7>": 93130,
|
589 |
+
"<D8>": 93131,
|
590 |
+
"<D9>": 93132,
|
591 |
+
"<E-1>": 93133,
|
592 |
+
"<E0>": 93134,
|
593 |
+
"<E1>": 93135,
|
594 |
+
"<E2>": 93136,
|
595 |
+
"<E3>": 93137,
|
596 |
+
"<E4>": 93138,
|
597 |
+
"<E5>": 93139,
|
598 |
+
"<E6>": 93140,
|
599 |
+
"<E7>": 93141,
|
600 |
+
"<E8>": 93142,
|
601 |
+
"<E9>": 93143,
|
602 |
+
"<F#-1>": 93144,
|
603 |
+
"<F#0>": 93145,
|
604 |
+
"<F#1>": 93146,
|
605 |
+
"<F#2>": 93147,
|
606 |
+
"<F#3>": 93148,
|
607 |
+
"<F#4>": 93149,
|
608 |
+
"<F#5>": 93150,
|
609 |
+
"<F#6>": 93151,
|
610 |
+
"<F#7>": 93152,
|
611 |
+
"<F#8>": 93153,
|
612 |
+
"<F#9>": 93154,
|
613 |
+
"<F-1>": 93155,
|
614 |
+
"<F0>": 93156,
|
615 |
+
"<F1>": 93157,
|
616 |
+
"<F2>": 93158,
|
617 |
+
"<F3>": 93159,
|
618 |
+
"<F4>": 93160,
|
619 |
+
"<F5>": 93161,
|
620 |
+
"<F6>": 93162,
|
621 |
+
"<F7>": 93163,
|
622 |
+
"<F8>": 93164,
|
623 |
+
"<F9>": 93165,
|
624 |
+
"<G#-1>": 93166,
|
625 |
+
"<G#0>": 93167,
|
626 |
+
"<G#1>": 93168,
|
627 |
+
"<G#2>": 93169,
|
628 |
+
"<G#3>": 93170,
|
629 |
+
"<G#4>": 93171,
|
630 |
+
"<G#5>": 93172,
|
631 |
+
"<G#6>": 93173,
|
632 |
+
"<G#7>": 93174,
|
633 |
+
"<G#8>": 93175,
|
634 |
+
"<G#9>": 93176,
|
635 |
+
"<G-1>": 93177,
|
636 |
+
"<G0>": 93178,
|
637 |
+
"<G1>": 93179,
|
638 |
+
"<G2>": 93180,
|
639 |
+
"<G3>": 93181,
|
640 |
+
"<G4>": 93182,
|
641 |
+
"<G5>": 93183,
|
642 |
+
"<G6>": 93184,
|
643 |
+
"<G7>": 93185,
|
644 |
+
"<G8>": 93186,
|
645 |
+
"<G9>": 93187,
|
646 |
+
"<bol>": 93188,
|
647 |
+
"<bom>": 93189,
|
648 |
+
"<bop>": 93190,
|
649 |
+
"<eol>": 93191,
|
650 |
+
"<eom>": 93192,
|
651 |
+
"<eop>": 93193
|
652 |
+
}
|
build_mlp.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import re
|
4 |
+
import math
|
5 |
+
from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
|
6 |
+
|
7 |
+
|
8 |
+
def build_vision_tower():
|
9 |
+
vision_tower = '/mnt/petrelfs/share_data/dongxiaoyi/share_models/clip_l_336'
|
10 |
+
return CLIPVisionTower(vision_tower)
|
11 |
+
|
12 |
+
|
13 |
+
def build_vision_projector():
|
14 |
+
projector_type = 'mlp2x_gelu'
|
15 |
+
mm_hidden_size = 1024
|
16 |
+
hidden_size = 4096
|
17 |
+
|
18 |
+
mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
|
19 |
+
if mlp_gelu_match:
|
20 |
+
mlp_depth = int(mlp_gelu_match.group(1))
|
21 |
+
modules = [nn.Linear(mm_hidden_size, hidden_size)]
|
22 |
+
for _ in range(1, mlp_depth):
|
23 |
+
modules.append(nn.GELU())
|
24 |
+
modules.append(nn.Linear(hidden_size, hidden_size))
|
25 |
+
return nn.Sequential(*modules)
|
26 |
+
|
27 |
+
if projector_type == 'identity':
|
28 |
+
return IdentityMap()
|
29 |
+
|
30 |
+
raise ValueError(f'Unknown projector type: {projector_type}')
|
31 |
+
|
32 |
+
class IdentityMap(nn.Module):
|
33 |
+
def __init__(self):
|
34 |
+
super().__init__()
|
35 |
+
|
36 |
+
def forward(self, x, *args, **kwargs):
|
37 |
+
return x
|
38 |
+
|
39 |
+
@property
|
40 |
+
def config(self):
|
41 |
+
return {"mm_projector_type": 'identity'}
|
42 |
+
|
43 |
+
|
44 |
+
class CLIPVisionTower(nn.Module):
|
45 |
+
def __init__(self, vision_tower):
|
46 |
+
super().__init__()
|
47 |
+
|
48 |
+
self.is_loaded = False
|
49 |
+
self.is_resize_pos = False
|
50 |
+
|
51 |
+
self.vision_tower_name = vision_tower
|
52 |
+
self.select_layer = -1
|
53 |
+
self.select_feature = 'patch'
|
54 |
+
self.load_model()
|
55 |
+
#self.resize_pos()
|
56 |
+
|
57 |
+
def load_model(self):
|
58 |
+
self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
|
59 |
+
self.vision_tower.requires_grad_(False)
|
60 |
+
|
61 |
+
self.is_loaded = True
|
62 |
+
def resize_pos(self):
|
63 |
+
pos_embed_checkpoint = self.vision_tower.vision_model.embeddings.position_embedding.weight
|
64 |
+
pos_embed_checkpoint = pos_embed_checkpoint.unsqueeze(0)
|
65 |
+
orig_size = 24
|
66 |
+
new_size = 16
|
67 |
+
|
68 |
+
if pos_embed_checkpoint.shape[1] == new_size ** 2 + 1:
|
69 |
+
self.is_resize_pos = True
|
70 |
+
else:
|
71 |
+
embedding_size = pos_embed_checkpoint.shape[-1]
|
72 |
+
num_extra_tokens = 1
|
73 |
+
new_num = new_size ** 2 + num_extra_tokens
|
74 |
+
print("Position interpolate from %dx%d to %dx%d" %
|
75 |
+
(orig_size, orig_size, new_size, new_size))
|
76 |
+
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
|
77 |
+
# only the position tokens are interpolated
|
78 |
+
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
|
79 |
+
pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size,
|
80 |
+
embedding_size).permute(
|
81 |
+
0, 3, 1, 2)
|
82 |
+
pos_tokens = torch.nn.functional.interpolate(pos_tokens,
|
83 |
+
size=(new_size,
|
84 |
+
new_size),
|
85 |
+
mode='bicubic',
|
86 |
+
align_corners=False)
|
87 |
+
pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
|
88 |
+
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
|
89 |
+
|
90 |
+
new_pos_embed = new_pos_embed.squeeze(0)
|
91 |
+
|
92 |
+
self.vision_tower.vision_model.embeddings.position_embedding = torch.nn.Embedding(new_num, 1024)
|
93 |
+
#self.vision_tower.vision_model.embeddings.position_embedding.weight = torch.nn.Parameter(new_pos_embed.to(pos_embed_checkpoint.dtype))
|
94 |
+
#self.vision_tower.vision_model.embeddings.position_ids = torch.arange(new_num).expand((1, -1))
|
95 |
+
|
96 |
+
self.vision_tower.vision_model.embeddings.position_embedding.weight = torch.nn.Parameter(new_pos_embed.to(pos_embed_checkpoint.device).to(pos_embed_checkpoint.dtype))
|
97 |
+
self.vision_tower.vision_model.embeddings.position_ids = torch.arange(new_num).expand((1, -1)).to(pos_embed_checkpoint.device)
|
98 |
+
self.is_resize_pos = True
|
99 |
+
|
100 |
+
def feature_select(self, image_forward_outs):
|
101 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
102 |
+
if self.select_feature == 'patch':
|
103 |
+
image_features = image_features[:, 1:]
|
104 |
+
elif self.select_feature == 'cls_patch':
|
105 |
+
image_features = image_features
|
106 |
+
else:
|
107 |
+
raise ValueError(f'Unexpected select feature: {self.select_feature}')
|
108 |
+
return image_features
|
109 |
+
|
110 |
+
def forward(self, images):
|
111 |
+
if not self.is_loaded:
|
112 |
+
self.load_model()
|
113 |
+
if type(images) is list:
|
114 |
+
image_features = []
|
115 |
+
for image in images:
|
116 |
+
image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
117 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
118 |
+
image_features.append(image_feature)
|
119 |
+
else:
|
120 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
121 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
122 |
+
|
123 |
+
return image_features
|
124 |
+
|
125 |
+
@property
|
126 |
+
def dummy_feature(self):
|
127 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
128 |
+
|
129 |
+
@property
|
130 |
+
def dtype(self):
|
131 |
+
return self.vision_tower.dtype
|
132 |
+
|
133 |
+
@property
|
134 |
+
def device(self):
|
135 |
+
return self.vision_tower.device
|
136 |
+
|
137 |
+
@property
|
138 |
+
def config(self):
|
139 |
+
if self.is_loaded:
|
140 |
+
return self.vision_tower.config
|
141 |
+
else:
|
142 |
+
return self.cfg_only
|
143 |
+
|
144 |
+
@property
|
145 |
+
def hidden_size(self):
|
146 |
+
return self.config.hidden_size
|
147 |
+
|
148 |
+
@property
|
149 |
+
def num_patches(self):
|
150 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
151 |
+
|
152 |
+
class PLoRA(nn.Linear):
|
153 |
+
def __init__(self,
|
154 |
+
in_features: int,
|
155 |
+
out_features: int,
|
156 |
+
bias: bool = True,
|
157 |
+
device=None,
|
158 |
+
dtype=None,
|
159 |
+
lora_r=8,
|
160 |
+
lora_alpha=16,
|
161 |
+
lora_dropout=0.05,
|
162 |
+
lora_len=0,
|
163 |
+
**kwargs) -> None:
|
164 |
+
super().__init__(in_features, out_features, bias, device, dtype)
|
165 |
+
self.lora_r = lora_r
|
166 |
+
self.lora_alpha = lora_alpha
|
167 |
+
self.lora_len = lora_len
|
168 |
+
if lora_dropout > 0.:
|
169 |
+
self.lora_dropout = nn.Dropout(p=lora_dropout)
|
170 |
+
else:
|
171 |
+
self.lora_dropout = lambda x: x
|
172 |
+
self.lora_scaling = self.lora_alpha / self.lora_r
|
173 |
+
|
174 |
+
self.Plora_A = nn.Linear(in_features,
|
175 |
+
self.lora_r,
|
176 |
+
bias=False,
|
177 |
+
device=device,
|
178 |
+
dtype=dtype)
|
179 |
+
self.Plora_B = nn.Linear(self.lora_r,
|
180 |
+
out_features,
|
181 |
+
bias=False,
|
182 |
+
device=device,
|
183 |
+
dtype=dtype)
|
184 |
+
|
185 |
+
self.reset_parameters()
|
186 |
+
|
187 |
+
def reset_parameters(self):
|
188 |
+
if hasattr(self, 'lora_A'):
|
189 |
+
# initialize A the same way as the default for nn.Linear and B to zero
|
190 |
+
nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5))
|
191 |
+
nn.init.zeros_(self.lora_B.weight)
|
192 |
+
#print ("lora weight init {} {}".format(torch.mean(self.lora_A.weight), torch.mean(self.lora_B.weight)))
|
193 |
+
|
194 |
+
def forward(self, x, im_mask=None):
|
195 |
+
res = super().forward(x)
|
196 |
+
if im_mask is not None:
|
197 |
+
if torch.sum(im_mask) > 0:
|
198 |
+
part_x = x[im_mask]
|
199 |
+
res[im_mask] += self.Plora_B(self.Plora_A(
|
200 |
+
self.lora_dropout(part_x))) * self.lora_scaling
|
201 |
+
else:
|
202 |
+
part_x = x[:, :1]
|
203 |
+
res[:, :1] += self.Plora_B(self.Plora_A(
|
204 |
+
self.lora_dropout(part_x))) * 0
|
205 |
+
return res
|
config.json
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/mnt/petrelfs/dingshuangrui/PuQu/output/internlm2_pretrain_slow",
|
3 |
+
"architectures": [
|
4 |
+
"InternLM2ForCausalLM"
|
5 |
+
],
|
6 |
+
"attn_implementation": "eager",
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_internlm.InternLMConfig",
|
9 |
+
"AutoModel": "modeling_internlm2.InternLM2ForCausalLM",
|
10 |
+
"AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM"
|
11 |
+
},
|
12 |
+
"bias": false,
|
13 |
+
"bos_token_id": 1,
|
14 |
+
"eos_token_id": 2,
|
15 |
+
"hidden_act": "silu",
|
16 |
+
"hidden_size": 4096,
|
17 |
+
"initializer_range": 0.02,
|
18 |
+
"intermediate_size": 14336,
|
19 |
+
"max_length": 2048,
|
20 |
+
"max_position_embeddings": 32768,
|
21 |
+
"model_type": "internlm",
|
22 |
+
"num_attention_heads": 32,
|
23 |
+
"num_hidden_layers": 32,
|
24 |
+
"num_key_value_heads": 8,
|
25 |
+
"pad_token_id": 2,
|
26 |
+
"rms_norm_eps": 1e-05,
|
27 |
+
"rope_scaling": {
|
28 |
+
"factor": 1.0,
|
29 |
+
"type": "dynamic"
|
30 |
+
},
|
31 |
+
"rope_theta": 1000000,
|
32 |
+
"tie_word_embeddings": false,
|
33 |
+
"torch_dtype": "bfloat16",
|
34 |
+
"transformers_version": "4.31.0",
|
35 |
+
"use_cache": false,
|
36 |
+
"vocab_size": 93194
|
37 |
+
}
|
configuration_internlm.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright (c) InternLM. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" InternLM model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.utils import logging
|
24 |
+
|
25 |
+
logger = logging.get_logger(__name__)
|
26 |
+
|
27 |
+
INTERNLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
28 |
+
|
29 |
+
|
30 |
+
class InternLMConfig(PretrainedConfig):
|
31 |
+
r"""
|
32 |
+
This is the configuration class to store the configuration of a [`InternLMModel`]. It is used to instantiate
|
33 |
+
an InternLM model according to the specified arguments, defining the model architecture. Instantiating a
|
34 |
+
configuration with the defaults will yield a similar configuration to that of the InternLM-7B.
|
35 |
+
|
36 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
37 |
+
documentation from [`PretrainedConfig`] for more information.
|
38 |
+
|
39 |
+
|
40 |
+
Args:
|
41 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
42 |
+
Vocabulary size of the InternLM model. Defines the number of different tokens that can be represented by the
|
43 |
+
`inputs_ids` passed when calling [`InternLMModel`]
|
44 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
45 |
+
Dimension of the hidden representations.
|
46 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
47 |
+
Dimension of the MLP representations.
|
48 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
49 |
+
Number of hidden layers in the Transformer encoder.
|
50 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
51 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
52 |
+
num_key_value_heads (`int`, *optional*):
|
53 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
54 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
55 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
56 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
57 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
58 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
59 |
+
`num_attention_heads`.
|
60 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
61 |
+
The non-linear activation function (function or string) in the decoder.
|
62 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
63 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
64 |
+
just in case (e.g., 512 or 1024 or 2048).
|
65 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
66 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
67 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-12):
|
68 |
+
The epsilon used by the rms normalization layers.
|
69 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
70 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
71 |
+
relevant if `config.is_decoder=True`.
|
72 |
+
tie_word_embeddings(`bool`, *optional*, defaults to `False`):
|
73 |
+
Whether to tie weight embeddings
|
74 |
+
Example:
|
75 |
+
|
76 |
+
```python
|
77 |
+
>>> from transformers import InternLMModel, InternLMConfig
|
78 |
+
|
79 |
+
>>> # Initializing a InternLM internlm-7b style configuration
|
80 |
+
>>> configuration = InternLMConfig()
|
81 |
+
|
82 |
+
>>> # Initializing a model from the internlm-7b style configuration
|
83 |
+
>>> model = InternLMModel(configuration)
|
84 |
+
|
85 |
+
>>> # Accessing the model configuration
|
86 |
+
>>> configuration = model.config
|
87 |
+
```"""
|
88 |
+
model_type = "internlm"
|
89 |
+
_auto_class = "AutoConfig"
|
90 |
+
|
91 |
+
def __init__( # pylint: disable=W0102
|
92 |
+
self,
|
93 |
+
vocab_size=103168,
|
94 |
+
hidden_size=4096,
|
95 |
+
intermediate_size=11008,
|
96 |
+
num_hidden_layers=32,
|
97 |
+
num_attention_heads=32,
|
98 |
+
num_key_value_heads=None,
|
99 |
+
hidden_act="silu",
|
100 |
+
max_position_embeddings=2048,
|
101 |
+
initializer_range=0.02,
|
102 |
+
rms_norm_eps=1e-6,
|
103 |
+
use_cache=True,
|
104 |
+
pad_token_id=0,
|
105 |
+
bos_token_id=1,
|
106 |
+
eos_token_id=2,
|
107 |
+
tie_word_embeddings=False,
|
108 |
+
bias=True,
|
109 |
+
rope_theta=10000,
|
110 |
+
rope_scaling=None,
|
111 |
+
attn_implementation="eager",
|
112 |
+
**kwargs,
|
113 |
+
):
|
114 |
+
self.vocab_size = vocab_size
|
115 |
+
self.max_position_embeddings = max_position_embeddings
|
116 |
+
self.hidden_size = hidden_size
|
117 |
+
self.intermediate_size = intermediate_size
|
118 |
+
self.num_hidden_layers = num_hidden_layers
|
119 |
+
self.num_attention_heads = num_attention_heads
|
120 |
+
self.bias = bias
|
121 |
+
|
122 |
+
if num_key_value_heads is None:
|
123 |
+
num_key_value_heads = num_attention_heads
|
124 |
+
self.num_key_value_heads = num_key_value_heads
|
125 |
+
|
126 |
+
self.hidden_act = hidden_act
|
127 |
+
self.initializer_range = initializer_range
|
128 |
+
self.rms_norm_eps = rms_norm_eps
|
129 |
+
self.use_cache = use_cache
|
130 |
+
self.rope_theta = rope_theta
|
131 |
+
self.rope_scaling = rope_scaling
|
132 |
+
self._rope_scaling_validation()
|
133 |
+
|
134 |
+
self.attn_implementation = attn_implementation
|
135 |
+
if self.attn_implementation is None:
|
136 |
+
self.attn_implementation = "eager"
|
137 |
+
super().__init__(
|
138 |
+
pad_token_id=pad_token_id,
|
139 |
+
bos_token_id=bos_token_id,
|
140 |
+
eos_token_id=eos_token_id,
|
141 |
+
tie_word_embeddings=tie_word_embeddings,
|
142 |
+
**kwargs,
|
143 |
+
)
|
144 |
+
|
145 |
+
def _rope_scaling_validation(self):
|
146 |
+
"""
|
147 |
+
Validate the `rope_scaling` configuration.
|
148 |
+
"""
|
149 |
+
if self.rope_scaling is None:
|
150 |
+
return
|
151 |
+
|
152 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
153 |
+
raise ValueError(
|
154 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
155 |
+
f"got {self.rope_scaling}"
|
156 |
+
)
|
157 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
158 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
159 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
160 |
+
raise ValueError(
|
161 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
162 |
+
)
|
163 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
|
164 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
|
generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# # Copyright (c) InternLM. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" PyTorch InternLM2 model."""
|
21 |
+
import math
|
22 |
+
import queue
|
23 |
+
import threading
|
24 |
+
import warnings
|
25 |
+
import copy
|
26 |
+
from typing import List, Optional, Tuple, Union
|
27 |
+
from torchvision import transforms
|
28 |
+
from torchvision.transforms.functional import InterpolationMode
|
29 |
+
from PIL import Image
|
30 |
+
|
31 |
+
import torch
|
32 |
+
import torch.utils.checkpoint
|
33 |
+
from einops import rearrange
|
34 |
+
from torch import nn
|
35 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
36 |
+
from transformers.activations import ACT2FN
|
37 |
+
from transformers.modeling_outputs import (
|
38 |
+
BaseModelOutputWithPast,
|
39 |
+
CausalLMOutputWithPast,
|
40 |
+
SequenceClassifierOutputWithPast,
|
41 |
+
)
|
42 |
+
from transformers.modeling_utils import PreTrainedModel
|
43 |
+
from transformers.utils import (
|
44 |
+
add_start_docstrings,
|
45 |
+
add_start_docstrings_to_model_forward,
|
46 |
+
logging,
|
47 |
+
replace_return_docstrings,
|
48 |
+
)
|
49 |
+
from transformers import StoppingCriteria, StoppingCriteriaList
|
50 |
+
try:
|
51 |
+
from transformers.generation.streamers import BaseStreamer
|
52 |
+
except: # noqa # pylint: disable=bare-except
|
53 |
+
BaseStreamer = None
|
54 |
+
|
55 |
+
from .configuration_internlm import InternLMConfig as InternLM2Config
|
56 |
+
from .build_mlp import build_vision_tower, build_vision_projector, PLoRA
|
57 |
+
|
58 |
+
logger = logging.get_logger(__name__)
|
59 |
+
|
60 |
+
_CONFIG_FOR_DOC = "InternLM2Config"
|
61 |
+
|
62 |
+
|
63 |
+
|
64 |
+
class StoppingCriteriaSub(StoppingCriteria):
|
65 |
+
def __init__(self, stops=[], encounters=1):
|
66 |
+
super().__init__()
|
67 |
+
self.stops = stops
|
68 |
+
|
69 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor):
|
70 |
+
for stop in self.stops:
|
71 |
+
if torch.all((stop == input_ids[0][-len(stop):])).item():
|
72 |
+
return True
|
73 |
+
|
74 |
+
return False
|
75 |
+
|
76 |
+
def text_gen(inst, tokenizer, model, stopping_criteria, temp=1.0, rept=1.005, sample=True):
|
77 |
+
d = f"{inst}"
|
78 |
+
input_ids = tokenizer(d, return_tensors="pt")["input_ids"]
|
79 |
+
eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["[UNUSED_TOKEN_145]"])[0]]
|
80 |
+
with torch.no_grad():
|
81 |
+
generate = model.generate(input_ids.cuda(),
|
82 |
+
do_sample=sample,
|
83 |
+
temperature=temp,
|
84 |
+
repetition_penalty=rept,
|
85 |
+
max_new_tokens=1000,
|
86 |
+
top_p=0.8,
|
87 |
+
top_k=50,
|
88 |
+
eos_token_id=eos_token_id,
|
89 |
+
stopping_criteria=stopping_criteria,)
|
90 |
+
|
91 |
+
res = tokenizer.decode(generate[0].tolist(), skip_special_tokens=True)
|
92 |
+
return (res)
|
93 |
+
|
94 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
95 |
+
def _make_causal_mask(
|
96 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
97 |
+
):
|
98 |
+
"""
|
99 |
+
Make causal mask used for bi-directional self-attention.
|
100 |
+
"""
|
101 |
+
bsz, tgt_len = input_ids_shape
|
102 |
+
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
103 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
104 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
105 |
+
mask = mask.to(dtype)
|
106 |
+
|
107 |
+
if past_key_values_length > 0:
|
108 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
109 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
110 |
+
|
111 |
+
|
112 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
113 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
114 |
+
"""
|
115 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
116 |
+
"""
|
117 |
+
bsz, src_len = mask.size()
|
118 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
119 |
+
|
120 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
121 |
+
|
122 |
+
inverted_mask = 1.0 - expanded_mask
|
123 |
+
|
124 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
125 |
+
|
126 |
+
|
127 |
+
class InternLM2RMSNorm(nn.Module):
|
128 |
+
def __init__(self, hidden_size, eps=1e-6):
|
129 |
+
"""
|
130 |
+
InternLM2RMSNorm is equivalent to T5LayerNorm
|
131 |
+
"""
|
132 |
+
super().__init__()
|
133 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
134 |
+
self.variance_epsilon = eps
|
135 |
+
|
136 |
+
def forward(self, hidden_states):
|
137 |
+
input_dtype = hidden_states.dtype
|
138 |
+
hidden_states = hidden_states.to(torch.float32)
|
139 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
140 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
141 |
+
return self.weight * hidden_states.to(input_dtype)
|
142 |
+
|
143 |
+
|
144 |
+
class InternLM2RotaryEmbedding(nn.Module):
|
145 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
146 |
+
super().__init__()
|
147 |
+
|
148 |
+
self.dim = dim
|
149 |
+
self.max_position_embeddings = max_position_embeddings
|
150 |
+
self.base = base
|
151 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
152 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
153 |
+
|
154 |
+
# Build here to make `torch.jit.trace` work.
|
155 |
+
self._set_cos_sin_cache(
|
156 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
157 |
+
)
|
158 |
+
|
159 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
160 |
+
self.max_seq_len_cached = seq_len
|
161 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
162 |
+
|
163 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
164 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
165 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
166 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
167 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
168 |
+
|
169 |
+
def forward(self, x, seq_len=None):
|
170 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
171 |
+
if seq_len > self.max_seq_len_cached:
|
172 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
173 |
+
|
174 |
+
return (
|
175 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
176 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
177 |
+
)
|
178 |
+
|
179 |
+
|
180 |
+
class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
181 |
+
"""InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
182 |
+
|
183 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
184 |
+
self.scaling_factor = scaling_factor
|
185 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
186 |
+
|
187 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
188 |
+
self.max_seq_len_cached = seq_len
|
189 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
190 |
+
t = t / self.scaling_factor
|
191 |
+
|
192 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
193 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
194 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
195 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
196 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
197 |
+
|
198 |
+
|
199 |
+
class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
200 |
+
"""InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
|
201 |
+
Credits to the Reddit users /u/bloc97 and /u/emozilla.
|
202 |
+
"""
|
203 |
+
|
204 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
205 |
+
self.scaling_factor = scaling_factor
|
206 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
207 |
+
|
208 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
209 |
+
self.max_seq_len_cached = seq_len
|
210 |
+
|
211 |
+
if seq_len > self.max_position_embeddings:
|
212 |
+
base = self.base * (
|
213 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
214 |
+
) ** (self.dim / (self.dim - 2))
|
215 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
216 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
217 |
+
|
218 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
219 |
+
|
220 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
221 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
222 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
223 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
224 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
225 |
+
|
226 |
+
|
227 |
+
def rotate_half(x):
|
228 |
+
"""Rotates half the hidden dims of the input."""
|
229 |
+
x1 = x[..., : x.shape[-1] // 2]
|
230 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
231 |
+
return torch.cat((-x2, x1), dim=-1)
|
232 |
+
|
233 |
+
|
234 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
235 |
+
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
236 |
+
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
237 |
+
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
238 |
+
cos = cos.unsqueeze(0).unsqueeze(0).expand(len(position_ids), -1, -1, -1)
|
239 |
+
sin = sin.unsqueeze(0).unsqueeze(0).expand(len(position_ids), -1, -1, -1)
|
240 |
+
if q.size(2) == 1:
|
241 |
+
q_embed = (q * cos[:, :, -1:, :]) + (rotate_half(q) * sin[:, :, -1:, :])
|
242 |
+
else:
|
243 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
244 |
+
|
245 |
+
if k.size(2) == 1:
|
246 |
+
k_embed = (k * cos[:, :, -1:, :]) + (rotate_half(k) * sin[:, :, -1:, :])
|
247 |
+
else:
|
248 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
249 |
+
|
250 |
+
return q_embed, k_embed
|
251 |
+
|
252 |
+
|
253 |
+
class InternLM2MLP(nn.Module):
|
254 |
+
def __init__(self, config):
|
255 |
+
super().__init__()
|
256 |
+
self.config = config
|
257 |
+
self.hidden_size = config.hidden_size
|
258 |
+
self.intermediate_size = config.intermediate_size
|
259 |
+
#self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
260 |
+
#self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
261 |
+
#self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
262 |
+
|
263 |
+
self.w1 = PLoRA(self.hidden_size, self.intermediate_size, bias=False,
|
264 |
+
lora_r=256, lora_alpha=256, lora_len=256)
|
265 |
+
self.w3 = PLoRA(self.hidden_size, self.intermediate_size, bias=False,
|
266 |
+
lora_r=256, lora_alpha=256, lora_len=256)
|
267 |
+
self.w2 = PLoRA(self.intermediate_size, self.hidden_size, bias=False,
|
268 |
+
lora_r=256, lora_alpha=256, lora_len=256)
|
269 |
+
|
270 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
271 |
+
|
272 |
+
def forward(self, x, im_mask):
|
273 |
+
down_proj = self.w2(self.act_fn(self.w1(x, im_mask)) * self.w3(x, im_mask), im_mask)
|
274 |
+
|
275 |
+
return down_proj
|
276 |
+
|
277 |
+
|
278 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
279 |
+
"""
|
280 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
281 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
282 |
+
"""
|
283 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
284 |
+
if n_rep == 1:
|
285 |
+
return hidden_states
|
286 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
287 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
288 |
+
|
289 |
+
|
290 |
+
class InternLM2Attention(nn.Module):
|
291 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
292 |
+
|
293 |
+
def __init__(self, config: InternLM2Config):
|
294 |
+
super().__init__()
|
295 |
+
self.config = config
|
296 |
+
self.hidden_size = config.hidden_size
|
297 |
+
self.num_heads = config.num_attention_heads
|
298 |
+
self.head_dim = self.hidden_size // self.num_heads
|
299 |
+
self.num_key_value_heads = config.num_key_value_heads
|
300 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
301 |
+
self.max_position_embeddings = config.max_position_embeddings
|
302 |
+
self.is_causal = True
|
303 |
+
|
304 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
305 |
+
raise ValueError(
|
306 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
307 |
+
f" and `num_heads`: {self.num_heads})."
|
308 |
+
)
|
309 |
+
|
310 |
+
#self.wqkv = nn.Linear(
|
311 |
+
self.wqkv = PLoRA(
|
312 |
+
self.hidden_size,
|
313 |
+
(self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
|
314 |
+
bias=config.bias,
|
315 |
+
lora_r=256, lora_alpha=256, lora_len=256
|
316 |
+
)
|
317 |
+
|
318 |
+
#self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
|
319 |
+
self.wo = PLoRA(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias,
|
320 |
+
lora_r=256, lora_alpha=256, lora_len=256)
|
321 |
+
self._init_rope()
|
322 |
+
|
323 |
+
def _init_rope(self):
|
324 |
+
if self.config.rope_scaling is None:
|
325 |
+
self.rotary_emb = InternLM2RotaryEmbedding(
|
326 |
+
self.head_dim,
|
327 |
+
max_position_embeddings=self.max_position_embeddings,
|
328 |
+
base=self.config.rope_theta,
|
329 |
+
)
|
330 |
+
else:
|
331 |
+
scaling_type = self.config.rope_scaling["type"]
|
332 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
333 |
+
if scaling_type == "dynamic":
|
334 |
+
self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
|
335 |
+
self.head_dim,
|
336 |
+
max_position_embeddings=self.max_position_embeddings,
|
337 |
+
base=self.config.rope_theta,
|
338 |
+
scaling_factor=scaling_factor
|
339 |
+
)
|
340 |
+
else:
|
341 |
+
raise ValueError("Currently we only support rotary embedding's type being 'dynamic'.")
|
342 |
+
return self.rotary_emb
|
343 |
+
|
344 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
345 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
346 |
+
|
347 |
+
def forward(
|
348 |
+
self,
|
349 |
+
hidden_states: torch.Tensor,
|
350 |
+
attention_mask: Optional[torch.Tensor] = None,
|
351 |
+
position_ids: Optional[torch.LongTensor] = None,
|
352 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
353 |
+
output_attentions: bool = False,
|
354 |
+
use_cache: bool = False,
|
355 |
+
im_mask: Optional[Tuple[torch.Tensor]] = None,
|
356 |
+
**kwargs,
|
357 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
358 |
+
if "padding_mask" in kwargs:
|
359 |
+
warnings.warn(
|
360 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. "
|
361 |
+
"Please make sure use `attention_mask` instead.`"
|
362 |
+
)
|
363 |
+
|
364 |
+
bsz, q_len, _ = hidden_states.size()
|
365 |
+
|
366 |
+
qkv_states = self.wqkv(hidden_states, im_mask)
|
367 |
+
|
368 |
+
qkv_states = rearrange(
|
369 |
+
qkv_states,
|
370 |
+
"b q (h gs d) -> b q h gs d",
|
371 |
+
gs=2 + self.num_key_value_groups,
|
372 |
+
d=self.head_dim,
|
373 |
+
)
|
374 |
+
|
375 |
+
query_states = qkv_states[..., : self.num_key_value_groups, :]
|
376 |
+
query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
|
377 |
+
key_states = qkv_states[..., -2, :]
|
378 |
+
value_states = qkv_states[..., -1, :]
|
379 |
+
|
380 |
+
query_states = query_states.transpose(1, 2)
|
381 |
+
key_states = key_states.transpose(1, 2)
|
382 |
+
value_states = value_states.transpose(1, 2)
|
383 |
+
|
384 |
+
kv_seq_len = key_states.shape[-2]
|
385 |
+
if past_key_value is not None:
|
386 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
387 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
388 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
389 |
+
|
390 |
+
if past_key_value is not None:
|
391 |
+
# reuse k, v, self_attention
|
392 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
393 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
394 |
+
|
395 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
396 |
+
|
397 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
398 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
399 |
+
|
400 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
401 |
+
|
402 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
403 |
+
raise ValueError(
|
404 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
405 |
+
f" {attn_weights.size()}"
|
406 |
+
)
|
407 |
+
|
408 |
+
if attention_mask is not None:
|
409 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
410 |
+
raise ValueError(
|
411 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
412 |
+
)
|
413 |
+
attn_weights = attn_weights + attention_mask
|
414 |
+
|
415 |
+
# upcast attention to fp32
|
416 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
417 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
418 |
+
|
419 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
420 |
+
raise ValueError(
|
421 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
422 |
+
f" {attn_output.size()}"
|
423 |
+
)
|
424 |
+
|
425 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
426 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
427 |
+
|
428 |
+
attn_output = self.wo(attn_output, im_mask)
|
429 |
+
|
430 |
+
if not output_attentions:
|
431 |
+
attn_weights = None
|
432 |
+
|
433 |
+
return attn_output, attn_weights, past_key_value
|
434 |
+
|
435 |
+
|
436 |
+
class InternLM2FlashAttention2(InternLM2Attention):
|
437 |
+
"""
|
438 |
+
InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
|
439 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
440 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
441 |
+
"""
|
442 |
+
|
443 |
+
def forward(
|
444 |
+
self,
|
445 |
+
hidden_states: torch.Tensor,
|
446 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
447 |
+
position_ids: Optional[torch.LongTensor] = None,
|
448 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
449 |
+
output_attentions: bool = False,
|
450 |
+
use_cache: bool = False,
|
451 |
+
im_mask: Optional[Tuple[torch.Tensor]] = None,
|
452 |
+
**kwargs,
|
453 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
454 |
+
# InternLM2FlashAttention2 attention does not support output_attentions
|
455 |
+
if "padding_mask" in kwargs:
|
456 |
+
warnings.warn(
|
457 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. "
|
458 |
+
"Please make sure use `attention_mask` instead.`"
|
459 |
+
)
|
460 |
+
|
461 |
+
# overwrite attention_mask with padding_mask
|
462 |
+
attention_mask = kwargs.pop("padding_mask")
|
463 |
+
|
464 |
+
output_attentions = False
|
465 |
+
|
466 |
+
bsz, q_len, _ = hidden_states.size()
|
467 |
+
|
468 |
+
qkv_states = self.wqkv(hidden_states, im_mask)
|
469 |
+
|
470 |
+
qkv_states = rearrange(
|
471 |
+
qkv_states,
|
472 |
+
"b q (h gs d) -> b q h gs d",
|
473 |
+
gs=self.num_heads + 2 * self.num_key_value_heads,
|
474 |
+
d=self.head_dim,
|
475 |
+
q=q_len,
|
476 |
+
)
|
477 |
+
|
478 |
+
query_states = qkv_states[..., : self.num_key_value_groups, :]
|
479 |
+
query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
|
480 |
+
key_states = qkv_states[..., -2, :]
|
481 |
+
value_states = qkv_states[..., -1, :]
|
482 |
+
|
483 |
+
kv_seq_len = key_states.shape[-2]
|
484 |
+
if past_key_value is not None:
|
485 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
486 |
+
|
487 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
488 |
+
|
489 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
490 |
+
|
491 |
+
if past_key_value is not None:
|
492 |
+
# reuse k, v, self_attention
|
493 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
494 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
495 |
+
|
496 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
497 |
+
|
498 |
+
query_states = query_states.transpose(1, 2)
|
499 |
+
key_states = key_states.transpose(1, 2)
|
500 |
+
value_states = value_states.transpose(1, 2)
|
501 |
+
|
502 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
503 |
+
|
504 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
505 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
506 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
507 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
508 |
+
# in fp32. (InternLM2RMSNorm handles it correctly)
|
509 |
+
|
510 |
+
input_dtype = query_states.dtype
|
511 |
+
if input_dtype == torch.float32:
|
512 |
+
# Handle the case where the model is quantized
|
513 |
+
if hasattr(self.config, "_pre_quantization_dtype"):
|
514 |
+
target_dtype = self.config._pre_quantization_dtype
|
515 |
+
else:
|
516 |
+
target_dtype = self.q_proj.weight.dtype
|
517 |
+
|
518 |
+
logger.warning_once(
|
519 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
520 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back "
|
521 |
+
f"the input in {target_dtype}."
|
522 |
+
)
|
523 |
+
|
524 |
+
query_states = query_states.to(target_dtype)
|
525 |
+
key_states = key_states.to(target_dtype)
|
526 |
+
value_states = value_states.to(target_dtype)
|
527 |
+
|
528 |
+
attn_output = self._flash_attention_forward(
|
529 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
530 |
+
)
|
531 |
+
|
532 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
533 |
+
attn_output = self.wo(attn_output, im_mask)
|
534 |
+
|
535 |
+
if not output_attentions:
|
536 |
+
attn_weights = None
|
537 |
+
|
538 |
+
return attn_output, attn_weights, past_key_value
|
539 |
+
|
540 |
+
|
541 |
+
class InternLM2DecoderLayer(nn.Module):
|
542 |
+
def __init__(self, config: InternLM2Config):
|
543 |
+
super().__init__()
|
544 |
+
self.hidden_size = config.hidden_size
|
545 |
+
self.attention = (
|
546 |
+
InternLM2Attention(config=config)
|
547 |
+
if not getattr(config, "_flash_attn_2_enabled", False)
|
548 |
+
else InternLM2FlashAttention2(config=config)
|
549 |
+
)
|
550 |
+
self.feed_forward = InternLM2MLP(config)
|
551 |
+
self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
552 |
+
self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
553 |
+
|
554 |
+
def forward(
|
555 |
+
self,
|
556 |
+
hidden_states: torch.Tensor,
|
557 |
+
attention_mask: Optional[torch.Tensor] = None,
|
558 |
+
position_ids: Optional[torch.LongTensor] = None,
|
559 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
560 |
+
output_attentions: Optional[bool] = False,
|
561 |
+
use_cache: Optional[bool] = False,
|
562 |
+
im_mask: Optional[Tuple[torch.Tensor]] = None,
|
563 |
+
**kwargs,
|
564 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
565 |
+
"""
|
566 |
+
Args:
|
567 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
568 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
569 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
570 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
571 |
+
output_attentions (`bool`, *optional*):
|
572 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
573 |
+
returned tensors for more detail.
|
574 |
+
use_cache (`bool`, *optional*):
|
575 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
576 |
+
(see `past_key_values`).
|
577 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
578 |
+
"""
|
579 |
+
if "padding_mask" in kwargs:
|
580 |
+
warnings.warn(
|
581 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. "
|
582 |
+
"Please make sure use `attention_mask` instead.`"
|
583 |
+
)
|
584 |
+
|
585 |
+
residual = hidden_states
|
586 |
+
|
587 |
+
hidden_states = self.attention_norm(hidden_states)
|
588 |
+
|
589 |
+
# Self Attention
|
590 |
+
hidden_states, self_attn_weights, present_key_value = self.attention(
|
591 |
+
hidden_states=hidden_states,
|
592 |
+
attention_mask=attention_mask,
|
593 |
+
position_ids=position_ids,
|
594 |
+
past_key_value=past_key_value,
|
595 |
+
output_attentions=output_attentions,
|
596 |
+
use_cache=use_cache,
|
597 |
+
im_mask=im_mask,
|
598 |
+
**kwargs,
|
599 |
+
)
|
600 |
+
hidden_states = residual + hidden_states
|
601 |
+
|
602 |
+
# Fully Connected
|
603 |
+
residual = hidden_states
|
604 |
+
hidden_states = self.ffn_norm(hidden_states)
|
605 |
+
hidden_states = self.feed_forward(hidden_states, im_mask)
|
606 |
+
hidden_states = residual + hidden_states
|
607 |
+
|
608 |
+
outputs = (hidden_states,)
|
609 |
+
|
610 |
+
if output_attentions:
|
611 |
+
outputs += (self_attn_weights,)
|
612 |
+
|
613 |
+
if use_cache:
|
614 |
+
outputs += (present_key_value,)
|
615 |
+
|
616 |
+
return outputs
|
617 |
+
|
618 |
+
|
619 |
+
InternLM2_START_DOCSTRING = r"""
|
620 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
621 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
622 |
+
etc.)
|
623 |
+
|
624 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
625 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
626 |
+
and behavior.
|
627 |
+
|
628 |
+
Parameters:
|
629 |
+
config ([`InternLM2Config`]):
|
630 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
631 |
+
load the weights associated with the model, only the configuration. Check out the
|
632 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
633 |
+
"""
|
634 |
+
|
635 |
+
|
636 |
+
@add_start_docstrings(
|
637 |
+
"The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
|
638 |
+
InternLM2_START_DOCSTRING,
|
639 |
+
)
|
640 |
+
class InternLM2PreTrainedModel(PreTrainedModel):
|
641 |
+
config_class = InternLM2Config
|
642 |
+
base_model_prefix = "model"
|
643 |
+
supports_gradient_checkpointing = True
|
644 |
+
_no_split_modules = ["InternLM2DecoderLayer"]
|
645 |
+
_skip_keys_device_placement = "past_key_values"
|
646 |
+
_supports_flash_attn_2 = True
|
647 |
+
|
648 |
+
def _init_weights(self, module):
|
649 |
+
std = self.config.initializer_range
|
650 |
+
if isinstance(module, nn.Linear):
|
651 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
652 |
+
if module.bias is not None:
|
653 |
+
module.bias.data.zero_()
|
654 |
+
elif isinstance(module, nn.Embedding):
|
655 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
656 |
+
if module.padding_idx is not None:
|
657 |
+
module.weight.data[module.padding_idx].zero_()
|
658 |
+
|
659 |
+
|
660 |
+
InternLM2_INPUTS_DOCSTRING = r"""
|
661 |
+
Args:
|
662 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
663 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
664 |
+
it.
|
665 |
+
|
666 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
667 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
668 |
+
|
669 |
+
[What are input IDs?](../glossary#input-ids)
|
670 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
671 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
672 |
+
|
673 |
+
- 1 for tokens that are **not masked**,
|
674 |
+
- 0 for tokens that are **masked**.
|
675 |
+
|
676 |
+
[What are attention masks?](../glossary#attention-mask)
|
677 |
+
|
678 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
679 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
680 |
+
|
681 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
682 |
+
`past_key_values`).
|
683 |
+
|
684 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
685 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
686 |
+
information on the default strategy.
|
687 |
+
|
688 |
+
- 1 indicates the head is **not masked**,
|
689 |
+
- 0 indicates the head is **masked**.
|
690 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
691 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
692 |
+
config.n_positions - 1]`.
|
693 |
+
|
694 |
+
[What are position IDs?](../glossary#position-ids)
|
695 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
|
696 |
+
when `config.use_cache=True`):
|
697 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
698 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
699 |
+
`(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
|
700 |
+
|
701 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
702 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
703 |
+
|
704 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
705 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
706 |
+
of shape `(batch_size, sequence_length)`.
|
707 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
708 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
709 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
710 |
+
model's internal embedding lookup matrix.
|
711 |
+
use_cache (`bool`, *optional*):
|
712 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
713 |
+
`past_key_values`).
|
714 |
+
output_attentions (`bool`, *optional*):
|
715 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
716 |
+
tensors for more detail.
|
717 |
+
output_hidden_states (`bool`, *optional*):
|
718 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
719 |
+
more detail.
|
720 |
+
return_dict (`bool`, *optional*):
|
721 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
722 |
+
"""
|
723 |
+
|
724 |
+
|
725 |
+
@add_start_docstrings(
|
726 |
+
"The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
|
727 |
+
InternLM2_START_DOCSTRING,
|
728 |
+
)
|
729 |
+
class InternLM2Model(InternLM2PreTrainedModel):
|
730 |
+
"""
|
731 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
|
732 |
+
|
733 |
+
Args:
|
734 |
+
config: InternLM2Config
|
735 |
+
"""
|
736 |
+
|
737 |
+
_auto_class = "AutoModel"
|
738 |
+
|
739 |
+
def __init__(self, config: InternLM2Config):
|
740 |
+
super().__init__(config)
|
741 |
+
self.padding_idx = config.pad_token_id
|
742 |
+
self.vocab_size = config.vocab_size
|
743 |
+
|
744 |
+
self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
745 |
+
self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
746 |
+
self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
747 |
+
|
748 |
+
self.gradient_checkpointing = False
|
749 |
+
# Initialize weights and apply final processing
|
750 |
+
self.post_init()
|
751 |
+
|
752 |
+
def get_input_embeddings(self):
|
753 |
+
return self.tok_embeddings
|
754 |
+
|
755 |
+
def set_input_embeddings(self, value):
|
756 |
+
self.tok_embeddings = value
|
757 |
+
|
758 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
759 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
760 |
+
# create causal mask
|
761 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
762 |
+
combined_attention_mask = None
|
763 |
+
if input_shape[-1] > 1:
|
764 |
+
combined_attention_mask = _make_causal_mask(
|
765 |
+
input_shape,
|
766 |
+
inputs_embeds.dtype,
|
767 |
+
device=inputs_embeds.device,
|
768 |
+
past_key_values_length=past_key_values_length,
|
769 |
+
)
|
770 |
+
|
771 |
+
if attention_mask is not None:
|
772 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
773 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
774 |
+
inputs_embeds.device
|
775 |
+
)
|
776 |
+
combined_attention_mask = (
|
777 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
778 |
+
)
|
779 |
+
|
780 |
+
return combined_attention_mask
|
781 |
+
|
782 |
+
@add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
|
783 |
+
def forward(
|
784 |
+
self,
|
785 |
+
input_ids: torch.LongTensor = None,
|
786 |
+
attention_mask: Optional[torch.Tensor] = None,
|
787 |
+
position_ids: Optional[torch.LongTensor] = None,
|
788 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
789 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
790 |
+
use_cache: Optional[bool] = None,
|
791 |
+
output_attentions: Optional[bool] = None,
|
792 |
+
output_hidden_states: Optional[bool] = None,
|
793 |
+
return_dict: Optional[bool] = None,
|
794 |
+
**kwargs
|
795 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
796 |
+
|
797 |
+
im_mask = kwargs.get('im_mask', None)
|
798 |
+
|
799 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
800 |
+
output_hidden_states = (
|
801 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
802 |
+
)
|
803 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
804 |
+
|
805 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
806 |
+
|
807 |
+
# retrieve input_ids and inputs_embeds
|
808 |
+
if input_ids is not None and inputs_embeds is not None:
|
809 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
810 |
+
elif input_ids is not None:
|
811 |
+
batch_size, seq_length = input_ids.shape[:2]
|
812 |
+
elif inputs_embeds is not None:
|
813 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
814 |
+
else:
|
815 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
816 |
+
|
817 |
+
seq_length_with_past = seq_length
|
818 |
+
past_key_values_length = 0
|
819 |
+
if past_key_values is not None:
|
820 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
821 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
822 |
+
|
823 |
+
if position_ids is None:
|
824 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
825 |
+
position_ids = torch.arange(
|
826 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
827 |
+
)
|
828 |
+
position_ids = position_ids.unsqueeze(0)
|
829 |
+
|
830 |
+
if inputs_embeds is None:
|
831 |
+
inputs_embeds = self.tok_embeddings(input_ids)
|
832 |
+
im_mask = torch.zeros(inputs_embeds.shape[:2]).to(inputs_embeds.device).bool()
|
833 |
+
# embed positions
|
834 |
+
if attention_mask is None:
|
835 |
+
attention_mask = torch.ones(
|
836 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
837 |
+
)
|
838 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
839 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
840 |
+
)
|
841 |
+
|
842 |
+
# embed positions
|
843 |
+
hidden_states = inputs_embeds
|
844 |
+
|
845 |
+
if self.gradient_checkpointing and self.training:
|
846 |
+
if use_cache:
|
847 |
+
logger.warning_once(
|
848 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
849 |
+
)
|
850 |
+
use_cache = False
|
851 |
+
|
852 |
+
# decoder layers
|
853 |
+
all_hidden_states = () if output_hidden_states else None
|
854 |
+
all_self_attns = () if output_attentions else None
|
855 |
+
next_decoder_cache = () if use_cache else None
|
856 |
+
|
857 |
+
for idx, decoder_layer in enumerate(self.layers):
|
858 |
+
if output_hidden_states:
|
859 |
+
all_hidden_states += (hidden_states,)
|
860 |
+
|
861 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
862 |
+
|
863 |
+
if self.gradient_checkpointing and self.training:
|
864 |
+
|
865 |
+
def create_custom_forward(module):
|
866 |
+
def custom_forward(*inputs):
|
867 |
+
# None for past_key_value
|
868 |
+
return module(*inputs, output_attentions, None, im_mask)
|
869 |
+
|
870 |
+
return custom_forward
|
871 |
+
|
872 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
873 |
+
create_custom_forward(decoder_layer),
|
874 |
+
hidden_states,
|
875 |
+
attention_mask,
|
876 |
+
position_ids,
|
877 |
+
None,
|
878 |
+
)
|
879 |
+
else:
|
880 |
+
layer_outputs = decoder_layer(
|
881 |
+
hidden_states,
|
882 |
+
attention_mask=attention_mask,
|
883 |
+
position_ids=position_ids,
|
884 |
+
past_key_value=past_key_value,
|
885 |
+
output_attentions=output_attentions,
|
886 |
+
use_cache=use_cache,
|
887 |
+
im_mask=im_mask,
|
888 |
+
)
|
889 |
+
|
890 |
+
hidden_states = layer_outputs[0]
|
891 |
+
|
892 |
+
if use_cache:
|
893 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
894 |
+
|
895 |
+
if output_attentions:
|
896 |
+
all_self_attns += (layer_outputs[1],)
|
897 |
+
|
898 |
+
hidden_states = self.norm(hidden_states)
|
899 |
+
|
900 |
+
# add hidden states from the last decoder layer
|
901 |
+
if output_hidden_states:
|
902 |
+
all_hidden_states += (hidden_states,)
|
903 |
+
|
904 |
+
next_cache = next_decoder_cache if use_cache else None
|
905 |
+
if not return_dict:
|
906 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
907 |
+
return BaseModelOutputWithPast(
|
908 |
+
last_hidden_state=hidden_states,
|
909 |
+
past_key_values=next_cache,
|
910 |
+
hidden_states=all_hidden_states,
|
911 |
+
attentions=all_self_attns,
|
912 |
+
)
|
913 |
+
|
914 |
+
|
915 |
+
class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
916 |
+
_auto_class = "AutoModelForCausalLM"
|
917 |
+
|
918 |
+
_tied_weights_keys = ["output.weight"]
|
919 |
+
|
920 |
+
def __init__(self, config):
|
921 |
+
super().__init__(config)
|
922 |
+
self.model = InternLM2Model(config)
|
923 |
+
self.vocab_size = config.vocab_size
|
924 |
+
self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
925 |
+
self.debug_flag = 1
|
926 |
+
self.tokenizer = None
|
927 |
+
|
928 |
+
self.max_length = config.max_length
|
929 |
+
print (f'Set max length to {self.max_length}')
|
930 |
+
self.debug_flag = 1
|
931 |
+
# Initialize weights and apply final processing
|
932 |
+
self.post_init()
|
933 |
+
|
934 |
+
# self.vit = build_vision_tower()
|
935 |
+
# self.vision_proj = build_vision_projector()
|
936 |
+
# self.im_size = 224
|
937 |
+
# self.vis_processor = transforms.Compose([
|
938 |
+
# transforms.Resize((224, 224),
|
939 |
+
# interpolation=InterpolationMode.BICUBIC),
|
940 |
+
# transforms.ToTensor(),
|
941 |
+
# transforms.Normalize((0.48145466, 0.4578275, 0.40821073),
|
942 |
+
# (0.26862954, 0.26130258, 0.27577711)),
|
943 |
+
# ])
|
944 |
+
|
945 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
946 |
+
if isinstance(module, InternLM2Model):
|
947 |
+
module.gradient_checkpointing = value
|
948 |
+
# if value:
|
949 |
+
# self.vit.vision_tower.vision_model.encoder.gradient_checkpointing = value
|
950 |
+
|
951 |
+
def get_input_embeddings(self):
|
952 |
+
return self.model.tok_embeddings
|
953 |
+
|
954 |
+
def set_input_embeddings(self, value):
|
955 |
+
self.model.tok_embeddings = value
|
956 |
+
|
957 |
+
def get_output_embeddings(self):
|
958 |
+
return self.output
|
959 |
+
|
960 |
+
def set_output_embeddings(self, new_embeddings):
|
961 |
+
self.output = new_embeddings
|
962 |
+
|
963 |
+
def set_decoder(self, decoder):
|
964 |
+
self.model = decoder
|
965 |
+
|
966 |
+
def get_decoder(self):
|
967 |
+
return self.model
|
968 |
+
def encode_text(self, t, add_special_tokens=False):
|
969 |
+
t = t.replace('<|User|>:', '[UNUSED_TOKEN_146]user\n')
|
970 |
+
t = t.replace('<|Bot|>:', '[UNUSED_TOKEN_146]assistant\n')
|
971 |
+
t = t.replace('<TOKENS_UNUSED_0>', '[UNUSED_TOKEN_145]')
|
972 |
+
t = t.replace('<TOKENS_UNUSED_1>', '[UNUSED_TOKEN_145]')
|
973 |
+
t = t.replace('[UNUSED_TOKEN_0]', '[UNUSED_TOKEN_145]')
|
974 |
+
t = t.replace('[UNUSED_TOKEN_1]', '[UNUSED_TOKEN_145]')
|
975 |
+
|
976 |
+
text = t
|
977 |
+
token = self.tokenizer(text,
|
978 |
+
return_tensors='pt',
|
979 |
+
add_special_tokens=add_special_tokens).input_ids.to(self.device)
|
980 |
+
embs = self.model.tok_embeddings(token)
|
981 |
+
return embs
|
982 |
+
|
983 |
+
# def encode_img(self, image):
|
984 |
+
# if image is None:
|
985 |
+
# return None
|
986 |
+
# if isinstance(image, str):
|
987 |
+
# image = Image.open(image).convert("RGB")
|
988 |
+
# image = self.vis_processor(image).unsqueeze(0).to(self.device)
|
989 |
+
# else:
|
990 |
+
# assert isinstance(image, torch.Tensor)
|
991 |
+
|
992 |
+
# img_embeds, atts_img, img_target = self.img2emb(image)
|
993 |
+
# return img_embeds
|
994 |
+
|
995 |
+
|
996 |
+
|
997 |
+
# def img2emb(self, image):
|
998 |
+
# img_embeds = self.vision_proj(
|
999 |
+
# self.vit(image.to(self.device)))
|
1000 |
+
# atts_img = torch.ones(img_embeds.size()[:-1], dtype=torch.long).to(img_embeds.device)
|
1001 |
+
|
1002 |
+
# img_target = torch.ones(img_embeds.size()[:2], dtype=torch.long).to(img_embeds.device) * -100
|
1003 |
+
|
1004 |
+
# return img_embeds, atts_img, img_target
|
1005 |
+
|
1006 |
+
def prompt_wrap(self, img_embeds, prompt):
|
1007 |
+
batch_size = img_embeds.shape[0]
|
1008 |
+
p_before, p_after = prompt.split('<ImageHere>')
|
1009 |
+
p_before_tokens = self.tokenizer(
|
1010 |
+
p_before, return_tensors="pt", add_special_tokens=True).to(img_embeds.device)
|
1011 |
+
|
1012 |
+
p_before_embeds = self.model.tok_embeddings(p_before_tokens.input_ids).expand(batch_size, -1, -1)
|
1013 |
+
wrapped_img_embeds = torch.cat([p_before_embeds, img_embeds], dim=1)
|
1014 |
+
|
1015 |
+
wrapped_atts_img = torch.ones(wrapped_img_embeds.size()[:-1], dtype=torch.long).to(img_embeds.device)
|
1016 |
+
|
1017 |
+
wrapped_target = torch.ones(batch_size, wrapped_img_embeds.shape[1], dtype=torch.long).to(img_embeds.device) * -100
|
1018 |
+
|
1019 |
+
|
1020 |
+
return wrapped_img_embeds, wrapped_atts_img, wrapped_target
|
1021 |
+
|
1022 |
+
def text2emb(self, text, add_special=False):
|
1023 |
+
# import pdb; pdb.set_trace()
|
1024 |
+
new_text = []
|
1025 |
+
for t in text:
|
1026 |
+
t = t.replace('<|User|>:', '[UNUSED_TOKEN_146]user\n')
|
1027 |
+
t = t.replace('<|Bot|>:', '[UNUSED_TOKEN_146]assistant\n')
|
1028 |
+
t = t.replace('<TOKENS_UNUSED_0>', '[UNUSED_TOKEN_145]')
|
1029 |
+
t = t.replace('<TOKENS_UNUSED_1>', '[UNUSED_TOKEN_145]')
|
1030 |
+
new_text.append(t)
|
1031 |
+
text = new_text
|
1032 |
+
to_regress_tokens = self.tokenizer(
|
1033 |
+
text,
|
1034 |
+
return_tensors="pt",
|
1035 |
+
padding="longest",
|
1036 |
+
truncation=True,
|
1037 |
+
max_length=self.max_length,
|
1038 |
+
add_special_tokens=add_special
|
1039 |
+
).to(self.device)
|
1040 |
+
|
1041 |
+
# targets = self.mask_human_targets(to_regress_tokens.input_ids)
|
1042 |
+
# targets = targets.to(self.device)
|
1043 |
+
targets = to_regress_tokens.input_ids.masked_fill(
|
1044 |
+
to_regress_tokens.input_ids == self.tokenizer.pad_token_id, -100
|
1045 |
+
).to(self.device)
|
1046 |
+
|
1047 |
+
|
1048 |
+
return to_regress_tokens, targets
|
1049 |
+
|
1050 |
+
def mask_human_targets(self, input_ids, pure=False):
|
1051 |
+
target_batch = []
|
1052 |
+
for bs in range(input_ids.shape[0]):
|
1053 |
+
cur_idx = 0
|
1054 |
+
ids = input_ids[bs]
|
1055 |
+
targets = copy.deepcopy(ids)
|
1056 |
+
end_count = 0
|
1057 |
+
last_eoa = 0
|
1058 |
+
for i, temp_id in enumerate(ids):
|
1059 |
+
if temp_id == 92542:
|
1060 |
+
if end_count % 2 == 0:
|
1061 |
+
targets[last_eoa: i+6] = -100
|
1062 |
+
else:
|
1063 |
+
last_eoa = i + 1
|
1064 |
+
end_count += 1
|
1065 |
+
elif temp_id == 2: ### eos and following pad
|
1066 |
+
targets[i+1:] = -100 #### loss on eos, but not on pad
|
1067 |
+
break
|
1068 |
+
if temp_id != 2 and end_count % 2 == 0: ### trunction, end at last question
|
1069 |
+
targets[last_eoa+1:] = -100 #### mask all after the last answer
|
1070 |
+
|
1071 |
+
target_batch.append(targets.unsqueeze(0))
|
1072 |
+
if self.debug_flag and 0:
|
1073 |
+
print ('#### Warining! System meta is not support now')
|
1074 |
+
targets_vis = targets.clone()
|
1075 |
+
targets_vis[targets_vis==-100] = 92399
|
1076 |
+
targets_vis_tokens = ''.join(self.tokenizer.convert_ids_to_tokens(targets_vis)).replace('[UNUSED_TOKEN_2]', " ")
|
1077 |
+
print(''.join(self.tokenizer.convert_ids_to_tokens(ids)))
|
1078 |
+
print('-----------')
|
1079 |
+
print([targets_vis_tokens])
|
1080 |
+
print('-----------------------------')
|
1081 |
+
|
1082 |
+
target_batch = torch.cat(target_batch, dim=0)
|
1083 |
+
return target_batch
|
1084 |
+
|
1085 |
+
@add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
|
1086 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1087 |
+
def forward(
|
1088 |
+
self,
|
1089 |
+
input_ids: torch.LongTensor = None,
|
1090 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1091 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1092 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1093 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1094 |
+
labels: Optional[torch.LongTensor] = None,
|
1095 |
+
use_cache: Optional[bool] = None,
|
1096 |
+
output_attentions: Optional[bool] = None,
|
1097 |
+
output_hidden_states: Optional[bool] = None,
|
1098 |
+
return_dict: Optional[bool] = None,
|
1099 |
+
**kwargs
|
1100 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1101 |
+
r"""
|
1102 |
+
Args:
|
1103 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1104 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1105 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1106 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1107 |
+
|
1108 |
+
Returns:
|
1109 |
+
|
1110 |
+
Example:
|
1111 |
+
|
1112 |
+
```python
|
1113 |
+
>>> from transformers import AutoTokenizer, InternLM2ForCausalLM
|
1114 |
+
|
1115 |
+
>>> model = InternLM2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
1116 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
1117 |
+
|
1118 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1119 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1120 |
+
|
1121 |
+
>>> # Generate
|
1122 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1123 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1124 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1125 |
+
```"""
|
1126 |
+
samples = kwargs.get('samples', None)
|
1127 |
+
if samples:
|
1128 |
+
if self.debug_flag:
|
1129 |
+
self.debug_flag += 1
|
1130 |
+
if self.debug_flag > 5:
|
1131 |
+
self.debug_flag = 0
|
1132 |
+
|
1133 |
+
has_img = 'image' in samples.keys()
|
1134 |
+
# import pdb; pdb.set_trace()
|
1135 |
+
### encode text
|
1136 |
+
# sp_token = samples["sp_token"]
|
1137 |
+
|
1138 |
+
text = samples['text_input']
|
1139 |
+
text = ['<|User|>:' + t for t in text]
|
1140 |
+
to_regress_tokens, targets = self.text2emb(text, add_special = True)
|
1141 |
+
|
1142 |
+
to_regress_embeds = self.model.tok_embeddings(to_regress_tokens.input_ids)
|
1143 |
+
attention_mask = to_regress_tokens.attention_mask
|
1144 |
+
|
1145 |
+
if has_img:
|
1146 |
+
### encode image
|
1147 |
+
image = samples["image"][0]
|
1148 |
+
bs = to_regress_embeds.shape[0]
|
1149 |
+
assert image.shape[0] == bs
|
1150 |
+
### combine text and image
|
1151 |
+
if samples['data_type'][0] != 'nlp':
|
1152 |
+
img_embeds, atts_img, img_target = self.img2emb(image)
|
1153 |
+
to_regress_embeds = torch.cat([to_regress_embeds[:,:1], img_embeds, to_regress_embeds[:,1:]], dim=1)
|
1154 |
+
attention_mask = torch.cat([attention_mask[:,:1], atts_img, attention_mask[:,1:]], dim=1)
|
1155 |
+
targets = torch.cat([targets[:,:1], img_target, targets[:,1:]], dim=1)
|
1156 |
+
|
1157 |
+
im_len = img_embeds.shape[1]
|
1158 |
+
im_mask = torch.zeros(to_regress_embeds.shape[:2]).cuda()
|
1159 |
+
im_mask[:,1:1+im_len] = 1
|
1160 |
+
temp_max_length = self.max_length
|
1161 |
+
|
1162 |
+
else:
|
1163 |
+
img_embeds, atts_img, img_target = self.img2emb(torch.zeros(1,3,self.im_size,self.im_size).to(image.device).to(image.dtype))
|
1164 |
+
to_regress_embeds += img_embeds.sum() * 0
|
1165 |
+
im_mask = torch.zeros(to_regress_embeds.shape[:2]).cuda()
|
1166 |
+
temp_max_length = 2048
|
1167 |
+
|
1168 |
+
temp_max_length = 2048
|
1169 |
+
inputs_embeds = to_regress_embeds[:, :temp_max_length]
|
1170 |
+
attention_mask = attention_mask[:, :temp_max_length]
|
1171 |
+
targets = targets[:, :temp_max_length]
|
1172 |
+
# im_mask = im_mask[:, :temp_max_length].bool()
|
1173 |
+
labels = targets
|
1174 |
+
if self.debug_flag:
|
1175 |
+
print (targets.shape, inputs_embeds.shape, attention_mask.shape)
|
1176 |
+
le = len(samples['text_input'])
|
1177 |
+
data_type = samples['data_type'][0]
|
1178 |
+
print (f'DataType: {data_type}. Has Image: {has_img}. Current max length: {self.max_length}, BatchSize is {le}')
|
1179 |
+
if has_img:
|
1180 |
+
print (img_embeds.shape)
|
1181 |
+
|
1182 |
+
else:
|
1183 |
+
self.debug_flag = 0
|
1184 |
+
im_mask = kwargs.get('im_mask', None)
|
1185 |
+
if im_mask is None and inputs_embeds is not None:
|
1186 |
+
im_mask = torch.zeros(inputs_embeds.shape[:2]).to(inputs_embeds.device)
|
1187 |
+
im_mask[:,1:1+256] = 1
|
1188 |
+
im_mask = im_mask.bool()
|
1189 |
+
|
1190 |
+
|
1191 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1192 |
+
output_hidden_states = (
|
1193 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1194 |
+
)
|
1195 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1196 |
+
|
1197 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1198 |
+
outputs = self.model(
|
1199 |
+
input_ids=input_ids,
|
1200 |
+
attention_mask=attention_mask,
|
1201 |
+
position_ids=position_ids,
|
1202 |
+
past_key_values=past_key_values,
|
1203 |
+
inputs_embeds=inputs_embeds,
|
1204 |
+
use_cache=use_cache,
|
1205 |
+
output_attentions=output_attentions,
|
1206 |
+
output_hidden_states=output_hidden_states,
|
1207 |
+
return_dict=return_dict,
|
1208 |
+
)
|
1209 |
+
|
1210 |
+
hidden_states = outputs[0]
|
1211 |
+
logits = self.output(hidden_states)
|
1212 |
+
logits = logits.float()
|
1213 |
+
|
1214 |
+
loss = None
|
1215 |
+
if labels is not None:
|
1216 |
+
# Shift so that tokens < n predict n
|
1217 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1218 |
+
shift_labels = labels[..., 1:].contiguous()
|
1219 |
+
# Flatten the tokens
|
1220 |
+
loss_fct = CrossEntropyLoss(reduce=False)
|
1221 |
+
B, N = shift_logits.shape[:2]
|
1222 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1223 |
+
shift_labels = shift_labels.view(-1)
|
1224 |
+
mask = shift_labels >= 0
|
1225 |
+
# Enable model parallelism
|
1226 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1227 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1228 |
+
loss = (loss.view(B,N).sum(dim=1) / mask.view(B,N).sum(dim=1)).mean()
|
1229 |
+
|
1230 |
+
if not return_dict:
|
1231 |
+
output = (logits,) + outputs[1:]
|
1232 |
+
return (loss,) + output if loss is not None else output
|
1233 |
+
|
1234 |
+
return CausalLMOutputWithPast(
|
1235 |
+
loss=loss,
|
1236 |
+
logits=logits,
|
1237 |
+
past_key_values=outputs.past_key_values,
|
1238 |
+
hidden_states=outputs.hidden_states,
|
1239 |
+
attentions=outputs.attentions,
|
1240 |
+
)
|
1241 |
+
|
1242 |
+
def prepare_inputs_for_generation(
|
1243 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, im_mask=None, **kwargs
|
1244 |
+
):
|
1245 |
+
if past_key_values is not None:
|
1246 |
+
past_length = past_key_values[0][0].shape[2]
|
1247 |
+
|
1248 |
+
# Some generation methods already pass only the last input ID
|
1249 |
+
if input_ids.shape[1] > past_length:
|
1250 |
+
remove_prefix_length = past_length
|
1251 |
+
else:
|
1252 |
+
# Default to old behavior: keep only final ID
|
1253 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
1254 |
+
|
1255 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
1256 |
+
|
1257 |
+
position_ids = kwargs.get("position_ids", None)
|
1258 |
+
if attention_mask is not None and position_ids is None:
|
1259 |
+
# create position_ids on the fly for batch generation
|
1260 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1261 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1262 |
+
if past_key_values:
|
1263 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1264 |
+
|
1265 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1266 |
+
if inputs_embeds is not None and past_key_values is None:
|
1267 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1268 |
+
else:
|
1269 |
+
model_inputs = {"input_ids": input_ids}
|
1270 |
+
|
1271 |
+
im_mask = im_mask
|
1272 |
+
|
1273 |
+
model_inputs.update(
|
1274 |
+
{
|
1275 |
+
"position_ids": position_ids,
|
1276 |
+
"past_key_values": past_key_values,
|
1277 |
+
"use_cache": kwargs.get("use_cache"),
|
1278 |
+
"attention_mask": attention_mask,
|
1279 |
+
"im_mask": im_mask,
|
1280 |
+
}
|
1281 |
+
)
|
1282 |
+
return model_inputs
|
1283 |
+
|
1284 |
+
@staticmethod
|
1285 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1286 |
+
reordered_past = ()
|
1287 |
+
for layer_past in past_key_values:
|
1288 |
+
reordered_past += (
|
1289 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1290 |
+
)
|
1291 |
+
return reordered_past
|
1292 |
+
|
1293 |
+
def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = [], meta_instruction=""):
|
1294 |
+
prompt = ""
|
1295 |
+
if meta_instruction:
|
1296 |
+
prompt += f"""<s>[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
|
1297 |
+
else:
|
1298 |
+
prompt += "<s>"
|
1299 |
+
for record in history:
|
1300 |
+
prompt += f"""[UNUSED_TOKEN_146]user\n{record[0]}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n{record[1]}[UNUSED_TOKEN_145]\n"""
|
1301 |
+
prompt += f"""[UNUSED_TOKEN_146]user\n{query}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n"""
|
1302 |
+
return tokenizer([prompt], return_tensors="pt")
|
1303 |
+
|
1304 |
+
def inference(self, question, tokenizer):
|
1305 |
+
print(question)
|
1306 |
+
question = f'[UNUSED_TOKEN_146]user\n{question}[UNUSED_TOKEN_145]\n'
|
1307 |
+
stop_words_ids = [
|
1308 |
+
torch.tensor([2]).cuda(), #'</s>'
|
1309 |
+
torch.tensor([92542]).cuda(), #'[UNUSED_TOKEN_145]'
|
1310 |
+
]
|
1311 |
+
stopping_criteria = StoppingCriteriaList(
|
1312 |
+
[StoppingCriteriaSub(stops=stop_words_ids)])
|
1313 |
+
result = []
|
1314 |
+
for i in range(3):
|
1315 |
+
print(f'------attempt {i}------')
|
1316 |
+
d = f"{question}"
|
1317 |
+
input_ids = tokenizer(d, return_tensors="pt")["input_ids"]
|
1318 |
+
eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["[UNUSED_TOKEN_145]"])[0]]
|
1319 |
+
with torch.no_grad():
|
1320 |
+
generate = self.generate(input_ids.cuda(),
|
1321 |
+
do_sample=True,
|
1322 |
+
temperature=1.0,
|
1323 |
+
repetition_penalty=1.005,
|
1324 |
+
max_new_tokens=1000,
|
1325 |
+
top_p=0.8,
|
1326 |
+
top_k=50,
|
1327 |
+
eos_token_id=eos_token_id,
|
1328 |
+
stopping_criteria=stopping_criteria,)
|
1329 |
+
response = tokenizer.decode(generate[0].tolist(), skip_special_tokens=True)
|
1330 |
+
response.split('[UNUSED_TOKEN_146]assistant')[1]
|
1331 |
+
print(response[len('[UNUSED_TOKEN_146]assistant\n'):-len('[UNUSED_TOKEN_145]\n')])
|
1332 |
+
|
special_tokens_map.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<s>",
|
3 |
+
"eos_token": "</s>",
|
4 |
+
"pad_token": "</s>",
|
5 |
+
"unk_token": "<unk>"
|
6 |
+
}
|
tokenization_internlm.py
ADDED
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright (c) InternLM. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
|
21 |
+
"""Tokenization classes for IntermLM."""
|
22 |
+
import os
|
23 |
+
from shutil import copyfile
|
24 |
+
from typing import Any, Dict, List, Optional, Tuple
|
25 |
+
|
26 |
+
import sentencepiece as spm
|
27 |
+
from transformers.tokenization_utils import PreTrainedTokenizer
|
28 |
+
from transformers.utils import logging
|
29 |
+
|
30 |
+
logger = logging.get_logger(__name__)
|
31 |
+
|
32 |
+
VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
|
33 |
+
|
34 |
+
PRETRAINED_VOCAB_FILES_MAP = {}
|
35 |
+
|
36 |
+
|
37 |
+
class InternLMTokenizer(PreTrainedTokenizer):
|
38 |
+
"""
|
39 |
+
Construct a InternLM tokenizer. Based on byte-level Byte-Pair-Encoding.
|
40 |
+
|
41 |
+
Args:
|
42 |
+
vocab_file (`str`):
|
43 |
+
Path to the vocabulary file.
|
44 |
+
"""
|
45 |
+
|
46 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
47 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
48 |
+
model_input_names = ["input_ids", "attention_mask"]
|
49 |
+
_auto_class = "AutoTokenizer"
|
50 |
+
|
51 |
+
def __init__(
|
52 |
+
self,
|
53 |
+
vocab_file,
|
54 |
+
unk_token="<unk>",
|
55 |
+
bos_token="<s>",
|
56 |
+
eos_token="</s>",
|
57 |
+
pad_token="</s>",
|
58 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
59 |
+
add_bos_token=True,
|
60 |
+
add_eos_token=False,
|
61 |
+
decode_with_prefix_space=False,
|
62 |
+
clean_up_tokenization_spaces=False,
|
63 |
+
**kwargs,
|
64 |
+
):
|
65 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
66 |
+
self.vocab_file = vocab_file
|
67 |
+
self.add_bos_token = add_bos_token
|
68 |
+
self.add_eos_token = add_eos_token
|
69 |
+
self.decode_with_prefix_space = decode_with_prefix_space
|
70 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
71 |
+
self.sp_model.Load(vocab_file)
|
72 |
+
self._no_prefix_space_tokens = None
|
73 |
+
super().__init__(
|
74 |
+
bos_token=bos_token,
|
75 |
+
eos_token=eos_token,
|
76 |
+
unk_token=unk_token,
|
77 |
+
pad_token=pad_token,
|
78 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
79 |
+
**kwargs,
|
80 |
+
)
|
81 |
+
|
82 |
+
""" Initialization"""
|
83 |
+
|
84 |
+
@property
|
85 |
+
def no_prefix_space_tokens(self):
|
86 |
+
if self._no_prefix_space_tokens is None:
|
87 |
+
vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
|
88 |
+
self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith("▁")}
|
89 |
+
return self._no_prefix_space_tokens
|
90 |
+
|
91 |
+
@property
|
92 |
+
def vocab_size(self):
|
93 |
+
"""Returns vocab size"""
|
94 |
+
return self.sp_model.get_piece_size()
|
95 |
+
|
96 |
+
@property
|
97 |
+
def bos_token_id(self) -> Optional[int]:
|
98 |
+
return self.sp_model.bos_id()
|
99 |
+
|
100 |
+
@property
|
101 |
+
def eos_token_id(self) -> Optional[int]:
|
102 |
+
return self.sp_model.eos_id()
|
103 |
+
|
104 |
+
def get_vocab(self):
|
105 |
+
"""Returns vocab as a dict"""
|
106 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
107 |
+
vocab.update(self.added_tokens_encoder)
|
108 |
+
return vocab
|
109 |
+
|
110 |
+
def _tokenize(self, text):
|
111 |
+
"""Returns a tokenized string."""
|
112 |
+
return self.sp_model.encode(text, out_type=str)
|
113 |
+
|
114 |
+
def _convert_token_to_id(self, token):
|
115 |
+
"""Converts a token (str) in an id using the vocab."""
|
116 |
+
return self.sp_model.piece_to_id(token)
|
117 |
+
|
118 |
+
def _convert_id_to_token(self, index):
|
119 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
120 |
+
token = self.sp_model.IdToPiece(index)
|
121 |
+
return token
|
122 |
+
|
123 |
+
def _maybe_add_prefix_space(self, tokens, decoded):
|
124 |
+
if tokens and tokens[0] not in self.no_prefix_space_tokens:
|
125 |
+
return " " + decoded
|
126 |
+
else:
|
127 |
+
return decoded
|
128 |
+
|
129 |
+
def convert_tokens_to_string(self, tokens):
|
130 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
131 |
+
current_sub_tokens = []
|
132 |
+
out_string = ""
|
133 |
+
prev_is_special = False
|
134 |
+
for token in tokens:
|
135 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
136 |
+
if token in self.all_special_tokens:
|
137 |
+
if not prev_is_special:
|
138 |
+
out_string += " "
|
139 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
140 |
+
prev_is_special = True
|
141 |
+
current_sub_tokens = []
|
142 |
+
else:
|
143 |
+
current_sub_tokens.append(token)
|
144 |
+
prev_is_special = False
|
145 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
146 |
+
out_string = self.clean_up_tokenization(out_string)
|
147 |
+
out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
|
148 |
+
return out_string[1:]
|
149 |
+
|
150 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
151 |
+
"""
|
152 |
+
Save the vocabulary and special tokens file to a directory.
|
153 |
+
|
154 |
+
Args:
|
155 |
+
save_directory (`str`):
|
156 |
+
The directory in which to save the vocabulary.
|
157 |
+
|
158 |
+
Returns:
|
159 |
+
`Tuple(str)`: Paths to the files saved.
|
160 |
+
"""
|
161 |
+
if not os.path.isdir(save_directory):
|
162 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
163 |
+
return
|
164 |
+
out_vocab_file = os.path.join(
|
165 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
166 |
+
)
|
167 |
+
|
168 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
169 |
+
copyfile(self.vocab_file, out_vocab_file)
|
170 |
+
elif not os.path.isfile(self.vocab_file):
|
171 |
+
with open(out_vocab_file, "wb") as fi:
|
172 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
173 |
+
fi.write(content_spiece_model)
|
174 |
+
|
175 |
+
return (out_vocab_file,)
|
176 |
+
|
177 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
178 |
+
if self.add_bos_token:
|
179 |
+
bos_token_ids = [self.bos_token_id]
|
180 |
+
else:
|
181 |
+
bos_token_ids = []
|
182 |
+
|
183 |
+
output = bos_token_ids + token_ids_0
|
184 |
+
|
185 |
+
if token_ids_1 is not None:
|
186 |
+
output = output + token_ids_1
|
187 |
+
|
188 |
+
if self.add_eos_token:
|
189 |
+
output = output + [self.eos_token_id]
|
190 |
+
|
191 |
+
return output
|
192 |
+
|
193 |
+
def get_special_tokens_mask(
|
194 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
195 |
+
) -> List[int]:
|
196 |
+
"""
|
197 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
198 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
199 |
+
|
200 |
+
Args:
|
201 |
+
token_ids_0 (`List[int]`):
|
202 |
+
List of IDs.
|
203 |
+
token_ids_1 (`List[int]`, *optional*):
|
204 |
+
Optional second list of IDs for sequence pairs.
|
205 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
206 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
207 |
+
|
208 |
+
Returns:
|
209 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
210 |
+
"""
|
211 |
+
if already_has_special_tokens:
|
212 |
+
return super().get_special_tokens_mask(
|
213 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
214 |
+
)
|
215 |
+
|
216 |
+
if token_ids_1 is None:
|
217 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
218 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
219 |
+
|
220 |
+
def create_token_type_ids_from_sequences(
|
221 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
222 |
+
) -> List[int]:
|
223 |
+
"""
|
224 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
|
225 |
+
use of token type ids, therefore a list of zeros is returned.
|
226 |
+
|
227 |
+
Args:
|
228 |
+
token_ids_0 (`List[int]`):
|
229 |
+
List of IDs.
|
230 |
+
token_ids_1 (`List[int]`, *optional*):
|
231 |
+
Optional second list of IDs for sequence pairs.
|
232 |
+
|
233 |
+
Returns:
|
234 |
+
`List[int]`: List of zeros.
|
235 |
+
"""
|
236 |
+
eos = [self.eos_token_id]
|
237 |
+
|
238 |
+
if token_ids_1 is None:
|
239 |
+
return len(token_ids_0 + eos) * [0]
|
240 |
+
return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f868398fc4e05ee1e8aeba95ddf18ddcc45b8bce55d5093bead5bbf80429b48b
|
3 |
+
size 1477754
|
tokenizer_config.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": [
|
4 |
+
"tokenization_internlm.InternLMTokenizer",
|
5 |
+
null
|
6 |
+
]
|
7 |
+
},
|
8 |
+
"bos_token": "<s>",
|
9 |
+
"clean_up_tokenization_spaces": false,
|
10 |
+
"eos_token": "</s>",
|
11 |
+
"model_max_length": 1000000000000000019884624838656,
|
12 |
+
"pad_token": "</s>",
|
13 |
+
"padding_side": "right",
|
14 |
+
"tokenizer_class": "InternLMTokenizer",
|
15 |
+
"unk_token": "<unk>"
|
16 |
+
}
|