Cotton code
48 lines · 1.8 KB · TypeScriptRaw
/** * The classifier's fake model (src/classify.ts `Embedder`): each of a choice * column's exemplar phrases is its choice's own axis, a record's words are the * vector a case set for them (`near`: a score against one choice and nothing * against any other), and any other words are noise. It counts what it was * asked, and fails on demand. */import type { Embedder } from "../src/classify.ts";/** The choice column a fake embeds for: its choices and their exemplar phrases. */export interface FakeColumn {  choices: string[];  examples: Record<string, string[]>;}export class Fake implements Embedder {  readonly asked: string[] = [];  fail = false;  readonly column: FakeColumn;  readonly words: Record<string, number[]>;  constructor(column: FakeColumn, words: Record<string, number[]>) {    this.column = column;    this.words = words;  }  /** The axis of choice `i` among `column`'s, one more for noise. */  static axis(column: FakeColumn, i: number): number[] {    return Array.from({ length: column.choices.length + 1 }, (_, d) => (d === i ? 1 : 0));  }  /** Words that score `score` against `choice`'s phrases and nothing against any other choice's. */  static near(column: FakeColumn, choice: string, score: number): number[] {    const v = Fake.axis(column, column.choices.length).map((x) => x * Math.sqrt(1 - score * score));    v[column.choices.indexOf(choice)] = score;    return v;  }  async embed(texts: string[]): Promise<number[][]> {    this.asked.push(...texts);    if (this.fail) throw new Error("Workers AI is down (invented)");    return texts.map((t) => {      if (this.words[t]) return this.words[t]!;      const choice = this.column.choices.find((c) => this.column.examples[c]?.includes(t));      return Fake.axis(this.column, choice ? this.column.choices.indexOf(choice) : this.column.choices.length);    });  }}