Skip to content

armgit / laya

Public Imported from GitHub
0

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.

12.6 KB
Raw Blame
import { readFileSync } from "node:fs";
import { describe, expect, it, vi } from "vitest";
import { Agent } from "../src/agent.js";
import { OptionStabilityHook } from "../src/option-stability.js";
import type { PredictContext } from "../src/hooks.js";
import type { Batch, SessionProvider } from "../src/providers.js";

// Generated by calling Python ONNXAgent.predict_long, including its real encoder,
// decoder and hook dispatcher. The fake provider is deterministic, not a model eval.
const fixtures = JSON.parse(readFileSync(new URL("../fixtures/predict-long.json", import.meta.url), "utf8"));
const clone = <T>(value: T): T => structuredClone(value);
const sum = (values: number[]) => values.reduce((left, right) => left + right, 0);

function setup(testCase: any) {
  const forwards: unknown[] = [];
  const provider: SessionProvider = {
    async runEncoder(batch: Batch) {
      forwards.push({ rows: batch.inputIds.length, tokens: batch.attentionMask.map(sum), sums: batch.inputIds.map(sum) });
      return { lastHidden: batch.inputIds.map(() => [[0]]) };
    },
    async runHead(_hidden, batch: Batch) {
      return {
        logits: batch.inputIds.map((row, index) => batch.markerMask[index].map((_, slot) =>
          slot === 0 ? (testCase.tie ? 2 : 1 + sum(row) % 5) : -slot)),
        act: batch.inputIds.map(() => [0.25, 0.75]),
      };
    },
  };
  const agent = new Agent({
    provider,
    cfg: clone(testCase.cfg),
    tok: {
      clsId: 1, sepId: 2, maskId: 3, padId: 0, maskToken: "[M]",
      encode: (text: string) => Array.from(text, (char) => char.codePointAt(0)! + 10),
      decode: (ids: number[]) => ids.map((id) => String.fromCodePoint(id - 10).repeat(testCase.expansion ?? 1)).join(""),
    },
  });
  if (testCase.behavior === "installed-end-reverse") {
    agent.addHook({ onPredictEnd(ctx) { ctx.results!.reverse(); } });
  }
  if (testCase.behavior === "shared-answer") {
    // A custom inference adapter sharing an answer object has no unique origin.
    // Install this before the public dispatcher records answers, matching Python.
    const original = (agent as any)._systemOneMany.bind(agent);
    (agent as any)._systemOneMany = async (...args: unknown[]) => {
      const rows = await original(...args);
      for (const row of rows) row.answers.route = rows[0].answers.route;
      return rows;
    };
  }
  if (["replace-batch", "replace-batch-added-removed"].includes(testCase.behavior)) {
    agent.predictBatch = async (states, questions, options = {}) => {
      if (testCase.behavior === "replace-batch-added-removed") {
        questions.temporary = { type: "noul", instructions: "?" };
      }
      const rows = await (agent as any)._systemOneMany(states, questions, options);
      if (testCase.behavior === "replace-batch-added-removed") {
        for (const row of rows) delete row.answers.temporary;
      }
      return rows;
    };
  }
  return { agent, forwards };
}

