├── LICENSE.md
├── README.md
├── datasets
├── elon_musk_tweets.csv
└── stable_diffusion_prompts.csv
├── example-chat.py
├── example.py
├── hf-chat-example.py
├── hf-inference-cuda-example.py
├── hf-inference-example.py
├── hf-training-example.py
├── llama
├── __init__.py
├── generation.py
├── model.py
└── tokenizer.py
├── llamahf
├── __init__.py
├── configuration_llama.py
├── convert_llama_weights_to_hf.py
├── modeling_llama.py
└── tokenization_llama.py
├── merge-weights.py
├── model
└── .gitignore
├── requirements.txt
├── setup.py
└── tokenizer
└── .gitignore
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Chat with Meta's LLaMA models at home made easy
2 |
3 | This repository is a chat example with [LLaMA](https://ai.facebook.com/blog/large-language-model-llama-meta-ai/) ([arXiv](https://arxiv.org/abs/2302.13971v1)) models running on a typical home PC. You will just need a NVIDIA videocard and some RAM to chat with model.
4 |
5 | By using HF version you may fine-tune the model to any desired task.
6 |
7 | ## Copyright
8 |
9 | This repo is heavily based on Meta's original repo: https://github.com/facebookresearch/llama
10 |
11 | And on Steve Manuatu's repo: https://github.com/venuatu/llama
12 |
13 | And on Shawn Presser's repo: https://github.com/shawwn/llama
14 |
15 | [HF 🤗 version](https://github.com/randaller/llama-chat#hugging-face--version-inference--training) by Yam Peleg and Jason Phang: https://github.com/ypeleg/llama & https://github.com/zphang
16 |
17 | ## Examples of chats here
18 |
19 | https://github.com/facebookresearch/llama/issues/162
20 |
21 | Share your best prompts, chats or generations here in this issue: https://github.com/randaller/llama-chat/issues/7
22 |
23 | ## System requirements
24 | - Modern enough CPU
25 | - NVIDIA graphics card (2 Gb of VRAM is ok); HF version is able to run on CPU, or mixed CPU/GPU, or pure GPU
26 | - 64 or better 128 Gb of RAM (192 would be perfect for 65B model)
27 |
28 | One may run with 32 Gb of RAM, but inference will be slow (with the speed of your swap file reading)
29 |
30 | I am running PyArrow version on a [12700k/128 Gb RAM/NVIDIA 3070ti 8Gb/fast huge nvme with 256 Gb swap for 65B model] and getting one token from 30B model in a few seconds.
31 |
32 | For example, **PyArrow 30B model uses around 70 Gb of RAM**. 7B model fits into 18 Gb. 13B model uses 48 Gb.
33 |
34 | If you do not have nvidia videocard, you may use another repo for cpu-only inference: https://github.com/randaller/llama-cpu or [HF 🤗 version](https://github.com/randaller/llama-chat#hugging-face--version-inference--training).
35 |
36 | ## Installation
37 |
38 | ### Download the repo
39 |
40 | ```
41 | git clone https://github.com/randaller/llama-chat.git
42 | cd llama-chat
43 | ```
44 |
45 | ### Conda Environment Setup Example for Windows 10+
46 | Download and install Anaconda Python https://www.anaconda.com and run Anaconda Prompt
47 | ```
48 | conda create -n llama python=3.10
49 | conda activate llama
50 | conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
51 | ```
52 |
53 | ### Install requirements
54 | In a conda env with pytorch / cuda available, run
55 | ```
56 | pip install -r requirements.txt
57 | ```
58 | Then in this repository
59 | ```
60 | pip install -e .
61 | ```
62 |
63 | ## PyArrow version (inference only)
64 |
65 | ### Download tokenizer and models
66 | magnet:?xt=urn:btih:ZXXDAUWYLRUXXBHUYEMS6Q5CE5WA3LVA&dn=LLaMA
67 |
68 | or
69 |
70 | magnet:?xt=urn:btih:b8287ebfa04f879b048d4d4404108cf3e8014352&dn=LLaMA&tr=udp%3a%2f%2ftracker.opentrackr.org%3a1337%2fannounce
71 |
72 | ### Prepare model
73 |
74 | First, you need to unshard model checkpoints to a single file. Let's do this for 30B model.
75 |
76 | ```
77 | python merge-weights.py --input_dir D:\Downloads\LLaMA --model_size 30B
78 | ```
79 |
80 | In this example, D:\Downloads\LLaMA is a root folder of downloaded torrent with weights.
81 |
82 | This will create merged.pth file in the root folder of this repo.
83 |
84 | Place this file and corresponding (torrentroot)/30B/params.json of model into [/model] folder.
85 |
86 | So you should end up with two files in [/model] folder: merged.pth and params.json.
87 |
88 | Place (torrentroot)/tokenizer.model file to the [/tokenizer] folder of this repo. Now you are ready to go.
89 |
90 | ### Run the chat
91 |
92 | ```
93 | python example-chat.py ./model ./tokenizer/tokenizer.model
94 | ```
95 |
96 | ### Generation parameters
97 |
98 | 
99 |
100 | **Temperature** is one of the key parameters of generation. You may wish to play with temperature. The more temperature is, the model will use more "creativity", and the less temperature instruct model to be "less creative", but following your prompt stronger.
101 |
102 | **Repetition penalty** is a feature implemented by Shawn Presser. With this, the model will be fined, when it would like to enter to repetion loop state. Set this parameter to 1.0, if you wish to disable this feature.
103 |
104 | **Samplers**
105 |
106 | By default, Meta provided us with top_p sampler only. Again, Shawn added an alternate top_k sampler, which (in my tests) performs pretty well. If you wish to switch to top_k sampler, use the following parameters:
107 |
108 | ```
109 | temperature: float = 0.7,
110 | top_p: float = 0.0,
111 | top_k: int = 40,
112 | sampler: str = 'top_k',
113 | ```
114 |
115 | For sure, you may play with all the values to get different outputs.
116 |
117 | **Launch examples**
118 |
119 | One may modify these hyperparameters straight in the code. But it is better to leave the defaults in code and set the parameters of experiments in the launch line.
120 |
121 | ```
122 | # Run with top_p sampler, with temperature 0.75, with top_p value 0.95, repetition penalty disabled
123 | python example-chat.py ./model ./tokenizer/tokenizer.model 0.75 0.95 0 1.0 top_p
124 |
125 | # Run with top_k sampler, with temperature 0.7, with top_k value 40, default repetition penalty value
126 | python example-chat.py ./model ./tokenizer/tokenizer.model 0.7 0.0 40 1.17 top_k
127 | ```
128 |
129 | Of course, this is also applicable to a [python example.py] as well (see below).
130 |
131 |
132 | ### Enable multi-line answers
133 |
134 | If you wish to stop generation not by "\n" sign, but by another signature, like "User:" (which is also good idea), or any other, make the following modification in the llama/generation.py:
135 |
136 | 
137 |
138 | -5 means to remove last 5 chars from resulting context, which is length of your stop signature, "User:" in this example.
139 |
140 | ### Share the best with community
141 |
142 | Share your best prompts and generations with others here: https://github.com/randaller/llama-chat/issues/7
143 |
144 | ### Typical generation with prompt (not a chat)
145 |
146 | Simply comment three lines in llama/generation.py to turn it to a generator back.
147 |
148 | 
149 |
150 | ```
151 | python example.py ./model ./tokenizer/tokenizer.model
152 | ```
153 |
154 | Confirming that 30B model is able to generate code and fix errors in code: https://github.com/randaller/llama-chat/issues/7
155 |
156 | Confirming that 30B model is able to generate prompts for Stable Diffusion: https://github.com/randaller/llama-chat/issues/7#issuecomment-1463691554
157 |
158 | Confirming that 7B and 30B model support Arduino IDE: https://github.com/randaller/llama-chat/issues/7#issuecomment-1464179944
159 |
160 | Confirming that 30B model is able to generate SQL code: https://github.com/randaller/llama-chat/issues/7#issuecomment-1467861922
161 |
162 | ## Hugging Face 🤗 version (inference & training)
163 |
164 | ### Inference
165 |
166 | Thanks to Yam Peleg, we now have *"No overengineering bullshit"* version.
167 |
168 | You do not need to download torrent or merge weights, as model shards and tokenizer will be downloaded from HF automatically at the first run. They will be cached in [C:\Users\USERNAME\\.cache\huggingface\hub] folder under Windows, so do not forget to clean up to 250 Gb after experiments.
169 |
170 | ```
171 | python hf-inference-example.py
172 | ```
173 |
174 | ### Chatting
175 |
176 | ```
177 | python hf-chat-example.py
178 | ```
179 |
180 | ### Training
181 |
182 | Prepare your dataset, edit the training example to define your dataset file and launch training. Dataset file with strings should be in UTF-8 encoding.
183 |
184 | 
185 | ```
186 | python hf-training-example.py
187 | ```
188 | Trained model will be saved into [./trained] folder. Now launch chat or inference example with freshly trained model:
189 |
190 | ```
191 | python hf-chat-example.py
192 | ```
193 | ```
194 | python hf-inference-example.py
195 | ```
196 |
197 | ### Bfloat16 training and inference optimization
198 |
199 | To save CPU RAM or GPU VRAM memory, one may wish to enable Bfloat16 processing.
200 |
201 | ```
202 | # to save memory use bfloat16
203 | import torch
204 | torch.set_default_dtype(torch.bfloat16)
205 | ```
206 |
207 | ### Offload to GPU with accelerate
208 |
209 | ```
210 | device_map = infer_auto_device_map(model, max_memory={0: "6GiB", "cpu": "128GiB"})
211 | ```
212 |
213 | One with A100 might try to set 38Gb to a GPU0 and try to inference the model completely in the GPU VRAM.
214 |
215 | One with 4*A100 might wish to use: {0: "38GiB", 1: "38GiB", 2: "38GiB", 3: "38GiB", "cpu":"128GiB"}.
216 |
217 | For me, with 7Gb for 3070ti, for 7B model, this works at the same speed as pure CPU inference.
218 |
219 | ```
220 | python hf-inference-cuda-example.py
221 | ```
222 |
223 | ### How to fine-tune LLaMA for Stable Diffusion prompting
224 |
225 | Modify hf-training-example.py, also feel free to use more or less lines of SD prompts examples in csv file:
226 |
227 | ```
228 | MODEL = 'decapoda-research/llama-7b-hf'
229 | DATA_FILE_PATH = 'datasets/stable_diffusion_prompts.csv'
230 | OUTPUT_DIR = './trained'
231 | ```
232 |
233 | *Note: You may also prepare your own dataset, for example, with Prompt: and Negative prompt: and even Steps Sampler etc lines interleaving or single-lined in csv. Max length of each data string should not exceed LLaMA's 2048 tokens.*
234 |
235 | Then run the training, then after a long-long time, use something like this as a prompt for LLaMA to generate SD prompts:
236 |
237 | ```
238 | batch = tokenizer("A portrait of a beautiful girl, ", return_tensors="pt")
239 | ```
240 |
241 | *Note: If you have prepared and used own dataset with Prompt: Negative prompt: lines, the initial LLaMA prompt may look like:*
242 |
243 | ```
244 | batch = tokenizer("Prompt: A warship flying thru the Wormhole, ", return_tensors="pt")
245 | ```
246 |
247 | Run inference, this should return continued prompt for SD.
248 |
249 | ## Reference
250 |
251 | LLaMA: Open and Efficient Foundation Language Models -- https://arxiv.org/abs/2302.13971
252 |
253 | ```
254 | @article{touvron2023llama,
255 | title={LLaMA: Open and Efficient Foundation Language Models},
256 | author={Touvron, Hugo and Lavril, Thibaut and Izacard, Gautier and Martinet, Xavier and Lachaux, Marie-Anne and Lacroix, Timoth{\'e}e and Rozi{\`e}re, Baptiste and Goyal, Naman and Hambro, Eric and Azhar, Faisal and Rodriguez, Aurelien and Joulin, Armand and Grave, Edouard and Lample, Guillaume},
257 | journal={arXiv preprint arXiv:2302.13971},
258 | year={2023}
259 | }
260 | ```
261 |
--------------------------------------------------------------------------------
/example-chat.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) Meta Platforms, Inc. and affiliates.
2 | # This software may be used and distributed according to the terms of the GNU General Public License version 3.
3 |
4 | from typing import Tuple
5 | import os
6 | import sys
7 | import torch
8 | import fire
9 | import time
10 | import json
11 | import pyarrow as pa
12 |
13 | from pathlib import Path
14 |
15 | from llama import ModelArgs, Transformer, Tokenizer, LLaMA
16 |
17 |
18 | def load(
19 | ckpt_dir: str,
20 | tokenizer_path: str,
21 | max_seq_len: int,
22 | max_batch_size: int,
23 | ) -> LLaMA:
24 | start_time = time.time()
25 | arrow_dir = Path(ckpt_dir).expanduser() / 'arrow'
26 |
27 | if not arrow_dir.exists():
28 | print('Converting checkpoints to arrow format')
29 | checkpoints = sorted(Path(ckpt_dir).expanduser().glob("*.pth"))
30 | for ckpt_file in checkpoints:
31 | print(ckpt_file)
32 | index = ckpt_file.parts[-1].split('.')[-2]
33 |
34 | ckpt = torch.load(ckpt_file, map_location='cpu')
35 | (arrow_dir / index).mkdir(parents=True, exist_ok=True)
36 | for k, v in ckpt.items():
37 | tens = pa.Tensor.from_numpy(v.numpy())
38 | with pa.output_stream(arrow_dir / index / k) as f:
39 | pa.ipc.write_tensor(tens, f)
40 | ckpt = None
41 |
42 | with open(Path(ckpt_dir) / "params.json", "r") as f:
43 | params = json.loads(f.read())
44 |
45 | print("Loading checkpoint")
46 | segments = sorted((arrow_dir / '00').glob("*"))
47 |
48 | checkpoint = {}
49 | files = []
50 | for seg in segments:
51 | f = pa.memory_map(str(seg))
52 | files.append(f)
53 | t = pa.ipc.read_tensor(f).to_numpy()
54 | t = torch.from_numpy(t)
55 | checkpoint[seg.parts[-1]] = t
56 |
57 | # torch.set_default_tensor_type(torch.cuda.HalfTensor)
58 | torch.set_default_tensor_type(torch.BFloat16Tensor)
59 | # torch.set_default_tensor_type(torch.FloatTensor)
60 |
61 | model_args: ModelArgs = ModelArgs(
62 | max_seq_len=max_seq_len, max_batch_size=max_batch_size, **params
63 | )
64 | print("Loading tokenizer")
65 | tokenizer = Tokenizer(model_path=tokenizer_path)
66 | model_args.vocab_size = tokenizer.n_words
67 | print("Loading model")
68 | model = Transformer(model_args)
69 |
70 | checkpoints = sorted(Path(ckpt_dir).glob("*.pth"))
71 | model.load_state_dict(torch.load(checkpoints[-1]), strict=False)
72 |
73 | for f in files:
74 | f.close()
75 | files = None
76 |
77 | generator = LLaMA(model, tokenizer)
78 | print(f"Loaded in {time.time() - start_time:.2f} seconds")
79 | return generator
80 |
81 |
82 | def main(
83 | ckpt_dir: str,
84 | tokenizer_path: str,
85 | temperature: float = 0.8,
86 | top_p: float = 0.95, # use 0.95 or so for top_p sampler, and 0.0 for top_k sampler
87 | top_k: int = 40,
88 | repetition_penalty: float = (1.0 / 0.85), # 1.0 to disable repetition_penalty
89 | sampler: str = 'top_p', # top_p or top_k
90 | max_seq_len: int = 2048,
91 | max_batch_size: int = 1,
92 | ):
93 | generator = load(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size)
94 |
95 | ctx = """A dialog, where User interacts with AI. AI is helpful, kind, obedient, honest, and knows its own limits.
96 | User: Hello, AI.
97 | AI: Hello! How can I assist you today?
98 | """
99 |
100 | while True:
101 | prompt = input(f'User: ')
102 | if ctx != "":
103 | ctx = ctx + "User: " + prompt + "\n"
104 | else:
105 | ctx = prompt + "\n"
106 |
107 | ctx = (ctx[-1920:]) if len(ctx) >= 2048 else ctx
108 |
109 | if len(ctx.strip()) > 0:
110 | prompts = [ctx]
111 | results = generator.generate(
112 | prompts, max_gen_len=max_seq_len, temperature=temperature, top_p=top_p, top_k=top_k, repetition_penalty=repetition_penalty, sampler=sampler
113 | )
114 | ctx = results[0]
115 |
116 |
117 | if __name__ == "__main__":
118 | fire.Fire(main)
119 |
--------------------------------------------------------------------------------
/example.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) Meta Platforms, Inc. and affiliates.
2 | # This software may be used and distributed according to the terms of the GNU General Public License version 3.
3 |
4 | from typing import Tuple
5 | import os
6 | import sys
7 | import torch
8 | import fire
9 | import time
10 | import json
11 | import pyarrow as pa
12 |
13 | from pathlib import Path
14 |
15 | from llama import ModelArgs, Transformer, Tokenizer, LLaMA
16 |
17 |
18 | def load(
19 | ckpt_dir: str,
20 | tokenizer_path: str,
21 | max_seq_len: int,
22 | max_batch_size: int,
23 | ) -> LLaMA:
24 | start_time = time.time()
25 | arrow_dir = Path(ckpt_dir).expanduser() / 'arrow'
26 |
27 | if not arrow_dir.exists():
28 | print('Converting checkpoints to arrow format')
29 | checkpoints = sorted(Path(ckpt_dir).expanduser().glob("*.pth"))
30 | for ckpt_file in checkpoints:
31 | print(ckpt_file)
32 | index = ckpt_file.parts[-1].split('.')[-2]
33 |
34 | ckpt = torch.load(ckpt_file, map_location='cpu')
35 | (arrow_dir / index).mkdir(parents=True, exist_ok=True)
36 | for k, v in ckpt.items():
37 | tens = pa.Tensor.from_numpy(v.numpy())
38 | with pa.output_stream(arrow_dir / index / k) as f:
39 | pa.ipc.write_tensor(tens, f)
40 | ckpt = None
41 |
42 | with open(Path(ckpt_dir) / "params.json", "r") as f:
43 | params = json.loads(f.read())
44 |
45 | print("Loading checkpoint")
46 | segments = sorted((arrow_dir / '00').glob("*"))
47 | # print(segments)
48 |
49 | checkpoint = {}
50 | files = []
51 | for seg in segments:
52 | f = pa.memory_map(str(seg))
53 | files.append(f)
54 | t = pa.ipc.read_tensor(f).to_numpy()
55 | t = torch.from_numpy(t)
56 | checkpoint[seg.parts[-1]] = t
57 |
58 | # torch.set_default_tensor_type(torch.cuda.HalfTensor)
59 | torch.set_default_tensor_type(torch.BFloat16Tensor)
60 | # torch.set_default_tensor_type(torch.FloatTensor)
61 |
62 | model_args: ModelArgs = ModelArgs(
63 | max_seq_len=max_seq_len, max_batch_size=max_batch_size, **params
64 | )
65 | print("Loading tokenizer")
66 | tokenizer = Tokenizer(model_path=tokenizer_path)
67 | model_args.vocab_size = tokenizer.n_words
68 | print("Loading model")
69 | model = Transformer(model_args)
70 |
71 | checkpoints = sorted(Path(ckpt_dir).glob("*.pth"))
72 | model.load_state_dict(torch.load(checkpoints[-1]), strict=False)
73 |
74 | for f in files:
75 | f.close()
76 | files = None
77 |
78 | generator = LLaMA(model, tokenizer)
79 | print(f"Loaded in {time.time() - start_time:.2f} seconds")
80 | return generator
81 |
82 |
83 | def main(
84 | ckpt_dir: str,
85 | tokenizer_path: str,
86 | temperature: float = 0.8,
87 | top_p: float = 0.95, # use 0.95 or so for top_p sampler, and 0.0 for top_k sampler
88 | top_k: int = 40,
89 | repetition_penalty: float = (1.0 / 0.85), # 1.0 to disable repetition_penalty
90 | sampler: str = 'top_p', # top_p or top_k
91 | max_seq_len: int = 2048,
92 | max_batch_size: int = 1,
93 | ):
94 | generator = load(ckpt_dir, tokenizer_path, max_seq_len, max_batch_size)
95 |
96 | prompts = [
97 | # "I believe the meaning of life is",
98 | """Write the Python code with detailed comments to generate 256 random integers in the range from -128 to 512, inclusive.
99 | \\begin{code}\n""",
100 | ]
101 |
102 | results = generator.generate(
103 | prompts, max_gen_len=max_seq_len, temperature=temperature, top_p=top_p, top_k=top_k, repetition_penalty=repetition_penalty, sampler=sampler
104 | )
105 |
106 | for result in results:
107 | print("\n==================================\n")
108 | print(result)
109 | print("\n==================================\n")
110 |
111 |
112 | if __name__ == "__main__":
113 | fire.Fire(main)
114 |
--------------------------------------------------------------------------------
/hf-chat-example.py:
--------------------------------------------------------------------------------
1 | import llamahf
2 | import os
3 | import torch
4 | from transformers import StoppingCriteria, StoppingCriteriaList
5 |
6 | # # to save memory use bfloat16
7 | # torch.set_default_dtype(torch.bfloat16)
8 |
9 | MODEL = 'decapoda-research/llama-7b-hf'
10 | # MODEL = 'decapoda-research/llama-13b-hf'
11 | # MODEL = 'decapoda-research/llama-30b-hf'
12 | # MODEL = 'decapoda-research/llama-65b-hf'
13 |
14 | if os.path.exists('./trained'):
15 | MODEL = './trained'
16 |
17 | tokenizer = llamahf.LLaMATokenizer.from_pretrained(MODEL)
18 | model = llamahf.LLaMAForCausalLM.from_pretrained(MODEL, low_cpu_mem_usage=True)
19 | model.to('cpu')
20 |
21 |
22 | class StoppingCriteriaSub(StoppingCriteria):
23 | def __init__(self):
24 | super().__init__()
25 |
26 | def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, stops=[]):
27 | print('-' * 40)
28 | print(tokenizer.decode(input_ids[0]))
29 | if input_ids[0][-1] == 13:
30 | return True
31 |
32 | return False
33 |
34 |
35 | ctx = """A dialog, where User interacts with AI. AI is helpful, kind, obedient, honest, and knows its own limits.
36 | User: Hello, AI.
37 | AI: Hello! How can I assist you today?
38 | """
39 |
40 | while True:
41 | print('-' * 40)
42 | print(ctx.rstrip("\n"))
43 | prompt = input(f'User: ')
44 | if ctx != "":
45 | ctx = ctx + "User: " + prompt + "\n"
46 | else:
47 | ctx = prompt + "\n"
48 |
49 | ctx = (ctx[-1920:]) if len(ctx) >= 2048 else ctx
50 |
51 | if len(ctx.strip()) > 0:
52 | batch = tokenizer(ctx, return_tensors="pt")
53 | result = model.generate(batch["input_ids"].cpu(),
54 | do_sample=True,
55 | top_k=50,
56 | max_length=2048,
57 | top_p=0.95,
58 | temperature=1.0,
59 | stopping_criteria=StoppingCriteriaList([StoppingCriteriaSub()]),
60 | # repetition_penalty=1.17
61 | )
62 | decoded = tokenizer.decode(result[0])
63 | ctx = decoded + "\n"
64 |
--------------------------------------------------------------------------------
/hf-inference-cuda-example.py:
--------------------------------------------------------------------------------
1 | import llamahf
2 | import os
3 | from accelerate import infer_auto_device_map
4 |
5 | # # to save memory use bfloat16
6 | # import torch
7 | # torch.set_default_dtype(torch.bfloat16)
8 |
9 | MODEL = 'decapoda-research/llama-7b-hf'
10 | # MODEL = 'decapoda-research/llama-13b-hf'
11 | # MODEL = 'decapoda-research/llama-30b-hf'
12 | # MODEL = 'decapoda-research/llama-65b-hf'
13 |
14 | if os.path.exists('./trained'):
15 | MODEL = './trained'
16 |
17 | tokenizer = llamahf.LLaMATokenizer.from_pretrained(MODEL)
18 | model = llamahf.LLaMAForCausalLM.from_pretrained(MODEL, low_cpu_mem_usage=True, device_map="auto", offload_folder="./offload")
19 |
20 | # will use 6 Gb of GPU VRAM, others to CPU RAM
21 | device_map = infer_auto_device_map(model, max_memory={0: "6GiB", "cpu": "128GiB"})
22 | print(device_map)
23 |
24 | batch = tokenizer("The highest mountain in China is ", return_tensors="pt")
25 | print(tokenizer.decode(model.generate(batch["input_ids"].cuda(), do_sample=True, top_k=50, max_length=100, top_p=0.95, temperature=1.0)[0]))
26 |
--------------------------------------------------------------------------------
/hf-inference-example.py:
--------------------------------------------------------------------------------
1 | import llamahf
2 | import os
3 |
4 | # # to save memory use bfloat16
5 | # import torch
6 | # torch.set_default_dtype(torch.bfloat16)
7 |
8 | MODEL = 'decapoda-research/llama-7b-hf'
9 | # MODEL = 'decapoda-research/llama-13b-hf'
10 | # MODEL = 'decapoda-research/llama-30b-hf'
11 | # MODEL = 'decapoda-research/llama-65b-hf'
12 |
13 | if os.path.exists('./trained'):
14 | MODEL = './trained'
15 |
16 | tokenizer = llamahf.LLaMATokenizer.from_pretrained(MODEL)
17 | model = llamahf.LLaMAForCausalLM.from_pretrained(MODEL, low_cpu_mem_usage=True)
18 | model.to('cpu')
19 |
20 | batch = tokenizer("The highest mountain in China is ", return_tensors="pt")
21 | print(tokenizer.decode(model.generate(batch["input_ids"].cpu(), do_sample=True, top_k=50, max_length=100, top_p=0.95, temperature=1.0)[0]))
22 |
--------------------------------------------------------------------------------
/hf-training-example.py:
--------------------------------------------------------------------------------
1 | import llamahf
2 | import torch
3 | import pandas as pd
4 | from torch.utils.data import Dataset, random_split
5 | from transformers import TrainingArguments, Trainer
6 |
7 | # # to save memory use bfloat16 on cpu
8 | # torch.set_default_dtype(torch.bfloat16)
9 |
10 | MODEL = 'decapoda-research/llama-7b-hf'
11 | DATA_FILE_PATH = 'datasets/elon_musk_tweets.csv'
12 | OUTPUT_DIR = './trained'
13 |
14 | texts = pd.read_csv(DATA_FILE_PATH)['text']
15 |
16 | tokenizer = llamahf.LLaMATokenizer.from_pretrained(MODEL)
17 | model = llamahf.LLaMAForCausalLM.from_pretrained(MODEL).cpu()
18 |
19 |
20 | class TextDataset(Dataset):
21 | def __init__(self, txt_list, tokenizer, max_length):
22 | self.labels = []
23 | self.input_ids = []
24 | self.attn_masks = []
25 | for txt in txt_list:
26 | # encodings_dict = tokenizer(txt, truncation=True, max_length=max_length, padding="max_length")
27 | encodings_dict = tokenizer(txt, truncation=True, max_length=max_length, pad_to_max_length=False)
28 | self.input_ids.append(torch.tensor(encodings_dict['input_ids']))
29 | self.attn_masks.append(torch.tensor(encodings_dict['attention_mask']))
30 |
31 | def __len__(self): return len(self.input_ids)
32 |
33 | def __getitem__(self, idx): return self.input_ids[idx], self.attn_masks[idx]
34 |
35 |
36 | dataset = TextDataset(texts, tokenizer, max_length=max([len(tokenizer.encode(text)) for text in texts]))
37 | train_dataset, val_dataset = random_split(dataset, [int(0.9 * len(dataset)), len(dataset) - int(0.9 * len(dataset))])
38 |
39 | training_args = TrainingArguments(
40 | save_steps=5000,
41 | warmup_steps=10,
42 | logging_steps=100,
43 | weight_decay=0.05,
44 | num_train_epochs=1,
45 | logging_dir='./logs',
46 | output_dir=OUTPUT_DIR,
47 | no_cuda=True,
48 | per_device_eval_batch_size=1,
49 | per_device_train_batch_size=1)
50 |
51 | trainer = Trainer(model=model,
52 | args=training_args,
53 | eval_dataset=val_dataset,
54 | train_dataset=train_dataset,
55 | data_collator=lambda data: {'input_ids': torch.stack([f[0] for f in data]),
56 | 'attention_mask': torch.stack([f[1] for f in data]),
57 | 'labels': torch.stack([f[0] for f in data])})
58 |
59 | trainer.train()
60 | trainer.save_model()
61 | tokenizer.save_pretrained(OUTPUT_DIR)
62 | del trainer
63 |
64 | sample_outputs = model.generate(tokenizer('', return_tensors="pt").input_ids.cpu(),
65 | do_sample=True,
66 | top_k=50,
67 | max_length=300,
68 | top_p=0.95,
69 | temperature=1.0)
70 |
71 | print(tokenizer.decode(sample_outputs[0]))
72 |
--------------------------------------------------------------------------------
/llama/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) Meta Platforms, Inc. and affiliates.
2 | # This software may be used and distributed according to the terms of the GNU General Public License version 3.
3 |
4 | from .generation import LLaMA
5 | from .model import ModelArgs, Transformer
6 | from .tokenizer import Tokenizer
7 |
--------------------------------------------------------------------------------
/llama/generation.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) Meta Platforms, Inc. and affiliates.
2 | # This software may be used and distributed according to the terms of the GNU General Public License version 3.
3 |
4 | # Copyright by Steve Manuatu
5 | # https://github.com/venuatu
6 |
7 | # Copyright by Shawn Presser
8 | # https://github.com/shawwn
9 | # taken here
10 | # https://github.com/shawwn/llama/commit/40d99d329a5e38d85904d3a6519c54e6dd6ee9e1
11 |
12 | from typing import List
13 |
14 | import torch
15 | import traceback
16 |
17 | from llama.tokenizer import Tokenizer
18 | from llama.model import Transformer
19 | from tqdm import trange
20 |
21 |
22 | class LLaMA:
23 | def __init__(self, model: Transformer, tokenizer: Tokenizer):
24 | self.model = model
25 | self.tokenizer = tokenizer
26 |
27 | def generate(
28 | self,
29 | prompts: List[str],
30 | max_gen_len: int,
31 | temperature: float = 0.8,
32 | top_p: float = 0.95,
33 | top_k: int = 40,
34 | repetition_penalty: float = (1.0 / 0.85),
35 | sampler: str = 'top_k',
36 | ) -> List[str]:
37 | bsz = len(prompts)
38 | params = self.model.params
39 | assert bsz <= params.max_batch_size, (bsz, params.max_batch_size)
40 |
41 | count_newlines = prompts[0].count("\n")
42 |
43 | prompt_tokens = [self.tokenizer.encode(x, bos=True, eos=False) for x in prompts]
44 |
45 | min_prompt_size = min([len(t) for t in prompt_tokens])
46 | max_prompt_size = max([len(t) for t in prompt_tokens])
47 |
48 | total_len = min(params.max_seq_len, max_gen_len + max_prompt_size)
49 |
50 | tokens = torch.full((bsz, total_len), self.tokenizer.pad_id).long()
51 | for k, t in enumerate(prompt_tokens):
52 | tokens[k, : len(t)] = torch.tensor(t).long()
53 | tokens[k, -1] = self.tokenizer.eos_id
54 | input_text_mask = tokens != self.tokenizer.pad_id
55 | start_pos = min_prompt_size
56 | prev_pos = 0
57 | decoded = [None] * bsz
58 |
59 | for cur_pos in trange(start_pos, total_len, desc="forward"):
60 | logits = self.model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
61 |
62 | # repetition penalty from CTRL paper (https://arxiv.org/abs/1909.05858)
63 | if repetition_penalty != 1.0:
64 | logits_new = logits.clone()
65 | batch_size = len(tokens)
66 | for i in range(batch_size):
67 | for token in set(tokens[i].tolist()):
68 | # if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
69 | if logits[i, token] < 0:
70 | logits_new[i, token] = logits[i, token] * repetition_penalty
71 | else:
72 | logits_new[i, token] = logits[i, token] / repetition_penalty
73 | logits = logits_new
74 |
75 | if temperature > 0:
76 | probs = torch.softmax(logits / temperature, dim=-1)
77 | if sampler == 'top_k':
78 | next_token = sample_top_k(probs, top_p=top_p, top_k=top_k)
79 | else:
80 | next_token = sample_top_p(probs, top_p)
81 | else:
82 | next_token = torch.argmax(logits, dim=-1)
83 | next_token = next_token.reshape(-1).cpu()
84 | # only replace token if prompt has already been generated
85 | next_token = torch.where(
86 | input_text_mask[:, cur_pos], tokens[:, cur_pos], next_token
87 | )
88 | tokens[:, cur_pos] = next_token
89 | prev_pos = cur_pos
90 |
91 | print("-" * 30)
92 | for i, t in enumerate(tokens.tolist()):
93 | # i = cur_pos
94 | # t = next_token
95 | # cut to max gen len
96 | # t = t[: len(pr-ompt_tokens[i]) + max_gen_len]
97 | t = t[: min(cur_pos, len(prompt_tokens[i]) + max_gen_len)]
98 | # cut to eos tok if any
99 | try:
100 | t = t[: t.index(self.tokenizer.eos_id)]
101 | except ValueError:
102 | pass # traceback.print_exc()
103 | try:
104 | d = self.tokenizer.decode(t)
105 | print(d)
106 | decoded[i] = d
107 |
108 | result_count_newlines = d.count("\n")
109 | if result_count_newlines > count_newlines:
110 | return decoded
111 |
112 | except IndexError:
113 | traceback.print_exc()
114 | print(t)
115 | print("-" * 30)
116 | return decoded
117 |
118 |
119 | # default sampler
120 | def sample_top_p(probs, p):
121 | probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
122 | probs_sum = torch.cumsum(probs_sort, dim=-1)
123 | mask = probs_sum - probs_sort > p
124 | probs_sort[mask] = 0.0
125 | probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
126 | next_token = torch.multinomial(probs_sort, num_samples=1)
127 | next_token = torch.gather(probs_idx, -1, next_token)
128 | return next_token
129 |
130 |
131 | # sampler by Shawn
132 | def sample_top_k(probs, top_p=0.0, top_k=40):
133 | if top_k > 0:
134 | probs_sort, probs_idx = torch.topk(probs, top_k)
135 | else:
136 | probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
137 | if top_p > 0.0:
138 | probs_sum = torch.cumsum(probs_sort, dim=-1)
139 | mask = probs_sum - probs_sort > top_p
140 | probs_sort[mask] = 0.0
141 | probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
142 | next_token = torch.multinomial(probs_sort, num_samples=1)
143 | next_token = torch.gather(probs_idx, -1, next_token)
144 | return next_token
145 |
--------------------------------------------------------------------------------
/llama/model.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) Meta Platforms, Inc. and affiliates.
2 | # This software may be used and distributed according to the terms of the GNU General Public License version 3.
3 |
4 | # Copyright by Steve Manuatu
5 | # https://github.com/venuatu
6 |
7 | from typing import Optional, Tuple
8 | from dataclasses import dataclass
9 | import math
10 |
11 | import torch
12 | from torch import nn
13 | import torch.nn.functional as F
14 | from torch.nn.utils import skip_init
15 |
16 | from tqdm import tqdm
17 |
18 | @dataclass
19 | class ModelArgs:
20 | dim: int = 512
21 | n_layers: int = 8
22 | n_heads: int = 8
23 | vocab_size: int = -1 # defined later by tokenizer
24 | multiple_of: int = 256 # make SwiGLU hidden layer size multiple of large power of 2
25 | norm_eps: float = 1e-5
26 |
27 | max_batch_size: int = 32
28 | max_seq_len: int = 1024
29 |
30 |
31 | class RMSNorm(torch.nn.Module):
32 | def __init__(self, dim: int, eps: float = 1e-6):
33 | super().__init__()
34 | self.eps = eps
35 | self.weight = nn.Parameter(torch.ones(dim))
36 |
37 | def _norm(self, x):
38 | return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
39 |
40 | def forward(self, x):
41 | output = self._norm(x.float()).type_as(x)
42 | return output * self.weight
43 |
44 |
45 | def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
46 | freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
47 | t = torch.arange(end, device=freqs.device) # type: ignore
48 | freqs = torch.outer(t, freqs).float() # type: ignore
49 | freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
50 | return freqs_cis
51 |
52 |
53 | def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
54 | ndim = x.ndim
55 | assert 0 <= 1 < ndim
56 | assert freqs_cis.shape == (x.shape[1], x.shape[-1])
57 | shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
58 | return freqs_cis.view(*shape)
59 |
60 |
61 | def apply_rotary_emb(
62 | xq: torch.Tensor,
63 | xk: torch.Tensor,
64 | freqs_cis: torch.Tensor,
65 | ) -> Tuple[torch.Tensor, torch.Tensor]:
66 | xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
67 | xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
68 | freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
69 | xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
70 | xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
71 | return xq_out.type_as(xq), xk_out.type_as(xk)
72 |
73 |
74 | class Attention(nn.Module):
75 | def __init__(self, args: ModelArgs):
76 | super().__init__()
77 |
78 | self.n_local_heads = args.n_heads # // fs_init.get_model_parallel_world_size()
79 | self.head_dim = args.dim // args.n_heads
80 |
81 | self.wq = skip_init(nn.Linear,
82 | args.dim,
83 | args.n_heads * self.head_dim,
84 | bias=False,
85 | )
86 | self.wk = skip_init(nn.Linear,
87 | args.dim,
88 | args.n_heads * self.head_dim,
89 | bias=False,
90 | )
91 | self.wv = skip_init(nn.Linear,
92 | args.dim,
93 | args.n_heads * self.head_dim,
94 | bias=False,
95 | )
96 | self.wo = skip_init(nn.Linear,
97 | args.n_heads * self.head_dim,
98 | args.dim,
99 | bias=False,
100 | )
101 |
102 | self.cache_k = torch.zeros(
103 | (args.max_batch_size, args.max_seq_len, self.n_local_heads, self.head_dim)
104 | ).cuda()
105 | self.cache_v = torch.zeros(
106 | (args.max_batch_size, args.max_seq_len, self.n_local_heads, self.head_dim)
107 | ).cuda()
108 |
109 | def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]):
110 | bsz, seqlen, _ = x.shape
111 | xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
112 |
113 | xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
114 | xk = xk.view(bsz, seqlen, self.n_local_heads, self.head_dim)
115 | xv = xv.view(bsz, seqlen, self.n_local_heads, self.head_dim)
116 |
117 | xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
118 |
119 | self.cache_k = self.cache_k.to(xq)
120 | self.cache_v = self.cache_v.to(xq)
121 |
122 | self.cache_k[:bsz, start_pos : start_pos + seqlen] = xk
123 | self.cache_v[:bsz, start_pos : start_pos + seqlen] = xv
124 |
125 | keys = self.cache_k[:bsz, : start_pos + seqlen]
126 | values = self.cache_v[:bsz, : start_pos + seqlen]
127 |
128 | xq = xq.transpose(1, 2)
129 | keys = keys.transpose(1, 2)
130 | values = values.transpose(1, 2)
131 | scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)
132 | if mask is not None:
133 | scores = scores + mask # (bs, n_local_heads, slen, cache_len + slen)
134 | scores = F.softmax(scores.float(), dim=-1).type_as(xq)
135 | output = torch.matmul(scores, values) # (bs, n_local_heads, slen, head_dim)
136 | output = output.transpose(
137 | 1, 2
138 | ).contiguous().view(bsz, seqlen, -1)
139 |
140 | return self.wo(output)
141 |
142 |
143 | class FeedForward(nn.Module):
144 | def __init__(
145 | self,
146 | dim: int,
147 | hidden_dim: int,
148 | multiple_of: int,
149 | ):
150 | super().__init__()
151 | hidden_dim = int(2 * hidden_dim / 3)
152 | hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
153 |
154 | self.w1 = skip_init(nn.Linear,
155 | dim,
156 | hidden_dim,
157 | bias=False,
158 | )
159 | self.w2 = skip_init(nn.Linear,
160 | hidden_dim,
161 | dim,
162 | bias=False,
163 | )
164 | self.w3 = skip_init(nn.Linear,
165 | dim,
166 | hidden_dim,
167 | bias=False,
168 | )
169 |
170 | def forward(self, x):
171 | return self.w2(F.silu(self.w1(x)) * self.w3(x))
172 |
173 |
174 | class TransformerBlock(nn.Module):
175 | def __init__(self, layer_id: int, args: ModelArgs):
176 | super().__init__()
177 | self.n_heads = args.n_heads
178 | self.dim = args.dim
179 | self.head_dim = args.dim // args.n_heads
180 | self.attention = Attention(args)
181 | self.feed_forward = FeedForward(
182 | dim=args.dim, hidden_dim=4 * args.dim, multiple_of=args.multiple_of
183 | )
184 | self.layer_id = layer_id
185 | self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
186 | self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
187 |
188 | def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]):
189 | h = x + self.attention.forward(self.attention_norm(x), start_pos, freqs_cis, mask)
190 | out = h + self.feed_forward.forward(self.ffn_norm(h))
191 | return out
192 |
193 | # https://github.com/gmorenz/llama/commit/4daf7f1a2f2bb22208b5d464bc2a18511d54408d
194 | def move_parameters_to_gpu(module):
195 | if not hasattr(module, "saved"):
196 | module.saved = module._parameters.copy()
197 | for k, param in module.saved.items():
198 | if param is not None:
199 | module._parameters[k] = param.to("cuda", non_blocking=True)
200 | for child in module.children():
201 | move_parameters_to_gpu(child)
202 |
203 | def move_parameters_to_cpu(module):
204 | for k, param in module.saved.items():
205 | del module._parameters[k]
206 | module._parameters[k] = param
207 | for child in module.children():
208 | move_parameters_to_cpu(child)
209 |
210 |
211 | class Transformer(nn.Module):
212 | def __init__(self, params: ModelArgs):
213 | super().__init__()
214 | self.params = params
215 | self.vocab_size = params.vocab_size
216 | self.n_layers = params.n_layers
217 |
218 | self.tok_embeddings = skip_init(nn.Embedding,
219 | params.vocab_size,
220 | params.dim,
221 | )
222 |
223 | self.layers = torch.nn.ModuleList()
224 | for layer_id in range(params.n_layers):
225 | self.layers.append(TransformerBlock(layer_id, params))
226 |
227 | self.layer_locations = [None] * len(self.layers)
228 |
229 | self.norm = RMSNorm(params.dim, eps=params.norm_eps).cuda()
230 | self.output = skip_init(nn.Linear,
231 | params.dim,
232 | params.vocab_size,
233 | bias=False,
234 | ).cuda()
235 |
236 | self.freqs_cis = precompute_freqs_cis(
237 | self.params.dim // self.params.n_heads, self.params.max_seq_len * 2
238 | ).cuda()
239 |
240 | @torch.inference_mode()
241 | def forward(self, tokens: torch.Tensor, start_pos: int):
242 | use_gpu = True # start_pos == 0
243 |
244 | _bsz, seqlen = tokens.shape
245 | h = self.tok_embeddings(tokens)
246 | self.freqs_cis = self.freqs_cis
247 | freqs_cis = self.freqs_cis[start_pos : start_pos + seqlen]
248 | if use_gpu:
249 | h = h.cuda()
250 |
251 | mask = None
252 | if seqlen > 1:
253 | mask = torch.full(
254 | (1, 1, seqlen, seqlen), float("-inf"), device=tokens.device
255 | )
256 | mask = torch.triu(mask, diagonal=start_pos + 1).type_as(h)
257 |
258 | if use_gpu and mask is not None:
259 | mask = mask.cuda()
260 |
261 | for layer in tqdm(self.layers, desc="flayers", leave=True):
262 | if use_gpu:
263 | move_parameters_to_gpu(layer)
264 | h = layer(h, start_pos, freqs_cis, mask)
265 | if use_gpu:
266 | move_parameters_to_cpu(layer)
267 |
268 | h = self.norm(h)
269 | if use_gpu:
270 | del mask
271 | torch.cuda.empty_cache()
272 | output = self.output(h[:, -1, :]) # only compute last logits
273 | return output.float()
274 |
--------------------------------------------------------------------------------
/llama/tokenizer.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) Meta Platforms, Inc. and affiliates.
2 | # This software may be used and distributed according to the terms of the GNU General Public License version 3.
3 |
4 | from sentencepiece import SentencePieceProcessor
5 | from logging import getLogger
6 | from typing import List
7 | import os
8 |
9 |
10 | logger = getLogger()
11 |
12 |
13 | class Tokenizer:
14 | def __init__(self, model_path: str):
15 | # reload tokenizer
16 | assert os.path.isfile(model_path), model_path
17 | self.sp_model = SentencePieceProcessor(model_file=model_path)
18 | logger.info(f"Reloaded SentencePiece model from {model_path}")
19 |
20 | # BOS / EOS token IDs
21 | self.n_words: int = self.sp_model.vocab_size()
22 | self.bos_id: int = self.sp_model.bos_id()
23 | self.eos_id: int = self.sp_model.eos_id()
24 | self.pad_id: int = self.sp_model.pad_id()
25 | logger.info(
26 | f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}"
27 | )
28 | assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
29 |
30 | def encode(self, s: str, bos: bool, eos: bool) -> List[int]:
31 | assert type(s) is str
32 | t = self.sp_model.encode(s)
33 | if bos:
34 | t = [self.bos_id] + t
35 | if eos:
36 | t = t + [self.eos_id]
37 | return t
38 |
39 | def decode(self, t: List[int]) -> str:
40 | return self.sp_model.decode(t)
41 |
--------------------------------------------------------------------------------
/llamahf/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2022 EleutherAI and The HuggingFace Inc. team. All rights reserved.
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | from typing import TYPE_CHECKING
15 |
16 | from transformers.utils import (
17 | OptionalDependencyNotAvailable,
18 | _LazyModule,
19 | is_torch_available,
20 | is_sentencepiece_available,
21 | )
22 |
23 |
24 | _import_structure = {
25 | "configuration_llama": ["LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "LLaMAConfig"],
26 | }
27 |
28 | try:
29 | if not is_sentencepiece_available():
30 | raise OptionalDependencyNotAvailable()
31 | except OptionalDependencyNotAvailable:
32 | pass
33 | else:
34 | _import_structure["tokenization_llama"] = ["LLaMATokenizer"]
35 |
36 | try:
37 | if not is_torch_available():
38 | raise OptionalDependencyNotAvailable()
39 | except OptionalDependencyNotAvailable:
40 | pass
41 | else:
42 | _import_structure["modeling_llama"] = [
43 | "LLaMAForCausalLM",
44 | "LLaMAModel",
45 | "LLaMAPreTrainedModel",
46 | ]
47 |
48 |
49 | if TYPE_CHECKING:
50 | from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LLaMAConfig
51 |
52 | try:
53 | if not is_sentencepiece_available():
54 | raise OptionalDependencyNotAvailable()
55 | except OptionalDependencyNotAvailable:
56 | pass
57 | else:
58 | from .tokenization_llama import LLaMATokenizer
59 |
60 | try:
61 | if not is_torch_available():
62 | raise OptionalDependencyNotAvailable()
63 | except OptionalDependencyNotAvailable:
64 | pass
65 | else:
66 | from .modeling_llama import (
67 | LLaMAForCausalLM,
68 | LLaMAModel,
69 | LLaMAPreTrainedModel,
70 | )
71 |
72 |
73 | else:
74 | import sys
75 |
76 | sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
--------------------------------------------------------------------------------
/llamahf/configuration_llama.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2022 EleutherAI and the HuggingFace Inc. team. 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 | """ LLaMA model configuration"""
21 |
22 | from transformers.configuration_utils import PretrainedConfig
23 | from transformers.utils import logging
24 |
25 |
26 | logger = logging.get_logger(__name__)
27 |
28 | LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29 |
30 |
31 | class LLaMAConfig(PretrainedConfig):
32 | r"""
33 | This is the configuration class to store the configuration of a [`~LLaMAModel`]. It is used to instantiate an LLaMA
34 | model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35 | defaults will yield a similar configuration to that of the LLaMA-7B.
36 |
37 | Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38 | documentation from [`PretrainedConfig`] for more information.
39 |
40 |
41 | Args:
42 | vocab_size (`int`, *optional*, defaults to 32000):
43 | Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44 | `inputs_ids` passed when calling [`~LLaMAModel`] or [`~TFLLaMAModel`].
45 | hidden_size (`int`, *optional*, defaults to 4096):
46 | Dimension of the hidden representations.
47 | intermediate_size (`int`, *optional*, defaults to 11008):
48 | Dimension of the MLP representations.
49 | num_hidden_layers (`int`, *optional*, defaults to 32):
50 | Number of hidden layers in the Transformer encoder.
51 | num_attention_heads (`int`, *optional*, defaults to 32):
52 | Number of attention heads for each attention layer in the Transformer encoder.
53 | hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
54 | The non-linear activation function (function or string) in the decoder.
55 | initializer_range (`float`, *optional*, defaults to 0.02):
56 | The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
57 | rms_norm_eps (`float`, *optional*, defaults to 1e-12):
58 | The epsilon used by the rms normalization layers.
59 | use_cache (`bool`, *optional*, defaults to `True`):
60 | Whether or not the model should return the last key/values attentions (not used by all models). Only
61 | relevant if `config.is_decoder=True`.
62 | tie_word_embeddings(`bool`, *optional*, defaults to `False`):
63 | Whether to tie weight embeddings
64 | Example:
65 |
66 | ```python
67 | >>> from transformers import LLaMAModel, LLaMAConfig
68 |
69 | >>> # Initializing a LLaMA llama-7b style configuration
70 | >>> configuration = LLaMAConfig()
71 |
72 | >>> # Initializing a model from the llama-7b style configuration
73 | >>> model = LLaMAModel(configuration)
74 |
75 | >>> # Accessing the model configuration
76 | >>> configuration = model.config
77 | ```"""
78 | model_type = "llama"
79 |
80 | def __init__(
81 | self,
82 | vocab_size=32000,
83 | hidden_size=4096,
84 | intermediate_size=11008,
85 | num_hidden_layers=32,
86 | num_attention_heads=32,
87 | hidden_act="silu",
88 | initializer_range=0.02,
89 | rms_norm_eps=1e-6,
90 | use_cache=True,
91 | pad_token_id=-1,
92 | bos_token_id=0,
93 | eos_token_id=1,
94 | tie_word_embeddings=False,
95 | **kwargs,
96 | ):
97 | self.vocab_size = vocab_size
98 | self.hidden_size = hidden_size
99 | self.intermediate_size = intermediate_size
100 | self.num_hidden_layers = num_hidden_layers
101 | self.num_attention_heads = num_attention_heads
102 | self.hidden_act = hidden_act
103 | self.initializer_range = initializer_range
104 | self.rms_norm_eps = rms_norm_eps
105 | self.use_cache = use_cache
106 | super().__init__(
107 | pad_token_id=pad_token_id,
108 | bos_token_id=bos_token_id,
109 | eos_token_id=eos_token_id,
110 | tie_word_embeddings=tie_word_embeddings,
111 | **kwargs,
112 | )
--------------------------------------------------------------------------------
/llamahf/convert_llama_weights_to_hf.py:
--------------------------------------------------------------------------------
1 | # Copyright 2022 EleutherAI and The HuggingFace Inc. team. All rights reserved.
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | import argparse
15 | import json
16 | import os
17 | import shutil
18 |
19 | import torch
20 |
21 |
22 | """
23 | Sample usage:
24 |
25 | ```
26 | python src/transformers/models/llama/convert_llama_weights_to_hf.py \
27 | --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path
28 | ```
29 |
30 | Thereafter, models can be loaded via:
31 |
32 | ```
33 | tokenizer = transformers.LLaMATokenizer.from_pretrained("/output/path/tokenizer/")
34 |
35 | model = transformers.LLaMAForCausalLM.from_pretrained("/output/path/llama-7b/")
36 | ```
37 | """
38 |
39 | INTERMEDIATE_SIZE_MAP = {
40 | "7B": 11008,
41 | "13B": 13824,
42 | "30B": 17920,
43 | "65B": 22016,
44 | }
45 | NUM_SHARDS = {
46 | "7B": 1,
47 | "13B": 2,
48 | "30B": 4,
49 | "65B": 8,
50 | }
51 |
52 |
53 | def read_json(path):
54 | with open(path, "r") as f:
55 | return json.load(f)
56 |
57 |
58 | def write_json(text, path):
59 | with open(path, "w") as f:
60 | json.dump(text, f)
61 |
62 |
63 | def write_model(model_path, input_base_path, model_size):
64 | assert model_size in INTERMEDIATE_SIZE_MAP
65 | os.makedirs(model_path, exist_ok=True)
66 |
67 | params = read_json(os.path.join(input_base_path, "params.json"))
68 | num_shards = NUM_SHARDS[model_size]
69 | n_layers = params["n_layers"]
70 | n_heads = params["n_heads"]
71 | n_heads_per_shard = n_heads // num_shards
72 | dim = params["dim"]
73 | dims_per_head = dim // n_heads
74 | base = 10000.0
75 | inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
76 |
77 | # permute for sliced rotary
78 | def permute(w):
79 | return w.view(n_heads, dim // n_heads // 2, 2, dim).transpose(1, 2).reshape(dim, dim)
80 |
81 | # Load weights
82 | if model_size == "7B":
83 | # Not shared
84 | # (The sharded implementation would also work, but this is simpler.)
85 | loaded = torch.load(os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu")
86 | else:
87 | # Sharded
88 | loaded = [
89 | torch.load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"), map_location="cpu")
90 | for i in range(num_shards)
91 | ]
92 | param_count = 0
93 | index_dict = {"weight_map": {}}
94 | for layer_i in range(n_layers):
95 | filename = "pytorch_model-{:05d}-of-{:05d}.bin".format(
96 | layer_i + 1,
97 | n_layers + 1,
98 | )
99 | if model_size == "7B":
100 | # Unsharded
101 | state_dict = {
102 | f"model.layers.{layer_i}.self_attn.q_proj.weight": permute(
103 | loaded[f"layers.{layer_i}.attention.wq.weight"]
104 | ),
105 | f"model.layers.{layer_i}.self_attn.k_proj.weight": permute(
106 | loaded[f"layers.{layer_i}.attention.wk.weight"]
107 | ),
108 | f"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[f"layers.{layer_i}.attention.wv.weight"],
109 | f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[f"layers.{layer_i}.attention.wo.weight"],
110 | f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w1.weight"],
111 | f"model.layers.{layer_i}.mlp.down_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w2.weight"],
112 | f"model.layers.{layer_i}.mlp.up_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w3.weight"],
113 | f"model.layers.{layer_i}.input_layernorm.weight": loaded[f"layers.{layer_i}.attention_norm.weight"],
114 | f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[f"layers.{layer_i}.ffn_norm.weight"],
115 | }
116 | else:
117 | # Sharded
118 | state_dict = {
119 | f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][f"layers.{layer_i}.attention_norm.weight"],
120 | f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
121 | f"layers.{layer_i}.ffn_norm.weight"
122 | ],
123 | }
124 | state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
125 | torch.cat(
126 | [
127 | loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
128 | for i in range(num_shards)
129 | ],
130 | dim=0,
131 | ).reshape(dim, dim)
132 | )
133 | state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
134 | torch.cat(
135 | [
136 | loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(n_heads_per_shard, dims_per_head, dim)
137 | for i in range(num_shards)
138 | ],
139 | dim=0,
140 | ).reshape(dim, dim)
141 | )
142 | state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
143 | [
144 | loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(n_heads_per_shard, dims_per_head, dim)
145 | for i in range(num_shards)
146 | ],
147 | dim=0,
148 | ).reshape(dim, dim)
149 |
150 | state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
151 | [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(num_shards)], dim=1
152 | )
153 | state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat(
154 | [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(num_shards)], dim=0
155 | )
156 | state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat(
157 | [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(num_shards)], dim=1
158 | )
159 | state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat(
160 | [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(num_shards)], dim=0
161 | )
162 |
163 | state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
164 | for k, v in state_dict.items():
165 | index_dict["weight_map"][k] = filename
166 | param_count += v.numel()
167 | torch.save(state_dict, os.path.join(model_path, filename))
168 |
169 | filename = "pytorch_model-{:05d}-of-{:05d}.bin".format(
170 | n_layers + 1,
171 | n_layers + 1,
172 | )
173 | if model_size == "7B":
174 | # Unsharded
175 | state_dict = {
176 | "model.embed_tokens.weight": loaded["tok_embeddings.weight"],
177 | "model.norm.weight": loaded["norm.weight"],
178 | "lm_head.weight": loaded["output.weight"],
179 | }
180 | else:
181 | state_dict = {
182 | "model.norm.weight": loaded[0]["norm.weight"],
183 | "model.embed_tokens.weight": torch.cat(
184 | [loaded[i]["tok_embeddings.weight"] for i in range(num_shards)], dim=1
185 | ),
186 | "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(num_shards)], dim=0),
187 | }
188 |
189 | for k, v in state_dict.items():
190 | index_dict["weight_map"][k] = filename
191 | param_count += v.numel()
192 | torch.save(state_dict, os.path.join(model_path, filename))
193 |
194 | # Write configs
195 | index_dict["metadata"] = {"total_size": param_count * 2}
196 | write_json(index_dict, os.path.join(model_path, "pytorch_model.bin.index.json"))
197 | config_out = {
198 | "architectures": ["LLaMAForCausalLM"],
199 | "bos_token_id": 0,
200 | "eos_token_id": 1,
201 | "hidden_act": "silu",
202 | "hidden_size": params["dim"],
203 | "intermediate_size": INTERMEDIATE_SIZE_MAP[model_size],
204 | "initializer_range": 0.02,
205 | "max_sequence_length": 2048,
206 | "model_type": "llama",
207 | "num_attention_heads": params["n_heads"],
208 | "num_hidden_layers": params["n_layers"],
209 | "pad_token_id": -1,
210 | "rms_norm_eps": params["norm_eps"],
211 | "torch_dtype": "float16",
212 | "transformers_version": "4.27.0.dev0",
213 | "use_cache": True,
214 | "vocab_size": 32000,
215 | }
216 | write_json(
217 | config_out,
218 | os.path.join(model_path, "config.json"),
219 | )
220 | generation_config = {
221 | "_from_model_config": True,
222 | "bos_token_id": 0,
223 | "eos_token_id": 1,
224 | "pad_token_id": 0,
225 | "transformers_version": "4.27.0.dev0",
226 | }
227 | write_json(
228 | generation_config,
229 | os.path.join(model_path, "generation_config.json"),
230 | )
231 |
232 |
233 | def write_tokenizer(tokenizer_path, input_tokenizer_path):
234 | os.makedirs(tokenizer_path, exist_ok=True)
235 | write_json({}, os.path.join(tokenizer_path, "special_tokens_map.json"))
236 | write_json(
237 | {
238 | "bos_token": "",
239 | "eos_token": "",
240 | "model_max_length": int(1e30),
241 | "tokenizer_class": "LLaMATokenizer",
242 | "unk_token": "",
243 | },
244 | os.path.join(tokenizer_path, "tokenizer_config.json"),
245 | )
246 | shutil.copyfile(input_tokenizer_path, os.path.join(tokenizer_path, "tokenizer.model"))
247 |
248 |
249 | def main():
250 | parser = argparse.ArgumentParser()
251 | parser.add_argument(
252 | "--input_dir",
253 | help="Location of LLaMA weights, which contains tokenizer.model and model folders",
254 | )
255 | parser.add_argument(
256 | "--model_size",
257 | choices=["7B", "13B", "30B", "65B"],
258 | )
259 | parser.add_argument(
260 | "--output_dir",
261 | help="Location to write HF model and tokenizer",
262 | )
263 | args = parser.parse_args()
264 | write_model(
265 | model_path=os.path.join(args.output_dir, "llama-{}".format(args.model_size).lower()),
266 | input_base_path=os.path.join(args.input_dir, args.model_size),
267 | model_size=args.model_size,
268 | )
269 | write_tokenizer(
270 | tokenizer_path=os.path.join(args.output_dir, "tokenizer"),
271 | input_tokenizer_path=os.path.join(args.input_dir, "tokenizer.model"),
272 | )
273 |
274 |
275 | if __name__ == "__main__":
276 | main()
--------------------------------------------------------------------------------
/llamahf/modeling_llama.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2022 EleutherAI and the HuggingFace Inc. team. 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 LLaMA model."""
21 | import math
22 | from typing import List, Optional, Tuple, Union
23 |
24 | import torch
25 | import torch.utils.checkpoint
26 | from torch import nn
27 | from torch.nn import CrossEntropyLoss
28 |
29 | from transformers.activations import ACT2FN
30 | from transformers.modeling_outputs import (
31 | BaseModelOutputWithPast,
32 | CausalLMOutputWithPast,
33 | )
34 | from transformers.modeling_utils import PreTrainedModel
35 | from transformers.utils import (
36 | add_code_sample_docstrings,
37 | add_start_docstrings,
38 | add_start_docstrings_to_model_forward,
39 | logging,
40 | replace_return_docstrings,
41 | )
42 | from .configuration_llama import LLaMAConfig
43 |
44 |
45 | logger = logging.get_logger(__name__)
46 |
47 | _CHECKPOINT_FOR_DOC = "llama-7b"
48 | _CONFIG_FOR_DOC = "LLaMAConfig"
49 |
50 |
51 | def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0):
52 | """
53 | Make causal mask used for bi-directional self-attention.
54 | """
55 | bsz, tgt_len = input_ids_shape
56 | mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min))
57 | mask_cond = torch.arange(mask.size(-1))
58 | mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
59 | mask = mask.to(dtype)
60 |
61 | if past_key_values_length > 0:
62 | mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1)
63 | return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
64 |
65 |
66 | def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
67 | """
68 | Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
69 | """
70 | bsz, src_len = mask.size()
71 | tgt_len = tgt_len if tgt_len is not None else src_len
72 |
73 | expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
74 |
75 | inverted_mask = 1.0 - expanded_mask
76 |
77 | return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
78 |
79 |
80 | class RMSNorm(nn.Module):
81 | def __init__(self, hidden_size, eps=1e-6):
82 | """
83 | RMSNorm is equivalent to T5LayerNorm
84 | """
85 | super().__init__()
86 | self.weight = nn.Parameter(torch.ones(hidden_size))
87 | self.variance_epsilon = eps
88 |
89 | def forward(self, hidden_states):
90 | variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
91 | hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
92 |
93 | # convert into half-precision if necessary
94 | if self.weight.dtype in [torch.float16, torch.bfloat16]:
95 | hidden_states = hidden_states.to(self.weight.dtype)
96 |
97 | return self.weight * hidden_states
98 |
99 |
100 | class RotaryEmbedding(torch.nn.Module):
101 | def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
102 | super().__init__()
103 | inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
104 | self.register_buffer("inv_freq", inv_freq)
105 |
106 | # Build here to make `torch.jit.trace` work.
107 | self.max_seq_len_cached = max_position_embeddings
108 | t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
109 | freqs = torch.einsum("i,j->ij", t, self.inv_freq)
110 | # Different from paper, but it uses a different permutation in order to obtain the same calculation
111 | emb = torch.cat((freqs, freqs), dim=-1)
112 | self.cos_cached = emb.cos()[None, None, :, :]
113 | self.sin_cached = emb.sin()[None, None, :, :]
114 |
115 | def forward(self, x, seq_len=None):
116 | # x: [bs, num_attention_heads, seq_len, head_size]
117 | # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
118 | if seq_len > self.max_seq_len_cached:
119 | self.max_seq_len_cached = seq_len
120 | t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
121 | freqs = torch.einsum("i,j->ij", t, self.inv_freq)
122 | # Different from paper, but it uses a different permutation in order to obtain the same calculation
123 | emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
124 | self.cos_cached = emb.cos()[None, None, :, :].to(dtype=x.dtype)
125 | self.sin_cached = emb.sin()[None, None, :, :].to(dtype=x.dtype)
126 | return (
127 | self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype, device=x.device),
128 | self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype, device=x.device),
129 | )
130 |
131 |
132 | def rotate_half(x):
133 | """Rotates half the hidden dims of the input."""
134 | x1 = x[..., : x.shape[-1] // 2]
135 | x2 = x[..., x.shape[-1] // 2 :]
136 | return torch.cat((-x2, x1), dim=-1)
137 |
138 |
139 | def apply_rotary_pos_emb(q, k, cos, sin, offset: int = 0):
140 | cos = cos[..., offset : q.shape[-2] + offset, :]
141 | sin = sin[..., offset : q.shape[-2] + offset, :]
142 | q_embed = (q * cos) + (rotate_half(q) * sin)
143 | k_embed = (k * cos) + (rotate_half(k) * sin)
144 | return q_embed, k_embed
145 |
146 |
147 | class LLaMAMLP(nn.Module):
148 | def __init__(
149 | self,
150 | hidden_size: int,
151 | intermediate_size: int,
152 | hidden_act: str,
153 | ):
154 | super().__init__()
155 | self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
156 | self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
157 | self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
158 | self.act_fn = ACT2FN[hidden_act]
159 |
160 | def forward(self, x):
161 | return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
162 |
163 |
164 | class LLaMAAttention(nn.Module):
165 | """Multi-headed attention from 'Attention Is All You Need' paper"""
166 |
167 | def __init__(
168 | self,
169 | hidden_size: int,
170 | num_heads: int,
171 | ):
172 | super().__init__()
173 | self.hidden_size = hidden_size
174 | self.num_heads = num_heads
175 | self.head_dim = hidden_size // num_heads
176 |
177 | if (self.head_dim * num_heads) != self.hidden_size:
178 | raise ValueError(
179 | f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
180 | f" and `num_heads`: {num_heads})."
181 | )
182 | self.q_proj = nn.Linear(
183 | hidden_size,
184 | num_heads * self.head_dim,
185 | bias=False,
186 | )
187 | self.k_proj = nn.Linear(
188 | hidden_size,
189 | num_heads * self.head_dim,
190 | bias=False,
191 | )
192 | self.v_proj = nn.Linear(
193 | hidden_size,
194 | num_heads * self.head_dim,
195 | bias=False,
196 | )
197 | self.o_proj = nn.Linear(
198 | num_heads * self.head_dim,
199 | hidden_size,
200 | bias=False,
201 | )
202 | self.rotary_emb = RotaryEmbedding(self.head_dim)
203 |
204 | def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
205 | return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
206 |
207 | def forward(
208 | self,
209 | hidden_states: torch.Tensor,
210 | past_key_value: Optional[Tuple[torch.Tensor]] = None,
211 | attention_mask: Optional[torch.Tensor] = None,
212 | output_attentions: bool = False,
213 | ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
214 | """Input shape: Batch x Time x Channel"""
215 |
216 | bsz, q_len, _ = hidden_states.size()
217 |
218 | query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
219 | key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
220 | value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
221 |
222 | kv_seq_len = key_states.shape[-2]
223 | offset = 0
224 | if past_key_value is not None:
225 | offset = past_key_value[0].shape[-2]
226 | kv_seq_len += offset
227 | cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
228 | query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, offset=offset)
229 | # [bsz, nh, t, hd]
230 |
231 | if past_key_value is not None:
232 | # reuse k, v, self_attention
233 | key_states = torch.cat([past_key_value[0], key_states], dim=2)
234 | value_states = torch.cat([past_key_value[1], value_states], dim=2)
235 |
236 | past_key_value = (key_states, value_states)
237 |
238 | attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
239 |
240 | if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
241 | raise ValueError(
242 | f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
243 | f" {attn_weights.size()}"
244 | )
245 |
246 | if attention_mask is not None:
247 | if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
248 | raise ValueError(
249 | f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
250 | )
251 | attn_weights = attn_weights + attention_mask
252 | attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
253 |
254 | # upcast attention to fp32
255 | attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
256 | attn_output = torch.matmul(attn_weights, value_states)
257 |
258 | if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
259 | raise ValueError(
260 | f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
261 | f" {attn_output.size()}"
262 | )
263 |
264 | attn_output = attn_output.transpose(1, 2)
265 | attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
266 |
267 | attn_output = self.o_proj(attn_output)
268 |
269 | if not output_attentions:
270 | attn_weights = None
271 |
272 | return attn_output, attn_weights, past_key_value
273 |
274 |
275 | class LLaMADecoderLayer(nn.Module):
276 | def __init__(self, config: LLaMAConfig):
277 | super().__init__()
278 | self.hidden_size = config.hidden_size
279 | self.self_attn = LLaMAAttention(
280 | hidden_size=self.hidden_size,
281 | num_heads=config.num_attention_heads,
282 | )
283 | self.mlp = LLaMAMLP(
284 | hidden_size=self.hidden_size,
285 | intermediate_size=config.intermediate_size,
286 | hidden_act=config.hidden_act,
287 | )
288 | self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
289 | self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
290 |
291 | def forward(
292 | self,
293 | hidden_states: torch.Tensor,
294 | attention_mask: Optional[torch.Tensor] = None,
295 | output_attentions: Optional[bool] = False,
296 | use_cache: Optional[bool] = False,
297 | past_key_value: Optional[Tuple[torch.Tensor]] = None,
298 | ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
299 | """
300 | Args:
301 | hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
302 | attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
303 | `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
304 | output_attentions (`bool`, *optional*):
305 | Whether or not to return the attentions tensors of all attention layers. See `attentions` under
306 | returned tensors for more detail.
307 | use_cache (`bool`, *optional*):
308 | If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
309 | (see `past_key_values`).
310 | past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
311 | """
312 |
313 | residual = hidden_states
314 |
315 | hidden_states = self.input_layernorm(hidden_states)
316 |
317 | # Self Attention
318 | hidden_states, self_attn_weights, present_key_value = self.self_attn(
319 | hidden_states=hidden_states,
320 | past_key_value=past_key_value,
321 | attention_mask=attention_mask,
322 | output_attentions=output_attentions,
323 | )
324 | hidden_states = residual + hidden_states
325 |
326 | # Fully Connected
327 | residual = hidden_states
328 | hidden_states = self.post_attention_layernorm(hidden_states)
329 | hidden_states = self.mlp(hidden_states)
330 | hidden_states = residual + hidden_states
331 |
332 | outputs = (hidden_states,)
333 |
334 | if output_attentions:
335 | outputs += (self_attn_weights,)
336 |
337 | if use_cache:
338 | outputs += (present_key_value,)
339 |
340 | return outputs
341 |
342 |
343 | LLAMA_START_DOCSTRING = r"""
344 | This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
345 | library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
346 | etc.)
347 |
348 | This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
349 | Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
350 | and behavior.
351 |
352 | Parameters:
353 | config ([`LLaMAConfig`]):
354 | Model configuration class with all the parameters of the model. Initializing with a config file does not
355 | load the weights associated with the model, only the configuration. Check out the
356 | [`~PreTrainedModel.from_pretrained`] method to load the model weights.
357 | """
358 |
359 |
360 | @add_start_docstrings(
361 | "The bare OPT Model outputting raw hidden-states without any specific head on top.",
362 | LLAMA_START_DOCSTRING,
363 | )
364 | class LLaMAPreTrainedModel(PreTrainedModel):
365 | config_class = LLaMAConfig
366 | base_model_prefix = "model"
367 | supports_gradient_checkpointing = True
368 | _no_split_modules = ["LLaMADecoderLayer"]
369 | _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
370 |
371 | def _init_weights(self, module):
372 | std = self.config.initializer_range
373 | if isinstance(module, nn.Linear):
374 | module.weight.data.normal_(mean=0.0, std=std)
375 | if module.bias is not None:
376 | module.bias.data.zero_()
377 | elif isinstance(module, nn.Embedding):
378 | module.weight.data.normal_(mean=0.0, std=std)
379 | if module.padding_idx is not None:
380 | module.weight.data[module.padding_idx].zero_()
381 |
382 | def _set_gradient_checkpointing(self, module, value=False):
383 | if isinstance(module, (LLaMADecoderLayer)):
384 | module.gradient_checkpointing = value
385 |
386 |
387 | LLAMA_INPUTS_DOCSTRING = r"""
388 | Args:
389 | input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
390 | Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
391 | it.
392 |
393 | Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
394 | [`PreTrainedTokenizer.__call__`] for details.
395 |
396 | [What are input IDs?](../glossary#input-ids)
397 | attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
398 | Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
399 |
400 | - 1 for tokens that are **not masked**,
401 | - 0 for tokens that are **masked**.
402 |
403 | [What are attention masks?](../glossary#attention-mask)
404 |
405 | Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
406 | [`PreTrainedTokenizer.__call__`] for details.
407 |
408 | If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
409 | `past_key_values`).
410 |
411 | If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
412 | and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
413 | information on the default strategy.
414 |
415 | - 1 indicates the head is **not masked**,
416 | - 0 indicates the head is **masked**.
417 |
418 | past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
419 | Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
420 | `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
421 | `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
422 |
423 | Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
424 | blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
425 |
426 | If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
427 | don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
428 | `decoder_input_ids` of shape `(batch_size, sequence_length)`.
429 | inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
430 | Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
431 | is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
432 | model's internal embedding lookup matrix.
433 | use_cache (`bool`, *optional*):
434 | If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
435 | `past_key_values`).
436 | output_attentions (`bool`, *optional*):
437 | Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
438 | tensors for more detail.
439 | output_hidden_states (`bool`, *optional*):
440 | Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
441 | more detail.
442 | return_dict (`bool`, *optional*):
443 | Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
444 | """
445 |
446 |
447 | @add_start_docstrings(
448 | "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
449 | LLAMA_START_DOCSTRING,
450 | )
451 | class LLaMAModel(LLaMAPreTrainedModel):
452 | """
453 | Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LLaMADecoderLayer`]
454 |
455 | Args:
456 | config: LLaMAConfig
457 | """
458 |
459 | def __init__(self, config: LLaMAConfig):
460 | super().__init__(config)
461 | self.padding_idx = config.pad_token_id
462 | self.vocab_size = config.vocab_size
463 |
464 | self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
465 | self.layers = nn.ModuleList([LLaMADecoderLayer(config) for _ in range(config.num_hidden_layers)])
466 | self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
467 |
468 | self.gradient_checkpointing = False
469 | # Initialize weights and apply final processing
470 | self.post_init()
471 |
472 | def get_input_embeddings(self):
473 | return self.embed_tokens
474 |
475 | def set_input_embeddings(self, value):
476 | self.embed_tokens = value
477 |
478 | # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
479 | def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
480 | # create causal mask
481 | # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
482 | combined_attention_mask = None
483 | if input_shape[-1] > 1:
484 | combined_attention_mask = _make_causal_mask(
485 | input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length
486 | ).to(inputs_embeds.device)
487 |
488 | if attention_mask is not None:
489 | # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
490 | expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
491 | inputs_embeds.device
492 | )
493 | combined_attention_mask = (
494 | expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
495 | )
496 |
497 | return combined_attention_mask
498 |
499 | def forward(
500 | self,
501 | input_ids: torch.LongTensor = None,
502 | attention_mask: Optional[torch.Tensor] = None,
503 | past_key_values: Optional[List[torch.FloatTensor]] = None,
504 | inputs_embeds: Optional[torch.FloatTensor] = None,
505 | use_cache: Optional[bool] = None,
506 | output_attentions: Optional[bool] = None,
507 | output_hidden_states: Optional[bool] = None,
508 | return_dict: Optional[bool] = None,
509 | ) -> Union[Tuple, BaseModelOutputWithPast]:
510 | r"""
511 | Args:
512 | input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
513 | Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
514 | provide it.
515 |
516 | Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
517 | [`PreTrainedTokenizer.__call__`] for details.
518 |
519 | [What are input IDs?](../glossary#input-ids)
520 | attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
521 | Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
522 |
523 | - 1 for tokens that are **not masked**,
524 | - 0 for tokens that are **masked**.
525 |
526 | [What are attention masks?](../glossary#attention-mask)
527 | past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
528 | Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
529 | shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
530 |
531 | Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
532 | cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
533 |
534 | If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
535 | that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
536 | all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
537 | use_cache (`bool`, *optional*):
538 | If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
539 | `past_key_values`).
540 | inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
541 | Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
542 | This is useful if you want more control over how to convert `input_ids` indices into associated vectors
543 | than the model's internal embedding lookup matrix.
544 | output_attentions (`bool`, *optional*):
545 | Whether or not to return the attentions tensors of all attention layers. See `attentions` under
546 | returned tensors for more detail.
547 | output_hidden_states (`bool`, *optional*):
548 | Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
549 | for more detail.
550 | return_dict (`bool`, *optional*):
551 | Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
552 | """
553 | output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
554 | output_hidden_states = (
555 | output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
556 | )
557 | use_cache = use_cache if use_cache is not None else self.config.use_cache
558 |
559 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict
560 |
561 | # retrieve input_ids and inputs_embeds
562 | if input_ids is not None and inputs_embeds is not None:
563 | raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
564 | elif input_ids is not None:
565 | input_shape = input_ids.size()
566 | input_ids = input_ids.view(-1, input_shape[-1])
567 | elif inputs_embeds is not None:
568 | input_shape = inputs_embeds.size()[:-1]
569 | else:
570 | raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
571 |
572 | past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
573 |
574 | if inputs_embeds is None:
575 | inputs_embeds = self.embed_tokens(input_ids)
576 |
577 | # embed positions
578 | if attention_mask is None:
579 | attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device)
580 |
581 | attention_mask = self._prepare_decoder_attention_mask(
582 | attention_mask, input_shape, inputs_embeds, past_key_values_length
583 | )
584 |
585 | hidden_states = inputs_embeds
586 |
587 | if self.gradient_checkpointing and self.training:
588 | if use_cache:
589 | logger.warning_once(
590 | "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
591 | )
592 | use_cache = False
593 |
594 | # decoder layers
595 | all_hidden_states = () if output_hidden_states else None
596 | all_self_attns = () if output_attentions else None
597 | next_decoder_cache = () if use_cache else None
598 |
599 | for idx, decoder_layer in enumerate(self.layers):
600 | if output_hidden_states:
601 | all_hidden_states += (hidden_states,)
602 |
603 | past_key_value = past_key_values[idx] if past_key_values is not None else None
604 |
605 | if self.gradient_checkpointing and self.training:
606 |
607 | def create_custom_forward(module):
608 | def custom_forward(*inputs):
609 | # None for past_key_value
610 | return module(*inputs, output_attentions, None)
611 |
612 | return custom_forward
613 |
614 | layer_outputs = torch.utils.checkpoint.checkpoint(
615 | create_custom_forward(decoder_layer),
616 | hidden_states,
617 | attention_mask,
618 | None,
619 | )
620 | else:
621 | layer_outputs = decoder_layer(
622 | hidden_states,
623 | attention_mask=attention_mask,
624 | past_key_value=past_key_value,
625 | output_attentions=output_attentions,
626 | use_cache=use_cache,
627 | )
628 |
629 | hidden_states = layer_outputs[0]
630 |
631 | if use_cache:
632 | next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
633 |
634 | if output_attentions:
635 | all_self_attns += (layer_outputs[1],)
636 |
637 | hidden_states = self.norm(hidden_states)
638 |
639 | # add hidden states from the last decoder layer
640 | if output_hidden_states:
641 | all_hidden_states += (hidden_states,)
642 |
643 | next_cache = next_decoder_cache if use_cache else None
644 | if not return_dict:
645 | return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
646 | return BaseModelOutputWithPast(
647 | last_hidden_state=hidden_states,
648 | past_key_values=next_cache,
649 | hidden_states=all_hidden_states,
650 | attentions=all_self_attns,
651 | )
652 |
653 |
654 | class LLaMAForCausalLM(LLaMAPreTrainedModel):
655 | _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
656 |
657 | def __init__(self, config):
658 | super().__init__(config)
659 | self.model = LLaMAModel(config)
660 |
661 | self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
662 |
663 | # Initialize weights and apply final processing
664 | self.post_init()
665 |
666 | def get_input_embeddings(self):
667 | return self.model.embed_tokens
668 |
669 | def set_input_embeddings(self, value):
670 | self.model.embed_tokens = value
671 |
672 | def get_output_embeddings(self):
673 | return self.lm_head
674 |
675 | def set_output_embeddings(self, new_embeddings):
676 | self.lm_head = new_embeddings
677 |
678 | def set_decoder(self, decoder):
679 | self.model = decoder
680 |
681 | def get_decoder(self):
682 | return self.model
683 |
684 | @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
685 | def forward(
686 | self,
687 | input_ids: torch.LongTensor = None,
688 | attention_mask: Optional[torch.Tensor] = None,
689 | past_key_values: Optional[List[torch.FloatTensor]] = None,
690 | inputs_embeds: Optional[torch.FloatTensor] = None,
691 | labels: Optional[torch.LongTensor] = None,
692 | use_cache: Optional[bool] = None,
693 | output_attentions: Optional[bool] = None,
694 | output_hidden_states: Optional[bool] = None,
695 | return_dict: Optional[bool] = None,
696 | ) -> Union[Tuple, CausalLMOutputWithPast]:
697 | r"""
698 | Args:
699 | input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
700 | Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
701 | provide it.
702 |
703 | Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
704 | [`PreTrainedTokenizer.__call__`] for details.
705 |
706 | [What are input IDs?](../glossary#input-ids)
707 | attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
708 | Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
709 |
710 | - 1 for tokens that are **not masked**,
711 | - 0 for tokens that are **masked**.
712 |
713 | [What are attention masks?](../glossary#attention-mask)
714 | past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
715 | Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
716 | shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
717 | shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
718 | tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
719 |
720 | Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
721 | cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
722 |
723 | If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
724 | that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
725 | all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
726 | inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
727 | Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
728 | This is useful if you want more control over how to convert `input_ids` indices into associated vectors
729 | than the model's internal embedding lookup matrix.
730 | labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
731 | Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
732 | config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
733 | (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
734 | use_cache (`bool`, *optional*):
735 | If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
736 | (see `past_key_values`).
737 | output_attentions (`bool`, *optional*):
738 | Whether or not to return the attentions tensors of all attention layers. See `attentions` under
739 | returned tensors for more detail.
740 | output_hidden_states (`bool`, *optional*):
741 | Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
742 | for more detail.
743 | return_dict (`bool`, *optional*):
744 | Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
745 |
746 | Returns:
747 |
748 | Example:
749 |
750 | ```python
751 | >>> from transformers import AutoTokenizer, LLaMAForCausalLM
752 |
753 | >>> model = LLaMAForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
754 | >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
755 |
756 | >>> prompt = "Hey, are you consciours? Can you talk to me?"
757 | >>> inputs = tokenizer(prompt, return_tensors="pt")
758 |
759 | >>> # Generate
760 | >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
761 | >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
762 | "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
763 | ```"""
764 |
765 | output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
766 | output_hidden_states = (
767 | output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
768 | )
769 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict
770 |
771 | # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
772 | outputs = self.model(
773 | input_ids=input_ids,
774 | attention_mask=attention_mask,
775 | past_key_values=past_key_values,
776 | inputs_embeds=inputs_embeds,
777 | use_cache=use_cache,
778 | output_attentions=output_attentions,
779 | output_hidden_states=output_hidden_states,
780 | return_dict=return_dict,
781 | )
782 |
783 | hidden_states = outputs[0]
784 | logits = self.lm_head(hidden_states)
785 |
786 | loss = None
787 | if labels is not None:
788 | # Shift so that tokens < n predict n
789 | shift_logits = logits[..., :-1, :].contiguous()
790 | shift_labels = labels[..., 1:].contiguous()
791 | # Flatten the tokens
792 | loss_fct = CrossEntropyLoss()
793 | loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
794 |
795 | if not return_dict:
796 | output = (logits,) + outputs[1:]
797 | return (loss,) + output if loss is not None else output
798 |
799 | return CausalLMOutputWithPast(
800 | loss=loss,
801 | logits=logits,
802 | past_key_values=outputs.past_key_values,
803 | hidden_states=outputs.hidden_states,
804 | attentions=outputs.attentions,
805 | )
806 |
807 | def prepare_inputs_for_generation(
808 | self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
809 | ):
810 | if past_key_values:
811 | input_ids = input_ids[:, -1:]
812 |
813 | # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
814 | if inputs_embeds is not None and past_key_values is None:
815 | model_inputs = {"inputs_embeds": inputs_embeds}
816 | else:
817 | model_inputs = {"input_ids": input_ids}
818 |
819 | model_inputs.update(
820 | {
821 | "past_key_values": past_key_values,
822 | "use_cache": kwargs.get("use_cache"),
823 | "attention_mask": attention_mask,
824 | }
825 | )
826 | return model_inputs
827 |
828 | @staticmethod
829 | def _reorder_cache(past_key_values, beam_idx):
830 | reordered_past = ()
831 | for layer_past in past_key_values:
832 | reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
833 | return reordered_past
--------------------------------------------------------------------------------
/llamahf/tokenization_llama.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2022 EleutherAI and the HuggingFace Inc. team. 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 LLaMA."""
22 | import os
23 | import re
24 | from shutil import copyfile
25 | from typing import Any, Dict, List, Optional, Tuple
26 |
27 | import sentencepiece as spm
28 |
29 | from transformers.tokenization_utils import PreTrainedTokenizer
30 | from transformers.utils import logging
31 |
32 |
33 | logger = logging.get_logger(__name__)
34 |
35 | VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
36 |
37 | PRETRAINED_VOCAB_FILES_MAP = {}
38 |
39 |
40 | class LLaMATokenizer(PreTrainedTokenizer):
41 | """
42 | Construct a LLaMA tokenizer. Based on byte-level Byte-Pair-Encoding.
43 |
44 | Args:
45 | vocab_file (`str`):
46 | Path to the vocabulary file.
47 | """
48 |
49 | vocab_files_names = VOCAB_FILES_NAMES
50 | pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
51 | model_input_names = ["input_ids", "attention_mask"]
52 |
53 | def __init__(
54 | self,
55 | vocab_file,
56 | unk_token="",
57 | bos_token=" ⁇ ",
58 | eos_token="",
59 | sp_model_kwargs: Optional[Dict[str, Any]] = None,
60 | add_bos_token=True,
61 | add_eos_token=False,
62 | **kwargs,
63 | ):
64 | self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
65 | super().__init__(bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, **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.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
70 | self.sp_model.Load(vocab_file)
71 |
72 | """ Initialisation"""
73 |
74 | @property
75 | def vocab_size(self):
76 | """Returns vocab size"""
77 | return self.sp_model.get_piece_size()
78 |
79 | @property
80 | def bos_token_id(self) -> Optional[int]:
81 | return self.sp_model.bos_id()
82 |
83 | @property
84 | def eos_token_id(self) -> Optional[int]:
85 | return self.sp_model.eos_id()
86 |
87 | def get_vocab(self):
88 | """Returns vocab as a dict"""
89 | vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
90 | vocab.update(self.added_tokens_encoder)
91 | return vocab
92 |
93 | def _tokenize(self, text):
94 | """Returns a tokenized string."""
95 | return self.sp_model.encode(text, out_type=str)
96 |
97 | def _convert_token_to_id(self, token):
98 | """Converts a token (str) in an id using the vocab."""
99 | return self.sp_model.piece_to_id(token)
100 |
101 | def _convert_id_to_token(self, index):
102 | """Converts an index (integer) in a token (str) using the vocab."""
103 | token = self.sp_model.IdToPiece(index)
104 | return token
105 |
106 | def convert_tokens_to_string(self, tokens):
107 | """Converts a sequence of tokens (string) in a single string."""
108 | current_sub_tokens = []
109 | out_string = ""
110 | prev_is_special = False
111 | for token in tokens:
112 | # make sure that special tokens are not decoded using sentencepiece model
113 | if token in self.all_special_tokens:
114 | if not prev_is_special:
115 | out_string += " "
116 | out_string += self.sp_model.decode(current_sub_tokens) + token
117 | prev_is_special = True
118 | current_sub_tokens = []
119 | else:
120 | current_sub_tokens.append(token)
121 | prev_is_special = False
122 | out_string += self.sp_model.decode(current_sub_tokens)
123 | return out_string.strip()
124 |
125 | def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
126 | """
127 | Save the vocabulary and special tokens file to a directory.
128 |
129 | Args:
130 | save_directory (`str`):
131 | The directory in which to save the vocabulary.
132 |
133 | Returns:
134 | `Tuple(str)`: Paths to the files saved.
135 | """
136 | if not os.path.isdir(save_directory):
137 | logger.error(f"Vocabulary path ({save_directory}) should be a directory")
138 | return
139 | out_vocab_file = os.path.join(
140 | save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
141 | )
142 |
143 | if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
144 | copyfile(self.vocab_file, out_vocab_file)
145 | elif not os.path.isfile(self.vocab_file):
146 | with open(out_vocab_file, "wb") as fi:
147 | content_spiece_model = self.sp_model.serialized_model_proto()
148 | fi.write(content_spiece_model)
149 |
150 | return (out_vocab_file,)
151 |
152 | def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
153 | if self.add_bos_token:
154 | bos_token_ids = [self.bos_token_id]
155 | else:
156 | bos_token_ids = []
157 |
158 | output = bos_token_ids + token_ids_0
159 |
160 | if token_ids_1 is not None:
161 | output = output + token_ids_1
162 |
163 | if self.add_eos_token:
164 | output = output + [self.eos_token_id]
165 |
166 | return output
167 |
168 | def get_special_tokens_mask(
169 | self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
170 | ) -> List[int]:
171 | """
172 | Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
173 | special tokens using the tokenizer `prepare_for_model` method.
174 |
175 | Args:
176 | token_ids_0 (`List[int]`):
177 | List of IDs.
178 | token_ids_1 (`List[int]`, *optional*):
179 | Optional second list of IDs for sequence pairs.
180 | already_has_special_tokens (`bool`, *optional*, defaults to `False`):
181 | Whether or not the token list is already formatted with special tokens for the model.
182 |
183 | Returns:
184 | `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
185 | """
186 | if already_has_special_tokens:
187 | return super().get_special_tokens_mask(
188 | token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
189 | )
190 |
191 | if token_ids_1 is None:
192 | return [1] + ([0] * len(token_ids_0)) + [1]
193 | return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
194 |
195 | def create_token_type_ids_from_sequences(
196 | self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
197 | ) -> List[int]:
198 | """
199 | Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
200 | use of token type ids, therefore a list of zeros is returned.
201 |
202 | Args:
203 | token_ids_0 (`List[int]`):
204 | List of IDs.
205 | token_ids_1 (`List[int]`, *optional*):
206 | Optional second list of IDs for sequence pairs.
207 |
208 | Returns:
209 | `List[int]`: List of zeros.
210 | """
211 | eos = [self.eos_token_id]
212 |
213 | if token_ids_1 is None:
214 | return len(token_ids_0 + eos) * [0]
215 | return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
--------------------------------------------------------------------------------
/merge-weights.py:
--------------------------------------------------------------------------------
1 | # Original copyright by Jason Phang
2 | # https://github.com/zphang
3 | # Taken here
4 | # https://github.com/huggingface/transformers/pull/21955/commits/8978f28e6c44b083c0b190d3931902c2904c940a#diff-110a445233a8b15a0875998eeaf75cb8607b38a5daa736291dd058766879bbdd
5 |
6 | import argparse
7 | import json
8 | import os
9 | import shutil
10 | import torch
11 |
12 | """
13 | Sample usage:
14 | ```
15 | python merge_weights.py --input_dir D:\Downloads\LLaMA --model_size 13B
16 | ```
17 | """
18 |
19 | INTERMEDIATE_SIZE_MAP = {
20 | "7B": 11008,
21 | "13B": 13824,
22 | "30B": 17920,
23 | "65B": 22016,
24 | }
25 |
26 | NUM_SHARDS = {
27 | "7B": 1,
28 | "13B": 2,
29 | "30B": 4,
30 | "65B": 8,
31 | }
32 |
33 |
34 | def read_json(path):
35 | with open(path, "r") as f:
36 | return json.loads(f.read())
37 |
38 |
39 | def write_model(input_base_path, model_size):
40 | assert model_size in INTERMEDIATE_SIZE_MAP
41 |
42 | params = read_json(os.path.join(input_base_path, "params.json"))
43 | num_shards = NUM_SHARDS[model_size]
44 | n_layers = params["n_layers"]
45 | n_heads = params["n_heads"]
46 | n_heads_per_shard = n_heads // num_shards
47 | dim = params["dim"]
48 | dims_per_head = dim // n_heads
49 |
50 | # Load weights
51 | if model_size == "7B":
52 | loaded = torch.load(os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu")
53 | else:
54 | loaded = [
55 | torch.load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"), map_location="cpu")
56 | for i in range(num_shards)
57 | ]
58 |
59 | state_dict = {}
60 |
61 | for layer_i in range(n_layers):
62 | if model_size == "7B":
63 | state_dict |= {
64 | f"layers.{layer_i}.attention.wq.weight": loaded[
65 | f"layers.{layer_i}.attention.wq.weight"
66 | ],
67 | f"layers.{layer_i}.attention.wk.weight": loaded[
68 | f"layers.{layer_i}.attention.wk.weight"
69 | ],
70 | f"layers.{layer_i}.attention.wv.weight": loaded[
71 | f"layers.{layer_i}.attention.wv.weight"
72 | ],
73 | f"layers.{layer_i}.attention.wo.weight": loaded[
74 | f"layers.{layer_i}.attention.wo.weight"
75 | ],
76 | f"layers.{layer_i}.feed_forward.w1.weight": loaded[
77 | f"layers.{layer_i}.feed_forward.w1.weight"
78 | ],
79 | f"layers.{layer_i}.feed_forward.w2.weight": loaded[
80 | f"layers.{layer_i}.feed_forward.w2.weight"
81 | ],
82 | f"layers.{layer_i}.feed_forward.w3.weight": loaded[
83 | f"layers.{layer_i}.feed_forward.w3.weight"
84 | ],
85 | f"layers.{layer_i}.attention_norm.weight": loaded[
86 | f"layers.{layer_i}.attention_norm.weight"
87 | ],
88 | f"layers.{layer_i}.ffn_norm.weight": loaded[f"layers.{layer_i}.ffn_norm.weight"],
89 | }
90 | else:
91 | state_dict |= {
92 | f"layers.{layer_i}.attention_norm.weight": loaded[0][
93 | f"layers.{layer_i}.attention_norm.weight"
94 | ],
95 | f"layers.{layer_i}.ffn_norm.weight": loaded[0][f"layers.{layer_i}.ffn_norm.weight"],
96 | }
97 | state_dict[f"layers.{layer_i}.attention.wq.weight"] = torch.cat(
98 | [
99 | loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
100 | for i in range(num_shards)
101 | ],
102 | dim=0,
103 | ).reshape(dim, dim)
104 | state_dict[f"layers.{layer_i}.attention.wk.weight"] = torch.cat(
105 | [
106 | loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(n_heads_per_shard, dims_per_head, dim)
107 | for i in range(num_shards)
108 | ],
109 | dim=0,
110 | ).reshape(dim, dim)
111 | state_dict[f"layers.{layer_i}.attention.wv.weight"] = torch.cat(
112 | [
113 | loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(n_heads_per_shard, dims_per_head, dim)
114 | for i in range(num_shards)
115 | ],
116 | dim=0,
117 | ).reshape(dim, dim)
118 | state_dict[f"layers.{layer_i}.attention.wo.weight"] = torch.cat(
119 | [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(num_shards)], dim=1
120 | )
121 | state_dict[f"layers.{layer_i}.feed_forward.w1.weight"] = torch.cat(
122 | [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(num_shards)], dim=0
123 | )
124 | state_dict[f"layers.{layer_i}.feed_forward.w2.weight"] = torch.cat(
125 | [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(num_shards)], dim=1
126 | )
127 | state_dict[f"layers.{layer_i}.feed_forward.w3.weight"] = torch.cat(
128 | [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(num_shards)], dim=0
129 | )
130 |
131 | if model_size == "7B":
132 | state_dict |= {
133 | "tok_embeddings.weight": loaded["tok_embeddings.weight"],
134 | "norm.weight": loaded["norm.weight"],
135 | "output.weight": loaded["output.weight"],
136 | }
137 | else:
138 | state_dict |= {
139 | "norm.weight": loaded[0]["norm.weight"],
140 | "tok_embeddings.weight": torch.cat(
141 | [loaded[i]["tok_embeddings.weight"] for i in range(num_shards)], dim=1
142 | ),
143 | "output.weight": torch.cat([loaded[i]["output.weight"] for i in range(num_shards)], dim=0),
144 | }
145 |
146 | torch.save(state_dict, 'merged.pth')
147 |
148 |
149 | def main():
150 | parser = argparse.ArgumentParser()
151 | parser.add_argument(
152 | "--input_dir",
153 | help="Location of LLaMA weights, which contains tokenizer.model and model folders",
154 | )
155 | parser.add_argument(
156 | "--model_size",
157 | choices=["7B", "13B", "30B", "65B"],
158 | )
159 | args = parser.parse_args()
160 |
161 | write_model(
162 | input_base_path=os.path.join(args.input_dir, args.model_size),
163 | model_size=args.model_size,
164 | )
165 |
166 |
167 | if __name__ == "__main__":
168 | main()
169 |
--------------------------------------------------------------------------------
/model/.gitignore:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | torch
2 | fire
3 | sentencepiece
4 | tqdm
5 | transformers==4.27.1
6 | pyarrow
7 | pandas
8 | accelerate
9 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) Meta Platforms, Inc. and affiliates.
2 | # This software may be used and distributed according to the terms of the GNU General Public License version 3.
3 |
4 | from setuptools import setup, find_packages
5 |
6 | setup(name="llama", version="0.0.0", packages=find_packages())
7 |
--------------------------------------------------------------------------------
/tokenizer/.gitignore:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------