bynn-intelligence commited on
Commit
071512e
·
verified ·
1 Parent(s): 6b65c35

DecisionNode Edge 0.9.1

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ decisionnode-edge-0.9.1-q8_0.gguf filter=lfs diff=lfs merge=lfs -text
37
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published by
637
+ the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
LICENSE-base 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 2026 Alibaba Cloud
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.
LICENSING.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensing
2
+
3
+ DecisionNode Edge and DecisionNode Edge Mini (the model weights and the `decisionnode_edge` runtime) are available under two licenses.
4
+
5
+ ## Open source: AGPL-3.0
6
+
7
+ You may use, study, modify and share DecisionNode Edge under the GNU Affero General Public License, version 3 (`LICENSE`). This suits personal projects, education, research and open-source work.
8
+
9
+ If you distribute DecisionNode Edge or a work based on it, or let others use such a work over a network, the AGPL requires you to make the complete corresponding source of that work available to them under the same license.
10
+
11
+ ## Commercial license
12
+
13
+ To use DecisionNode Edge in a commercial product or service without the obligations of the AGPL, for example inside closed-source software, in a device you sell or in a service you run for your customers, you need a commercial license from Bynn Intelligence Inc.
14
+
15
+ Write to licensing@bynn.com.
16
+
17
+ ## The base models
18
+
19
+ DecisionNode Edge is built on Qwen3.5-2B-Base and DecisionNode Edge Mini on Qwen3.5-0.8B-Base. The Qwen team releases both under the Apache License, Version 2.0. That license is in `LICENSE-base`, and `NOTICE` lists the changes we made.
MANIFEST.sha256 ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 ./LICENSE
2
+ 50cbab8a892c5f2993b8c7351a99182507472def3b1374558308605d99b86b32 ./LICENSE-base
3
+ 2014f13a6fe1d9178c84cde47bb087a7a74adbe38650f1823a944077081e86d0 ./LICENSING.md
4
+ e4dcac398e39a098e07f625ed239949296a2000d95dcc275cb0d8083ebb51dc9 ./NOTICE
5
+ 345be060d1192db591b96ba8e5ddea26ccbbd819a0958e5151527c18f6e99a3b ./README.md
6
+ 5febf5c3cb5843034f2251d959c475a4a629dec65bf3ea494b4fed0a3b8aa3aa ./calibration.json
7
+ 28b44a18f60b7e3039c503971b6d194b51c723f0c8a62d56bd6ce7f7f34e9f87 ./config.json
8
+ 8da27e0c66f1196243e6a4220213050001be1837b502ba8b20bd4e787bb1091a ./decisionnode-edge-0.9.1-q8_0.gguf
9
+ 288aeaff4fb2db60e3a706a5380d9f4a0f937bec77634513064589b26e95e19d ./decisionnode_edge.json
10
+ 82f54898bde6ff4f1af907db2d2423fc5e2efed77a4622f0b79a7b5d486d054b ./decisionnode_edge_build.json
11
+ e0a87595ad939efa5585b61844d3a2a70d29ba7752f68b8139f2195753a6bfde ./examples/request.json
12
+ d3d84ca9d2701443b84960ba25b4ee21f5125cdf03007b1dc3633c315447ba6a ./model.safetensors
13
+ 27225450ac9c6529872ee1924fcb0962ff5634834f817040f444118116f4e516 ./preprocessor_config.json
14
+ 04603015c9b8bc70dd5e7a5c8f0ff14a3ac52aaa359b16b23f662f8f51edd5cd ./readout.safetensors
15
+ 0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 ./runtime/LICENSE
16
+ 41e6c8237772a353f80aea98ef4dd63a1e0df73447d236bc2fd403b46507992b ./runtime/README.md
17
+ e0a87595ad939efa5585b61844d3a2a70d29ba7752f68b8139f2195753a6bfde ./runtime/examples/request.json
18
+ bdcc0ff2b9f4b90b20337fb98ff2817288d9c194c7fd3ab07e85b11938686b77 ./runtime/pyproject.toml
19
+ d2c1e3b3032e5499c75dc1932d26477ff1e4b8e0cf2f23043ac5c0329a117abe ./runtime/src/decisionnode_edge/__init__.py
20
+ 245003271a41ecab8fe982194acf84f9c4fc0b686762583931a9444ad2aa6354 ./runtime/src/decisionnode_edge/__main__.py
21
+ 1751dfc288ffcdd03719738000ac073a8e0b8ffe2a4e04bfc0f1ea97419bcd51 ./runtime/src/decisionnode_edge/answers.py
22
+ c34f84c5da93d012d329762b6e099bc5aa7b7d998f790b88471f75399cd3eee8 ./runtime/src/decisionnode_edge/backends.py
23
+ 4ace977690bb7ae16010a298c478f1a5056caaf724c0d696b5ddac6699225f6b ./runtime/src/decisionnode_edge/build.py
24
+ 4575c765a97ed27e40a57021a6d2ecb3bd4ff79835119e50895cd42eaae06f31 ./runtime/src/decisionnode_edge/model.py
25
+ 460a3d7a3fb93531d82bd54f0ca70e25a69cd06ee6a8b41643ed205c2a0dfb6e ./runtime/src/decisionnode_edge/request.py
26
+ 0d7a3a43ec25e21d98a3fbe9a958fb3c9cc2cc0c9b1c9a7335b73ff1310fa801 ./runtime/src/decisionnode_edge/server.py
27
+ 463a7cef3ae1cc97a989dbc664e4a9d970cdb80fec9950c718d3b68af695ec35 ./runtime/src/decisionnode_edge/template.py
28
+ 6e9f31870a35eb9372bbc8719603e5d02f2e07eff90af9f7b77fe3b17d3628ff ./tokenizer.json
29
+ 429721f730f42043159445b48039714682fac2cef2ad0e82917dfa0c8ca5f430 ./tokenizer_config.json
30
+ d039cd7d88b3502a99edd455496b75b44ecf7dd3b3669748bafac37e6cecc085 ./video_preprocessor_config.json
NOTICE ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ DecisionNode Edge 0.9.1
2
+ Copyright 2026 Bynn Intelligence Inc.
3
+
4
+ DecisionNode Edge is licensed under the GNU Affero General Public License, version 3 (see LICENSE),
5
+ or under a commercial license from Bynn Intelligence Inc. (licensing@bynn.com). See LICENSING.md.
6
+
7
+ This model is a modified version of Qwen3.5-2B-Base (https://huggingface.co/Qwen/Qwen3.5-2B-Base),
8
+ which is licensed under the Apache License, Version 2.0 (see LICENSE-base). Bynn Intelligence Inc.
9
+ further trained the model and added a decision head and a calibration. The base model's multi-token
10
+ prediction layer is not included.
README.md ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: agpl-3.0
3
+ license_link: LICENSE
4
+ base_model: Qwen/Qwen3.5-2B-Base
5
+ base_model_relation: finetune
6
+ library_name: transformers
7
+ tags:
8
+ - decision-making
9
+ - classification
10
+ - calibration
11
+ - structured-output
12
+ - on-device
13
+ - multimodal
14
+ ---
15
+
16
+ # DecisionNode Edge
17
+
18
+ DecisionNode Edge is an open-weight decision model from [Bynn Intelligence](https://decisionnode.com). It reads text and images and answers each question with a typed, calibrated decision: a choice, a score, a yes-or-no probability or a number. It never generates free text. It runs entirely on your own hardware, from a datacenter GPU to a laptop CPU, and uses the same request and response format as the [DecisionNode API](https://decisionnode.com/docs/api).
19
+
20
+ This repository contains DecisionNode Edge 0.9.1, the larger of the two DecisionNode Edge models. [DecisionNode Edge Mini](https://huggingface.co/bynn-intelligence-com/decisionnode-edge-mini) is a 0.85-billion-parameter sibling for CPUs and constrained devices.
21
+
22
+ ## Highlights
23
+
24
+ - **Typed decisions instead of text.** Four question types, each answered as a probability distribution over the allowed values, ready to use in code without parsing.
25
+ - **Calibrated.** Probabilities are calibrated on held-out data, so a fixed threshold such as 0.7 means the same thing from one question to the next.
26
+ - **Constant cost per question.** Every question is a single forward pass, whether it has 2 options or 255.
27
+ - **Fast everywhere.** Optimized backends for NVIDIA GPUs, Apple silicon, x86 CPUs and llama.cpp devices, selected automatically, with consistent answers across all of them.
28
+ - **Private by design.** Inference runs offline. Nothing you send to the model leaves your machine.
29
+ - **Compatible with the DecisionNode API.** Code written for the hosted API runs against DecisionNode Edge with only the transport changed.
30
+
31
+ ## The DecisionNode family
32
+
33
+ DecisionNode Edge is the open-weight member of the DecisionNode family. The hosted models, DecisionNode and DecisionNode Flash, offer the highest accuracy and the full feature set through the [DecisionNode API](https://decisionnode.com/docs/api), at very low cost.
34
+
35
+ | Model | Availability | Decision accuracy |
36
+ |---|---|---|
37
+ | DecisionNode | Hosted API | 81.7% |
38
+ | DecisionNode Flash | Hosted API | 78.3% |
39
+ | DecisionNode Edge | Open weights | 74.2% |
40
+ | DecisionNode Edge Mini | Open weights | 69.2% |
41
+
42
+ All four models are measured on the same 15-benchmark evaluation suite (see Evaluation).
43
+
44
+ Available only on the hosted platform:
45
+
46
+ - **Boosters.** Specialist models that read each image before the decision is made: Human Age, AI-generated image detection, Face detection, Face recognition, OCR, Depth Vision and Segment Vision. See [boosters](https://decisionnode.com/docs/concepts/boosters).
47
+ - **Knowledge.** Connect your own documents, and the Knowledge booster retrieves the passages each decision needs. See [knowledge](https://decisionnode.com/docs/knowledge).
48
+ - **Fine-tuning.** Adapt DecisionNode to your own decisions and data. See [fine-tuning](https://decisionnode.com/docs/fine-tuning).
49
+ - **Video and localization.** Video input, and points and bounding boxes in images.
50
+ - **Scale.** Streaming sessions for high-frequency decisions, batch jobs at a discount, file uploads and inputs of up to 65,536 tokens.
51
+ - **Low cost.** Pricing starts at a few cents per million input tokens, output tokens are free, and every account includes a free daily allowance. See [pricing](https://decisionnode.com/#pricing).
52
+
53
+ [Create a free account](https://decisionnode.com/console/keys) to get an API key.
54
+
55
+ ### Open models
56
+
57
+ | Model | Parameters | Decision accuracy | NVIDIA RTX PRO 6000 (vLLM) | Apple M5 Max (MLX) | Desktop CPU (OpenVINO) |
58
+ |---|---|---|---|---|---|
59
+ | [DecisionNode Edge](https://huggingface.co/bynn-intelligence-com/decisionnode-edge) | 2.21B | 74.2% | 9.5 ms | 35 ms | 0.46 s |
60
+ | [DecisionNode Edge Mini](https://huggingface.co/bynn-intelligence-com/decisionnode-edge-mini) | 0.85B | 69.2% | 7.3 ms | 17 ms | 0.24 s |
61
+
62
+ Decision accuracy is the mean over our 15-benchmark evaluation suite (see Evaluation). Times are the median for one question at about 500 tokens of input; the desktop CPU is an 8-core AMD Ryzen 7 9800X3D.
63
+
64
+ ## Model details
65
+
66
+ | | |
67
+ |---|---|
68
+ | Developer | Bynn Intelligence Inc. |
69
+ | Version | 0.9.1 (October 2026) |
70
+ | Parameters | 2.21 billion (1.88 billion in the language model, 0.33 billion in the vision encoder) |
71
+ | Base model | [Qwen3.5-2B-Base](https://huggingface.co/Qwen/Qwen3.5-2B-Base) |
72
+ | Input | Text, and up to 16 images per request (JPEG, PNG or WebP) |
73
+ | Output | Typed decisions: `choice`, `score`, `truth` and `number` |
74
+ | Context | Evaluated on inputs of up to 8,192 tokens; the runtime accepts up to 16,384 |
75
+ | Weights | bfloat16 safetensors, plus an 8-bit GGUF build (2.0 GB) |
76
+ | License | AGPL-3.0, or a commercial license from Bynn Intelligence |
77
+
78
+ ## Quick start
79
+
80
+ Install the runtime from PyPI:
81
+
82
+ ```bash
83
+ pip install decisionnode-edge # PyTorch, Transformers and safetensors
84
+ pip install "decisionnode-edge[images]" # adds image support
85
+ ```
86
+
87
+ Ask a question:
88
+
89
+ ```python
90
+ from huggingface_hub import snapshot_download
91
+ from decisionnode_edge import EdgeModel
92
+
93
+ model = EdgeModel.load(snapshot_download("bynn-intelligence-com/decisionnode-edge"))
94
+ response = model.decide({
95
+ "state": "Customer: I was charged twice and nobody has replied for 3 days.",
96
+ "questions": {
97
+ "route": {
98
+ "type": "choice",
99
+ "instructions": "Where should this go?",
100
+ "criteria": {"billing": "money", "bug": "broken", "account": "login"},
101
+ },
102
+ "urgency": {
103
+ "type": "score",
104
+ "instructions": "How urgent is this?",
105
+ "criteria": ["routine", "today", "urgent", "critical"],
106
+ },
107
+ "escalate": {"type": "truth", "instructions": "Escalate to a human now?"},
108
+ },
109
+ })
110
+ print(response["answers"]["route"]["choice"], response["answers"]["escalate"]["truth"])
111
+ ```
112
+
113
+ The response follows the DecisionNode API:
114
+
115
+ ```json
116
+ {
117
+ "model": "decisionnode-edge-0.9.1",
118
+ "answers": {
119
+ "route": {"type": "choice", "choice": "billing", "confidence": 0.93, "probabilities": {"account": 0.02, "billing": 0.95, "bug": 0.03}},
120
+ "urgency": {"type": "score", "score": 2.2, "confidence": 0.57, "legend": {"0": "routine", "1": "today", "2": "urgent", "3": "critical"}, "probabilities": {"0": 0.01, "1": 0.09, "2": 0.59, "3": 0.31}},
121
+ "escalate": {"type": "truth", "truth": 0.74}
122
+ },
123
+ "usage": {"input_tokens": 103, "output_tokens": 0}
124
+ }
125
+ ```
126
+
127
+ Images are passed as base64 `data` with a `media_type`, or as a local `path`:
128
+
129
+ ```python
130
+ model.decide({
131
+ "state": {"claim": {"merchant": "Nordic Rail", "total": "740.00", "currency": "SEK"}},
132
+ "images": [{"id": "receipt", "path": "receipt.jpg"}],
133
+ "questions": {
134
+ "total_matches": {"type": "truth", "instructions": "Does the total on the receipt equal the total in the claim?"},
135
+ "items": {"type": "number", "instructions": "How many line items are on the receipt?", "min": 0, "max": 50},
136
+ },
137
+ })
138
+ ```
139
+
140
+ The runtime also runs from the command line (`python -m decisionnode_edge <model-folder> request.json`) and as a local HTTP server (`python -m decisionnode_edge serve <model-folder>`).
141
+
142
+ ## Question types
143
+
144
+ | Type | You provide | You receive |
145
+ |---|---|---|
146
+ | `choice` | 1 to 255 options, each with an optional description | the selected option, a confidence and a probability for every option |
147
+ | `score` | 1 to 10 ordered levels, from low to high | the expected level, a confidence and a probability for every level |
148
+ | `truth` | a statement or question, with optional `true` and `false` criteria | the probability that the answer is yes |
149
+ | `number` | `min`, `max` and `step` (up to 4,096 values) | the most probable value, the expected value, a confidence and the probable values |
150
+
151
+ Write what the question means into `instructions` and `criteria`; the question's key is never shown to the model. Images are seen by every question in the request.
152
+
153
+ ## Performance
154
+
155
+ `EdgeModel.load` selects the fastest backend installed on your machine. Every backend computes the same internal representation and applies the same decision head and calibration, so answers are consistent across devices. Median time for one question at about 500 and 2,000 tokens of input:
156
+
157
+ | Device | Backend | Install | Time |
158
+ |---|---|---|---|
159
+ | NVIDIA GPU | vLLM | `pip install "decisionnode-edge[vllm]"` | 9.5 / 23 ms (RTX PRO 6000) |
160
+ | Apple silicon | MLX | `pip install "decisionnode-edge[mlx]"` | 35 / 127 ms (M5 Max) |
161
+ | x86 CPU | OpenVINO | `pip install "decisionnode-edge[openvino]"`, then a one-time build | 0.46 / 1.7 s (Ryzen 7 9800X3D) |
162
+ | Any device llama.cpp supports, including NVIDIA Jetson | llama.cpp with the included 8-bit GGUF | `llama-server` on your path | 14 / 44 ms (RTX PRO 6000), 55 / 212 ms (M5 Max), 1.1 / 5.1 s (Ryzen 7 9800X3D) |
163
+ | Any | PyTorch (reference) | included | 14 / 28 ms (RTX PRO 6000, with optional kernels) |
164
+
165
+ Each backend reproduces the reference bfloat16 answer on at least 98.6% of a fixed set of held-out questions. Images, and inputs longer than a backend supports, are handled by the PyTorch backend automatically. A request with several questions costs one forward pass per question.
166
+
167
+ GPU memory in bfloat16 with PyTorch, one request at a time:
168
+
169
+ | Input | Peak memory |
170
+ |---|---|
171
+ | Weights alone | 4.43 GB |
172
+ | 2,048 text tokens | 4.62 GB |
173
+ | 8,192 text tokens | 5.09 GB |
174
+ | 16,384 text tokens | 5.71 GB |
175
+ | A 2,048-pixel image (3,109 tokens) | 5.10 GB |
176
+
177
+ A GPU with 6 GB of memory serves requests of up to about 8,000 tokens in bfloat16; the 8-bit GGUF build needs roughly half the memory for the weights.
178
+
179
+ ## Evaluation
180
+
181
+ We evaluate the DecisionNode models on an internal suite of 15 held-out decision benchmarks. The suite covers routing and triage, classification, scoring against rubrics, rule following, long documents, multilingual input, knowledge-intensive questions, decisions in web tasks and resistance to prompt injection.
182
+
183
+ | Model | Mean accuracy |
184
+ |---|---|
185
+ | DecisionNode Edge 0.9.1 (bfloat16) | 74.2% |
186
+ | DecisionNode Edge 0.9.1 (8-bit GGUF) | 74.2% |
187
+
188
+ Compared with DecisionNode Edge Mini, Edge is about 5 points more accurate and roughly half as fast on a CPU. The 8-bit build matches the bfloat16 weights on all 15 benchmarks; 4-bit builds lose accuracy and are not offered.
189
+
190
+ ## Intended use
191
+
192
+ DecisionNode Edge is designed for the frequent, well-defined judgments inside software, where hand-written rules are too brittle and a general-purpose language model is too slow, too costly or too far away:
193
+
194
+ - routing and triage of tickets, messages, documents and alerts
195
+ - classification and scoring against criteria you define in the request
196
+ - validation and guardrail checks before an action runs
197
+ - reading values from images, such as whether a total matches or how many items are present
198
+ - applications that must run offline or keep data on the device
199
+
200
+ ## Limitations
201
+
202
+ - **Decisions about people need human oversight.** Do not use DecisionNode Edge to make consequential decisions about individuals on its own. Uses in hiring, credit, housing, insurance, education, benefits, law enforcement or health care require a person who reviews each decision and can overrule it, in line with the DecisionNode acceptable use policy.
203
+ - **Calibrated, not infallible.** An answer given with probability 0.9 is wrong about one time in ten. Use the probabilities to decide when to defer to a person or a larger model.
204
+ - **Accuracy varies by domain and language.** Evaluate the model on your own data before relying on it.
205
+ - **Input length.** The model was evaluated on inputs of up to 8,192 tokens. The runtime accepts up to 16,384 tokens and rejects longer inputs rather than truncating them.
206
+ - **Not a generative model.** DecisionNode Edge does not produce text. Use it through the runtime; loading it in a text-generation pipeline yields meaningless output.
207
+ - **Scope.** Video input, object localization, boosters, knowledge and fine-tuning are available on the hosted DecisionNode platform, not in DecisionNode Edge.
208
+
209
+ ## Files
210
+
211
+ | File | Contents |
212
+ |---|---|
213
+ | `model.safetensors`, `config.json` | model weights (bfloat16) and configuration |
214
+ | `readout.safetensors`, `calibration.json` | decision head and calibration |
215
+ | `tokenizer.json`, `tokenizer_config.json` | tokenizer |
216
+ | `preprocessor_config.json`, `video_preprocessor_config.json` | image preprocessing settings |
217
+ | `decisionnode_edge.json` | prompt format and limits used by the runtime |
218
+ | `decisionnode-edge-0.9.1-q8_0.gguf`, `decisionnode_edge_build.json` | 8-bit GGUF build for llama.cpp and its build record |
219
+ | `runtime/` | the `decisionnode-edge` Python package, for offline installation (`pip install ./runtime`) |
220
+ | `examples/request.json` | an example request |
221
+ | `LICENSE`, `LICENSING.md`, `NOTICE` | license terms |
222
+ | `LICENSE-base` | the license of the base model |
223
+ | `MANIFEST.sha256` | checksums of every file |
224
+
225
+ ## License
226
+
227
+ DecisionNode Edge is released under the [GNU Affero General Public License v3.0](LICENSE). For use in commercial products and services without the obligations of the AGPL, a commercial license is available from Bynn Intelligence Inc.; see [LICENSING.md](LICENSING.md).
228
+
229
+ The base model, [Qwen3.5-2B-Base](https://huggingface.co/Qwen/Qwen3.5-2B-Base), is released by the Qwen team under the Apache License 2.0, reproduced in `LICENSE-base`.
230
+
231
+ ## Citation
232
+
233
+ ```bibtex
234
+ @misc{bynn2026decisionnodeedge,
235
+ title = {{DecisionNode Edge}},
236
+ author = {{Bynn Intelligence}},
237
+ year = {2026},
238
+ url = {https://huggingface.co/bynn-intelligence-com/decisionnode-edge}
239
+ }
240
+ ```
241
+
242
+ ## Contact
243
+
244
+ Commercial licensing, questions and reports: [licensing@bynn.com](mailto:licensing@bynn.com). The DecisionNode API and accounts: [decisionnode.com](https://decisionnode.com).
calibration.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "decisionnode-edge-calibration-1",
3
+ "text": {
4
+ "choice": {
5
+ "t0": 1.2375112770461538,
6
+ "t1": 0.0,
7
+ "k_min": 2,
8
+ "k_max": 174
9
+ },
10
+ "truth": {
11
+ "temperature": 1.3413976982253513,
12
+ "bias": -0.02644671770889415
13
+ },
14
+ "score": {
15
+ "t0": 1.0,
16
+ "t1": 0.0,
17
+ "k_min": 3,
18
+ "k_max": 10
19
+ }
20
+ },
21
+ "image": {}
22
+ }
config.json ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3_5ForConditionalGeneration"
4
+ ],
5
+ "dtype": "bfloat16",
6
+ "image_token_id": 248056,
7
+ "model_type": "qwen3_5",
8
+ "text_config": {
9
+ "attention_bias": false,
10
+ "attention_dropout": 0.0,
11
+ "attn_output_gate": true,
12
+ "bos_token_id": null,
13
+ "dtype": "bfloat16",
14
+ "eos_token_id": 248044,
15
+ "full_attention_interval": 4,
16
+ "head_dim": 256,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 2048,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 6144,
21
+ "layer_types": [
22
+ "linear_attention",
23
+ "linear_attention",
24
+ "linear_attention",
25
+ "full_attention",
26
+ "linear_attention",
27
+ "linear_attention",
28
+ "linear_attention",
29
+ "full_attention",
30
+ "linear_attention",
31
+ "linear_attention",
32
+ "linear_attention",
33
+ "full_attention",
34
+ "linear_attention",
35
+ "linear_attention",
36
+ "linear_attention",
37
+ "full_attention",
38
+ "linear_attention",
39
+ "linear_attention",
40
+ "linear_attention",
41
+ "full_attention",
42
+ "linear_attention",
43
+ "linear_attention",
44
+ "linear_attention",
45
+ "full_attention"
46
+ ],
47
+ "linear_conv_kernel_dim": 4,
48
+ "linear_key_head_dim": 128,
49
+ "linear_num_key_heads": 16,
50
+ "linear_num_value_heads": 16,
51
+ "linear_value_head_dim": 128,
52
+ "mamba_ssm_dtype": "float32",
53
+ "max_position_embeddings": 262144,
54
+ "mlp_only_layers": [],
55
+ "model_type": "qwen3_5_text",
56
+ "mtp_num_hidden_layers": 0,
57
+ "mtp_use_dedicated_embeddings": false,
58
+ "num_attention_heads": 8,
59
+ "num_hidden_layers": 24,
60
+ "num_key_value_heads": 2,
61
+ "pad_token_id": null,
62
+ "partial_rotary_factor": 0.25,
63
+ "rms_norm_eps": 1e-06,
64
+ "rope_parameters": {
65
+ "mrope_interleaved": true,
66
+ "mrope_section": [
67
+ 11,
68
+ 11,
69
+ 10
70
+ ],
71
+ "partial_rotary_factor": 0.25,
72
+ "rope_theta": 10000000,
73
+ "rope_type": "default"
74
+ },
75
+ "tie_word_embeddings": true,
76
+ "use_cache": true,
77
+ "vocab_size": 248384
78
+ },
79
+ "tie_word_embeddings": true,
80
+ "transformers_version": "5.18.0",
81
+ "video_token_id": 248057,
82
+ "vision_config": {
83
+ "deepstack_visual_indexes": [],
84
+ "depth": 24,
85
+ "dtype": "bfloat16",
86
+ "hidden_act": "gelu_pytorch_tanh",
87
+ "hidden_size": 1024,
88
+ "in_channels": 3,
89
+ "initializer_range": 0.02,
90
+ "intermediate_size": 4096,
91
+ "model_type": "qwen3_5_vision",
92
+ "num_heads": 16,
93
+ "num_position_embeddings": 2304,
94
+ "out_hidden_size": 2048,
95
+ "patch_size": 16,
96
+ "rope_parameters": {
97
+ "rope_theta": 10000.0,
98
+ "rope_type": "axial"
99
+ },
100
+ "spatial_merge_size": 2,
101
+ "temporal_patch_size": 2
102
+ },
103
+ "vision_end_token_id": 248054,
104
+ "vision_start_token_id": 248053
105
+ }
decisionnode-edge-0.9.1-q8_0.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8da27e0c66f1196243e6a4220213050001be1837b502ba8b20bd4e787bb1091a
3
+ size 2012145024
decisionnode_edge.json ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "decisionnode-edge-1",
3
+ "name": "decisionnode-edge-0.9.1",
4
+ "template": {
5
+ "version": 2,
6
+ "layout": "state_first",
7
+ "image_labels": "Picture <n> (<id>): ",
8
+ "answer_cue": "Answer",
9
+ "added_tokens": [
10
+ "<|state|>",
11
+ "<|question|>",
12
+ "<|answer|>",
13
+ "<|yes|>",
14
+ "<|no|>",
15
+ "<|opt_000|>",
16
+ "<|opt_001|>",
17
+ "<|opt_002|>",
18
+ "<|opt_003|>",
19
+ "<|opt_004|>",
20
+ "<|opt_005|>",
21
+ "<|opt_006|>",
22
+ "<|opt_007|>",
23
+ "<|opt_008|>",
24
+ "<|opt_009|>",
25
+ "<|opt_010|>",
26
+ "<|opt_011|>",
27
+ "<|opt_012|>",
28
+ "<|opt_013|>",
29
+ "<|opt_014|>",
30
+ "<|opt_015|>",
31
+ "<|opt_016|>",
32
+ "<|opt_017|>",
33
+ "<|opt_018|>",
34
+ "<|opt_019|>",
35
+ "<|opt_020|>",
36
+ "<|opt_021|>",
37
+ "<|opt_022|>",
38
+ "<|opt_023|>",
39
+ "<|opt_024|>",
40
+ "<|opt_025|>",
41
+ "<|opt_026|>",
42
+ "<|opt_027|>",
43
+ "<|opt_028|>",
44
+ "<|opt_029|>",
45
+ "<|opt_030|>",
46
+ "<|opt_031|>",
47
+ "<|opt_032|>",
48
+ "<|opt_033|>",
49
+ "<|opt_034|>",
50
+ "<|opt_035|>",
51
+ "<|opt_036|>",
52
+ "<|opt_037|>",
53
+ "<|opt_038|>",
54
+ "<|opt_039|>",
55
+ "<|opt_040|>",
56
+ "<|opt_041|>",
57
+ "<|opt_042|>",
58
+ "<|opt_043|>",
59
+ "<|opt_044|>",
60
+ "<|opt_045|>",
61
+ "<|opt_046|>",
62
+ "<|opt_047|>",
63
+ "<|opt_048|>",
64
+ "<|opt_049|>",
65
+ "<|opt_050|>",
66
+ "<|opt_051|>",
67
+ "<|opt_052|>",
68
+ "<|opt_053|>",
69
+ "<|opt_054|>",
70
+ "<|opt_055|>",
71
+ "<|opt_056|>",
72
+ "<|opt_057|>",
73
+ "<|opt_058|>",
74
+ "<|opt_059|>",
75
+ "<|opt_060|>",
76
+ "<|opt_061|>",
77
+ "<|opt_062|>",
78
+ "<|opt_063|>",
79
+ "<|opt_064|>",
80
+ "<|opt_065|>",
81
+ "<|opt_066|>",
82
+ "<|opt_067|>",
83
+ "<|opt_068|>",
84
+ "<|opt_069|>",
85
+ "<|opt_070|>",
86
+ "<|opt_071|>",
87
+ "<|opt_072|>",
88
+ "<|opt_073|>",
89
+ "<|opt_074|>",
90
+ "<|opt_075|>",
91
+ "<|opt_076|>",
92
+ "<|opt_077|>",
93
+ "<|opt_078|>",
94
+ "<|opt_079|>",
95
+ "<|opt_080|>",
96
+ "<|opt_081|>",
97
+ "<|opt_082|>",
98
+ "<|opt_083|>",
99
+ "<|opt_084|>",
100
+ "<|opt_085|>",
101
+ "<|opt_086|>",
102
+ "<|opt_087|>",
103
+ "<|opt_088|>",
104
+ "<|opt_089|>",
105
+ "<|opt_090|>",
106
+ "<|opt_091|>",
107
+ "<|opt_092|>",
108
+ "<|opt_093|>",
109
+ "<|opt_094|>",
110
+ "<|opt_095|>",
111
+ "<|opt_096|>",
112
+ "<|opt_097|>",
113
+ "<|opt_098|>",
114
+ "<|opt_099|>",
115
+ "<|opt_100|>",
116
+ "<|opt_101|>",
117
+ "<|opt_102|>",
118
+ "<|opt_103|>",
119
+ "<|opt_104|>",
120
+ "<|opt_105|>",
121
+ "<|opt_106|>",
122
+ "<|opt_107|>",
123
+ "<|opt_108|>",
124
+ "<|opt_109|>",
125
+ "<|opt_110|>",
126
+ "<|opt_111|>",
127
+ "<|opt_112|>",
128
+ "<|opt_113|>",
129
+ "<|opt_114|>",
130
+ "<|opt_115|>",
131
+ "<|opt_116|>",
132
+ "<|opt_117|>",
133
+ "<|opt_118|>",
134
+ "<|opt_119|>",
135
+ "<|opt_120|>",
136
+ "<|opt_121|>",
137
+ "<|opt_122|>",
138
+ "<|opt_123|>",
139
+ "<|opt_124|>",
140
+ "<|opt_125|>",
141
+ "<|opt_126|>",
142
+ "<|opt_127|>",
143
+ "<|opt_128|>",
144
+ "<|opt_129|>",
145
+ "<|opt_130|>",
146
+ "<|opt_131|>",
147
+ "<|opt_132|>",
148
+ "<|opt_133|>",
149
+ "<|opt_134|>",
150
+ "<|opt_135|>",
151
+ "<|opt_136|>",
152
+ "<|opt_137|>",
153
+ "<|opt_138|>",
154
+ "<|opt_139|>",
155
+ "<|opt_140|>",
156
+ "<|opt_141|>",
157
+ "<|opt_142|>",
158
+ "<|opt_143|>",
159
+ "<|opt_144|>",
160
+ "<|opt_145|>",
161
+ "<|opt_146|>",
162
+ "<|opt_147|>",
163
+ "<|opt_148|>",
164
+ "<|opt_149|>",
165
+ "<|opt_150|>",
166
+ "<|opt_151|>",
167
+ "<|opt_152|>",
168
+ "<|opt_153|>",
169
+ "<|opt_154|>",
170
+ "<|opt_155|>",
171
+ "<|opt_156|>",
172
+ "<|opt_157|>",
173
+ "<|opt_158|>",
174
+ "<|opt_159|>",
175
+ "<|opt_160|>",
176
+ "<|opt_161|>",
177
+ "<|opt_162|>",
178
+ "<|opt_163|>",
179
+ "<|opt_164|>",
180
+ "<|opt_165|>",
181
+ "<|opt_166|>",
182
+ "<|opt_167|>",
183
+ "<|opt_168|>",
184
+ "<|opt_169|>",
185
+ "<|opt_170|>",
186
+ "<|opt_171|>",
187
+ "<|opt_172|>",
188
+ "<|opt_173|>",
189
+ "<|opt_174|>",
190
+ "<|opt_175|>",
191
+ "<|opt_176|>",
192
+ "<|opt_177|>",
193
+ "<|opt_178|>",
194
+ "<|opt_179|>",
195
+ "<|opt_180|>",
196
+ "<|opt_181|>",
197
+ "<|opt_182|>",
198
+ "<|opt_183|>",
199
+ "<|opt_184|>",
200
+ "<|opt_185|>",
201
+ "<|opt_186|>",
202
+ "<|opt_187|>",
203
+ "<|opt_188|>",
204
+ "<|opt_189|>",
205
+ "<|opt_190|>",
206
+ "<|opt_191|>",
207
+ "<|opt_192|>",
208
+ "<|opt_193|>",
209
+ "<|opt_194|>",
210
+ "<|opt_195|>",
211
+ "<|opt_196|>",
212
+ "<|opt_197|>",
213
+ "<|opt_198|>",
214
+ "<|opt_199|>",
215
+ "<|opt_200|>",
216
+ "<|opt_201|>",
217
+ "<|opt_202|>",
218
+ "<|opt_203|>",
219
+ "<|opt_204|>",
220
+ "<|opt_205|>",
221
+ "<|opt_206|>",
222
+ "<|opt_207|>",
223
+ "<|opt_208|>",
224
+ "<|opt_209|>",
225
+ "<|opt_210|>",
226
+ "<|opt_211|>",
227
+ "<|opt_212|>",
228
+ "<|opt_213|>",
229
+ "<|opt_214|>",
230
+ "<|opt_215|>",
231
+ "<|opt_216|>",
232
+ "<|opt_217|>",
233
+ "<|opt_218|>",
234
+ "<|opt_219|>",
235
+ "<|opt_220|>",
236
+ "<|opt_221|>",
237
+ "<|opt_222|>",
238
+ "<|opt_223|>",
239
+ "<|opt_224|>",
240
+ "<|opt_225|>",
241
+ "<|opt_226|>",
242
+ "<|opt_227|>",
243
+ "<|opt_228|>",
244
+ "<|opt_229|>",
245
+ "<|opt_230|>",
246
+ "<|opt_231|>",
247
+ "<|opt_232|>",
248
+ "<|opt_233|>",
249
+ "<|opt_234|>",
250
+ "<|opt_235|>",
251
+ "<|opt_236|>",
252
+ "<|opt_237|>",
253
+ "<|opt_238|>",
254
+ "<|opt_239|>",
255
+ "<|opt_240|>",
256
+ "<|opt_241|>",
257
+ "<|opt_242|>",
258
+ "<|opt_243|>",
259
+ "<|opt_244|>",
260
+ "<|opt_245|>",
261
+ "<|opt_246|>",
262
+ "<|opt_247|>",
263
+ "<|opt_248|>",
264
+ "<|opt_249|>",
265
+ "<|opt_250|>",
266
+ "<|opt_251|>",
267
+ "<|opt_252|>",
268
+ "<|opt_253|>",
269
+ "<|opt_254|>",
270
+ "<|opt_255|>"
271
+ ],
272
+ "first_token_id": 248077,
273
+ "code_seed_hex": "6a6566662d74656d706c6174652d32"
274
+ },
275
+ "readout": {
276
+ "file": "readout.safetensors",
277
+ "tensor": "readout.weight",
278
+ "first_token_id": 248077,
279
+ "rows": 261,
280
+ "dtype": "float32"
281
+ },
282
+ "calibration": "calibration.json",
283
+ "limits": {
284
+ "max_input_tokens": 16384,
285
+ "max_image_side": 2048,
286
+ "max_images": 16,
287
+ "max_options": 255,
288
+ "max_levels": 10,
289
+ "max_grid_values": 4096
290
+ }
291
+ }
decisionnode_edge_build.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "decisionnode-edge-build-1",
3
+ "backend": "llamacpp",
4
+ "model": "decisionnode-edge-0.9.1",
5
+ "model_fingerprint": "b46a3cb3c389f9e4ad1472f0a3420260d45871879cccf7aa7424f5cf8a9012b0",
6
+ "files": {
7
+ "gguf": "decisionnode-edge-0.9.1-q8_0.gguf"
8
+ },
9
+ "type": "q8_0",
10
+ "bytes": 2012145024,
11
+ "llama_cpp": "f174553",
12
+ "converted": "convert_hf_to_gguf.py --no-mtp --outtype q8_0 (llama.cpp f174553)",
13
+ "general_name": "DecisionNode Edge 0.9.1"
14
+ }
examples/request.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "state": {
3
+ "ticket": "Hi, I was charged twice for my March invoice and nobody has replied to my two emails since Monday. Please refund the second charge.",
4
+ "customer": {"plan": "business", "since": "2023-05-14"}
5
+ },
6
+ "questions": {
7
+ "route": {
8
+ "type": "choice",
9
+ "instructions": "Which team should handle `ticket`?",
10
+ "criteria": {
11
+ "billing": "charges, invoices, refunds",
12
+ "bug": "something in the product is broken",
13
+ "account": "login, access, settings"
14
+ }
15
+ },
16
+ "urgency": {
17
+ "type": "score",
18
+ "instructions": "How urgent is `ticket`?",
19
+ "criteria": ["routine", "today", "urgent", "critical"]
20
+ },
21
+ "refund": {
22
+ "type": "truth",
23
+ "instructions": "Does the customer ask for a refund?"
24
+ },
25
+ "emails": {
26
+ "type": "number",
27
+ "instructions": "How many emails has the customer sent before this one?",
28
+ "min": 0,
29
+ "max": 10
30
+ }
31
+ }
32
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3d84ca9d2701443b84960ba25b4ee21f5125cdf03007b1dc3633c315447ba6a
3
+ size 4426821008
preprocessor_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "size": {
3
+ "longest_edge": 16777216,
4
+ "shortest_edge": 65536
5
+ },
6
+ "patch_size": 16,
7
+ "temporal_patch_size": 2,
8
+ "merge_size": 2,
9
+ "image_mean": [
10
+ 0.5,
11
+ 0.5,
12
+ 0.5
13
+ ],
14
+ "image_std": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "processor_class": "Qwen3VLProcessor",
20
+ "image_processor_type": "Qwen2VLImageProcessorFast"
21
+ }
readout.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04603015c9b8bc70dd5e7a5c8f0ff14a3ac52aaa359b16b23f662f8f51edd5cd
3
+ size 2138256
runtime/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published by
637
+ the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
runtime/README.md ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DecisionNode Edge runtime
2
+
3
+ The official runtime for the DecisionNode Edge models from Bynn Intelligence. Load a model, send a request in the DecisionNode API format, and receive typed, calibrated decisions. It runs on NVIDIA GPUs, Apple silicon and CPUs, entirely offline.
4
+
5
+ Models: [DecisionNode Edge](https://huggingface.co/bynn-intelligence-com/decisionnode-edge) and [DecisionNode Edge Mini](https://huggingface.co/bynn-intelligence-com/decisionnode-edge-mini) on Hugging Face.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install decisionnode-edge # torch, transformers, safetensors
11
+ pip install "decisionnode-edge[images]" # adds Pillow and torchvision, for pictures
12
+ ```
13
+
14
+ The model folders carry a copy of this package in `runtime/` for machines without network access: `pip install ./runtime` (or `"./runtime[images]"`) from the model folder installs the same thing.
15
+
16
+ Optional, for speed on NVIDIA GPUs with the PyTorch backend: `flash-linear-attention` and `causal-conv1d`. transformers uses them when they are installed. Without them the model gives the same answers about twice as slowly on long inputs.
17
+
18
+ ### The fastest install for your device
19
+
20
+ The runtime reads the model with PyTorch unless a faster backend is installed. Install the one for your device:
21
+
22
+ | Device | Install | Backend |
23
+ |---|---|---|
24
+ | NVIDIA GPU (Linux) | `pip install "decisionnode-edge[vllm]"` | `vllm` |
25
+ | x86 CPU | `pip install "decisionnode-edge[openvino]"`, then build the OpenVINO files once ([below](#building-what-a-backend-loads)) | `openvino` |
26
+ | Apple silicon | `pip install "decisionnode-edge[mlx]"` | `mlx` |
27
+ | Any device llama.cpp supports, including NVIDIA Jetson | llama.cpp's `llama-server`; the model folder ships the 8-bit GGUF file ([below](#building-what-a-backend-loads)) | `llamacpp` |
28
+
29
+ Every backend agrees with the PyTorch reference on at least 98% of top answers in our tests, and the remaining differences fall on near ties. A backend only computes the model's last hidden state; the runtime then applies the model's own answer table (`readout.safetensors`) and calibration (`calibration.json`) in float32, as it does on PyTorch.
30
+
31
+ Measured with one `truth` question per request, one request at a time, median time of the whole `decide` call:
32
+
33
+ | Device (as measured) | Backend | Edge, about 500 / 2,000 tokens | Edge Mini | Answers kept (Edge, Edge Mini) | PyTorch on the same device (Edge; Edge Mini) |
34
+ |---|---|---|---|---|---|
35
+ | NVIDIA RTX PRO 6000 Blackwell | `vllm` | 9.5 / 23 ms | 7.3 / 15 ms | 99.7%, 99.2% | 14 / 28 ms; 14 / 16 ms (with the optional kernels) |
36
+ | AMD Ryzen 7 9800X3D (8 cores) | `openvino` | 0.46 / 1.7 s | 0.24 / 0.90 s | 98.6%, 98.4% | bfloat16: 0.49 / 2.6 s; 0.28 / 1.4 s. float32, the default: 1.6 / 7.8 s; 0.66 / 4.0 s |
37
+ | Apple M5 Max | `mlx` | 35 / 127 ms | 17 / 65 ms | 99.5%, 99.3% | `device="mps"`: 0.30 / 1.3 s; 0.28 / 1.2 s |
38
+ | Apple M5 Max | `llamacpp` (Metal) | 55 / 212 ms | 30 / 112 ms | 99.4%, 99.0% | |
39
+ | NVIDIA RTX PRO 6000 Blackwell | `llamacpp` (CUDA) | 14 / 44 ms | 10.5 / 30 ms | 99.2%, 98.4% | |
40
+ | AMD Ryzen 7 9800X3D (8 cores) | `llamacpp` (CPU) | 1.1 / 5.1 s | 0.58 / 2.7 s | 99.8%, 98.1% (412 questions up to 512 tokens) | |
41
+
42
+ At about 8,000 tokens: `vllm` 87 ms (Edge) and 50 ms (Edge Mini), `mlx` 625 and 297 ms, `llamacpp` 218 and 160 ms on CUDA and 0.92 and 0.55 s on Metal. OpenVINO hands prompts of that length to PyTorch.
43
+
44
+ "Answers kept" is how often the backend's top answer equals the PyTorch reference (bfloat16 on an NVIDIA GPU) on a fixed set of 2,056 held-out questions; for OpenVINO, on the 1,936 of them up to 2,048 tokens, the longest it is built for.
45
+
46
+ The GPU is an NVIDIA RTX PRO 6000 Blackwell workstation card, the CPU an AMD Ryzen 7 9800X3D (8 cores, 16 threads), the Mac an Apple M5 Max. Versions: vLLM 0.32.0, OpenVINO 2026.4.1, MLX 0.32.4 with mlx-lm 0.32.2, llama.cpp at commit f174553, PyTorch 2.13 and 2.14, transformers 5.18 and 5.19. All backends ran in bfloat16 except llama.cpp, which ran the 8-bit (Q8_0) file.
47
+
48
+ ## Use
49
+
50
+ ```python
51
+ from decisionnode_edge import EdgeModel
52
+
53
+ model = EdgeModel.load("path/to/decisionnode-edge") # CUDA if present, else the CPU
54
+
55
+ response = model.decide({
56
+ "state": {"ticket": "I was charged twice and nobody has replied for 3 days."},
57
+ "questions": {
58
+ "route": {
59
+ "type": "choice",
60
+ "instructions": "Where should `ticket` go?",
61
+ "criteria": {"billing": "money", "bug": "something broken", "account": "login and access"},
62
+ },
63
+ "urgency": {
64
+ "type": "score",
65
+ "instructions": "How urgent is `ticket`?",
66
+ "criteria": ["routine", "today", "urgent", "critical"],
67
+ },
68
+ "escalate": {"type": "truth", "instructions": "Should a human take over now?"},
69
+ "days": {"type": "number", "instructions": "How many days has the customer waited?", "min": 0, "max": 30},
70
+ },
71
+ })
72
+
73
+ response["answers"]["route"] # {"type": "choice", "choice": ..., "confidence": ..., "probabilities": {...}}
74
+ response["answers"]["escalate"] # {"type": "truth", "truth": ...}
75
+ ```
76
+
77
+ `model.predict(request)` gives the unrounded calibrated probabilities per question instead: one per option or level in request order, `[yes, no]` for a truth question, one per grid value for a number question.
78
+
79
+ A response names the model that answered: `decisionnode-edge-0.9.1` for DecisionNode Edge, `decisionnode-edge-mini-0.9.1` for DecisionNode Edge Mini (the `name` in the model directory's `decisionnode_edge.json`).
80
+
81
+ From the command line:
82
+
83
+ ```bash
84
+ python -m decisionnode_edge path/to/decisionnode-edge request.json
85
+ cat request.json | python -m decisionnode_edge path/to/decisionnode-edge -
86
+ ```
87
+
88
+ ### Serving over HTTP
89
+
90
+ ```bash
91
+ python -m decisionnode_edge serve path/to/decisionnode-edge --host 127.0.0.1 --port 8000
92
+ python -m decisionnode_edge serve path/to/decisionnode-edge --api-key key.txt # callers send Authorization: Bearer <key>
93
+ ```
94
+
95
+ A small server on Python's standard library, with nothing more to install. It loads the model with the backend `EdgeModel.load` picks (or `--backend`, `--artifacts`, `--device`, `--dtype`), answers one request at a time, and listens on 127.0.0.1 unless `--host` says otherwise.
96
+
97
+ | Route | What |
98
+ |---|---|
99
+ | `POST /v1/systemone` | the `/v1/systemone` format used by public decision-model leaderboards: `{"model", "state", "questions", "assets"}` with `noul`, `choice` and `score` questions. A `noul` is answered `{"type": "noul", "noul": p}`, a choice and a score as on `/v1/decide` (probabilities that sum to 1). `model` is required, and any name is accepted |
100
+ | `POST /v1/decide` | the request and answers of this runtime ([below](#the-request)), `number` and `truth` included |
101
+ | `GET /v1/models` | `{"models": [{"name", "description", "release_date"}]}` |
102
+ | `GET /healthz` | `{"status": "ok", "model", "backend"}`, no key needed |
103
+
104
+ Every answer carries `usage`: `input_tokens` and `output_tokens` (always 0). Pictures go as base64: the runtime's `images` with `data` (a local `path` is refused over HTTP, so a caller can never make the server read a file), or, on `/v1/systemone`, an `assets` map, `{"<ref>": {"type": "image", "format": "png", "data_base64": "..."}}` with format `png`, `jpg` or `jpeg`. Each asset becomes a picture whose id is its reference.
105
+
106
+ Errors come as `{"detail": {"error_type": ..., "message": ...}}` (a 422 as a list of field errors). A request longer than the model's limit is a 400 whose message says "maximum context length"; a choice with more than 255 options is a 400 that says "options per choice".
107
+
108
+ ### Options
109
+
110
+ `EdgeModel.load(path, device=None, dtype=None, backend=None, artifacts=None, options=None)`:
111
+
112
+ - `device`: `"cuda"`, `"cuda:1"`, `"cpu"` or `"mps"`. Default: CUDA when present, else the CPU. It also sets the device class the backend is chosen for.
113
+ - `dtype`: `"bfloat16"` or `"float32"`, for PyTorch. Default: bfloat16 on a GPU (the reference precision) and float32 on a CPU. On CPUs with bfloat16 support (recent AMD and Intel parts) `dtype="bfloat16"` was about three times faster in our tests, with answers as close to the GPU's as float32 gives.
114
+ - `backend`: `"auto"` (the default), `"torch"`, `"vllm"`, `"openvino"`, `"mlx"` or `"llamacpp"`.
115
+ - `artifacts`: the directory the build tool wrote, for `openvino` and `llamacpp`.
116
+ - `options`: the backend's settings ([below](#backend-options)).
117
+
118
+ ### Choosing a backend
119
+
120
+ By default `EdgeModel.load` takes the fastest backend that is installed and can run on the machine:
121
+
122
+ | Device class | Order |
123
+ |---|---|
124
+ | NVIDIA GPU | `vllm`, `llamacpp`, `torch` |
125
+ | Apple silicon | `mlx`, `llamacpp`, `torch` |
126
+ | Any other CPU | `openvino`, `llamacpp`, `torch` |
127
+
128
+ `openvino` counts only when `artifacts` holds an OpenVINO build, and `llamacpp` only when `artifacts` holds a GGUF build and `llama-server` is found (or `options` names a running server). Asked for by name, `openvino` and `llamacpp` also find a build in the model folder itself, such as the GGUF file that ships there. `model.backend` says which one was taken.
129
+
130
+ To choose yourself:
131
+
132
+ ```python
133
+ model = EdgeModel.load("path/to/decisionnode-edge", backend="torch")
134
+ model = EdgeModel.load("path/to/decisionnode-edge", backend="openvino", artifacts="path/to/edge-openvino")
135
+ model = EdgeModel.load("path/to/decisionnode-edge", backend="llamacpp", options={"url": "http://127.0.0.1:8080"})
136
+ ```
137
+
138
+ The same from the environment: `DECISIONNODE_EDGE_BACKEND`, `DECISIONNODE_EDGE_ARTIFACTS`, and `DECISIONNODE_EDGE_OPTIONS` (a JSON object). Arguments win over the environment. On the command line: `python -m decisionnode_edge path/to/decisionnode-edge request.json --backend openvino --artifacts path/to/edge-openvino`.
139
+
140
+ The faster backends read text. PyTorch reads what they do not take: pictures, and prompts longer than the backend's limit (an OpenVINO build's longest length, 2,048 tokens by default; a llama.cpp context, 16,384 tokens by default). It is loaded the first time it is needed, on `device` in `dtype`, and stays loaded. If most of your requests carry pictures, use `backend="torch"`.
141
+
142
+ ### Building what a backend loads
143
+
144
+ The build tools read the model directory and write a new directory. They never change the model directory.
145
+
146
+ **OpenVINO.** One file per static input length, 512 and 2,048 tokens by default:
147
+
148
+ ```bash
149
+ pip install "decisionnode-edge[openvino]"
150
+ python -m decisionnode_edge.build openvino path/to/decisionnode-edge --out path/to/edge-openvino
151
+ python -m decisionnode_edge.build openvino path/to/decisionnode-edge --out path/to/edge-openvino --lengths 512,1024,2048
152
+ ```
153
+
154
+ The export runs on the GPU when there is one (`--device cuda`, then the default) and on the CPU otherwise. On our machine it took 14 minutes for 512 tokens and 19 minutes for 2,048, per length. The files keep the weights in float32 (exact copies of the bfloat16 weights) and OpenVINO runs them in bfloat16, so the build takes 6.2 GB for Edge Mini and 15.2 GB for Edge. Before it ends, the tool runs each file once against PyTorch.
155
+
156
+ A prompt is padded to the next length it fits, so a 600-token prompt costs about what a 2,048-token one does. Add a length (for example `--lengths 512,1024,2048`) if many of your prompts fall between two lengths. Lengths above a few thousand tokens take hours to export; longer prompts go to PyTorch.
157
+
158
+ **GGUF for llama.cpp.** The model folder ships the 8-bit file (`decisionnode-edge-0.9.1-q8_0.gguf`, `decisionnode-edge-mini-0.9.1-q8_0.gguf`) with its build record, so `EdgeModel.load("path/to/decisionnode-edge", backend="llamacpp")` uses it with no build step. To make it yourself (8-bit keeps the answers; 4-bit does not, so the tool does not offer it):
159
+
160
+ ```bash
161
+ git clone https://github.com/ggml-org/llama.cpp
162
+ cmake -S llama.cpp -B llama.cpp/build -DCMAKE_BUILD_TYPE=Release # add -DGGML_CUDA=ON on an NVIDIA GPU or a Jetson
163
+ cmake --build llama.cpp/build --target llama-server -j
164
+ pip install -r llama.cpp/requirements/requirements-convert_hf_to_gguf.txt
165
+ python -m decisionnode_edge.build gguf path/to/decisionnode-edge --out path/to/edge-gguf --llama-cpp llama.cpp
166
+ ```
167
+
168
+ The conversion takes seconds and writes one file: 2.0 GB for Edge, 0.8 GB for Edge Mini. The same file serves a CPU, an NVIDIA GPU, a Jetson and a Mac; llama.cpp itself is built for each.
169
+
170
+ The runtime then starts `llama-server` on 127.0.0.1 itself (from your `PATH`, or `options={"server": "path/to/llama-server"}`) and stops it with the model. To run the server yourself, start it with the embedding endpoint and the last-position pooling, with a batch as large as the context:
171
+
172
+ ```bash
173
+ llama-server -m edge-gguf/model-q8_0.gguf --embeddings --pooling last -c 16384 -b 16384 -ub 16384 -ngl 999 --port 8080
174
+ ```
175
+
176
+ and pass `options={"url": "http://127.0.0.1:8080"}`. The runtime sends token ids, so llama.cpp's own tokenizer is never used.
177
+
178
+ ### Backend options
179
+
180
+ Options can be flat (`{"threads": 16}`) or under a backend's name (`{"openvino": {"threads": 16}}`), so one set of options can serve whichever backend is taken.
181
+
182
+ | Backend | Option | Default |
183
+ |---|---|---|
184
+ | `vllm` | any vLLM engine argument, such as `gpu_memory_utilization` or `enforce_eager` | a 2 GiB KV cache; the share of the GPU that covers the weights, that cache and 4 GiB for activations |
185
+ | `openvino` | `threads` | OpenVINO's choice |
186
+ | `openvino` | `precision`: `"bf16"` or `"f32"` | `"bf16"` (OpenVINO falls back to f32 on CPUs without bfloat16) |
187
+ | `openvino` | `config`: other OpenVINO CPU properties | |
188
+ | `llamacpp` | `url`: a running `llama-server` | start one |
189
+ | `llamacpp` | `server`, `gguf`: the program and the model file | `llama-server` on `PATH`, the build's file |
190
+ | `llamacpp` | `gpu_layers`, `threads` | 999 (all layers on the GPU when there is one), llama.cpp's choice |
191
+ | `llamacpp` | `context`: the longest prompt llama.cpp takes | 16,384 |
192
+
193
+ vLLM runs its engine inside your process and uses the first visible GPU (choose it with `CUDA_VISIBLE_DEVICES`). Its first load takes about half a minute while it compiles. MLX uses the Apple GPU.
194
+
195
+ ### Pictures
196
+
197
+ Send pictures beside the state, up to 16, each with an `id`:
198
+
199
+ ```python
200
+ {"images": [{"id": "receipt", "data": "<base64>", "media_type": "image/jpeg"}]} # as with the hosted API
201
+ {"images": [{"id": "receipt", "path": "/data/receipt.jpg"}]} # a local file, Edge only
202
+ ```
203
+
204
+ A picture is turned upright from its EXIF orientation, converted to RGB and scaled so its longest side is at most 2,048 pixels. Every question sees every picture. The prompt names a picture `Picture <n> (<id>)`, so instructions can refer to "Picture 2" or to "the receipt".
205
+
206
+ ## The request
207
+
208
+ The request and the answers follow the DecisionNode API's `/v1/decide`:
209
+
210
+ | Field | Notes |
211
+ |---|---|
212
+ | `state` | a string (used as it is), an object or an array (compact JSON, key order kept); missing, null and `""` are the empty state |
213
+ | `questions` | id to question, at least one; the id is never shown to the model |
214
+ | `images` | optional, see above |
215
+ | `model` | ignored |
216
+
217
+ | Question type | Fields |
218
+ |---|---|
219
+ | `choice` | `instructions` (optional), `criteria`: {option: description}, 1 to 255 options; a description may be a string, an object, an array or null |
220
+ | `score` | `instructions` (optional), `criteria`: [level, ...] low to high, 1 to 10 levels |
221
+ | `truth` | `instructions` and/or `criteria`: {"true": ..., "false": ...} |
222
+ | `number` | `instructions`, `min`, `max`, `step` (defaults 0, 255, 1), up to 4,096 values; more than 256 values are answered in pages of 256 and composed |
223
+
224
+ Answers are rounded as the API rounds them: probabilities to 2 decimals (3 for number questions), with the largest entries moved by 0.01 until a list sums to 1.
225
+
226
+ A request the model cannot answer raises `decisionnode_edge.RequestError`, whose `status` is the HTTP status the hosted API gives the same fault (400 or 422). The runtime checks what the model needs; the hosted API's error bodies are not reproduced word for word. Requests longer than the model's limit (`limits.max_input_tokens` in `decisionnode_edge.json`, 16,384 tokens) are refused, never cut.
227
+
228
+ Not on Edge: videos, points and boxes, boosters, image URLs and uploads, sessions and batch jobs. These are features of the hosted API.
229
+
230
+ ## How it works
231
+
232
+ Each question becomes one prompt: the state block (pictures first, then the state text), then the question block (the type, the instructions, then one line per option, each led by an answer code token), then the word `Answer` and an answer marker. The codes of a question are drawn from a hash of the question alone, so the same question always gets the same codes. The model reads the prompt in one forward pass, and the last hidden state is scored against the rows of `readout.safetensors` that belong to the question's codes (or to its yes and no tokens). `calibration.json` turns those scores into probabilities. The model never generates text.
233
+
234
+ The code is a few short modules: `template.py` (the prompt and the codes), `request.py` (reading a request), `answers.py` (calibration and the answer shapes), `backends.py` (what reads the backbone: PyTorch, vLLM, OpenVINO, MLX or llama.cpp), `build.py` (the OpenVINO and GGUF builds), `server.py` (the HTTP server), with `model.py` tying them to the weights.
235
+
236
+ ## License
237
+
238
+ The runtime code, like the model weights, is licensed under the GNU Affero General Public License, version 3 only (SPDX: `AGPL-3.0-only`). For use in closed products and services, Bynn Intelligence Inc. offers a commercial license: licensing@bynn.com.
runtime/examples/request.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "state": {
3
+ "ticket": "Hi, I was charged twice for my March invoice and nobody has replied to my two emails since Monday. Please refund the second charge.",
4
+ "customer": {"plan": "business", "since": "2023-05-14"}
5
+ },
6
+ "questions": {
7
+ "route": {
8
+ "type": "choice",
9
+ "instructions": "Which team should handle `ticket`?",
10
+ "criteria": {
11
+ "billing": "charges, invoices, refunds",
12
+ "bug": "something in the product is broken",
13
+ "account": "login, access, settings"
14
+ }
15
+ },
16
+ "urgency": {
17
+ "type": "score",
18
+ "instructions": "How urgent is `ticket`?",
19
+ "criteria": ["routine", "today", "urgent", "critical"]
20
+ },
21
+ "refund": {
22
+ "type": "truth",
23
+ "instructions": "Does the customer ask for a refund?"
24
+ },
25
+ "emails": {
26
+ "type": "number",
27
+ "instructions": "How many emails has the customer sent before this one?",
28
+ "min": 0,
29
+ "max": 10
30
+ }
31
+ }
32
+ }
runtime/pyproject.toml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=77"] # a PEP 639 license expression
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "decisionnode-edge"
7
+ version = "0.9.1"
8
+ description = "Run DecisionNode Edge locally: typed, calibrated decisions in the shape of the DecisionNode API."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "AGPL-3.0-only" # and a commercial license from Bynn Intelligence Inc. (README, License)
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Bynn Intelligence Inc.", email = "licensing@bynn.com" }]
14
+ dependencies = [
15
+ "torch>=2.6",
16
+ "transformers>=5.18",
17
+ "safetensors>=0.4",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ # pictures: Pillow decodes them, torchvision runs the backbone's fast image processor
22
+ images = ["pillow>=10", "torchvision>=0.21"]
23
+ # faster backends (src/decisionnode_edge/backends.py), each optional; llama.cpp is a program of its own, not a Python package
24
+ vllm = ["vllm>=0.32; sys_platform == 'linux'"]
25
+ openvino = ["openvino>=2026.4", "onnx>=1.23", "onnxscript>=0.7"] # onnx and onnxscript for the build only
26
+ mlx = ["mlx>=0.32; sys_platform == 'darwin' and platform_machine == 'arm64'", "mlx-lm>=0.32.2; sys_platform == 'darwin' and platform_machine == 'arm64'"]
27
+
28
+ [tool.setuptools.packages.find]
29
+ where = ["src"]
runtime/src/decisionnode_edge/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DecisionNode Edge: typed, calibrated decisions from a model that runs on your own hardware.
2
+
3
+ from decisionnode_edge import EdgeModel
4
+
5
+ model = EdgeModel.load("path/to/decisionnode-edge")
6
+ model.decide({"state": "...", "questions": {"escalate": {"type": "truth", "instructions": "Escalate now?"}}})
7
+ """
8
+
9
+ from .model import EdgeModel
10
+ from .request import RequestError
11
+
12
+ __all__ = ["EdgeModel", "RequestError"]
13
+ __version__ = "0.9.1"
runtime/src/decisionnode_edge/__main__.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Answer one request from the command line, or serve the model over HTTP (server.py).
2
+
3
+ python -m decisionnode_edge path/to/decisionnode-edge request.json # or "-" to read the request from stdin
4
+ python -m decisionnode_edge serve path/to/decisionnode-edge --port 8000
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+
13
+ from . import EdgeModel, RequestError
14
+
15
+
16
+ def main(argv: list[str] | None = None) -> int:
17
+ argv = sys.argv[1:] if argv is None else argv
18
+ if argv[:1] == ["serve"]:
19
+ from .server import main as serve
20
+
21
+ return serve(argv[1:])
22
+ parser = argparse.ArgumentParser(prog="python -m decisionnode_edge", description="Answer a /v1/decide request with a local DecisionNode Edge model.")
23
+ parser.add_argument("model", help="the model directory")
24
+ parser.add_argument("request", help="a JSON file with the request body, or - for stdin")
25
+ parser.add_argument("--device", default=None, help="cuda or cpu (default: cuda when present)")
26
+ parser.add_argument("--dtype", default=None, help="bfloat16 or float32 (default: bfloat16 on cuda, float32 on cpu)")
27
+ parser.add_argument("--backend", default=None, help="auto, torch, vllm, openvino, mlx or llamacpp (default: auto, the fastest installed)")
28
+ parser.add_argument("--artifacts", default=None, help="the directory python -m decisionnode_edge.build wrote (openvino, llamacpp)")
29
+ args = parser.parse_args(argv)
30
+ body = json.load(sys.stdin if args.request == "-" else open(args.request, encoding="utf-8"))
31
+ model = EdgeModel.load(args.model, device=args.device, dtype=args.dtype, backend=args.backend, artifacts=args.artifacts)
32
+ try:
33
+ response = model.decide(body)
34
+ except RequestError as error:
35
+ print(json.dumps({"error": str(error), "status": error.status}), file=sys.stderr)
36
+ return 1
37
+ print(json.dumps(response, ensure_ascii=False, indent=2))
38
+ return 0
39
+
40
+
41
+ if __name__ == "__main__":
42
+ sys.exit(main())
runtime/src/decisionnode_edge/answers.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Calibration and the answer objects of the hosted API.
2
+
3
+ Calibration (calibration.json):
4
+
5
+ choice, score p = softmax(z / T(K)), T(K) = t0 + t1 * ln K, K clamped to the fitted range
6
+ truth p_yes = sigmoid((z_yes - z_no) / T + b)
7
+
8
+ A parameter set exists per input kind ("text", "image"); a missing one is the identity.
9
+
10
+ The answers, rounded as the hosted API rounds them:
11
+
12
+ choice {"type", "choice", "confidence", "probabilities": {option: p}} options in alphabetical order
13
+ score {"type", "score", "confidence", "legend": {"0": level}, "probabilities": {"0": p}}
14
+ truth {"type", "truth"}
15
+ number {"type", "number", "expected", "confidence", "probabilities": {value: p}}
16
+
17
+ `choice`, `score`, `number` and the confidences come from the unrounded probabilities. A probability list is rounded
18
+ to 2 decimals entry by entry, then its largest entries move by 0.01 until it sums to 1 (`round_probabilities`).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ from decimal import Decimal, localcontext
25
+ from typing import Sequence
26
+
27
+ T_MIN, T_MAX = 0.05, 100.0
28
+ UNIT = 0.01
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Calibration
33
+ # ---------------------------------------------------------------------------
34
+
35
+
36
+ def _temperature(params: dict, k: int) -> float:
37
+ if params.get("k_min") is not None:
38
+ k = min(max(k, params["k_min"]), params["k_max"])
39
+ t = float(params.get("t0", 1.0)) + float(params.get("t1", 0.0)) * math.log(k)
40
+ return min(T_MAX, max(T_MIN, t))
41
+
42
+
43
+ def calibrated(logits: Sequence[float], kind: str, calibration: dict, has_images: bool) -> list[float]:
44
+ """Calibrated class probabilities from a question's code logits (class order: options or levels as given,
45
+ [yes, no] for truth)."""
46
+ params = (calibration.get("image" if has_images else "text") or {}).get("choice" if kind == "number" else kind) or {}
47
+ z = [float(x) for x in logits]
48
+ if kind == "truth":
49
+ x = (z[0] - z[1]) / float(params.get("temperature", 1.0)) + float(params.get("bias", 0.0))
50
+ p = 1.0 / (1.0 + math.exp(-x)) if x >= 0 else math.exp(x) / (1.0 + math.exp(x))
51
+ return [p, 1.0 - p]
52
+ if len(z) == 1:
53
+ return [1.0]
54
+ t = _temperature(params, len(z))
55
+ scaled = [x / t for x in z]
56
+ top = max(scaled)
57
+ log_total = math.log(sum(math.exp(x - top) for x in scaled))
58
+ return [math.exp(x - top - log_total) for x in scaled]
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Rounding
63
+ # ---------------------------------------------------------------------------
64
+
65
+
66
+ def _units(x: float) -> int:
67
+ """x in hundredths, halves up (the epsilon absorbs binary error: 0.805 rounds to 0.81)."""
68
+ return int(math.floor(x * 100.0 + 0.5 + 1e-9))
69
+
70
+
71
+ def round2(x: float) -> float:
72
+ value = _units(x) / 100.0
73
+ return 0.0 if value == 0 else value
74
+
75
+
76
+ def round_probabilities(probs: Sequence[float]) -> list[float]:
77
+ """Round to 2 decimals, then move the |n| largest entries by 0.01, n = int((1 - fsum(rounded)) / 0.01).
78
+ A moved entry is not rounded again (0.81 + 0.01 is 0.8200000000000001), as the hosted API returns it."""
79
+ p = [float(x) for x in probs]
80
+ units = [_units(x) for x in p]
81
+ rounded = [u / 100.0 for u in units]
82
+ n = int((1.0 - math.fsum(rounded)) / UNIT)
83
+ if n:
84
+ step = 1 if n > 0 else -1
85
+ for i in sorted(range(len(p)), key=lambda i: (-p[i], i))[: abs(n)]:
86
+ rounded[i] = rounded[i] + UNIT if step > 0 else rounded[i] - UNIT
87
+ return [0.0 if x == 0 else x for x in rounded]
88
+
89
+
90
+ def _argmax_first(probs: Sequence[float]) -> int:
91
+ best = 0
92
+ for i, p in enumerate(probs):
93
+ if p > probs[best]:
94
+ best = i
95
+ return best
96
+
97
+
98
+ # ---------------------------------------------------------------------------
99
+ # Answers
100
+ # ---------------------------------------------------------------------------
101
+
102
+
103
+ def choice_answer(keys: Sequence[str], probs: Sequence[float]) -> dict:
104
+ best = _argmax_first(probs)
105
+ k = len(probs)
106
+ confidence = 1.0 if k == 1 else min(1.0, max(0.0, (k * probs[best] - 1.0) / (k - 1.0)))
107
+ shown = round_probabilities(probs)
108
+ return {"type": "choice", "choice": keys[best], "confidence": round2(confidence), "probabilities": dict(sorted(zip(keys, shown)))}
109
+
110
+
111
+ def score_answer(levels: Sequence, probs: Sequence[float]) -> dict:
112
+ k = len(probs)
113
+ if k == 1:
114
+ confidence = 1.0
115
+ else:
116
+ mode = _argmax_first(probs)
117
+ spread = sum(p * abs(i - mode) for i, p in enumerate(probs))
118
+ confidence = min(1.0, max(0.0, 1.0 - spread / ((k * k // 4) / k)))
119
+ return {
120
+ "type": "score",
121
+ "score": round2(sum(i * p for i, p in enumerate(probs))),
122
+ "confidence": round2(confidence),
123
+ "legend": {str(i): level for i, level in enumerate(levels)},
124
+ "probabilities": {str(i): x for i, x in enumerate(round_probabilities(probs))},
125
+ }
126
+
127
+
128
+ def truth_answer(probs: Sequence[float]) -> dict:
129
+ return {"type": "truth", "truth": round2(probs[0])}
130
+
131
+
132
+ def _expected_text(value: float, decimals: int) -> str:
133
+ """Halves up to `decimals` (at most 15 significant digits), with a decimal point, never -0.0."""
134
+ with localcontext() as ctx:
135
+ ctx.prec = 200
136
+ exact = Decimal(value)
137
+ whole = abs(int(exact))
138
+ decimals = min(decimals, 15 - (len(str(whole)) if whole else 0))
139
+ units = (exact * Decimal(10) ** decimals + Decimal("0.5") + Decimal("1e-9")).to_integral_value(rounding="ROUND_FLOOR")
140
+ text = format(units * Decimal(10) ** -decimals, "f")
141
+ if "." in text:
142
+ text = text.rstrip("0")
143
+ text = text + "0" if text.endswith(".") else text
144
+ else:
145
+ text += ".0"
146
+ return "0.0" if text == "-0.0" else text
147
+
148
+
149
+ def _number(text: str) -> int | float:
150
+ return float(text) if "." in text else int(text)
151
+
152
+
153
+ def number_answer(grid, probs: Sequence[float]) -> dict:
154
+ """The most probable value, the probability-weighted mean (`expected`), the probability of the value
155
+ (`confidence`) and every value above 0.001 to 3 decimals (rounded entries that sum above 1 lose 0.001 each,
156
+ the largest first, the answer's own last)."""
157
+ best = _argmax_first(probs)
158
+ texts = grid.texts()
159
+ expected = math.fsum(float(text) * p for text, p in zip(texts, probs))
160
+ listed = [i for i in range(grid.n) if probs[i] > 0.001 or i == best]
161
+ millis = {i: int(math.floor(probs[i] * 1000.0 + 0.5 + 1e-9)) for i in listed}
162
+ excess = sum(millis.values()) - 1000
163
+ order = sorted((i for i in listed if i != best), key=lambda i: (-probs[i], i))
164
+ while excess > 0:
165
+ lowered = False
166
+ for i in order:
167
+ if excess <= 0:
168
+ break
169
+ if millis[i] > 0:
170
+ millis[i] -= 1
171
+ excess -= 1
172
+ lowered = True
173
+ if not lowered:
174
+ millis[best] -= 1
175
+ excess -= 1
176
+ return {
177
+ "type": "number",
178
+ "number": _number(texts[best]),
179
+ "expected": float(_expected_text(expected, max(2, grid.d))),
180
+ "confidence": round2(probs[best]),
181
+ "probabilities": {texts[i]: millis[i] / 1000.0 for i in listed},
182
+ }
runtime/src/decisionnode_edge/backends.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Backends: what reads the backbone. Every backend gives, for a prompt's token ids, the hidden state at the last position
2
+ after the final norm (float32, one vector). The package's readout table and calibration go on top in model.py, so the
3
+ answers are the package's whichever backend reads the prompt.
4
+
5
+ torch transformers; every input, pictures included (always installed) NVIDIA GPU, CPU, Apple (mps)
6
+ vllm vLLM's pooling runner, LAST pooling with no normalization NVIDIA GPU
7
+ openvino OpenVINO, bf16, one IR per static length (python -m decisionnode_edge.build) x86 CPU
8
+ mlx mlx-lm's Qwen3.5 text model, reading the model directory as it is Apple silicon
9
+ llamacpp llama.cpp's llama-server (--embeddings --pooling last) on a GGUF Q8_0 file any machine llama.cpp builds for
10
+
11
+ The fast backends read text. A prompt one of them cannot take (pictures; a prompt longer than an OpenVINO build's largest
12
+ length or a llama.cpp context) is read by torch, loaded on first use.
13
+
14
+ Choosing: `backend` (EdgeModel.load) or DECISIONNODE_EDGE_BACKEND; "auto" (the default) takes the first that can run here,
15
+ in the order of `ORDER` for the device class. A backend that needs built files (openvino, llamacpp) runs only with the
16
+ directory the build tool wrote (`artifacts`, or DECISIONNODE_EDGE_ARTIFACTS). Options are flat, or under a backend's name
17
+ ({"openvino": {"threads": 16}}) so one set can serve whichever backend auto takes.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import dataclasses
23
+ import hashlib
24
+ import importlib.util
25
+ import json
26
+ import logging
27
+ import os
28
+ import platform
29
+ import shutil
30
+ import socket
31
+ import subprocess
32
+ import sys
33
+ import tempfile
34
+ import time
35
+ import urllib.error
36
+ import urllib.request
37
+ import weakref
38
+ from typing import Any, Sequence
39
+
40
+ NAMES = ("torch", "vllm", "openvino", "mlx", "llamacpp")
41
+ # per device class, fastest first (the runtime README's table)
42
+ ORDER = {
43
+ "cuda": ("vllm", "llamacpp", "torch"),
44
+ "apple": ("mlx", "llamacpp", "torch"),
45
+ "cpu": ("openvino", "llamacpp", "torch"),
46
+ }
47
+ ENV_BACKEND = "DECISIONNODE_EDGE_BACKEND"
48
+ ENV_ARTIFACTS = "DECISIONNODE_EDGE_ARTIFACTS"
49
+ ENV_OPTIONS = "DECISIONNODE_EDGE_OPTIONS"
50
+ BUILD_FILE = "decisionnode_edge_build.json"
51
+ BUILD_FORMAT = "decisionnode-edge-build-1"
52
+ # what a backend that reads the model directory needs from it: never readout.safetensors (vLLM loads every .safetensors file)
53
+ MODEL_FILES = ("config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json", "preprocessor_config.json", "video_preprocessor_config.json")
54
+
55
+ log = logging.getLogger("decisionnode_edge")
56
+
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # Choosing
60
+ # ---------------------------------------------------------------------------
61
+
62
+
63
+ def apple_silicon() -> bool:
64
+ return sys.platform == "darwin" and platform.machine() == "arm64"
65
+
66
+
67
+ def linux() -> bool:
68
+ return sys.platform.startswith("linux")
69
+
70
+
71
+ def device_class(device: str | None) -> str:
72
+ """"cuda", "apple" or "cpu": the device given, else CUDA when present, else Apple silicon, else the CPU."""
73
+ if device is not None:
74
+ device = str(device)
75
+ return "cuda" if device.startswith("cuda") else "apple" if device.startswith("mps") else "cpu"
76
+ import torch
77
+
78
+ if torch.cuda.is_available():
79
+ return "cuda"
80
+ return "apple" if apple_silicon() else "cpu"
81
+
82
+
83
+ def env_options() -> dict:
84
+ raw = os.environ.get(ENV_OPTIONS)
85
+ if not raw:
86
+ return {}
87
+ value = json.loads(raw)
88
+ if not isinstance(value, dict):
89
+ raise ValueError(f"{ENV_OPTIONS} must be a JSON object")
90
+ return value
91
+
92
+
93
+ def read_build(artifacts: str | None) -> dict | None:
94
+ """The build tool's record in `artifacts` (decisionnode_edge_build.json), or None."""
95
+ if not artifacts or not os.path.isfile(os.path.join(artifacts, BUILD_FILE)):
96
+ return None
97
+ with open(os.path.join(artifacts, BUILD_FILE), encoding="utf-8") as f:
98
+ build = json.load(f)
99
+ if build.get("format") != BUILD_FORMAT:
100
+ raise ValueError(f"{artifacts}: not a build of this runtime ({build.get('format')!r})")
101
+ return build
102
+
103
+
104
+ def own_options(name: str, options: dict) -> dict:
105
+ """The options for one backend: the flat ones, then the ones under its name."""
106
+ return {**{k: v for k, v in options.items() if k not in NAMES}, **(options.get(name) or {})}
107
+
108
+
109
+ def _installed(*modules: str) -> bool:
110
+ return all(importlib.util.find_spec(m) is not None for m in modules)
111
+
112
+
113
+ def unavailable(name: str, device: str | None, artifacts: str | None, options: dict) -> str | None:
114
+ """Why `name` cannot run here, or None when it can."""
115
+ if name == "torch":
116
+ return None
117
+ if name == "vllm":
118
+ if not linux() or not _installed("vllm"):
119
+ return "vLLM is not installed (pip install 'decisionnode-edge[vllm]', Linux with an NVIDIA GPU)"
120
+ return None if device_class(device) == "cuda" else "vLLM needs an NVIDIA GPU"
121
+ if name == "mlx":
122
+ if not apple_silicon():
123
+ return "MLX needs Apple silicon"
124
+ return None if _installed("mlx", "mlx_lm") else "MLX is not installed (pip install 'decisionnode-edge[mlx]')"
125
+ build = read_build(artifacts)
126
+ if name == "openvino":
127
+ if not _installed("openvino"):
128
+ return "OpenVINO is not installed (pip install 'decisionnode-edge[openvino]')"
129
+ if not build or build.get("backend") != "openvino":
130
+ return "OpenVINO needs a build: python -m decisionnode_edge.build openvino <model> --out <dir>, then artifacts=<dir>"
131
+ return None
132
+ if name == "llamacpp":
133
+ options = own_options(name, options)
134
+ if options.get("url"):
135
+ return None
136
+ if not build or build.get("backend") != "llamacpp":
137
+ return "llama.cpp needs a GGUF build (python -m decisionnode_edge.build gguf) as artifacts, or options={'url': <a running llama-server>}"
138
+ if not (options.get("server") or shutil.which("llama-server")):
139
+ return "llama-server is not on PATH: give options={'server': <path to llama-server>} or {'url': <a running llama-server>}"
140
+ return None
141
+ raise ValueError(f"unknown backend {name!r}: one of {', '.join(NAMES)} or auto")
142
+
143
+
144
+ def choose(requested: str | None, device: str | None, artifacts: str | None, options: dict) -> str:
145
+ """The backend to load: the one asked for (argument, else DECISIONNODE_EDGE_BACKEND), or for "auto" the first of the
146
+ device class's order that can run here."""
147
+ name = (requested or os.environ.get(ENV_BACKEND) or "auto").strip().lower()
148
+ if name != "auto":
149
+ reason = unavailable(name, device, artifacts, options)
150
+ if reason:
151
+ raise RuntimeError(f"backend {name!r}: {reason}")
152
+ return name
153
+ for candidate in ORDER[device_class(device)]:
154
+ reason = unavailable(candidate, device, artifacts, options)
155
+ if reason is None:
156
+ return candidate
157
+ log.info("auto: not %s: %s", candidate, reason)
158
+ return "torch"
159
+
160
+
161
+ def load(name: str, path: str, config: dict, artifacts: str | None, options: dict, device: str | None):
162
+ """The backend object for a name other than torch (model.py loads torch itself)."""
163
+ max_tokens = int(config["limits"]["max_input_tokens"])
164
+ options = own_options(name, options)
165
+ if name == "vllm":
166
+ return VLLM(path, max_tokens, options, device)
167
+ if name == "mlx":
168
+ return MLX(path)
169
+ build = read_build(artifacts)
170
+ if build is not None and build.get("model_fingerprint") != fingerprint(path):
171
+ raise ValueError(f"{artifacts} was built from another model than {path}")
172
+ if name == "openvino":
173
+ return OpenVINO(artifacts, build, options)
174
+ if name == "llamacpp":
175
+ return LlamaCpp(artifacts, build, max_tokens, options)
176
+ raise ValueError(f"unknown backend {name!r}")
177
+
178
+
179
+ def fingerprint(path: str) -> str:
180
+ """A quick identity of a model directory's weights, kept in every build: the file's size, its safetensors header and
181
+ 1 MiB every 256 MiB plus the last MiB (hashing all of it would add seconds to every load)."""
182
+ weights = os.path.join(path, "model.safetensors")
183
+ size = os.path.getsize(weights)
184
+ h = hashlib.sha256(str(size).encode())
185
+ with open(weights, "rb") as f:
186
+ n = int.from_bytes(f.read(8), "little")
187
+ h.update(f.read(n))
188
+ for offset in list(range(8 + n, size, 256 << 20)) + [max(0, size - (1 << 20))]:
189
+ f.seek(offset)
190
+ h.update(f.read(1 << 20))
191
+ return h.hexdigest()
192
+
193
+
194
+ def link_model_files(path: str, target: str) -> None:
195
+ """Links in `target` to the model directory's backbone files (MODEL_FILES), never its readout."""
196
+ for name in MODEL_FILES:
197
+ src = os.path.join(os.path.abspath(path), name)
198
+ if os.path.exists(src):
199
+ os.symlink(src, os.path.join(target, name))
200
+
201
+
202
+ # ---------------------------------------------------------------------------
203
+ # Backends: hidden(ids) gives the float32 hidden state of the last position; accepts(n) says whether a prompt of n
204
+ # tokens is theirs (torch reads the others)
205
+ # ---------------------------------------------------------------------------
206
+
207
+
208
+ class VLLM:
209
+ """vLLM's pooling runner (convert "embed", LAST pooling, use_activation False: the raw hidden state after the final norm)
210
+ on a temporary directory of links to the model files. Text only: the multimodal limits are 0. Its engine runs in this
211
+ process (VLLM_ENABLE_V1_MULTIPROCESSING 0 unless set): as fast at batch 1, and a child process would need the caller's
212
+ script to be importable (vLLM starts it with spawn once CUDA is up)."""
213
+
214
+ name = "vllm"
215
+ KV_CACHE_BYTES = 2 << 30 # several prompts of the full 16,384 tokens
216
+ HEADROOM_BYTES = 4 << 30 # activations at 16,384 tokens, CUDA graphs, the CUDA context
217
+
218
+ def __init__(self, path: str, max_tokens: int, options: dict, device: str | None):
219
+ if device is not None and str(device) not in ("cuda", "cuda:0"):
220
+ raise ValueError("vLLM runs on the first visible GPU: choose the card with CUDA_VISIBLE_DEVICES")
221
+ os.environ.setdefault("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
222
+ from vllm import LLM
223
+ from vllm.config import PoolerConfig
224
+ from vllm.engine.arg_utils import EngineArgs
225
+ from vllm.platforms import current_platform
226
+
227
+ self.dir = tempfile.mkdtemp(prefix="decisionnode-edge-vllm-")
228
+ self._cleanup = weakref.finalize(self, shutil.rmtree, self.dir, True)
229
+ link_model_files(path, self.dir)
230
+ # the KV cache is sized, not a share of the card: the share only has to cover it, the weights and the headroom
231
+ total = current_platform.get_device_total_memory(0)
232
+ need = os.path.getsize(os.path.join(path, "model.safetensors")) + self.KV_CACHE_BYTES + self.HEADROOM_BYTES
233
+ args: dict[str, Any] = {
234
+ "model": self.dir,
235
+ "runner": "pooling",
236
+ "convert": "embed",
237
+ "pooler_config": PoolerConfig(pooling_type="LAST", use_activation=False),
238
+ "dtype": "bfloat16",
239
+ "max_model_len": max_tokens,
240
+ "kv_cache_memory_bytes": self.KV_CACHE_BYTES,
241
+ "gpu_memory_utilization": round(min(0.92, need / total), 3),
242
+ "enable_prefix_caching": False,
243
+ "limit_mm_per_prompt": {"image": 0, "video": 0},
244
+ "seed": 0,
245
+ "disable_log_stats": True,
246
+ }
247
+ fields = {f.name for f in dataclasses.fields(EngineArgs)}
248
+ args.update({k: v for k, v in options.items() if k in fields}) # any vLLM engine argument, as given
249
+ if set(options) - fields:
250
+ log.warning("options vLLM does not know, not used: %s", sorted(set(options) - fields))
251
+ self.llm = LLM(**args)
252
+
253
+ def accepts(self, n: int) -> bool:
254
+ return True
255
+
256
+ def hidden(self, ids: Sequence[int]):
257
+ import torch
258
+
259
+ out = self.llm.embed([{"prompt_token_ids": list(ids)}], use_tqdm=False)[0]
260
+ return torch.tensor(out.outputs.embedding, dtype=torch.float32)
261
+
262
+
263
+ class OpenVINO:
264
+ """OpenVINO on the CPU, one compiled model per static length of the build. A prompt is padded on the right to the
265
+ smallest length that holds it and the row of its last token is read: the backbone is causal (attention, the short
266
+ convolution and the delta rule), so the padding never reaches the earlier rows. The weights are float32 in the IR (the
267
+ bf16 weights, exactly) and run with OpenVINO's bf16 inference precision."""
268
+
269
+ name = "openvino"
270
+
271
+ def __init__(self, artifacts: str, build: dict, options: dict):
272
+ import openvino as ov
273
+
274
+ config = {"PERFORMANCE_HINT": "LATENCY", "INFERENCE_PRECISION_HINT": options.get("precision", "bf16")}
275
+ if options.get("threads"):
276
+ config["INFERENCE_NUM_THREADS"] = int(options["threads"])
277
+ config.update(options.get("config") or {})
278
+ core = ov.Core()
279
+ self.pad = int(build["pad_token_id"])
280
+ self.runners = {}
281
+ for length, file in sorted(((int(L), f) for L, f in build["files"].items())):
282
+ compiled = core.compile_model(os.path.join(artifacts, file), "CPU", config)
283
+ self.runners[length] = (compiled.create_infer_request(), compiled.output(0))
284
+ self.lengths = sorted(self.runners)
285
+
286
+ def accepts(self, n: int) -> bool:
287
+ return n <= self.lengths[-1]
288
+
289
+ def hidden(self, ids: Sequence[int]):
290
+ import numpy as np
291
+ import torch
292
+
293
+ n = len(ids)
294
+ length = next(L for L in self.lengths if L >= n)
295
+ request, output = self.runners[length]
296
+ x = np.full((1, length), self.pad, dtype=np.int64)
297
+ x[0, :n] = ids
298
+ out = request.infer({0: x})[output]
299
+ return torch.from_numpy(np.asarray(out[0, n - 1], dtype=np.float32))
300
+
301
+
302
+ class MLX:
303
+ """mlx-lm's Qwen3.5 model on the model directory (it reads model*.safetensors, leaves the picture encoder out and never
304
+ touches readout.safetensors); the text model's output is the hidden state after the final norm."""
305
+
306
+ name = "mlx"
307
+
308
+ def __init__(self, path: str):
309
+ from pathlib import Path
310
+
311
+ import mlx.core as mx
312
+ from mlx_lm.utils import load_model
313
+
314
+ self.mx = mx
315
+ model, _ = load_model(Path(path))
316
+ self.text = model.language_model.model
317
+
318
+ def accepts(self, n: int) -> bool:
319
+ return True
320
+
321
+ def hidden(self, ids: Sequence[int]):
322
+ import numpy as np
323
+ import torch
324
+
325
+ h = self.text(self.mx.array([list(ids)]))[0, -1].astype(self.mx.float32)
326
+ self.mx.eval(h)
327
+ return torch.from_numpy(np.array(h))
328
+
329
+
330
+ class LlamaCpp:
331
+ """llama.cpp's llama-server answering /embedding with the last position's hidden state after the final norm,
332
+ unnormalized (embd_normalize -1). The prompt goes as token ids, so llama.cpp's tokenizer is never used. Either a server
333
+ you run (options["url"]) or one started here on the build's GGUF, on 127.0.0.1, stopped with the model."""
334
+
335
+ name = "llamacpp"
336
+
337
+ def __init__(self, artifacts: str | None, build: dict | None, max_tokens: int, options: dict):
338
+ self.context = int(options.get("context", max_tokens))
339
+ self.process = None
340
+ url = options.get("url")
341
+ if not url:
342
+ gguf = options.get("gguf") or os.path.join(artifacts, build["files"]["gguf"])
343
+ server = options.get("server") or shutil.which("llama-server")
344
+ with socket.socket() as s:
345
+ s.bind(("127.0.0.1", 0))
346
+ port = s.getsockname()[1]
347
+ # the embedding endpoint needs the whole prompt in one micro-batch: batch and micro-batch are the context
348
+ command = [server, "-m", gguf, "--embeddings", "--pooling", "last", "-c", str(self.context), "-b", str(self.context), "-ub", str(self.context),
349
+ "-ngl", str(options.get("gpu_layers", 999)), "--parallel", "1", "--host", "127.0.0.1", "--port", str(port)] # fmt: skip
350
+ if options.get("threads"):
351
+ command += ["-t", str(int(options["threads"]))]
352
+ self.output = tempfile.TemporaryFile()
353
+ self.process = subprocess.Popen(command, stdout=self.output, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
354
+ self._stop = weakref.finalize(self, _stop, self.process)
355
+ url = f"http://127.0.0.1:{port}"
356
+ self._wait(url, float(options.get("start_timeout", 600)))
357
+ self.url = url.rstrip("/") + "/embedding"
358
+
359
+ def _wait(self, url: str, timeout: float) -> None:
360
+ deadline = time.monotonic() + timeout
361
+ while time.monotonic() < deadline:
362
+ if self.process.poll() is not None:
363
+ self.output.seek(0)
364
+ tail = self.output.read().decode("utf-8", "replace")[-2000:]
365
+ raise RuntimeError(f"llama-server stopped (exit {self.process.returncode}):\n{tail}")
366
+ try:
367
+ with urllib.request.urlopen(url + "/health", timeout=5) as r:
368
+ if r.status == 200:
369
+ return
370
+ except (urllib.error.URLError, OSError):
371
+ pass
372
+ time.sleep(0.5)
373
+ raise RuntimeError(f"llama-server did not answer within {timeout:.0f} s")
374
+
375
+ def accepts(self, n: int) -> bool:
376
+ return n <= self.context
377
+
378
+ def hidden(self, ids: Sequence[int]):
379
+ import torch
380
+
381
+ body = json.dumps({"content": list(ids), "embd_normalize": -1, "cache_prompt": False}).encode()
382
+ request = urllib.request.Request(self.url, data=body, headers={"Content-Type": "application/json"})
383
+ with urllib.request.urlopen(request, timeout=600) as r:
384
+ out = json.loads(r.read())
385
+ vector = (out[0] if isinstance(out, list) else out)["embedding"]
386
+ if vector and isinstance(vector[0], list): # one row per position: the last
387
+ vector = vector[-1]
388
+ return torch.tensor(vector, dtype=torch.float32)
389
+
390
+
391
+ def _stop(process: subprocess.Popen) -> None:
392
+ if process.poll() is None:
393
+ process.terminate()
394
+ try:
395
+ process.wait(10)
396
+ except subprocess.TimeoutExpired:
397
+ process.kill()
runtime/src/decisionnode_edge/build.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the files a faster backend loads, from a model directory (only read) into a new directory.
2
+
3
+ python -m decisionnode_edge.build openvino path/to/model --out path/to/model-openvino [--lengths 512,2048]
4
+ python -m decisionnode_edge.build gguf path/to/model --out path/to/model-gguf --llama-cpp path/to/llama.cpp
5
+
6
+ openvino The backbone's text path (the token embedding, the layers, the final norm: input_ids [1, L] to the hidden
7
+ states [1, L, hidden]) exported with torch.onnx's dynamo exporter in float32 at each static length, then
8
+ saved as OpenVINO IR with float32 weights (the bf16 weights, exactly); the runtime runs it in bf16. One IR per
9
+ length, since the export unrolls the delta rule over the length: each takes 15 to 20 minutes, and lengths
10
+ above a few thousand tokens take hours. Then each IR is run once against torch. Needs the `openvino` extra
11
+ (openvino, onnx, onnxscript); `--device cuda` (the default when a GPU is present) keeps the weights on the card.
12
+ gguf llama.cpp's converter (convert_hf_to_gguf.py --no-mtp) on links to the backbone files, Q8_0 by default: 8-bit
13
+ keeps the answers, 4-bit does not. Needs a llama.cpp checkout and its converter's Python requirements, in the
14
+ environment of `--python` (default: this one).
15
+
16
+ Both write decisionnode_edge_build.json (the backend, the files, the model's fingerprint, versions, times), which
17
+ EdgeModel.load reads from `artifacts`.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import importlib.metadata
24
+ import json
25
+ import os
26
+ import shutil
27
+ import subprocess
28
+ import sys
29
+ import time
30
+
31
+ from .backends import BUILD_FILE, BUILD_FORMAT, fingerprint, link_model_files
32
+
33
+ DEFAULT_LENGTHS = (512, 2048)
34
+
35
+
36
+ def versions(*names: str) -> dict:
37
+ out = {}
38
+ for name in names:
39
+ try:
40
+ out[name] = importlib.metadata.version(name)
41
+ except importlib.metadata.PackageNotFoundError:
42
+ out[name] = None
43
+ return out
44
+
45
+
46
+ def new_directory(out: str) -> None:
47
+ if os.path.exists(out):
48
+ raise SystemExit(f"{out} exists: the build writes a new directory")
49
+ os.makedirs(out)
50
+
51
+
52
+ def write_record(out: str, record: dict) -> None:
53
+ with open(os.path.join(out, BUILD_FILE), "w", encoding="utf-8") as f:
54
+ json.dump(record, f, indent=2)
55
+ f.write("\n")
56
+
57
+
58
+ def model_name(model: str) -> str:
59
+ with open(os.path.join(model, "decisionnode_edge.json"), encoding="utf-8") as f:
60
+ return json.load(f)["name"]
61
+
62
+
63
+ def build_openvino(model: str, out: str, lengths: list[int], device: str | None) -> dict:
64
+ import numpy as np
65
+ import openvino as ov
66
+ import torch
67
+ from transformers import AutoModelForImageTextToText, AutoTokenizer
68
+
69
+ device = device or ("cuda" if torch.cuda.is_available() else "cpu")
70
+ record = {"format": BUILD_FORMAT, "backend": "openvino", "model": model_name(model), "model_fingerprint": fingerprint(model), "files": {},
71
+ "weights": "float32 (the bf16 weights, exactly); run in bf16", "export_device": device,
72
+ "versions": versions("torch", "transformers", "onnx", "onnxscript", "openvino"), "seconds": {}, "check": {}} # fmt: skip
73
+ tokenizer = AutoTokenizer.from_pretrained(model)
74
+ record["pad_token_id"] = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
75
+
76
+ class LastHidden(torch.nn.Module):
77
+ def __init__(self, text):
78
+ super().__init__()
79
+ self.text = text
80
+
81
+ def forward(self, input_ids):
82
+ return self.text(input_ids=input_ids, use_cache=False).last_hidden_state
83
+
84
+ full = AutoModelForImageTextToText.from_pretrained(model, dtype=torch.float32).to(device).eval()
85
+ text = LastHidden(full.model.language_model).eval()
86
+ generator = torch.Generator().manual_seed(0)
87
+ for length in lengths:
88
+ work = os.path.join(out, f"onnx-{length}")
89
+ os.makedirs(work)
90
+ onnx_file = os.path.join(work, "edge.onnx")
91
+ ids = torch.randint(10, 200000, (1, length), generator=generator).to(device)
92
+ t0 = time.perf_counter()
93
+ with torch.inference_mode():
94
+ torch.onnx.export(text, (ids,), onnx_file, dynamo=True, external_data=True, input_names=["input_ids"], output_names=["last_hidden_state"], optimize=True)
95
+ t1 = time.perf_counter()
96
+ ir = ov.convert_model(onnx_file)
97
+ name = f"openvino-{length}.xml"
98
+ ov.save_model(ir, os.path.join(out, name), compress_to_fp16=False)
99
+ del ir
100
+ shutil.rmtree(work)
101
+ record["files"][str(length)] = name
102
+ record["seconds"][str(length)] = {"export": round(t1 - t0, 1), "convert": round(time.perf_counter() - t1, 1)}
103
+ print(json.dumps({"length": length, **record["seconds"][str(length)]}), flush=True)
104
+
105
+ # each IR against torch (float32) on a prompt shorter than its length, so the padding is read past as at run time
106
+ core = ov.Core()
107
+ for length in lengths:
108
+ n = length - 37
109
+ ids = torch.randint(10, 200000, (1, n), generator=generator)
110
+ with torch.inference_mode():
111
+ want = text(ids.to(device))[0, -1].float().cpu()
112
+ compiled = core.compile_model(os.path.join(out, record["files"][str(length)]), "CPU", {"INFERENCE_PRECISION_HINT": "bf16"})
113
+ x = np.full((1, length), record["pad_token_id"], dtype=np.int64)
114
+ x[0, :n] = ids[0].numpy()
115
+ got = torch.from_numpy(np.asarray(compiled.create_infer_request().infer({0: x})[compiled.output(0)][0, n - 1], dtype=np.float32))
116
+ cosine = float(torch.nn.functional.cosine_similarity(got, want, dim=0))
117
+ record["check"][str(length)] = {"tokens": n, "cosine_to_torch_float32": round(cosine, 6), "largest_difference": round(float((got - want).abs().max()), 4)}
118
+ print(json.dumps({"check": length, **record["check"][str(length)]}), flush=True)
119
+ del compiled
120
+ if not torch.isfinite(got).all() or cosine < 0.99:
121
+ raise SystemExit(f"the IR at {length} tokens does not reproduce the backbone (cosine {cosine:.4f}): {out} is incomplete")
122
+ return record
123
+
124
+
125
+ def build_gguf(model: str, out: str, llama_cpp: str, outtype: str, python: str) -> dict:
126
+ converter = os.path.join(llama_cpp, "convert_hf_to_gguf.py")
127
+ if not os.path.isfile(converter):
128
+ raise SystemExit(f"{converter} not found: --llama-cpp is the llama.cpp checkout")
129
+ source = os.path.join(out, "source") # the converter reads links to the backbone files, never the readout
130
+ os.makedirs(source)
131
+ link_model_files(model, source)
132
+ name = f"model-{outtype}.gguf"
133
+ t0 = time.perf_counter()
134
+ subprocess.run([python, converter, source, "--no-mtp", "--outfile", os.path.join(out, name), "--outtype", outtype], check=True)
135
+ shutil.rmtree(source)
136
+ commit = subprocess.run(["git", "-C", llama_cpp, "rev-parse", "--short", "HEAD"], capture_output=True, text=True).stdout.strip() or None
137
+ return {"format": BUILD_FORMAT, "backend": "llamacpp", "model": model_name(model), "model_fingerprint": fingerprint(model), "files": {"gguf": name},
138
+ "type": outtype, "bytes": os.path.getsize(os.path.join(out, name)), "llama_cpp": commit, "seconds": round(time.perf_counter() - t0, 1)} # fmt: skip
139
+
140
+
141
+ def main(argv: list[str] | None = None) -> int:
142
+ parser = argparse.ArgumentParser(prog="python -m decisionnode_edge.build", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
143
+ parser.add_argument("backend", choices=("openvino", "gguf"))
144
+ parser.add_argument("model", help="the model directory (only read)")
145
+ parser.add_argument("--out", required=True, help="the directory to write (must not exist)")
146
+ parser.add_argument("--lengths", default=",".join(map(str, DEFAULT_LENGTHS)), help="openvino: the static lengths in tokens (default 512,2048)")
147
+ parser.add_argument("--device", default=None, help="openvino: where the export runs, cuda or cpu (default: cuda when present)")
148
+ parser.add_argument("--llama-cpp", help="gguf: the llama.cpp checkout (its convert_hf_to_gguf.py)")
149
+ parser.add_argument("--type", default="q8_0", choices=("q8_0", "bf16"), help="gguf: the weight type (default q8_0)")
150
+ parser.add_argument("--python", default=sys.executable, help="gguf: the Python that runs llama.cpp's converter (default: this one)")
151
+ args = parser.parse_args(argv)
152
+ for name in ("config.json", "model.safetensors", "decisionnode_edge.json"):
153
+ if not os.path.isfile(os.path.join(args.model, name)):
154
+ raise SystemExit(f"{args.model} is not a DecisionNode Edge model directory (no {name})")
155
+ if args.backend == "gguf" and not args.llama_cpp:
156
+ raise SystemExit("gguf needs --llama-cpp")
157
+ new_directory(args.out)
158
+ if args.backend == "openvino":
159
+ lengths = sorted({int(x) for x in args.lengths.split(",") if x.strip()})
160
+ record = build_openvino(args.model, args.out, lengths, args.device)
161
+ else:
162
+ record = build_gguf(args.model, args.out, args.llama_cpp, args.type, args.python)
163
+ write_record(args.out, record)
164
+ print(json.dumps({k: v for k, v in record.items() if k != "versions"}), flush=True)
165
+ return 0
166
+
167
+
168
+ if __name__ == "__main__":
169
+ sys.exit(main())
runtime/src/decisionnode_edge/model.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load a DecisionNode Edge model directory and answer requests.
2
+
3
+ from decisionnode_edge import EdgeModel
4
+
5
+ model = EdgeModel.load("path/to/decisionnode-edge")
6
+ response = model.decide({"state": "...", "questions": {"route": {"type": "choice", "criteria": {...}}}})
7
+
8
+ The model reads the prompt once per question and never generates text. Its answer is read at the
9
+ <|answer|> position: the last hidden state there is scored against a small readout table
10
+ (readout.safetensors), one row per answer code, and only the rows of the question's codes are read.
11
+ Calibration (calibration.json) turns those scores into probabilities.
12
+
13
+ The backbone is read by torch (transformers) or by a faster backend (backends.py: vLLM, OpenVINO, MLX,
14
+ llama.cpp); the readout and calibration are this module's in every case.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import io
21
+ import json
22
+ import logging
23
+ import os
24
+ from typing import Any
25
+
26
+ import torch
27
+ from safetensors.torch import load_file
28
+
29
+ from . import answers, backends, request as requests
30
+ from .template import Template
31
+
32
+ CONFIG_FILE = "decisionnode_edge.json"
33
+
34
+ log = logging.getLogger("decisionnode_edge")
35
+
36
+
37
+ def load_backbone(path: str, device: str | None, dtype: str | torch.dtype | None) -> tuple[Any, bool]:
38
+ """The transformers backbone on `device` (default CUDA when present, else the CPU) in `dtype` (default bfloat16 on
39
+ CUDA, float32 elsewhere), and whether it runs under bf16 autocast."""
40
+ from transformers import AutoModelForImageTextToText
41
+
42
+ device = device or ("cuda" if torch.cuda.is_available() else "cpu")
43
+ if dtype is None:
44
+ dtype = torch.bfloat16 if str(device).startswith("cuda") else torch.float32
45
+ dtype = getattr(torch, dtype) if isinstance(dtype, str) else dtype
46
+ backbone = AutoModelForImageTextToText.from_pretrained(path, dtype=dtype).to(device).eval()
47
+ # bf16 weights run under bf16 autocast, the reference numerics: some operations then compute in float32
48
+ return backbone, dtype == torch.bfloat16
49
+
50
+
51
+ class EdgeModel:
52
+ def __init__(self, backbone: Any, tokenizer: Any, readout: torch.Tensor, config: dict, calibration: dict, path: str, autocast: bool,
53
+ runner: Any = None, torch_options: dict | None = None): # fmt: skip
54
+ self.backbone = backbone # the transformers model; None until torch is needed when a faster backend reads the prompts
55
+ self.tokenizer = tokenizer
56
+ self.readout = readout
57
+ self.config = config
58
+ self.calibration = calibration
59
+ self.path = path
60
+ self.autocast = autocast
61
+ self.runner = runner # the backend object (backends.py), or None: torch reads every prompt
62
+ self.torch_options = torch_options or {} # device and dtype for torch when it is loaded on first use
63
+ self.template = Template(tokenizer, bytes.fromhex(config["template"]["code_seed_hex"]).decode("utf-8"))
64
+ if self.template.first_id != config["readout"]["first_token_id"]:
65
+ raise ValueError("the tokenizer and the readout table disagree on the ids of the added tokens")
66
+ self.limits = config["limits"]
67
+ self._images = None
68
+
69
+ @classmethod
70
+ def load(cls, path: str, device: str | None = None, dtype: str | torch.dtype | None = None, backend: str | None = None,
71
+ artifacts: str | None = None, options: dict | None = None) -> "EdgeModel": # fmt: skip
72
+ """Load the model directory.
73
+
74
+ `backend`: "auto" (the default, or DECISIONNODE_EDGE_BACKEND), "torch", "vllm", "openvino", "mlx" or "llamacpp".
75
+ Auto takes the fastest that is installed and can run here (backends.ORDER). `artifacts`: the directory the build
76
+ tool wrote for openvino or llamacpp (or DECISIONNODE_EDGE_ARTIFACTS); for either asked for by name it defaults to
77
+ the model directory when that holds a build (the GGUF that ships with the model). `options`: the backend's settings (the
78
+ README; DECISIONNODE_EDGE_OPTIONS as JSON is read under them).
79
+
80
+ `device` defaults to CUDA when present, else the CPU, and `dtype` to bfloat16 on CUDA (the reference
81
+ precision) and float32 elsewhere; both are torch's, also when torch only reads the prompts a
82
+ faster backend cannot take."""
83
+ from transformers import AutoTokenizer
84
+
85
+ with open(os.path.join(path, CONFIG_FILE), encoding="utf-8") as f:
86
+ config = json.load(f)
87
+ with open(os.path.join(path, config["calibration"]), encoding="utf-8") as f:
88
+ calibration = json.load(f)
89
+ tokenizer = AutoTokenizer.from_pretrained(path)
90
+ table = load_file(os.path.join(path, config["readout"]["file"]))[config["readout"]["tensor"]]
91
+ artifacts = artifacts or os.environ.get(backends.ENV_ARTIFACTS) or None
92
+ if artifacts is None and (backend or os.environ.get(backends.ENV_BACKEND) or "").strip().lower() in ("openvino", "llamacpp") and backends.read_build(path):
93
+ artifacts = path # a build that ships in the model folder (the GGUF), for a backend asked for by name
94
+ options = {**backends.env_options(), **(options or {})}
95
+ name = backends.choose(backend, device, artifacts, options)
96
+ log.info("the %s backend reads the prompts", name)
97
+ if name == "torch":
98
+ backbone, autocast = load_backbone(path, device, dtype)
99
+ return cls(backbone, tokenizer, table.float().to(backbone.device), config, calibration, path, autocast)
100
+ runner = backends.load(name, path, config, artifacts, options, device)
101
+ # the readout and calibration stay here, in float32 on the CPU
102
+ return cls(None, tokenizer, table.float(), config, calibration, path, False, runner=runner, torch_options={"device": device, "dtype": dtype})
103
+
104
+ @property
105
+ def device(self) -> torch.device:
106
+ return self.readout.device
107
+
108
+ @property
109
+ def backend(self) -> str:
110
+ """The backend that reads the prompts ("torch" also reads, on any backend, the pictures and the prompts longer than
111
+ the backend takes)."""
112
+ return self.runner.name if self.runner is not None else "torch"
113
+
114
+ # -- public -----------------------------------------------------------
115
+
116
+ def decide(self, body: dict) -> dict:
117
+ """Answer a `/v1/decide` request body. Returns {"model", "answers", "usage"} as the hosted API does."""
118
+ parsed = requests.parse(body)
119
+ probs, input_tokens = self._predict(parsed)
120
+ out = {}
121
+ for q in parsed.questions:
122
+ p = probs[q.id]
123
+ if q.type == "choice":
124
+ out[q.id] = answers.choice_answer(q.keys, p)
125
+ elif q.type == "score":
126
+ out[q.id] = answers.score_answer(q.levels, p)
127
+ elif q.type == "truth":
128
+ out[q.id] = answers.truth_answer(p)
129
+ else:
130
+ out[q.id] = answers.number_answer(q.grid, p)
131
+ return {"model": self.config["name"], "answers": out, "usage": {"input_tokens": input_tokens, "output_tokens": 0}}
132
+
133
+ def predict(self, body: dict) -> dict[str, list[float]]:
134
+ """The unrounded calibrated probabilities of every question: per option or level in request order, [yes, no]
135
+ for truth, per grid value for number."""
136
+ return self._predict(requests.parse(body))[0]
137
+
138
+ # -- internals --------------------------------------------------------
139
+
140
+ def _predict(self, parsed: requests.Request) -> tuple[dict[str, list[float]], int]:
141
+ images = self._load_images(parsed.images) if parsed.images else None
142
+ image_ids = [image["id"] for image in parsed.images]
143
+ out: dict[str, list[float]] = {}
144
+ state_tokens, total = None, 0
145
+ for q in parsed.questions:
146
+ answered = []
147
+ for row in q.rows:
148
+ encoded = self.template.encode(row, parsed.state, image_ids, images[2] if images else None)
149
+ if len(encoded.input_ids) > self.limits["max_input_tokens"]:
150
+ raise requests.RequestError(f"question {q.id!r} needs {len(encoded.input_ids):,} tokens; the maximum context length is {self.limits['max_input_tokens']:,} tokens",
151
+ error_type="max_tokens_exceeded") # fmt: skip
152
+ logits = self._logits(encoded, images)
153
+ answered.append(answers.calibrated(logits, row["type"], self.calibration, bool(image_ids)))
154
+ # the state and its pictures count once, every question's own tokens on top (as the hosted usage counts)
155
+ total += len(encoded.input_ids) - (encoded.state_tokens if state_tokens is not None else 0)
156
+ state_tokens = encoded.state_tokens
157
+ if q.type == "number":
158
+ out[q.id] = [1.0] if not q.rows else requests.compose(q.grid, answered)
159
+ else:
160
+ out[q.id] = answered[0] if answered else [1.0]
161
+ return out, total
162
+
163
+ @torch.inference_mode()
164
+ def _logits(self, encoded: Any, images: tuple | None) -> list[float]:
165
+ if self.runner is not None and images is None and self.runner.accepts(len(encoded.input_ids)):
166
+ h = self.runner.hidden(encoded.input_ids).to(self.device, torch.float32)
167
+ else:
168
+ h = self._torch_hidden(encoded, images).to(self.device)
169
+ scores = h @ self.readout.t() # one score per added token, never the vocabulary
170
+ rows = torch.tensor(encoded.class_ids, device=self.device) - self.template.first_id
171
+ return scores[rows].tolist()
172
+
173
+ def _torch_hidden(self, encoded: Any, images: tuple | None) -> torch.Tensor:
174
+ """The hidden state at the <|answer|> position (the last token) from the transformers backbone, float32."""
175
+ if self.backbone is None:
176
+ log.warning("loading torch for the prompts the %s backend does not take (pictures, longer inputs)", self.backend)
177
+ self.backbone, self.autocast = load_backbone(self.path, self.torch_options.get("device"), self.torch_options.get("dtype"))
178
+ device = self.backbone.device
179
+ input_ids = torch.tensor([encoded.input_ids], device=device)
180
+ extra = {}
181
+ if images is not None:
182
+ extra = {
183
+ "pixel_values": images[0].to(device),
184
+ "image_grid_thw": images[1].to(device),
185
+ "mm_token_type_ids": (input_ids == self.template.image_pad).long(),
186
+ }
187
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=self.autocast):
188
+ hidden = self.backbone.model(input_ids=input_ids, attention_mask=torch.ones_like(input_ids), use_cache=False, **extra).last_hidden_state
189
+ return hidden[0, -1].float()
190
+
191
+ def _load_images(self, images: list[dict]) -> tuple[torch.Tensor, torch.Tensor, dict[str, int]]:
192
+ """(pixel values, grid, placeholder tokens per image id) of a request's pictures: EXIF orientation applied,
193
+ RGB, the longest side at most max_image_side, then the backbone's own image processor."""
194
+ from PIL import Image, ImageOps
195
+ from transformers import AutoImageProcessor
196
+
197
+ if self._images is None:
198
+ self._images = AutoImageProcessor.from_pretrained(self.path)
199
+ max_side = int(self.limits["max_image_side"])
200
+ fitted = []
201
+ for image in images:
202
+ source = image["path"] if image.get("path") is not None else io.BytesIO(base64.b64decode(image["data"]))
203
+ try:
204
+ with Image.open(source) as im:
205
+ im = ImageOps.exif_transpose(im).convert("RGB")
206
+ if max(im.size) > max_side:
207
+ scale = max_side / max(im.size)
208
+ im = im.resize((max(1, round(im.width * scale)), max(1, round(im.height * scale))), Image.BICUBIC)
209
+ fitted.append(im.copy())
210
+ except (OSError, ValueError) as error:
211
+ raise requests.RequestError(f"Image {image['id']!r} could not be read: {error}") from None
212
+ out = self._images(images=fitted, return_tensors="pt")
213
+ merge = int(getattr(self._images, "merge_size", 2))
214
+ counts = (out["image_grid_thw"].prod(dim=-1) // merge**2).tolist()
215
+ return out["pixel_values"], out["image_grid_thw"], {image["id"]: int(n) for image, n in zip(images, counts)}
runtime/src/decisionnode_edge/request.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The request of the hosted `/v1/decide` endpoint, read into the questions the model answers.
2
+
3
+ {"state": ..., "questions": {"<id>": {"type": "choice" | "score" | "truth" | "number", ...}}, "images": [...]}
4
+
5
+ What a request becomes (the same rules as the hosted API):
6
+
7
+ state a string is used as it is; an object or array becomes compact JSON with its key order
8
+ kept; a missing state, null and "" are the empty state.
9
+ instructions a string, or the compact JSON of an object or array; missing or null is the empty text.
10
+ choice criteria {option: description}, 1 to 255 options. A description is a string, the compact
11
+ JSON of an object or array, or "" for null.
12
+ score criteria [level, ...], 1 to 10 levels. One level is answered without the model.
13
+ truth optional criteria {"true": ..., "false": ...}; needs instructions or criteria.
14
+ number min, max and step (default 0, 255, 1): the answer is a value of that grid. Up to 256 values
15
+ are one internal choice over the values; up to 4,096 are answered as pages of 256 (one choice
16
+ over the pages, one per page) and composed. A grid of one value is answered without the model.
17
+ images [{"id", "data" (base64) and "media_type"}] or, on Edge, [{"id", "path"}] for a local file.
18
+ Every question sees every picture, in request order.
19
+
20
+ Edge has no videos, boosters, uploads, image URLs, points or boxes: a request that names them is refused.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import math
27
+ from dataclasses import dataclass, field
28
+ from decimal import Decimal, localcontext
29
+ from typing import Any
30
+
31
+ MAX_OPTIONS = 255
32
+ MAX_LEVELS = 10
33
+ MAX_IMAGES = 16
34
+ MAX_IMAGE_ID = 64
35
+ IMAGE_MEDIA_TYPES = ("image/jpeg", "image/png", "image/webp")
36
+ ONE_ROW_VALUES = 256 # the answer codes: a grid up to this size is one internal choice
37
+ MAX_GRID_VALUES = 4096
38
+ MAX_DECIMALS = 6
39
+ NUMBER_DEFAULTS = {"min": 0, "max": 255, "step": 1}
40
+ NOT_ON_EDGE = ("videos", "boosters")
41
+
42
+
43
+ class RequestError(ValueError):
44
+ """A request the model cannot answer. `status` is the HTTP status the hosted API gives the same fault, `error_type`
45
+ the kind of fault its error body names (the local server's, server.py)."""
46
+
47
+ def __init__(self, message: str, status: int = 400, error_type: str = "api_usage_error"):
48
+ super().__init__(message)
49
+ self.status = status
50
+ self.error_type = error_type
51
+
52
+
53
+ def text_of(value: Any) -> str:
54
+ """A state, instruction, description or level as the prompt carries it."""
55
+ if value is None:
56
+ return ""
57
+ if isinstance(value, str):
58
+ return value
59
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
60
+
61
+
62
+ def _content(value: Any, where: str, nullable: bool = True) -> None:
63
+ if not (isinstance(value, (str, dict, list)) or (value is None and nullable)):
64
+ raise RequestError(f"{where} must be a string, an object or an array", 422)
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Number grids
69
+ # ---------------------------------------------------------------------------
70
+
71
+
72
+ def _decimal(value: Any) -> Decimal:
73
+ return Decimal(repr(value)) if isinstance(value, float) else Decimal(int(value))
74
+
75
+
76
+ def _places(value: Decimal) -> int:
77
+ """Digits after the point once trailing zeros are dropped: 0.5 has 1, 7 has 0."""
78
+ text = format(value.normalize(), "f")
79
+ return len(text.split(".")[1]) if "." in text else 0
80
+
81
+
82
+ def _value_text(scaled: int, d: int) -> str:
83
+ """The grid value scaled / 10^d in its shortest plain decimal form."""
84
+ digits = str(abs(scaled)).rjust(d + 1, "0")
85
+ whole, frac = (digits[:-d], digits[-d:].rstrip("0")) if d else (digits, "")
86
+ text = whole + ("." + frac if frac else "")
87
+ return "-" + text if scaled < 0 else text
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class Grid:
92
+ """Value i is (m + i * s) / 10^d, for i in 0 .. n - 1."""
93
+
94
+ d: int
95
+ m: int
96
+ s: int
97
+ n: int
98
+
99
+ def text(self, i: int) -> str:
100
+ return _value_text(self.m + i * self.s, self.d)
101
+
102
+ def texts(self, start: int = 0, end: int | None = None) -> list[str]:
103
+ return [self.text(i) for i in range(start, self.n if end is None else end)]
104
+
105
+ @property
106
+ def pages(self) -> int:
107
+ return 1 if self.n <= ONE_ROW_VALUES else -(-self.n // ONE_ROW_VALUES)
108
+
109
+ def page_bounds(self) -> list[tuple[int, int]]:
110
+ """(first, end) of each page; the first n mod pages pages hold one value more."""
111
+ q, r = divmod(self.n, self.pages)
112
+ out, start = [], 0
113
+ for j in range(self.pages):
114
+ size = q + 1 if j < r else q
115
+ out.append((start, start + size))
116
+ start += size
117
+ return out
118
+
119
+
120
+ def number_grid(question: dict, qid: str) -> Grid:
121
+ values = {}
122
+ for name in ("min", "max", "step"):
123
+ value = question.get(name)
124
+ if value is None:
125
+ value = NUMBER_DEFAULTS[name]
126
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or (isinstance(value, float) and not math.isfinite(value)):
127
+ raise RequestError(f"question {qid!r}: {name} must be a finite number", 422)
128
+ values[name] = _decimal(value)
129
+ if abs(values[name]) > 2**53:
130
+ raise RequestError(f"question {qid!r}: {name} must be within plus or minus 2^53", 422)
131
+ if name != "max" and _places(values[name]) > MAX_DECIMALS:
132
+ raise RequestError(f"question {qid!r}: {name} has more than {MAX_DECIMALS} decimals", 422)
133
+ if values["step"] <= 0:
134
+ raise RequestError(f"question {qid!r}: step must be above 0", 422)
135
+ if values["min"] > values["max"]:
136
+ raise RequestError(f"question {qid!r}: min is above max", 422)
137
+ d = max(_places(values["min"]), _places(values["step"]))
138
+ with localcontext() as ctx:
139
+ ctx.prec = 200
140
+ if d:
141
+ bound = Decimal(10) ** (15 - d) - Decimal(10) ** -d
142
+ if abs(values["min"]) > bound or abs(values["max"]) > bound:
143
+ raise RequestError(f"question {qid!r}: on a grid with {d} decimals, min and max must stay within plus or minus {bound}", 422)
144
+ scale = Decimal(10) ** d
145
+ m, s = int(values["min"] * scale), int(values["step"] * scale)
146
+ top = int((values["max"] * scale).to_integral_value(rounding="ROUND_FLOOR"))
147
+ n = (top - m) // s + 1
148
+ if n > MAX_GRID_VALUES:
149
+ raise RequestError(f"question {qid!r}: the grid holds {n} values, the limit is {MAX_GRID_VALUES}", 422)
150
+ return Grid(d=d, m=m, s=s, n=n)
151
+
152
+
153
+ def number_rows(instructions: str, grid: Grid) -> list[dict]:
154
+ """The internal choice questions of a number question: one over the values, or one over the pages and one per page."""
155
+ if grid.pages == 1:
156
+ keys = grid.texts()
157
+ return [{"type": "choice", "instructions": instructions, "keys": keys, "descs": [""] * len(keys)}]
158
+ bounds = grid.page_bounds()
159
+ rows = [{"type": "choice", "instructions": instructions, "keys": [f"{grid.text(a)} to {grid.text(b - 1)}" for a, b in bounds], "descs": [""] * len(bounds)}]
160
+ for a, b in bounds:
161
+ keys = grid.texts(a, b)
162
+ rows.append({"type": "choice", "instructions": instructions, "keys": keys, "descs": [""] * len(keys)})
163
+ return rows
164
+
165
+
166
+ def compose(grid: Grid, answered: list[list[float]]) -> list[float]:
167
+ """The probability of every grid value: p(page) * p(value | page) on a paged grid."""
168
+ if grid.pages == 1:
169
+ return list(answered[0])
170
+ out: list[float] = []
171
+ for j, page in enumerate(answered[1:]):
172
+ out.extend(answered[0][j] * p for p in page)
173
+ return out
174
+
175
+
176
+ # ---------------------------------------------------------------------------
177
+ # The request
178
+ # ---------------------------------------------------------------------------
179
+
180
+
181
+ @dataclass
182
+ class Question:
183
+ id: str
184
+ type: str # choice, score, truth or number (as answered)
185
+ rows: list[dict] # what the model runs: one prompt per row (none for a question answered without the model)
186
+ levels: list | None = None # score: the levels as sent, for `legend`
187
+ keys: list[str] | None = None # choice: the options in request order
188
+ grid: Grid | None = None # number
189
+
190
+
191
+ @dataclass
192
+ class Request:
193
+ state: str
194
+ questions: list[Question]
195
+ images: list[dict] = field(default_factory=list)
196
+
197
+
198
+ def parse(body: Any) -> Request:
199
+ """Validate a `/v1/decide` request body (a dict) and read it into questions. Raises RequestError."""
200
+ if not isinstance(body, dict):
201
+ raise RequestError("the request must be a JSON object", 422)
202
+ for name in NOT_ON_EDGE:
203
+ if body.get(name):
204
+ raise RequestError(f"`{name}` is not available on DecisionNode Edge")
205
+ state = body.get("state")
206
+ _content(state, "state")
207
+ questions = body.get("questions")
208
+ if not isinstance(questions, dict) or not questions:
209
+ raise RequestError("questions must be an object with at least one question", 422)
210
+ state_text = text_of(state)
211
+ out = [_question(qid, q) for qid, q in questions.items()]
212
+ return Request(state=state_text, questions=out, images=_images(body.get("images")))
213
+
214
+
215
+ def _question(qid: str, q: Any) -> Question:
216
+ if not isinstance(q, dict) or "type" not in q:
217
+ raise RequestError(f"question {qid!r} must be an object with a type", 422)
218
+ kind = q["type"]
219
+ if kind == "noul": # the older name of the yes-or-no type, answered as truth
220
+ kind = "truth"
221
+ if kind not in ("choice", "score", "truth", "number"):
222
+ raise RequestError(f"question {qid!r}: unknown question type {kind!r}")
223
+ instructions, criteria = q.get("instructions"), q.get("criteria")
224
+ _content(instructions, f"question {qid!r}: instructions")
225
+ text = text_of(instructions)
226
+
227
+ if kind == "number":
228
+ if instructions is None or instructions == "":
229
+ raise RequestError(f"Number question must have instructions: {qid}")
230
+ grid = number_grid(q, qid)
231
+ rows = [] if grid.n == 1 else number_rows(text, grid)
232
+ return Question(qid, "number", rows, grid=grid)
233
+
234
+ if kind == "choice":
235
+ if not isinstance(criteria, dict):
236
+ raise RequestError(f"question {qid!r}: a choice needs criteria, an object of options", 422)
237
+ if not criteria:
238
+ raise RequestError(f"Choice question must have at least one choice: {qid}")
239
+ if len(criteria) > MAX_OPTIONS:
240
+ raise RequestError(f"Too many choices: question {qid!r} has {len(criteria)} options, the limit is {MAX_OPTIONS} options per choice.")
241
+ for key, desc in criteria.items():
242
+ _content(desc, f"question {qid!r}: the description of {key!r}")
243
+ keys = list(criteria)
244
+ row = {"type": "choice", "instructions": text, "keys": keys, "descs": [text_of(d) for d in criteria.values()]}
245
+ return Question(qid, "choice", [] if len(keys) == 1 else [row], keys=keys)
246
+
247
+ if kind == "score":
248
+ if not isinstance(criteria, list) or not criteria:
249
+ raise RequestError(f"question {qid!r}: a score needs criteria, a list of 1 to {MAX_LEVELS} levels", 422)
250
+ if len(criteria) > MAX_LEVELS:
251
+ raise RequestError(f"Too many score levels. Must have at most {MAX_LEVELS} levels.")
252
+ for i, level in enumerate(criteria):
253
+ _content(level, f"question {qid!r}: level {i}", nullable=False)
254
+ row = {"type": "score", "instructions": text, "levels": [text_of(level) for level in criteria]}
255
+ return Question(qid, "score", [] if len(criteria) == 1 else [row], levels=list(criteria))
256
+
257
+ # truth
258
+ if criteria is not None and not isinstance(criteria, dict):
259
+ raise RequestError(f"question {qid!r}: truth criteria must be an object with `true` and `false`", 422)
260
+ if instructions is None and criteria is None:
261
+ raise RequestError(f"Truth question must have criteria or instructions: {qid}")
262
+ row: dict = {"type": "truth", "instructions": text}
263
+ if criteria:
264
+ for side in ("true", "false"):
265
+ _content(criteria.get(side), f"question {qid!r}: criteria.{side}")
266
+ sides = {side: text_of(criteria.get(side)) for side in ("true", "false") if text_of(criteria.get(side))}
267
+ if sides:
268
+ row["criteria"] = sides
269
+ return Question(qid, "truth", [row])
270
+
271
+
272
+ def _images(images: Any) -> list[dict]:
273
+ if images is None:
274
+ return []
275
+ if not isinstance(images, list):
276
+ raise RequestError("images must be a list", 422)
277
+ if len(images) > MAX_IMAGES:
278
+ raise RequestError(f"Too many images: {len(images)}, the limit is {MAX_IMAGES}.")
279
+ seen = set()
280
+ for i, image in enumerate(images):
281
+ if not isinstance(image, dict) or not isinstance(image.get("id"), str) or not image["id"]:
282
+ raise RequestError(f"Image {i} needs an id.")
283
+ image_id = image["id"]
284
+ if len(image_id) > MAX_IMAGE_ID:
285
+ raise RequestError(f"Image {i}: its id is longer than {MAX_IMAGE_ID} characters.")
286
+ if image_id in seen:
287
+ raise RequestError(f"Image id {image_id!r} is used twice.")
288
+ seen.add(image_id)
289
+ if image.get("url") is not None or image.get("upload_id") is not None:
290
+ raise RequestError(f"Image {image_id!r}: DecisionNode Edge reads pictures from `data` or a local `path`, not from a URL or an upload.")
291
+ forms = [name for name in ("data", "path") if image.get(name) is not None]
292
+ if len(forms) != 1:
293
+ raise RequestError(f"Image {image_id!r} needs exactly one of data and path.")
294
+ if forms == ["data"] and image.get("media_type") not in IMAGE_MEDIA_TYPES:
295
+ raise RequestError(f"Image {image_id!r}: media_type must be one of {', '.join(IMAGE_MEDIA_TYPES)}.")
296
+ return images
runtime/src/decisionnode_edge/server.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A local HTTP server for a DecisionNode Edge model, on the standard library only.
2
+
3
+ python -m decisionnode_edge serve path/to/model [--host 127.0.0.1] [--port 8000] [--api-key FILE] [--backend ...]
4
+
5
+ POST /v1/systemone the /v1/systemone format used by public decision-model leaderboards:
6
+ {"model", "state", "questions", "assets"}; noul, choice and score questions; a noul is
7
+ answered {"type": "noul", "noul": p}, a choice and a score as on /v1/decide
8
+ POST /v1/decide the DecisionNode API's call: the runtime's own request and answers (EdgeModel.decide)
9
+ GET /v1/models {"models": [{"name", "description", "release_date"}]}
10
+ GET /healthz {"status": "ok", "model", "backend"} (no key needed)
11
+
12
+ Pictures: `images` as the runtime takes them, base64 `data` only (a local `path` is refused over HTTP: a caller must
13
+ never make the server read its files), and on /v1/systemone the `assets` map of that format, {"<ref>": {"type": "image",
14
+ "format": "png" | "jpg" | "jpeg", "data_base64": ...}}, each asset a picture whose id is its reference (the state names
15
+ it), in the map's order.
16
+
17
+ Errors carry a `detail` body: {"detail": {"error_type", "message"}} (a 422 as a list of field errors). A
18
+ request over the model's length limit says "maximum context length", a choice over 255 options "options per choice",
19
+ the words leaderboard harnesses look for to count a request as beyond the model rather than as a failure.
20
+
21
+ The model answers one request at a time (a lock); the server listens on the loopback address unless told otherwise.
22
+ `model` is required on /v1/systemone, as on the hosted API, and any name is accepted: the answer names the model that
23
+ answered.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import hmac
30
+ import json
31
+ import logging
32
+ import sys
33
+ import threading
34
+ import time
35
+ import traceback
36
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
37
+ from typing import Any
38
+
39
+ from .request import RequestError
40
+
41
+ MAX_BODY_BYTES = 64 << 20 # 16 pictures as base64 with room to spare
42
+ SYSTEMONE_TYPES = ("noul", "choice", "score")
43
+ ASSET_MEDIA_TYPES = {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg"}
44
+ AUTH_MESSAGE = "Cannot authenticate with the server. Please check your API key and try again."
45
+ ROUTES = {"/v1/systemone": "POST", "/v1/decide": "POST", "/v1/models": "GET", "/healthz": "GET"}
46
+
47
+ log = logging.getLogger("decisionnode_edge.server")
48
+
49
+
50
+ class HTTPError(Exception):
51
+ def __init__(self, status: int, error_type: str, message: str, headers: dict | None = None):
52
+ super().__init__(message)
53
+ self.status, self.error_type, self.message, self.headers = status, error_type, message, headers or {}
54
+
55
+
56
+ def error_body(status: int, error_type: str, message: str) -> dict:
57
+ if status == 422:
58
+ return {"detail": [{"type": "value_error", "loc": ["body"], "msg": message, "input": None}]}
59
+ return {"detail": {"error_type": error_type, "message": message}}
60
+
61
+
62
+ def _images_over_http(images: Any) -> list:
63
+ if images is None:
64
+ return []
65
+ if not isinstance(images, list):
66
+ raise RequestError("images must be a list", 422)
67
+ for image in images:
68
+ if isinstance(image, dict) and image.get("path") is not None:
69
+ raise RequestError("Over HTTP a picture is sent as base64 `data` (or an asset), never as a local `path`.")
70
+ return list(images)
71
+
72
+
73
+ def _asset_images(assets: Any) -> list[dict]:
74
+ """The /v1/systemone `assets` map as the runtime's images: the reference is the picture's id."""
75
+ if assets is None:
76
+ return []
77
+ if not isinstance(assets, dict):
78
+ raise RequestError("assets must be an object of references", 422)
79
+ out = []
80
+ for ref, asset in assets.items():
81
+ if not isinstance(asset, dict) or asset.get("type", "image") not in ("image", None):
82
+ raise RequestError(f"Asset {ref!r}: only image assets are taken.")
83
+ media_type = ASSET_MEDIA_TYPES.get(str(asset.get("format", "")).lower())
84
+ if media_type is None:
85
+ raise RequestError(f"Asset {ref!r}: format must be one of png, jpg, jpeg.")
86
+ if not isinstance(asset.get("data_base64"), str) or not asset["data_base64"]:
87
+ raise RequestError(f"Asset {ref!r} needs data_base64.", 422)
88
+ out.append({"id": ref, "data": asset["data_base64"], "media_type": media_type})
89
+ return out
90
+
91
+
92
+ class Service:
93
+ """The routes, without the socket: handle(method, path, headers, body) gives (status, JSON body, extra headers)."""
94
+
95
+ def __init__(self, model: Any, api_key: str | None = None, description: str | None = None, release_date: str | None = None):
96
+ self.model = model
97
+ self.api_key = api_key
98
+ self.name = model.config["name"]
99
+ self.description = description or model.config.get("description") or f"{self.name}: typed, calibrated decisions, run locally"
100
+ self.release_date = release_date or model.config.get("release_date")
101
+ self.lock = threading.Lock()
102
+
103
+ def handle(self, method: str, path: str, headers: dict[str, str], body: bytes) -> tuple[int, dict, dict]:
104
+ try:
105
+ return 200, self._route(method, path.split("?", 1)[0], headers, body), {}
106
+ except HTTPError as error:
107
+ return error.status, error_body(error.status, error.error_type, error.message), error.headers
108
+ except RequestError as error:
109
+ return error.status, error_body(error.status, error.error_type, str(error)), {}
110
+ except Exception: # a fault of the model or the backend, never the caller's
111
+ log.error("the model could not answer:\n%s", traceback.format_exc())
112
+ return 500, error_body(500, "internal_error", "The model could not answer this request."), {}
113
+
114
+ def _route(self, method: str, path: str, headers: dict[str, str], body: bytes) -> dict:
115
+ if path not in ROUTES:
116
+ raise HTTPError(404, "not_found_error", "Not found.")
117
+ if method != ROUTES[path]:
118
+ raise HTTPError(405, "api_usage_error", "Method not allowed.", {"Allow": ROUTES[path]})
119
+ if path == "/healthz":
120
+ return {"status": "ok", "model": self.name, "backend": self.model.backend}
121
+ self._authenticate(headers)
122
+ if path == "/v1/models":
123
+ return {"models": [{"name": self.name, "description": self.description, "release_date": self.release_date}]}
124
+ try:
125
+ request = json.loads(body)
126
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
127
+ raise RequestError(f"the body is not JSON: {error}", 422) from None
128
+ if path == "/v1/decide":
129
+ if isinstance(request, dict) and request.get("images") is not None:
130
+ request = {**request, "images": _images_over_http(request["images"])}
131
+ with self.lock:
132
+ return self.model.decide(request)
133
+ return self._systemone(request)
134
+
135
+ def _authenticate(self, headers: dict[str, str]) -> None:
136
+ if self.api_key is None:
137
+ return
138
+ given = headers.get("authorization", "")
139
+ scheme, _, token = given.partition(" ")
140
+ if scheme.lower() != "bearer" or not hmac.compare_digest(token.strip().encode(), self.api_key.encode()):
141
+ raise HTTPError(401, "authentication_error", AUTH_MESSAGE, {"WWW-Authenticate": "Bearer"})
142
+
143
+ def _systemone(self, request: Any) -> dict:
144
+ if not isinstance(request, dict):
145
+ raise RequestError("the request must be a JSON object", 422)
146
+ if not isinstance(request.get("model"), str):
147
+ raise RequestError("model: Field required, a string", 422)
148
+ questions = request.get("questions")
149
+ if isinstance(questions, dict):
150
+ for qid, question in questions.items():
151
+ kind = question.get("type") if isinstance(question, dict) else None
152
+ if kind == "number":
153
+ raise RequestError(f"question {qid!r}: the number type is not available on /v1/systemone; send it to /v1/decide")
154
+ if isinstance(question, dict) and "type" in question and kind not in SYSTEMONE_TYPES:
155
+ raise RequestError(f"question {qid!r}: unknown question type {kind!r}")
156
+ images = _images_over_http(request.get("images")) + _asset_images(request.get("assets"))
157
+ body = {"state": request.get("state"), "questions": questions}
158
+ if images:
159
+ body["images"] = images
160
+ with self.lock:
161
+ response = self.model.decide(body)
162
+ answers = {}
163
+ for qid, answer in response["answers"].items(): # a noul is answered under its own name, as the format has it
164
+ answers[qid] = {"type": "noul", "noul": answer["truth"]} if answer["type"] == "truth" else answer
165
+ return {"model": response["model"], "answers": answers, "usage": response["usage"]}
166
+
167
+
168
+ class Handler(BaseHTTPRequestHandler):
169
+ protocol_version = "HTTP/1.1" # keep-alive: every response carries Content-Length
170
+ disable_nagle_algorithm = True # headers and body are two writes: without it a kept-alive client waits for a delayed ACK
171
+ server_version = "decisionnode-edge"
172
+ service: Service = None # set by make_server
173
+
174
+ def _answer(self, method: str) -> None:
175
+ started = time.perf_counter()
176
+ body = b""
177
+ if method == "POST":
178
+ length = self.headers.get("Content-Length")
179
+ if length is None or not length.isdigit():
180
+ return self._send(411, error_body(411, "api_usage_error", "Content-Length is required."), {"Connection": "close"}, started)
181
+ if int(length) > MAX_BODY_BYTES:
182
+ return self._send(413, error_body(413, "api_usage_error", "Request body too large."), {"Connection": "close"}, started)
183
+ body = self.rfile.read(int(length))
184
+ headers = {k.lower(): v for k, v in self.headers.items()}
185
+ status, payload, extra = self.service.handle(method, self.path, headers, body)
186
+ self._send(status, payload, extra, started)
187
+
188
+ def _send(self, status: int, payload: dict, extra: dict, started: float) -> None:
189
+ data = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
190
+ self.send_response(status)
191
+ self.send_header("Content-Type", "application/json")
192
+ self.send_header("Content-Length", str(len(data)))
193
+ self.send_header("X-Latency-Ms", f"{(time.perf_counter() - started) * 1000:.2f}")
194
+ for name, value in extra.items():
195
+ self.send_header(name, value)
196
+ self.end_headers()
197
+ self.wfile.write(data)
198
+ if extra.get("Connection") == "close":
199
+ self.close_connection = True
200
+
201
+ def do_GET(self) -> None: # noqa: N802 (the standard library's names)
202
+ self._answer("GET")
203
+
204
+ def do_POST(self) -> None: # noqa: N802
205
+ self._answer("POST")
206
+
207
+ def do_PUT(self) -> None: # noqa: N802
208
+ self._answer("PUT")
209
+
210
+ def do_DELETE(self) -> None: # noqa: N802
211
+ self._answer("DELETE")
212
+
213
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002
214
+ log.info("%s %s", self.address_string(), format % args)
215
+
216
+
217
+ def make_server(model: Any, host: str = "127.0.0.1", port: int = 8000, api_key: str | None = None, **service: Any) -> ThreadingHTTPServer:
218
+ handler = type("EdgeHandler", (Handler,), {"service": Service(model, api_key=api_key, **service)})
219
+ server = ThreadingHTTPServer((host, port), handler)
220
+ server.daemon_threads = True
221
+ return server
222
+
223
+
224
+ def main(argv: list[str] | None = None) -> int:
225
+ from . import EdgeModel
226
+
227
+ parser = argparse.ArgumentParser(prog="python -m decisionnode_edge serve", description="Serve a DecisionNode Edge model over HTTP: /v1/systemone, /v1/decide, /v1/models.")
228
+ parser.add_argument("model", help="the model directory")
229
+ parser.add_argument("--host", default="127.0.0.1", help="the address to listen on (default 127.0.0.1, this machine only)")
230
+ parser.add_argument("--port", type=int, default=8000)
231
+ parser.add_argument("--api-key", default=None, help="a file holding the key callers must send as `Authorization: Bearer <key>`")
232
+ parser.add_argument("--device", default=None)
233
+ parser.add_argument("--dtype", default=None)
234
+ parser.add_argument("--backend", default=None, help="auto, torch, vllm, openvino, mlx or llamacpp (default: auto)")
235
+ parser.add_argument("--artifacts", default=None, help="the directory python -m decisionnode_edge.build wrote")
236
+ parser.add_argument("--description", default=None, help="the description GET /v1/models gives")
237
+ parser.add_argument("--release-date", default=None, help="the release date GET /v1/models gives (YYYY-MM-DD)")
238
+ args = parser.parse_args(argv)
239
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s")
240
+ api_key = None
241
+ if args.api_key:
242
+ with open(args.api_key, encoding="utf-8") as f:
243
+ api_key = f.read().strip()
244
+ if not api_key:
245
+ raise SystemExit(f"{args.api_key} is empty")
246
+ model = EdgeModel.load(args.model, device=args.device, dtype=args.dtype, backend=args.backend, artifacts=args.artifacts)
247
+ model.decide({"state": "The color is red.", "questions": {"warmup": {"type": "choice", "instructions": "Which color is named?", "criteria": {"red": "red", "blue": "blue"}}}})
248
+ server = make_server(model, args.host, args.port, api_key, description=args.description, release_date=args.release_date)
249
+ log.info("serving %s (%s backend) on http://%s:%d%s", model.config["name"], model.backend, args.host, server.server_address[1], ", key required" if api_key else "")
250
+ try:
251
+ server.serve_forever()
252
+ except KeyboardInterrupt:
253
+ pass
254
+ finally:
255
+ server.server_close()
256
+ return 0
257
+
258
+
259
+ if __name__ == "__main__":
260
+ sys.exit(main())
runtime/src/decisionnode_edge/template.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The prompt format the model reads: the added tokens, the answer codes and the encoder.
2
+
3
+ One prompt per question. The state block comes first, then the question block, then the
4
+ word "Answer" and the <|answer|> token, whose position the answer is read from:
5
+
6
+ <|state|>\\n{Picture n (id): <|vision_start|>pads<|vision_end|>\\n ...}{state}\\n
7
+ <|question|>\\ntype: {choice|score|noul}\\n{instructions}\\n{option lines}Answer<|answer|>
8
+
9
+ A choice option line is `<|opt_NNN|> key: description\\n` (`<|opt_NNN|> key\\n` when the
10
+ description is empty), a score level line `<|opt_NNN|> index: level\\n`. A truth question
11
+ has no option lines (the prompt calls it `noul`) and carries
12
+ its criteria as `yes: ...\\n` and `no: ...\\n` lines. It is answered by <|yes|> and <|no|>.
13
+
14
+ Each option gets one of 256 code tokens. The codes are drawn from a stream seeded by a
15
+ SHA-256 of the question alone (never the state), so the same question always gets the
16
+ same codes. The seed's first part is a fixed string from the model directory
17
+ (`code_seed_hex` in decisionnode_edge.json): the model gives its published answers only
18
+ with that string.
19
+
20
+ Request text can never become a control token: plain text is tokenised with
21
+ `split_special_tokens=True`, and the few added tokens that flag does not split (such as
22
+ `<think>`) are cut inside the string before tokenising.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import hashlib
28
+ import re
29
+ from dataclasses import dataclass, field
30
+ from typing import Any, Sequence
31
+
32
+ STATE = "<|state|>"
33
+ QUESTION = "<|question|>"
34
+ ANSWER = "<|answer|>"
35
+ YES = "<|yes|>"
36
+ NO = "<|no|>"
37
+ N_CODES = 256
38
+ CODES = tuple(f"<|opt_{i:03d}|>" for i in range(N_CODES))
39
+ ADDED_TOKENS = (STATE, QUESTION, ANSWER, YES, NO) + CODES # 261 tokens, in id order
40
+ ANSWER_CUE = "Answer"
41
+ # The type word each question type carries in the prompt.
42
+ TYPE_WORDS = {"choice": "choice", "score": "score", "truth": "noul"}
43
+
44
+ IMAGE_PAD = "<|image_pad|>"
45
+ VISION_START = "<|vision_start|>"
46
+ VISION_END = "<|vision_end|>"
47
+
48
+ # Segment kinds
49
+ SPECIAL, TEXT, STATE_TEXT, IMAGE = "special", "text", "state", "image"
50
+
51
+
52
+ class TemplateError(ValueError):
53
+ pass
54
+
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # Codes
58
+ # ---------------------------------------------------------------------------
59
+
60
+
61
+ def question_hash(seed: str, question: dict, pass_index: int = 0) -> bytes:
62
+ """SHA-256 of the question alone: the seed, the pass, the type word, the instructions and the options
63
+ (or levels, or truth criteria). Every part is length-prefixed, so two questions cannot collide by concatenation."""
64
+ kind = question["type"]
65
+ parts = [seed, str(int(pass_index)), TYPE_WORDS[kind], question["instructions"]]
66
+ if kind == "choice":
67
+ for key, desc in zip(question["keys"], question["descs"]):
68
+ parts += [key, desc]
69
+ elif kind == "score":
70
+ parts += list(question["levels"])
71
+ else:
72
+ for name, text in criteria_lines(question):
73
+ parts += [name, text]
74
+ h = hashlib.sha256()
75
+ for part in parts:
76
+ raw = part.encode("utf-8")
77
+ h.update(len(raw).to_bytes(8, "big"))
78
+ h.update(raw)
79
+ return h.digest()
80
+
81
+
82
+ class HashStream:
83
+ """Deterministic integers from a seed: SHA-256 in counter mode, 4 bytes at a time."""
84
+
85
+ def __init__(self, seed: bytes):
86
+ self._seed, self._counter, self._buf = seed, 0, b""
87
+
88
+ def _u32(self) -> int:
89
+ if len(self._buf) < 4:
90
+ self._buf += hashlib.sha256(self._seed + self._counter.to_bytes(8, "big")).digest()
91
+ self._counter += 1
92
+ value = int.from_bytes(self._buf[:4], "big")
93
+ self._buf = self._buf[4:]
94
+ return value
95
+
96
+ def below(self, n: int) -> int:
97
+ """A uniform integer in [0, n), by rejection (no modulo bias)."""
98
+ limit = (1 << 32) - ((1 << 32) % n)
99
+ while True:
100
+ value = self._u32()
101
+ if value < limit:
102
+ return value % n
103
+
104
+ def sample(self, population: int, k: int) -> list[int]:
105
+ """k distinct integers from range(population): a partial Fisher-Yates shuffle."""
106
+ pool = list(range(population))
107
+ for i in range(k):
108
+ j = i + self.below(population - i)
109
+ pool[i], pool[j] = pool[j], pool[i]
110
+ return pool[:k]
111
+
112
+
113
+ def n_classes(question: dict) -> int:
114
+ if question["type"] == "choice":
115
+ return len(question["keys"])
116
+ if question["type"] == "score":
117
+ return len(question["levels"])
118
+ return 2
119
+
120
+
121
+ def assign_codes(seed: str, question: dict) -> list[int]:
122
+ """The code index of every option (or level) of a choice or score question, in the order given."""
123
+ k = n_classes(question)
124
+ if k > N_CODES:
125
+ raise TemplateError(f"{k} options, the model has {N_CODES} codes")
126
+ return HashStream(question_hash(seed, question)).sample(N_CODES, k)
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # Segments
131
+ # ---------------------------------------------------------------------------
132
+
133
+
134
+ def criteria_lines(question: dict) -> list[tuple[str, str]]:
135
+ """A truth question's criteria as ("yes", text) and ("no", text), each only if given."""
136
+ criteria = question.get("criteria") or {}
137
+ return [(label, criteria[name]) for name, label in (("true", "yes"), ("false", "no")) if criteria.get(name)]
138
+
139
+
140
+ def image_label(number: int, image_id: str) -> str:
141
+ """The words in front of the request's number-th picture (counted from 1)."""
142
+ return f"Picture {int(number)} ({image_id}): "
143
+
144
+
145
+ def build_segments(question: dict, state: str, image_ids: Sequence[str], codes: Sequence[int]) -> list[tuple[str, str]]:
146
+ """The prompt of one question as (kind, value) segments, state first."""
147
+ segments: list[tuple[str, str]] = [(SPECIAL, STATE), (TEXT, "\n")]
148
+ for number, image_id in enumerate(image_ids, 1):
149
+ segments += [(TEXT, image_label(number, image_id)), (IMAGE, image_id), (TEXT, "\n")]
150
+ segments += [(STATE_TEXT, state), (TEXT, "\n")]
151
+
152
+ kind = question["type"]
153
+ text = f"\ntype: {TYPE_WORDS[kind]}\n{question['instructions']}\n"
154
+ if kind == "truth":
155
+ text += "".join(f"{label}: {value}\n" for label, value in criteria_lines(question))
156
+ segments += [(SPECIAL, QUESTION), (TEXT, text)]
157
+ if kind == "choice":
158
+ for key, desc, code in zip(question["keys"], question["descs"], codes):
159
+ segments += [(SPECIAL, CODES[code]), (TEXT, f" {key}: {desc}\n" if desc else f" {key}\n")]
160
+ elif kind == "score":
161
+ for index, (level, code) in enumerate(zip(question["levels"], codes)):
162
+ segments += [(SPECIAL, CODES[code]), (TEXT, f" {index}: {level}\n")]
163
+ segments += [(TEXT, ANSWER_CUE), (SPECIAL, ANSWER)]
164
+ return segments
165
+
166
+
167
+ # ---------------------------------------------------------------------------
168
+ # Encoder
169
+ # ---------------------------------------------------------------------------
170
+
171
+
172
+ @dataclass
173
+ class Encoded:
174
+ input_ids: list[int]
175
+ class_ids: list[int] # the token whose readout row scores each class, in class order
176
+ state_tokens: int # tokens of the state block (with its pictures), shared by every question of a request
177
+ image_slots: list[tuple[str, int, int]] = field(default_factory=list) # (image id, first pad position, count)
178
+
179
+
180
+ class Template:
181
+ """The template bound to the model's tokenizer."""
182
+
183
+ def __init__(self, tokenizer: Any, seed: str):
184
+ self.tokenizer = tokenizer
185
+ self.seed = seed
186
+ ids = [tokenizer.convert_tokens_to_ids(token) for token in ADDED_TOKENS]
187
+ first = ids[0]
188
+ if first is None or ids != list(range(first, first + len(ADDED_TOKENS))):
189
+ raise TemplateError("the tokenizer does not hold the model's added tokens as one id range")
190
+ self.first_id = first
191
+ self.special_ids = dict(zip(ADDED_TOKENS, ids))
192
+ self.image_pad, self.vision_start, self.vision_end = (tokenizer.convert_tokens_to_ids(t) for t in (IMAGE_PAD, VISION_START, VISION_END))
193
+ unsplit = _unsplit_added_tokens(tokenizer)
194
+ self._guard = re.compile("|".join(re.escape(t) for t in sorted(unsplit, key=len, reverse=True))) if unsplit else None
195
+ self._guarded_ids = frozenset(unsplit.values())
196
+
197
+ def class_ids(self, question: dict, codes: Sequence[int]) -> list[int]:
198
+ if question["type"] == "truth":
199
+ return [self.special_ids[YES], self.special_ids[NO]]
200
+ return [self.first_id + 5 + c for c in codes]
201
+
202
+ def encode(self, question: dict, state: str, image_ids: Sequence[str] = (), image_tokens: dict[str, int] | None = None) -> Encoded:
203
+ codes = assign_codes(self.seed, question) if question["type"] in ("choice", "score") else []
204
+ segments = build_segments(question, state, image_ids, codes)
205
+ table = self._tokenize([value for kind, value in segments if kind in (TEXT, STATE_TEXT)])
206
+ ids: list[int] = []
207
+ slots: list[tuple[str, int, int]] = []
208
+ state_tokens = 0
209
+ for kind, value in segments:
210
+ if kind == SPECIAL:
211
+ ids.append(self.special_ids[value])
212
+ elif kind in (TEXT, STATE_TEXT):
213
+ ids.extend(table[value])
214
+ if kind == STATE_TEXT:
215
+ state_tokens = len(ids) + len(table["\n"]) # the state block ends with the line break after the state
216
+ else: # a picture: its placeholders, as many as the image processor gives it
217
+ count = int((image_tokens or {})[value])
218
+ ids.append(self.vision_start)
219
+ slots.append((value, len(ids), count))
220
+ ids.extend([self.image_pad] * count)
221
+ ids.append(self.vision_end)
222
+ return Encoded(ids, self.class_ids(question, codes), state_tokens, slots)
223
+
224
+ def _tokenize(self, texts: Sequence[str]) -> dict[str, list[int]]:
225
+ """Plain-text ids of every distinct text, with special-token strings kept as text."""
226
+ unique = [t for t in dict.fromkeys(texts) if t]
227
+ pieces_of = {t: _break_tokens(t, self._guard) for t in unique if self._guard is not None and self._guard.search(t)}
228
+ flat = list(dict.fromkeys(p for t in unique for p in pieces_of.get(t, (t,))))
229
+ encoded = {}
230
+ if flat:
231
+ out = self.tokenizer(flat, add_special_tokens=False, split_special_tokens=True, return_attention_mask=False)["input_ids"]
232
+ encoded = dict(zip(flat, (list(x) for x in out)))
233
+ table: dict[str, list[int]] = {"": []}
234
+ for text in unique:
235
+ if text in pieces_of:
236
+ ids = [i for piece in pieces_of[text] for i in encoded[piece]]
237
+ if not self._guarded_ids.isdisjoint(ids):
238
+ raise TemplateError("request text produced a control token")
239
+ table[text] = ids
240
+ else:
241
+ table[text] = encoded[text]
242
+ return table
243
+
244
+
245
+ def _unsplit_added_tokens(tokenizer: Any) -> dict[str, int]:
246
+ """Added tokens that `split_special_tokens=True` still turns into one id (found by trying each)."""
247
+ out = {}
248
+ for token, index in dict(tokenizer.get_added_vocab()).items():
249
+ if len(token) >= 2 and tokenizer.encode(token, add_special_tokens=False, split_special_tokens=True) == [index]:
250
+ out[token] = int(index)
251
+ return out
252
+
253
+
254
+ def _break_tokens(text: str, pattern: "re.Pattern[str]") -> list[str]:
255
+ """Cut `text` after the first character of every added-token string, so none survives whole."""
256
+ pieces, start = [], 0
257
+ for match in pattern.finditer(text):
258
+ pieces.append(text[start : match.start() + 1])
259
+ start = match.start() + 1
260
+ pieces.append(text[start:])
261
+ out = []
262
+ for piece in pieces:
263
+ out.extend(_break_tokens(piece, pattern) if pattern.search(piece) else [piece])
264
+ return [piece for piece in out if piece]
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e9f31870a35eb9372bbc8719603e5d02f2e07eff90af9f7b77fe3b17d3628ff
3
+ size 20038396
tokenizer_config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "audio_bos_token": "<|audio_start|>",
4
+ "audio_eos_token": "<|audio_end|>",
5
+ "audio_token": "<|audio_pad|>",
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|endoftext|>",
10
+ "errors": "replace",
11
+ "extra_special_tokens": [
12
+ "<|im_start|>",
13
+ "<|im_end|>",
14
+ "<|object_ref_start|>",
15
+ "<|object_ref_end|>",
16
+ "<|box_start|>",
17
+ "<|box_end|>",
18
+ "<|quad_start|>",
19
+ "<|quad_end|>",
20
+ "<|vision_start|>",
21
+ "<|vision_end|>",
22
+ "<|vision_pad|>",
23
+ "<|image_pad|>",
24
+ "<|video_pad|>"
25
+ ],
26
+ "image_token": "<|image_pad|>",
27
+ "is_local": true,
28
+ "local_files_only": false,
29
+ "merges_file": null,
30
+ "model_max_length": 262144,
31
+ "model_specific_special_tokens": {
32
+ "audio_bos_token": "<|audio_start|>",
33
+ "audio_eos_token": "<|audio_end|>",
34
+ "audio_token": "<|audio_pad|>",
35
+ "image_token": "<|image_pad|>",
36
+ "video_token": "<|video_pad|>",
37
+ "vision_bos_token": "<|vision_start|>",
38
+ "vision_eos_token": "<|vision_end|>"
39
+ },
40
+ "pad_token": "<|endoftext|>",
41
+ "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
42
+ "split_special_tokens": false,
43
+ "tokenizer_class": "Qwen3_5Tokenizer",
44
+ "unk_token": null,
45
+ "video_token": "<|video_pad|>",
46
+ "vision_bos_token": "<|vision_start|>",
47
+ "vision_eos_token": "<|vision_end|>"
48
+ }
video_preprocessor_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "size": {
3
+ "longest_edge": 234881024,
4
+ "shortest_edge": 4096
5
+ },
6
+ "patch_size": 16,
7
+ "temporal_patch_size": 2,
8
+ "merge_size": 2,
9
+ "image_mean": [
10
+ 0.5,
11
+ 0.5,
12
+ 0.5
13
+ ],
14
+ "image_std": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "processor_class": "Qwen3VLProcessor",
20
+ "video_processor_type": "Qwen3VLVideoProcessor"
21
+ }