Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
fix(ts): read a temperature as float() does, not as Number() does
Aashish642f37a736ce
diff --git a/laya-ts/src/common.ts b/laya-ts/src/common.tsindex ec21ccbe..131c2e10 100644--- a/laya-ts/src/common.ts+++ b/laya-ts/src/common.ts@@ -396,9 +396,34 @@ export function flagLowConfidence(}}export const TEMP_MIN = 0.5, TEMP_MAX = 5.0;+/**+ * A usable temperature: `t` confined to [`TEMP_MIN`, `TEMP_MAX`], falling back to the neutral 1.0+ * when it is not a number. Parity with py `common.clamp_temperature`, which asks that question with+ * `float()`.+ *+ * `Number()` asks it more loosely, so a value that is not a number at all reaches the clamp as one.+ * Measured as `clamp_temperature(t)` / `clampTemperature(t)` over the values a checkpoint config can+ * hold:+ *+ * t py ts (before)+ * " " 1.0 0.5 Number(" ") is 0, float(" ") raises+ * [] 1.0 0.5 Number([]) is 0+ * [2] 1.0 2.0 Number([2]) is 2+ * ["2"] 1.0 2.0 Number(["2"]) is 2+ *+ * The nested lists are the worse half: 2.0 is inside the range, so the loader's own diagnostic+ * compared it, found it equal, and said nothing about the value the reference refuses outright.+ * Whichever number landed then scales the logits every published confidence comes from. Take an+ * answer the neutral 1.0 puts at 0.60: the port's old 0.5 reads it as 0.69 among two options and+ * 0.92 among six, and its old 2.0 reads the same answer as 0.55 and 0.35. So one malformed field+ * made a coin flip look certain or a real preference look like noise, depending on which way+ * `Number()` happened to coerce it. Only a number, or a string that holds one, reaches the clamp.+ */export function clampTemperature(t: unknown): number {- if (t === null || t === undefined || t === "" || typeof t === "boolean") return 1.0;- const f = typeof t === "number" ? t : Number(t);+ let f: number;+ if (typeof t === "number" || typeof t === "bigint") f = Number(t);+ else if (typeof t === "string" && t.trim() !== "") f = Number(t);+ else return 1.0;if (!Number.isFinite(f)) return 1.0;return Math.min(TEMP_MAX, Math.max(TEMP_MIN, f));}diff --git a/laya-ts/tests/temperature-coercion.test.ts b/laya-ts/tests/temperature-coercion.test.tsnew file mode 100644index 00000000..216c92db--- /dev/null+++ b/laya-ts/tests/temperature-coercion.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it, vi } from "vitest";+import { clampTemperature, TEMP_MAX, TEMP_MIN } from "../src/common.js";+import { Agent } from "../src/agent.js";++// The reference asks "is this a number?" with `float()`, which answers no for null, a boolean, a+// list, an object and a string that holds nothing but blanks. `Number()` answers yes for all six and+// produces 0 or the inner element, and 0 lands on TEMP_MIN -- the sharpening end, where a published+// confidence is inflated rather than merely uncalibrated. These are the cases where the two answers+// differed, measured as `clamp_temperature(t)` / `clampTemperature(t)` on the port's own base.++const fakeProvider = () => ({+ async runEncoder(_b: any) { return { lastHidden: [[1, 0], [0, 1]] }; },+ async runHead(_h: any) { return { logits: [[2, 0]], act: [[3, 0]] }; },+});++const CHOICE = { d: { type: "choice", instructions: "q?", criteria: { x: "yes", y: "no" } } } as any;++function loadWith(temperature: unknown[]) {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ const agent = new Agent({+ provider: fakeProvider(),+ cfg: { temperature },+ } as any);+ return { agent, warnings: warn.mock.calls.map((call: unknown[]) => String(call[0])) };+ } finally {+ warn.mockRestore();+ }+}++describe("clampTemperature", () => {+ it.each([+ ["[]", []],+ ["[2]", [2]],+ ['["2"]', ["2"]],+ ['" "', " "],+ ['"\\t\\n"', "\t\n"],+ ["null", null],+ ["undefined", undefined],+ ['""', ""],+ ["true", true],+ ["false", false],+ ["{}", {}],+ ["NaN", NaN],+ ["Infinity", Infinity],+ ])("falls back to the neutral 1.0 for %s, which is not a number", (_label, value) => {+ expect(clampTemperature(value)).toBe(1.0);+ });++ it("still bounds a real number instead of falling back", () => {+ // The fallback must not swallow the clamp: 0 is a number, and 0 means sharpen hard.+ expect(clampTemperature(0)).toBe(TEMP_MIN);+ expect(clampTemperature(-3)).toBe(TEMP_MIN);+ expect(clampTemperature(0.1006)).toBe(TEMP_MIN);+ expect(clampTemperature(9)).toBe(TEMP_MAX);+ expect(clampTemperature(1.7601518630981445)).toBe(1.7601518630981445);+ expect(clampTemperature(1.0)).toBe(1.0);+ });++ it("still reads a number out of a string, as float() does", () => {+ expect(clampTemperature("2")).toBe(2.0);+ expect(clampTemperature(" 2 ")).toBe(2.0);+ expect(clampTemperature("2e0")).toBe(2.0);+ expect(clampTemperature("1.5")).toBe(1.5);+ // float("nan") and float("inf") do convert, and then fail the finite test the same way.+ expect(clampTemperature("nan")).toBe(1.0);+ expect(clampTemperature("invalid")).toBe(1.0);+ // A bigint is Python's int on the JSON-bigint path, not a value to fall back for.+ expect(clampTemperature(2n as never)).toBe(2.0);+ });+});++describe("checkpoint temperature loading", () => {+ it.each([+ [["[2]", [2]]],+ [['["2"]', ["2"]]],+ [['" "', " "]],+ [["[]", []]],+ ])("loads %s as the neutral 1.0 and says so", (_label: string, value: unknown) => {+ const { agent, warnings } = loadWith([value, 2.0, 3.0]);+ expect(agent.temperature).toEqual([1.0, 2.0, 3.0]);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain("temperature[0]");+ expect(warnings[0]).toContain("uncalibrated");+ });++ it("scales the answer by the neutral 1.0 it installed, not by a coerced number", async () => {+ // The whole point of the fallback. Logits [2, 0] at T=1 publish 0.8808; the same forward at the+ // 0.5 the old coercion installed for `[]` publishes 0.9820, and at the 2.0 it installed for+ // `[2]` publishes 0.7311. One bad field, and the answer is over- or under-confident depending on+ // which way `Number()` happened to round it.+ const { agent } = loadWith([[2], 2.0, 3.0]);+ const r: any = await agent.systemOne("hi", CHOICE);+ expect(r.answers.d.probabilities.x).toBeCloseTo(0.8808, 4);+ });++ it("leaves a list of three real numbers alone", () => {+ const { agent, warnings } = loadWith([1.0, 2.0, 0.5]);+ expect(agent.temperature).toEqual([1.0, 2.0, 0.5]);+ expect(warnings).toEqual([]);+ });+});