function hooksFor(testCase: any, events: unknown[], cached: any) {
  const behavior = testCase.behavior;
  const onPredictStart = (ctx: PredictContext) => {
    if (behavior === "reverse-states") ctx.states.reverse();
    else if (behavior === "clone-states") ctx.states = clone(ctx.states);
    else if (behavior === "rewrite-states") ctx.states = ["rewritten"];
    else if (behavior === "empty-states") ctx.states = [];
    else if (["temporary-remove-all", "temporary-remove-some"].includes(behavior)) {
      ctx.questions.temporary = { type: "noul", instructions: "?" };
    } else if (behavior === "rewrite-question-type") {
      ctx.questions.route = { type: "noul", instructions: "?" };
    } else if (behavior === "clear-questions") ctx.questions = {};
    else if (["skip", "skip-many"].includes(behavior)) {
      ctx.skip(Array.from({ length: behavior === "skip-many" ? ctx.states.length : 1 }, () => cached));
    } else if (behavior === "budget") ctx.maxLen = 48;
    else if (behavior === "widen") {
      const criteria = (ctx.questions.route as any).criteria;
      for (let i = 0; i < 8; i++) criteria[`opt${String(i).padStart(2, "0")}`] = "d".repeat(20);
    }
    events.push({ phase: "start", states: clone(ctx.states), questions: Object.keys(ctx.questions) });
  };
  const onPredictEnd = (ctx: PredictContext) => {
    events.push({ phase: "end", results: ctx.results?.length ?? null, error: ctx.error !== null });
    const rows = ctx.results as any[] | null;
    if (rows === null) return;
    if (behavior === "reverse-results") rows.reverse();
    else if (behavior === "clone-results") ctx.results = clone(rows);
    else if (behavior === "shorten-results") rows.pop();
    else if (["remove-caller-all", "remove-caller-some", "temporary-remove-all", "temporary-remove-some"].includes(behavior)) {
      const qid = behavior.startsWith("temporary") ? "temporary" : "route";
      for (const row of behavior.endsWith("all") ? rows : rows.slice(0, 1)) delete row.answers[qid];
    } else if (behavior === "annotate") {
      for (const row of rows) for (const answer of Object.values(row.answers) as any[]) {
        answer.reliability = { note: "observer" };
        answer.action.note = "observer";
      }
    } else if (behavior === "usage-fields") {
      rows.forEach((row, index) => Object.assign(row.usage, {
        extra: index + 1, flag: true, details: { [String(index)]: index }, label: String(index), output_tokens: 9,
      }));
    } else if (behavior === "edit") {
      const { field, qid } = testCase;
      for (const row of rows) {
        const answer = row.answers[qid];
        if (field === "type") Object.assign(answer, { type: "score", score: 0.5, legend: { "0": "low", "1": "high" } });
        else if (field === "choice") answer[field] = "edited";
        else if (field === "legend" || field === "probabilities") {
          answer[field][Object.keys(answer[field])[0]] = field === "legend" ? "edited" : 0.1234;
        } else answer[field] = 0.1234;
      }
    }
  };
  const hooks = behavior === "stability" ? [new OptionStabilityHook({
    accept: null, escalate: null, probes: "reorder", variants: ["reversed"], seed: "long-fixture",
  })] : [];
  return { hooks, onPredictStart, onPredictEnd };
}

