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.

test(go): PredictLong unit, golden and real-graph tests

Adeshina Lasisi550f8cda3f55
diff --git a/laya-go/agent/long_golden_test.go b/laya-go/agent/long_golden_test.go
new file mode 100644
index 00000000..1f85b718
--- /dev/null
+++ b/laya-go/agent/long_golden_test.go
@@ -0,0 +1,206 @@
+package agent
+
+import (
+ "encoding/json"
+ "os"
+ "reflect"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/NandhaKishorM/laya/laya-go/internal/fixtures"
+ "github.com/NandhaKishorM/laya/laya-go/schema"
+ "github.com/NandhaKishorM/laya/laya-go/sequence"
+ "github.com/NandhaKishorM/laya/laya-go/tokenizer"
+)
+
+var (
+ tokMu sync.Mutex
+ tokens = map[string]*tokenizer.Tokenizer{}
+)
+
+// realTokenizer loads a shipped checkpoint's tokenizer once. CI fails the run on any skip, so a
+// missing checkpoint cannot pass as green.
+func realTokenizer(tb testing.TB, name string) *tokenizer.Tokenizer {
+ tb.Helper()
+ root := fixtures.Checkpoints()
+ if root == "" {
+ tb.Skip("set LAYA_CHECKPOINTS to a directory holding the english and multilingual checkpoints")
+ }
+ tokMu.Lock()
+ defer tokMu.Unlock()
+ if tok, ok := tokens[name]; ok {
+ return tok
+ }
+ tok, err := tokenizer.LoadFS(os.DirFS(root), name)
+ if err != nil {
+ tb.Fatalf("load the %s tokenizer: %v", name, err)
+ }
+ tokens[name] = tok
+ return tok
+}
+
+// longCases are the recorded cases of predict_long.json for one checkpoint.
+func longCases(t *testing.T, name string) (entry fixtures.Object, cases []fixtures.Object) {
+ t.Helper()
+ golden := fixtures.Load(t, "predict_long.json")
+ entry = fixtures.Obj(t, fixtures.Field(t, fixtures.Obj(t, golden.Must("by")), name))
+ for _, c := range fixtures.List(t, entry.Must("cases")) {
+ cases = append(cases, fixtures.Obj(t, c))
+ }
+ return entry, cases
+}
+
+func optionalInt(t *testing.T, v any) int {
+ t.Helper()
+ if v == nil {
+ return 0
+ }
+ return fixtures.Int(t, v)
+}
+
+func caseQuestions(t *testing.T, rec fixtures.Object) schema.Questions {
+ t.Helper()
+ qs, err := schema.ParseQuestions(fixtures.Marshal(t, rec.Must("questions")))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return qs
+}
+
+func planOf(t *testing.T, tok *tokenizer.Tokenizer, entry, rec fixtures.Object) sequence.WindowPlan {
+ t.Helper()
+ qs := caseQuestions(t, rec)
+ questions := make([]schema.Question, qs.Len())
+ for i := range questions {
+ questions[i] = qs.At(i).Question
+ }
+ b := sequence.Budget{MaxLen: fixtures.Int(t, entry.Must("max_len")), HeadMaxLen: fixtures.Int(t, entry.Must("head_max_len"))}
+ plan, err := sequence.PlanWindows(tok, questions, b, sequence.WindowRequest{
+ Window: optionalInt(t, rec.Must("window")), Stride: optionalInt(t, rec.Must("stride"))})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return plan
+}
+
+// TestPredictLongSplitGolden holds the scan's windows to the ones predict_long handed to
+// predict_batch: the state tokenization, the window offsets and the per-window decode together.
+func TestPredictLongSplitGolden(t *testing.T) {
+ scans := 0
+ for _, name := range []string{"english", "multilingual"} {
+ tok := realTokenizer(t, name)
+ entry, cases := longCases(t, name)
+ states, splits := fixtures.Obj(t, entry.Must("states")), fixtures.Obj(t, entry.Must("splits"))
+ for _, rec := range cases {
+ if rec.Must("split_key") == nil {
+ continue
+ }
+ scans++
+ id := name + "/" + fixtures.Str(t, rec.Must("case"))
+ t.Run(id, func(t *testing.T) {
+ plan := planOf(t, tok, entry, rec)
+ if want := fixtures.Int(t, rec.Must("budget")); plan.Window != want {
+ t.Errorf("window = %d, want %d", plan.Window, want)
+ }
+ st, err := sequence.EncodeState(tok, fixtures.Str(t, fixtures.Field(t, states, fixtures.Str(t, rec.Must("state_key")))))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := fixtures.Int(t, rec.Must("state_tokens")); len(st.IDs) != want {
+ t.Fatalf("state tokens = %d, want %d", len(st.IDs), want)
+ }
+ texts, starts := splitWindows(tok, st.IDs, plan)
+ if want := fixtures.Strings(t, fixtures.Field(t, splits, fixtures.Str(t, rec.Must("split_key")))); !reflect.DeepEqual(texts, want) {
+ t.Errorf("%d windows, want %d; they differ", len(texts), len(want))
+ }
+ var want []int
+ for _, s := range fixtures.Ints(t, rec.Must("starts")) {
+ want = append(want, int(s))
+ }
+ if !reflect.DeepEqual(starts, want) {
+ t.Errorf("starts = %v, want %v", starts, want)
+ }
+ // The recorder's stub calls window_budget a second time inside predict_batch, so
+ // it records each warning twice; predict_long itself raises it once.
+ recorded := fixtures.Strings(t, rec.Must("warnings"))
+ if want := append(slices.Clone(plan.Warnings), plan.Warnings...); len(want) != len(recorded) || len(want) > 0 && !slices.Equal(want, recorded) {
+ t.Errorf("warnings = %q, recorded %q", plan.Warnings, recorded)
+ }
+ })
+ }
+ }
+ if scans < 20 {
+ t.Errorf("only %d scanned cases", scans)
+ }
+}
+
+// TestPredictLongAggregateGolden drives the aggregation with the per-window results the Python
+// stub produced, where a tie or a chosen deciding window can be constructed. The answers are
+// compared as bytes, and so is usage, less keys a Prediction has no field for (the stub's
+// "backend"). Python's own scan mutates the winning answers it recorded in per_window, so those
+// carry a window the aggregation must replace, not trust.
+func TestPredictLongAggregateGolden(t *testing.T) {
+ ties, windows := 0, 0
+ for _, name := range []string{"english", "multilingual"} {
+ _, cases := longCases(t, name)
+ for _, rec := range cases {
+ if rec.Must("per_window") == nil {
+ continue
+ }
+ id := fixtures.Str(t, rec.Must("case"))
+ if strings.Contains(id, "tie") {
+ ties++
+ }
+ t.Run(name+"/"+id, func(t *testing.T) {
+ var results []schema.Prediction
+ for _, w := range fixtures.List(t, rec.Must("per_window")) {
+ var p schema.Prediction
+ if err := json.Unmarshal(fixtures.Marshal(t, w), &p); err != nil {
+ t.Fatal(err)
+ }
+ results = append(results, p)
+ }
+ var starts []int
+ for _, s := range fixtures.Ints(t, rec.Must("starts")) {
+ starts = append(starts, int(s))
+ }
+ got := aggregate(caseQuestions(t, rec), results, starts,
+ fixtures.Int(t, rec.Must("budget")), fixtures.Int(t, rec.Must("state_tokens")))
+ gotJSON, err := json.Marshal(got)
+ if err != nil {
+ t.Fatal(err)
+ }
+ windows += len(results)
+
+ want := fixtures.Obj(t, rec.Must("result"))
+ usage := fixtures.Obj(t, want.Must("usage"))
+ var kept fixtures.Object
+ for _, m := range usage {
+ if m.Key != "backend" {
+ kept = append(kept, m)
+ }
+ }
+ wantJSON := string(fixtures.Marshal(t, fixtures.Object{
+ {Key: "model", Value: want.Must("model")}, {Key: "answers", Value: want.Must("answers")}, {Key: "usage", Value: kept}}))
+ if g := compact(t, string(gotJSON)); g != compact(t, wantJSON) {
+ t.Errorf("result\n got %s\nwant %s", g, compact(t, wantJSON))
+ }
+ })
+ }
+ }
+ if ties < 4 || windows < 40 {
+ t.Errorf("the cases reach %d ties and %d windows", ties, windows)
+ }
+}
+
+// compact re-encodes JSON text without whitespace, keeping object order and number spelling.
+func compact(t *testing.T, s string) string {
+ t.Helper()
+ v, err := fixtures.Parse([]byte(s))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(fixtures.Marshal(t, v))
+}
diff --git a/laya-go/agent/long_internal_test.go b/laya-go/agent/long_internal_test.go
new file mode 100644
index 00000000..3ecfda0f
--- /dev/null
+++ b/laya-go/agent/long_internal_test.go
@@ -0,0 +1,20 @@
+package agent
+
+import (
+ "testing"
+
+ "github.com/NandhaKishorM/laya/laya-go/schema"
+)
+
+func TestMergeCollapsedLaterWindowReplaces(t *testing.T) {
+ r := func(id string, total int) schema.CollapsedQuestion {
+ return schema.CollapsedQuestion{ID: id, CollapsedOptions: schema.CollapsedOptions{Total: total}}
+ }
+ var all schema.CollapsedQuestions
+ for _, c := range []schema.CollapsedQuestion{r("a", 1), r("b", 2), r("a", 3)} {
+ all = mergeCollapsed(all, c)
+ }
+ if len(all) != 2 || all[0].ID != "a" || all[0].Total != 3 || all[1].ID != "b" || all[1].Total != 2 {
+ t.Errorf("merged = %+v, want a replaced in place by its later report, b kept", all)
+ }
+}
diff --git a/laya-go/agent/long_test.go b/laya-go/agent/long_test.go
new file mode 100644
index 00000000..05c1b5db
--- /dev/null
+++ b/laya-go/agent/long_test.go
@@ -0,0 +1,297 @@
+package agent_test
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/NandhaKishorM/laya/laya-go/agent"
+ "github.com/NandhaKishorM/laya/laya-go/internal/fixtures"
+ "github.com/NandhaKishorM/laya/laya-go/schema"
+ "github.com/NandhaKishorM/laya/laya-go/sequence"
+)
+
+const longConfig = `{"max_len": 128, "head_max_len": 64}`
+
+// longState is a state of n bytes, which the toy tokenizer reads as about n tokens.
+func longState(n int) string { return strings.Repeat("abcdefghij", n/10+1)[:n] }
+
+func TestPredictLongScansAndNamesTheWindow(t *testing.T) {
+ a, s := open(t, longConfig)
+ got, err := a.PredictLong(context.Background(), longState(900), questions(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ u := got.Usage
+ if u.Windows < 3 || len(s.seen()) != 1 || s.seen()[0].Rows != u.Windows*3 {
+ t.Fatalf("windows = %d, runs = %+v: want one run of every window for each of 3 questions", u.Windows, s.seen())
+ }
+ if u.OutputTokens != 0 || u.TruncatedQuestions == nil {
+ t.Errorf("usage = %+v", u)
+ }
+ for _, an := range got.Answers {
+ w := an.Answer.Base().Window
+ if w == nil || w.Count != u.Windows || w.Index < 0 || w.Index >= w.Count || w.TokenEnd <= w.TokenStart || w.TokenEnd > 900 {
+ t.Errorf("%s: window = %+v", an.ID, w)
+ }
+ }
+ b, err := json.Marshal(got)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var back schema.Prediction
+ if err := json.Unmarshal(b, &back); err != nil {
+ t.Fatalf("%v in %s", err, b)
+ }
+ if !reflect.DeepEqual(back.Usage.Windows, u.Windows) || back.Usage.TruncatedWindows != u.TruncatedWindows {
+ t.Errorf("round trip lost the window count: %+v vs %+v", back.Usage, u)
+ }
+}
+
+func TestPredictLongFittingStateIsPlainPredict(t *testing.T) {
+ a, _ := open(t, longConfig)
+ ctx := context.Background()
+ long, err := a.PredictLong(ctx, "short state", questions(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ plain, err := a.Predict(ctx, "short state", questions(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if long.Usage.Windows != 1 {
+ t.Errorf("windows = %d, want 1", long.Usage.Windows)
+ }
+ long.Usage.Windows = 0
+ if !reflect.DeepEqual(long.Prediction, plain) {
+ t.Errorf("a state that fits one window was answered differently:\n%+v\n%+v", long.Prediction, plain)
+ }
+ b, _ := json.Marshal(long)
+ if strings.Contains(string(b), `"window":`) || !strings.Contains(string(b), `"truncated":false`) {
+ t.Errorf("single-window result = %s", b)
+ }
+}
+
+func TestPredictLongBatchSizeBoundsTheRun(t *testing.T) {
+ a, s := open(t, longConfig)
+ got, err := a.PredictLong(context.Background(), longState(900), questions(t), agent.WithBatchSize(2), agent.WithSortByLength(true))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := (got.Usage.Windows + 1) / 2
+ if runs := s.seen(); len(runs) != want || runs[0].Rows != 6 {
+ t.Errorf("%d runs of %d windows, want %d runs of 2", len(runs), got.Usage.Windows, want)
+ }
+}
+
+func TestPredictLongExplicitWindowAndStride(t *testing.T) {
+ a, _ := open(t, longConfig)
+ got, err := a.PredictLong(context.Background(), longState(400), questions(t), agent.WithWindow(50), agent.WithStride(25))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Usage.Windows != 15 || len(got.Warnings) != 0 {
+ t.Errorf("windows = %d, warnings = %q; want 15 and none", got.Usage.Windows, got.Warnings)
+ }
+ // A window wider than the room is cut, and the caller is told.
+ got, err = a.PredictLong(context.Background(), longState(400), questions(t), agent.WithWindow(5000))
+ if err != nil || len(got.Warnings) != 1 || !strings.Contains(got.Warnings[0], "window=5000 is wider than") {
+ t.Errorf("warnings = %q, %v", got.Warnings, err)
+ }
+ // An explicit window decides whether a state fits, not the room.
+ got, err = a.PredictLong(context.Background(), longState(60), questions(t), agent.WithWindow(30))
+ if err != nil || got.Usage.Windows < 2 {
+ t.Errorf("a state wider than the explicit window was not scanned: windows = %d, %v", got.Usage.Windows, err)
+ }
+}
+
+func TestPredictLongRefusals(t *testing.T) {
+ a, s := open(t, longConfig)
+ ctx := context.Background()
+ if _, err := a.PredictLong(ctx, nil, questions(t)); !errors.Is(err, sequence.ErrUnsupportedState) {
+ t.Errorf("nil state: %v", err)
+ }
+ if _, err := a.PredictLong(ctx, longState(900), questions(t), agent.WithWindow(10), agent.WithStride(500)); !errors.Is(err, sequence.ErrStrideGap) {
+ t.Errorf("stride gap: %v", err)
+ }
+ tight, ts := open(t, `{"max_len": 8, "head_max_len": 8}`)
+ if _, err := tight.PredictLong(ctx, longState(900), questions(t)); !errors.Is(err, sequence.ErrNoRoom) || len(ts.seen()) != 0 {
+ t.Errorf("no room: %v", err)
+ }
+ cctx, cancel := context.WithCancel(ctx)
+ cancel()
+ if _, err := a.PredictLong(cctx, longState(900), questions(t)); !errors.Is(err, context.Canceled) {
+ t.Errorf("cancelled: %v", err)
+ }
+ if n := len(s.seen()); n != 0 {
+ t.Errorf("%d runs after refusals", n)
+ }
+ a.Close()
+ if _, err := a.PredictLong(ctx, "x", questions(t)); !errors.Is(err, agent.ErrClosed) {
+ t.Errorf("closed: %v", err)
+ }
+}
+
+func TestPredictLongWithoutQuestions(t *testing.T) {
+ a, s := open(t, longConfig)
+ got, err := a.PredictLong(context.Background(), longState(900), schema.Questions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(got.Answers) != 0 || got.Usage.Windows < 3 || len(s.seen()) != 0 {
+ t.Errorf("answers = %v, windows = %d, runs = %d", got.Answers, got.Usage.Windows, len(s.seen()))
+ }
+}
+
+// TestPredictLongGoldenCases runs the recorded cases through the whole path on the shipped
+// checkpoints: the windows are the ones the reference scanned, they are batched as it batched
+// them, and the window each answer names is the one an independent reading of the per-window
+// answers picks.
+func TestPredictLongGoldenCases(t *testing.T) {
+ root := fixtures.Checkpoints()
+ if root == "" {
+ t.Skip("set LAYA_CHECKPOINTS to a directory holding the english and multilingual checkpoints")
+ }
+ golden := fixtures.Load(t, "predict_long.json")
+ by := fixtures.Obj(t, golden.Must("by"))
+ scanned := 0
+ for _, name := range []string{"english", "multilingual"} {
+ entry := fixtures.Obj(t, fixtures.Field(t, by, name))
+ states, splits := fixtures.Obj(t, entry.Must("states")), fixtures.Obj(t, entry.Must("splits"))
+ for _, c := range fixtures.List(t, entry.Must("cases")) {
+ rec := fixtures.Obj(t, c)
+ t.Run(name+"/"+fixtures.Str(t, rec.Must("case")), func(t *testing.T) {
+ sess := &fakeSession{}
+ a, err := agent.Open(os.DirFS(filepath.Join(root, name)), sess)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer a.Close()
+ qs, err := schema.ParseQuestions(fixtures.Marshal(t, rec.Must("questions")))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var opts []agent.CallOption
+ if v := rec.Must("window"); v != nil {
+ opts = append(opts, agent.WithWindow(fixtures.Int(t, v)))
+ }
+ if v := rec.Must("stride"); v != nil {
+ opts = append(opts, agent.WithStride(fixtures.Int(t, v)))
+ }
+ if v := rec.Must("batch_size"); v != nil {
+ opts = append(opts, agent.WithBatchSize(fixtures.Int(t, v)))
+ }
+ state := fixtures.Str(t, fixtures.Field(t, states, fixtures.Str(t, rec.Must("state_key"))))
+ got, err := a.PredictLong(context.Background(), state, qs, opts...)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rec.Must("split_key") == nil {
+ if got.Usage.Windows != 1 || len(sess.seen()) != 1 || sess.seen()[0].Rows != qs.Len() {
+ t.Errorf("fits one window: windows = %d, runs = %+v", got.Usage.Windows, sess.seen())
+ }
+ for _, an := range got.Answers {
+ if an.Answer.Base().Window != nil {
+ t.Errorf("%s names a window", an.ID)
+ }
+ }
+ return
+ }
+ scanned++
+ texts := fixtures.Strings(t, fixtures.Field(t, splits, fixtures.Str(t, rec.Must("split_key"))))
+ starts := fixtures.Ints(t, rec.Must("starts"))
+ if got.Usage.Windows != len(texts) {
+ t.Fatalf("windows = %d, want %d", got.Usage.Windows, len(texts))
+ }
+ // Batching: one run unless a cap was recorded.
+ runs, per := sess.seen(), len(texts)
+ if v := rec.Must("batch_cap_used"); v != nil {
+ per = fixtures.Int(t, v)
+ }
+ if want := (len(texts) + per - 1) / per; len(runs) != want {
+ t.Errorf("%d runs, want %d of up to %d windows", len(runs), want, per)
+ }
+ // The reference reading of the same windows, scored by the same session.
+ states := make([]any, len(texts))
+ for i := range texts {
+ states[i] = texts[i]
+ }
+ ref, err := a.PredictBatch(context.Background(), states, qs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for r, an := range got.Answers {
+ best, bestKey := 0, key(ref[0].Answers[r].Answer)
+ for j := range ref {
+ if k := key(ref[j].Answers[r].Answer); k > bestKey {
+ best, bestKey = j, k
+ }
+ }
+ w := an.Answer.Base().Window
+ if w == nil || w.Index != best || w.Count != len(texts) || w.TokenStart != int(starts[best]) ||
+ w.TokenEnd != min(int(starts[best])+fixtures.Int(t, rec.Must("budget")), fixtures.Int(t, rec.Must("state_tokens"))) {
+ t.Errorf("%s: window = %+v, want index %d of %d", an.ID, w, best, len(texts))
+ }
+ plain, _ := json.Marshal(ref[best].Answers[r].Answer)
+ decided := an.Answer
+ again, _ := json.Marshal(withoutWindow(decided))
+ if string(plain) != string(again) {
+ t.Errorf("%s: answer\n got %s\nwant %s", an.ID, again, plain)
+ }
+ }
+ want := fixtures.Strings(t, rec.Must("warnings"))
+ if len(want) != 2*len(got.Warnings) {
+ t.Errorf("warnings = %q, recorded %q", got.Warnings, want)
+ }
+ })
+ }
+ }
+ if scanned < 20 {
+ t.Errorf("%d scanned cases", scanned)
+ }
+}
+
+func key(a schema.Answer) float64 {
+ if n, ok := a.(*schema.NoulAnswer); ok {
+ return n.Noul
+ }
+ return a.Base().AnswerConfidence
+}
+
+// withoutWindow is a copy of a that carries no window.
+func withoutWindow(a schema.Answer) schema.Answer {
+ switch x := a.(type) {
+ case *schema.ChoiceAnswer:
+ c := *x
+ c.Window = nil
+ return &c
+ case *schema.ScoreAnswer:
+ c := *x
+ c.Window = nil
+ return &c
+ case *schema.NoulAnswer:
+ c := *x
+ c.Window = nil
+ return &c
+ }
+ return a
+}
+
+func TestPredictLongImplicitBatchCapBoundsTheRun(t *testing.T) {
+ a, s := open(t, longConfig)
+ got, err := a.PredictLong(context.Background(), longState(900), questions(t), agent.WithWindow(10))
+ if err != nil {
+ t.Fatal(err)
+ }
+ n := got.Usage.Windows
+ capW, _ := sequence.BatchCap(n, 10, 64, 0)
+ runs := s.seen()
+ if capW <= 0 || capW >= n || len(runs) < 2 || runs[0].Rows != capW*3 {
+ t.Errorf("windows = %d, cap = %d, runs = %+v: want runs of %d windows", n, capW, runs, capW)
+ }
+}
diff --git a/laya-go/onnx/predictlong_test.go b/laya-go/onnx/predictlong_test.go
new file mode 100644
index 00000000..141ca7c4
--- /dev/null
+++ b/laya-go/onnx/predictlong_test.go
@@ -0,0 +1,167 @@
+//go:build cgo
+
+package onnx
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/NandhaKishorM/laya/laya-go/agent"
+ "github.com/NandhaKishorM/laya/laya-go/schema"
+ "github.com/NandhaKishorM/laya/laya-go/sequence"
+ "github.com/NandhaKishorM/laya/laya-go/tokenizer"
+)
+
+// longDocument is a support thread of about n sentences with one localized signal in the middle,
+// which is what a scan has to find and an averaged reading would lose.
+func longDocument(n int) string {
+ var b strings.Builder
+ for i := 0; i < n; i++ {
+ if i == n/2 {
+ b.WriteString("Customer: this is the third time I ask, I am furious and I demand a refund of the duplicate charge today. ")
+ continue
+ }
+ fmt.Fprintf(&b, "Agent: note %d, the delivery window for order %d was confirmed and the parcel left the depot on schedule. ", i, 7000+i)
+ }
+ return b.String()
+}
+
+// TestPredictLongThroughTheGraph runs a scan on the real graph. A state that fits is answered as
+// Predict answers it. A long one is split here, independently of PredictLong, and each window is
+// scored by PredictBatch; the answer and window PredictLong names must be the ones that reading
+// picks, and a window cap must not move them past the tolerance a batch shape allows.
+func TestPredictLongThroughTheGraph(t *testing.T) {
+ p := need(t)
+ a := openAgent(t, p, sharedSession(t))
+ ctx := context.Background()
+ qs := singles(t)[0].qs
+
+ short := "Customer: I was charged twice for one order and want my money back."
+ plain, err := a.Predict(ctx, short, qs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fit, err := a.PredictLong(ctx, short, qs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fit.Usage.Windows != 1 {
+ t.Errorf("a state that fits reported %d windows", fit.Usage.Windows)
+ }
+ fit.Usage.Windows = 0
+ if x, y := mustJSON(t, fit.Prediction), mustJSON(t, plain); x != y {
+ t.Errorf("a state that fits was answered differently:\n%s\n%s", x, y)
+ }
+
+ tok, err := tokenizer.LoadFS(os.DirFS(p.checkpoints), "multilingual")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfg := a.Config()
+ questions := make([]schema.Question, qs.Len())
+ for i := range questions {
+ questions[i] = qs.At(i).Question
+ }
+ plan, err := sequence.PlanWindows(tok, questions, sequence.Budget{MaxLen: cfg.MaxLen, HeadMaxLen: cfg.HeadMaxLen}, sequence.WindowRequest{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ doc := longDocument(160)
+ st, err := sequence.EncodeState(tok, doc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var texts []any
+ var starts []int
+ for i := 0; i < len(st.IDs); i += plan.Stride {
+ end := min(i+plan.Window, len(st.IDs))
+ texts, starts = append(texts, tok.Decode(st.IDs[i:end], false)), append(starts, i)
+ if end >= len(st.IDs) {
+ break
+ }
+ }
+ if len(texts) < 3 {
+ t.Fatalf("the document made %d windows; it must exceed %d tokens by more", len(texts), plan.Window)
+ }
+ scored, err := a.PredictBatch(ctx, texts, qs)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ long, err := a.PredictLong(ctx, doc, qs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if long.Usage.Windows != len(texts) || long.Usage.OutputTokens != 0 {
+ t.Fatalf("usage = %+v, want %d windows", long.Usage, len(texts))
+ }
+ for r, an := range long.Answers {
+ best, bestKey := 0, deciding(scored[0].Answers[r].Answer)
+ for j := range scored {
+ if k := deciding(scored[j].Answers[r].Answer); k > bestKey {
+ best, bestKey = j, k
+ }
+ }
+ w := an.Answer.Base().Window
+ if w == nil || w.Index != best || w.Count != len(texts) || w.TokenStart != starts[best] || w.TokenEnd != min(starts[best]+plan.Window, len(st.IDs)) {
+ t.Errorf("%s: window = %+v, want index %d of %d", an.ID, w, best, len(texts))
+ continue
+ }
+ if g, want := mustJSON(t, strippedWindow(an.Answer)), mustJSON(t, scored[best].Answers[r].Answer); g != want {
+ t.Errorf("%s: answer\n got %s\nwant %s", an.ID, g, want)
+ }
+ t.Logf("%s decided by window %d of %d, %s", an.ID, w.Index, w.Count, mustJSON(t, an.Answer))
+ }
+
+ capped, err := a.PredictLong(ctx, doc, qs, agent.WithBatchSize(1))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for r, an := range long.Answers {
+ other := capped.Answers[r].Answer
+ if an.Answer.Base().Window.Index != other.Base().Window.Index {
+ t.Errorf("%s: a window cap moved the deciding window %d -> %d", an.ID, an.Answer.Base().Window.Index, other.Base().Window.Index)
+ }
+ if d := deciding(an.Answer) - deciding(other); d > 2e-4 || d < -2e-4 {
+ t.Errorf("%s: a window cap moved the deciding value by %.2e", an.ID, d)
+ }
+ }
+}
+
+func deciding(a schema.Answer) float64 {
+ if n, ok := a.(*schema.NoulAnswer); ok {
+ return n.Noul
+ }
+ return a.Base().AnswerConfidence
+}
+
+func strippedWindow(a schema.Answer) schema.Answer {
+ switch x := a.(type) {
+ case *schema.ChoiceAnswer:
+ c := *x
+ c.Window = nil
+ return &c
+ case *schema.ScoreAnswer:
+ c := *x
+ c.Window = nil
+ return &c
+ case *schema.NoulAnswer:
+ c := *x
+ c.Window = nil
+ return &c
+ }
+ return a
+}
+
+func mustJSON(t testing.TB, v any) string {
+ t.Helper()
+ b, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}