gamedevelop commited on
Commit
5ba1bb4
·
verified ·
1 Parent(s): 7b6ca56

Upload text-only Chat & Code training project

Browse files

Text-only source, pinned Qwen base configuration, cloud QLoRA training recipe, tests and source bundle. No custom trained weights are included.

LICENSE ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+
6
+ Everyone is permitted to copy and distribute verbatim copies 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 software and other kinds of works.
11
+
12
+ The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
13
+
14
+ When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
15
+
16
+ To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
17
+
18
+ For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
19
+
20
+ Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
21
+
22
+ For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
23
+
24
+ Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
25
+
26
+ Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
27
+
28
+ The precise terms and conditions for copying, distribution and modification follow.
29
+
30
+ TERMS AND CONDITIONS
31
+
32
+ 0. Definitions.
33
+
34
+ “This License” refers to version 3 of the GNU General Public License.
35
+
36
+ “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
37
+
38
+ “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
39
+
40
+ To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
41
+
42
+ A “covered work” means either the unmodified Program or a work based on the Program.
43
+
44
+ To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
45
+
46
+ To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
47
+
48
+ An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
49
+
50
+ 1. Source Code.
51
+ The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
52
+
53
+ A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
54
+
55
+ The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
56
+
57
+ The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
58
+
59
+ The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
60
+
61
+ The Corresponding Source for a work in source code form is that same work.
62
+
63
+ 2. Basic Permissions.
64
+ All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
65
+
66
+ You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
67
+
68
+ Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
69
+
70
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
71
+ No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
72
+
73
+ When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
74
+
75
+ 4. Conveying Verbatim Copies.
76
+ You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
77
+
78
+ You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
79
+
80
+ 5. Conveying Modified Source Versions.
81
+ You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
82
+
83
+ a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
84
+
85
+ b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
86
+
87
+ c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
88
+
89
+ d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
90
+
91
+ A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
92
+
93
+ 6. Conveying Non-Source Forms.
94
+ You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
95
+
96
+ a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
97
+
98
+ b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
99
+
100
+ c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
101
+
102
+ d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
103
+
104
+ e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
105
+
106
+ A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
107
+
108
+ A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
109
+
110
+ “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
111
+
112
+ If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
113
+
114
+ The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
115
+
116
+ Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
117
+
118
+ 7. Additional Terms.
119
+ “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
120
+
121
+ When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
122
+
123
+ Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
124
+
125
+ a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
126
+
127
+ b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
128
+
129
+ c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
130
+
131
+ d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
132
+
133
+ e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
134
+
135
+ f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
136
+
137
+ All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
138
+
139
+ If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
140
+
141
+ Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
142
+
143
+ 8. Termination.
144
+ You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
145
+
146
+ However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
147
+
148
+ Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
149
+
150
+ Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
151
+
152
+ 9. Acceptance Not Required for Having Copies.
153
+ You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
154
+
155
+ 10. Automatic Licensing of Downstream Recipients.
156
+ Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
157
+
158
+ An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
159
+
160
+ You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
161
+
162
+ 11. Patents.
163
+ A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
164
+
165
+ A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
166
+
167
+ Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
168
+
169
+ In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
170
+
171
+ If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
172
+
173
+ If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
174
+
175
+ A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
176
+
177
+ Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
178
+
179
+ 12. No Surrender of Others' Freedom.
180
+ If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
181
+
182
+ 13. Use with the GNU Affero General Public License.
183
+ Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
184
+
185
+ 14. Revised Versions of this License.
186
+ The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
187
+
188
+ Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
189
+
190
+ If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
191
+
192
+ Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
193
+
194
+ 15. Disclaimer of Warranty.
195
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
196
+
197
+ 16. Limitation of Liability.
198
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
199
+
200
+ 17. Interpretation of Sections 15 and 16.
201
+ If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
202
+
203
+ END OF TERMS AND CONDITIONS
204
+
205
+ How to Apply These Terms to Your New Programs
206
+
207
+ If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
208
+
209
+ To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
210
+
211
+ <one line to give the program's name and a brief idea of what it does.>
212
+ Copyright (C) <year> <name of author>
213
+
214
+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
215
+
216
+ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
217
+
218
+ You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
219
+
220
+ Also add information on how to contact you by electronic and paper mail.
221
+
222
+ If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
223
+
224
+ <program> Copyright (C) <year> <name of author>
225
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
226
+ This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
227
+
228
+ The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
229
+
230
+ You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
231
+
232
+ The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
LICENSE-BASE-MODEL.txt ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: gpl-3.0
5
+ tags:
6
+ - code
7
+ - text-only
8
+ - training-recipe
9
+ - work-in-progress
10
+ ---
11
+
12
+ # PocketVision Chat & Code
13
+
14
+ **Status: source project and cloud training recipe only. No custom model weights or adapter have been trained or uploaded for this version.**
15
+
16
+ This project focuses on text conversation and programming: explaining code, generating functions, and debugging. Image upload and image understanding have been removed from the active application.
17
+
18
+ This repository is not yet a downloadable fine-tuned model or a running chat service. The supplied app uses the pretrained base until a compatible trained adapter is supplied. On a computer without a CUDA GPU it displays an interface preview and does not download the larger base weights.
19
+
20
+ ## Selected base model
21
+
22
+ [Qwen/Qwen3-4B-Instruct-2507](https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507), Apache-2.0.
23
+ Pinned revision: `cdbee75f17c01a7cc42f958dc650907174af0554`.
24
+
25
+ The Qwen weights are supplied by the original publisher and are not re-uploaded here. The original PocketVision SmolVLM/ChartQA adapter cannot be used with this architecture.
26
+
27
+ ## Planned training
28
+
29
+ The first proposed cloud experiment uses 20,000 examples from [HuggingFaceTB/smoltalk](https://huggingface.co/datasets/HuggingFaceTB/smoltalk), pinned to `5feaf2fd3ffca7c237fc38d1861bc30365d48ffa`:
30
+
31
+ - 60% `self-oss-instruct`: programming, primarily Python. Original source: BigCode, [self-oss-instruct-sc2-exec-filter-50k](https://huggingface.co/datasets/bigcode/self-oss-instruct-sc2-exec-filter-50k), ODC-BY.
32
+ - 40% `smol-magpie-ultra`: conversation and instruction following, Apache-2.0.
33
+ - Separate derived validation and test splits; duplicate opening prompts are removed.
34
+ - Assistant-only loss; 4-bit NF4 QLoRA, rank 16; one epoch as a starting experiment.
35
+
36
+ These are planned settings, not a description of completed training. Synthetic answers may contain errors. The base may already have seen these sources. The programming pilot does not establish broad coverage of other languages.
37
+
38
+ ## Files and cloud workflow
39
+
40
+ - `app.py` and `chat.py`: text-only web and CLI entry points.
41
+ - `chatcode/`: runtime, data preparation, cloud trainer, tests, configuration, dependencies, and the detailed guide.
42
+ - [Cloud training guide](chatcode/README.md).
43
+ - [Download the complete source bundle](pocketvision-chat-code-source.zip).
44
+
45
+ Run the following on a remote Linux CUDA GPU, from the source directory:
46
+
47
+ ```bash
48
+ python -m pip install torch==2.9.1 --index-url https://download.pytorch.org/whl/cu128
49
+ python -m pip install -r chatcode/requirements-cloud.txt
50
+ python -m pip check
51
+ python -m chatcode.data --output /checkpoints/chatcode-data
52
+ python -m chatcode.train --data /checkpoints/chatcode-data --output /checkpoints/smoke --max-steps 25
53
+ ```
54
+
55
+ Use mounted persistent storage for `/checkpoints`. Inspect the smoke run before estimating and launching a full experiment. No paid hardware is started by uploading this repository. The trainer refuses CPU training and does not upload automatically.
56
+
57
+ ## Verification and limits
58
+
59
+ Five small offline checks passed: assistant-only labels and padding, text-only record validation, CPU refusal before model download, data manifest integrity, and a forward/backward check with a tiny randomly initialized Qwen architecture. These checks do not train or evaluate the selected 4B model.
60
+
61
+ The cloud dependencies and full GPU training run still need a cloud smoke test. No chat-quality or programming-accuracy improvement is claimed. A trained candidate needs separate answer review and isolated code tests before release. This repository does not include a sandboxed code-execution evaluator.
62
+
63
+ ## Licenses and attribution
64
+
65
+ Project source: GPL-3.0-only (`LICENSE`). Original Qwen base: Apache-2.0 (`LICENSE-BASE-MODEL.txt`). Dataset and dependency licenses remain applicable. See the training guide and configuration for provenance. No pretrained base weights, raw datasets, credentials, or original vision adapter are included.
app.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Default entry point for the text-only Chat & Code successor."""
2
+ from chatcode.app import demo, launch
3
+
4
+ __all__ = ["demo", "launch"]
5
+
6
+ if __name__ == "__main__":
7
+ launch()
8
+
chat.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cloud GPU command-line chat. The original CLI is vision_chat.py."""
2
+ import argparse
3
+ from chatcode.runtime import answer, load_engine
4
+
5
+ if __name__ == "__main__":
6
+ parser = argparse.ArgumentParser(description="PocketVision Chat & Code (text only, cloud GPU)")
7
+ parser.add_argument("prompt")
8
+ parser.add_argument("--adapter", help="A matching chat/code adapter; omit to use the pretrained base")
9
+ parser.add_argument("--max-new-tokens", type=int, default=768)
10
+ args = parser.parse_args()
11
+ try:
12
+ tokenizer, model = load_engine(args.adapter)
13
+ print(answer(tokenizer, model, args.prompt, max_new_tokens=args.max_new_tokens))
14
+ except (ValueError, RuntimeError) as error:
15
+ parser.exit(1, f"{error}\n")
16
+
chatcode/README.md ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PocketVision Chat & Code — version 2 preparation
2
+
3
+ This version accepts text and produces text. It focuses on ordinary conversation,
4
+ explaining code, generating functions, and debugging. There is no image input,
5
+ vision encoder, image processor, or ChartQA training in the new pipeline.
6
+
7
+ **Status:** source and training recipe prepared; no new model trained or deployed.
8
+ The private `gamedevelop/pocketvision` repository still contains the original
9
+ SmolVLM/ChartQA prototype. Its weights are incompatible with this version.
10
+ The local app shows an interface preview without downloading the new base weights.
11
+ It does not silently run the old model under the new name.
12
+
13
+ ## Model and training data
14
+
15
+ - Base: [Qwen/Qwen3-4B-Instruct-2507](https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507),
16
+ Apache-2.0, pinned to `cdbee75f17c01a7cc42f958dc650907174af0554`.
17
+ This is an instruction-tuned text model; its model card includes chat and coding evaluations.
18
+ - Data: [HuggingFaceTB/smoltalk](https://huggingface.co/datasets/HuggingFaceTB/smoltalk),
19
+ pinned to `5feaf2fd3ffca7c237fc38d1861bc30365d48ffa`.
20
+ - Pilot: 12,000 `self-oss-instruct` programming examples and 8,000
21
+ `smol-magpie-ultra` conversation examples. The coding source primarily covers
22
+ Python. JavaScript and other languages need additional sources and tests.
23
+ - Attribution for the coding subset: BigCode,
24
+ [self-oss-instruct-sc2-exec-filter-50k](https://huggingface.co/datasets/bigcode/self-oss-instruct-sc2-exec-filter-50k),
25
+ Open Data Commons Attribution License (ODC-BY). The source describes its responses
26
+ as execution-validated; this project does not rerun or independently certify them.
27
+ Smol-Magpie-Ultra is Apache-2.0. Dependency and underlying source terms still apply.
28
+ - Separate validation and test sets: 128 examples from each source per split.
29
+ All three derived splits come from the sources' official **training** split.
30
+ Official test data is unused. Identical normalized opening questions are grouped
31
+ and deduplicated globally. This does not establish novel or semantically disjoint
32
+ data relative to the pretrained base.
33
+ - Examples longer than 2,048 tokens are skipped, preserving complete code/answers.
34
+ Only assistant answer and end-of-turn tokens contribute to loss.
35
+ - One epoch of 4-bit NF4 QLoRA, rank 16, all linear projections, learning rate
36
+ 5e-5, microbatch 1, accumulation 16. This is a starting recipe, not validated
37
+ evidence of improved model quality or a guarantee that it fits every GPU.
38
+
39
+ ## Local interface preview
40
+
41
+ Use the existing environment and run `python app.py`. With no CUDA GPU, it displays
42
+ the text-only interface with sending disabled. No new model weights are fetched.
43
+ The original visual UI is preserved as `vision_app.py` for reproducibility.
44
+
45
+ ## Train on a remote Linux GPU
46
+
47
+ Use a Colab GPU runtime or a Hugging Face Job. A 24 GB GPU is a reasonable starting
48
+ target, subject to an actual memory smoke test. None has been rented or started.
49
+ Run these commands **on the cloud machine**, from the unpacked source directory:
50
+
51
+ ```bash
52
+ python -m pip install torch==2.9.1 --index-url https://download.pytorch.org/whl/cu128
53
+ python -m pip install -r chatcode/requirements-cloud.txt
54
+ python -m pip check
55
+ python -m chatcode.data --output /checkpoints/chatcode-data
56
+ python -m chatcode.train --data /checkpoints/chatcode-data --output /checkpoints/smoke --max-steps 25
57
+ ```
58
+
59
+ `/checkpoints` must be your mounted **persistent** bucket/volume or Drive directory.
60
+ Do not use a transient runtime directory as the only copy: Jobs discard local disk
61
+ when they end, and notebook sessions can be terminated. Checkpoints include optimizer,
62
+ scheduler, trainer and random state; they are saved every 25 steps.
63
+
64
+ First inspect the smoke run's GPU memory and steps/second. Estimate cost and agree
65
+ on a run limit before launching the full run. A 25-step smoke run is still paid
66
+ compute when using a paid GPU. Model/data downloads and setup also take time.
67
+ Once that succeeds, run the full pilot in a new output directory:
68
+
69
+ ```bash
70
+ python -m chatcode.train --data /checkpoints/chatcode-data --output /checkpoints/pilot
71
+ ```
72
+
73
+ Resume an interrupted run with the same configuration and data:
74
+
75
+ ```bash
76
+ python -m chatcode.train --data /checkpoints/chatcode-data --output /checkpoints/pilot --resume-from-checkpoint /checkpoints/pilot/checkpoint-N
77
+ ```
78
+
79
+ The script explicitly refuses CPU training. It writes the selected adapter,
80
+ tokenizer, provenance, training report, and candidate model card under `adapter/`.
81
+ It does not upload automatically, launch cloud hardware, or change the existing Hub
82
+ repository. There is no new dataset or GPU training run in this delivery.
83
+
84
+ ## Evaluate and release
85
+
86
+ Validation loss selects a checkpoint; it does not measure whether generated programs
87
+ work. Before releasing, compare the base and candidate on the untouched derived test
88
+ split and a separate set of conversation, instruction-following, debugging, and
89
+ coding tasks. Record every prompt, output, model revision, and generation setting.
90
+ Use tests for coding correctness and inspect chat quality for regressions.
91
+ The source bundle does **not** include a sandboxed code-execution evaluator;
92
+ never automatically execute arbitrary training data or generated programs on a
93
+ machine with credentials. Use an isolated evaluation environment.
94
+
95
+ Publish a tested candidate to a new private repository or a distinct version branch;
96
+ the old vision adapter must not be relabeled as a chat/code model. Preserve the
97
+ base revision and dataset attribution. No quality improvement is claimed yet.
98
+
99
+ For a regular cloud GPU demo, install the cloud dependencies, set
100
+ `POCKETCHAT_ADAPTER` to the compatible local adapter directory or Hub repository,
101
+ and run `python app.py`. Without an adapter it explicitly identifies itself as the
102
+ pretrained Qwen base. On Spaces set `SPACE_ID` normally via the platform.
103
+ ZeroGPU needs a separate startup/decorator integration and compatible PyTorch
104
+ environment; this ordinary GPU app is not yet a verified ZeroGPU deployment.
105
+
106
+ ## Package
107
+
108
+ `python -m chatcode.package` creates `dist/pocketvision-chat-code-source.zip`.
109
+ It includes only the active app, text pipeline, configuration, documentation,
110
+ and licenses. It excludes old weights, datasets, caches, environments, and credentials.
111
+ Project source remains GPL-3.0-only; original Qwen weights remain Apache-2.0.
112
+
113
+ Sources: [QLoRA with PEFT](https://huggingface.co/docs/peft/developer_guides/quantization),
114
+ [Hugging Face training Jobs](https://huggingface.co/docs/hub/jobs-training).
chatcode/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Text-only successor to the original PocketVision experiment."""
chatcode/app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio chat with code formatting and no image inputs."""
2
+ from functools import lru_cache
3
+ import os
4
+ import threading
5
+
6
+ from .runtime import CONFIG, answer, gpu_available, load_engine
7
+ import gradio as gr
8
+
9
+ LOCK = threading.Lock()
10
+ PREVIEW = os.environ.get("POCKETCHAT_PREVIEW") == "1" or not gpu_available()
11
+ ADAPTER = os.environ.get("POCKETCHAT_ADAPTER")
12
+
13
+
14
+ @lru_cache(maxsize=1)
15
+ def engine():
16
+ return load_engine(ADAPTER)
17
+
18
+
19
+ def respond(message, history):
20
+ if not message or not message.strip():
21
+ raise gr.Error("Enter a message first.")
22
+ if PREVIEW:
23
+ raise gr.Error("The cloud model is not connected yet.")
24
+ try:
25
+ with LOCK:
26
+ tokenizer, model = engine()
27
+ reply = answer(tokenizer, model, message, history)
28
+ except (ValueError, RuntimeError) as error:
29
+ raise gr.Error(str(error)) from error
30
+ return "", (history or []) + [
31
+ {"role": "user", "content": message}, {"role": "assistant", "content": reply}]
32
+
33
+
34
+ with gr.Blocks(title=CONFIG["name"]) as demo:
35
+ gr.Markdown("# PocketVision · Chat & Code\nA place to talk, learn, write code, and work through bugs.")
36
+ if PREVIEW:
37
+ gr.Markdown("**Interface preview** · The cloud model is not connected yet.")
38
+ elif ADAPTER:
39
+ gr.Markdown("Custom chat and programming model · Review generated code before using it.")
40
+ else:
41
+ gr.Markdown("Pretrained model · Custom chat and programming training is pending.")
42
+ chatbot = gr.Chatbot(type="messages", label="Conversation", height=460, allow_tags=False)
43
+ message = gr.Textbox(label="Your message", lines=3, max_lines=14,
44
+ placeholder="Ask a question, paste code, or describe a bug…", interactive=not PREVIEW)
45
+ with gr.Row():
46
+ send = gr.Button("Send", variant="primary", interactive=not PREVIEW)
47
+ clear = gr.Button("New chat")
48
+ gr.Examples([
49
+ "Write a Python function that removes duplicates while preserving their order.",
50
+ "Explain JavaScript async and await with a small example.",
51
+ "Help me debug my code. I’ll paste it in the next message.",
52
+ ], inputs=message)
53
+ for event in [send.click, message.submit]:
54
+ event(respond, [message, chatbot], [message, chatbot])
55
+ clear.click(lambda: ("", []), outputs=[message, chatbot])
56
+
57
+
58
+ def launch():
59
+ demo.queue(default_concurrency_limit=1).launch(
60
+ server_name="0.0.0.0" if os.environ.get("SPACE_ID") else "127.0.0.1",
61
+ server_port=int(os.environ.get("PORT", "7860")), share=False)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ launch()
chatcode/config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "PocketVision Chat & Code",
3
+ "base_model": "Qwen/Qwen3-4B-Instruct-2507",
4
+ "base_revision": "cdbee75f17c01a7cc42f958dc650907174af0554",
5
+ "dataset": "HuggingFaceTB/smoltalk",
6
+ "dataset_revision": "5feaf2fd3ffca7c237fc38d1861bc30365d48ffa",
7
+ "sources": [
8
+ {"config": "self-oss-instruct", "purpose": "programming", "weight": 0.6, "license": "odc-by", "original": "bigcode/self-oss-instruct-sc2-exec-filter-50k"},
9
+ {"config": "smol-magpie-ultra", "purpose": "conversation", "weight": 0.4, "license": "apache-2.0", "original": "HuggingFaceTB/smoltalk"}
10
+ ],
11
+ "seed": 42,
12
+ "train_examples": 20000,
13
+ "validation_examples": 256,
14
+ "test_examples": 256,
15
+ "max_sequence_length": 2048,
16
+ "max_new_tokens": 768,
17
+ "system_prompt": "You are a helpful assistant focused on conversation and programming. Explain ideas clearly. For programming tasks, provide readable code and explain relevant assumptions and edge cases. Ask a short clarifying question when essential information is missing. Be honest about uncertainty and never claim to have run code or tests unless you actually have."
18
+ }
chatcode/data.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prepare a bounded, reproducible text-only dataset on the cloud machine."""
2
+ import argparse
3
+ from collections import Counter
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+ import random
8
+ import re
9
+
10
+ from .runtime import CONFIG
11
+
12
+
13
+ def normalize_messages(row):
14
+ messages = row.get("messages")
15
+ if not isinstance(messages, list) or not messages:
16
+ raise ValueError("Expected a nonempty messages list.")
17
+ clean = []
18
+ for index, item in enumerate(messages):
19
+ role, content = item.get("role"), item.get("content")
20
+ if role not in {"system", "user", "assistant"} or not isinstance(content, str) or not content.strip():
21
+ raise ValueError("Only nonempty text messages are supported.")
22
+ if role == "system" and index != 0:
23
+ raise ValueError("System messages must come first.")
24
+ clean.append({"role": role, "content": content.strip()})
25
+ turns = clean[1:] if clean[0]["role"] == "system" else clean
26
+ if len(turns) < 2 or len(turns) % 2:
27
+ raise ValueError("Expected complete conversation turns.")
28
+ if any(m["role"] != ("user" if i % 2 == 0 else "assistant") for i, m in enumerate(turns)):
29
+ raise ValueError("Expected alternating user and assistant turns.")
30
+ if clean[0]["role"] != "system":
31
+ clean.insert(0, {"role": "system", "content": CONFIG["system_prompt"]})
32
+ return clean
33
+
34
+
35
+ def prompt_key(messages):
36
+ # Group identical opening questions, even when answers differ.
37
+ first = next(m["content"] for m in messages if m["role"] == "user")
38
+ normalized = re.sub(r"\s+", " ", first).strip().casefold()
39
+ return hashlib.sha256(normalized.encode()).hexdigest()
40
+
41
+
42
+ def encode_example(tokenizer, messages, max_length):
43
+ """Supervise assistant content and end-of-turn tokens; mask every prompt."""
44
+ ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=False)
45
+ if len(ids) > max_length:
46
+ raise ValueError("Overlength example; skip rather than truncate code or its answer.")
47
+ labels = [-100] * len(ids)
48
+ for index, message in enumerate(messages):
49
+ if message["role"] != "assistant":
50
+ continue
51
+ prefix = tokenizer.apply_chat_template(messages[:index], tokenize=True, add_generation_prompt=True)
52
+ end = tokenizer.apply_chat_template(messages[:index + 1], tokenize=True, add_generation_prompt=False)
53
+ if ids[:len(prefix)] != prefix or ids[:len(end)] != end:
54
+ raise ValueError("Chat template does not preserve assistant boundaries.")
55
+ labels[len(prefix):len(end)] = ids[len(prefix):len(end)]
56
+ if not any(x != -100 for x in labels[1:]):
57
+ raise ValueError("No assistant target tokens.")
58
+ return {"input_ids": ids, "attention_mask": [1] * len(ids), "labels": labels}
59
+
60
+
61
+ def split_for(key):
62
+ bucket = int(key[:8], 16) % 100
63
+ return "validation" if bucket < 2 else "test" if bucket < 4 else "train"
64
+
65
+
66
+ def prepare(args):
67
+ from datasets import load_dataset
68
+ from transformers import AutoTokenizer
69
+
70
+ output = Path(args.output)
71
+ if output.exists() and any(output.iterdir()):
72
+ raise FileExistsError("Use an empty data output directory.")
73
+ tokenizer = AutoTokenizer.from_pretrained(
74
+ CONFIG["base_model"], revision=CONFIG["base_revision"], trust_remote_code=False)
75
+ result = {name: [] for name in ["train", "validation", "test"]}
76
+ seen = set()
77
+ stats = {}
78
+ for source in CONFIG["sources"]:
79
+ targets = {
80
+ "train": round(args.train * source["weight"]),
81
+ "validation": args.holdout_per_source,
82
+ "test": args.holdout_per_source,
83
+ }
84
+ counts, skipped = Counter(), Counter()
85
+ stream = load_dataset(
86
+ CONFIG["dataset"], source["config"], split="train",
87
+ revision=CONFIG["dataset_revision"], streaming=True)
88
+ stream = stream.shuffle(seed=CONFIG["seed"], buffer_size=4096)
89
+ for row in stream:
90
+ try:
91
+ messages = normalize_messages(row)
92
+ key = prompt_key(messages)
93
+ if key in seen:
94
+ skipped["duplicate_prompt"] += 1
95
+ continue
96
+ encode_example(tokenizer, messages, CONFIG["max_sequence_length"])
97
+ except (ValueError, TypeError, KeyError):
98
+ skipped["invalid_or_overlength"] += 1
99
+ continue
100
+ seen.add(key)
101
+ split = split_for(key)
102
+ if counts[split] >= targets[split]:
103
+ continue
104
+ content_hash = hashlib.sha256(json.dumps(messages, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
105
+ result[split].append({"id": content_hash, "prompt_hash": key,
106
+ "source": source["config"], "messages": messages})
107
+ counts[split] += 1
108
+ if all(counts[s] >= targets[s] for s in targets):
109
+ break
110
+ if any(counts[s] < targets[s] for s in targets):
111
+ raise RuntimeError(f"Not enough usable data for {source['config']}: {dict(counts)}")
112
+ stats[source["config"]] = {"selected": dict(counts), "skipped": dict(skipped)}
113
+ print(source["config"], dict(counts), flush=True)
114
+ output.mkdir(parents=True, exist_ok=True)
115
+ hashes = {}
116
+ for split, rows in result.items():
117
+ random.Random(CONFIG["seed"]).shuffle(rows)
118
+ content = "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows)
119
+ (output / f"{split}.jsonl").write_bytes(content.encode("utf-8"))
120
+ hashes[split] = hashlib.sha256(content.encode()).hexdigest()
121
+ manifest = {"config": CONFIG, "counts": {k: len(v) for k, v in result.items()},
122
+ "sources": stats, "sha256": hashes,
123
+ "split_policy": "Hash of normalized first user question; official source test splits unused.",
124
+ "limitations": ["Synthetic data may contain mistakes.",
125
+ "Exact prompt deduplication is not semantic or repository-level decontamination.",
126
+ "The pretrained base may already have seen these data.",
127
+ "This pilot's code source focuses on Python; other languages need additional data and evaluation."]}
128
+ (output / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ parser = argparse.ArgumentParser(description="Prepare Chat & Code data on the cloud machine")
133
+ parser.add_argument("--output", default="chatcode-data")
134
+ parser.add_argument("--train", type=int, default=CONFIG["train_examples"])
135
+ parser.add_argument("--holdout-per-source", type=int, default=128)
136
+ args = parser.parse_args()
137
+ if args.train < 10 or args.train % 10 or args.holdout_per_source < 1:
138
+ parser.error("--train must be a positive multiple of 10; holdouts must be positive.")
139
+ prepare(args)
chatcode/package.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Package only source and configuration; no credentials, data, or old weights."""
2
+ from pathlib import Path
3
+ import zipfile
4
+
5
+ ROOT = Path(__file__).resolve().parent.parent
6
+
7
+
8
+ if __name__ == "__main__":
9
+ files = [ROOT / name for name in ["app.py", "chat.py", "LICENSE", "LICENSE-BASE-MODEL.txt"]]
10
+ files += [p for p in (ROOT / "chatcode").iterdir()
11
+ if p.is_file() and p.suffix in {".py", ".json", ".md", ".txt"}]
12
+ (ROOT / "dist").mkdir(exist_ok=True)
13
+ destination = ROOT / "dist/pocketvision-chat-code-source.zip"
14
+ with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED) as bundle:
15
+ for path in sorted(files):
16
+ bundle.write(path, path.relative_to(ROOT).as_posix())
17
+ print(f"Created {destination} ({destination.stat().st_size:,} bytes; source only, untrained)")
chatcode/requirements-cloud.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Install a CUDA PyTorch build separately; never use the old CPU-only requirements here.
2
+ transformers==4.57.6
3
+ peft==0.18.1
4
+ accelerate==1.12.0
5
+ huggingface-hub==0.36.2
6
+ datasets==4.4.1
7
+ bitsandbytes==0.48.2
8
+ gradio==5.50.0
chatcode/runtime.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pinned text-only inference. Model weights are loaded only on a cloud GPU."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+
8
+ ROOT = Path(__file__).resolve().parent.parent
9
+ CONFIG = json.loads(Path(__file__).with_name("config.json").read_text(encoding="utf-8"))
10
+ os.environ.setdefault("HF_HOME", str(ROOT / ".cache/huggingface"))
11
+ os.environ.setdefault("HF_HUB_DISABLE_XET", "1")
12
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
13
+ os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "false")
14
+
15
+
16
+ def conversation(prompt: str, history: list[dict] | None = None) -> list[dict]:
17
+ if not prompt.strip():
18
+ raise ValueError("Enter a message first.")
19
+ if len(prompt) > 24000:
20
+ raise ValueError("Please split this message into smaller parts.")
21
+ messages = [{"role": "system", "content": CONFIG["system_prompt"]}]
22
+ previous = history or []
23
+ if len(previous) % 2:
24
+ raise ValueError("Conversation history is incomplete. Start a new chat.")
25
+ for index, item in enumerate(previous):
26
+ if item.get("role") != ("user" if index % 2 == 0 else "assistant"):
27
+ raise ValueError("Conversation history is invalid. Start a new chat.")
28
+ if not isinstance(item.get("content"), str):
29
+ raise ValueError("This chat accepts text messages only.")
30
+ messages.append({"role": item["role"], "content": item["content"]})
31
+ messages.append({"role": "user", "content": prompt.strip()})
32
+ return messages
33
+
34
+
35
+ def gpu_available() -> bool:
36
+ import torch
37
+ return bool(torch.cuda.is_available())
38
+
39
+
40
+ def load_engine(adapter: str | None = None):
41
+ import torch
42
+ from transformers import AutoModelForCausalLM, AutoTokenizer
43
+
44
+ if not gpu_available():
45
+ raise RuntimeError("The cloud model is not connected. This computer shows the interface preview only.")
46
+ tokenizer = AutoTokenizer.from_pretrained(
47
+ CONFIG["base_model"], revision=CONFIG["base_revision"], trust_remote_code=False)
48
+ model = AutoModelForCausalLM.from_pretrained(
49
+ CONFIG["base_model"], revision=CONFIG["base_revision"], trust_remote_code=False,
50
+ dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16,
51
+ device_map={"": "cuda:0"}, attn_implementation="sdpa")
52
+ if adapter:
53
+ from peft import PeftConfig, PeftModel
54
+ adapter_config = PeftConfig.from_pretrained(adapter)
55
+ if (adapter_config.base_model_name_or_path != CONFIG["base_model"]
56
+ or adapter_config.revision != CONFIG["base_revision"]):
57
+ raise ValueError("Adapter does not match the pinned chat-and-code model.")
58
+ model = PeftModel.from_pretrained(model, adapter)
59
+ return tokenizer, model.eval()
60
+
61
+
62
+ def answer(tokenizer, model, prompt: str, history: list[dict] | None = None,
63
+ max_new_tokens: int = CONFIG["max_new_tokens"]) -> str:
64
+ import torch
65
+
66
+ if not 1 <= max_new_tokens <= 2048:
67
+ raise ValueError("Response length must be between 1 and 2,048 tokens.")
68
+ messages = conversation(prompt, history)
69
+ while True:
70
+ inputs = tokenizer.apply_chat_template(
71
+ messages, tokenize=True, add_generation_prompt=True,
72
+ return_dict=True, return_tensors="pt")
73
+ if inputs["input_ids"].shape[1] + max_new_tokens <= 4096:
74
+ break
75
+ if len(messages) <= 2:
76
+ raise ValueError("This message is too long. Please send a smaller code example.")
77
+ del messages[1:3]
78
+ inputs = inputs.to(model.device)
79
+ with torch.inference_mode():
80
+ output = model.generate(
81
+ **inputs, max_new_tokens=max_new_tokens, do_sample=True,
82
+ temperature=0.7, top_p=0.8, top_k=20,
83
+ pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id)
84
+ reply = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
85
+ if not reply:
86
+ raise RuntimeError("The model returned an empty response. Please try again.")
87
+ return reply
chatcode/test_pipeline.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small offline checks; no pretrained weights, dataset downloads, or GPU jobs."""
2
+ import hashlib
3
+ import json
4
+ from pathlib import Path
5
+ import tempfile
6
+ import unittest
7
+ from unittest.mock import patch
8
+
9
+ from .data import encode_example, normalize_messages, prompt_key
10
+ from .runtime import CONFIG, conversation, load_engine
11
+ from .train import collate, read_data
12
+
13
+
14
+ class PipelineTests(unittest.TestCase):
15
+ @classmethod
16
+ def setUpClass(cls):
17
+ from tokenizers import Tokenizer
18
+ from tokenizers.models import WordLevel
19
+ from tokenizers.pre_tokenizers import Whitespace
20
+ from transformers import PreTrainedTokenizerFast
21
+ words = ["[UNK]", "[PAD]", "<|im_start|>", "<|im_end|>",
22
+ "system", "user", "assistant", "first", "second", "answer", "other"]
23
+ tokenizer = Tokenizer(WordLevel({word: i for i, word in enumerate(words)}, unk_token="[UNK]"))
24
+ tokenizer.pre_tokenizer = Whitespace()
25
+ cls.tokenizer = PreTrainedTokenizerFast(
26
+ tokenizer_object=tokenizer, unk_token="[UNK]", pad_token="[PAD]", eos_token="<|im_end|>",
27
+ additional_special_tokens=["<|im_start|>", "<|im_end|>"])
28
+ cls.tokenizer.chat_template = (
29
+ "{% for message in messages %}{{ '<|im_start|>' + message['role'] + '\n' + "
30
+ "message['content'] + '<|im_end|>\n' }}{% endfor %}"
31
+ "{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}")
32
+
33
+ def test_multiturn_assistant_targets_and_padding(self):
34
+ messages = normalize_messages({"messages": [
35
+ {"role": "user", "content": "first"}, {"role": "assistant", "content": "answer"},
36
+ {"role": "user", "content": "second"}, {"role": "assistant", "content": "other"}]})
37
+ encoded = encode_example(self.tokenizer, messages, 2048)
38
+ targets = [x for x in encoded["labels"] if x != -100]
39
+ self.assertEqual(self.tokenizer.decode(targets), "answer <|im_end|> other <|im_end|>")
40
+ short = encode_example(self.tokenizer, messages[:3], 2048)
41
+ batch = collate([encoded, short], self.tokenizer.pad_token_id)
42
+ self.assertTrue((batch["labels"][1, len(short["input_ids"]):] == -100).all())
43
+ self.assertTrue((batch["attention_mask"][1, len(short["input_ids"]):] == 0).all())
44
+ with self.assertRaises(ValueError):
45
+ encode_example(self.tokenizer, messages, 4)
46
+
47
+ def test_no_image_records_and_no_partial_turns(self):
48
+ for messages in [
49
+ [{"role": "user", "content": [{"type": "image"}]}],
50
+ [{"role": "user", "content": "first"}],
51
+ [{"role": "assistant", "content": "answer"}, {"role": "user", "content": "first"}],
52
+ ]:
53
+ with self.assertRaises(ValueError):
54
+ normalize_messages({"messages": messages})
55
+ self.assertEqual(conversation("first")[-1], {"role": "user", "content": "first"})
56
+ with self.assertRaises(ValueError):
57
+ conversation("first", [{"role": "user", "content": "second"}])
58
+
59
+ def test_cpu_training_and_inference_fail_before_download(self):
60
+ from argparse import Namespace
61
+ from .train import train
62
+ with patch("torch.cuda.is_available", return_value=False):
63
+ with self.assertRaisesRegex(RuntimeError, "cloud model"):
64
+ load_engine()
65
+ with self.assertRaisesRegex(RuntimeError, "No training or model download"):
66
+ train(Namespace())
67
+
68
+ def test_manifest_integrity_and_prompt_separation(self):
69
+ with tempfile.TemporaryDirectory() as temp:
70
+ folder = Path(temp)
71
+ manifest = {"config": CONFIG, "sha256": {}, "counts": {}}
72
+ for split in ["train", "validation", "test"]:
73
+ messages = normalize_messages({"messages": [
74
+ {"role": "user", "content": f"question {split}"},
75
+ {"role": "assistant", "content": "answer"}]})
76
+ row = {"messages": messages, "prompt_hash": prompt_key(messages)}
77
+ raw = (json.dumps(row) + "\n").encode()
78
+ (folder / f"{split}.jsonl").write_bytes(raw)
79
+ manifest["sha256"][split] = hashlib.sha256(raw).hexdigest()
80
+ manifest["counts"][split] = 1
81
+ (folder / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
82
+ self.assertEqual(set(read_data(folder)), {"train", "validation", "test"})
83
+ (folder / "train.jsonl").write_text("changed", encoding="utf-8")
84
+ with self.assertRaisesRegex(ValueError, "Data changed"):
85
+ read_data(folder)
86
+
87
+ def test_small_qwen_lora_forward_and_gradients(self):
88
+ import torch
89
+ from peft import LoraConfig, TaskType, get_peft_model
90
+ from transformers import Qwen3Config, Qwen3ForCausalLM
91
+ torch.set_num_threads(2)
92
+ model = get_peft_model(Qwen3ForCausalLM(Qwen3Config(
93
+ vocab_size=len(self.tokenizer), hidden_size=32, intermediate_size=64,
94
+ num_hidden_layers=1, num_attention_heads=2, num_key_value_heads=1,
95
+ head_dim=16, max_position_embeddings=512)),
96
+ LoraConfig(r=2, lora_alpha=4, target_modules="all-linear", task_type=TaskType.CAUSAL_LM))
97
+ messages = normalize_messages({"messages": [
98
+ {"role": "user", "content": "first"}, {"role": "assistant", "content": "answer"}]})
99
+ batch = collate([encode_example(self.tokenizer, messages, 512)], self.tokenizer.pad_token_id)
100
+ loss = model(**batch).loss
101
+ self.assertTrue(torch.isfinite(loss))
102
+ loss.backward()
103
+ self.assertTrue(any(p.grad is not None and p.grad.abs().sum() > 0
104
+ for name, p in model.named_parameters() if "lora_B" in name))
105
+ self.assertFalse(any(p.requires_grad for name, p in model.named_parameters() if "lora_" not in name))
106
+
107
+
108
+ if __name__ == "__main__":
109
+ unittest.main()
chatcode/train.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cloud GPU QLoRA training. Never falls back to training on the user's CPU."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import shutil
7
+
8
+ from .data import encode_example, normalize_messages, prompt_key
9
+ from .runtime import CONFIG
10
+
11
+
12
+ def read_data(folder):
13
+ manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))
14
+ if manifest["config"] != CONFIG:
15
+ raise ValueError("Data manifest does not match the pinned experiment configuration.")
16
+ records, seen = {}, set()
17
+ for split in ["train", "validation", "test"]:
18
+ raw = (folder / f"{split}.jsonl").read_bytes()
19
+ if hashlib.sha256(raw).hexdigest() != manifest["sha256"][split]:
20
+ raise ValueError(f"Data changed after preparation: {split}")
21
+ records[split] = [json.loads(line) for line in raw.decode().splitlines() if line]
22
+ if not records[split] or len(records[split]) != manifest["counts"][split]:
23
+ raise ValueError(f"Unexpected split size: {split}")
24
+ for row in records[split]:
25
+ key = prompt_key(normalize_messages(row))
26
+ if key != row["prompt_hash"] or key in seen:
27
+ raise ValueError("Duplicate or inconsistent prompts across dataset splits.")
28
+ seen.add(key)
29
+ return records
30
+
31
+
32
+ def collate(examples, pad_token_id):
33
+ import torch
34
+ length = max(len(item["input_ids"]) for item in examples)
35
+ return {key: torch.tensor([item[key] + [pad] * (length - len(item[key])) for item in examples])
36
+ for key, pad in [("input_ids", pad_token_id), ("attention_mask", 0), ("labels", -100)]}
37
+
38
+
39
+ def train(args):
40
+ import torch
41
+ if not torch.cuda.is_available():
42
+ raise RuntimeError("Cloud CUDA GPU required. No training or model download was started.")
43
+ from datasets import Dataset
44
+ from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training
45
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
46
+ from transformers import Trainer, TrainingArguments, set_seed
47
+
48
+ output = Path(args.output)
49
+ if output.exists() and any(output.iterdir()) and not args.resume_from_checkpoint:
50
+ raise FileExistsError("Use an empty output directory or explicitly resume a checkpoint.")
51
+ records = read_data(Path(args.data))
52
+ set_seed(CONFIG["seed"])
53
+ tokenizer = AutoTokenizer.from_pretrained(
54
+ CONFIG["base_model"], revision=CONFIG["base_revision"], trust_remote_code=False)
55
+ tokenizer.padding_side = "right"
56
+ dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
57
+ base = AutoModelForCausalLM.from_pretrained(
58
+ CONFIG["base_model"], revision=CONFIG["base_revision"], trust_remote_code=False,
59
+ dtype=dtype, device_map={"": torch.cuda.current_device()}, attn_implementation="sdpa",
60
+ quantization_config=BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
61
+ bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=dtype))
62
+ base.config.use_cache = False
63
+ base = prepare_model_for_kbit_training(base, use_gradient_checkpointing=True,
64
+ gradient_checkpointing_kwargs={"use_reentrant": False})
65
+ model = get_peft_model(base, LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
66
+ target_modules="all-linear", bias="none", task_type=TaskType.CAUSAL_LM))
67
+ model.peft_config["default"].base_model_name_or_path = CONFIG["base_model"]
68
+ model.peft_config["default"].revision = CONFIG["base_revision"]
69
+ datasets = {split: Dataset.from_list([
70
+ encode_example(tokenizer, row["messages"], CONFIG["max_sequence_length"]) for row in records[split]
71
+ ]) for split in ["train", "validation"]}
72
+ settings = TrainingArguments(
73
+ output_dir=str(output), num_train_epochs=1, max_steps=args.max_steps,
74
+ per_device_train_batch_size=1, per_device_eval_batch_size=1,
75
+ gradient_accumulation_steps=16, learning_rate=5e-5, warmup_ratio=0.05,
76
+ lr_scheduler_type="cosine", logging_steps=5, eval_strategy="steps", eval_steps=25,
77
+ save_strategy="steps", save_steps=25, save_total_limit=2,
78
+ load_best_model_at_end=True, metric_for_best_model="eval_loss",
79
+ greater_is_better=False, bf16=dtype == torch.bfloat16, fp16=dtype == torch.float16,
80
+ gradient_checkpointing=True, gradient_checkpointing_kwargs={"use_reentrant": False},
81
+ optim="adamw_torch", report_to="none", seed=CONFIG["seed"],
82
+ dataloader_num_workers=0, remove_unused_columns=False)
83
+ trainer = Trainer(model=model, args=settings, processing_class=tokenizer,
84
+ train_dataset=datasets["train"], eval_dataset=datasets["validation"],
85
+ data_collator=lambda batch: collate(batch, tokenizer.pad_token_id))
86
+ baseline = trainer.evaluate()
87
+ trained = trainer.train(resume_from_checkpoint=args.resume_from_checkpoint)
88
+ final = trainer.evaluate()
89
+ destination = output / "adapter"
90
+ trainer.save_model(str(destination))
91
+ tokenizer.save_pretrained(destination)
92
+ shutil.copy2(Path(args.data) / "manifest.json", destination / "data_manifest.json")
93
+ report = {"config": CONFIG, "baseline_validation": baseline, "final_validation": final,
94
+ "training": trained.metrics, "counts": {k: len(v) for k, v in records.items()},
95
+ "status": "candidate_requires_answer_and_code_evaluation", "max_steps": args.max_steps}
96
+ (destination / "training_report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
97
+ (destination / "README.md").write_text(
98
+ "---\nlicense: gpl-3.0\nlibrary_name: peft\npipeline_tag: text-generation\n"
99
+ f"base_model: {CONFIG['base_model']}\nbase_model_relation: adapter\n"
100
+ "datasets:\n- HuggingFaceTB/smoltalk\ntags:\n- lora\n- code\n- experimental\n---\n\n"
101
+ "# PocketVision Chat & Code candidate\n\nText-only QLoRA adapter. "
102
+ "This candidate has validation-loss measurements only; no claim of better chat or coding accuracy. "
103
+ "See training_report.json and data_manifest.json. "
104
+ "Training data: Smol-Magpie-Ultra (Apache-2.0) and the Self-OSS-Instruct subset "
105
+ "(original: bigcode/self-oss-instruct-sc2-exec-filter-50k, ODC-BY). "
106
+ "Original base weights remain Apache-2.0; project code and adapter use GPL-3.0-only.\n",
107
+ encoding="utf-8")
108
+ for source in ["LICENSE", "LICENSE-BASE-MODEL.txt"]:
109
+ shutil.copy2(Path(__file__).resolve().parent.parent / source, destination / source)
110
+ print(f"Candidate saved to {destination}. Evaluate answers before publishing a release.")
111
+
112
+
113
+ if __name__ == "__main__":
114
+ parser = argparse.ArgumentParser(description="Train text-only Chat & Code on a cloud CUDA GPU")
115
+ parser.add_argument("--data", default="chatcode-data")
116
+ parser.add_argument("--output", required=True, help="Prefer mounted persistent cloud storage")
117
+ parser.add_argument("--max-steps", type=int, default=-1, help="25 for a smoke run; -1 for one epoch")
118
+ parser.add_argument("--resume-from-checkpoint")
119
+ args = parser.parse_args()
120
+ if args.max_steps != -1 and args.max_steps < 25:
121
+ parser.error("Use at least 25 steps so validation and checkpoint saving occur.")
122
+ train(args)
pocketvision-chat-code-source.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55bf45eb8011265a2314bf12d3c726ccd7f2d881ad64d1983679a06d1d6ab5ae
3
+ size 32278