fasdfsa commited on
Commit
b65604f
·
1 Parent(s): 4c0402d
Files changed (6) hide show
  1. LICENSE +674 -0
  2. README.md +175 -0
  3. main.py +37 -0
  4. readme.txt +6 -0
  5. rosaplus.py +746 -0
  6. tinyshakespeare.txt +0 -0
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 ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ROSA+
2
+ **ROSA+**: RWKV's ROSA implementation with fallback statistical predictor
3
+ <hr/>
4
+ <img width="700" alt="image" src="https://github.com/user-attachments/assets/606a4d61-87b8-4bfc-ac27-564528042605" />
5
+ <hr/>
6
+
7
+ ## What is ROSA+?
8
+ **ROSA+** is an extension of the **statistical next-token predictor** [proposed by BlinkDL](https://x.com/BlinkDL_AI/status/1976912771985146184) in extending the RWKV language model. It provides an intuitive Python interface as well as a fallback Witten–Bell predictor for unknown sequences.
9
+
10
+ ## Example Usage in Python
11
+ The implementation is self-contained in `rosaplus.py`. You can download the repository and use it from there.
12
+
13
+ ```python
14
+ # example.py
15
+ from rosaplus import ROSAPlus
16
+ import requests
17
+
18
+ # Train on Shakespare
19
+ url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
20
+
21
+ # Download the text
22
+ response = requests.get(url)
23
+ text = response.text
24
+ print("Downloaded text.")
25
+
26
+ # Initialize model
27
+ m = ROSAPlus(max_order=1048576, use_eot=False, seed=0)
28
+ m.train_example(text) # Train ROSA
29
+ m.build_lm() # Train fallback predictor
30
+
31
+ # Prompting
32
+ prompt = "ROMEO:" # Novel text
33
+ max_tokens = 256
34
+
35
+ # Eval mode
36
+ print(prompt + m.generate(prompt, steps=max_tokens))
37
+
38
+ # Saving model
39
+ m.save("rosa-model.json")
40
+ m2 = ROSAPlus.load("rosa-model.json") # Loading model
41
+ ```
42
+
43
+ **Output:** (verbatim)
44
+ ```
45
+ ROMEO:
46
+ In faith, I will. Let me peruse this face.
47
+ Mercutio's kinsman, noble County Paris!
48
+ What said my man, when my betossed soul
49
+ Did not attend him as we rode? I think
50
+ ...
51
+ ```
52
+
53
+ ## Novel Text Generation
54
+ ROSA+ can also be used to generate novel sequences that **do not show up in the training dataset.** You can enable this by **always** using the fallback predictor. It often leads to coherent, surprising results.
55
+ ```python
56
+ # add always_fallback=True to the example
57
+ print(prompt + m.generate(prompt, steps=max_tokens, always_fallback=True))
58
+ ```
59
+
60
+ **Output:** (novel)
61
+ ```
62
+ ROMEO:
63
+ The exchange of joy
64
+ That only Warwick's daughter.
65
+
66
+ CLARENCE:
67
+ To whom, my lord; the foe vantage.
68
+ But make you read no other, and look'd deadly that name remains;
69
+ The cruelty and envy of the people,
70
+ Permitted by our faces
71
+ For man or master; then it for some
72
+ ```
73
+
74
+ As you can see, these arrangement of sentences do not show up in the dataset (CTRL+F). Rather, ROSA+ intelligently splices and pulls together the features from ROSA to perform next-character prediction.
75
+
76
+ For any given prefix, you can also get the probability distribution for the next token:
77
+ ```python
78
+ # Eval mode
79
+ print(m.get_dist("ROMEO:\nOh, how could yo"))
80
+ ```
81
+
82
+ Output:
83
+ ```
84
+ {'u': 0.9999989177710094, 'n': 5.442332067424175e-07, 'k': 5.379892385443467e-07, 'r': 6.0439900862193395e-12, ' ...
85
+ ```
86
+
87
+ As you can see, ROSA+ is extremely confident that 'u' is the next token (and it is correct!)
88
+
89
+ ## RWKV Support
90
+ This is just a standalone example of ROSA and does not provide RWKV integration. You will have to go to the RWKV Discord or ask the main maintainer (BlinkDL) for assistance in this regard.
91
+
92
+ ## Extensions
93
+ ROSA+ extends ROSA by:
94
+
95
+ - Allowing training and sampling on individual sequences, similar to a LLM
96
+ - Utilizing a (coherent) fallback Witten–Bell based predictor for when ROSA is unsure of the next token.
97
+
98
+ This makes it extremely fast, since ROSA is used for 99% of the predictions and the fallback only occurs for novel sequences.
99
+
100
+ **Tokenization:** The default tokenization is character-based (I will add support for new tokenizers coming soon.)
101
+
102
+ ## Notes
103
+
104
+ If you install [orjson](https://github.com/ijl/orjson), it will use it automatically and lead to far faster import/export speed.
105
+ Docs coming soon.
106
+
107
+ ## Issues with ROSA+
108
+
109
+ ROSA+ is entirely statistical-based -- it extends upon the ROSA predictor proposed by BlinkDL, then provides a probability predictor as a fallback. However, this means it only has a **database-like** understanding of text -- it can **stitch together multiple sentences** and **demonstrate grammar**, but it lacks the same context understanding as an NN (RWKV, Transformer etc.)
110
+
111
+ For instance, when trained on Shakespeare, and with `always_fallback=True` (forcing novel predictions), it generates text that "looks right", but switches between characters every stanza.
112
+
113
+ ```
114
+ COMINIUS:
115
+ Well, one nail;
116
+ Right noble is thy mercy dried their watches of chance and thy lord's false love;
117
+ For both of you are birds of selfsame feather.
118
+
119
+ KING EDWARD IV:
120
+ Peace, wilful boy, or I will charm your tongue.
121
+
122
+ CLARENCE:
123
+ Unhappy fortune! by my troth, I looked upon his faith iron cook you, sir, he bid me knocks; ha! let me be unrolled and said 'The better for our purpose.'
124
+
125
+ KING RICHARD III:
126
+ So proud the name of Henry with your holy look'd on me,
127
+ And wouldst do not break your oaths; for of that sin
128
+ May deny her aiding have these nothing here.
129
+
130
+ AUTOLYCUS:
131
+ I hope so, sir; for I have about me manner doth accuse my husband, I
132
+ ...
133
+ ```
134
+
135
+ A ChatGPT analysis of ROSA+'s lines uncovers some insight:
136
+ ```
137
+ Short answer: it’s Shakespeare-flavored, not Shakespearean. It reads like a collage of misquoted or remixed lines, with scrambled idioms, mixed plays (Juliet/Romeo with Buckingham and Gaunt), and meter/grammar that don’t line up with blank verse.
138
+
139
+ Quick notes:
140
+
141
+ * “Now, by Saint Peter’s Church…” and “I have forgot why I did call thee back” echo *Romeo and Juliet*, but they’re spliced into new contexts.
142
+ * “The world goes his bonnet to an oystery” mangles Pistol’s “The world’s mine oyster.”
143
+ * Shifts between **you/thee/thou/thy** are inconsistent (use *thou* as subject, *thee* as object, *thy/thine* as possessives).
144
+ * Many lines don’t scan as iambic pentameter (10 syllables, mostly unstressed–stressed).
145
+ ```
146
+
147
+ A true NN-based model would outperform a standalone ROSA+ implementation because of the understanding of actual context. While ROSA+ has impressive surface-level understanding, it lacks deeper, low level meaning expressed by NNs.
148
+
149
+
150
+ ### Interesting occurences
151
+ You can view all the samples in the `samples` directory -- interestingly, in `sample_default_output.txt`, the model falls into an attractor state, repeating itself every ~3k lines, halfway through. However, in `sample_novel_output.txt`, you can spot some very novel sentences:
152
+ ```
153
+ LADY ANNE:
154
+ Well, well, peace be with you, sir, he bid me know the points o' the dead
155
+ May walk again: if such thing but what I am,
156
+ I would wish it gone,
157
+ ```
158
+
159
+ The phrases `Well, well, peace be with you` and `I would wish it gone` never show up in the training data.
160
+
161
+ ## Use cases
162
+ - Autocorrect / word prediction
163
+ - Translation (possibly)
164
+ - Features for a lower level model
165
+ - Generating surface-level text that fools detectors
166
+
167
+ ## Improving ROSA+
168
+ One may be able to create a coherent language model simply by feeding ROSA+ embeddings into a GRU. Since ROSA+ captures the immediate surface-level features of text, a sufficient neural network may be able to operate on these embeddings and alter the distribution for more fine-grained understanding.
169
+
170
+ ## Downsides of statistical LMs
171
+ Unless statistical LMs incorporate some kind of **statistical attention mechanism** (which is possible!) they will never be able to grasp a high-level understanding of text as do humans and LMs. A statistical LM is unable to **copy data / tokens from one place to another**, **operate on a continous state**, **blend together tokens across different spaces**, perform **few-shot learning** (needs neural mechanism!) or **transfer learning** (no state vectors!). Therefore, their purpose remains limited to grasping **surface-level** features of text, like syntax, or general structure.
172
+
173
+ Google pushed to make their translation software (which in the 2010s, was n-gram based) the best at the time, but even **LSTMs** (which were invented way before Transformers) managed to outperform them.
174
+
175
+ Do not let this discourage you though. It may be practical to incorporate some kind of **continous state vector / representation** within a statistical model, making it **drastically more efficient than LLMs** while preserving all the benefits of **NN-based models.** This is an active field of research at **Bellevue College ML** (BCML) -- and if pioneered, could result in language models thousands of times more efficient. Don't let an article discourage you.
main.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from rosaplus import ROSAPlus
2
+ # import requests
3
+
4
+ # # Train on Shakespare
5
+ # url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
6
+
7
+ # # Download the text
8
+ # response = requests.get(url)
9
+ # text = response.text
10
+ # print("Downloaded text.")
11
+
12
+
13
+ # m2 = ROSAPlus.load("rosa-model.json")
14
+ # prompt = "ROMEO:" # Novel text
15
+ # max_tokens = 256
16
+ # print(prompt + m2.generate(prompt, steps=max_tokens))
17
+
18
+
19
+
20
+ with open('tinyshakespeare.txt', "r", encoding='UTF-8') as f:
21
+ text = f.read()
22
+
23
+ # Initialize model
24
+ m = ROSAPlus(max_order=1048576, use_eot=False, seed=0)
25
+ m.train_example(text) # Train ROSA
26
+ m.build_lm() # Train fallback predictor
27
+
28
+ # Prompting
29
+ prompt = "ROMEO:" # Novel text
30
+ max_tokens = 256
31
+
32
+ # Eval mode
33
+ print(prompt + m.generate(prompt, steps=max_tokens))
34
+
35
+ # Saving model
36
+ m.save("rosa-model.json")
37
+ m2 = ROSAPlus.load("rosa-model.json") # Loading model
readme.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+
2
+ see https://github.com/zyaaa-ux/ROSA-Tuning
3
+
4
+
5
+
6
+
rosaplus.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ ROSA Plus v2 (character-level)
5
+ --------------------------------
6
+ A boundary-aware Suffix Automaton (SAM) with a probabilistic fallback LM
7
+ (Witten–Bell interpolation along suffix links). This module exposes a single
8
+ high-level class `ROSAPlus` and supporting classes that let you:
9
+
10
+ - Create a model object
11
+ - Train on individual samples (examples) *without* crossing boundaries
12
+ - Build the fallback LM (from accumulated examples) and keep the SAM frozen at inference
13
+ - Save/load a JSON model
14
+ - Provide a pre-existing context and:
15
+ * generate text (string) with sampling controls, or
16
+ * query the probability of the next character (or the full next-char distribution)
17
+
18
+ This is a modular split of the original script into a library you can import.
19
+ The companion CLI wrapper `rosa_plus_train.py` maintains the original flags.
20
+ """
21
+ from __future__ import annotations
22
+ from collections import deque
23
+ from typing import List, Optional, Dict, Tuple
24
+ from collections import defaultdict, Counter
25
+ import json as _stdlib_json
26
+ import math
27
+ import random
28
+
29
+ try:
30
+ import orjson as _json
31
+ _dumps = _json.dumps # returns bytes
32
+ _loads = _json.loads
33
+ except Exception: # pragma: no cover
34
+ # Fallback to stdlib json (slower, but keeps things working)
35
+ _json = _stdlib_json
36
+ _dumps = lambda obj: _stdlib_json.dumps(obj).encode("utf-8")
37
+ _loads = lambda b: _stdlib_json.loads(b.decode("utf-8"))
38
+
39
+ from tqdm import tqdm
40
+
41
+ __all__ = [
42
+ "load_examples_from_file",
43
+ "ROSACharPredictor",
44
+ "ROSAFallbackLM",
45
+ "ROSAPlus",
46
+ "ROSAGRUAdapter",
47
+ ]
48
+
49
+
50
+ # =========================
51
+ # 1) Load & split examples
52
+ # =========================
53
+
54
+ def load_examples_from_file(
55
+ path: str,
56
+ delimiter: str = "<|ENDOFTEXT|>",
57
+ strip_each: bool = True,
58
+ use_eot: bool = True,
59
+ eot_char: str = "\u0004", # single-char EOT (U+0004 by default)
60
+ ) -> List[str]:
61
+ """Reads a file, splits by `delimiter`, optional strip, drops empties.
62
+ If `use_eot`, appends a single-character EOT to each example.
63
+ """
64
+ if not isinstance(eot_char, str) or len(eot_char) != 1:
65
+ raise ValueError("eot_char must be a single character.")
66
+ with open(path, "r", encoding="utf-8") as f:
67
+ raw = f.read()
68
+ parts = raw.split(delimiter)
69
+ if strip_each:
70
+ parts = [p.strip() for p in parts]
71
+ parts = [p for p in parts if p]
72
+
73
+ if use_eot:
74
+ parts = [p + eot_char for p in parts]
75
+
76
+ return parts[:100000]
77
+
78
+
79
+ # =========================
80
+ # 2) Boundary-aware SAM
81
+ # =========================
82
+
83
+ class ROSACharPredictor:
84
+ """
85
+ Online/streaming SAM builder (ROSA core), boundary-aware.
86
+ Arrays:
87
+ - b: transitions (list[dict(char->next_state)])
88
+ - c: suffix links (list[int])
89
+ - d: max length (list[int])
90
+ - e: rightmost previous end position per state (list[int])
91
+ - g: last (active) state (int)
92
+ Additionally:
93
+ - text: list[str] training characters in sequence
94
+ - boundary_after[i] = True if an example boundary occurs immediately AFTER position i
95
+ """
96
+ def __init__(self):
97
+ self.b: List[Dict[str, int]] = [{}] # transitions
98
+ self.c: List[int] = [-1] # suffix links
99
+ self.d: List[int] = [0] # max length
100
+ self.e: List[int] = [-1] # rightmost previous indices
101
+ self.g: int = 0 # last state
102
+ self.text: List[str] = [] # stores training text characters
103
+ self.boundary_after: List[bool] = [] # boundary flags per char index
104
+
105
+ def feed(self, ch: str) -> None:
106
+ """Extend SAM with `ch` (training step). Deterministic prediction is computed at inference."""
107
+ i = len(self.text)
108
+ self.text.append(ch)
109
+ if len(self.boundary_after) < len(self.text):
110
+ self.boundary_after.append(False)
111
+
112
+ b, c, d, e, g = self.b, self.c, self.d, self.e, self.g
113
+
114
+ # --- SAM extend ---
115
+ r = len(b)
116
+ b.append({})
117
+ c.append(0)
118
+ d.append(d[g] + 1)
119
+ e.append(-1)
120
+ p = g
121
+ while p != -1 and ch not in b[p]:
122
+ b[p][ch] = r
123
+ p = c[p]
124
+ if p == -1:
125
+ c[r] = 0
126
+ else:
127
+ q = b[p][ch]
128
+ if d[p] + 1 == d[q]:
129
+ c[r] = q
130
+ else:
131
+ # clone q -> u
132
+ u = len(b)
133
+ b.append(b[q].copy())
134
+ c.append(c[q])
135
+ d.append(d[p] + 1)
136
+ e.append(e[q])
137
+ while p != -1 and b[p].get(ch) == q:
138
+ b[p][ch] = u
139
+ p = c[p]
140
+ c[q] = c[r] = u
141
+ self.g = r
142
+
143
+ # --- update rightmost indices ---
144
+ v = self.g
145
+ while v != -1 and self.e[v] < i:
146
+ self.e[v] = i
147
+ v = self.c[v]
148
+
149
+ def mark_boundary(self) -> None:
150
+ """Call after finishing an example."""
151
+ if self.text:
152
+ self.boundary_after[len(self.text) - 1] = True
153
+ self.g = 0 # reset 'last' to root for a fresh example
154
+
155
+ # ----- Serialization -----
156
+ def to_state_dict(self) -> Dict:
157
+ return {
158
+ "b": self.b,
159
+ "c": self.c,
160
+ "d": self.d,
161
+ "e": self.e,
162
+ "g": self.g,
163
+ "text_str": "".join(self.text),
164
+ "boundary_after": self.boundary_after,
165
+ }
166
+
167
+ @classmethod
168
+ def from_state_dict(cls, obj: Dict) -> "ROSACharPredictor":
169
+ inst = cls()
170
+ inst.b = obj["b"]
171
+ inst.c = obj["c"]
172
+ inst.d = obj["d"]
173
+ inst.e = obj["e"]
174
+ inst.g = obj.get("g", 0)
175
+ inst.text = list(obj.get("text_str", ""))
176
+ inst.boundary_after = obj.get("boundary_after", [False] * len(inst.text))
177
+ if len(inst.boundary_after) < len(inst.text):
178
+ inst.boundary_after += [False] * (len(inst.text) - len(inst.boundary_after))
179
+ return inst
180
+
181
+
182
+ # ===============================
183
+ # 3) Walk a frozen SAM (inference)
184
+ # ===============================
185
+
186
+ def _advance_state(b, c, d, v: int, ch: str) -> int:
187
+ """Walk the trained SAM with character `ch` (no learning). Returns new state v'."""
188
+ while v != -1 and ch not in b[v]:
189
+ v = c[v]
190
+ if v == -1:
191
+ return b[0].get(ch, 0)
192
+ return b[v][ch]
193
+
194
+
195
+ def _predict_from_state(
196
+ b, c, d, e, train_text: str, v: int, boundary_after: Optional[List[bool]] = None
197
+ ) -> Optional[str]:
198
+ """Deterministic ROSA next-char from current state v using rightmost indices.
199
+ Refuses to cross an example boundary.
200
+ """
201
+ u = v
202
+ n = len(train_text)
203
+ while u != -1:
204
+ i = e[u]
205
+ j = i + 1
206
+ if d[u] > 0 and 0 <= j < n:
207
+ if boundary_after is not None and 0 <= i < len(boundary_after) and boundary_after[i]:
208
+ u = c[u]
209
+ continue
210
+ return train_text[j]
211
+ u = c[u]
212
+ return None
213
+
214
+
215
+ # ============================================
216
+ # 4) Fallback LM that never crosses boundaries
217
+ # ============================================
218
+
219
+ class ROSAFallbackLM:
220
+ """Character LM using Witten–Bell interpolation down the SAM suffix chain.
221
+ IMPORTANT: counts are constructed per-example; no cross-boundary pairs.
222
+ """
223
+ def __init__(self, sam: ROSACharPredictor, examples: List[str], max_order: Optional[int] = None, show_progress: bool = True):
224
+ self.b, self.c, self.d, self.e = sam.b, sam.c, sam.d, sam.e
225
+ self.max_order = max_order
226
+ joined = "".join(examples)
227
+ self.alphabet = sorted(set(joined)) or ['\n']
228
+ self.freq: List[Dict[str, int]] = [defaultdict(int) for _ in range(len(self.b))]
229
+ self.unigram = Counter(joined) if joined else Counter({'\n': 1})
230
+ self._cache: Dict[int, Dict[str, float]] = {}
231
+ self._build_counts_examples_fast(examples, show_progress=show_progress)
232
+
233
+ def _build_counts_examples_fast(self, examples: List[str], show_progress: bool = True) -> None:
234
+ """Optimized: single pass per example, update-exclusion at the longest context,
235
+ optionally clamped by `max_order`.
236
+ """
237
+ total_pairs = sum(max(0, len(seg) - 1) for seg in examples if seg)
238
+ pbar = tqdm(total=total_pairs, desc="Training fallback LM (pairs)", disable=not show_progress, leave=False)
239
+
240
+ b, c, d = self.b, self.c, self.d
241
+ freq = self.freq
242
+ max_order = self.max_order
243
+
244
+ for seg in examples:
245
+ if not seg:
246
+ continue
247
+ v = 0 # root
248
+ for i in range(len(seg) - 1):
249
+ ch = seg[i]
250
+ # inline _advance_state
251
+ u = v
252
+ while u != -1 and ch not in b[u]:
253
+ u = c[u]
254
+ if u == -1:
255
+ v = b[0].get(ch, 0)
256
+ else:
257
+ v = b[u][ch]
258
+
259
+ ctx = v
260
+ if max_order is not None:
261
+ while ctx != -1 and d[ctx] > max_order:
262
+ ctx = c[ctx]
263
+ if ctx == -1:
264
+ ctx = 0
265
+ nxt = seg[i + 1]
266
+ freq[ctx][nxt] += 1
267
+ pbar.update(1)
268
+
269
+ pbar.close()
270
+
271
+ self._propagate_counts_up_suffix_links()
272
+ # invalidate any cached distributions built before propagation
273
+ self._cache.clear()
274
+
275
+ def ensure_capacity(self) -> None:
276
+ """Make sure freq has one bucket per SAM state (called after SAM grows)."""
277
+ missing = len(self.b) - len(self.freq)
278
+ if missing > 0:
279
+ self.freq.extend(defaultdict(int) for _ in range(missing))
280
+
281
+ def observe_pair(self, ctx_state: int, next_ch: str, *, propagate: bool = True) -> None:
282
+ """
283
+ Online update: record one observation of (ctx_state -> next_ch).
284
+ If propagate=True we mirror the offline build's suffix-up accumulation.
285
+ """
286
+ # Keep alphabet fixed during online learning (simple path).
287
+ if next_ch not in self.alphabet:
288
+ return # or raise if you prefer a hard failure
289
+
290
+ self.ensure_capacity()
291
+ self.freq[ctx_state][next_ch] += 1
292
+
293
+ if propagate:
294
+ u = self.c[ctx_state]
295
+ while u != -1:
296
+ self.freq[u][next_ch] += 1
297
+ u = self.c[u]
298
+
299
+ # Invalidate memoized distributions for this chain
300
+ u = ctx_state
301
+ while u != -1:
302
+ self._cache.pop(u, None)
303
+ u = self.c[u]
304
+
305
+ def _probs_for_state(self, v: int) -> Dict[str, float]:
306
+ """Witten–Bell interpolation down suffix links, memoized by state."""
307
+ if v in self._cache:
308
+ return self._cache[v]
309
+
310
+ # Build suffix chain (optionally truncated by max_order)
311
+ chain = []
312
+ u = v
313
+ while u != -1:
314
+ if self.max_order is not None and self.d[u] > self.max_order:
315
+ u = self.c[u]
316
+ continue
317
+ chain.append(u)
318
+ u = self.c[u]
319
+
320
+ residual = 1.0
321
+ probs: Dict[str, float] = {}
322
+
323
+ def add_counts(state: int, scale: float):
324
+ if scale <= 0.0:
325
+ return
326
+ total = sum(self.freq[state].values())
327
+ if total == 0:
328
+ return
329
+ inv_total = 1.0 / total
330
+ for ch, cnt in self.freq[state].items():
331
+ probs[ch] = probs.get(ch, 0.0) + scale * (cnt * inv_total)
332
+
333
+ for state in chain:
334
+ N = sum(self.freq[state].values())
335
+ T = len(self.freq[state])
336
+ if N == 0:
337
+ continue
338
+ lam = N / (N + T) if T > 0 else 1.0 # Witten–Bell
339
+ add_counts(state, residual * lam)
340
+ residual *= (1.0 - lam)
341
+
342
+ # Unigram fallback
343
+ total_uni = sum(self.unigram.values())
344
+ if total_uni > 0 and residual > 0.0:
345
+ inv_total = 1.0 / total_uni
346
+ for ch, cnt in self.unigram.items():
347
+ probs[ch] = probs.get(ch, 0.0) + residual * (cnt * inv_total)
348
+
349
+ s = sum(probs.values())
350
+ if s > 0:
351
+ inv_s = 1.0 / s
352
+ for k in list(probs.keys()):
353
+ probs[k] *= inv_s
354
+ else:
355
+ u = 1.0 / max(1, len(self.alphabet))
356
+ probs = {ch: u for ch in self.alphabet}
357
+
358
+ self._cache[v] = probs
359
+ return probs
360
+
361
+ def _propagate_counts_up_suffix_links(self) -> None:
362
+ """
363
+ After filling self.freq only at the longest contexts, push counts up the
364
+ suffix-link tree so every shorter context has aggregated counts.
365
+ Process states in decreasing d[v] so children flow into parents.
366
+ """
367
+ order = sorted(range(len(self.b)), key=lambda v: self.d[v], reverse=True)
368
+ for v in order:
369
+ p = self.c[v]
370
+ if p < 0: # root has no parent
371
+ continue
372
+ if not self.freq[v]:
373
+ continue
374
+ dv = self.freq[v]
375
+ dp = self.freq[p]
376
+ for ch, cnt in dv.items():
377
+ dp[ch] += cnt
378
+
379
+ @staticmethod
380
+ def _sample_from_dist(
381
+ dist: Dict[str, float],
382
+ temperature: float = 1.0,
383
+ top_p: Optional[float] = 0.9,
384
+ top_k: Optional[int] = None,
385
+ ) -> str:
386
+ if temperature <= 0:
387
+ temperature = 1e-6
388
+ items = sorted(dist.items(), key=lambda x: x[1], reverse=True)
389
+ if top_k is not None and top_k > 0:
390
+ items = items[:max(1, top_k)]
391
+ if top_p is not None:
392
+ cum, cut = 0.0, []
393
+ for ch, p in items:
394
+ cum += p
395
+ cut.append((ch, p))
396
+ if cum >= top_p:
397
+ break
398
+ items = cut or items[:1]
399
+ logits = [math.log(max(p, 1e-12)) / temperature for _, p in items]
400
+ m = max(logits)
401
+ exps = [math.exp(z - m) for z in logits]
402
+ Z = sum(exps)
403
+ probs = [x / Z for x in exps]
404
+ idx = random.choices(range(len(items)), weights=probs, k=1)[0]
405
+ return items[idx][0]
406
+
407
+ # ----- Serialization -----
408
+ def to_state_dict(self) -> Dict:
409
+ freq_plain = [{k: int(v) for k, v in d.items()} for d in tqdm(self.freq, leave=False)]
410
+ return {
411
+ "alphabet": self.alphabet,
412
+ "unigram": {k: int(v) for k, v in self.unigram.items()},
413
+ "freq": freq_plain,
414
+ "max_order": self.max_order,
415
+ }
416
+
417
+ @classmethod
418
+ def from_state_dict(cls, sam: ROSACharPredictor, obj: Dict) -> "ROSAFallbackLM":
419
+ inst = cls.__new__(cls) # bypass __init__
420
+ inst.b, inst.c, inst.d, inst.e = sam.b, sam.c, sam.d, sam.e
421
+ inst.max_order = obj.get("max_order", None)
422
+ inst.alphabet = obj["alphabet"]
423
+ inst.unigram = Counter({k: int(v) for k, v in obj["unigram"].items()})
424
+ inst.freq = [defaultdict(int, {k: int(v) for k, v in d.items()}) for d in tqdm(obj["freq"], leave=False)]
425
+ inst._cache = {}
426
+ return inst
427
+
428
+
429
+ # ============================================
430
+ # 5) Mixed generation: deterministic + fallback
431
+ # ============================================
432
+
433
+ def _generate_mixed(
434
+ sam: ROSACharPredictor,
435
+ lm: ROSAFallbackLM,
436
+ prompt: str,
437
+ max_steps: int = 200,
438
+ always_fallback = False,
439
+ stop_at: Optional[str] = None,
440
+ fallback_temperature: float = 1.0,
441
+ fallback_top_p: Optional[float] = 0.9,
442
+ fallback_top_k: Optional[int] = 50,
443
+ ) -> str:
444
+ b, c, d, e = sam.b, sam.c, sam.d, sam.e
445
+ train_text = "".join(sam.text)
446
+ v = 0
447
+ for ch in prompt:
448
+ v = _advance_state(b, c, d, v, ch)
449
+
450
+ out: List[str] = []
451
+ for _ in range(max_steps):
452
+ # 1) Deterministic ROSA
453
+ ch = None
454
+ if not always_fallback:
455
+ ch = _predict_from_state(b, c, d, e, train_text, v, boundary_after=sam.boundary_after)
456
+ if ch is None:
457
+ dist = lm._probs_for_state(v)
458
+ ch = ROSAFallbackLM._sample_from_dist(
459
+ dist, temperature=fallback_temperature, top_p=fallback_top_p, top_k=fallback_top_k
460
+ )
461
+ out.append(ch)
462
+ if stop_at is not None and ch == stop_at:
463
+ break
464
+ v = _advance_state(b, c, d, v, ch)
465
+
466
+ return "".join(out)
467
+
468
+
469
+ # ============================================
470
+ # 6) High-level wrapper class
471
+ # ============================================
472
+
473
+ MODEL_MAGIC = "rosa_pb_v2" # v2 **only**
474
+
475
+ class ROSAPlus:
476
+ """High-level model wrapper exposing a clean API.
477
+
478
+ Typical usage:
479
+ m = ROSAPlus(max_order=1048576, use_eot=True, eot_char="\u0004", seed=0)
480
+ m.train_example("hello world\u0004") # or skip EOT if you set use_eot=False
481
+ m.build_lm() # required before generation / probs
482
+ out = m.generate("he", steps=20, temperature=0.7)
483
+ p = m.next_char_prob("he", "l")
484
+ m.save("model.bin")
485
+ m2 = ROSAPlus.load("model.bin")
486
+ """
487
+
488
+ def __init__(self, *, max_order: Optional[int] = 1048576, use_eot: bool = True, eot_char: str = "\u0004", seed: int = 0):
489
+ if not isinstance(eot_char, str) or len(eot_char) != 1:
490
+ raise ValueError("eot_char must be a single character.")
491
+ self.max_order = max_order
492
+ self.use_eot = use_eot
493
+ self.eot_char = eot_char
494
+ self.seed = seed
495
+ random.seed(seed)
496
+
497
+ self.sam = ROSACharPredictor()
498
+ self._examples: List[str] = []
499
+ self.lm: Optional[ROSAFallbackLM] = None # built later
500
+ self.neural: Optional["ROSAGRUAdapter"] = None # optional GRU adapter
501
+
502
+ # ---- Training API ----
503
+ def train_example(self, example: str) -> None:
504
+ """Train on a single example string. Appends EOT if `use_eot` and it's not present as the final char."""
505
+ if not example:
506
+ return
507
+ if self.use_eot:
508
+ if example[-1] != self.eot_char:
509
+ example = example + self.eot_char
510
+ self._examples.append(example)
511
+ for ch in tqdm(example):
512
+ self.sam.feed(ch)
513
+ self.sam.mark_boundary()
514
+
515
+ def fit_from_examples(self, examples: List[str], *, show_progress: bool = True) -> None:
516
+ """Convenience: train on many examples and build LM."""
517
+ total_chars = sum(len(ex) for ex in examples)
518
+ with tqdm(total=total_chars, desc="Training SAM (ROSA) over chars", disable=not show_progress) as pbar:
519
+ for ex in examples:
520
+ self.train_example(ex) # this already appends EOT if enabled
521
+ pbar.update(len(ex) if ex else 0)
522
+ self.build_lm(show_progress=show_progress)
523
+
524
+ def build_lm(self, *, show_progress: bool = True) -> None:
525
+ if not self._examples:
526
+ raise RuntimeError("No training examples available. Use train_example() first.")
527
+ self.lm = ROSAFallbackLM(self.sam, self._examples, max_order=self.max_order, show_progress=show_progress)
528
+
529
+ # ---- Optional neural adapter integration ----
530
+ def attach_gru_adapter(self, adapter: "ROSAGRUAdapter") -> None:
531
+ """Attach a trained (or untrained) GRU adapter."""
532
+ self.neural = adapter
533
+
534
+ def train_gru_adapter(
535
+ self,
536
+ *,
537
+ examples,
538
+ emb_dim: int = 128,
539
+ hidden_dim: int = 256,
540
+ num_layers: int = 1,
541
+ dropout: float = 0.0,
542
+ combine: str = "poe",
543
+ beta: float = 1.0,
544
+ device: Optional[str] = None,
545
+ epochs: int = 1,
546
+ lr: float = 1e-3,
547
+ max_tokens_per_step: int = 4096*10,
548
+ clip_grad: float = 1.0,
549
+ show_progress: bool = True,
550
+ # NEW:
551
+ online_sam: bool = False,
552
+ online_lm: bool = False,
553
+ propagate_updates: bool = True,
554
+ ) -> "ROSAGRUAdapter":
555
+ if self.lm is None:
556
+ raise RuntimeError("Fallback LM not built. Call build_lm() first.")
557
+ adapter = ROSAGRUAdapter(
558
+ self.lm.alphabet,
559
+ emb_dim=emb_dim,
560
+ hidden_dim=hidden_dim,
561
+ num_layers=num_layers,
562
+ dropout=dropout,
563
+ combine=combine,
564
+ beta=beta,
565
+ device=device,
566
+ )
567
+ adapter.fit(
568
+ self.sam,
569
+ self.lm,
570
+ examples,
571
+ eot_char=self.eot_char,
572
+ epochs=epochs,
573
+ lr=lr,
574
+ max_tokens_per_step=max_tokens_per_step,
575
+ clip_grad=clip_grad,
576
+ show_progress=show_progress,
577
+ online_sam=online_sam,
578
+ online_lm=online_lm,
579
+ propagate_updates=propagate_updates,
580
+ )
581
+ self.neural = adapter
582
+ return adapter
583
+
584
+ # ---- Inference API ----
585
+ def generate(
586
+ self,
587
+ prompt: str,
588
+ *,
589
+ steps: int = 200,
590
+ always_fallback = False,
591
+ stop_at: Optional[str] = None,
592
+ temperature: float = 0.5,
593
+ top_p: Optional[float] = 0.9,
594
+ top_k: Optional[int] = 50,
595
+ use_gru_adapter: bool = True, # enable/disable neural reweighting
596
+ ) -> str:
597
+ """
598
+ Generate a continuation from `prompt`.
599
+
600
+ Order of operations per token:
601
+ 1) Try deterministic ROSA next-char (won't cross boundaries).
602
+ 2) Otherwise sample from fallback LM; if a GRU adapter is attached,
603
+ refine the LM distribution first. The adapter consumes one base
604
+ distribution per token; we *always* call step_with_char(ch) after
605
+ emitting a char—this becomes a no-op if refine_distribution() was
606
+ called in the same tick (the adapter guards against double steps).
607
+ """
608
+ if self.lm is None:
609
+ raise RuntimeError("Fallback LM not built. Call build_lm() after training.")
610
+
611
+ if stop_at is None and self.use_eot:
612
+ stop_at = self.eot_char
613
+ if top_k is not None and top_k <= 0:
614
+ top_k = None
615
+
616
+ # Unpack SAM internals
617
+ b, c, d, e = self.sam.b, self.sam.c, self.sam.d, self.sam.e
618
+ train_text = "".join(self.sam.text)
619
+
620
+ # Walk SAM with the prompt to get the starting state
621
+ v = 0
622
+ for ch in prompt:
623
+ v = _advance_state(b, c, d, v, ch)
624
+
625
+ # Prime GRU with the prompt by consuming base distributions along the path
626
+ if use_gru_adapter and self.neural is not None:
627
+ try:
628
+ self.neural.reset()
629
+ v_prime = 0
630
+ for ch in prompt:
631
+ v_prime = _advance_state(b, c, d, v_prime, ch)
632
+ base = self.lm._probs_for_state(v_prime)
633
+ if hasattr(self.neural, "step_with_dist"):
634
+ self.neural.step_with_dist(base)
635
+ except Exception:
636
+ # Priming is best-effort; fall back silently if adapter errors
637
+ pass
638
+
639
+ out: List[str] = []
640
+ for _ in range(steps):
641
+ # 1) Deterministic ROSA (if allowed)
642
+ ch = None
643
+ if not always_fallback:
644
+ ch = _predict_from_state(
645
+ b, c, d, e, train_text, v, boundary_after=self.sam.boundary_after
646
+ )
647
+
648
+ # 2) Otherwise sample from (possibly GRU-refined) fallback LM
649
+ if ch is None:
650
+ base_dist = self.lm._probs_for_state(v)
651
+ if use_gru_adapter and self.neural is not None and hasattr(self.neural, "refine_distribution"):
652
+ try:
653
+ dist = self.neural.refine_distribution(base_dist) # consumes one step
654
+ except Exception:
655
+ dist = base_dist
656
+ else:
657
+ dist = base_dist
658
+
659
+ ch = ROSAFallbackLM._sample_from_dist(
660
+ dist, temperature=temperature, top_p=top_p, top_k=top_k
661
+ )
662
+
663
+ out.append(ch)
664
+ if stop_at is not None and ch == stop_at:
665
+ break
666
+
667
+ # Advance SAM (and adapter) with the emitted char
668
+ v = _advance_state(b, c, d, v, ch)
669
+ if use_gru_adapter and self.neural is not None and hasattr(self.neural, "step_with_char"):
670
+ try:
671
+ # If refine_distribution() already stepped this tick, this is a no-op.
672
+ self.neural.step_with_char(ch)
673
+ except Exception:
674
+ pass
675
+
676
+ return "".join(out)
677
+
678
+ def get_dist(self, context: str, deterministic=False) -> Dict[str, float]:
679
+ """Return a dict of next-char probabilities given `context`.
680
+ If deterministic=True: Get direct prediction instead of probability (no fallback)
681
+ """
682
+ if self.lm is None:
683
+ raise RuntimeError("Fallback LM not built. Call build_lm() after training.")
684
+ b, c, d, e = self.sam.b, self.sam.c, self.sam.d, self.sam.e
685
+ train_text = "".join(self.sam.text)
686
+ v = 0
687
+ for ch in context:
688
+ v = _advance_state(b, c, d, v, ch)
689
+ if deterministic:
690
+ det = _predict_from_state(b, c, d, e, train_text, v, boundary_after=self.sam.boundary_after)
691
+ if det is not None:
692
+ return {det: 1.0}
693
+ base = self.lm._probs_for_state(v)
694
+ # If neural adapter is attached, offer a reweighted distribution helper-style
695
+ if self.neural is not None and hasattr(self.neural, "refine_distribution"):
696
+ try:
697
+ return self.neural.refine_distribution(base)
698
+ except Exception:
699
+ return base
700
+ return base
701
+
702
+ # ---- Persistence ----
703
+ def save(self, path: str) -> None:
704
+ if self.lm is None:
705
+ raise RuntimeError("Fallback LM not built. Call build_lm() before saving.")
706
+ payload = {
707
+ "magic": MODEL_MAGIC,
708
+ "sam": self.sam.to_state_dict(),
709
+ "lm": self.lm.to_state_dict(),
710
+ "meta": {
711
+ "use_eot": self.use_eot,
712
+ "eot_char": self.eot_char,
713
+ "max_order": self.max_order,
714
+ "seed": self.seed,
715
+ },
716
+ # Note: neural adapter is NOT serialized here by default to avoid
717
+ # adding a framework dependency into the model blob.
718
+ }
719
+ with open(path, "wb") as f:
720
+ f.write(_dumps(payload))
721
+
722
+ @classmethod
723
+ def load(cls, path: str) -> "ROSAPlus":
724
+ with open(path, "rb") as f:
725
+ payload = _loads(f.read())
726
+ magic = payload.get("magic")
727
+ if magic != MODEL_MAGIC:
728
+ raise ValueError(f"Unrecognized or unsupported model magic in {path}: {magic} (v2 only)")
729
+ meta = payload.get("meta", {})
730
+ inst = cls(
731
+ max_order=meta.get("max_order", 1048576),
732
+ use_eot=meta.get("use_eot", True),
733
+ eot_char=meta.get("eot_char", "\u0004"),
734
+ seed=meta.get("seed", 0),
735
+ )
736
+ inst.sam = ROSACharPredictor.from_state_dict(payload["sam"]) # type: ignore[arg-type]
737
+ inst.lm = ROSAFallbackLM.from_state_dict(inst.sam, payload["lm"]) # type: ignore[arg-type]
738
+ return inst
739
+
740
+ # ---- Utilities ----
741
+ @staticmethod
742
+ def decode_escape(s: str) -> str:
743
+ try:
744
+ return s.encode("utf-8").decode("unicode_escape")
745
+ except Exception:
746
+ return s
tinyshakespeare.txt ADDED
The diff for this file is too large to render. See raw diff