diff --git a/scripts/runtime-files.mjs b/scripts/runtime-files.mjs index 3bb98bc..bfdb1d4 100644 --- a/scripts/runtime-files.mjs +++ b/scripts/runtime-files.mjs @@ -180,6 +180,7 @@ const groups = { "neural-cat-lesson.mjs", "neural-cat-quick-ui.mjs", "neural-core.mjs", + "neural-field.mjs", "neural-generalization-ui.mjs", "neural-generalization-view.mjs", "neural-generalization.css", diff --git a/src/experiments/neural/neural-field.mjs b/src/experiments/neural/neural-field.mjs new file mode 100644 index 0000000..9a17cd6 --- /dev/null +++ b/src/experiments/neural/neural-field.mjs @@ -0,0 +1,18 @@ +import {predict} from './neural-core.mjs'; + +// One display grid, not training state. Theme, points and cursor do not change +// these probabilities; compare the actual weights so rewind and in-place edits +// cannot reuse another model's field. Consumers treat the returned grid as read-only. +export function createPredictionField(cols,rows){ + let kind,weights=[],values; + return model=>{ + if(values&&kind===model.kind&&weights.length===model.weights.length + &&weights.every((w,i)=>Object.is(w,model.weights[i])))return values; + const next=new Float64Array(cols*rows); + for(let row=0;row - 算法游乐场 · 涂鸦训练场 + 算法游乐场 · 涂鸦训练场 diff --git a/src/experiments/neural/neural.mjs b/src/experiments/neural/neural.mjs index 7b498a3..404a075 100644 --- a/src/experiments/neural/neural.mjs +++ b/src/experiments/neural/neural.mjs @@ -2,10 +2,12 @@ import {createModel,predict,metrics,train,makeDataset,editPoints,MAX_POINTS,MAX_ import {DRAFT_KEYS,readDraft,writeDraft,clearDraft,validateNeuralDraft,draftMessage,questionKey} from '../../shared/local-drafts.mjs'; import {createStepTrial,guessStep,runStepTrial,rewindStepTrial,stepEvidence} from './neural-step.mjs'; import {paintStep} from './neural-step-view.mjs'; +import {createPredictionField} from './neural-field.mjs'; const $=id=>document.getElementById(id),field=$('field'),ctx=field.getContext('2d'),chart=$('history').getContext('2d'); const tools=[...document.querySelectorAll('[data-tool]')],presets=[...document.querySelectorAll('[data-preset]')],guesses=[...document.querySelectorAll('[data-guess]')]; const names={diagonal:'一分为二',islands:'四个小岛',ring:'甜甜圈',custom:'我的涂鸦'}; const W=900,H=560,percent=v=>(v*100).toFixed(0)+'%'; +const fieldCols=75,fieldRows=46,readField=createPredictionField(fieldCols,fieldRows); let dataset=makeDataset('islands'),points=dataset.train,testPoints=dataset.test,preset='islands'; let model=createModel(),rate=.15,tool='probe',guess=null,history=[],undo=[],gesture=null; let running=false,remaining=0,raf=null,token=0,cursor={x:0,y:0},showCursor=false,probeActive=false; @@ -190,9 +192,9 @@ function switchModel(kind){ function path(context,pts){context.beginPath();pts.forEach((p,i)=>i?context.lineTo(p.x,p.y):context.moveTo(p.x,p.y));} function draw(){ ctx.fillStyle=paper;ctx.fillRect(0,0,W,H); - const cols=75,rows=46; + const cols=fieldCols,rows=fieldRows,probabilities=readField(model); for(let row=0;row{ + const read=createPredictionField(75,46),points=makeDataset('islands').train; + const models=[createModel('linear'),createModel(),train(createModel(),points,.15,20)]; + for(const model of models){ + const before=structuredClone(model),values=read(model); + assert.ok(values instanceof Float64Array);assert.equal(values.byteLength,27600); + // Compatibility oracle: the unchanged scalar engine at the original draw coordinates. + for(let row=0;row<46;row++)for(let col=0;col<75;col++){ + assert.equal(values[row*75+col],predict(model,(col+.5)/75*2-1,1-(row+.5)/46*2)); + } + assert.deepEqual(model,before,'sampling must not change learned weights or epoch'); + } +}); + +test('in-place parameter changes invalidate even when model identity and epoch are unchanged',()=>{ + const model=createModel('linear'),read=createPredictionField(3,2); + assert.deepEqual([...read(model)],[.5,.5,.5,.5,.5,.5]); + model.weights[2]=Math.log(3); + assert.ok(read(model).every(p=>Math.abs(p-.75){ + const read=createPredictionField(75,46),model=createModel(),base=structuredClone(model); + const originalTanh=Math.tanh;let calls=0; + Math.tanh=value=>{calls++;return originalTanh(value);}; + try{ + const first=read(model);assert.equal(calls,27600);calls=0; + for(let i=0;i<60;i++)read(structuredClone(model)); + model.epoch++;read(model); + assert.equal(calls,0,'identity or epoch alone is not a prediction change'); + train(model,makeDataset('islands').train,.15,1);calls=0; + const after=read(model);assert.equal(calls,27600);assert.notDeepEqual(after,first); + const linear=createModel('linear');assert.ok(read(linear).every(p=>p===.5));calls=0; + const rewound=read(base);assert.equal(calls,27600);assert.deepEqual(rewound,first); + calls=0;read(structuredClone(base));assert.equal(calls,0); + }finally{Math.tanh=originalTanh;} +}); diff --git a/tests/experiments/neural/neural-ui.test.mjs b/tests/experiments/neural/neural-ui.test.mjs index e9b531a..58048c2 100644 --- a/tests/experiments/neural/neural-ui.test.mjs +++ b/tests/experiments/neural/neural-ui.test.mjs @@ -4,6 +4,24 @@ import {readFile} from 'node:fs/promises'; import {memoryStorage} from '../../helpers/storage-helper.mjs'; import {DRAFT_KEYS} from '../../../dist/local-drafts.mjs'; let serial=0; +test('drawing previews reuse the unchanged model field and preserve the saved world on cancellation',async()=>{ + const storage=memoryStorage(),u=await boot({storage,source:true}); + const originalTanh=Math.tanh;let calls=0; + Math.tanh=value=>{calls++;return originalTanh(value);}; + try{ + u.click('step'); + u.choose('tool','0'); + const saved=storage.getItem(DRAFT_KEYS.neural),writes=storage.writes; + u.pointer('pointerdown',200,100);calls=0; + for(let i=0;i<60;i++)u.pointer('pointermove',205+i*5,110+i*2); + assert.equal(calls,0,'moving a draft point must not repeat the unchanged background network'); + assert.equal(storage.getItem(DRAFT_KEYS.neural),saved); + assert.equal(storage.writes,writes); + u.pointer('pointercancel'); + assert.equal(storage.getItem(DRAFT_KEYS.neural),saved); + assert.equal(u.elements.get('epoch').textContent,'1'); + }finally{Math.tanh=originalTanh;u.restore();} +}); test('one ordinary step reports its actual change beside training without interrupting another action',async()=>{ const storage=memoryStorage(),u=await boot({storage});try{ window.innerHeight=844;u.elements.get('status').getBoundingClientRect=()=>({top:500,bottom:570}); @@ -243,8 +261,9 @@ test('model and learning-rate controls occur once beside the canvas, before trai } assert.ok(actions''); +async function boot({noCanvas=false,hidden=false,storage=memoryStorage(),source=false}={}){ + const base=source?'../../../src/experiments/neural/':'../../../dist/'; + const html=await readFile(new URL(base+'neural.html',import.meta.url),'utf8').catch(()=>''); assert.ok(html.includes('id="field"'),'new playable page must exist'); const frames=new Map();let next=0; const ctx=new Proxy({},{get:(o,k)=>o[k]??(()=>{})}); @@ -264,7 +283,7 @@ async function boot({noCanvas=false,hidden=false,storage=memoryStorage()}={}){ const old=new Map(Object.keys(globals).map(k=>[k,Object.getOwnPropertyDescriptor(globalThis,k)])); const restore=()=>{for(const[k,d]of old)if(d)Object.defineProperty(globalThis,k,d);else delete globalThis[k];}; Object.assign(globalThis,globals); - try{await import(new URL('../../../dist/neural.mjs?test='+ ++serial,import.meta.url));}catch(e){restore();throw e;} + try{await import(new URL(base+'neural.mjs?test='+ ++serial,import.meta.url));}catch(e){restore();throw e;} const fire=(el,type,props={})=>type==='click'&&el.disabled?false:el.dispatchEvent(Object.assign(new Event(type,{cancelable:true}),props)); return {elements,frames,restore,fire,click:id=>fire(elements.get(id),'click'),choose:(key,value)=>fire(groups[key].find(e=>e.dataset[key]===value),'click'), change(id,value){elements.get(id).value=value;fire(elements.get(id),'change');},