File size: 13,995 Bytes
1f5647a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | import { Tokenizer } from '@huggingface/tokenizers';
import { env, InferenceSession, Tensor } from 'onnxruntime-web/wasm';
export const discourseTasks = ['BASIL_lexical_bias', 'BASIL_informational_bias'] as const;
type Task = typeof discourseTasks[number];
type Asset = { path: string; sha256: string; bytes?: number };
type Calibration = { task: Task; scale: number; intercept: number; threshold: number; margin: number; method: string };
export type DiscourseManifest = {
method: 'doxa-contextual-discourse-v0.2.0';
model_id: string; revision: string;
publication_status: 'qualified_release' | 'local_candidate_withheld';
maximum_tokens: number; applied_rubric: 'BASIL-source-annotation-v1';
calibration: Calibration[];
files: { tokenizer: Asset; weights: Asset };
scope: string;
};
export type DiscourseRequest = {
target: string; before: string[]; after: string[];
applied_rubric: string;
tasks?: string[];
language: string; genre: string;
source_anchor?: { document_id: string; start: number; end: number; sha256: string; offset_unit: 'unicode_codepoint' };
};
export type DiscourseTaskResult = {
task: string; applied_rubric: string | null;
prediction_status: 'ok' | 'abstained' | 'unsupported_criterion' | 'missing_rubric' | 'out_of_evaluated_domain' | 'insufficient_context' | 'invalid_input';
suggested_decision: 'present' | 'absent' | null;
model_score: number | null; decision_threshold: number | null;
abstention_margin: number | null; calibration: string | null;
reason: string | null; review_priority: 'unassigned';
};
async function digest(bytes: ArrayBuffer) {
return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), value => value.toString(16).padStart(2, '0')).join('');
}
async function asset(root: string, value: Asset) {
const response = await fetch(new URL(value.path, root), { credentials: 'omit', referrerPolicy: 'no-referrer' });
if (!response.ok) throw new Error('The pinned discourse model asset is unavailable.');
const bytes = await response.arrayBuffer();
if (await digest(bytes) !== value.sha256) throw new Error('The discourse model asset failed its published checksum.');
return bytes;
}
function wellFormed(text: string) {
for (let index = 0; index < text.length; index++) {
const unit = text.charCodeAt(index);
if (unit >= 0xD800 && unit <= 0xDBFF) {
const next = text.charCodeAt(++index);
if (!(next >= 0xDC00 && next <= 0xDFFF)) return false;
} else if (unit >= 0xDC00 && unit <= 0xDFFF) return false;
}
return true;
}
export async function loadDiscourse(options: { manifestUrl: string; wasmBase: string; allowLocalCandidateAudit?: boolean }) {
const audit = options.allowLocalCandidateAudit === true && ['127.0.0.1', 'localhost'].includes(location.hostname);
const response = await fetch(options.manifestUrl, { credentials: 'omit', referrerPolicy: 'no-referrer' });
if (!response.ok) throw new Error('The discourse model manifest is unavailable.');
const manifest = await response.json() as DiscourseManifest;
if (manifest.method !== 'doxa-contextual-discourse-v0.2.0' || manifest.applied_rubric !== 'BASIL-source-annotation-v1'
|| manifest.maximum_tokens !== 256 || manifest.calibration.length !== 2
|| (!audit && (!/^[a-f0-9]{40}$/.test(manifest.revision) || manifest.publication_status !== 'qualified_release'))) {
throw new Error('The discourse candidate has no qualified pinned public release.');
}
for (const [index, value] of manifest.calibration.entries()) {
if (value.task !== discourseTasks[index] || !Number.isFinite(value.scale) || !Number.isFinite(value.intercept)
|| value.threshold <= 0 || value.threshold >= 1 || value.margin < 0 || value.margin > .25) {
throw new Error('The discourse calibration manifest is invalid.');
}
}
const root = `https://huggingface.co/${manifest.model_id}/resolve/${manifest.revision}/`;
env.wasm.numThreads = 1;
env.wasm.wasmPaths = {
mjs: new URL('ort-wasm-simd-threaded.mjs', options.wasmBase),
wasm: new URL('ort-wasm-simd-threaded.wasm', options.wasmBase),
};
const [tokenizerBytes, weights] = await Promise.all([asset(root, manifest.files.tokenizer), asset(root, manifest.files.weights)]);
const tokenizerData = JSON.parse(new TextDecoder().decode(tokenizerBytes));
if (tokenizerData.truncation) throw new Error('The discourse tokenizer must preserve full target length.');
const tokenizer = new Tokenizer(tokenizerData, {});
const cls = tokenizer.token_to_id('[CLS]')!, sep = tokenizer.token_to_id('[SEP]')!;
if (cls === undefined || sep === undefined) throw new Error('The discourse tokenizer lacks required source separators.');
const session = await InferenceSession.create(weights, { executionProviders: ['wasm'], graphOptimizationLevel: 'all' });
async function check(request: DiscourseRequest) {
const started = performance.now();
const object = request && typeof request === 'object' && !Array.isArray(request) ? request : null;
const requested = object?.tasks === undefined ? [...discourseTasks] : object.tasks;
const validTasks = Array.isArray(requested) && requested.length > 0
&& requested.every(task => typeof task === 'string' && task.trim()) && new Set(requested).size === requested.length;
const tasks: string[] = validTasks ? requested as string[] : [];
const rubric = typeof object?.applied_rubric === 'string' ? object.applied_rubric : null;
const results: DiscourseTaskResult[] = tasks.map(task => ({ task, applied_rubric: rubric,
prediction_status: 'unsupported_criterion', suggested_decision: null, model_score: null,
decision_threshold: null, abstention_margin: null, calibration: null, reason: null, review_priority: 'unassigned' }));
const common = { method: manifest.method, model_id: manifest.model_id, model_revision: manifest.revision,
applied_rubric: rubric, evaluated_scope: manifest.scope,
source_anchor: null as DiscourseRequest['source_anchor'] | null, evidence_role: 'exact_target_location_not_a_model_rationale',
reporter_endorsement: 'unresolved', speaker_stance_model: 'not_qualified',
reference_span_prediction: 'not_supported', publication_status: manifest.publication_status,
source_payloads_sent: false, results };
const invalid = (reason: string) => {
for (const result of results) { result.prediction_status = 'invalid_input'; result.reason = reason; }
return { ...common, prediction_status: 'invalid_input', reason, elapsed_ms: performance.now() - started };
};
if (!object) return invalid('A discourse request must be an object.');
if (!validTasks) return invalid('tasks must be a non-empty array of unique non-empty task strings.');
if (typeof request.target !== 'string' || !request.target.trim()) return invalid('target must be a non-empty source string.');
if (!Array.isArray(request.before) || !Array.isArray(request.after)
|| !request.before.every(text => typeof text === 'string') || !request.after.every(text => typeof text === 'string')) {
return invalid('before and after must be arrays of source strings; a string is not a neighbor array.');
}
if (request.applied_rubric !== undefined && request.applied_rubric !== null && typeof request.applied_rubric !== 'string') return invalid('applied_rubric must be a string or null.');
if (typeof request.language !== 'string' || !request.language.trim() || typeof request.genre !== 'string' || !request.genre.trim()) return invalid('language and genre must be non-empty declared strings.');
if (![request.target, ...request.before, ...request.after].every(wellFormed)) return invalid('Source strings must contain well-formed Unicode.');
if (request.source_anchor !== undefined && request.source_anchor !== null) {
const anchor = request.source_anchor;
if (typeof anchor !== 'object' || Array.isArray(anchor) || typeof anchor.document_id !== 'string' || !anchor.document_id.trim()
|| !Number.isSafeInteger(anchor.start) || !Number.isSafeInteger(anchor.end) || anchor.start < 0 || anchor.end <= anchor.start
|| anchor.offset_unit !== 'unicode_codepoint' || typeof anchor.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(anchor.sha256)) {
return invalid('source_anchor needs a document ID, integer codepoint bounds, unicode_codepoint unit and SHA256.');
}
if (anchor.end - anchor.start !== Array.from(request.target).length
|| anchor.sha256 !== await digest(new TextEncoder().encode(request.target).buffer)) return invalid('The target does not match its declared original source anchor.');
common.source_anchor = { document_id: anchor.document_id, start: anchor.start, end: anchor.end,
offset_unit: anchor.offset_unit, sha256: anchor.sha256 };
}
const fail = (status: DiscourseTaskResult['prediction_status'], reason: string) => {
for (const result of results) {
if (request.applied_rubric === manifest.applied_rubric && !(discourseTasks as readonly string[]).includes(result.task)) {
result.reason = 'No eligible task-specific head is registered for this criterion.';
} else { result.prediction_status = status; result.reason = reason; }
}
return { ...common, elapsed_ms: performance.now() - started };
};
if (!request.applied_rubric?.trim()) return fail('missing_rubric', 'Specify the actual task or framework and its version.');
if (request.applied_rubric !== manifest.applied_rubric) return fail('unsupported_criterion', 'This model cannot substitute BASIL labels for a different named framework or review criterion.');
if (!tasks.some(task => (discourseTasks as readonly string[]).includes(task))) return fail('unsupported_criterion', 'No qualified task-specific head is registered for the requested criteria.');
if (request.language !== 'en' || request.genre !== 'news') return fail('out_of_evaluated_domain', 'Only the declared English-news source tasks have held-out evaluation.');
const before = request.before.slice(-2).flatMap(text => tokenizer.encode(text, { add_special_tokens: false }).ids);
const after = request.after.slice(0, 2).flatMap(text => tokenizer.encode(text, { add_special_tokens: false }).ids);
if (!before.length && !after.length) return fail('insufficient_context', 'Supply original neighboring sentences; target-only inference is a separate ablation.');
const target = tokenizer.encode(request.target, { add_special_tokens: false }).ids;
if (!target.length || target.every(value => value === tokenizer.token_to_id('[UNK]'))) return fail('abstained', 'no_known_target_tokens');
if (target.length + 2 > manifest.maximum_tokens) return fail('abstained', 'The complete target exceeds the evaluated input budget; it was not silently truncated.');
const budget = Math.max(0, manifest.maximum_tokens - target.length - 4);
let keepBefore = Math.min(before.length, Math.floor(budget / 2));
const keepAfter = Math.min(after.length, budget - keepBefore);
keepBefore = Math.min(before.length, budget - keepAfter);
const left = keepBefore ? before.slice(-keepBefore) : [];
const right = after.slice(0, keepAfter);
if (!left.length && !right.length) return fail('abstained', 'The complete target leaves no evaluated context budget.');
const ids = [cls, ...target, sep];
const typeIds = Array(ids.length).fill(0);
const targetMask = [0, ...Array(target.length).fill(1), 0];
const contextMask = Array(ids.length).fill(0);
if (left.length || right.length) {
const tail = [...left, sep, ...right, sep];
ids.push(...tail); typeIds.push(...Array(tail.length).fill(1)); targetMask.push(...Array(tail.length).fill(0));
contextMask.push(...Array(left.length).fill(1), 0, ...Array(right.length).fill(1), 0);
}
const values: Record<string, number[]> = { input_ids: ids, attention_mask: Array(ids.length).fill(1),
token_type_ids: typeIds, target_mask: targetMask, context_mask: contextMask };
const tensors = Object.fromEntries(session.inputNames.map(name => [name, new Tensor('int64', BigInt64Array.from(values[name], BigInt), [1, ids.length])]));
const output = await session.run(tensors);
const logits = Array.from(output[session.outputNames[0]].data, Number);
for (const result of results) {
const index = discourseTasks.indexOf(result.task as Task);
if (index < 0) { result.reason = 'No eligible task-specific human reference labels or qualified model are registered for this criterion.'; continue; }
const calibration = manifest.calibration[index];
const score = 1 / (1 + Math.exp(-Math.max(-60, Math.min(60, logits[index] * calibration.scale + calibration.intercept))));
result.model_score = score; result.decision_threshold = calibration.threshold;
result.abstention_margin = calibration.margin; result.calibration = calibration.method;
if (Math.abs(score - calibration.threshold) < calibration.margin) {
result.prediction_status = 'abstained'; result.reason = 'The model score is inside the validation-selected unresolved margin.';
} else {
result.prediction_status = 'ok'; result.suggested_decision = score >= calibration.threshold ? 'present' : 'absent';
}
}
for (const value of Object.values(output)) value.dispose();
for (const value of Object.values(tensors)) value.dispose();
return { ...common, token_coverage: { maximum_tokens: manifest.maximum_tokens, target_tokens: target.length,
target_tokens_retained: target.length, context_tokens_available: before.length + after.length,
context_tokens_retained: left.length + right.length, actual_tokens: ids.length },
input_ids_for_audit: audit ? ids : undefined, input_values_for_audit: audit ? values : undefined,
elapsed_ms: performance.now() - started };
}
return { manifest, check, dispose: () => session.release() };
}
|