williamyangwentao commited on
Commit
14091f2
ยท
1 Parent(s): bd4066b

Upload folder using huggingface_hub

Browse files
.gitignore ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.npy
3
+ *.npz
4
+ *.pyc
5
+ *.pyd
6
+ *.so
7
+ *.ipynb
8
+ .ipynb_checkpoints
9
+ models/base_models/*
10
+ !models/base_models/.gitkeep
11
+ models/lora_weights/*
12
+ !models/lora_weights/.gitkeep
13
+ outputs/*
14
+ !outputs/.gitkeep
15
+ data/*
16
+ !data/.gitkeep
17
+ wandb/
18
+ flagged/
19
+ .DS_Store
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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
+ <program> Copyright (C) <year> <name of author>
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
+ <https://www.gnu.org/licenses/>.
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
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,12 +1,248 @@
1
  ---
2
- title: Law Llama
3
- emoji: ๐ŸŒ
4
- colorFrom: red
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 3.40.1
8
- app_file: app.py
9
- pinned: false
10
  ---
 
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Law_llama
3
+ app_file: webui.py
 
 
4
  sdk: gradio
5
+ sdk_version: 3.39.0
 
 
6
  ---
7
+ # LaWGPT๏ผšๅŸบไบŽไธญๆ–‡ๆณ•ๅพ‹็Ÿฅ่ฏ†็š„ๅคง่ฏญ่จ€ๆจกๅž‹
8
 
9
+ <p align="center">
10
+ <a href="assets/logo/lawgpt.jpeg">
11
+ <img src="./assets/logo/lawgpt.jpeg" width="80%" >
12
+ </a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <a href="https://github.com/pengxiao-song/LaWGPT/wiki"><img src="https://img.shields.io/badge/docs-Wiki-brightgreen"></a>
17
+ <a href="https://huggingface.co/entity303"><img src="https://img.shields.io/badge/Hugging%20Face-entity303-green"></a>
18
+ <a href=""><img src="https://img.shields.io/badge/version-beta1.1-blue"></a>
19
+ <a href=""><img src="https://img.shields.io/badge/os-Linux-9cf"></a>
20
+ <a href=""><img src="https://img.shields.io/github/last-commit/pengxiao-song/lawgpt"></a>
21
+ <a href="https://star-history.com/#pengxiao-song/LaWGPT&Timeline"><img src="https://img.shields.io/github/stars/pengxiao-song/lawgpt?color=yellow"></a>
22
+ <!-- <a href="https://www.lamda.nju.edu.cn/"><img src="https://img.shields.io/badge/support-NJU--LAMDA-9cf.svg"></a> -->
23
+ </p>
24
+
25
+ LaWGPT ๆ˜ฏไธ€็ณปๅˆ—ๅŸบไบŽไธญๆ–‡ๆณ•ๅพ‹็Ÿฅ่ฏ†็š„ๅผ€ๆบๅคง่ฏญ่จ€ๆจกๅž‹ใ€‚
26
+
27
+ ่ฏฅ็ณปๅˆ—ๆจกๅž‹ๅœจ้€š็”จไธญๆ–‡ๅŸบๅบงๆจกๅž‹๏ผˆๅฆ‚ Chinese-LLaMAใ€ChatGLM ็ญ‰๏ผ‰็š„ๅŸบ็ก€ไธŠๆ‰ฉๅ……ๆณ•ๅพ‹้ข†ๅŸŸไธ“ๆœ‰่ฏ่กจใ€**ๅคง่ง„ๆจกไธญๆ–‡ๆณ•ๅพ‹่ฏญๆ–™้ข„่ฎญ็ปƒ**๏ผŒๅขžๅผบไบ†ๅคงๆจกๅž‹ๅœจๆณ•ๅพ‹้ข†ๅŸŸ็š„ๅŸบ็ก€่ฏญไน‰็†่งฃ่ƒฝๅŠ›ใ€‚ๅœจๆญคๅŸบ็ก€ไธŠ๏ผŒ**ๆž„้€ ๆณ•ๅพ‹้ข†ๅŸŸๅฏน่ฏ้—ฎ็ญ”ๆ•ฐๆฎ้›†ใ€ไธญๅ›ฝๅธๆณ•่€ƒ่ฏ•ๆ•ฐๆฎ้›†่ฟ›่กŒๆŒ‡ไปค็ฒพ่ฐƒ**๏ผŒๆๅ‡ไบ†ๆจกๅž‹ๅฏนๆณ•ๅพ‹ๅ†…ๅฎน็š„็†่งฃๅ’Œๆ‰ง่กŒ่ƒฝๅŠ›ใ€‚
28
+
29
+ ่ฏฆ็ป†ๅ†…ๅฎน่ฏทๅ‚่€ƒ[ๆŠ€ๆœฏๆŠฅๅ‘Š]()ใ€‚
30
+
31
+ ---
32
+
33
+ ๆœฌ้กน็›ฎๆŒ็ปญๅผ€ๅฑ•๏ผŒๆณ•ๅพ‹้ข†ๅŸŸๆ•ฐๆฎ้›†ๅŠ็ณปๅˆ—ๆจกๅž‹ๅŽ็ปญ็›ธ็ปงๅผ€ๆบ๏ผŒๆ•ฌ่ฏทๅ…ณๆณจใ€‚
34
+
35
+ ## ๆ›ดๆ–ฐ
36
+
37
+ - ๐ŸŒŸ 2023/05/30๏ผšๅ…ฌๅผ€ๅ‘ๅธƒ
38
+ <a href="https://huggingface.co/entity303/lawgpt-lora-7b-v2"><img src="https://img.shields.io/badge/Model-LaWGPT--7B--beta1.1-yellow"></a>
39
+
40
+ - **LaWGPT-7B-beta1.1**๏ผšๆณ•ๅพ‹ๅฏน่ฏๆจกๅž‹๏ผŒๆž„้€  35w ้ซ˜่ดจ้‡ๆณ•ๅพ‹้—ฎ็ญ”ๆ•ฐๆฎ้›†ๅŸบไบŽ Chinese-alpaca-plus-7B ๆŒ‡ไปค็ฒพ่ฐƒ
41
+
42
+ - ๐Ÿ“ฃ 2023/05/26๏ผšๅผ€ๆ”พ [Discussions ่ฎจ่ฎบๅŒบ](https://github.com/pengxiao-song/LaWGPT/discussions)๏ผŒๆฌข่ฟŽๆœ‹ๅ‹ไปฌไบคๆตๆŽข่ฎจใ€ๆๅ‡บๆ„่งใ€ๅˆ†ไบซ่ง‚็‚น๏ผ
43
+
44
+ - ๐Ÿ› ๏ธ 2023/05/22๏ผš้กน็›ฎไธปๅˆ†ๆ”ฏ็ป“ๆž„่ฐƒๆ•ด๏ผŒ่ฏฆ่ง[้กน็›ฎ็ป“ๆž„](https://github.com/pengxiao-song/LaWGPT#้กน็›ฎ็ป“ๆž„)๏ผ›ๆ”ฏๆŒ[ๅ‘ฝไปค่กŒๆ‰น้‡ๆŽจ็†](https://github.com/pengxiao-song/LaWGPT/blob/main/scripts/infer.sh)
45
+
46
+ - ๐Ÿชด 2023/05/15๏ผšๅ‘ๅธƒ [ไธญๆ–‡ๆณ•ๅพ‹ๆ•ฐๆฎๆบๆฑ‡ๆ€ป๏ผˆAwesome Chinese Legal Resources๏ผ‰](https://github.com/pengxiao-song/awesome-chinese-legal-resources) ๅ’Œ [ๆณ•ๅพ‹้ข†ๅŸŸ่ฏ่กจ](https://github.com/pengxiao-song/LaWGPT/blob/main/resources/legal_vocab.txt)
47
+
48
+ - ๐ŸŒŸ 2023/05/13๏ผšๅ…ฌๅผ€ๅ‘ๅธƒ
49
+ <a href="https://huggingface.co/entity303/legal-lora-7b"><img src="https://img.shields.io/badge/Model-Legal--Base--7B-blue"></a>
50
+ <a href="https://huggingface.co/entity303/lawgpt-legal-lora-7b"><img src="https://img.shields.io/badge/Model-LaWGPT--7B--beta1.0-yellow"></a>
51
+
52
+ - **Legal-Base-7B**๏ผšๆณ•ๅพ‹ๅŸบๅบงๆจกๅž‹๏ผŒไฝฟ็”จ 50w ไธญๆ–‡่ฃๅˆคๆ–‡ไนฆๆ•ฐๆฎไบŒๆฌก้ข„่ฎญ็ปƒ
53
+
54
+ - **LaWGPT-7B-beta1.0**๏ผšๆณ•ๅพ‹ๅฏน่ฏๆจกๅž‹๏ผŒๆž„้€  30w ้ซ˜่ดจ้‡ๆณ•ๅพ‹้—ฎ็ญ”ๆ•ฐๆฎ้›†ๅŸบไบŽ Legal-Base-7B ๆŒ‡ไปค็ฒพ่ฐƒ
55
+
56
+ - ๐ŸŒŸ 2023/04/12๏ผšๅ†…้ƒจๆต‹่ฏ•
57
+ <a href="https://huggingface.co/entity303/lawgpt-lora-7b"><img src="https://img.shields.io/badge/Model-Lawgpt--7B--alpha-yellow"></a>
58
+ - **LaWGPT-7B-alpha**๏ผšๅœจ Chinese-LLaMA-7B ็š„ๅŸบ็ก€ไธŠ็›ดๆŽฅๆž„้€  30w ๆณ•ๅพ‹้—ฎ็ญ”ๆ•ฐๆฎ้›†ๆŒ‡ไปค็ฒพ่ฐƒ
59
+
60
+ ## ๅฟซ้€Ÿๅผ€ๅง‹
61
+
62
+ 1. ๅ‡†ๅค‡ไปฃ็ ๏ผŒๅˆ›ๅปบ็Žฏๅขƒ
63
+
64
+ ```bash
65
+ # ไธ‹่ฝฝไปฃ็ 
66
+ git clone [email protected]:pengxiao-song/LaWGPT.git
67
+ cd LaWGPT
68
+
69
+ # ๅˆ›ๅปบ็Žฏๅขƒ
70
+ conda create -n lawgpt python=3.10 -y
71
+ conda activate lawgpt
72
+ pip install -r requirements.txt
73
+ ```
74
+ 2. **ๅฏๅŠจ web ui๏ผˆๅฏ้€‰๏ผŒๆ˜“ไบŽ่ฐƒ่Š‚ๅ‚ๆ•ฐ๏ผ‰**
75
+
76
+ - ้ฆ–ๅ…ˆ๏ผŒๆ‰ง่กŒๆœๅŠกๅฏๅŠจ่„šๆœฌ๏ผš`bash scripts/webui.sh`
77
+
78
+ - ๅ…ถๆฌก๏ผŒ่ฎฟ้—ฎ http://127.0.0.1:7860 ๏ผš
79
+
80
+ <p align="center">
81
+ <img style="border-radius: 50%; box-shadow: 0 0 10px rgba(0,0,0,0.5); width: 80%;", src="./assets/demo/example-03.jpeg">
82
+ </p>
83
+
84
+ 3. **ๅ‘ฝไปค่กŒๆŽจ็†๏ผˆๅฏ้€‰๏ผŒๆ”ฏๆŒๆ‰น้‡ๆต‹่ฏ•๏ผ‰**
85
+
86
+ - ้ฆ–ๅ…ˆ๏ผŒๅ‚่€ƒ `resources/example_infer_data.json` ๆ–‡ไปถๅ†…ๅฎนๆž„้€ ๆต‹่ฏ•ๆ ทๆœฌ้›†๏ผ›
87
+
88
+ - ๅ…ถๆฌก๏ผŒๆ‰ง่กŒๆŽจ็†่„šๆœฌ๏ผš`bash scripts/infer.sh`ใ€‚ๅ…ถไธญ `--infer_data_path` ๅ‚ๆ•ฐไธบๆต‹่ฏ•ๆ ทๆœฌ้›†่ทฏๅพ„๏ผŒๅฆ‚ๆžœไธบ็ฉบๆˆ–่€…่ทฏๅพ„ๅ‡บ้”™๏ผŒๅˆ™ไปฅไบคไบ’ๆจกๅผ่ฟ่กŒใ€‚
89
+
90
+ ๆณจๆ„๏ผŒไปฅไธŠๆญฅ้ชค็š„้ป˜่ฎคๆจกๅž‹ไธบ LaWGPT-7B-alpha ๏ผŒๅฆ‚ๆžœๆ‚จๆƒณไฝฟ็”จ LaWGPT-7B-beta1.0 ๆจกๅž‹๏ผš
91
+
92
+ - ็”ฑไบŽ [LLaMA](https://github.com/facebookresearch/llama) ๅ’Œ [Chinese-LLaMA](https://github.com/ymcui/Chinese-LLaMA-Alpaca) ๅ‡ๆœชๅผ€ๆบๆจกๅž‹ๆƒ้‡ใ€‚ๆ นๆฎ็›ธๅบ”ๅผ€ๆบ่ฎธๅฏ๏ผŒ**ๆœฌ้กน็›ฎๅช่ƒฝๅ‘ๅธƒ LoRA ๆƒ้‡**๏ผŒๆ— ๆณ•ๅ‘ๅธƒๅฎŒๆ•ด็š„ๆจกๅž‹ๆƒ้‡๏ผŒ่ฏทๅ„ไฝ่ฐ…๏ฟฝ๏ฟฝใ€‚
93
+
94
+ - ๆœฌ้กน็›ฎ็ป™ๅ‡บ[ๅˆๅนถๆ–นๅผ](https://github.com/pengxiao-song/LaWGPT/wiki/%E6%A8%A1%E5%9E%8B%E5%90%88%E5%B9%B6)๏ผŒ่ฏทๅ„ไฝ่Žทๅ–ๅŽŸ็‰ˆๆƒ้‡ๅŽ่‡ช่กŒ้‡ๆž„ๆจกๅž‹ใ€‚
95
+
96
+
97
+ ## ้กน็›ฎ็ป“ๆž„
98
+
99
+ ```bash
100
+ LaWGPT
101
+ โ”œโ”€โ”€ assets # ้™ๆ€่ต„ๆบ
102
+ โ”œโ”€โ”€ resources # ้กน็›ฎ่ต„ๆบ
103
+ โ”œโ”€โ”€ models # ๅŸบๅบงๆจกๅž‹ๅŠ lora ๆƒ้‡
104
+ โ”‚ โ”œโ”€โ”€ base_models
105
+ โ”‚ โ””โ”€โ”€ lora_weights
106
+ โ”œโ”€โ”€ outputs # ๆŒ‡ไปคๅพฎ่ฐƒ็š„่พ“ๅ‡บๆƒ้‡
107
+ โ”œโ”€โ”€ data # ๅฎž้ชŒๆ•ฐๆฎ
108
+ โ”œโ”€โ”€ scripts # ่„šๆœฌ็›ฎๅฝ•
109
+ โ”‚ โ”œโ”€โ”€ finetune.sh # ๆŒ‡ไปคๅพฎ่ฐƒ่„šๆœฌ
110
+ โ”‚ โ””โ”€โ”€ webui.sh # ๅฏๅŠจๆœๅŠก่„šๆœฌ
111
+ โ”œโ”€โ”€ templates # prompt ๆจกๆฟ
112
+ โ”œโ”€โ”€ tools # ๅทฅๅ…ทๅŒ…
113
+ โ”œโ”€โ”€ utils
114
+ โ”œโ”€โ”€ train_clm.py # ไบŒๆฌก่ฎญ็ปƒ
115
+ โ”œโ”€โ”€ finetune.py # ๆŒ‡ไปคๅพฎ่ฐƒ
116
+ โ”œโ”€โ”€ webui.py # ๅฏๅŠจๆœๅŠก
117
+ โ”œโ”€โ”€ README.md
118
+ โ””โ”€โ”€ requirements.txt
119
+ ```
120
+
121
+
122
+ ## ๆ•ฐๆฎๆž„ๅปบ
123
+
124
+ ๆœฌ้กน็›ฎๅŸบไบŽไธญๆ–‡่ฃๅˆคๆ–‡ไนฆ็ฝ‘ๅ…ฌๅผ€ๆณ•ๅพ‹ๆ–‡ไนฆๆ•ฐๆฎใ€ๅธๆณ•่€ƒ่ฏ•ๆ•ฐๆฎ็ญ‰ๆ•ฐๆฎ้›†ๅฑ•ๅผ€๏ผŒ่ฏฆๆƒ…ๅ‚่€ƒ[ไธญๆ–‡ๆณ•ๅพ‹ๆ•ฐๆฎๆบๆฑ‡ๆ€ป๏ผˆAwesome Chinese Legal Resources๏ผ‰](https://github.com/pengxiao-song/awesome-chinese-legal-resources)ใ€‚
125
+
126
+ 1. ๅˆ็บงๆ•ฐๆฎ็”Ÿๆˆ๏ผšๆ นๆฎ [Stanford_alpaca](https://github.com/tatsu-lab/stanford_alpaca#data-generation-process) ๅ’Œ [self-instruct](https://github.com/yizhongw/self-instruct) ๆ–นๅผ็”Ÿๆˆๅฏน่ฏ้—ฎ็ญ”ๆ•ฐๆฎ
127
+ 2. ็Ÿฅ่ฏ†ๅผ•ๅฏผ็š„ๆ•ฐๆฎ็”Ÿๆˆ๏ผš้€š่ฟ‡ Knowledge-based Self-Instruct ๆ–นๅผๅŸบไบŽไธญๆ–‡ๆณ•ๅพ‹็ป“ๆž„ๅŒ–็Ÿฅ่ฏ†็”Ÿๆˆๆ•ฐๆฎใ€‚
128
+ 3. ๅผ•ๅ…ฅ ChatGPT ๆธ…ๆด—ๆ•ฐๆฎ๏ผŒ่พ…ๅŠฉๆž„้€ ้ซ˜่ดจ้‡ๆ•ฐๆฎ้›†ใ€‚
129
+
130
+ ## ๆจกๅž‹่ฎญ็ปƒ
131
+
132
+ LawGPT ็ณปๅˆ—ๆจกๅž‹็š„่ฎญ็ปƒ่ฟ‡็จ‹ๅˆ†ไธบไธคไธช้˜ถๆฎต๏ผš
133
+
134
+ 1. ็ฌฌไธ€้˜ถๆฎต๏ผšๆ‰ฉๅ……ๆณ•ๅพ‹้ข†ๅŸŸ่ฏ่กจ๏ผŒๅœจๅคง่ง„ๆจกๆณ•ๅพ‹ๆ–‡ไนฆๅŠๆณ•ๅ…ธๆ•ฐๆฎไธŠ้ข„่ฎญ็ปƒ Chinese-LLaMA
135
+ 2. ็ฌฌไบŒ้˜ถๆฎต๏ผšๆž„้€ ๆณ•ๅพ‹้ข†ๅŸŸๅฏน่ฏ้—ฎ็ญ”ๆ•ฐๆฎ้›†๏ผŒๅœจ้ข„่ฎญ็ปƒๆจกๅž‹ๅŸบ็ก€ไธŠๆŒ‡ไปค็ฒพ่ฐƒ
136
+
137
+ ### ไบŒๆฌก่ฎญ็ปƒๆต็จ‹
138
+
139
+ 1. ๅ‚่€ƒ `resources/example_instruction_train.json` ๆž„้€ ไบŒๆฌก่ฎญ็ปƒๆ•ฐๆฎ้›†
140
+ 2. ่ฟ่กŒ `scripts/train_clm.sh`
141
+
142
+ ### ๆŒ‡ไปค็ฒพ่ฐƒๆญฅ้ชค
143
+
144
+ 1. ๅ‚่€ƒ `resources/example_instruction_tune.json` ๆž„้€ ๆŒ‡ไปคๅพฎ่ฐƒๆ•ฐๆฎ้›†
145
+ 2. ่ฟ่กŒ `scripts/finetune.sh`
146
+
147
+ ### ่ฎก็ฎ—่ต„ๆบ
148
+
149
+ 8 ๅผ  Tesla V100-SXM2-32GB ๏ผšไบŒๆฌก่ฎญ็ปƒ้˜ถๆฎต่€—ๆ—ถ็บฆ 24h / epoch๏ผŒๅพฎ่ฐƒ้˜ถๆฎต่€—ๆ—ถ็บฆ 12h / epoch
150
+
151
+ ## ๆจกๅž‹่ฏ„ไผฐ
152
+
153
+ ### ่พ“ๅ‡บ็คบไพ‹
154
+
155
+ <details><summary>้—ฎ้ข˜๏ผš้…’้ฉพๆ’žไบบๆ€Žไนˆๅˆคๅˆ‘๏ผŸ</summary>
156
+
157
+ ![](assets/demo/demo07.jpeg)
158
+
159
+ </details>
160
+
161
+ <details><summary>้—ฎ้ข˜๏ผš่ฏท็ป™ๅ‡บๅˆคๅ†ณๆ„่งใ€‚</summary>
162
+
163
+ ![](assets/demo/example-05.jpeg)
164
+
165
+ </details>
166
+
167
+ <details><summary>้—ฎ้ข˜๏ผš่ฏทไป‹็ป่ตŒๅš็ฝช็š„ๅฎšไน‰ใ€‚</summary>
168
+
169
+ ![](assets/demo/example-06.jpeg)
170
+
171
+ </details>
172
+
173
+ <details><summary>้—ฎ้ข˜๏ผš่ฏท้—ฎๅŠ ็ญๅทฅ่ต„ๆ€Žไนˆ็ฎ—๏ผŸ</summary>
174
+
175
+ ![](assets/demo/example-04.jpeg)
176
+
177
+ </details>
178
+
179
+ <details><summary>้—ฎ้ข˜๏ผšๆฐ‘้—ดๅ€Ÿ่ดทๅ—ๅ›ฝๅฎถไฟๆŠค็š„ๅˆๆณ•ๅˆฉๆฏๆ˜ฏๅคšๅฐ‘?</summary>
180
+
181
+ ![](assets/demo/example-02.jpeg)
182
+
183
+ </details>
184
+
185
+ <details><summary>้—ฎ้ข˜๏ผšๆฌ ไบ†ไฟก็”จๅก็š„้’ฑ่ฟ˜ไธไธŠ่ฆๅ็‰ขๅ—๏ผŸ</summary>
186
+
187
+ ![](assets/demo/example-01.jpeg)
188
+
189
+ </details>
190
+
191
+ <details><summary>้—ฎ้ข˜๏ผšไฝ ่ƒฝๅฆๅ†™ไธ€ๆฎตๆŠขๅŠซ็ฝช็ฝชๅ็š„ๆกˆๆƒ…ๆ่ฟฐ๏ผŸ</summary>
192
+
193
+ ![](assets/demo/example-03.jpeg)
194
+
195
+ </details>
196
+
197
+
198
+ ### ๅฑ€้™ๆ€ง
199
+
200
+ ็”ฑไบŽ่ฎก็ฎ—่ต„ๆบใ€ๆ•ฐๆฎ่ง„ๆจก็ญ‰ๅ› ็ด ้™ๅˆถ๏ผŒๅฝ“ๅ‰้˜ถๆฎต LawGPT ๅญ˜ๅœจ่ฏธๅคšๅฑ€้™ๆ€ง๏ผš
201
+
202
+ 1. ๆ•ฐๆฎ่ต„ๆบๆœ‰้™ใ€ๆจกๅž‹ๅฎน้‡่พƒๅฐ๏ผŒๅฏผ่‡ดๅ…ถ็›ธๅฏน่พƒๅผฑ็š„ๆจกๅž‹่ฎฐๅฟ†ๅ’Œ่ฏญ่จ€่ƒฝๅŠ›ใ€‚ๅ› ๆญค๏ผŒๅœจ้ขๅฏนไบ‹ๅฎžๆ€ง็Ÿฅ่ฏ†ไปปๅŠกๆ—ถ๏ผŒๅฏ่ƒฝไผš็”Ÿๆˆไธๆญฃ็กฎ็š„็ป“ๆžœใ€‚
203
+ 2. ่ฏฅ็ณปๅˆ—ๆจกๅž‹ๅช่ฟ›่กŒไบ†ๅˆๆญฅ็š„ไบบ็ฑปๆ„ๅ›พๅฏน้ฝใ€‚ๅ› ๆญค๏ผŒๅฏ่ƒฝไบง็”Ÿไธๅฏ้ข„ๆต‹็š„ๆœ‰ๅฎณๅ†…ๅฎนไปฅๅŠไธ็ฌฆๅˆไบบ็ฑปๅๅฅฝๅ’Œไปทๅ€ผ่ง‚็š„ๅ†…ๅฎนใ€‚
204
+ 3. ่‡ชๆˆ‘่ฎค็Ÿฅ่ƒฝๅŠ›ๅญ˜ๅœจ้—ฎ้ข˜๏ผŒไธญๆ–‡็†่งฃ่ƒฝๅŠ›ๆœ‰ๅพ…ๅขžๅผบใ€‚
205
+
206
+ ่ฏท่ฏธๅ›ๅœจไฝฟ็”จๅ‰ไบ†่งฃไธŠ่ฟฐ้—ฎ้ข˜๏ผŒไปฅๅ…้€ ๆˆ่ฏฏ่งฃๅ’Œไธๅฟ…่ฆ็š„้บป็ƒฆใ€‚
207
+
208
+
209
+ ## ๅไฝœ่€…
210
+
211
+ ๅฆ‚ไธ‹ๅ„ไฝๅˆไฝœๅผ€ๅฑ•๏ผˆๆŒ‰ๅญ—ๆฏๅบๆŽ’ๅˆ—๏ผ‰๏ผš[@cainiao](https://github.com/herobrine19)ใ€[@njuyxw](https://github.com/njuyxw)ใ€[@pengxiao-song](https://github.com/pengxiao-song)
212
+
213
+
214
+ ## ๅ…่ดฃๅฃฐๆ˜Ž
215
+
216
+ ่ฏทๅ„ไฝไธฅๆ ผ้ตๅฎˆๅฆ‚ไธ‹็บฆๅฎš๏ผš
217
+
218
+ 1. ๆœฌ้กน็›ฎไปปไฝ•่ต„ๆบ**ไป…ไพ›ๅญฆๆœฏ็ ”็ฉถไฝฟ็”จ๏ผŒไธฅ็ฆไปปไฝ•ๅ•†ไธš็”จ้€”**ใ€‚
219
+ 2. ๆจกๅž‹่พ“ๅ‡บๅ—ๅคš็งไธ็กฎๅฎšๆ€งๅ› ็ด ๅฝฑๅ“๏ผŒๆœฌ้กน็›ฎๅฝ“ๅ‰ๆ— ๆณ•ไฟ่ฏๅ…ถๅ‡†็กฎๆ€ง๏ผŒ**ไธฅ็ฆ็”จไบŽ็œŸๅฎžๆณ•ๅพ‹ๅœบๆ™ฏ**ใ€‚
220
+ 3. ๆœฌ้กน็›ฎไธๆ‰ฟๆ‹…ไปปไฝ•ๆณ•ๅพ‹่ดฃไปป๏ผŒไบฆไธๅฏนๅ› ไฝฟ็”จ็›ธๅ…ณ่ต„ๆบๅ’Œ่พ“ๅ‡บ็ป“ๆžœ่€Œๅฏ่ƒฝไบง็”Ÿ็š„ไปปไฝ•ๆŸๅคฑๆ‰ฟๆ‹…่ดฃไปปใ€‚
221
+
222
+
223
+ ## ้—ฎ้ข˜ๅ้ฆˆ
224
+
225
+ ๅฆ‚ๆœ‰้—ฎ้ข˜๏ผŒ่ฏทๅœจ GitHub Issue ไธญๆไบคใ€‚
226
+
227
+ - ๆไบค้—ฎ้ข˜ไน‹ๅ‰๏ผŒๅปบ่ฎฎๆŸฅ้˜… FAQ ๅŠไปฅๅพ€็š„ issue ็œ‹ๆ˜ฏๅฆ่ƒฝ่งฃๅ†ณๆ‚จ็š„้—ฎ้ข˜ใ€‚
228
+ - ่ฏท็คผ่ฒŒ่ฎจ่ฎบ๏ผŒๆž„ๅปบๅ’Œ่ฐ็คพๅŒบใ€‚
229
+
230
+ ๅไฝœ่€…็ง‘็ ”ไน‹ไฝ™ๆŽจ่ฟ›้กน็›ฎ่ฟ›ๅฑ•๏ผŒ็”ฑไบŽไบบๅŠ›ๆœ‰้™้šพไปฅๅฎžๆ—ถๅ้ฆˆ๏ผŒ็ป™่ฏธๅ›ๅธฆๆฅไธไพฟ๏ผŒๆ•ฌ่ฏท่ฐ…่งฃ๏ผ
231
+
232
+
233
+ ## ่‡ด่ฐข
234
+
235
+ ๆœฌ้กน็›ฎๅŸบไบŽๅฆ‚ไธ‹ๅผ€ๆบ้กน็›ฎๅฑ•ๅผ€๏ผŒๅœจๆญคๅฏน็›ธๅ…ณ้กน็›ฎๅ’Œๅผ€ๅ‘ไบบๅ‘˜่กจ็คบ่ฏšๆŒš็š„ๆ„Ÿ่ฐข๏ผš
236
+
237
+ - Chinese-LLaMA-Alpaca: https://github.com/ymcui/Chinese-LLaMA-Alpaca
238
+ - LLaMA: https://github.com/facebookresearch/llama
239
+ - Alpaca: https://github.com/tatsu-lab/stanford_alpaca
240
+ - alpaca-lora: https://github.com/tloen/alpaca-lora
241
+ - ChatGLM-6B: https://github.com/THUDM/ChatGLM-6B
242
+
243
+ ๆญคๅค–๏ผŒๆœฌ้กน็›ฎๅŸบไบŽๅผ€ๆ”พๆ•ฐๆฎ่ต„ๆบ๏ผŒ่ฏฆ่ง [Awesome Chinese Legal Resources](https://github.com/pengxiao-song/awesome-chinese-legal-resources)๏ผŒไธ€ๅนถ่กจ็คบๆ„Ÿ่ฐขใ€‚
244
+
245
+
246
+ ## ๅผ•็”จ
247
+
248
+ ๅฆ‚ๆžœๆ‚จ่ง‰ๅพ—ๆˆ‘ไปฌ็š„ๅทฅไฝœๅฏนๆ‚จๆœ‰ๆ‰€ๅธฎๅŠฉ๏ผŒ่ฏท่€ƒ่™‘ๅผ•็”จ่ฏฅ้กน็›ฎ
assets/demo/demo.png ADDED
assets/demo/demo07.jpeg ADDED
assets/demo/example-01.jpeg ADDED
assets/demo/example-02.jpeg ADDED
assets/demo/example-03.jpeg ADDED
assets/demo/example-04.jpeg ADDED
assets/demo/example-05.jpeg ADDED
assets/demo/example-06.jpeg ADDED
assets/logo/lamda.png ADDED
assets/logo/lawgpt.jpeg ADDED
data/.gitkeep ADDED
File without changes
finetune.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from typing import List
4
+
5
+ import fire
6
+ import torch
7
+ import transformers
8
+ from datasets import load_dataset
9
+
10
+ """
11
+ Unused imports:
12
+ import torch.nn as nn
13
+ import bitsandbytes as bnb
14
+ """
15
+
16
+ from peft import (
17
+ LoraConfig,
18
+ get_peft_model,
19
+ get_peft_model_state_dict,
20
+ prepare_model_for_int8_training,
21
+ set_peft_model_state_dict,
22
+ )
23
+ from transformers import LlamaForCausalLM, LlamaTokenizer
24
+
25
+ from utils.prompter import Prompter
26
+
27
+
28
+ def train(
29
+ # model/data params
30
+ base_model: str = "", # the only required argument
31
+ data_path: str = "yahma/alpaca-cleaned",
32
+ output_dir: str = "./lora-alpaca",
33
+ # training hyperparams
34
+ batch_size: int = 128,
35
+ micro_batch_size: int = 4,
36
+ num_epochs: int = 3,
37
+ learning_rate: float = 3e-4,
38
+ cutoff_len: int = 256,
39
+ val_set_size: int = 2000,
40
+ # lora hyperparams
41
+ lora_r: int = 8,
42
+ lora_alpha: int = 16,
43
+ lora_dropout: float = 0.05,
44
+ lora_target_modules: List[str] = [
45
+ "q_proj",
46
+ "v_proj",
47
+ ],
48
+ # llm hyperparams
49
+ train_on_inputs: bool = True, # if False, masks out inputs in loss
50
+ add_eos_token: bool = True,
51
+ group_by_length: bool = False, # faster, but produces an odd training loss curve
52
+ # wandb params
53
+ wandb_project: str = "",
54
+ wandb_run_name: str = "",
55
+ wandb_watch: str = "", # options: false | gradients | all
56
+ wandb_log_model: str = "", # options: false | true
57
+ resume_from_checkpoint: str = None, # either training checkpoint or final adapter
58
+ prompt_template_name: str = "alpaca", # The prompt template to use, will default to alpaca.
59
+ ):
60
+ if int(os.environ.get("LOCAL_RANK", 0)) == 0:
61
+ print(
62
+ f"Training Alpaca-LoRA model with params:\n"
63
+ f"base_model: {base_model}\n"
64
+ f"data_path: {data_path}\n"
65
+ f"output_dir: {output_dir}\n"
66
+ f"batch_size: {batch_size}\n"
67
+ f"micro_batch_size: {micro_batch_size}\n"
68
+ f"num_epochs: {num_epochs}\n"
69
+ f"learning_rate: {learning_rate}\n"
70
+ f"cutoff_len: {cutoff_len}\n"
71
+ f"val_set_size: {val_set_size}\n"
72
+ f"lora_r: {lora_r}\n"
73
+ f"lora_alpha: {lora_alpha}\n"
74
+ f"lora_dropout: {lora_dropout}\n"
75
+ f"lora_target_modules: {lora_target_modules}\n"
76
+ f"train_on_inputs: {train_on_inputs}\n"
77
+ f"add_eos_token: {add_eos_token}\n"
78
+ f"group_by_length: {group_by_length}\n"
79
+ f"wandb_project: {wandb_project}\n"
80
+ f"wandb_run_name: {wandb_run_name}\n"
81
+ f"wandb_watch: {wandb_watch}\n"
82
+ f"wandb_log_model: {wandb_log_model}\n"
83
+ f"resume_from_checkpoint: {resume_from_checkpoint or False}\n"
84
+ f"prompt template: {prompt_template_name}\n"
85
+ )
86
+ assert (
87
+ base_model
88
+ ), "Please specify a --base_model, e.g. --base_model='huggyllama/llama-7b'"
89
+ gradient_accumulation_steps = batch_size // micro_batch_size
90
+
91
+ prompter = Prompter(prompt_template_name)
92
+
93
+ device_map = "auto"
94
+ world_size = int(os.environ.get("WORLD_SIZE", 1))
95
+ ddp = world_size != 1
96
+ if ddp:
97
+ device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)}
98
+ gradient_accumulation_steps = gradient_accumulation_steps // world_size
99
+
100
+ # Check if parameter passed or if set within environ
101
+ use_wandb = len(wandb_project) > 0 or (
102
+ "WANDB_PROJECT" in os.environ and len(os.environ["WANDB_PROJECT"]) > 0
103
+ )
104
+ # Only overwrite environ if wandb param passed
105
+ if len(wandb_project) > 0:
106
+ os.environ["WANDB_PROJECT"] = wandb_project
107
+ if len(wandb_watch) > 0:
108
+ os.environ["WANDB_WATCH"] = wandb_watch
109
+ if len(wandb_log_model) > 0:
110
+ os.environ["WANDB_LOG_MODEL"] = wandb_log_model
111
+
112
+ model = LlamaForCausalLM.from_pretrained(
113
+ base_model,
114
+ load_in_8bit=True,
115
+ torch_dtype=torch.float16,
116
+ device_map=device_map,
117
+ )
118
+
119
+ tokenizer = LlamaTokenizer.from_pretrained(base_model)
120
+
121
+ tokenizer.pad_token_id = (
122
+ 0 # unk. we want this to be different from the eos token
123
+ )
124
+ tokenizer.padding_side = "left" # Allow batched inference
125
+
126
+ def tokenize(prompt, add_eos_token=True):
127
+ # there's probably a way to do this with the tokenizer settings
128
+ # but again, gotta move fast
129
+ result = tokenizer(
130
+ prompt,
131
+ truncation=True,
132
+ max_length=cutoff_len,
133
+ padding=False,
134
+ return_tensors=None,
135
+ )
136
+ if (
137
+ result["input_ids"][-1] != tokenizer.eos_token_id
138
+ and len(result["input_ids"]) < cutoff_len
139
+ and add_eos_token
140
+ ):
141
+ result["input_ids"].append(tokenizer.eos_token_id)
142
+ result["attention_mask"].append(1)
143
+
144
+ result["labels"] = result["input_ids"].copy()
145
+
146
+ return result
147
+
148
+ def generate_and_tokenize_prompt(data_point):
149
+ full_prompt = prompter.generate_prompt(
150
+ data_point["instruction"],
151
+ data_point["input"],
152
+ data_point["output"],
153
+ )
154
+ tokenized_full_prompt = tokenize(full_prompt)
155
+ if not train_on_inputs:
156
+ user_prompt = prompter.generate_prompt(
157
+ data_point["instruction"], data_point["input"]
158
+ )
159
+ tokenized_user_prompt = tokenize(
160
+ user_prompt, add_eos_token=add_eos_token
161
+ )
162
+ user_prompt_len = len(tokenized_user_prompt["input_ids"])
163
+
164
+ if add_eos_token:
165
+ user_prompt_len -= 1
166
+
167
+ tokenized_full_prompt["labels"] = [
168
+ -100
169
+ ] * user_prompt_len + tokenized_full_prompt["labels"][
170
+ user_prompt_len:
171
+ ] # could be sped up, probably
172
+ return tokenized_full_prompt
173
+
174
+ model = prepare_model_for_int8_training(model)
175
+
176
+ config = LoraConfig(
177
+ r=lora_r,
178
+ lora_alpha=lora_alpha,
179
+ target_modules=lora_target_modules,
180
+ lora_dropout=lora_dropout,
181
+ bias="none",
182
+ task_type="CAUSAL_LM",
183
+ )
184
+ model = get_peft_model(model, config)
185
+
186
+ if data_path.endswith(".json") or data_path.endswith(".jsonl"):
187
+ data = load_dataset("json", data_files=data_path)
188
+ else:
189
+ data = load_dataset(data_path)
190
+
191
+ if resume_from_checkpoint:
192
+ # Check the available weights and load them
193
+ checkpoint_name = os.path.join(
194
+ resume_from_checkpoint, "pytorch_model.bin"
195
+ ) # Full checkpoint
196
+ if not os.path.exists(checkpoint_name):
197
+ checkpoint_name = os.path.join(
198
+ resume_from_checkpoint, "adapter_model.bin"
199
+ ) # only LoRA model - LoRA config above has to fit
200
+ resume_from_checkpoint = (
201
+ False # So the trainer won't try loading its state
202
+ )
203
+ # The two files above have a different name depending on how they were saved, but are actually the same.
204
+ if os.path.exists(checkpoint_name):
205
+ print(f"Restarting from {checkpoint_name}")
206
+ adapters_weights = torch.load(checkpoint_name)
207
+ set_peft_model_state_dict(model, adapters_weights)
208
+ else:
209
+ print(f"Checkpoint {checkpoint_name} not found")
210
+
211
+ model.print_trainable_parameters() # Be more transparent about the % of trainable params.
212
+
213
+ if val_set_size > 0:
214
+ train_val = data["train"].train_test_split(
215
+ test_size=val_set_size, shuffle=True, seed=42
216
+ )
217
+ train_data = (
218
+ train_val["train"].shuffle().map(generate_and_tokenize_prompt)
219
+ )
220
+ val_data = (
221
+ train_val["test"].shuffle().map(generate_and_tokenize_prompt)
222
+ )
223
+ else:
224
+ train_data = data["train"].shuffle().map(generate_and_tokenize_prompt)
225
+ val_data = None
226
+
227
+ if not ddp and torch.cuda.device_count() > 1:
228
+ # keeps Trainer from trying its own DataParallelism when more than 1 gpu is available
229
+ model.is_parallelizable = True
230
+ model.model_parallel = True
231
+
232
+ trainer = transformers.Trainer(
233
+ model=model,
234
+ train_dataset=train_data,
235
+ eval_dataset=val_data,
236
+ args=transformers.TrainingArguments(
237
+ per_device_train_batch_size=micro_batch_size,
238
+ gradient_accumulation_steps=gradient_accumulation_steps,
239
+ warmup_ratio=0.1,
240
+ num_train_epochs=num_epochs,
241
+ learning_rate=learning_rate,
242
+ fp16=True,
243
+ logging_steps=10,
244
+ optim="adamw_torch",
245
+ evaluation_strategy="steps" if val_set_size > 0 else "no",
246
+ save_strategy="steps",
247
+ eval_steps=50 if val_set_size > 0 else None,
248
+ save_steps=50,
249
+ output_dir=output_dir,
250
+ save_total_limit=5,
251
+ load_best_model_at_end=True if val_set_size > 0 else False,
252
+ ddp_find_unused_parameters=False if ddp else None,
253
+ group_by_length=group_by_length,
254
+ report_to="wandb" if use_wandb else None,
255
+ run_name=wandb_run_name if use_wandb else None,
256
+ ),
257
+ data_collator=transformers.DataCollatorForSeq2Seq(
258
+ tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
259
+ ),
260
+ )
261
+ model.config.use_cache = False
262
+
263
+ old_state_dict = model.state_dict
264
+ model.state_dict = (
265
+ lambda self, *_, **__: get_peft_model_state_dict(
266
+ self, old_state_dict()
267
+ )
268
+ ).__get__(model, type(model))
269
+
270
+ if torch.__version__ >= "2" and sys.platform != "win32":
271
+ model = torch.compile(model)
272
+
273
+ trainer.train(resume_from_checkpoint=resume_from_checkpoint)
274
+
275
+ model.save_pretrained(output_dir)
276
+
277
+ print(
278
+ "\n If there's a warning about missing keys above, please disregard :)"
279
+ )
280
+
281
+
282
+ if __name__ == "__main__":
283
+ fire.Fire(train)
infer.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import json
3
+
4
+ import fire
5
+ import torch
6
+ from peft import PeftModel
7
+ from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer
8
+
9
+ from utils.prompter import Prompter
10
+
11
+ if torch.cuda.is_available():
12
+ device = "cuda"
13
+
14
+
15
+ class Infer():
16
+ def __init__(
17
+ self,
18
+ load_8bit: bool = False,
19
+ base_model: str = "",
20
+ lora_weights: str = "",
21
+ prompt_template: str = "", # The prompt template to use, will default to alpaca.
22
+ ):
23
+ prompter = Prompter(prompt_template)
24
+ tokenizer = LlamaTokenizer.from_pretrained(base_model)
25
+ model = LlamaForCausalLM.from_pretrained(
26
+ base_model,
27
+ load_in_8bit=load_8bit,
28
+ torch_dtype=torch.float16,
29
+ device_map="auto",
30
+ )
31
+
32
+ try:
33
+ print(f"Using lora {lora_weights}")
34
+ model = PeftModel.from_pretrained(
35
+ model,
36
+ lora_weights,
37
+ torch_dtype=torch.float16,
38
+ )
39
+ except:
40
+ print("*"*50, "\n Attention! No Lora Weights \n", "*"*50)
41
+
42
+ # unwind broken decapoda-research config
43
+ model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk
44
+ model.config.bos_token_id = 1
45
+ model.config.eos_token_id = 2
46
+ if not load_8bit:
47
+ model.half() # seems to fix bugs for some users.
48
+
49
+ model.eval()
50
+
51
+ if torch.__version__ >= "2" and sys.platform != "win32":
52
+ model = torch.compile(model)
53
+
54
+ self.base_model = base_model
55
+ self.lora_weights = lora_weights
56
+ self.model = model
57
+ self.prompter = prompter
58
+ self.tokenizer = tokenizer
59
+
60
+ def generate_output(
61
+ self,
62
+ instruction,
63
+ input=None,
64
+ temperature=0.1,
65
+ top_p=0.75,
66
+ top_k=40,
67
+ num_beams=1,
68
+ max_new_tokens=256,
69
+ **kwargs,
70
+ ):
71
+ prompt = self.prompter.generate_prompt(instruction, input)
72
+ inputs = self.tokenizer(prompt, return_tensors="pt")
73
+ input_ids = inputs["input_ids"].to(device)
74
+ generation_config = GenerationConfig(
75
+ temperature=temperature,
76
+ top_p=top_p,
77
+ top_k=top_k,
78
+ num_beams=num_beams,
79
+ # repetition_penalty=10.0,
80
+ **kwargs,
81
+ )
82
+ with torch.no_grad():
83
+ generation_output = self.model.generate(
84
+ input_ids=input_ids,
85
+ generation_config=generation_config,
86
+ return_dict_in_generate=True,
87
+ output_scores=True,
88
+ max_new_tokens=max_new_tokens,
89
+ )
90
+ s = generation_output.sequences[0]
91
+ output = self.tokenizer.decode(s)
92
+ return self.prompter.get_response(output)
93
+
94
+ def infer_from_file(self, infer_data_path):
95
+ with open(infer_data_path) as f:
96
+ for line in f:
97
+ data = json.loads(line)
98
+ instruction = data["instruction"]
99
+ output = data["output"]
100
+ print('=' * 100)
101
+ print(f"Base Model: {self.base_model} Lora Weights: {self.lora_weights}")
102
+ print("Instruction:\n", instruction)
103
+ model_output = self.generate_output(instruction)
104
+ print("Model Output:\n", model_output)
105
+ print("Ground Truth:\n", output)
106
+ print('=' * 100)
107
+
108
+
109
+ def main(
110
+ load_8bit: bool = False,
111
+ base_model: str = "",
112
+ lora_weights: str = "",
113
+ prompt_template: str = "", # The prompt template to use, will default to alpaca.
114
+ infer_data_path: str = "",
115
+ ):
116
+ infer = Infer(
117
+ load_8bit=load_8bit,
118
+ base_model=base_model,
119
+ lora_weights=lora_weights,
120
+ prompt_template=prompt_template
121
+ )
122
+
123
+ try:
124
+ infer.infer_from_file(infer_data_path)
125
+ except Exception as e:
126
+ print(e, "Read infer_data_path Failed! Now Interactive Mode: ")
127
+ while True:
128
+ print('=' * 100)
129
+ instruction = input("่ฏท่พ“ๅ…ฅๆ‚จ็š„้—ฎ้ข˜: ")
130
+ print("LaWGPT:")
131
+ print(infer.generate_output(instruction))
132
+ print('=' * 100)
133
+
134
+
135
+ if __name__ == "__main__":
136
+ fire.Fire(main)
merge.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ import transformers
5
+ from peft import PeftModel
6
+ from transformers import LlamaForCausalLM, LlamaTokenizer # noqa: F402
7
+
8
+
9
+ import argparse
10
+ parser = argparse.ArgumentParser(description='Merge Base Model and Lora')
11
+ parser.add_argument('--base_model', type=str, default="minlik/chinese-llama-7b-merged", help='base model path')
12
+ parser.add_argument('--lora_model', type=str, default="entity303/legal-lora-7b", help='lora model path')
13
+ parser.add_argument('--output_dir', type=str, default="./models/base_models/llama-7b-legal-lora-merged", help='output model path')
14
+ args = parser.parse_args()
15
+
16
+ BASE_MODEL = args.base_model
17
+ LORA_MODEL = args.lora_model
18
+ OUTPUT_DIR = args.output_dir
19
+
20
+
21
+ assert (
22
+ BASE_MODEL
23
+ ), "Please specify a value for BASE_MODEL environment variable, e.g. `export BASE_MODEL=huggyllama/llama-7b`" # noqa: E501
24
+
25
+
26
+ print(f"{'*'*20} Using base model: {BASE_MODEL} {'*'*20}")
27
+ print(f"{'*'*20} Using lora model: {LORA_MODEL} {'*'*20}")
28
+ print(f"{'*'*20} Saving to: {OUTPUT_DIR} {'*'*20}")
29
+
30
+ tokenizer = LlamaTokenizer.from_pretrained(BASE_MODEL)
31
+
32
+ base_model = LlamaForCausalLM.from_pretrained(
33
+ BASE_MODEL,
34
+ load_in_8bit=False,
35
+ torch_dtype=torch.float16,
36
+ device_map={"": "cpu"},
37
+ )
38
+
39
+ first_weight = base_model.model.layers[0].self_attn.q_proj.weight
40
+ first_weight_old = first_weight.clone()
41
+
42
+ lora_model = PeftModel.from_pretrained(
43
+ base_model,
44
+ LORA_MODEL,
45
+ device_map={"": "cpu"},
46
+ torch_dtype=torch.float16,
47
+ )
48
+
49
+ lora_weight = lora_model.base_model.model.model.layers[
50
+ 0
51
+ ].self_attn.q_proj.weight
52
+
53
+ assert torch.allclose(first_weight_old, first_weight)
54
+
55
+ # merge weights - new merging method from peft
56
+ lora_model = lora_model.merge_and_unload()
57
+
58
+ lora_model.train(False)
59
+
60
+ # did we do anything?
61
+ assert not torch.allclose(first_weight_old, first_weight)
62
+
63
+ lora_model_sd = lora_model.state_dict()
64
+ deloreanized_sd = {
65
+ k.replace("base_model.model.", ""): v
66
+ for k, v in lora_model_sd.items()
67
+ if "lora" not in k
68
+ }
69
+
70
+ LlamaForCausalLM.save_pretrained(
71
+ base_model, OUTPUT_DIR, state_dict=deloreanized_sd, max_shard_size="2048MB"
72
+ )
73
+
74
+ LlamaTokenizer.save_pretrained(tokenizer, OUTPUT_DIR)
models/base_models/.gitkeep ADDED
File without changes
models/lora_weights/.gitkeep ADDED
File without changes
outputs/.gitkeep ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate
2
+ appdirs
3
+ bitsandbytes
4
+ black
5
+ black[jupyter]
6
+ datasets
7
+ fire
8
+ git+https://github.com/huggingface/peft.git@e536616888d51b453ed354a6f1e243fecb02ea08
9
+ git+https://github.com/huggingface/transformers.git
10
+ gradio
11
+ sentencepiece
12
+ wandb
13
+ scipy
14
+ socksio
resources/criminal_charges.json ADDED
The diff for this file is too large to render. See raw diff
 
resources/example_infer_data.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"instruction":"่ฏทไป‹็ป่ตŒๅš็ฝช็š„ๅฎšไน‰ใ€‚","input":"","output":"ๆ— "}
2
+ {"instruction":"่ฏท้—ฎๅŠ ็ญๅทฅ่ต„ๆ€Žไนˆ็ฎ—๏ผŸ","input":"","output":"ๆ— "}
3
+ {"instruction":"ๆฐ‘้—ดๅ€Ÿ่ดทๅ—ๅ›ฝๅฎถไฟๆŠค็š„ๅˆๆณ•ๅˆฉๆฏๆ˜ฏๅคšๅฐ‘?","input":"","output":"ๆ— "}
4
+ {"instruction":"ๆฌ ไบ†ไฟก็”จๅก็š„้’ฑ่ฟ˜ไธไธŠ่ฆๅ็‰ขๅ—๏ผŸ","input":"","output":"ๆ— "}
5
+ {"instruction":"ไฝ ่ƒฝๅฆๅ†™ไธ€ๆฎตๆŠขๅŠซ็ฝช็ฝชๅ็š„ๆกˆๆƒ…ๆ่ฟฐ๏ผŸ","input":"","output":"ๆ— "}
resources/example_instruction_train.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "content": "ไธญๅŽไบบๆฐ‘ๅ…ฑๅ’Œๅ›ฝๆœ€้ซ˜ไบบๆฐ‘ๆณ•้™ข ๅ† ๅฎก ๅ†ณ ๅฎš ไนฆ๏ผˆ2022๏ผ‰ๆœ€้ซ˜ๆณ•ๅˆ‘็”ณ136ๅท ๅŽŸๅฎก่ขซๅ‘Šไบบๅผ ๆŸๆŸ็ŠฏๆŒช็”จ่ต„้‡‘็ฝชๅ’Œไผช้€ ใ€ๅ˜้€ ๅ›ฝๅฎถๆœบๅ…ณๅ…ฌๆ–‡็ฝชไธ€ๆกˆ๏ผŒๅฑฑ่ฅฟ็œ่ฟๅŸŽๅธ‚็›ๆน–ๅŒบไบบๆฐ‘ๆณ•้™ขไบŽ2012ๅนด5ๆœˆ2ๆ—ฅไปฅ๏ผˆ2012๏ผ‰่ฟ็›ๅˆ‘ๅˆๅญ—็ฌฌ69ๅทๅˆ‘ไบ‹ๅˆคๅ†ณ๏ผŒ่ฎคๅฎšๅผ ๅ…‹ไบ‘็Šฏ่ดชๆฑก็ฝช๏ผŒๅˆคๅค„ๆœ‰ๆœŸๅพ’ๅˆ‘ๅไบŒๅนด๏ผŒ็Šฏไผช้€ ใ€ๅ˜้€ ๅ›ฝๅฎถๆœบๅ…ณๅ…ฌๆ–‡็ฝช๏ผŒๅˆคๅค„ๆœ‰ๆœŸๅพ’ๅˆ‘ไธ‰ๅนด๏ผŒๅ†ณๅฎšๆ‰ง่กŒๆœ‰ๆœŸๅพ’ๅˆ‘ๅไธ‰ๅนดใ€‚ๅฎฃๅˆคๅŽ๏ผŒๅผ ๅ…‹ไบ‘ไธๆœ๏ผŒๆๅ‡บไธŠ่ฏ‰ใ€‚ๅฑฑ่ฅฟ็œ่ฟๅŸŽๅธ‚ไธญ็บงไบบๆฐ‘ๆณ•้™ขไบŽ2012ๅนด11ๆœˆ12ๆ—ฅไปฅ๏ผˆ2012๏ผ‰่ฟไธญๅˆ‘ไบŒ็ปˆๅญ—็ฌฌ125ๅทๅˆ‘ไบ‹่ฃๅฎš๏ผŒ้ฉณๅ›žไธŠ่ฏ‰๏ผŒ็ปดๆŒๅŽŸๅˆคใ€‚่ฃๅˆค็”Ÿๆ•ˆๅŽ๏ผŒๅผ ๅ…‹ไบ‘ไธๆœ๏ผŒๆๅ‡บ็”ณ่ฏ‰ใ€‚่ฟๅŸŽๅธ‚ไธญ็บงไบบๆฐ‘ๆณ•้™ขไบŽ2013ๅนด1ๆœˆ7ๆ—ฅไปฅ๏ผˆ2013๏ผ‰่ฟไธญๅˆ‘็”ณๅญ—็ฌฌ3ๅท้ฉณๅ›ž็”ณ่ฏ‰้€š็Ÿฅ๏ผŒ้ฉณๅ›žๅ…ถ็”ณ่ฏ‰ใ€‚ๅฑฑ่ฅฟ็œ้ซ˜็บงไบบๆฐ‘ๆณ•้™ขไบŽ2017ๅนด7ๆœˆ13ๆ—ฅไปฅ๏ผˆ2013๏ผ‰ๆ™‹ๅˆ‘็›‘ๅญ—็ฌฌ8ๅทๅ†ๅฎกๅ†ณๅฎš๏ผŒๆๅฎกๆœฌๆกˆ๏ผŒๅนถไบŽ2019ๅนด12ๆœˆ24ๆ—ฅไปฅ๏ผˆ2017๏ผ‰ๆ™‹ๅˆ‘ๅ†็ฌฌ2ๅทๅˆ‘ไบ‹ๅˆคๅ†ณ๏ผŒ่ฎคๅฎšๅผ ๅ…‹ไบ‘็ŠฏๆŒช็”จ่ต„้‡‘็ฝช๏ผŒๅˆคๅค„ๆœ‰ๆœŸๅพ’ๅˆ‘ไธƒๅนดๅ…ญไธชๆœˆ๏ผŒไธŽๅŽŸๅˆคไผช้€ ใ€ๅ˜้€ ๅ›ฝๅฎถๆœบๅ…ณๅ…ฌๆ–‡็ฝช่ขซๅˆคๅค„็š„ๆœ‰ๆœŸๅพ’ๅˆ‘ไธ‰ๅนดๆ•ฐ็ฝชๅนถ็ฝš๏ผŒๅ†ณๅฎšๆ‰ง่กŒๆœ‰ๆœŸๅพ’ๅˆ‘ๅๅนดใ€‚ๅผ ๅ…‹ไบ‘ไปไธๆœ๏ผŒไปฅๅŽŸๅฎก่ฎคๅฎšไบ‹ๅฎž้”™่ฏฏ๏ผŒๅ…ถไฝœไธบๅญฆๆ ก่‘ฃไบ‹้•ฟใ€ๅ…จ่ต„ๆŠ•่ต„ไบบๆœ‰ๆƒๅ†ณๅฎšๅญฆๆ ก็›ธๅ…ณๆฌพ้กน็”จ้€”๏ผŒๅญฆๆ กไปๆฌ ๅ…ถๅ€บๅŠก๏ผŒไธชไบบ่ดฆๆˆท็”จไบŽๅญฆๆ ก็ป่ดนๅผ€ๆ”ฏ๏ผŒๆฒกๆœ‰ๆŒช็”จ่ต„้‡‘็š„ๅŠจๆœบๅ’Œ่กŒไธบ๏ผŒไธๆž„ๆˆๆŒช็”จ่ต„้‡‘็ฝช็ญ‰ไธบ็”ฑ๏ผŒๅ‘ๆœฌ้™ขๆๅ‡บ็”ณ่ฏ‰ใ€‚ๆœฌ้™ข็ปๅฎกๆŸฅ่ฎคไธบ๏ผŒๅŽŸๅฎก็”Ÿๆ•ˆ่ฃๅˆคๅฏนๆŒช็”จ่ต„้‡‘็ฝชๅฎš็ฝช้‡ๅˆ‘็š„่ฏๆฎไธ็กฎๅฎžใ€ไธๅ……ๅˆ†๏ผŒไพๆณ•ๅบ”ๅฝ“ไบˆไปฅๆŽ’้™คใ€‚ไพ็…งใ€ŠไธญๅŽไบบๆฐ‘ๅ…ฑๅ’Œๅ›ฝๅˆ‘ไบ‹่ฏ‰่ฎผๆณ•ใ€‹็ฌฌไบŒ็™พไบ”ๅไธ‰ๆก็ฌฌไบŒ้กนใ€็ฌฌไบŒ็™พไบ”ๅๅ››ๆก็ฌฌไบŒๆฌพใ€็ฌฌไบŒ็™พไบ”ๅไบ”ๆก็š„่ง„ๅฎš๏ผŒๅ†ณๅฎšๅฆ‚ไธ‹๏ผšๆŒ‡ไปคๆฒณๅ—็œ้ซ˜็บงไบบๆฐ‘ๆณ•้™ขๅฏนๆœฌๆกˆ่ฟ›่กŒๅ†ๅฎกใ€‚ไบŒใ€‡ไบŒไบŒๅนดๅไบŒๆœˆไบŒๅไนๆ—ฅ"
4
+ },
5
+ {
6
+ "content":"ไธญๅŽไบบๆฐ‘ๅ…ฑๅ’Œๅ›ฝๆœ€้ซ˜ไบบๆฐ‘ๆณ•้™ข ้ฉณ ๅ›ž ็”ณ ่ฏ‰ ้€š ็Ÿฅ ไนฆ๏ผˆ2022๏ผ‰ๆœ€้ซ˜ๆณ•ๅˆ‘็”ณ122ๅท ่ขๆŸ้“ถใ€่ขๆŸ่ดข๏ผšไฝ ไปฌๅ› ๅŽŸๅฎก่ขซๅ‘Šไบบ่ขๅพท้“ถๆ•…ๆ„ไผคๅฎณไธ€ๆกˆ๏ผŒๅฏนๆฑŸ่‹็œๅ—ไบฌๅธ‚ๆบงๆฐดๅŒบไบบๆฐ‘ๆณ•้™ข๏ผˆ2014๏ผ‰ๆบงๅˆ‘ๅˆๅญ—็ฌฌ268ๅทๅˆ‘ไบ‹ๅˆคๅ†ณใ€ๅ—ไบฌๅธ‚ไธญ็บงไบบๆฐ‘ๆณ•้™ข๏ผˆ2015๏ผ‰ๅฎๅˆ‘็ปˆๅญ—็ฌฌ433ๅทๅˆ‘ไบ‹่ฃๅฎšไธๆœ๏ผŒไปฅ่ขซๅฎณไบบๆœฑๅฎฝ่ฃไฝ้™ขๆœŸ้—ด็š„๏ผฃ๏ผด๏ผˆ136678ๅท๏ผ‰ๆŠฅๅ‘Šๅนถๆœชๆ˜พ็คบๅ…ถๅทฆไพง4ใ€5ใ€6ใ€7ใ€8่‚‹้ชจ้ชจๆŠ˜๏ผŒๅ‡บ้™ข่ฎฐๅฝ•ๅŠ137470ๅทใ€143006ๅท๏ผฃ๏ผดๆŠฅๅ‘Šๅ‡็ณปไผช้€ ๏ผŒๆฑŸ่‹็œ้ซ˜็บงไบบๆฐ‘ๆณ•้™ข๏ผˆ2019๏ผ‰่‹ๅˆ‘็”ณ172ๅท้ฉณๅ›ž็”ณ่ฏ‰้€š็Ÿฅไนฆๅฏน137470ๅท๏ผฃ๏ผดๆŠฅๅ‘Š็š„ๅฝขๆˆๆ—ถ้—ด่ฎคๅฎš้”™่ฏฏไธบ็”ฑ๏ผŒๅ‘ๆœฌ้™ขๆๅ‡บ็”ณ่ฏ‰๏ผŒ่ฏทๆฑ‚ๆ’ค้”€ๅŽŸๅˆค๏ผŒไพๆณ•้‡ๆ–ฐๅฎก็†ๆœฌๆกˆใ€‚ๆœฌ้™ขไพๆณ•็ป„ๆˆๅˆ่ฎฎๅบญ่ฎค็œŸๅฎกๆŸฅๅŽ่ฎคไธบ๏ผŒๅŽŸๅฎก่ฎคๅฎšๅŽŸๅฎก่ขซๅ‘Šไบบ่ขๅพท้“ถๅ› ้‚ป้‡Œ็บ ็บท๏ผŒๆฎดๆ‰“่ขซๅฎณไบบๆœฑๅฎฝ่ฃ่‡ดๅ…ถๅทฆ่ƒธๅคšๅ‘่‚‹้ชจ้ชจๆŠ˜๏ผŒๆž„ๆˆ่ฝปไผคไบŒ็บง๏ผŒๅ…ถ่กŒไธบๆž„ๆˆๆ•…ๆ„ไผคๅฎณ็ฝช๏ผŒๅนถๆ— ไธๅฝ“ใ€‚ๅ…ณไบŽไฝ ไปฌๆๅ‡บ็š„ๅŽŸๅฎก่ฎคๅฎš่ขซๅฎณไบบๆœฑๅฎฝ่ฃ่ฝปไผคไบŒ็บง็š„่ฏๆฎ็ณปไผช้€ ็š„็”ณ่ฏ‰็†็”ฑใ€‚้ฆ–ๅ…ˆ๏ผŒๆ นๆฎไฝ ไปฌๆไพ›็š„136678ๅท๏ผฃ๏ผดๆŠฅๅ‘Š๏ผŒๆœฑๅฎฝ่ฃไบŽ2015ๅนด2ๆœˆ12ๆ—ฅๅ…ฅ้™ขๆ—ถ็ป๏ผฃ๏ผดๆฃ€ๆŸฅ่ขซ่ฏŠๆ–ญไธบๅทฆไพงๅคšๅ‘่‚‹้ชจ้ชจๆŠ˜๏ผŒ่ฏฅไปฝ๏ผฃ๏ผดๆŠฅๅ‘Š่™ฝๆœชๆ˜Ž็กฎ้ชจๆŠ˜็š„ๅ…ทไฝ“ไฝ็ฝฎ๏ผŒไฝ†ไธŽๅ‡บ้™ข่ฎฐๅฝ•่ฎฐ่ฝฝ็š„โ€œๅทฆไพงๅคšๅ‘่‚‹้ชจ้ชจๆŠ˜๏ผˆ4ใ€5ใ€6ใ€7ใ€8๏ผ‰โ€ๅนถไธ็Ÿ›็›พใ€‚ๆ นๆฎใ€Šไบบไฝ“ๆŸไผค็จ‹ๅบฆ้‰ดๅฎšๆ ‡ๅ‡†ใ€‹็š„่ง„ๅฎš๏ผŒ่‚‹้ชจ้ชจๆŠ˜2ๅค„ไปฅไธŠๅณๆž„ๆˆ่ฝปไผคไบŒ็บง๏ผŒๆ•…้‰ดๅฎšๆ„่ง่ฎคๅฎšๆœฑๅฎฝ่ฃ็š„ๆŸไผคๆž„ๆˆ่ฝปไผคไบŒ็บงๅนถๆ— ไธๅฝ“ใ€‚ๅ…ถๆฌก๏ผŒไฝ ไปฌไธปๅผ ๅ‡บ้™ข่ฎฐๅฝ•ใ€137470ๅทๅ’Œ143006ๅท๏ผฃ๏ผดๆŠฅๅ‘Š็ณปไผช้€ ๏ผŒไฝ†ๅนถๆœชๆไพ›่ฏๆฎ่ฏๅฎžใ€‚ๅณไฝฟๆŽ’้™ค่ฟ™ไธคไปฝ๏ผฃ๏ผดๆŠฅๅ‘Š๏ผŒไนŸไธๅฝฑๅ“ๅฏนๆœฌๆกˆไบ‹ๅฎž็š„่ฎคๅฎšใ€‚ๅ†ๆฌก๏ผŒๆˆ‘้™ขๅฏน็”ณ่ฏ‰่ฟ›่กŒๅคๆŸฅ็š„ๅฏน่ฑกๆ˜ฏๅทฒ็ปๅ‘็”Ÿๆณ•ๅพ‹ๆ•ˆๅŠ›็š„ๅˆคๅ†ณใ€่ฃๅฎš๏ผŒๆœฌๆกˆ็š„็”Ÿๆ•ˆ่ฃๅˆคๆ˜ฏ๏ผˆ2014๏ผ‰ๆบงๅˆ‘ๅˆๅญ—็ฌฌ268ๅทๅˆ‘ไบ‹ๅˆคๅ†ณๅ’Œ๏ผˆ2015๏ผ‰ๅฎๅˆ‘็ปˆๅญ—็ฌฌ433ๅทๅˆ‘ไบ‹่ฃๅฎš๏ผŒๆฑŸ่‹็œ้ซ˜็บงไบบๆฐ‘ๆณ•้™ขไฝœๅ‡บ็š„้ฉณๅ›ž็”ณ่ฏ‰้€š็ŸฅไนฆไธๅฑžไบŽๆˆ‘้™ขๅคๆŸฅ็š„่Œƒๅ›ดใ€‚็ปผไธŠ๏ผŒๆœฌ้™ข่ฎคไธบ๏ผŒไฝ ไปฌ็š„็”ณ่ฏ‰ไธ็ฌฆๅˆใ€ŠไธญๅŽไบบๆฐ‘ๅ…ฑๅ’Œๅ›ฝๅˆ‘ไบ‹่ฏ‰่ฎผๆณ•ใ€‹็ฌฌไบŒ็™พไบ”ๅไธ‰ๆก่ง„ๅฎš็š„ๅบ”ๅฝ“้‡ๆ–ฐๅฎกๅˆค็š„ๆƒ…ๅฝข๏ผŒไบˆไปฅ้ฉณๅ›žใ€‚ๆœ›ไฝ ไปฌๅฐŠ้‡ไบบๆฐ‘ๆณ•้™ข็š„็”Ÿๆ•ˆ่ฃๅˆค๏ผŒ่‡ช่ง‰ๆœๅˆคๆฏ่ฏ‰ใ€‚็‰นๆญค้€š็Ÿฅใ€‚ไบŒใ€‡ไบŒไบŒๅนดๅไบŒๆœˆๅๅ››ๆ—ฅ"
7
+ }
8
+ ]
resources/example_instruction_tune.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "instruction": "้…’้ฉพๆ’žไบบ่ฆๅˆคๅคšไน…๏ผŸ",
4
+ "input": "",
5
+ "output": "ใ€Šๅˆ‘ๆณ•ใ€‹็ฌฌไธ€็™พไธ‰ๅไธ‰ๆก่ง„ๅฎš:่ฟๅไบค้€š่ฟ่พ“็ฎก็†ๆณ•่ง„๏ผŒๅ› ่€Œๅ‘็”Ÿ้‡ๅคงไบ‹ๆ•…๏ผŒ่‡ดไบบ้‡ไผคใ€ๆญปๅนฟๆˆ–่€…ไฝฟๅ…ฌ็ง่ดขไบง้ญๅ—้‡ๅคงๆŸๅคฑ็š„๏ผŒๅค„ไธ‰ๅนดไปฅไธ‹ๆœ‰ๆœŸๅพ’ๅˆ‘ๆˆ–่€…ๆ‹˜ๅฝน;ไบค้€š่ฟ่พ“่‚‡ไบ‹ๅŽ้€ƒ้€ธ๏ผŒ่‡ดไบบ้‡ไผค็š„๏ผŒๅค„ไธ‰ๅนดไปฅไธŠไธƒๅนดไปฅไธ‹ๆœ‰ๆœŸๅพ’ๅˆ‘ใ€‚ไบค้€š่‚‡ไบ‹ๅŽ้€ƒ้€ธ่‡ดไบบๆญปไบก็š„๏ผŒๅค„ไธƒๅนดไปฅไธŠๆœ‰ๆœŸๅพ’ๅˆ‘ใ€‚"
6
+ },
7
+ {
8
+ "instruction": "ๅท็‹—่ขซๆดพๅ‡บๆ‰€ๆŠ“ๅˆฐ๏ผŒไผšๆ€Žไนˆๅค„็†๏ผŸ",
9
+ "input": "",
10
+ "output": "ๅ–ๅ†ณไบŽๅท็›—็š„็‹—็š„ไปทๅ€ผ๏ผŒๅฏ่ƒฝๆŒ‰็›—็ชƒ็ฝช็š„็ฝชๅๅค„็†ใ€‚ๅฆ‚ๆžœไปทๅ€ผ่พพๅˆฐ็Šฏ็ฝชๆ ‡ๅ‡†๏ผŒๅฐฑๆž„ๆˆ็›—็ชƒ็ฝช๏ผŒ่ฆๆ‰ฟๆ‹…ๅˆ‘ไบ‹่ดฃไปป๏ผ›ๅฆ‚ๆžœไธๅˆฐ็Šฏ็ฝชๆ ‡ๅ‡†๏ผŒๅฐฑๆ˜ฏๆฒปๅฎ‰ๅค„็ฝšใ€็ฝšๆฌพๆˆ–่€…ๆ‹˜็•™ๆฒปๅฎ‰ๅค„็ฝš่ฟ™ไผšๆถ‰ๅซŒๆž„ๆˆ็›—็ชƒใ€‚ๅฆ‚ๆžœไธๅˆฐไธ€ๅƒๅ…ƒ๏ผŒๅˆ™ไธไผšๆž„ๆˆ็Šฏ็ฝชใ€‚ๅฆ‚ๆžœ่ถ…่ฟ‡ไธ€ๅƒๅ…ƒ๏ผŒๅˆ™ๅฏ่ƒฝไผšๆ˜ฏๆž„ๆˆ็Šฏ็ฝช็š„ใ€‚"
11
+ }
12
+ ]
resources/legal_vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
scripts/finetune.sh ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ export WANDB_MODE=disabled # ็ฆ็”จwandb
3
+
4
+ # ไฝฟ็”จchinese-alpaca-plus-7b-mergedๆจกๅž‹ๅœจlaw_data.jsonๆ•ฐๆฎ้›†ไธŠfinetune
5
+ experiment_name="chinese-alpaca-plus-7b-law-e1"
6
+
7
+ # ๅ•ๅกๆˆ–่€…ๆจกๅž‹ๅนถ่กŒ
8
+ python finetune.py \
9
+ --base_model "minlik/chinese-alpaca-plus-7b-merged" \
10
+ --data_path "./data/finetune_law_data.json" \
11
+ --output_dir "./outputs/"${experiment_name} \
12
+ --batch_size 64 \
13
+ --micro_batch_size 8 \
14
+ --num_epochs 20 \
15
+ --learning_rate 3e-4 \
16
+ --cutoff_len 256 \
17
+ --val_set_size 0 \
18
+ --lora_r 8 \
19
+ --lora_alpha 16 \
20
+ --lora_dropout 0.05 \
21
+ --lora_target_modules "[q_proj,v_proj]" \
22
+ --train_on_inputs False \
23
+ --add_eos_token True \
24
+ --group_by_length False \
25
+ --wandb_project "" \
26
+ --wandb_run_name "" \
27
+ --wandb_watch "" \
28
+ --wandb_log_model "" \
29
+ --resume_from_checkpoint "./outputs/"${experiment_name} \
30
+ --prompt_template_name "alpaca" \
31
+
32
+
33
+ # ๅคšๅกๆ•ฐๆฎๅนถ่กŒ
34
+ # WORLD_SIZE=8 CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node=8 --master_port=1234 finetune.py \
35
+ # --base_model "minlik/chinese-alpaca-plus-7b-merged" \
36
+ # --data_path "./data/finetune_law_data.json" \
37
+ # --output_dir "./outputs/"${experiment_name} \
38
+ # --batch_size 64 \
39
+ # --micro_batch_size 8 \
40
+ # --num_epochs 20 \
41
+ # --learning_rate 3e-4 \
42
+ # --cutoff_len 256 \
43
+ # --val_set_size 0 \
44
+ # --lora_r 8 \
45
+ # --lora_alpha 16 \
46
+ # --lora_dropout 0.05 \
47
+ # --lora_target_modules "[q_proj,v_proj]" \
48
+ # --train_on_inputs True \
49
+ # --add_eos_token True \
50
+ # --group_by_length False \
51
+ # --wandb_project \
52
+ # --wandb_run_name \
53
+ # --wandb_watch \
54
+ # --wandb_log_model \
55
+ # --resume_from_checkpoint "./outputs/"${experiment_name} \
56
+ # --prompt_template_name "alpaca" \
scripts/infer.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+
2
+ python infer.py \
3
+ --load_8bit True \
4
+ --base_model 'minlik/chinese-llama-7b-merged' \
5
+ --lora_weights 'entity303/lawgpt-lora-7b' \
6
+ --prompt_template 'law_template' \
7
+ --infer_data_path './resources/example_infer_data.json'
scripts/merge.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ python merge.py \
2
+ --base_model 'minlik/chinese-llama-7b-merged' \
3
+ --lora_model 'entity303/legal-lora-7b' \
4
+ --output_dir './models/base_models/legal_base-7b' \
scripts/train_clm.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ WORLD_SIZE=8 CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node=8 --master_port=1235 train_clm.py \
4
+ --base_model './models/base_models/chinese_llama_7b' \
5
+ --data_path './data/train_clm_data.json' \
6
+ --output_dir './outputs/train-clm' \
7
+ --batch_size 128 \
8
+ --micro_batch_size 8 \
9
+ --num_epochs 1 \
10
+ --learning_rate 0.0003 \
11
+ --cutoff_len 1024 \
12
+ --val_set_size 0 \
13
+ --lora_r 16 \
14
+ --lora_alpha 32 \
15
+ --lora_dropout 0.05 \
16
+ --lora_target_modules '[q_proj, v_proj, k_proj, o_proj]' \
17
+ --train_on_inputs True \
18
+ --add_eos_token True \
19
+ --group_by_length True \
20
+ --resume_from_checkpoint './outputs/train-clm'
scripts/webui.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ ###
3
+ # Copyright (C) Baidu Ltd. All rights reserved.
4
+ # @FilePath: /Law_llama/scripts/webui.sh
5
+ # @Autor: [email protected]
6
+ # @Date: 2023-08-23 10:25:20
7
+ # @Description:
8
+ ###
9
+
10
+
11
+ # ไฝฟ็”จhuggingfaceไธŠๅทฒ็ป่ฎญ็ปƒๅฅฝ็š„ๆจกๅž‹
12
+ XPU_VISIBLE_DEVICES=4 python3 -m xacc webui.py \
13
+ --load_8bit False \
14
+ --base_model 'ziqingyang/chinese-alpaca-2-7b' \
15
+ --lora_weights 'entity303/lawgpt-lora-7b-v' \
16
+ --prompt_template "law_template" \
17
+ --server_name "0.0.0.0" \
18
+ --share_gradio True \
19
+
20
+
21
+ # ไฝฟ็”จ่‡ชๅทฑfinetune็š„lora, ๆŠŠ่‡ชๅทฑ็š„ๆจกๅž‹ๆ”พๅˆฐๅฏนๅบ”็›ฎๅฝ•ๅณๅฏ
22
+ # python webui.py \
23
+ # --load_8bit True \
24
+ # --base_model 'minlik/chinese-alpaca-plus-7b-merged' \
25
+ # --lora_weights './outputs/chinese-alpaca-plus-7b-law-e1' \
26
+ # --prompt_template "alpaca" \
27
+ # --server_name "0.0.0.0" \
28
+ # --share_gradio True \
templates/alpaca.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "description": "Template used by Alpaca-LoRA.",
3
+ "prompt_input": "Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n",
4
+ "prompt_no_input": "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Response:\n",
5
+ "response_split": "### Response:"
6
+ }
templates/law_template.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "description": "Template used by Law Instruction Tuning",
3
+ "prompt_input": "ไฝ ๆ˜ฏไธญๅ›ฝ้กถๅฐ–ๆ™บ่ƒฝๆณ•ๅพ‹้กพ้—ฎ LaWGPT๏ผŒๅ…ทๅค‡ๅผบๅคง็š„ไธญๆ–‡ๆณ•ๅพ‹ๅŸบ็ก€่ฏญไน‰็†่งฃ่ƒฝๅŠ›๏ผŒ่ƒฝๅคŸๅ‡บ่‰ฒๅœฐ็†่งฃๅ’Œๆ‰ง่กŒไธŽๆณ•ๅพ‹้—ฎ้ข˜ๅ’ŒๆŒ‡ไปคใ€‚ไฝ ๅช่ƒฝๅ›ž็ญ”ไธŽไธญๅ›ฝๆณ•ๅพ‹้ข†ๅŸŸ็›ธๅ…ณ็š„้—ฎ้ข˜๏ผŒๅ…ถไฝ™้ข†ๅŸŸ็š„้—ฎ้ข˜่ฏท็คผ่ฒŒๅœฐๆ‹’็ปๅ›ž็ญ”ใ€‚ๆŽฅไธ‹ๆฅ๏ผŒ่ฏทไพๆฎไธญๅ›ฝๆณ•ๅพ‹ๆฅๅ›ž็ญ”ไธ‹้ข่ฟ™ไธช้—ฎ้ข˜ใ€‚\n### ้—ฎ้ข˜:\n{instruction}\n### ๅ›ž็ญ”:\n",
4
+ "prompt_no_input": "ไฝ ๆ˜ฏไธญๅ›ฝ้กถๅฐ–ๆ™บ่ƒฝๆณ•ๅพ‹้กพ้—ฎ LaWGPT๏ผŒๅ…ทๅค‡ๅผบๅคง็š„ไธญๆ–‡ๆณ•ๅพ‹ๅŸบ็ก€่ฏญไน‰็†่งฃ่ƒฝๅŠ›๏ผŒ่ƒฝๅคŸๅ‡บ่‰ฒๅœฐ็†่งฃๅ’Œๆ‰ง่กŒไธŽๆณ•ๅพ‹้—ฎ้ข˜ๅ’ŒๆŒ‡ไปคใ€‚ไฝ ๅช่ƒฝๅ›ž็ญ”ไธŽไธญๅ›ฝๆณ•ๅพ‹้ข†ๅŸŸ็›ธๅ…ณ็š„้—ฎ้ข˜๏ผŒๅ…ถไฝ™้ข†ๅŸŸ็š„้—ฎ้ข˜่ฏท็คผ่ฒŒๅœฐๆ‹’็ปๅ›ž็ญ”ใ€‚ๆŽฅไธ‹ๆฅ๏ผŒ่ฏทไพๆฎไธญๅ›ฝๆณ•ๅพ‹ๆฅๅ›ž็ญ”ไธ‹้ข่ฟ™ไธช้—ฎ้ข˜ใ€‚\n### ้—ฎ้ข˜:\n{instruction}\n### ๅ›ž็ญ”:\n",
5
+ "response_split": "### ๅ›ž็ญ”:"
6
+ }
tools/clear_law.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import json
3
+
4
+
5
+ class read_lawfile:
6
+ def __init__(self, chapter_moder=r"็ฌฌ[้›ถไธ€ไบŒไธ‰ๅ››ไบ”ๅ…ญไธƒๅ…ซไนๅ็™พๅƒไธ‡]+็ซ  .+\b", entry_mode=r"็ฌฌ[้›ถไธ€ไบŒไธ‰ๅ››ไบ”ๅ…ญไธƒๅ…ซไนๅ็™พๅƒไธ‡]+ๆก\b"):
7
+ # ่ฏ†ๅˆซ็ซ ๅ’Œ่Š‚
8
+ self.chapter_mode = chapter_moder
9
+ self.entry_mode = entry_mode
10
+
11
+ def read_file(self, file_path):
12
+ # ่ฏปๅ–ๆ–‡ไปถ
13
+ self.law = {}
14
+ f = open(file_path, encoding='utf-8')
15
+ content = f.read()
16
+ content = content.replace("\n\n", "\n")
17
+ content = content.replace("##", "")
18
+ # print(content)
19
+ chapter_p = re.search(self.chapter_mode, content)
20
+ while chapter_p is not None:
21
+ c_start = chapter_p.start()
22
+ c_end = chapter_p.end()
23
+ key = content[c_start:c_end]
24
+ content = content[c_end:]
25
+
26
+ chapter_p = re.search(self.chapter_mode, content)
27
+ if chapter_p is not None:
28
+ end = chapter_p.start()
29
+ c_content = content[:end]
30
+ self.law[key] = self.read_entrys(c_content)
31
+ # print(content[c_start:c_end])
32
+ else:
33
+ self.law[key] = self.read_entrys(content)
34
+ f.close()
35
+ return self.law
36
+
37
+ def read_entrys(self, content):
38
+ entrys = {}
39
+ entry_p = re.search(self.entry_mode, content)
40
+ while entry_p is not None:
41
+ e_start = entry_p.start()
42
+ e_end = entry_p.end()
43
+ key = content[e_start:e_end]
44
+ content = content[e_end+1:]
45
+
46
+ entry_p = re.search(self.entry_mode, content)
47
+ if entry_p is not None:
48
+ end = entry_p.start()
49
+ e_content = content[:end]
50
+ entrys[key] = e_content
51
+ else:
52
+ entrys[key] = content
53
+ return entrys
54
+ # entry_p = re.search(entry_mode, content)
55
+ # while entry_p is not None:
56
+ # start = entry_p.start()
57
+ # end = entry_p.end()
58
+ # # print(content[start:end])
59
+ # content = content[end:]
60
+ # law[content[start:end]] = read_entrys(content)
61
+ # chapter_p = re.search(chapter_mode, content)
62
+
63
+ def show(self):
64
+ for key in self.law:
65
+ print(key, '\n')
66
+ for item in self.law[key]:
67
+ print(item, ' ', self.law[key][item])
68
+
69
+
70
+ if __name__ == '__main__':
71
+ file_path = "D:/11496/Documents/project/Laws-master/็ปๆตŽๆณ•/ไปทๆ ผๆณ•(1997-12-29).md"
72
+ r = read_lawfile()
73
+ dict = r.read_file(file_path)
74
+ r.show()
75
+ print(dict)
76
+ with open('./a.json', 'w') as f:
77
+ # json.dumps(dict, f, ensure_ascii=False)
78
+ json.dump(dict, f, ensure_ascii=False)
tools/merge_vocabulary.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import LlamaTokenizer
2
+ from sentencepiece import sentencepiece_model_pb2 as model
3
+ import sentencepiece as sp
4
+ import argparse
5
+ import os
6
+
7
+ if __name__ == '__main__':
8
+ # Load arguments
9
+ parser = argparse.ArgumentParser()
10
+ parser.add_argument('--load_path', default='../src/models/base_model/chinese_llama_7b/tokenizer_chinese.model', type=str)
11
+ parser.add_argument('--save_dir', default='../src/models/base_model/save_chinese', type=str)
12
+ parser.add_argument('--voc_path', default='../data/vocabulary/legal_vocab_processed.txt', type=str)
13
+ args = parser.parse_args()
14
+
15
+ LOAD_PATH = args.load_path
16
+ SAVE_DIR = args.save_dir
17
+ VOC_PATH = args.voc_path
18
+
19
+ # Load pre-trained llama tokenizer and sentencepiece model
20
+ llama_spm = model.ModelProto()
21
+ llama_spm.ParseFromString(open(LOAD_PATH, "rb").read())
22
+
23
+ # show size of llama's vocabulary
24
+ llama_spm_tokens_set = set(p.piece for p in llama_spm.pieces)
25
+ print(f"Size of initial llama's vocabulary: {len(llama_spm_tokens_set)}")
26
+
27
+ # Load custom vocabulary
28
+ new_tokens = open(VOC_PATH, "r").read().split("\n")
29
+ for token in new_tokens:
30
+ if token not in llama_spm_tokens_set:
31
+ new_token = model.ModelProto().SentencePiece()
32
+ new_token.piece = token
33
+ new_token.score = 0
34
+ llama_spm.pieces.append(new_token)
35
+ print(f"Size of merged llama's vocabulary: {len(llama_spm.pieces)}")
36
+
37
+ # save
38
+ os.makedirs(SAVE_DIR, exist_ok=True)
39
+ SAVE_MODEL_PATH = os.path.join(SAVE_DIR, 'tokenizer.model')
40
+ SAVE_VOCAB_PATH = os.path.join(SAVE_DIR, 'tokenizer.vocab')
41
+ with open(SAVE_MODEL_PATH, 'wb') as f:
42
+ f.write(llama_spm.SerializeToString())
43
+ with open(SAVE_VOCAB_PATH, 'w') as f:
44
+ f.writelines([f'{token.piece} {token.score}\n' for token in llama_spm.pieces])
45
+ tokenizer = LlamaTokenizer(SAVE_MODEL_PATH)
46
+ tokenizer.save_pretrained(SAVE_DIR)
47
+ print(f'New llama tokenizer and spm has been saved to {SAVE_DIR}')
48
+
49
+ # test
50
+ llama_tokenizer_old = LlamaTokenizer.from_pretrained(LOAD_PATH)
51
+ llama_tokenizer_new = LlamaTokenizer.from_pretrained(SAVE_DIR)
52
+ text = '''็™ป่ฎฐ้”™่ฏฏ่ต”ๅฟ่ดฃไปป็™ป่ฎฐ็ญ‰ๆ‰‹็ปญ็™ป่ฎฐ็ญ‰ๆ‰‹็ปญ็”Ÿๆ•ˆ็™ป่ฎฐๆœบๆž„ๅ’Œ็™ป่ฎฐๅŠžๆณ•็™ป่ฎฐๆœบๆž„่ต”ๅฟๅŽ็™ป่ฎฐๆœบๆž„ๅบ”ๅฝ“ๆไพ›็™ป่ฎฐๆ”ถ่ดน้—ฎ้ข˜'''
53
+
54
+ print(f'Size of old vocabulary: {llama_tokenizer_old.vocab_size}')
55
+ print(f'Size of new vocabulary: {llama_tokenizer_new.vocab_size}')
56
+ print('All special tokens and ids in new llama:')
57
+ print(llama_tokenizer_new.all_special_tokens)
58
+ print(llama_tokenizer_new.all_special_ids)
59
+ print(llama_tokenizer_new.special_tokens_map)
60
+
61
+ print(f'Text:\n{text}')
62
+ print(f'Tokenized by LLaMA tokenizer:\n {llama_tokenizer_old.tokenize(text)}')
63
+ print(f'Tokenized by NEW LLaMA tokenizer:\n {llama_tokenizer_new.tokenize(text)}')
train_clm.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from typing import List
4
+
5
+ import fire
6
+ import torch
7
+ import transformers
8
+ from datasets import load_dataset
9
+
10
+ from peft import (
11
+ LoraConfig,
12
+ get_peft_model,
13
+ get_peft_model_state_dict,
14
+ prepare_model_for_int8_training,
15
+ set_peft_model_state_dict,
16
+ )
17
+ from transformers import LlamaForCausalLM, LlamaTokenizer
18
+ from utils.prompter import Prompter
19
+
20
+
21
+ def train(
22
+ # model/data params
23
+ base_model: str = "./models/base_models/your_base_model_dir",
24
+ data_path: str = "./data/your_data.json",
25
+ output_dir: str = "./outputs/your_version_dir",
26
+
27
+ # training hyperparams
28
+ batch_size: int = 128,
29
+ micro_batch_size: int = 4,
30
+ num_epochs: int = 10,
31
+ learning_rate: float = 3e-4,
32
+ cutoff_len: int = 512,
33
+ val_set_size: int = 2000,
34
+
35
+ # lora hyperparams
36
+ lora_r: int = 8,
37
+ lora_alpha: int = 16,
38
+ lora_dropout: float = 0.05,
39
+ lora_target_modules: List[str] = ["q_proj", "v_proj",],
40
+
41
+ # llm hyperparams
42
+ train_on_inputs: bool = True, # if False, masks out inputs in loss
43
+ add_eos_token: bool = True,
44
+ group_by_length: bool = False, # faster, but produces an odd training loss curve
45
+
46
+ # wandb params
47
+ wandb_project: str = "",
48
+ wandb_run_name: str = "",
49
+ wandb_watch: str = "", # options: false | gradients | all
50
+ wandb_log_model: str = "", # options: false | true
51
+
52
+ # either training checkpoint or final adapter
53
+ resume_from_checkpoint: str = None,
54
+
55
+ # The prompt template to use, will default to alpaca.
56
+ prompt_template_name: str = "alpaca",
57
+ ):
58
+ if int(os.environ.get("LOCAL_RANK", 0)) == 0:
59
+ print(
60
+ f"Training Alpaca-LoRA model with params:\n"
61
+ f"base_model: {base_model}\n"
62
+ f"data_path: {data_path}\n"
63
+ f"output_dir: {output_dir}\n"
64
+ f"batch_size: {batch_size}\n"
65
+ f"micro_batch_size: {micro_batch_size}\n"
66
+ f"num_epochs: {num_epochs}\n"
67
+ f"learning_rate: {learning_rate}\n"
68
+ f"cutoff_len: {cutoff_len}\n"
69
+ f"val_set_size: {val_set_size}\n"
70
+ f"lora_r: {lora_r}\n"
71
+ f"lora_alpha: {lora_alpha}\n"
72
+ f"lora_dropout: {lora_dropout}\n"
73
+ f"lora_target_modules: {lora_target_modules}\n"
74
+ f"train_on_inputs: {train_on_inputs}\n"
75
+ f"add_eos_token: {add_eos_token}\n"
76
+ f"group_by_length: {group_by_length}\n"
77
+ f"wandb_project: {wandb_project}\n"
78
+ f"wandb_run_name: {wandb_run_name}\n"
79
+ f"wandb_watch: {wandb_watch}\n"
80
+ f"wandb_log_model: {wandb_log_model}\n"
81
+ f"resume_from_checkpoint: {resume_from_checkpoint or False}\n"
82
+ f"prompt template: {prompt_template_name}\n"
83
+ )
84
+ gradient_accumulation_steps = batch_size // micro_batch_size
85
+
86
+ prompter = Prompter(prompt_template_name)
87
+
88
+ # Configure device and distributed training
89
+ device_map = "auto"
90
+ world_size = int(os.environ.get("WORLD_SIZE", 1))
91
+ ddp = world_size != 1
92
+ if ddp:
93
+ device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)}
94
+ gradient_accumulation_steps = gradient_accumulation_steps // world_size
95
+
96
+ # Check if parameter passed or if set within environ
97
+ use_wandb = len(wandb_project) > 0 or (
98
+ "WANDB_PROJECT" in os.environ and len(os.environ["WANDB_PROJECT"]) > 0)
99
+
100
+ # Only overwrite environ if wandb param passed
101
+ if len(wandb_project) > 0:
102
+ os.environ["WANDB_PROJECT"] = wandb_project
103
+ if len(wandb_watch) > 0:
104
+ os.environ["WANDB_WATCH"] = wandb_watch
105
+ if len(wandb_log_model) > 0:
106
+ os.environ["WANDB_LOG_MODEL"] = wandb_log_model
107
+
108
+ model = LlamaForCausalLM.from_pretrained(
109
+ base_model,
110
+ load_in_8bit=True,
111
+ torch_dtype=torch.float16,
112
+ device_map=device_map,
113
+ )
114
+
115
+ tokenizer = LlamaTokenizer.from_pretrained(base_model)
116
+ tokenizer.bos_token_id = 1
117
+ tokenizer.eos_token_id = 2
118
+ bos = tokenizer.bos_token_id
119
+ eos = tokenizer.eos_token_id
120
+ pad = tokenizer.pad_token_id
121
+
122
+ print("pre-trained model's BOS EOS and PAD token id:",
123
+ bos, eos, pad, " => It should be 1,2,none")
124
+
125
+ tokenizer.pad_token_id = (
126
+ 0 # unk. we want this to be different from the eos token
127
+ )
128
+ tokenizer.padding_side = "left" # Allow batched inference
129
+
130
+ def tokenize(prompt, add_eos_token=True):
131
+ # there's probably a way to do this with the tokenizer settings
132
+ # but again, gotta move fast
133
+ result = tokenizer(
134
+ prompt,
135
+ truncation=True,
136
+ max_length=cutoff_len,
137
+ padding=False,
138
+ return_tensors=None,
139
+ )
140
+ if (
141
+ result["input_ids"][-1] != tokenizer.eos_token_id
142
+ and len(result["input_ids"]) < cutoff_len
143
+ and add_eos_token
144
+ ):
145
+ result["input_ids"].append(tokenizer.eos_token_id)
146
+ result["attention_mask"].append(1)
147
+
148
+ result["labels"] = result["input_ids"].copy()
149
+
150
+ return result
151
+
152
+ def generate_and_tokenize_prompt(data_point):
153
+ text = data_point['content']
154
+ tokenized_full_prompt = tokenize(text)
155
+ return tokenized_full_prompt
156
+
157
+ model = prepare_model_for_int8_training(model)
158
+
159
+ config = LoraConfig(
160
+ r=lora_r,
161
+ lora_alpha=lora_alpha,
162
+ target_modules=lora_target_modules,
163
+ lora_dropout=lora_dropout,
164
+ bias="none",
165
+ task_type="CAUSAL_LM",
166
+ )
167
+ model = get_peft_model(model, config)
168
+
169
+ if data_path.endswith(".json") or data_path.endswith(".jsonl"):
170
+ data = load_dataset("json", data_files=data_path)
171
+ else:
172
+ data = load_dataset(data_path)
173
+
174
+ if resume_from_checkpoint:
175
+ # Check the available weights and load them
176
+ checkpoint_name = os.path.join(
177
+ resume_from_checkpoint, "pytorch_model.bin"
178
+ ) # Full checkpoint
179
+ if not os.path.exists(checkpoint_name):
180
+ checkpoint_name = os.path.join(
181
+ resume_from_checkpoint, "adapter_model.bin"
182
+ ) # only LoRA model - LoRA config above has to fit
183
+ resume_from_checkpoint = (
184
+ False # So the trainer won't try loading its state
185
+ )
186
+ # The two files above have a different name depending on how they were saved, but are actually the same.
187
+ if os.path.exists(checkpoint_name):
188
+ print(f"Restarting from {checkpoint_name}")
189
+ adapters_weights = torch.load(checkpoint_name)
190
+ set_peft_model_state_dict(model, adapters_weights)
191
+ else:
192
+ print(f"Checkpoint {checkpoint_name} not found")
193
+
194
+ # Be more transparent about the % of trainable params.
195
+ model.print_trainable_parameters()
196
+
197
+ if val_set_size > 0:
198
+ train_val = data["train"].train_test_split(test_size=val_set_size, shuffle=True, seed=42)
199
+ train_data = (train_val["train"].shuffle().map(generate_and_tokenize_prompt))
200
+ val_data = (train_val["test"].shuffle().map(generate_and_tokenize_prompt))
201
+ else:
202
+ train_data = data["train"].shuffle().map(generate_and_tokenize_prompt)
203
+ val_data = None
204
+
205
+ if not ddp and torch.cuda.device_count() > 1:
206
+ # keeps Trainer from trying its own DataParallelism when more than 1 gpu is available
207
+ model.is_parallelizable = True
208
+ model.model_parallel = True
209
+
210
+ trainer = transformers.Trainer(
211
+ model=model,
212
+ train_dataset=train_data,
213
+ eval_dataset=val_data,
214
+ args=transformers.TrainingArguments(
215
+ per_device_train_batch_size=micro_batch_size,
216
+ gradient_accumulation_steps=gradient_accumulation_steps,
217
+ warmup_steps=100,
218
+ num_train_epochs=num_epochs,
219
+ learning_rate=learning_rate,
220
+ fp16=True,
221
+ logging_steps=10,
222
+ optim="adamw_torch",
223
+ evaluation_strategy="steps" if val_set_size > 0 else "no",
224
+ save_strategy="steps",
225
+ eval_steps=100 if val_set_size > 0 else None,
226
+ save_steps=100,
227
+ output_dir=output_dir,
228
+ save_total_limit=3,
229
+ load_best_model_at_end=True if val_set_size > 0 else False,
230
+ ddp_find_unused_parameters=False if ddp else None,
231
+ group_by_length=group_by_length,
232
+ report_to="wandb" if use_wandb else None,
233
+ run_name=wandb_run_name if use_wandb else None,
234
+ ),
235
+ data_collator=transformers.DataCollatorForSeq2Seq(
236
+ tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
237
+ ),
238
+ )
239
+ model.config.use_cache = False
240
+
241
+ old_state_dict = model.state_dict
242
+ model.state_dict = (
243
+ lambda self, *_, **__: get_peft_model_state_dict(
244
+ self, old_state_dict()
245
+ )
246
+ ).__get__(model, type(model))
247
+
248
+ if torch.__version__ >= "2" and sys.platform != "win32":
249
+ model = torch.compile(model)
250
+
251
+ trainer.train(resume_from_checkpoint=resume_from_checkpoint)
252
+
253
+ model.save_pretrained(output_dir)
254
+
255
+ print("\n If there's a warning about missing keys above, please disregard :)")
256
+
257
+
258
+ if __name__ == "__main__":
259
+ fire.Fire(train)
utils/__init__.py ADDED
File without changes
utils/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (131 Bytes). View file
 
utils/__pycache__/callbacks.cpython-38.pyc ADDED
Binary file (2.65 kB). View file
 
utils/__pycache__/prompter.cpython-38.pyc ADDED
Binary file (1.61 kB). View file
 
utils/callbacks.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helpers to support streaming generate output.
3
+ Borrowed from https://github.com/oobabooga/text-generation-webui/blob/ad37f396fc8bcbab90e11ecf17c56c97bfbd4a9c/modules/callbacks.py
4
+ """
5
+
6
+ import gc
7
+ import traceback
8
+ from queue import Queue
9
+ from threading import Thread
10
+
11
+ import torch
12
+ import transformers
13
+
14
+
15
+ class Stream(transformers.StoppingCriteria):
16
+ def __init__(self, callback_func=None):
17
+ self.callback_func = callback_func
18
+
19
+ def __call__(self, input_ids, scores) -> bool:
20
+ if self.callback_func is not None:
21
+ self.callback_func(input_ids[0])
22
+ return False
23
+
24
+
25
+ class Iteratorize:
26
+
27
+ """
28
+ Transforms a function that takes a callback
29
+ into a lazy iterator (generator).
30
+ """
31
+
32
+ def __init__(self, func, kwargs={}, callback=None):
33
+ self.mfunc = func
34
+ self.c_callback = callback
35
+ self.q = Queue()
36
+ self.sentinel = object()
37
+ self.kwargs = kwargs
38
+ self.stop_now = False
39
+
40
+ def _callback(val):
41
+ if self.stop_now:
42
+ raise ValueError
43
+ self.q.put(val)
44
+
45
+ def gentask():
46
+ try:
47
+ ret = self.mfunc(callback=_callback, **self.kwargs)
48
+ except ValueError:
49
+ pass
50
+ except:
51
+ traceback.print_exc()
52
+ pass
53
+
54
+ self.q.put(self.sentinel)
55
+ if self.c_callback:
56
+ self.c_callback(ret)
57
+
58
+ self.thread = Thread(target=gentask)
59
+ self.thread.start()
60
+
61
+ def __iter__(self):
62
+ return self
63
+
64
+ def __next__(self):
65
+ obj = self.q.get(True, None)
66
+ if obj is self.sentinel:
67
+ raise StopIteration
68
+ else:
69
+ return obj
70
+
71
+ def __enter__(self):
72
+ return self
73
+
74
+ def __exit__(self, exc_type, exc_val, exc_tb):
75
+ self.stop_now = True
utils/evaluate.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import sys
4
+
5
+ import fire
6
+ from tqdm import tqdm
7
+ import pandas as pd
8
+ import torch
9
+ import transformers
10
+ from peft import PeftModel
11
+ import datasets
12
+ from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer
13
+
14
+ from utils.callbacks import Iteratorize, Stream
15
+ from utils.prompter import Prompter
16
+
17
+ device = "cuda"
18
+
19
+
20
+ def main(
21
+ load_8bit: bool = True,
22
+ base_model: str = "decapoda-research/llama-7b-hf",
23
+ lora_weights: str = "./lora-alpaca",
24
+ data_path: str = "./data",
25
+ output_path: str = "./output",
26
+ eval_rate: float = 0.1,
27
+ batch_size: int = 32,
28
+ # The prompt template to use, will default to alpaca.
29
+ prompt_template: str = "alpaca",
30
+ ):
31
+ base_model = base_model or os.environ.get("BASE_MODEL", "")
32
+ assert (base_model), "Please specify a --base_model, e.g. --base_model='huggyllama/llama-7b'"
33
+
34
+ prompter = Prompter(prompt_template)
35
+ tokenizer = LlamaTokenizer.from_pretrained(base_model)
36
+ if device == "cuda":
37
+ model = LlamaForCausalLM.from_pretrained(
38
+ base_model,
39
+ load_in_8bit=load_8bit,
40
+ torch_dtype=torch.float16,
41
+ device_map="auto",
42
+ )
43
+ model = PeftModel.from_pretrained(
44
+ model,
45
+ lora_weights,
46
+ torch_dtype=torch.float16,
47
+ )
48
+
49
+ # unwind broken decapoda-research config
50
+ model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk
51
+ model.config.bos_token_id = 1
52
+ model.config.eos_token_id = 2
53
+
54
+ if not load_8bit:
55
+ model.half() # seems to fix bugs for some users.
56
+
57
+ model.eval()
58
+ if torch.__version__ >= "2" and sys.platform != "win32":
59
+ model = torch.compile(model)
60
+
61
+ def evaluate_one(
62
+ instruction,
63
+ input=None,
64
+ temperature=0.1,
65
+ top_p=0.75,
66
+ top_k=40,
67
+ num_beams=2,
68
+ max_new_tokens=128,
69
+ **kwargs,
70
+ ):
71
+ prompt = prompter.generate_prompt(instruction, input)
72
+ inputs = tokenizer(prompt, return_tensors="pt")
73
+ input_ids = inputs["input_ids"].to(device)
74
+ generation_config = GenerationConfig(
75
+ temperature=temperature,
76
+ top_p=top_p,
77
+ top_k=top_k,
78
+ num_beams=num_beams,
79
+ **kwargs,
80
+ )
81
+
82
+ # Without streaming
83
+ with torch.no_grad():
84
+ generation_output = model.generate(
85
+ input_ids=input_ids,
86
+ generation_config=generation_config,
87
+ return_dict_in_generate=True,
88
+ output_scores=True,
89
+ max_new_tokens=max_new_tokens,
90
+ )
91
+ s = generation_output.sequences[0]
92
+ output = tokenizer.decode(s, skip_special_tokens=True)
93
+ return prompter.get_response(output)
94
+
95
+ def evaluate_all():
96
+ # data = datasets.load_dataset("json", data_files=data_path)
97
+ # data = data["train"]
98
+ # df = data.to_pandas()
99
+ df = pd.read_json(data_path, orient='records')
100
+ print(df.info())
101
+ # ่ฎก็ฎ—ๅ‡†็กฎ็Ž‡
102
+ correct = 0
103
+ total = 0
104
+ total_step = len(df)
105
+ pbar = tqdm(total=total_step, unit='batch')
106
+ error = []
107
+ for i in range(total_step):
108
+ instruction = df['instruction'].iloc[i]
109
+ input = df['input'].iloc[i]
110
+ label = df['output'].iloc[i]
111
+ pred = evaluate_one(instruction=instruction, input=input)
112
+ if pred == label:
113
+ correct += 1
114
+ else:
115
+ error.append((label, pred))
116
+ total += 1
117
+ acc = correct / total
118
+ # ๆ›ดๆ–ฐ่ฟ›ๅบฆๆก
119
+ # Update the progress bar
120
+ pbar.set_description(
121
+ f"Testing: Sample [{total}/{total_step}] Acc: {acc :.4f}")
122
+ pbar.update(1)
123
+
124
+ for e in error:
125
+ print(e)
126
+
127
+ def evaluate_by_batch(
128
+ temperature=0.1,
129
+ top_p=0.75,
130
+ top_k=40,
131
+ num_beams=1,
132
+ max_new_tokens=32
133
+ ):
134
+ df = pd.read_json(data_path, orient='records')
135
+ # df = df.sample(frac=eval_rate).reset_index(drop=True)
136
+ df['prompt'] = df.apply(lambda x: prompter.generate_prompt(
137
+ x['instruction'], x['input']), axis=1)
138
+ tokenizer.padding_side = "left" # Allow batched inference
139
+
140
+ generation_config = GenerationConfig(
141
+ temperature=temperature,
142
+ top_p=top_p,
143
+ top_k=top_k,
144
+ num_beams=num_beams
145
+ )
146
+
147
+ outputs = []
148
+ total = 0
149
+ total_step = math.ceil(len(df) / batch_size)
150
+ pbar = tqdm(total=total_step, unit='batch')
151
+ # ่ฎก็ฎ—ๅ‡†็กฎ็Ž‡
152
+ with torch.no_grad():
153
+ for i in range(total_step):
154
+ batch = df.iloc[i*batch_size:(i+1)*batch_size]
155
+ inputs = tokenizer(batch['prompt'].tolist(), return_tensors="pt", padding=True)[
156
+ 'input_ids'].to(device)
157
+
158
+ generation_outputs = model.generate(
159
+ input_ids=inputs,
160
+ generation_config=generation_config,
161
+ max_new_tokens=max_new_tokens,
162
+ pad_token_id=tokenizer.pad_token_id
163
+ )
164
+
165
+ for g in generation_outputs:
166
+ decoded_item = tokenizer.decode(
167
+ g, skip_special_tokens=True)
168
+ try:
169
+ output = prompter.get_response(decoded_item)
170
+ except:
171
+ output = decoded_item
172
+ outputs.append(output)
173
+ total += 1
174
+
175
+ # ๆ›ดๆ–ฐ่ฟ›ๅบฆๆก
176
+ pbar.set_description(f"Testing: Sample [{total}/{len(df)}] ")
177
+ pbar.update(1)
178
+ df['pred'] = outputs
179
+ df['pred'].to_csv(output_path, index=False)
180
+
181
+ evaluate_by_batch()
182
+
183
+
184
+ if __name__ == "__main__":
185
+ # fire.Fire(main)
186
+ import yaml
187
+ dataset_param = sys.argv[1]
188
+ with open("./configs/evaluate_params.yaml", "r") as stream:
189
+ # try:
190
+ params = yaml.safe_load(stream)
191
+ print('=' * 80)
192
+ print(params[dataset_param])
193
+ print('=' * 80)
194
+
195
+ # fire.Fire(train)
196
+ main(**params[dataset_param])
utils/merge.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ import transformers
5
+ from peft import PeftModel
6
+ from transformers import LlamaForCausalLM, LlamaTokenizer # noqa: F402
7
+
8
+ BASE_MODEL = os.environ.get("BASE_MODEL", None)
9
+ assert (
10
+ BASE_MODEL
11
+ ), "Please specify a value for BASE_MODEL environment variable, e.g. `export BASE_MODEL=huggyllama/llama-7b`" # noqa: E501
12
+
13
+ tokenizer = LlamaTokenizer.from_pretrained(BASE_MODEL)
14
+
15
+ base_model = LlamaForCausalLM.from_pretrained(
16
+ BASE_MODEL,
17
+ load_in_8bit=False,
18
+ torch_dtype=torch.float16,
19
+ device_map={"": "cpu"},
20
+ )
21
+
22
+ first_weight = base_model.model.layers[0].self_attn.q_proj.weight
23
+ first_weight_old = first_weight.clone()
24
+
25
+ lora_model = PeftModel.from_pretrained(
26
+ base_model,
27
+ "../outputs/lora-llama-clm-e2",
28
+ device_map={"": "cpu"},
29
+ torch_dtype=torch.float16,
30
+ )
31
+
32
+ lora_weight = lora_model.base_model.model.model.layers[0].self_attn.q_proj.weight
33
+
34
+ assert torch.allclose(first_weight_old, first_weight)
35
+
36
+ # merge weights - new merging method from peft
37
+ lora_model = lora_model.merge_and_unload()
38
+
39
+ lora_model.train(False)
40
+
41
+ # did we do anything?
42
+ assert not torch.allclose(first_weight_old, first_weight)
43
+
44
+ lora_model_sd = lora_model.state_dict()
45
+ deloreanized_sd = {
46
+ k.replace("base_model.model.", ""): v
47
+ for k, v in lora_model_sd.items()
48
+ if "lora" not in k
49
+ }
50
+
51
+ LlamaForCausalLM.save_pretrained(base_model, '../models/legal-base-7b', state_dict=deloreanized_sd, max_shard_size="400MB")
utils/prompter.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A dedicated helper to manage templates and prompt building.
3
+ """
4
+
5
+ import json
6
+ import os.path as osp
7
+ from typing import Union
8
+
9
+
10
+ class Prompter(object):
11
+ __slots__ = ("template", "_verbose")
12
+
13
+ def __init__(self, template_name: str = "", verbose: bool = False):
14
+ self._verbose = verbose
15
+ if not template_name:
16
+ # Enforce the default here, so the constructor can be called with '' and will not break.
17
+ template_name = "alpaca"
18
+ file_name = osp.join("templates", f"{template_name}.json")
19
+ if not osp.exists(file_name):
20
+ raise ValueError(f"Can't read {file_name}")
21
+ with open(file_name) as fp:
22
+ self.template = json.load(fp)
23
+ if self._verbose:
24
+ print(
25
+ f"Using prompt template {template_name}: {self.template['description']}"
26
+ )
27
+
28
+ def generate_prompt(
29
+ self,
30
+ instruction: str,
31
+ input: Union[None, str] = None,
32
+ label: Union[None, str] = None,
33
+ ) -> str:
34
+ # returns the full prompt from instruction and optional input
35
+ # if a label (=response, =output) is provided, it's also appended.
36
+ if input:
37
+ res = self.template["prompt_input"].format(
38
+ instruction=instruction, input=input
39
+ )
40
+ else:
41
+ res = self.template["prompt_no_input"].format(
42
+ instruction=instruction
43
+ )
44
+ if label:
45
+ res = f"{res}{label}"
46
+ if self._verbose:
47
+ print(res)
48
+ return res
49
+
50
+ def get_response(self, output: str) -> str:
51
+ return output.split(self.template["response_split"])[1].strip()
webui.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ import fire
5
+ import gradio as gr
6
+ import torch
7
+ import transformers
8
+ from peft import PeftModel
9
+ from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer, AutoModel, AutoTokenizer, AutoModelForCausalLM,AutoConfig
10
+
11
+ from utils.callbacks import Iteratorize, Stream
12
+ from utils.prompter import Prompter
13
+
14
+ # if torch.cuda.is_available():
15
+ # device = "cuda"
16
+ # else:
17
+ # device = "cpu"
18
+
19
+ # try:
20
+ # if torch.backends.mps.is_available():
21
+ # device = "mps"
22
+ # except:
23
+ # pass
24
+
25
+ device = "xpu"
26
+
27
+
28
+ def main(
29
+ load_8bit: bool = False,
30
+ base_model: str = "",
31
+ lora_weights: str = "",
32
+ prompt_template: str = "", # The prompt template to use, will default to alpaca.
33
+ server_name: str = "0.0.0.0", # Allows to listen on all interfaces by providing '0.
34
+ share_gradio: bool = False,
35
+ ):
36
+ base_model = base_model or os.environ.get("BASE_MODEL", "")
37
+ assert (
38
+ base_model
39
+ ), "Please specify a --base_model, e.g. --base_model='huggyllama/llama-7b'"
40
+
41
+ prompter = Prompter(prompt_template)
42
+ tokenizer = LlamaTokenizer.from_pretrained(base_model)
43
+ prompter = Prompter(prompt_template)
44
+ tokenizer = LlamaTokenizer.from_pretrained(base_model)
45
+ config = AutoConfig.from_pretrained(base_model)
46
+ model = AutoModelForCausalLM.from_pretrained(
47
+ base_model,
48
+ config=config,
49
+ load_in_8bit=load_8bit,
50
+ torch_dtype=torch.float16,
51
+ device_map="auto",
52
+ )
53
+
54
+ try:
55
+ print(f"Using lora {lora_weights}")
56
+ model = PeftModel.from_pretrained(
57
+ model,
58
+ lora_weights,
59
+ torch_dtype=torch.float16,
60
+ )
61
+ except:
62
+ print("*"*50, "\n Attention! No Lora Weights \n", "*"*50)
63
+
64
+ # unwind broken decapoda-research config
65
+ model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk
66
+ model.config.bos_token_id = 1
67
+ model.config.eos_token_id = 2
68
+
69
+ # if not load_8bit:
70
+ # model.half() # seems to fix bugs for some users.
71
+
72
+ model.eval()
73
+ if torch.__version__ >= "2" and sys.platform != "win32":
74
+ model = torch.compile(model)
75
+
76
+ def evaluate(
77
+ instruction,
78
+ # input=None,
79
+ temperature=0.1,
80
+ top_p=0.75,
81
+ top_k=40,
82
+ num_beams=4,
83
+ max_new_tokens=128,
84
+ stream_output=False,
85
+ **kwargs,
86
+ ):
87
+ input=None
88
+ prompt = prompter.generate_prompt(instruction, input)
89
+ inputs = tokenizer(prompt, return_tensors="pt")
90
+ input_ids = inputs["input_ids"].to(device)
91
+ generation_config = GenerationConfig(
92
+ temperature=temperature,
93
+ top_p=top_p,
94
+ top_k=top_k,
95
+ num_beams=num_beams,
96
+ **kwargs,
97
+ )
98
+
99
+ generate_params = {
100
+ "input_ids": input_ids,
101
+ "generation_config": generation_config,
102
+ "return_dict_in_generate": True,
103
+ "output_scores": True,
104
+ "max_new_tokens": max_new_tokens,
105
+ }
106
+
107
+ if stream_output:
108
+ # Stream the reply 1 token at a time.
109
+ # This is based on the trick of using 'stopping_criteria' to create an iterator,
110
+ # from https://github.com/oobabooga/text-generation-webui/blob/ad37f396fc8bcbab90e11ecf17c56c97bfbd4a9c/modules/text_generation.py#L216-L243.
111
+
112
+ def generate_with_callback(callback=None, **kwargs):
113
+ kwargs.setdefault(
114
+ "stopping_criteria", transformers.StoppingCriteriaList()
115
+ )
116
+ kwargs["stopping_criteria"].append(
117
+ Stream(callback_func=callback)
118
+ )
119
+ with torch.no_grad():
120
+ model.generate(**kwargs)
121
+
122
+ def generate_with_streaming(**kwargs):
123
+ return Iteratorize(
124
+ generate_with_callback, kwargs, callback=None
125
+ )
126
+
127
+ with generate_with_streaming(**generate_params) as generator:
128
+ for output in generator:
129
+ # new_tokens = len(output) - len(input_ids[0])
130
+ decoded_output = tokenizer.decode(output)
131
+
132
+ if output[-1] in [tokenizer.eos_token_id]:
133
+ break
134
+
135
+ yield prompter.get_response(decoded_output)
136
+ print(decoded_output)
137
+ return # early return for stream_output
138
+
139
+ # Without streaming
140
+ with torch.no_grad():
141
+ generation_output = model.generate(
142
+ input_ids=input_ids,
143
+ generation_config=generation_config,
144
+ return_dict_in_generate=True,
145
+ output_scores=True,
146
+ max_new_tokens=max_new_tokens,
147
+ )
148
+ s = generation_output.sequences[0]
149
+ output = tokenizer.decode(s)
150
+ print(output)
151
+ yield prompter.get_response(output)
152
+
153
+ gr.Interface(
154
+ fn=evaluate,
155
+ inputs=[
156
+ gr.components.Textbox(
157
+ lines=2,
158
+ label="Instruction",
159
+ placeholder="ๆญคๅค„่พ“ๅ…ฅๆณ•ๅพ‹็›ธๅ…ณ้—ฎ้ข˜",
160
+ ),
161
+ # gr.components.Textbox(lines=2, label="Input", placeholder="none"),
162
+ gr.components.Slider(
163
+ minimum=0, maximum=1, value=0.1, label="Temperature"
164
+ ),
165
+ gr.components.Slider(
166
+ minimum=0, maximum=1, value=0.75, label="Top p"
167
+ ),
168
+ gr.components.Slider(
169
+ minimum=0, maximum=100, step=1, value=40, label="Top k"
170
+ ),
171
+ gr.components.Slider(
172
+ minimum=1, maximum=4, step=1, value=1, label="Beams"
173
+ ),
174
+ gr.components.Slider(
175
+ minimum=1, maximum=2000, step=1, value=256, label="Max tokens"
176
+ ),
177
+ gr.components.Checkbox(label="Stream output", value=True),
178
+ ],
179
+ outputs=[
180
+ gr.inputs.Textbox(
181
+ lines=8,
182
+ label="Output",
183
+ )
184
+ ],
185
+ title="๐Ÿฆ™๐ŸŒฒ LaWGPT",
186
+ description="",
187
+ ).queue().launch(server_name="0.0.0.0", share=share_gradio)
188
+
189
+
190
+ if __name__ == "__main__":
191
+ fire.Fire(main)