Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions scripts/runtime-files.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
18 changes: 18 additions & 0 deletions src/experiments/neural/neural-field.mjs
Original file line number Diff line number Diff line change
@@ -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<rows;row++)for(let col=0;col<cols;col++){
next[row*cols+col]=predict(model,(col+.5)/cols*2-1,1-(row+.5)/rows*2);
}
kind=model.kind;weights=[...model.weights];values=next;
return values;
};
}
2 changes: 1 addition & 1 deletion src/experiments/neural/neural.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<meta name="color-scheme" content="light dark"><link rel="icon" href="data:,">
<link rel="stylesheet" href="./style.css"><link rel="stylesheet" href="./neural.css?v=step-verdict-v1">
<link rel="stylesheet" href="./neural-lesson.css"><script type="module" src="./neural-lesson-ui.mjs?v=neural-learning-20261026"></script>
<script type="module" src="./neural.mjs?v=step-verdict-v2"></script><title>算法游乐场 · 涂鸦训练场</title>
<script type="module" src="./neural.mjs?v=field-cache-v1"></script><title>算法游乐场 · 涂鸦训练场</title>
<link rel="stylesheet" href="./navigation.css?v=three-cat-brand-v1"><script type="module" src="./navigation.mjs?v=cats-in-scenes-v1"></script>
<link rel="stylesheet" href="./neural-guide.css"><script type="module" src="./neural-guide-ui.mjs"></script>
<script type="module" src="./neural-gradient-ui.mjs"></script>
Expand Down
6 changes: 4 additions & 2 deletions src/experiments/neural/neural.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<rows;row++)for(let col=0;col<cols;col++){
const x=(col+.5)/cols*2-1,y=1-(row+.5)/rows*2,p=predict(model,x,y);
const p=probabilities[row*cols+col];
// Neutral at 0.5; saturation represents model tendency, not calibrated certainty.
const strength=Math.abs(p-.5)*2;
ctx.globalAlpha=(dark?.42:.52)*strength;
Expand Down
1 change: 1 addition & 0 deletions tests/delivery/delivery.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ const files=['app.mjs','core.mjs','data.mjs','evolution-core.mjs','evolution.css
files.push('neural-lesson.mjs','neural-lesson-ui.mjs','neural-lesson.css');
files.push('pathfinding-cats.mjs','pathfinding-cats-ui.mjs','pathfinding-cats.css');
files.push('neural-step.mjs','neural-step-view.mjs');
files.push('neural-field.mjs');
files.push('neural-guide.mjs','neural-guide-ui.mjs','neural-guide-view.mjs','neural-guide.css');
files.push('neural-cat-lesson.mjs','neural-cat-lesson-ui.mjs','neural-cat-lesson.css',
'neural-cat-01.jpg','neural-cat-02.jpg','neural-cat-03.jpg','neural-cat-04.jpg',
Expand Down
44 changes: 44 additions & 0 deletions tests/experiments/neural/neural-field.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createPredictionField} from '../../../src/experiments/neural/neural-field.mjs';
import {createModel,makeDataset,predict,train} from '../../../src/experiments/neural/neural-core.mjs';

test('field probabilities retain full precision and the original cell-center coordinates',()=>{
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)<Number.EPSILON),'log/exp round-off stays within one machine epsilon of 3/4');
model.weights[2]=0;
assert.deepEqual([...read(model)],[.5,.5,.5,.5,.5,.5]);
});

test('unchanged snapshots reuse work, but training, switching and rewind show the right field',()=>{
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;}
});
25 changes: 22 additions & 3 deletions tests/experiments/neural/neural-ui.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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});
Expand Down Expand Up @@ -243,8 +261,9 @@ test('model and learning-rate controls occur once beside the canvas, before trai
}
assert.ok(actions<html.indexOf('class="prediction"'),'optional guess must not separate settings from training');
});
async function boot({noCanvas=false,hidden=false,storage=memoryStorage()}={}){
const html=await readFile(new URL('../../../dist/neural.html',import.meta.url),'utf8').catch(()=>'');
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]??(()=>{})});
Expand All @@ -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');},
Expand Down
Loading