Playground archived at branch archive/playground-solidjs (tag playground-solidjs-final) and deleted from main. Retargets: - run-all-tests.sh stage 5 → manifold (typecheck + bun test + build + playwright via non-snap node runner, BUILD-PLAN gotcha) - ci.yml playground-tests → manifold-tests; osc-bridge.yml → manifold/osc-bridge (was already broken: playground/osc-bridge no longer existed) - codegen: TS emission target removed (returns at P5 → manifold); golden test now C++-only; TS emitters retained dormant - .gitignore: manifold/osc-bridge paths; drop dead playground faust exception - docs: AGENTS.md gates, README quickstart, MAP.md, ALIGNMENT.md (C15 now archive-only — defect #1 updated), AGENT-REFERENCE.md, specs/MAIN.md Part of docs/specs/plans/one-core-engine-refactor.md P1.
2 lines
16 KiB
JavaScript
2 lines
16 KiB
JavaScript
import{m as d,p,l as y}from"./index-C1-a2ZPT.js";class T{maxSize;inputSize_=0;outputSize_=0;features_=new Float32Array(0);labels_=new Float32Array(0);size_=0;constructor(t=100){if(t<=0)throw new Error("Dataset.maxSize must be > 0");this.maxSize=t}get size(){return this.size_}isEmpty(){return this.size_===0}add(t,e){if(this.size_===0&&(this.inputSize_=t.length,this.outputSize_=e.length,this.features_=new Float32Array(this.maxSize*this.inputSize_),this.labels_=new Float32Array(this.maxSize*this.outputSize_)),t.length!==this.inputSize_||e.length!==this.outputSize_)return!1;this.size_>=this.maxSize&&(this.features_.copyWithin(0,this.inputSize_),this.labels_.copyWithin(0,this.outputSize_),this.size_=this.maxSize-1);const s=this.size_*this.inputSize_,a=this.size_*this.outputSize_;for(let r=0;r<this.inputSize_;++r)this.features_[s+r]=t[r];for(let r=0;r<this.outputSize_;++r)this.labels_[a+r]=e[r];return this.size_++,!0}clear(){this.size_=0}feature(t){if(t<0||t>=this.size_)throw new RangeError(`feature index ${t} out of bounds`);return this.features_.subarray(t*this.inputSize_,(t+1)*this.inputSize_)}label(t){if(t<0||t>=this.size_)throw new RangeError(`label index ${t} out of bounds`);return this.labels_.subarray(t*this.outputSize_,(t+1)*this.outputSize_)}featuresFlat(){return this.features_.subarray(0,this.size_*this.inputSize_)}labelsFlat(){return this.labels_.subarray(0,this.size_*this.outputSize_)}get inputSize(){return this.inputSize_}get outputSize(){return this.outputSize_}computeWeights(t="uniform",e={}){const s=this.size_;if(s===0)return new Float32Array(0);if(s===1)return new Float32Array([1]);const a=new Float32Array(s).fill(1);if(t==="global"||t==="combined"){const i=e.recencyBias??.6;if(i>0){const n=1-.3*i;for(let o=s-2;o>=0;--o)a[o]=a[o+1]*n}}if((t==="local"||t==="combined")&&e.queryInput){const i=e.queryInput,n=e.radius??.15,o=n*n,_=this.inputSize_;for(let u=0;u<s;++u){const S=u*_;let c=0;for(let m=0;m<_;++m){const g=this.features_[S+m]-(i[m]??0);c+=g*g}if(c<o){const m=1-Math.sqrt(c)/n;let g=0;for(let l=u+1;l<s;++l){const h=l*_;let f=0;for(let w=0;w<_;++w){const A=this.features_[S+w]-this.features_[h+w];f+=A*A}f<o&&++g}g>0&&(a[u]*=Math.pow(1-m,g))}}}let r=0;for(let i=0;i<s;++i)r+=a[i];if(r>0)for(let i=0;i<s;++i)a[i]/=r;return a}}class H{worker;nextId=1;pending=new Map;disposed=!1;static async create(){const t=new H;return await t.init_(),t}constructor(){this.worker=new Worker(new URL("/assets/wasm-worker-OATBBHaT.js",import.meta.url),{type:"module"}),this.worker.onmessage=t=>this.onMessage_(t.data),this.worker.onerror=t=>{for(const{reject:e}of this.pending.values())e(t.message??"worker error");this.pending.clear()}}init_(){return new Promise((t,e)=>{const s=r=>{const i=r.data;i.kind==="ready"?(this.worker.removeEventListener("message",s),t()):i.kind==="error"&&(this.worker.removeEventListener("message",s),e(new Error(i.message)))};this.worker.addEventListener("message",s);const a=(Date.now()^Math.floor(Math.random()*4294967295))>>>0;this.worker.postMessage({kind:"init",seed:a})})}train(t){if(this.disposed)return Promise.reject(new Error("WasmTrainer disposed"));const e=this.nextId++;return new Promise((s,a)=>{this.pending.set(e,{resolve:s,reject:a});const r={kind:"train",requestId:e,weights:t.weights,features:t.features,labels:t.labels,sampleWeights:t.sampleWeights,lr:t.lr,maxIter:t.maxIter,minErr:t.minErr,inputSize:t.inputSize,outputSize:t.outputSize};this.worker.postMessage(r,[t.weights.buffer,t.features.buffer,t.labels.buffer,t.sampleWeights.buffer])})}dispose(){if(!this.disposed){this.disposed=!0;try{this.worker.postMessage({kind:"dispose"})}catch{}this.worker.terminate();for(const{reject:t}of this.pending.values())t(new Error("disposed"));this.pending.clear()}}onMessage_(t){if(t.kind==="result"){const e=this.pending.get(t.requestId);e&&(this.pending.delete(t.requestId),e.resolve({loss:t.loss,weights:t.weights,lossHistory:t.lossHistory}))}else if(t.kind==="error"){const e=this.pending.get(t.requestId);e&&(this.pending.delete(t.requestId),e.reject(new Error(t.message)))}}}function M(){return H.create()}const W=typeof window>"u"&&typeof self<"u"&&typeof self.importScripts<"u";if(W){let v=function(l,h,f,w){if(!s)throw new Error("worker module not loaded");n!==r&&(i&&s._free(i),i=s._malloc(r*4),n=r),l.length!==_&&(o&&s._free(o),o=s._malloc(l.length*4),_=l.length),h.length!==S&&(u&&s._free(u),u=s._malloc(h.length*4),S=h.length),f.length!==m&&(c&&s._free(c),c=f.length>0?s._malloc(f.length*4):0,m=f.length),new Float32Array(s.HEAPF32.buffer,i,r).set(w),new Float32Array(s.HEAPF32.buffer,o,l.length).set(l),new Float32Array(s.HEAPF32.buffer,u,h.length).set(h),c&&new Float32Array(s.HEAPF32.buffer,c,f.length).set(f)},t=function(l){if(!s)return{kind:"error",requestId:l.requestId,message:"worker not initialised"};try{v(l.features,l.labels,l.sampleWeights,l.weights),s._nisps_ml_set_weights(a,i),s._nisps_ml_clear_examples(a);const h=l.inputSize,f=l.outputSize,w=l.features.length/h;for(let B=0;B<w;++B){const P=o+B*h*4,I=u+B*f*4;s._nisps_ml_add_example(a,P,I)}const A=l.sampleWeights.length>0?c:0,E=s._nisps_ml_train(a,l.lr,l.maxIter,l.minErr,A);s._nisps_ml_get_weights(a,i);const k=new Float32Array(s.HEAPF32.buffer,i,r),L=new Float32Array(k),x=new Float32Array([E]);return{kind:"result",requestId:l.requestId,loss:E,weights:L,lossHistory:x}}catch(h){return{kind:"error",requestId:l.requestId,message:h instanceof Error?h.message:String(h)}}},e=function(){s&&(a&&(s._nisps_ml_destroy(a),a=0),i&&(s._free(i),i=0),o&&(s._free(o),o=0),u&&(s._free(u),u=0),c&&(s._free(c),c=0),s=null)},s=null,a=0,r=0,i=0,n=0,o=0,_=0,u=0,S=0,c=0,m=0;async function g(l){const h=await import(new URL("/nisps.js",self.location.origin).toString());s=await(h.default??h.createNispsModule)({locateFile:w=>w.endsWith(".wasm")?new URL("/nisps.wasm",self.location.origin).toString():w}),a=s._nisps_ml_create(0,0,0,0,l>>>0),r=s._nisps_ml_weight_count(a)}self.addEventListener("message",async l=>{const h=l.data;if(h.kind==="init")try{await g(h.seed),self.postMessage({kind:"ready"})}catch(f){self.postMessage({kind:"error",requestId:0,message:f instanceof Error?f.message:String(f)})}else if(h.kind==="train"){const f=t(h);f.kind==="result"?self.postMessage(f,[f.weights.buffer,f.lossHistory.buffer]):self.postMessage(f)}else h.kind==="dispose"&&e()})}const C="/nisps.js",O="/nisps.wasm",U=2,j=126;let F=null;async function N(){if(F)return F;const t=await import(new URL(C,window.location.origin).toString()),e=t.default??t.createNispsModule;if(!e)throw new Error("[wasm-iml] nisps.js does not export a module factory");return F=e,e}class z{constructor(t,e){if(this.mod=t,this.count=e,this.ptr=t._malloc(e*4),!this.ptr)throw new Error(`malloc(${e*4}) failed`);this.view=new Float32Array(t.HEAPF32.buffer,this.ptr,e)}ptr;view;rebind(){Object.defineProperty(this,"view",{value:new Float32Array(this.mod.HEAPF32.buffer,this.ptr,this.count),writable:!1})}free(){this.mod._free(this.ptr)}}class ${constructor(t,e){if(this.mod=t,this.count=e,this.ptr=t._malloc(e),!this.ptr)throw new Error(`malloc(${e}) failed`);this.view=new Uint8Array(t.HEAPU8.buffer,this.ptr,e)}ptr;view;rebind(){Object.defineProperty(this,"view",{value:new Uint8Array(this.mod.HEAPU8.buffer,this.ptr,this.count),writable:!1})}free(){this.mod._free(this.ptr)}}class b{module;mlHandle=0;weightCount_=0;arch_={inputSize:U,hidden:[10,14,18],outputSize:j,numLayers:4};featuresBuf;labelsBuf;weightsBuf;statsBuf;batchInBuf;batchOutBuf;pinMaskBuf;describeBuf;describePtr=0;dataset;lastLoss_=null;trainer=null;storageKey;saveTimer=null;destroyed=!1;static MAX_BATCH=4096;constructor(t){this.dataset=new T(t.maxExamples??100),this.storageKey=t.storageKey??"nisps:wasm-iml"}static async create(t={}){const e=new b(t);return await e.init_(t),e}async init_(t){const e=await N();this.module=await e({locateFile:n=>n.endsWith(".wasm")?new URL(O,window.location.origin).toString():n}),this.describePtr=this.module._malloc(6*4),this.module._nisps_ml_describe(this.describePtr);const s=new Int32Array(this.module.HEAP32.buffer,this.describePtr,6);this.arch_={inputSize:s[0],hidden:[s[1],s[2],s[3]],outputSize:s[4],numLayers:s[5]};const a=t.inputSize??this.arch_.inputSize,r=t.outputSize??this.arch_.outputSize;(a!==this.arch_.inputSize||r!==this.arch_.outputSize)&&console.warn(`[wasm-iml] requested ${a}->${r} but WASM build is fixed at ${this.arch_.inputSize}->${this.arch_.outputSize}; extras are ignored.`);const i=(t.seed??Date.now()>>>0)>>>0;if(this.mlHandle=this.module._nisps_ml_create(this.arch_.inputSize,this.arch_.outputSize,0,0,i),!this.mlHandle)throw new Error("[wasm-iml] nisps_ml_create returned null");this.weightCount_=this.module._nisps_ml_weight_count(this.mlHandle),this.featuresBuf=new z(this.module,this.arch_.inputSize),this.labelsBuf=new z(this.module,this.arch_.outputSize),this.weightsBuf=new z(this.module,this.weightCount_),this.statsBuf=new z(this.module,this.arch_.numLayers*4),this.batchInBuf=new z(this.module,b.MAX_BATCH*this.arch_.inputSize),this.batchOutBuf=new z(this.module,b.MAX_BATCH*this.arch_.outputSize),this.pinMaskBuf=new $(this.module,this.arch_.outputSize),d.__setState(p(n=>{n.inputSize=this.arch_.inputSize,n.outputSize=this.arch_.outputSize,n.exampleCount=0,n.lastLoss=null,n.lossHistory=[],n.training=!1,n.ready=!0})),d.__setOutputs(new Float32Array(this.arch_.outputSize)),this.publishWeights_(),this.tryLoadFromStorage_()}dispose(){this.destroyed||(this.destroyed=!0,this.saveTimer!==null&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.trainer&&(this.trainer.dispose(),this.trainer=null),this.module&&this.mlHandle&&(this.module._nisps_ml_destroy(this.mlHandle),this.mlHandle=0),this.featuresBuf&&this.featuresBuf.free(),this.labelsBuf&&this.labelsBuf.free(),this.weightsBuf&&this.weightsBuf.free(),this.statsBuf&&this.statsBuf.free(),this.batchInBuf&&this.batchInBuf.free(),this.batchOutBuf&&this.batchOutBuf.free(),this.pinMaskBuf&&this.pinMaskBuf.free(),this.describePtr&&this.module._free(this.describePtr),d.__setState(p(t=>{t.ready=!1})))}get architecture(){return this.arch_}get weightCount(){return this.weightCount_}get exampleCount(){return this.dataset.size}get lastLoss(){return this.lastLoss_}setInput(t,e){this.module._nisps_ml_set_input(this.mlHandle,t,e)}process(){this.module._nisps_ml_process(this.mlHandle);const t=this.module._nisps_ml_outputs(this.mlHandle),e=new Float32Array(this.module.HEAPF32.buffer,t,this.arch_.outputSize),s=new Float32Array(e);return d.__setOutputs(s),s}inferXY(t,e){return this.setInput(0,t),this.setInput(1,e),this.process()}inferBatch(t){const e=t.length,s=this.arch_.inputSize,a=this.arch_.outputSize,r=new Float32Array(e*a);let i=0;for(let n=0;n<e;n+=b.MAX_BATCH){const o=Math.min(b.MAX_BATCH,e-n);for(let u=0;u<o;++u){const S=t[n+u],c=u*s;for(let m=0;m<s;++m)this.batchInBuf.view[c+m]=S[m]??0}this.module._nisps_ml_infer_batch(this.mlHandle,this.batchInBuf.ptr,o,this.batchOutBuf.ptr);const _=this.batchOutBuf.view.subarray(0,o*a);r.set(_,i),i+=o*a}return r}addExample(t,e){return this.dataset.add(t,e)?(this.copyExampleToWasm_(t,e),d.__setState(p(a=>{a.exampleCount=this.dataset.size})),y.emit("ml.example_added",{count:this.dataset.size}),this.scheduleSave_(),!0):!1}copyExampleToWasm_(t,e){const s=this.featuresBuf.view,a=this.labelsBuf.view,r=this.arch_.inputSize,i=this.arch_.outputSize;for(let n=0;n<r;++n)s[n]=t[n]??0;for(let n=0;n<i;++n)a[n]=e[n]??0;this.module._nisps_ml_add_example(this.mlHandle,this.featuresBuf.ptr,this.labelsBuf.ptr)}train(t=1,e=1e3,s=.001,a){if(this.dataset.isEmpty())return this.lastLoss_=0,d.__setState(p(o=>{o.lastLoss=0})),0;let r=0,i=null;a&&a.length===this.dataset.size&&(i=new z(this.module,a.length),i.view.set(a),r=i.ptr),d.__setState(p(o=>{o.training=!0}));let n=0;try{n=this.module._nisps_ml_train(this.mlHandle,t,e,s,r)}finally{i&&i.free(),d.__setState(p(o=>{o.training=!1}))}return this.lastLoss_=n,d.__setState(p(o=>{o.lastLoss=n,o.lossHistory=[n]})),this.publishWeights_(),y.emit("ml.trained",{loss:n}),this.scheduleSave_(),n}async trainAsync(t=1,e=1e3,s=.001,a){if(this.dataset.isEmpty())return this.lastLoss_=0,0;this.trainer||(this.trainer=await M());const r=this.getWeights(),i=new Float32Array(this.dataset.featuresFlat()),n=new Float32Array(this.dataset.labelsFlat()),o=a?new Float32Array(a):new Float32Array(0);d.__setState(p(_=>{_.training=!0}));try{const _=await this.trainer.train({weights:r,features:i,labels:n,sampleWeights:o,lr:t,maxIter:e,minErr:s,inputSize:this.arch_.inputSize,outputSize:this.arch_.outputSize});return this.setWeights(_.weights),this.lastLoss_=_.loss,d.__setState(p(u=>{u.lastLoss=_.loss,u.lossHistory=Array.from(_.lossHistory)})),y.emit("ml.trained",{loss:_.loss}),this.scheduleSave_(),_.loss}finally{d.__setState(p(_=>{_.training=!1}))}}evalLoss(){return this.module._nisps_ml_eval_loss(this.mlHandle)}clearExamples(){this.dataset.clear(),this.module._nisps_ml_clear_examples(this.mlHandle),d.__setState(p(t=>{t.exampleCount=0})),y.emit("ml.examples_cleared",void 0),this.scheduleSave_()}randomiseWeights(t=.6){this.module._nisps_ml_draw_weights(this.mlHandle,t),this.publishWeights_(),y.emit("ml.delta_update",{reason:"randomize"}),this.scheduleSave_()}moveWeights(t,e,s){let a=0;if(s){const r=Math.min(s.length,this.arch_.outputSize);for(let i=0;i<r;++i)this.pinMaskBuf.view[i]=s[i];for(let i=r;i<this.arch_.outputSize;++i)this.pinMaskBuf.view[i]=0;a=this.pinMaskBuf.ptr}this.module._nisps_ml_move_weights(this.mlHandle,t,e,a),this.publishWeights_(),y.emit("ml.delta_update",{reason:"thumbs_down"})}getWeights(){return this.module._nisps_ml_get_weights(this.mlHandle,this.weightsBuf.ptr),new Float32Array(this.weightsBuf.view)}setWeights(t){if(t.length<this.weightCount_)throw new Error(`setWeights: expected ${this.weightCount_} floats, got ${t.length}`);this.weightsBuf.view.set(t,0),this.module._nisps_ml_set_weights(this.mlHandle,this.weightsBuf.ptr),this.publishWeights_()}getLayerStats(){this.module._nisps_ml_get_layer_stats(this.mlHandle,this.statsBuf.ptr);const t=[];for(let e=0;e<this.arch_.numLayers;++e){const s=e*4;t.push({meanAbs:this.statsBuf.view[s],maxAbs:this.statsBuf.view[s+1],deadFrac:this.statsBuf.view[s+2],saturatingFrac:this.statsBuf.view[s+3]})}return t}getLayerStatsFlat(){return this.module._nisps_ml_get_layer_stats(this.mlHandle,this.statsBuf.ptr),new Float32Array(this.statsBuf.view)}reset(){this.module._nisps_ml_reset(this.mlHandle),this.dataset.clear(),this.lastLoss_=null,d.__setState(p(t=>{t.exampleCount=0,t.lastLoss=null,t.lossHistory=[]})),this.publishWeights_(),y.emit("ml.examples_cleared",void 0),this.scheduleSave_()}scheduleSave_(){this.saveTimer!==null&&clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>this.saveNow(),500)}saveNow(){if(!this.destroyed){this.saveTimer!==null&&(clearTimeout(this.saveTimer),this.saveTimer=null);try{const t=this.getWeights(),e={v:1,arch:this.arch_,weights:Array.from(t),features:Array.from(this.dataset.featuresFlat()),labels:Array.from(this.dataset.labelsFlat()),size:this.dataset.size,lastLoss:this.lastLoss_};localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(t){console.warn("[wasm-iml] saveNow failed:",t)}}}tryLoadFromStorage_(){try{const t=localStorage.getItem(this.storageKey);if(!t)return;const e=JSON.parse(t);if(e.v!==1)return;const s=this.arch_.inputSize,a=this.arch_.outputSize;if(e.size>0&&e.features.length===e.size*s&&e.labels.length===e.size*a)for(let r=0;r<e.size;++r){const i=e.features.slice(r*s,(r+1)*s),n=e.labels.slice(r*a,(r+1)*a);this.dataset.add(i,n),this.copyExampleToWasm_(i,n)}e.weights.length===this.weightCount_&&this.setWeights(new Float32Array(e.weights)),this.lastLoss_=e.lastLoss,d.__setState(p(r=>{r.exampleCount=this.dataset.size,r.lastLoss=this.lastLoss_}))}catch(t){console.warn("[wasm-iml] tryLoadFromStorage failed:",t)}}publishWeights_(){const t=this.getWeights();d.__setWeights(t)}}export{b as WasmIML};
|
|
//# sourceMappingURL=wasm-iml-FZSgVMmn.js.map
|