function diagnostic(text: string): unknown {
  const normalized = text.replaceAll("predictLong", "predict_long").replaceAll("predictBatch", "predict_batch")
    .replaceAll("maxLen", "max_len").replaceAll("headMaxLen", "head_max_len");
  // Diagnostic spelling is language-specific; compare its category and concrete
  // parameters, not camelCase versus snake_case or the suggested next step's prose.
  if (normalized.includes("after the start hooks ran")) {
    return { kind: "budget", values: normalized.match(/\d+/g)?.map(Number) };
  }
  const missing = normalized.match(/answer ['"](.*?)['"] is missing from (\d+) of (\d+) windows/);
  if (missing) return { kind: "missing-answer", qid: missing[1], missing: Number(missing[2]), total: Number(missing[3]) };
  const capPython = normalized.match(/window=(\d+) is wider than the (\d+) state tokens.*max_len=(\d+)/);
  const capDefault = normalized.match(/leave only (\d+) of max_len=(\d+).*capped (\d+) -> (\d+)/);
  const capTS = normalized.match(/questions leave (\d+) state tokens inside max_len=(\d+); capping window (\d+) -> (\d+)/);
  if (capPython) return { kind: "window-cap", requested: +capPython[1], room: +capPython[2], maxLen: +capPython[3], effective: +capPython[2] };
  if (capDefault) return { kind: "window-cap", requested: +capDefault[3], room: +capDefault[1], maxLen: +capDefault[2], effective: +capDefault[4] };
  if (capTS) return { kind: "window-cap", requested: +capTS[3], room: +capTS[1], maxLen: +capTS[2], effective: +capTS[4] };
  const stridePython = normalized.match(/stride=(\d+).*window was reduced to (\d+).*stride=(\d+) instead/);
  const strideTS = normalized.match(/window was reduced to (\d+); adjusting stride (\d+) -> (\d+)/);
  if (stridePython) return { kind: "stride", before: +stridePython[1], window: +stridePython[2], after: +stridePython[3] };
  if (strideTS) return { kind: "stride", before: +strideTS[2], window: +strideTS[1], after: +strideTS[3] };
  if (normalized.includes("a hook answered the state before it was scanned, so no window decided the result")) {
    return { kind: "skip-unattributed" };
  }
  return normalized;
}

function sameContract(actual: any, expected: any, path = "result") {
  // Python uses float32 ONNX outputs; JS computes softmax in double precision.
  // Public values are rounded to four decimals. Nothing structural is relaxed.
  if (typeof expected === "number" && !Number.isInteger(expected)) {
    expect(typeof actual, path).toBe("number");
    expect(Math.abs(actual - expected), path).toBeLessThanOrEqual(0.00010001);
  } else if (Array.isArray(expected)) {
    expect(Array.isArray(actual), path).toBe(true);
    expect(actual.length, path).toBe(expected.length);
    expected.forEach((value, index) => sameContract(actual[index], value, `${path}[${index}]`));
  } else if (expected !== null && typeof expected === "object") {
    expect(actual, path).not.toBeNull();
    expect(Object.keys(actual).sort(), path).toEqual(Object.keys(expected).sort());
    for (const key of Object.keys(expected)) sameContract(actual[key], expected[key], `${path}.${key}`);
  } else if (typeof expected === "string") {
    if (path.endsWith(".error") || path.includes(".warnings[")) {
      expect(diagnostic(actual), path).toEqual(diagnostic(expected));
    } else {
      // The published TS model identifier is unchanged by adding predictLong.
      const want = path.endsWith(".model") && expected === "laya-rl-agent-onnx" ? "laya-rl-agent" : expected;
      expect(actual, path).toBe(want);
    }
  } else {
    expect(actual, path).toBe(expected);
  }
}

describe("predictLong Python ONNX oracle", () => {
  it("records the approved clean Python reference and method", () => {
    expect(fixtures.reference.commit).toBe("118d361a774c9a28cd02a78d6cf4d2af0614f422");
    expect(fixtures.reference.modified_reference_files).toEqual([]);
    expect(fixtures.reference.method).toBe("laya.onnx_agent.ONNXAgent.predict_long");
  });

  for (const testCase of fixtures.cases) it(testCase.name, async () => {
    const { agent, forwards } = setup(testCase);
    const events: unknown[] = [];
    const cached = { model: "cache", answers: { cached: { type: "noul", noul: 0.8,
      confidence: 0.8, answer_confidence: 0.8, action: { act_probability: 0.5 } } }, usage: { input_tokens: 0, output_tokens: 0 } };
    const initialCache = clone(cached);
    const warnings: string[] = [];
    const warningSpy = vi.spyOn(console, "warn").mockImplementation((message) => warnings.push(String(message)));
    const actual: any = {};
    try {
      actual.result = await agent.predictLong(clone(testCase.state), clone(testCase.questions), {
        ...testCase.options, ...hooksFor(testCase, events, cached),
      });
    } catch (error) {
      actual.error = (error as Error).message;
    } finally {
      warningSpy.mockRestore();
    }
    actual.warnings = warnings;
    actual.forwards = forwards;
    actual.events = events;
    actual.cache_unchanged = JSON.stringify(cached) === JSON.stringify(initialCache);
    if (testCase.name === "short-skip") {
      // The approved TS contract explicitly warns on every skipped scan, including
      // this short path where Python v0.4.18 returns windows=0 without a warning.
      expect(warnings).toEqual(["laya: predictLong: a hook answered the state before it was scanned, so no window decided the result"]);
      actual.warnings = [];
    }
    sameContract(actual, testCase.expected, testCase.name);
  });

  it("the oracle actually exercises post-inference rejection and real truncation", () => {
    for (const name of ["budget-after-forward", "short-budget-after-forward", "in-place-question-budget"]) {
      const outcome = fixtures.cases.find((testCase: any) => testCase.name === name).expected;
      expect(outcome.error).toContain("after the start hooks ran");
      expect(outcome.forwards.length).toBeGreaterThan(0);
      expect(outcome.events.at(-1)).toMatchObject({ phase: "end", error: false });
    }
    const drift = fixtures.cases.find((testCase: any) => testCase.name === "decode-expansion-truncates").expected.result;
    expect(drift.usage.state_tokens_dropped).toBeGreaterThan(0);
    expect(drift.usage.truncated).toBeGreaterThan(0);
    const stability = fixtures.cases.find((testCase: any) => testCase.name === "stability-long").expected.result;
    expect(stability.answers.route.reliability.probes).toEqual(["reorder"]);
    expect(stability.answers.route.window).toBeDefined();
    const shared = fixtures.cases.find((testCase: any) => testCase.name === "shared-answer").expected.result;
    expect(shared.answers.route.window).toBeUndefined();
  });
});