Download web-src/src/lite.ts from sasakiy84/bibform-lite: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/sasakiy84/bibform-lite/resolve/main/web-src/src/lite.ts
- Command line
-
hf download hf://sasakiy84/bibform-lite/web-src/src/lite.ts
-
curl -L -o lite.ts https://huggingface.co/sasakiy84/bibform-lite/resolve/main/web-src/src/lite.ts
18.5 kB
| import { env, InferenceSession, Tensor } from 'onnxruntime-web/wasm'; | |
| interface Span { | |
| start: number; | |
| end: number; | |
| value: string; | |
| } | |
| interface Field extends Span { | |
| label: string; | |
| } | |
| interface Contributor extends Span { | |
| kind: 'person' | 'organization'; | |
| nameParts: Map<string, Span>; | |
| roles: string[]; | |
| } | |
| export interface TypeCandidate { | |
| type: string; | |
| score: number; | |
| } | |
| export interface Prediction { | |
| fields: Field[]; | |
| contributors: Contributor[]; | |
| candidates: TypeCandidate[]; | |
| } | |
| interface ModelConfig { | |
| version: 1 | 2; | |
| blend: number | null; | |
| characterVocabulary: Map<string, number>; | |
| outer: string[]; | |
| names: string[]; | |
| fields: string[]; | |
| roles: string[]; | |
| exportTypes: string[]; | |
| ngrams: number[]; | |
| buckets: number; | |
| states: number[][]; | |
| transitions: number[][]; | |
| start: number[]; | |
| end: number[]; | |
| } | |
| function strings(value: unknown): string[] { | |
| if (!Array.isArray(value) || !value.every((entry: unknown) => typeof entry === 'string')) { | |
| throw new Error('Invalid model labels'); | |
| } | |
| return value; | |
| } | |
| function numbers(value: unknown): number[] { | |
| if (!Array.isArray(value) || !value.every((entry: unknown) => typeof entry === 'number' && Number.isFinite(entry))) { | |
| throw new Error('Invalid model scores'); | |
| } | |
| return value; | |
| } | |
| function matrix(value: unknown): number[][] { | |
| if (!Array.isArray(value)) throw new Error('Invalid model matrix'); | |
| return value.map(numbers); | |
| } | |
| function parseConfig(value: unknown): ModelConfig { | |
| if (!value || typeof value !== 'object' || | |
| !('outer_labels' in value && 'name_labels' in value && 'fields' in value && 'roles' in value && | |
| 'type_labels' in value && 'export_types' in value && | |
| 'states' in value && 'transitions' in value && 'start' in value && 'end' in value)) { | |
| throw new Error('Invalid Bibform model config'); | |
| } | |
| const exportMap = value.export_types; | |
| if (!exportMap || typeof exportMap !== 'object') { | |
| throw new Error('Invalid Bibform type mapping'); | |
| } | |
| const lookup = new Map<string, unknown>(Object.entries(exportMap)); | |
| const exportTypes = strings(value.type_labels).map((label): string => { | |
| const type = lookup.get(label); | |
| if (typeof type !== 'string') throw new Error('Missing BibLaTeX type'); | |
| return type; | |
| }); | |
| const states = matrix(value.states); | |
| const transitions = matrix(value.transitions); | |
| const start = numbers(value.start); | |
| const end = numbers(value.end); | |
| const outer = strings(value.outer_labels); | |
| const names = strings(value.name_labels); | |
| const version = 'version' in value && value.version === 2 ? 2 : 1; | |
| const ngrams = version === 1 ? numbers('ngrams' in value ? value.ngrams : undefined) : []; | |
| const buckets = version === 1 && 'buckets' in value && typeof value.buckets === 'number' ? value.buckets : 1; | |
| if (!Number.isSafeInteger(buckets) || buckets < 1) throw new Error('Invalid Bibform n-gram buckets'); | |
| const blend = 'blend' in value && typeof value.blend === 'number' ? value.blend : null; | |
| const characterVocabulary = new Map<string, number>(); | |
| if (blend !== null) { | |
| if (version !== 2 || !(blend > 0 && blend < 1) || !('character_vocabulary' in value) || | |
| !value.character_vocabulary || typeof value.character_vocabulary !== 'object') { | |
| throw new Error('Invalid Bibform ensemble'); | |
| } | |
| const entries = Object.entries(value.character_vocabulary); | |
| for (const [character, id] of entries) { | |
| if (Array.from(character).length !== 1 || typeof id !== 'number' || !Number.isSafeInteger(id) || id < 2) { | |
| throw new Error('Invalid Bibform character vocabulary'); | |
| } | |
| characterVocabulary.set(character, id); | |
| } | |
| } | |
| if (!states.length || states.length >= 65536 || | |
| states.some(([outerId, nameId]) => !Number.isInteger(outerId) || !Number.isInteger(nameId) || | |
| outerId < 0 || outerId > 2 * outer.length || nameId < 0 || nameId > 2 * names.length) || | |
| transitions.length !== states.length || transitions.some((row) => row.length !== states.length) || | |
| start.length !== states.length || end.length !== states.length || | |
| ngrams.some((n) => !Number.isSafeInteger(n) || n < 1)) { | |
| throw new Error('Invalid Bibform decoder config'); | |
| } | |
| return { version, blend, characterVocabulary, outer, names, fields: strings(value.fields), roles: strings(value.roles), | |
| exportTypes, ngrams, buckets, states, transitions, start, end }; | |
| } | |
| function ngramIds(characters: string[], config: ModelConfig): BigInt64Array { | |
| const points = [1, ...characters.map((char) => (char.codePointAt(0) ?? 0) + 3), 2]; | |
| const ids = new Set<number>(); | |
| for (const size of config.ngrams) { | |
| for (let start = 0; start + size <= points.length; start++) { | |
| let hash = size * 4099; | |
| for (let index = start; index < start + size; index++) { | |
| hash = Math.imul(hash ^ points[index], 16777619); | |
| } | |
| ids.add(((hash ^ (hash >>> 16)) >>> 0) % config.buckets); | |
| } | |
| } | |
| return BigInt64Array.from(ids.size ? [...ids].sort((a, b) => a - b).map(BigInt) : [0n]); | |
| } | |
| function byteIds(characters: string[]): BigInt64Array { | |
| const output = new BigInt64Array(characters.length * 4); | |
| const encoder = new TextEncoder(); | |
| characters.forEach((char, index) => { | |
| encoder.encode(char).forEach((byte, offset) => { | |
| output[index * 4 + offset] = BigInt(byte + 1); | |
| }); | |
| }); | |
| return output; | |
| } | |
| function viterbi(outer: Float32Array, names: Float32Array, length: number, config: ModelConfig): number[] { | |
| const count = config.states.length; | |
| const outerWidth = 1 + 2 * config.outer.length; | |
| const nameWidth = 1 + 2 * config.names.length; | |
| const location = 1 + 2 * config.outer.indexOf('LOCATION'); | |
| const scoreAt = (position: number, state: number): number => { | |
| const [outerId, nameId] = config.states[state]; | |
| const outerScore = outerId === location || outerId === location + 1 | |
| ? -10000 : outer[position * outerWidth + outerId]; | |
| return Math.fround(outerScore + names[position * nameWidth + nameId]); | |
| }; | |
| let scores = Float32Array.from(config.start, (start, index) => Math.fround(start + scoreAt(0, index))); | |
| let next = new Float32Array(count); | |
| const history = new Uint16Array(count * length); | |
| for (let position = 1; position < length; position++) { | |
| for (let current = 0; current < count; current++) { | |
| let best = -Infinity; | |
| let parent = 0; | |
| for (let previous = 0; previous < count; previous++) { | |
| const score = Math.fround(scores[previous] + config.transitions[previous][current]); | |
| if (score > best) { | |
| best = score; | |
| parent = previous; | |
| } | |
| } | |
| next[current] = Math.fround(best + scoreAt(position, current)); | |
| history[position * count + current] = parent; | |
| } | |
| [scores, next] = [next, scores]; | |
| } | |
| let best = -Infinity; | |
| let current = 0; | |
| for (let state = 0; state < count; state++) { | |
| const score = Math.fround(scores[state] + config.end[state]); | |
| if (score > best) { | |
| current = state; | |
| best = score; | |
| } | |
| } | |
| const path = new Array<number>(length); | |
| for (let position = length - 1; position >= 0; position--) { | |
| path[position] = current; | |
| current = history[position * count + current]; | |
| } | |
| return path; | |
| } | |
| function bioSpans(indices: number[], labels: string[]): [string, number, number][] { | |
| const spans: [string, number, number][] = []; | |
| let active: string | undefined; | |
| let start = 0; | |
| [...indices, 0].forEach((index, position) => { | |
| const label = index ? labels[Math.floor((index - 1) / 2)] : undefined; | |
| if (active && (active !== label || index % 2 === 1)) { | |
| spans.push([active, start, position]); | |
| active = undefined; | |
| } | |
| if (label && !active) { | |
| active = label; | |
| start = position; | |
| } | |
| }); | |
| return spans; | |
| } | |
| function visibleValue(characters: string[], start: number, end: number, label: string): string { | |
| const value = characters.slice(start, end).join('') | |
| .replace(/[\p{White_Space}\u001c-\u001f]+/gu, ' ').replace(/^ | $/g, ''); | |
| return ['DOI', 'URL', 'ISBN'].includes(label) ? value.normalize('NFKC') : value; | |
| } | |
| function trim(characters: string[], span: Span): boolean { | |
| const whitespace = /^[\p{White_Space}\u001c-\u001f]$/u; | |
| while (span.start < span.end && whitespace.test(characters[span.start])) span.start++; | |
| while (span.end > span.start && whitespace.test(characters[span.end - 1])) span.end--; | |
| return span.start < span.end; | |
| } | |
| function floatOutput(tensor: Tensor): Float32Array { | |
| const { data } = tensor; | |
| if (!(data instanceof Float32Array)) throw new Error('Invalid Bibform output scores'); | |
| return data; | |
| } | |
| export async function loadBinary(url: URL): Promise<ArrayBuffer> { | |
| const response = await fetch(url); | |
| if (!response.ok) throw new Error(`モデルのファイルを読み込めませんでした(${response.status})`); | |
| const body = await response.arrayBuffer(); | |
| const marker = new Uint8Array(body, 0, Math.min(2, body.byteLength)); | |
| if (marker[0] !== 0x1f || marker[1] !== 0x8b) return body; | |
| const decoded = new Blob([body]).stream().pipeThrough(new DecompressionStream('gzip')); | |
| return new Response(decoded).arrayBuffer(); | |
| } | |
| interface MiniLMTokenizerModule { | |
| default(path: URL): Promise<unknown>; | |
| CitationTokenizer: new (definition: string) => { encode(text: string): Uint32Array }; | |
| } | |
| class MiniLMNetwork { | |
| private constructor(private readonly encoder: InferenceSession, private readonly features: InferenceSession, | |
| private readonly tokenizer: { encode(text: string): Uint32Array }, | |
| private readonly vocabulary: Map<string, number>) {} | |
| static async load(base: URL, vocabulary: Map<string, number>): Promise<MiniLMNetwork> { | |
| const script = new URL('tokenizer/bibform_tokenizer.js', base); | |
| const tokenizerModule: MiniLMTokenizerModule = await import(script.href); | |
| const options = { executionProviders: ['wasm'] }; | |
| const [definition, encoderBytes, featureBytes] = await Promise.all([ | |
| loadBinary(new URL('tokenizer.json.gz', base)), | |
| loadBinary(new URL('encoder.onnx.gz', base)), | |
| loadBinary(new URL('features.onnx.gz', base)), | |
| tokenizerModule.default(new URL('tokenizer/bibform_tokenizer_bg.wasm', base)), | |
| ]); | |
| const tokenizer = new tokenizerModule.CitationTokenizer(new TextDecoder().decode(definition)); | |
| const encoder = await InferenceSession.create(encoderBytes, options); | |
| const features = await InferenceSession.create(featureBytes, options); | |
| return new MiniLMNetwork(encoder, features, tokenizer, vocabulary); | |
| } | |
| async scores(text: string, characters: string[]): Promise<InferenceSession.ReturnType> { | |
| const encoded = this.tokenizer.encode(text); | |
| const count = encoded.length / 3; | |
| const ids = new BigInt64Array(count); | |
| const positions = new BigInt64Array(characters.length); | |
| const mapping = new BigInt64Array(characters.length); | |
| for (let index = 0; index < count; index++) { | |
| ids[index] = BigInt(encoded[3 * index]); | |
| const start = encoded[3 * index + 1]; | |
| const end = Math.min(encoded[3 * index + 2], characters.length); | |
| for (let offset = start; offset < end; offset++) { | |
| mapping[offset] = BigInt(index); | |
| positions[offset] = BigInt(Math.min(offset - start + 1, 31)); | |
| } | |
| } | |
| let last = 0n; | |
| for (let index = 0; index < mapping.length; index++) { | |
| if (mapping[index]) last = mapping[index]; | |
| else mapping[index] = last; | |
| } | |
| let context: Float32Array | undefined; | |
| let hiddenWidth = 0; | |
| const coverage = new Uint8Array(count); | |
| for (let from = 0; from < count; from += 384) { | |
| const until = Math.min(from + 512, count); | |
| const { contextual } = await this.encoder.run({ | |
| token_ids: new Tensor('int64', ids.slice(from, until), [1, until - from]), | |
| }); | |
| hiddenWidth = contextual.dims[2]; | |
| const accumulated = context ?? new Float32Array(count * hiddenWidth); | |
| context = accumulated; | |
| floatOutput(contextual).forEach((value, index) => accumulated[from * hiddenWidth + index] += value); | |
| for (let index = from; index < until; index++) coverage[index]++; | |
| if (until === count) break; | |
| } | |
| if (!context) throw new Error('引用のトークンを生成できませんでした'); | |
| for (let index = 0; index < context.length; index++) context[index] /= coverage[Math.floor(index / hiddenWidth)]; | |
| const shape = [1, characters.length]; | |
| return this.features.run({ | |
| contextual: new Tensor('float32', context, [1, count, hiddenWidth]), | |
| character_tokens: new Tensor('int64', mapping, shape), | |
| character_ids: new Tensor('int64', BigInt64Array.from(characters.map((char) => BigInt(this.vocabulary.get(char) ?? 1))), shape), | |
| token_positions: new Tensor('int64', positions, shape), | |
| }); | |
| } | |
| } | |
| function blendScores(primary: Float32Array, secondary: Float32Array, weight: number): Float32Array { | |
| if (primary.length !== secondary.length) throw new Error('モデルの出力形式が一致しません'); | |
| return primary.map((value, index) => Math.fround(value + weight * Math.fround(secondary[index] - value))); | |
| } | |
| function softmax(logits: Float32Array): Float32Array { | |
| const maximum = Math.max(...logits); | |
| const exponentials = logits.map((value) => Math.exp(value - maximum)); | |
| const sum = exponentials.reduce((total, value) => total + value, 0); | |
| return exponentials.map((value) => value / sum); | |
| } | |
| export class LiteModel { | |
| private constructor(private readonly config: ModelConfig, private readonly core: InferenceSession, | |
| private readonly roleNetwork: InferenceSession, private readonly minilm: MiniLMNetwork | null) {} | |
| static async load(base: URL): Promise<LiteModel> { | |
| env.wasm.numThreads = 1; | |
| const runtime = new URL('../runtime/', base); | |
| env.wasm.wasmPaths = runtime.href; | |
| const [configResponse, wasm, roleBytes] = await Promise.all([ | |
| fetch(new URL('model.json', base)), | |
| loadBinary(new URL('ort-wasm-simd-threaded.wasm.gz', runtime)), | |
| loadBinary(new URL('role-network.onnx.gz', base)), | |
| ]); | |
| if (!configResponse.ok) throw new Error('軽量版のモデル設定を読み込めません'); | |
| const config = parseConfig(await configResponse.json()); | |
| env.wasm.wasmBinary = wasm; | |
| const options = { executionProviders: ['wasm'] }; | |
| const byteBase = config.blend === null ? base : new URL('../lite/', base); | |
| const core = await InferenceSession.create(await loadBinary(new URL('byte-network.onnx.gz', byteBase)), options); | |
| const roles = await InferenceSession.create(roleBytes, options); | |
| const minilm = config.blend === null ? null : await MiniLMNetwork.load(base, config.characterVocabulary); | |
| return new LiteModel(config, core, roles, minilm); | |
| } | |
| async predict(text: string): Promise<Prediction> { | |
| const characters = Array.from(text); | |
| if (!characters.length) throw new Error('引用を入力してください'); | |
| const { config } = this; | |
| const feeds: Record<string, Tensor> = { | |
| bytes: new Tensor('int64', byteIds(characters), [1, characters.length, 4]), | |
| }; | |
| if (config.version === 1) { | |
| const grams = ngramIds(characters, config); | |
| feeds.ngrams = new Tensor('int64', grams, [grams.length]); | |
| } | |
| const byte = await this.core.run(feeds); | |
| const primary = this.minilm ? await this.minilm.scores(text, characters) : byte; | |
| let fieldsScores = floatOutput(primary.outer); | |
| let nameScores = floatOutput(primary.names); | |
| let typeProbabilities: Float32Array; | |
| if (config.version === 2) { | |
| let typeLogits = floatOutput(primary.type_logits); | |
| if (config.blend !== null) { | |
| fieldsScores = blendScores(fieldsScores, floatOutput(byte.outer), config.blend); | |
| nameScores = blendScores(nameScores, floatOutput(byte.names), config.blend); | |
| typeLogits = blendScores(typeLogits, floatOutput(byte.type_logits), config.blend); | |
| } | |
| typeProbabilities = softmax(typeLogits); | |
| } else { | |
| typeProbabilities = floatOutput(byte.type_probabilities); | |
| } | |
| const path = viterbi(fieldsScores, nameScores, characters.length, config); | |
| const fields: Field[] = []; | |
| const contributors: Contributor[] = []; | |
| const outerSpans = bioSpans(path.map((index) => config.states[index][0]), config.outer); | |
| const nameSpans = bioSpans(path.map((index) => config.states[index][1]), config.names); | |
| for (const [label, start, end] of outerSpans) { | |
| const span = { start, end, value: visibleValue(characters, start, end, label) }; | |
| if (config.fields.includes(label)) { | |
| fields.push({ label, ...span }); | |
| } else if (label === 'organization' || label === 'person') { | |
| const nameParts = new Map<string, Span>(); | |
| if (label === 'person') { | |
| for (const [name, left, right] of nameSpans) { | |
| if (start <= left && right <= end && !nameParts.has(name)) { | |
| nameParts.set(name, { start: left, end: right, value: visibleValue(characters, left, right, name) }); | |
| } | |
| } | |
| if (!nameParts.size) continue; | |
| } | |
| contributors.push({ kind: label, ...span, nameParts, roles: [] }); | |
| } | |
| } | |
| if (contributors.length) { | |
| const starts = BigInt64Array.from(contributors.map((span) => BigInt(span.start))); | |
| const ends = BigInt64Array.from(contributors.map((span) => BigInt(span.end))); | |
| const roleFeeds: Record<string, Tensor> = { hidden: primary.hidden, | |
| starts: new Tensor('int64', starts, [starts.length]), ends: new Tensor('int64', ends, [ends.length]) }; | |
| if (config.blend !== null) roleFeeds.alternate = byte.hidden; | |
| const { roles } = await this.roleNetwork.run(roleFeeds); | |
| const masks = floatOutput(roles); | |
| contributors.forEach((person, index) => { | |
| person.roles = config.roles.filter((_, offset) => masks[index * config.roles.length + offset]).sort(); | |
| for (const [key, part] of person.nameParts) { | |
| if (!trim(characters, part)) person.nameParts.delete(key); | |
| } | |
| }); | |
| } | |
| const totals = new Map<string, number>(); | |
| typeProbabilities.forEach((score, index) => { | |
| const type = config.exportTypes[index]; | |
| totals.set(type, Math.fround((totals.get(type) ?? 0) + score)); | |
| }); | |
| const candidates = [...totals].map(([type, score]) => ({ type, score })) | |
| .sort((left, right) => right.score - left.score || left.type.localeCompare(right.type, 'en')); | |
| return { fields: fields.filter((field) => trim(characters, field)), | |
| contributors: contributors.filter((person) => trim(characters, person)), candidates }; | |
| } | |
| } | |