@johnhenry/mallory-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
|
@@ -0,0 +1,1153 @@
|
|
|
1
|
+
// The `tensor` helper: an n-dimensional array of numbers as a value. A tensor is a plain object,
|
|
2
|
+
// `{ kind: "tensor", shape, dtype, data }`, where `data` is a typed array in row-major order, so it
|
|
3
|
+
// crosses panes as the same object (no JSON copy: nothing turns it into a list of numbers), survives a
|
|
4
|
+
// structured clone, and is shown by the inspector as its shape, dtype and a heatmap. This file also reads
|
|
5
|
+
// and writes NumPy `.npy` files and reads the header of a safetensors file with range reads (shapes without
|
|
6
|
+
// the weights). Pure: no imports, no DOM, no Node built-ins; it is the module Node imports
|
|
7
|
+
// (src/tensor/index.js) and the text the sandbox Worker loads as `mallory:tensor` (src/runtime/sources.js).
|
|
8
|
+
// It reads no device, no clock and makes no request of its own: a URL is fetched by the `fetch` it is given.
|
|
9
|
+
|
|
10
|
+
export const version = 1;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Every dtype: its typed array, bytes per element, NumPy's code and safetensors' code. 64-bit integers are
|
|
14
|
+
* BigInt arrays, as in JavaScript; `bool` is a byte that is 0 or 1.
|
|
15
|
+
*/
|
|
16
|
+
export const DTYPES = Object.freeze({
|
|
17
|
+
float32: { array: Float32Array, size: 4, npy: "f4", st: "F32", float: true },
|
|
18
|
+
float64: { array: Float64Array, size: 8, npy: "f8", st: "F64", float: true },
|
|
19
|
+
int8: { array: Int8Array, size: 1, npy: "i1", st: "I8" },
|
|
20
|
+
int16: { array: Int16Array, size: 2, npy: "i2", st: "I16" },
|
|
21
|
+
int32: { array: Int32Array, size: 4, npy: "i4", st: "I32" },
|
|
22
|
+
int64: { array: BigInt64Array, size: 8, npy: "i8", st: "I64", big: true },
|
|
23
|
+
uint8: { array: Uint8Array, size: 1, npy: "u1", st: "U8" },
|
|
24
|
+
uint16: { array: Uint16Array, size: 2, npy: "u2", st: "U16" },
|
|
25
|
+
uint32: { array: Uint32Array, size: 4, npy: "u4", st: "U32" },
|
|
26
|
+
uint64: { array: BigUint64Array, size: 8, npy: "u8", st: "U64", big: true },
|
|
27
|
+
bool: { array: Uint8Array, size: 1, npy: "b1", st: "BOOL" },
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
/** The dtype names, in the order DTYPES lists them. */
|
|
31
|
+
export const DTYPE_NAMES = Object.freeze(Object.keys(DTYPES));
|
|
32
|
+
|
|
33
|
+
/** The largest number of elements a tensor made here may have (a guard against a shape typo). */
|
|
34
|
+
export const MAX_ELEMENTS = 2 ** 28;
|
|
35
|
+
|
|
36
|
+
const LITTLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
|
|
37
|
+
const fail = (message) => {
|
|
38
|
+
throw new Error(message);
|
|
39
|
+
};
|
|
40
|
+
const isInt = (n) => Number.isInteger(n) && n >= 0;
|
|
41
|
+
|
|
42
|
+
const dtypeInfo = (dtype) => DTYPES[dtype] ?? fail(`unknown dtype "${dtype}" (one of ${DTYPE_NAMES.join(", ")})`);
|
|
43
|
+
|
|
44
|
+
/** The dtype name of a typed array (a Uint8Array is "uint8"), or undefined. */
|
|
45
|
+
export function dtypeOfArray(array) {
|
|
46
|
+
if (!ArrayBuffer.isView(array)) return undefined;
|
|
47
|
+
for (const name of DTYPE_NAMES) if (name !== "bool" && array.constructor === DTYPES[name].array) return name;
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Is this value a tensor made here (or the plain object a structured clone of one gives)? */
|
|
52
|
+
export function isTensor(value) {
|
|
53
|
+
return Boolean(value) && typeof value === "object" && value.kind === "tensor" && Array.isArray(value.shape) && value.shape.every(isInt) && typeof value.dtype === "string" && value.dtype in DTYPES && ArrayBuffer.isView(value.data) && value.data.length === sizeOf(value.shape);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The number of elements a shape holds (1 for the empty shape, a scalar). */
|
|
57
|
+
export function sizeOf(shape) {
|
|
58
|
+
let n = 1;
|
|
59
|
+
for (const d of shape) n *= d;
|
|
60
|
+
return n;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function checkShape(shape) {
|
|
64
|
+
if (!Array.isArray(shape) || !shape.every(isInt)) fail(`a shape is a list of whole numbers (got ${JSON.stringify(shape)})`);
|
|
65
|
+
if (sizeOf(shape) > MAX_ELEMENTS) fail(`a tensor of shape [${shape}] has more than ${MAX_ELEMENTS} elements`);
|
|
66
|
+
return shape.slice();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function build(shape, dtype, data) {
|
|
70
|
+
return Object.freeze({ kind: "tensor", shape: Object.freeze(shape), dtype, data });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const stridesOf = (shape) => {
|
|
74
|
+
const out = new Array(shape.length);
|
|
75
|
+
let s = 1;
|
|
76
|
+
for (let i = shape.length - 1; i >= 0; i--) (out[i] = s), (s *= shape[i]);
|
|
77
|
+
return out;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
function allocate(shape, dtype) {
|
|
81
|
+
const info = dtypeInfo(dtype);
|
|
82
|
+
return new info.array(sizeOf(shape));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function tensorOf(value, name = "a tensor") {
|
|
86
|
+
return isTensor(value) ? value : fail(`${name} is expected to be a tensor (got ${value === null ? "null" : typeof value})`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---------------------------------------------------------------------------------------------- making
|
|
90
|
+
|
|
91
|
+
function inferShape(data) {
|
|
92
|
+
const shape = [];
|
|
93
|
+
let at = data;
|
|
94
|
+
while (Array.isArray(at)) {
|
|
95
|
+
shape.push(at.length);
|
|
96
|
+
if (!at.length) break;
|
|
97
|
+
at = at[0];
|
|
98
|
+
}
|
|
99
|
+
return shape;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function flatten(data, shape, out, depth = 0, at = { i: 0 }) {
|
|
103
|
+
if (depth === shape.length) {
|
|
104
|
+
if (Array.isArray(data)) fail(`the nested lists are ragged: expected a number at depth ${depth}, found a list`);
|
|
105
|
+
out[at.i++] = data;
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!Array.isArray(data) || data.length !== shape[depth]) fail(`the nested lists are ragged: expected ${shape[depth]} items at depth ${depth}, found ${Array.isArray(data) ? data.length : "a non-list"}`);
|
|
109
|
+
for (const item of data) flatten(item, shape, out, depth + 1, at);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function convert(from, dtype) {
|
|
113
|
+
const info = dtypeInfo(dtype);
|
|
114
|
+
const to = new info.array(from.length);
|
|
115
|
+
const bigFrom = typeof from[0] === "bigint" || from instanceof BigInt64Array || from instanceof BigUint64Array;
|
|
116
|
+
for (let i = 0; i < from.length; i++) {
|
|
117
|
+
let v = from[i];
|
|
118
|
+
if (info.big) v = typeof v === "bigint" ? v : BigInt(Math.trunc(Number(v)));
|
|
119
|
+
else if (bigFrom || typeof v === "bigint") v = Number(v);
|
|
120
|
+
if (dtype === "bool") v = v ? 1 : 0;
|
|
121
|
+
to[i] = v;
|
|
122
|
+
}
|
|
123
|
+
return to;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* A tensor from nested lists (`[[1, 2], [3, 4]]`), a flat list or typed array with a `shape`, a number (a scalar), or
|
|
128
|
+
* another tensor. `dtype` defaults to what the data is (a typed array's own; float64 for numbers, int64 for BigInts,
|
|
129
|
+
* bool for booleans). The data is copied unless `copy: false` and the typed array already has the dtype.
|
|
130
|
+
* @param {*} data
|
|
131
|
+
* @param {{ shape?: number[], dtype?: string, copy?: boolean }} [options]
|
|
132
|
+
*/
|
|
133
|
+
export function from(data, { shape, dtype, copy = true } = {}) {
|
|
134
|
+
if (isTensor(data)) {
|
|
135
|
+
if (shape) return reshape(dtype ? astype(data, dtype) : data, shape);
|
|
136
|
+
return dtype && dtype !== data.dtype ? astype(data, dtype) : data;
|
|
137
|
+
}
|
|
138
|
+
if (data instanceof Uint8Array && data.constructor !== Uint8Array) data = new Uint8Array(data.buffer, data.byteOffset, data.length);
|
|
139
|
+
if (ArrayBuffer.isView(data) && !(data instanceof DataView)) {
|
|
140
|
+
const own = dtypeOfArray(data) ?? fail(`can't make a tensor from a ${data.constructor.name}`);
|
|
141
|
+
const out = shape ? checkShape(shape) : [data.length];
|
|
142
|
+
if (sizeOf(out) !== data.length) fail(`shape [${out}] holds ${sizeOf(out)} elements but the data has ${data.length}`);
|
|
143
|
+
const want = dtype ?? own;
|
|
144
|
+
const kept = want === own && !copy ? data : want === own ? data.slice() : convert(data, want);
|
|
145
|
+
return build(out, want, kept);
|
|
146
|
+
}
|
|
147
|
+
const inferred = Array.isArray(data) ? inferShape(data) : [];
|
|
148
|
+
const out = shape ? checkShape(shape) : checkShape(inferred);
|
|
149
|
+
const flat = [];
|
|
150
|
+
if (Array.isArray(data) && shape && inferred.length !== out.length) {
|
|
151
|
+
// a flat list given a shape
|
|
152
|
+
if (data.length !== sizeOf(out)) fail(`shape [${out}] holds ${sizeOf(out)} elements but the data has ${data.length}`);
|
|
153
|
+
for (const v of data) flat.push(v);
|
|
154
|
+
} else flatten(data, out, flat);
|
|
155
|
+
let want = dtype;
|
|
156
|
+
if (!want) {
|
|
157
|
+
const first = flat.find((v) => v !== undefined);
|
|
158
|
+
want = typeof first === "bigint" ? "int64" : typeof first === "boolean" ? "bool" : "float64";
|
|
159
|
+
}
|
|
160
|
+
const info = dtypeInfo(want);
|
|
161
|
+
const array = new info.array(flat.length);
|
|
162
|
+
for (let i = 0; i < flat.length; i++) {
|
|
163
|
+
let v = flat[i];
|
|
164
|
+
if (typeof v === "boolean") v = v ? 1 : 0;
|
|
165
|
+
if (info.big) v = typeof v === "bigint" ? v : Number.isInteger(v) ? BigInt(v) : fail(`element ${i} (${v}) isn't a whole number, so it can't be ${want}`);
|
|
166
|
+
else if (typeof v === "bigint") v = Number(v);
|
|
167
|
+
else if (typeof v !== "number") fail(`element ${i} isn't a number (${typeof v})`);
|
|
168
|
+
if (want === "bool") v = v ? 1 : 0;
|
|
169
|
+
array[i] = v;
|
|
170
|
+
}
|
|
171
|
+
return build(out, want, array);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** A tensor of zeros (`tensor.zeros([2, 3])`, `dtype` float64 unless given). */
|
|
175
|
+
export function zeros(shape, dtype = "float64") {
|
|
176
|
+
const s = checkShape(shape);
|
|
177
|
+
return build(s, dtype, allocate(s, dtype));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** A tensor filled with `value`. */
|
|
181
|
+
export function full(shape, value, dtype = "float64") {
|
|
182
|
+
const s = checkShape(shape);
|
|
183
|
+
const array = allocate(s, dtype);
|
|
184
|
+
array.fill(dtypeInfo(dtype).big ? BigInt(value) : dtype === "bool" ? (value ? 1 : 0) : value);
|
|
185
|
+
return build(s, dtype, array);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** A tensor of ones. */
|
|
189
|
+
export const ones = (shape, dtype = "float64") => full(shape, 1, dtype);
|
|
190
|
+
|
|
191
|
+
/** `arange(n)` is 0 … n-1; `arange(start, stop, step = 1)` like NumPy's. */
|
|
192
|
+
export function arange(start, stop, step = 1, dtype = "float64") {
|
|
193
|
+
if (stop === undefined) [start, stop] = [0, start];
|
|
194
|
+
if (!step) fail("arange: step can't be 0");
|
|
195
|
+
const n = Math.max(0, Math.ceil((stop - start) / step));
|
|
196
|
+
if (n > MAX_ELEMENTS) fail(`arange: more than ${MAX_ELEMENTS} elements`);
|
|
197
|
+
const array = allocate([n], dtype);
|
|
198
|
+
for (let i = 0; i < n; i++) array[i] = dtypeInfo(dtype).big ? BigInt(start + i * step) : start + i * step;
|
|
199
|
+
return build([n], dtype, array);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** `count` evenly spaced numbers from `start` to `stop`, both included. */
|
|
203
|
+
export function linspace(start, stop, count = 50, dtype = "float64") {
|
|
204
|
+
if (!isInt(count)) fail("linspace: count is a whole number");
|
|
205
|
+
const array = allocate([count], dtype);
|
|
206
|
+
for (let i = 0; i < count; i++) array[i] = count === 1 ? start : start + ((stop - start) * i) / (count - 1);
|
|
207
|
+
return build([count], dtype, array);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** A seeded random number generator (mulberry32): `next()` is in [0, 1). The same seed gives the same numbers on a machine. */
|
|
211
|
+
export function rng(seed = 1) {
|
|
212
|
+
let a = seed >>> 0;
|
|
213
|
+
const next = () => {
|
|
214
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
215
|
+
let t = a;
|
|
216
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
217
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
218
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
219
|
+
};
|
|
220
|
+
const normal = () => Math.sqrt(-2 * Math.log(1 - next())) * Math.cos(2 * Math.PI * next());
|
|
221
|
+
return { next, normal };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Random numbers: `tensor.random([3, 3], { seed: 7 })` uniform in [0, 1), or `{ dist: "normal" }` (mean 0, deviation 1).
|
|
226
|
+
* Without a `seed` the numbers come from a fixed seed (1): a tensor is a value, and the same code gives the same tensor.
|
|
227
|
+
*/
|
|
228
|
+
export function random(shape, { seed = 1, dist = "uniform", dtype = "float64" } = {}) {
|
|
229
|
+
const s = checkShape(shape);
|
|
230
|
+
const gen = rng(seed);
|
|
231
|
+
const array = allocate(s, dtype);
|
|
232
|
+
const draw = dist === "normal" ? gen.normal : dist === "uniform" ? gen.next : fail(`random: dist is "uniform" or "normal"`);
|
|
233
|
+
for (let i = 0; i < array.length; i++) array[i] = draw();
|
|
234
|
+
return build(s, dtype, array);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ---------------------------------------------------------------------------------------------- shape
|
|
238
|
+
|
|
239
|
+
/** The same elements in a new shape; one dimension may be -1 (worked out). Shares the data. */
|
|
240
|
+
export function reshape(t, shape) {
|
|
241
|
+
tensorOf(t);
|
|
242
|
+
const want = shape.slice();
|
|
243
|
+
const hole = want.indexOf(-1);
|
|
244
|
+
if (hole >= 0) {
|
|
245
|
+
const rest = want.reduce((n, d, i) => (i === hole ? n : n * d), 1);
|
|
246
|
+
if (!rest || t.data.length % rest) fail(`can't reshape ${t.data.length} elements into [${shape}]`);
|
|
247
|
+
want[hole] = t.data.length / rest;
|
|
248
|
+
}
|
|
249
|
+
checkShape(want);
|
|
250
|
+
if (sizeOf(want) !== t.data.length) fail(`can't reshape ${t.data.length} elements into [${shape}]`);
|
|
251
|
+
return build(want, t.dtype, t.data);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** A flat tensor of the same elements. */
|
|
255
|
+
export const flat = (t) => reshape(t, [-1]);
|
|
256
|
+
|
|
257
|
+
/** Reorder the axes (default: reverse them). A copy. */
|
|
258
|
+
export function transpose(t, axes) {
|
|
259
|
+
tensorOf(t);
|
|
260
|
+
const n = t.shape.length;
|
|
261
|
+
const order = axes ?? Array.from({ length: n }, (_, i) => n - 1 - i);
|
|
262
|
+
if (order.length !== n || new Set(order).size !== n || !order.every((a) => Number.isInteger(a) && a >= 0 && a < n)) fail(`transpose: axes must be a permutation of 0 … ${n - 1}`);
|
|
263
|
+
const shape = order.map((a) => t.shape[a]);
|
|
264
|
+
const out = allocate(shape, t.dtype);
|
|
265
|
+
const src = stridesOf(t.shape);
|
|
266
|
+
const strides = order.map((a) => src[a]);
|
|
267
|
+
const counter = new Array(n).fill(0);
|
|
268
|
+
let from_ = 0;
|
|
269
|
+
for (let i = 0; i < out.length; i++) {
|
|
270
|
+
out[i] = t.data[from_];
|
|
271
|
+
for (let d = n - 1; d >= 0; d--) {
|
|
272
|
+
counter[d]++;
|
|
273
|
+
from_ += strides[d];
|
|
274
|
+
if (counter[d] < shape[d]) break;
|
|
275
|
+
from_ -= strides[d] * shape[d];
|
|
276
|
+
counter[d] = 0;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return build(shape, t.dtype, out);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Elements `start` to `end` (exclusive; negative counts from the end) along `axis` (default 0). A copy. */
|
|
283
|
+
export function slice(t, axis, start = 0, end) {
|
|
284
|
+
tensorOf(t);
|
|
285
|
+
if (!Number.isInteger(axis) || axis < 0 || axis >= t.shape.length) fail(`slice: axis ${axis} isn't one of 0 … ${t.shape.length - 1}`);
|
|
286
|
+
const n = t.shape[axis];
|
|
287
|
+
const norm = (v, dflt) => (v === undefined ? dflt : Math.min(n, Math.max(0, v < 0 ? n + v : v)));
|
|
288
|
+
const a = norm(start, 0);
|
|
289
|
+
const b = Math.max(a, norm(end, n));
|
|
290
|
+
const shape = t.shape.slice();
|
|
291
|
+
shape[axis] = b - a;
|
|
292
|
+
const outer = sizeOf(t.shape.slice(0, axis));
|
|
293
|
+
const inner = sizeOf(t.shape.slice(axis + 1));
|
|
294
|
+
const out = allocate(shape, t.dtype);
|
|
295
|
+
let at = 0;
|
|
296
|
+
for (let o = 0; o < outer; o++) {
|
|
297
|
+
const from_ = (o * n + a) * inner;
|
|
298
|
+
const len = (b - a) * inner;
|
|
299
|
+
out.set(t.data.subarray(from_, from_ + len), at);
|
|
300
|
+
at += len;
|
|
301
|
+
}
|
|
302
|
+
return build(shape, t.dtype, out);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** The `i`th item along the first axis, as a tensor one dimension shorter (a row of a matrix). A copy. */
|
|
306
|
+
export function at(t, i) {
|
|
307
|
+
tensorOf(t);
|
|
308
|
+
if (!t.shape.length) fail("at: a scalar has no items");
|
|
309
|
+
const n = t.shape[0];
|
|
310
|
+
const k = i < 0 ? n + i : i;
|
|
311
|
+
if (!Number.isInteger(k) || k < 0 || k >= n) fail(`at: index ${i} is outside 0 … ${n - 1}`);
|
|
312
|
+
return reshape(slice(t, 0, k, k + 1), t.shape.slice(1));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** One element by its indices: `get(t, 1, 2)`. */
|
|
316
|
+
export function get(t, ...index) {
|
|
317
|
+
tensorOf(t);
|
|
318
|
+
if (index.length !== t.shape.length) fail(`get: ${t.shape.length} indices expected for shape [${t.shape}], got ${index.length}`);
|
|
319
|
+
let k = 0;
|
|
320
|
+
for (let d = 0; d < index.length; d++) {
|
|
321
|
+
const i = index[d] < 0 ? t.shape[d] + index[d] : index[d];
|
|
322
|
+
if (!Number.isInteger(i) || i < 0 || i >= t.shape[d]) fail(`get: index ${index[d]} is outside 0 … ${t.shape[d] - 1} on axis ${d}`);
|
|
323
|
+
k = k * t.shape[d] + i;
|
|
324
|
+
}
|
|
325
|
+
return t.data[k];
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Join tensors along an existing axis (default 0); the other dimensions must match. */
|
|
329
|
+
export function concat(list, axis = 0) {
|
|
330
|
+
if (!Array.isArray(list) || !list.length) fail("concat: a non-empty list of tensors");
|
|
331
|
+
list.forEach((t, i) => tensorOf(t, `item ${i}`));
|
|
332
|
+
const first = list[0];
|
|
333
|
+
if (!Number.isInteger(axis) || axis < 0 || axis >= first.shape.length) fail(`concat: axis ${axis} isn't one of 0 … ${first.shape.length - 1}`);
|
|
334
|
+
const dtype = list.every((t) => t.dtype === first.dtype) ? first.dtype : "float64";
|
|
335
|
+
for (const t of list) {
|
|
336
|
+
if (t.shape.length !== first.shape.length || t.shape.some((d, i) => i !== axis && d !== first.shape[i])) fail(`concat: shapes [${first.shape}] and [${t.shape}] differ off axis ${axis}`);
|
|
337
|
+
}
|
|
338
|
+
const shape = first.shape.slice();
|
|
339
|
+
shape[axis] = list.reduce((n, t) => n + t.shape[axis], 0);
|
|
340
|
+
const outer = sizeOf(first.shape.slice(0, axis));
|
|
341
|
+
const inner = sizeOf(first.shape.slice(axis + 1));
|
|
342
|
+
const out = allocate(shape, dtype);
|
|
343
|
+
let at_ = 0;
|
|
344
|
+
for (let o = 0; o < outer; o++) {
|
|
345
|
+
for (const t of list) {
|
|
346
|
+
const len = t.shape[axis] * inner;
|
|
347
|
+
const part = t.data.subarray(o * len, o * len + len);
|
|
348
|
+
if (t.dtype === dtype) out.set(part, at_);
|
|
349
|
+
else for (let i = 0; i < len; i++) out[at_ + i] = Number(part[i]);
|
|
350
|
+
at_ += len;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return build(shape, dtype, out);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** The tensor as another dtype (floats are truncated towards zero going to an integer type). */
|
|
357
|
+
export function astype(t, dtype) {
|
|
358
|
+
tensorOf(t);
|
|
359
|
+
dtypeInfo(dtype);
|
|
360
|
+
if (dtype === t.dtype) return t;
|
|
361
|
+
const info = DTYPES[dtype];
|
|
362
|
+
const from_ = t.data;
|
|
363
|
+
const to = new info.array(from_.length);
|
|
364
|
+
const bigFrom = DTYPES[t.dtype].big;
|
|
365
|
+
for (let i = 0; i < from_.length; i++) {
|
|
366
|
+
let v = from_[i];
|
|
367
|
+
if (info.big) v = bigFrom ? v : BigInt(Math.trunc(v) || 0);
|
|
368
|
+
else {
|
|
369
|
+
if (bigFrom) v = Number(v);
|
|
370
|
+
if (dtype === "bool") v = v ? 1 : 0;
|
|
371
|
+
else if (!info.float) v = Math.trunc(v);
|
|
372
|
+
}
|
|
373
|
+
to[i] = v;
|
|
374
|
+
}
|
|
375
|
+
return build(t.shape.slice(), dtype, to);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** The tensor as nested JavaScript lists (a scalar as a number). 64-bit integers stay BigInts; a bool is true/false. */
|
|
379
|
+
export function toArray(t) {
|
|
380
|
+
tensorOf(t);
|
|
381
|
+
const isBool = t.dtype === "bool";
|
|
382
|
+
const walk = (d, offset) => {
|
|
383
|
+
if (d === t.shape.length) return isBool ? Boolean(t.data[offset]) : t.data[offset];
|
|
384
|
+
const step = sizeOf(t.shape.slice(d + 1));
|
|
385
|
+
return Array.from({ length: t.shape[d] }, (_, i) => walk(d + 1, offset + i * step));
|
|
386
|
+
};
|
|
387
|
+
return walk(0, 0);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// ---------------------------------------------------------------------------------------------- arithmetic
|
|
391
|
+
|
|
392
|
+
const FLOAT_ORDER = { float64: 2, float32: 1 };
|
|
393
|
+
function promote(a, b, always = false) {
|
|
394
|
+
if (DTYPES[a].big || DTYPES[b].big) fail(`arithmetic on ${DTYPES[a].big ? a : b} isn't supported: convert it with tensor.astype(t, "float64") first`);
|
|
395
|
+
if (a === b) return a;
|
|
396
|
+
const fa = FLOAT_ORDER[a] ?? 0;
|
|
397
|
+
const fb = FLOAT_ORDER[b] ?? 0;
|
|
398
|
+
if (fa && fb) return fa >= fb ? a : b;
|
|
399
|
+
return always ? a : "float64";
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function broadcastShape(a, b) {
|
|
403
|
+
const n = Math.max(a.length, b.length);
|
|
404
|
+
const out = new Array(n);
|
|
405
|
+
for (let i = 0; i < n; i++) {
|
|
406
|
+
const x = a[a.length - n + i] ?? 1;
|
|
407
|
+
const y = b[b.length - n + i] ?? 1;
|
|
408
|
+
if (x !== y && x !== 1 && y !== 1) fail(`can't broadcast shapes [${a}] and [${b}]`);
|
|
409
|
+
out[i] = x === 1 ? y : x;
|
|
410
|
+
}
|
|
411
|
+
return out;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function broadcastStrides(shape, out) {
|
|
415
|
+
const n = out.length;
|
|
416
|
+
const own = stridesOf(shape);
|
|
417
|
+
return out.map((d, i) => {
|
|
418
|
+
const j = i - (n - shape.length);
|
|
419
|
+
return j < 0 || shape[j] === 1 ? 0 : own[j];
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function binary(a, b, fn, { floatOut = false, name = "an operation" } = {}) {
|
|
424
|
+
const ta = typeof a === "number" ? null : tensorOf(a, `the first argument of ${name}`);
|
|
425
|
+
const tb = typeof b === "number" ? null : tensorOf(b, `the second argument of ${name}`);
|
|
426
|
+
if (!ta && !tb) return fn(a, b);
|
|
427
|
+
const arith = (d) => (d === "bool" ? "uint8" : d);
|
|
428
|
+
let finalType;
|
|
429
|
+
if (ta && tb) finalType = promote(arith(ta.dtype), arith(tb.dtype));
|
|
430
|
+
else {
|
|
431
|
+
const t = ta ?? tb;
|
|
432
|
+
const n = ta ? b : a;
|
|
433
|
+
// A number beside a tensor keeps the tensor's dtype (a float one always; an integer one when the number is whole).
|
|
434
|
+
finalType = DTYPES[t.dtype].float || Number.isInteger(n) ? arith(t.dtype) : "float64";
|
|
435
|
+
if (DTYPES[finalType].big) promote(finalType, finalType, true);
|
|
436
|
+
}
|
|
437
|
+
if (floatOut && !DTYPES[finalType].float) finalType = "float64";
|
|
438
|
+
const shapeA = ta ? ta.shape : [];
|
|
439
|
+
const shapeB = tb ? tb.shape : [];
|
|
440
|
+
const shape = broadcastShape(shapeA, shapeB);
|
|
441
|
+
const out = allocate(shape, finalType);
|
|
442
|
+
const xa = ta ? ta.data : null;
|
|
443
|
+
const xb = tb ? tb.data : null;
|
|
444
|
+
const same = ta && tb && ta.shape.length === tb.shape.length && ta.shape.every((d, i) => d === tb.shape[i]);
|
|
445
|
+
if (same) for (let i = 0; i < out.length; i++) out[i] = fn(xa[i], xb[i]);
|
|
446
|
+
else if (!ta) for (let i = 0; i < out.length; i++) out[i] = fn(a, xb[i]);
|
|
447
|
+
else if (!tb) for (let i = 0; i < out.length; i++) out[i] = fn(xa[i], b);
|
|
448
|
+
else {
|
|
449
|
+
const sa = broadcastStrides(ta.shape, shape);
|
|
450
|
+
const sb = broadcastStrides(tb.shape, shape);
|
|
451
|
+
const counter = new Array(shape.length).fill(0);
|
|
452
|
+
let ia = 0;
|
|
453
|
+
let ib = 0;
|
|
454
|
+
for (let i = 0; i < out.length; i++) {
|
|
455
|
+
out[i] = fn(xa[ia], xb[ib]);
|
|
456
|
+
for (let d = shape.length - 1; d >= 0; d--) {
|
|
457
|
+
counter[d]++;
|
|
458
|
+
ia += sa[d];
|
|
459
|
+
ib += sb[d];
|
|
460
|
+
if (counter[d] < shape[d]) break;
|
|
461
|
+
ia -= sa[d] * shape[d];
|
|
462
|
+
ib -= sb[d] * shape[d];
|
|
463
|
+
counter[d] = 0;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
return build(shape, finalType, out);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Elementwise sum, with NumPy's broadcasting (shapes line up from the right; a 1 stretches). Either side may be a number. */
|
|
471
|
+
export const add = (a, b) => binary(a, b, (x, y) => x + y, { name: "add" });
|
|
472
|
+
/** Elementwise difference. */
|
|
473
|
+
export const sub = (a, b) => binary(a, b, (x, y) => x - y, { name: "sub" });
|
|
474
|
+
/** Elementwise product. */
|
|
475
|
+
export const mul = (a, b) => binary(a, b, (x, y) => x * y, { name: "mul" });
|
|
476
|
+
/** Elementwise quotient (a float tensor). */
|
|
477
|
+
export const div = (a, b) => binary(a, b, (x, y) => x / y, { floatOut: true, name: "div" });
|
|
478
|
+
/** Elementwise power. */
|
|
479
|
+
export const pow = (a, b) => binary(a, b, (x, y) => x ** y, { floatOut: true, name: "pow" });
|
|
480
|
+
/** Elementwise larger of the two. */
|
|
481
|
+
export const maximum = (a, b) => binary(a, b, (x, y) => (x > y || Number.isNaN(x) ? x : y), { name: "maximum" });
|
|
482
|
+
/** Elementwise smaller of the two. */
|
|
483
|
+
export const minimum = (a, b) => binary(a, b, (x, y) => (x < y || Number.isNaN(x) ? x : y), { name: "minimum" });
|
|
484
|
+
/** Multiply every element by a number. */
|
|
485
|
+
export const scale = (t, k) => mul(t, k);
|
|
486
|
+
|
|
487
|
+
/** `fn(value, index)` of every element, as a tensor of `dtype` (default: the tensor's own, or float64 for an integer one). */
|
|
488
|
+
export function map(t, fn, dtype) {
|
|
489
|
+
tensorOf(t);
|
|
490
|
+
const out_ = dtype ?? (DTYPES[t.dtype].big || t.dtype === "bool" ? "float64" : t.dtype);
|
|
491
|
+
const out = allocate(t.shape, out_);
|
|
492
|
+
const big = DTYPES[t.dtype].big;
|
|
493
|
+
for (let i = 0; i < out.length; i++) out[i] = fn(big ? Number(t.data[i]) : t.data[i], i);
|
|
494
|
+
return build(t.shape.slice(), out_, out);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const unaryFloat = (fn) => (t) => map(t, fn, FLOAT_ORDER[tensorOf(t).dtype] ? t.dtype : "float64");
|
|
498
|
+
export const neg = (t) => map(t, (x) => -x);
|
|
499
|
+
export const abs = (t) => map(t, Math.abs);
|
|
500
|
+
export const square = (t) => map(t, (x) => x * x);
|
|
501
|
+
export const sqrt = unaryFloat(Math.sqrt);
|
|
502
|
+
export const exp = unaryFloat(Math.exp);
|
|
503
|
+
export const log = unaryFloat(Math.log);
|
|
504
|
+
export const tanh = unaryFloat(Math.tanh);
|
|
505
|
+
export const sin = unaryFloat(Math.sin);
|
|
506
|
+
export const cos = unaryFloat(Math.cos);
|
|
507
|
+
export const sigmoid = unaryFloat((x) => 1 / (1 + Math.exp(-x)));
|
|
508
|
+
export const relu = (t) => map(t, (x) => (x > 0 ? x : 0));
|
|
509
|
+
|
|
510
|
+
/** Matrix product of two matrices (`[n, k] · [k, m]`), a matrix and a vector, or two vectors (a number). */
|
|
511
|
+
export function matmul(a, b) {
|
|
512
|
+
tensorOf(a, "the first argument of matmul");
|
|
513
|
+
tensorOf(b, "the second argument of matmul");
|
|
514
|
+
if (a.shape.length > 2 || b.shape.length > 2 || !a.shape.length || !b.shape.length) fail(`matmul: vectors and matrices only (shapes [${a.shape}] and [${b.shape}])`);
|
|
515
|
+
const A = a.shape.length === 1 ? [1, a.shape[0]] : a.shape;
|
|
516
|
+
const B = b.shape.length === 1 ? [b.shape[0], 1] : b.shape;
|
|
517
|
+
if (A[1] !== B[0]) fail(`matmul: the inner sizes differ (shapes [${a.shape}] and [${b.shape}])`);
|
|
518
|
+
const dtype = promote(a.dtype, b.dtype, false);
|
|
519
|
+
const [n, k] = A;
|
|
520
|
+
const m = B[1];
|
|
521
|
+
const out = allocate([n, m], dtype);
|
|
522
|
+
const x = a.data;
|
|
523
|
+
const y = b.data;
|
|
524
|
+
const acc = new Float64Array(m);
|
|
525
|
+
for (let i = 0; i < n; i++) {
|
|
526
|
+
acc.fill(0);
|
|
527
|
+
for (let p = 0; p < k; p++) {
|
|
528
|
+
const v = x[i * k + p];
|
|
529
|
+
if (v === 0) continue;
|
|
530
|
+
const row = p * m;
|
|
531
|
+
for (let j = 0; j < m; j++) acc[j] += v * y[row + j];
|
|
532
|
+
}
|
|
533
|
+
for (let j = 0; j < m; j++) out[i * m + j] = acc[j];
|
|
534
|
+
}
|
|
535
|
+
const shape = a.shape.length === 1 && b.shape.length === 1 ? [] : a.shape.length === 1 ? [m] : b.shape.length === 1 ? [n] : [n, m];
|
|
536
|
+
return build(shape, dtype, out);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** The dot product of two tensors of the same shape (a number), or `matmul` for matrices. */
|
|
540
|
+
export function dot(a, b) {
|
|
541
|
+
const r = matmul(a, b);
|
|
542
|
+
return r.shape.length ? r : r.data[0];
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// ---------------------------------------------------------------------------------------------- reductions
|
|
546
|
+
|
|
547
|
+
function reduce(t, axis, keepdims, init, step, finish, outType) {
|
|
548
|
+
tensorOf(t);
|
|
549
|
+
const big = DTYPES[t.dtype].big;
|
|
550
|
+
const data = t.data;
|
|
551
|
+
if (axis === undefined || axis === null) {
|
|
552
|
+
let acc = init;
|
|
553
|
+
for (let i = 0; i < data.length; i++) acc = step(acc, big ? Number(data[i]) : data[i], i);
|
|
554
|
+
const r = finish ? finish(acc, data.length) : acc;
|
|
555
|
+
if (!keepdims) return r;
|
|
556
|
+
return build(t.shape.map(() => 1), outType ?? "float64", Float64Array.of(r));
|
|
557
|
+
}
|
|
558
|
+
const n = t.shape.length;
|
|
559
|
+
const ax = axis < 0 ? n + axis : axis;
|
|
560
|
+
if (!Number.isInteger(ax) || ax < 0 || ax >= n) fail(`axis ${axis} isn't one of 0 … ${n - 1} for shape [${t.shape}]`);
|
|
561
|
+
const outer = sizeOf(t.shape.slice(0, ax));
|
|
562
|
+
const len = t.shape[ax];
|
|
563
|
+
const inner = sizeOf(t.shape.slice(ax + 1));
|
|
564
|
+
const shape = t.shape.slice();
|
|
565
|
+
keepdims ? (shape[ax] = 1) : shape.splice(ax, 1);
|
|
566
|
+
const out = allocate(shape, outType ?? "float64");
|
|
567
|
+
for (let o = 0; o < outer; o++) {
|
|
568
|
+
for (let j = 0; j < inner; j++) {
|
|
569
|
+
let acc = init;
|
|
570
|
+
for (let i = 0; i < len; i++) {
|
|
571
|
+
const v = data[(o * len + i) * inner + j];
|
|
572
|
+
acc = step(acc, big ? Number(v) : v, i);
|
|
573
|
+
}
|
|
574
|
+
out[o * inner + j] = finish ? finish(acc, len) : acc;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
return build(shape, outType ?? "float64", out);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** The sum of all elements (a number), or along `axis` (a tensor); `{ keepdims: true }` keeps the axis as size 1. */
|
|
581
|
+
export const sum = (t, axis, { keepdims = false } = {}) => reduce(t, axis, keepdims, 0, (a, v) => a + v, null);
|
|
582
|
+
/** The mean of all elements, or along `axis`. */
|
|
583
|
+
export const mean = (t, axis, { keepdims = false } = {}) => reduce(t, axis, keepdims, 0, (a, v) => a + v, (a, n) => a / n);
|
|
584
|
+
/** The smallest element, or along `axis`. */
|
|
585
|
+
export const min = (t, axis, { keepdims = false } = {}) => reduce(t, axis, keepdims, Infinity, (a, v) => (v < a || Number.isNaN(v) ? v : a), null);
|
|
586
|
+
/** The largest element, or along `axis`. */
|
|
587
|
+
export const max = (t, axis, { keepdims = false } = {}) => reduce(t, axis, keepdims, -Infinity, (a, v) => (v > a || Number.isNaN(v) ? v : a), null);
|
|
588
|
+
/** The position of the largest element along `axis` (default: in the flattened tensor). */
|
|
589
|
+
export function argmax(t, axis) {
|
|
590
|
+
tensorOf(t);
|
|
591
|
+
if (axis === undefined) {
|
|
592
|
+
let best = 0;
|
|
593
|
+
for (let i = 1; i < t.data.length; i++) if (t.data[i] > t.data[best]) best = i;
|
|
594
|
+
return best;
|
|
595
|
+
}
|
|
596
|
+
const r = reduce(t, axis, false, { v: -Infinity, at: 0 }, (a, v, i) => (v > a.v ? { v, at: i } : a), (a) => a.at, "float64");
|
|
597
|
+
return astype(r, "int32");
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** Softmax along `axis` (default: the last), a float tensor whose slices sum to 1. */
|
|
601
|
+
export function softmax(t, axis = -1) {
|
|
602
|
+
tensorOf(t);
|
|
603
|
+
const top = max(t, axis, { keepdims: true });
|
|
604
|
+
const e = exp(sub(t, top));
|
|
605
|
+
return div(e, sum(e, axis, { keepdims: true }));
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Count, min, max, mean, deviation and the number of NaN and infinite elements (finite elements only in the first four). */
|
|
609
|
+
export function stats(t) {
|
|
610
|
+
tensorOf(t);
|
|
611
|
+
const data = t.data;
|
|
612
|
+
const big = DTYPES[t.dtype].big;
|
|
613
|
+
let lo = Infinity;
|
|
614
|
+
let hi = -Infinity;
|
|
615
|
+
let total = 0;
|
|
616
|
+
let finite = 0;
|
|
617
|
+
let nan = 0;
|
|
618
|
+
let inf = 0;
|
|
619
|
+
for (let i = 0; i < data.length; i++) {
|
|
620
|
+
const v = big ? Number(data[i]) : data[i];
|
|
621
|
+
if (Number.isNaN(v)) nan++;
|
|
622
|
+
else if (!Number.isFinite(v)) inf++;
|
|
623
|
+
else {
|
|
624
|
+
finite++;
|
|
625
|
+
total += v;
|
|
626
|
+
if (v < lo) lo = v;
|
|
627
|
+
if (v > hi) hi = v;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
const avg = finite ? total / finite : NaN;
|
|
631
|
+
let sq = 0;
|
|
632
|
+
for (let i = 0; i < data.length; i++) {
|
|
633
|
+
const v = big ? Number(data[i]) : data[i];
|
|
634
|
+
if (Number.isFinite(v)) sq += (v - avg) ** 2;
|
|
635
|
+
}
|
|
636
|
+
return { count: data.length, min: finite ? lo : NaN, max: finite ? hi : NaN, mean: avg, std: finite ? Math.sqrt(sq / finite) : NaN, nan, inf };
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// ---------------------------------------------------------------------------------------------- the view
|
|
640
|
+
|
|
641
|
+
/** Slices of a many-dimensional tensor a preview keeps, and the largest side of a heatmap. */
|
|
642
|
+
export const PREVIEW_SLICES = 6;
|
|
643
|
+
export const PREVIEW_SIDE = 64;
|
|
644
|
+
|
|
645
|
+
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
646
|
+
/** Bytes as base64 text (the heatmap cells in a preview). */
|
|
647
|
+
export function base64(bytes) {
|
|
648
|
+
let out = "";
|
|
649
|
+
let i = 0;
|
|
650
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
651
|
+
const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
|
|
652
|
+
out += BASE64[n >> 18] + BASE64[(n >> 12) & 63] + BASE64[(n >> 6) & 63] + BASE64[n & 63];
|
|
653
|
+
}
|
|
654
|
+
if (i + 1 === bytes.length) {
|
|
655
|
+
const n = bytes[i] << 16;
|
|
656
|
+
out += BASE64[n >> 18] + BASE64[(n >> 12) & 63] + "==";
|
|
657
|
+
} else if (i + 2 === bytes.length) {
|
|
658
|
+
const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
|
|
659
|
+
out += BASE64[n >> 18] + BASE64[(n >> 12) & 63] + BASE64[(n >> 6) & 63] + "=";
|
|
660
|
+
}
|
|
661
|
+
return out;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/** The bytes of base64 text. */
|
|
665
|
+
export function fromBase64(text) {
|
|
666
|
+
const clean = String(text).replace(/=+$/, "");
|
|
667
|
+
const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
|
|
668
|
+
let bits = 0;
|
|
669
|
+
let acc = 0;
|
|
670
|
+
let at_ = 0;
|
|
671
|
+
for (const ch of clean) {
|
|
672
|
+
const v = BASE64.indexOf(ch);
|
|
673
|
+
if (v < 0) fail("not base64");
|
|
674
|
+
acc = (acc << 6) | v;
|
|
675
|
+
bits += 6;
|
|
676
|
+
if (bits >= 8) {
|
|
677
|
+
bits -= 8;
|
|
678
|
+
out[at_++] = (acc >> bits) & 255;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
return out;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* A heatmap of two dimensions of a tensor as 0 … 255 cells: the last two axes (a vector is one row), with leading axes
|
|
686
|
+
* walked by `index` (a flat position among them). A side longer than `maxSide` is averaged into blocks. `lo` and `hi`
|
|
687
|
+
* give the range the cells are scaled to (the tensor's own when left out); NaN is cell 0.
|
|
688
|
+
* @returns {{ rows: number, cols: number, srcRows: number, srcCols: number, cells: Uint8Array, binned: boolean }}
|
|
689
|
+
*/
|
|
690
|
+
export function heatmap(t, { index = 0, maxSide = PREVIEW_SIDE, lo, hi } = {}) {
|
|
691
|
+
tensorOf(t);
|
|
692
|
+
const shape = t.shape;
|
|
693
|
+
const srcRows = shape.length >= 2 ? shape[shape.length - 2] : shape.length === 1 ? 1 : 1;
|
|
694
|
+
const srcCols = shape.length >= 1 ? shape[shape.length - 1] : 1;
|
|
695
|
+
const plane = srcRows * srcCols;
|
|
696
|
+
const planes = plane ? t.data.length / plane : 0;
|
|
697
|
+
if (index < 0 || index >= Math.max(planes, 1)) fail(`heatmap: slice ${index} isn't one of 0 … ${Math.max(planes, 1) - 1}`);
|
|
698
|
+
const range = lo === undefined || hi === undefined ? stats(t) : { min: lo, max: hi };
|
|
699
|
+
const a = lo ?? range.min;
|
|
700
|
+
const b = hi ?? range.max;
|
|
701
|
+
const rows = Math.min(srcRows, maxSide);
|
|
702
|
+
const cols = Math.min(srcCols, shape.length === 1 ? maxSide * 4 : maxSide);
|
|
703
|
+
const cells = new Uint8Array(rows * cols);
|
|
704
|
+
const big = DTYPES[t.dtype].big;
|
|
705
|
+
const base = index * plane;
|
|
706
|
+
const span = b - a;
|
|
707
|
+
for (let r = 0; r < rows; r++) {
|
|
708
|
+
const r0 = Math.floor((r * srcRows) / rows);
|
|
709
|
+
const r1 = Math.max(r0 + 1, Math.floor(((r + 1) * srcRows) / rows));
|
|
710
|
+
for (let c = 0; c < cols; c++) {
|
|
711
|
+
const c0 = Math.floor((c * srcCols) / cols);
|
|
712
|
+
const c1 = Math.max(c0 + 1, Math.floor(((c + 1) * srcCols) / cols));
|
|
713
|
+
let total = 0;
|
|
714
|
+
let n = 0;
|
|
715
|
+
let bad = false;
|
|
716
|
+
for (let y = r0; y < r1; y++) {
|
|
717
|
+
for (let x = c0; x < c1; x++) {
|
|
718
|
+
const v = big ? Number(t.data[base + y * srcCols + x]) : t.data[base + y * srcCols + x];
|
|
719
|
+
if (Number.isNaN(v)) bad = true;
|
|
720
|
+
else (total += v), n++;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
const v = n ? total / n : NaN;
|
|
724
|
+
cells[r * cols + c] = bad && !n ? 0 : !Number.isFinite(span) || span <= 0 || Number.isNaN(v) ? 0 : Math.round(Math.max(0, Math.min(1, (v - a) / span)) * 255);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return { rows, cols, srcRows, srcCols, cells, binned: rows < srcRows || cols < srcCols };
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* What a preview carries for a tensor: its shape, dtype, bytes, statistics and heatmap cells (base64) for the first
|
|
732
|
+
* few slices, all bounded (at most PREVIEW_SLICES maps of PREVIEW_SIDE squared cells, fewer and smaller with `heat`
|
|
733
|
+
* set to a smaller side). `heat: false` leaves the cells out.
|
|
734
|
+
*/
|
|
735
|
+
export function preview(t, { heat = true, side = PREVIEW_SIDE, slices = PREVIEW_SLICES } = {}) {
|
|
736
|
+
tensorOf(t);
|
|
737
|
+
const st = stats(t);
|
|
738
|
+
const info = DTYPES[t.dtype];
|
|
739
|
+
const out = {
|
|
740
|
+
shape: t.shape.slice(),
|
|
741
|
+
dtype: t.dtype,
|
|
742
|
+
elements: t.data.length,
|
|
743
|
+
bytes: t.data.byteLength,
|
|
744
|
+
min: st.min,
|
|
745
|
+
max: st.max,
|
|
746
|
+
mean: st.mean,
|
|
747
|
+
std: st.std,
|
|
748
|
+
...(st.nan ? { nan: st.nan } : {}),
|
|
749
|
+
...(st.inf ? { inf: st.inf } : {}),
|
|
750
|
+
...(info.big ? { big: true } : {}),
|
|
751
|
+
};
|
|
752
|
+
if (!heat || !t.data.length) return out;
|
|
753
|
+
const plane = t.shape.length >= 2 ? t.shape[t.shape.length - 2] * t.shape[t.shape.length - 1] : t.data.length;
|
|
754
|
+
const planes = plane ? t.data.length / plane : 1;
|
|
755
|
+
const shown = Math.min(planes, slices);
|
|
756
|
+
const leading = t.shape.slice(0, Math.max(0, t.shape.length - 2));
|
|
757
|
+
const maps = [];
|
|
758
|
+
const smaller = shown > 1 ? Math.min(side, 40) : side;
|
|
759
|
+
for (let i = 0; i < shown; i++) {
|
|
760
|
+
const h = heatmap(t, { index: i, maxSide: smaller, lo: st.min, hi: st.max });
|
|
761
|
+
maps.push({ index: i, at: unflatten(i, leading), data: base64(h.cells), rows: h.rows, cols: h.cols });
|
|
762
|
+
}
|
|
763
|
+
const first = heatmap(t, { index: 0, maxSide: smaller, lo: st.min, hi: st.max });
|
|
764
|
+
return { ...out, rows: first.rows, cols: first.cols, srcRows: first.srcRows, srcCols: first.srcCols, binned: first.binned, planes, maps };
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
function unflatten(index, leading) {
|
|
768
|
+
const out = new Array(leading.length);
|
|
769
|
+
let rest = index;
|
|
770
|
+
for (let d = leading.length - 1; d >= 0; d--) {
|
|
771
|
+
out[d] = rest % leading[d];
|
|
772
|
+
rest = Math.floor(rest / leading[d]);
|
|
773
|
+
}
|
|
774
|
+
return out;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** A line about a tensor: `float32 [2, 3] · 6 elements · 24 B`. */
|
|
778
|
+
export function describe(t) {
|
|
779
|
+
tensorOf(t);
|
|
780
|
+
return `${t.dtype} [${t.shape.join(", ")}] · ${t.data.length} element${t.data.length === 1 ? "" : "s"} · ${t.data.byteLength} B`;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// ---------------------------------------------------------------------------------------------- bytes helpers
|
|
784
|
+
|
|
785
|
+
function toBytes(source) {
|
|
786
|
+
if (source instanceof Uint8Array) return source.constructor === Uint8Array ? source : new Uint8Array(source.buffer, source.byteOffset, source.length); // Node's byte buffers slice into views, not copies
|
|
787
|
+
if (ArrayBuffer.isView(source)) return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
|
|
788
|
+
if (source instanceof ArrayBuffer || Object.prototype.toString.call(source) === "[object ArrayBuffer]") return new Uint8Array(source);
|
|
789
|
+
if (Array.isArray(source) && source.every((n) => Number.isInteger(n) && n >= 0 && n < 256)) return Uint8Array.from(source);
|
|
790
|
+
return undefined;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const text = (bytes) => {
|
|
794
|
+
let out = "";
|
|
795
|
+
for (let i = 0; i < bytes.length; i++) out += String.fromCharCode(bytes[i]);
|
|
796
|
+
return out;
|
|
797
|
+
};
|
|
798
|
+
|
|
799
|
+
function half(bits) {
|
|
800
|
+
const sign = bits & 0x8000 ? -1 : 1;
|
|
801
|
+
const exp_ = (bits >> 10) & 31;
|
|
802
|
+
const frac = bits & 1023;
|
|
803
|
+
if (exp_ === 0) return sign * frac * 2 ** -24;
|
|
804
|
+
if (exp_ === 31) return frac ? NaN : sign * Infinity;
|
|
805
|
+
return sign * (1 + frac / 1024) * 2 ** (exp_ - 15);
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/** The bytes of a Float32Array copy, unaligned or not. */
|
|
809
|
+
function copyOf(bytes) {
|
|
810
|
+
return bytes.byteOffset % 8 === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes.buffer : bytes.slice().buffer;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// ---------------------------------------------------------------------------------------------- .npy
|
|
814
|
+
|
|
815
|
+
const NPY_MAGIC = [0x93, 0x4e, 0x55, 0x4d, 0x50, 0x59];
|
|
816
|
+
const NPY_READ = {
|
|
817
|
+
"|b1": "bool", "|?": "bool", "|u1": "uint8", "|i1": "int8", "|B": "uint8", "|b": "int8",
|
|
818
|
+
"f4": "float32", "f8": "float64", "i2": "int16", "i4": "int32", "i8": "int64", "u2": "uint16", "u4": "uint32", "u8": "uint64", "f2": "float16",
|
|
819
|
+
};
|
|
820
|
+
|
|
821
|
+
function parseNpyHeader(bytes) {
|
|
822
|
+
if (bytes.length < 10 || NPY_MAGIC.some((b, i) => bytes[i] !== b)) fail("not a .npy file (it doesn't start with \\x93NUMPY)");
|
|
823
|
+
const major = bytes[6];
|
|
824
|
+
if (major < 1 || major > 3) fail(`unsupported .npy version ${major}.${bytes[7]}`);
|
|
825
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
826
|
+
const headerLength = major === 1 ? view.getUint16(8, true) : view.getUint32(8, true);
|
|
827
|
+
const start = major === 1 ? 10 : 12;
|
|
828
|
+
if (start + headerLength > bytes.length) fail("the .npy header is cut short");
|
|
829
|
+
const header = (major === 3 ? new TextDecoder("utf-8").decode(bytes.subarray(start, start + headerLength)) : text(bytes.subarray(start, start + headerLength))).trim();
|
|
830
|
+
const descr = /'descr'\s*:\s*(?:'([^']*)'|"([^"]*)")/.exec(header);
|
|
831
|
+
const order = /'fortran_order'\s*:\s*(True|False)/.exec(header);
|
|
832
|
+
const shape = /'shape'\s*:\s*\(([^)]*)\)/.exec(header);
|
|
833
|
+
if (!descr || !order || !shape) {
|
|
834
|
+
if (/'descr'\s*:\s*\[/.test(header)) fail("this .npy holds a structured array (named fields), which a tensor can't represent");
|
|
835
|
+
fail("the .npy header isn't the usual dictionary of descr, fortran_order and shape");
|
|
836
|
+
}
|
|
837
|
+
const dims = shape[1].split(",").map((s) => s.trim()).filter(Boolean).map((s) => (/^\d+$/.test(s.replace(/L$/, "")) ? Number(s.replace(/L$/, "")) : fail(`the .npy shape "${shape[1]}" isn't a list of whole numbers`)));
|
|
838
|
+
return { descr: descr[1] ?? descr[2], fortran: order[1] === "True", shape: dims, dataStart: start + headerLength };
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* A tensor from the bytes of a NumPy `.npy` file (versions 1 to 3): bool, int8 … int64, uint8 … uint64, float16
|
|
843
|
+
* (read as float32), float32 and float64, either byte order, C or Fortran order (it becomes C order). Object arrays,
|
|
844
|
+
* strings and structured arrays are refused with a sentence that says so.
|
|
845
|
+
* @param {Uint8Array | ArrayBuffer} source
|
|
846
|
+
*/
|
|
847
|
+
export function fromNpy(source) {
|
|
848
|
+
const bytes = toBytes(source) ?? fail("fromNpy: bytes expected (a Uint8Array or ArrayBuffer); use tensor.load(blob) for a file");
|
|
849
|
+
const head = parseNpyHeader(bytes);
|
|
850
|
+
const m = /^([<>|=]?)([a-zA-Z])(\d*)$/.exec(head.descr);
|
|
851
|
+
if (!m) fail(`this .npy's dtype "${head.descr}" can't be read`);
|
|
852
|
+
const [, order, letter, width] = m;
|
|
853
|
+
if (letter === "O") fail("this .npy holds Python objects, which a tensor can't represent");
|
|
854
|
+
if (letter === "U" || letter === "S" || letter === "a") fail(`this .npy holds text (${head.descr}), which a tensor can't represent`);
|
|
855
|
+
if (letter === "c") fail("this .npy holds complex numbers, which a tensor can't represent");
|
|
856
|
+
if (letter === "M" || letter === "m") fail("this .npy holds dates or time spans, which a tensor can't represent");
|
|
857
|
+
const key = width === "1" ? `|${letter}${width}` : `${letter}${width}`;
|
|
858
|
+
const dtype = NPY_READ[key] ?? NPY_READ[`${letter}${width}`] ?? fail(`this .npy's dtype "${head.descr}" can't be read`);
|
|
859
|
+
const bigEndian = order === ">" || (order === "=" && !LITTLE);
|
|
860
|
+
const itemSize = Number(width);
|
|
861
|
+
const count = sizeOf(head.shape);
|
|
862
|
+
if (count > MAX_ELEMENTS) fail(`this .npy has ${count} elements, more than ${MAX_ELEMENTS}`);
|
|
863
|
+
const body = bytes.subarray(head.dataStart);
|
|
864
|
+
if (body.length < count * itemSize) fail(`this .npy is cut short: its shape [${head.shape}] needs ${count * itemSize} bytes of data and the file has ${body.length}`);
|
|
865
|
+
const raw = body.slice(0, count * itemSize);
|
|
866
|
+
if (bigEndian && itemSize > 1) for (let i = 0; i < raw.length; i += itemSize) raw.subarray(i, i + itemSize).reverse();
|
|
867
|
+
let data;
|
|
868
|
+
let outType = dtype;
|
|
869
|
+
if (dtype === "float16") {
|
|
870
|
+
const bits = new Uint16Array(raw.buffer, 0, count);
|
|
871
|
+
data = new Float32Array(count);
|
|
872
|
+
for (let i = 0; i < count; i++) data[i] = half(bits[i]);
|
|
873
|
+
outType = "float32";
|
|
874
|
+
} else {
|
|
875
|
+
data = new DTYPES[dtype].array(raw.buffer, 0, count);
|
|
876
|
+
if (dtype === "bool") for (let i = 0; i < count; i++) data[i] = data[i] ? 1 : 0;
|
|
877
|
+
}
|
|
878
|
+
const t = build(head.shape.slice(), outType, data);
|
|
879
|
+
if (!head.fortran || head.shape.length < 2) return t;
|
|
880
|
+
// Fortran order lists the first axis fastest: read it with the axes reversed, then flip them back.
|
|
881
|
+
return transpose(build(head.shape.slice().reverse(), outType, data), head.shape.map((_, i) => head.shape.length - 1 - i));
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
/**
|
|
885
|
+
* A tensor as the bytes of a NumPy `.npy` file (version 1.0, little-endian, C order), which `numpy.load` reads.
|
|
886
|
+
* @param {*} t
|
|
887
|
+
*/
|
|
888
|
+
export function toNpy(t) {
|
|
889
|
+
tensorOf(t);
|
|
890
|
+
if (!LITTLE) fail("toNpy: this machine is big-endian, which isn't supported");
|
|
891
|
+
const info = DTYPES[t.dtype];
|
|
892
|
+
const descr = (t.dtype === "bool" || info.size === 1 ? "|" : "<") + info.npy;
|
|
893
|
+
const shape = t.shape.length === 1 ? `(${t.shape[0]},)` : `(${t.shape.join(", ")})`;
|
|
894
|
+
let header = `{'descr': '${descr}', 'fortran_order': False, 'shape': ${shape}, }`;
|
|
895
|
+
const total = 10 + header.length + 1;
|
|
896
|
+
header += " ".repeat((64 - (total % 64)) % 64) + "\n";
|
|
897
|
+
const body = new Uint8Array(t.data.buffer, t.data.byteOffset, t.data.byteLength);
|
|
898
|
+
const out = new Uint8Array(10 + header.length + body.length);
|
|
899
|
+
out.set(NPY_MAGIC, 0);
|
|
900
|
+
out[6] = 1;
|
|
901
|
+
out[7] = 0;
|
|
902
|
+
out[8] = header.length & 255;
|
|
903
|
+
out[9] = header.length >> 8;
|
|
904
|
+
for (let i = 0; i < header.length; i++) out[10 + i] = header.charCodeAt(i);
|
|
905
|
+
out.set(body, 10 + header.length);
|
|
906
|
+
return out;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// ---------------------------------------------------------------------------------------------- readers
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* A byte reader over a source, with the counts of what it read: `{ read(start, end), size, bytesRead, requests }`.
|
|
913
|
+
* The source is bytes (a Uint8Array, an ArrayBuffer), a Blob or File (or a media value holding one), a URL string
|
|
914
|
+
* (read with HTTP Range requests through `fetch`), a function `(start, end) => bytes`, or an object with `read`.
|
|
915
|
+
* @param {*} source
|
|
916
|
+
* @param {{ fetch?: Function, signal?: AbortSignal, size?: number }} [options]
|
|
917
|
+
*/
|
|
918
|
+
export function reader(source, { fetch: fetchWith, signal, size } = {}) {
|
|
919
|
+
// One of these already (header and load share theirs, so the counts and the size it learned stay together).
|
|
920
|
+
if (source && typeof source === "object" && typeof source.read === "function" && "bytesRead" in source && "requests" in source) return source;
|
|
921
|
+
const counts = { bytesRead: 0, requests: 0 };
|
|
922
|
+
const count = (bytes) => {
|
|
923
|
+
counts.requests++;
|
|
924
|
+
counts.bytesRead += bytes.length;
|
|
925
|
+
return bytes;
|
|
926
|
+
};
|
|
927
|
+
let known = size;
|
|
928
|
+
const make = (read, total) => {
|
|
929
|
+
known ??= total;
|
|
930
|
+
return {
|
|
931
|
+
get size() {
|
|
932
|
+
return known;
|
|
933
|
+
},
|
|
934
|
+
get bytesRead() {
|
|
935
|
+
return counts.bytesRead;
|
|
936
|
+
},
|
|
937
|
+
get requests() {
|
|
938
|
+
return counts.requests;
|
|
939
|
+
},
|
|
940
|
+
async read(start, end) {
|
|
941
|
+
if (known !== undefined) end = Math.min(end, known);
|
|
942
|
+
if (end <= start) return new Uint8Array(0);
|
|
943
|
+
return count(await read(start, end));
|
|
944
|
+
},
|
|
945
|
+
};
|
|
946
|
+
};
|
|
947
|
+
const bytes = toBytes(source);
|
|
948
|
+
if (bytes) return make(async (s, e) => bytes.subarray(s, e), bytes.length);
|
|
949
|
+
const blob = source && typeof source === "object" && source.blob && typeof source.blob.slice === "function" ? source.blob : source;
|
|
950
|
+
if (blob && typeof blob === "object" && typeof blob.slice === "function" && typeof blob.size === "number") return make(async (s, e) => new Uint8Array(await blob.slice(s, e).arrayBuffer()), blob.size);
|
|
951
|
+
if (typeof source === "function") return make(async (s, e) => toBytes(await source(s, e)) ?? fail("a reader function returns bytes"), size);
|
|
952
|
+
if (source && typeof source === "object" && typeof source.read === "function") return make(async (s, e) => toBytes(await source.read(s, e)) ?? fail("a reader's read returns bytes"), source.size ?? size);
|
|
953
|
+
if (typeof source === "string" || (typeof URL !== "undefined" && source instanceof URL)) {
|
|
954
|
+
const url = String(source);
|
|
955
|
+
const doFetch = fetchWith ?? (typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : fail("reading a URL needs a fetch: tensor.safetensors.header(url, { fetch })"));
|
|
956
|
+
const r = make(async (s, e) => {
|
|
957
|
+
const res = await doFetch(url, { headers: { Range: `bytes=${s}-${e - 1}` }, ...(signal ? { signal } : {}) });
|
|
958
|
+
if (res.status === 200) {
|
|
959
|
+
try {
|
|
960
|
+
await res.body?.cancel?.();
|
|
961
|
+
} catch {}
|
|
962
|
+
fail("the server ignored the Range header and answered with the whole file; nothing was kept (a server that supports range requests is needed to read part of a file)");
|
|
963
|
+
}
|
|
964
|
+
if (res.status !== 206) fail(`the server answered ${res.status}${res.statusText ? ` ${res.statusText}` : ""} to a range request`);
|
|
965
|
+
const total = /\/(\d+)\s*$/.exec(res.headers?.get?.("content-range") ?? "");
|
|
966
|
+
if (total) known = Number(total[1]);
|
|
967
|
+
const got = new Uint8Array(await res.arrayBuffer());
|
|
968
|
+
if (got.length > e - s) fail("the server sent more than the range that was asked for");
|
|
969
|
+
return got;
|
|
970
|
+
}, size);
|
|
971
|
+
return r;
|
|
972
|
+
}
|
|
973
|
+
return fail("a source is bytes, a Blob or File, a URL, or a function (start, end) => bytes");
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
// ---------------------------------------------------------------------------------------------- safetensors
|
|
977
|
+
|
|
978
|
+
const ST_FROM = Object.fromEntries(Object.entries(DTYPES).map(([name, info]) => [info.st, name]));
|
|
979
|
+
const ST_EXTRA = { F16: { size: 2, load: "float32" }, BF16: { size: 2, load: "float32" }, F8_E5M2: { size: 1 }, F8_E4M3: { size: 1 }, F8_E8M0: { size: 1 } };
|
|
980
|
+
|
|
981
|
+
/** The bytes per element of a safetensors dtype code, or undefined when it isn't known. */
|
|
982
|
+
export const safetensorsItemSize = (code) => ST_EXTRA[code]?.size ?? (ST_FROM[code] ? DTYPES[ST_FROM[code]].size : undefined);
|
|
983
|
+
|
|
984
|
+
/** The widest header (bytes) the reader accepts: the format asks for at most 100 MB, and a larger one is refused before it is read. */
|
|
985
|
+
export const MAX_HEADER = 100 * 1024 * 1024;
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* Check and describe a safetensors header (the JSON text, as an object). Returns `{ metadata, tensors, problems }`:
|
|
989
|
+
* `tensors` in file order, each `{ name, dtype, shape, elements, bytes, start, end }` (offsets within the data
|
|
990
|
+
* that follows the header). `size` (the data's length, when known) checks that the tensors fit in the file.
|
|
991
|
+
*/
|
|
992
|
+
export function describeHeader(header, size) {
|
|
993
|
+
if (!header || typeof header !== "object" || Array.isArray(header)) fail("the safetensors header isn't a JSON object");
|
|
994
|
+
const tensors = [];
|
|
995
|
+
const problems = [];
|
|
996
|
+
let metadata = {};
|
|
997
|
+
for (const [name, entry] of Object.entries(header)) {
|
|
998
|
+
if (name === "__metadata__") {
|
|
999
|
+
metadata = entry && typeof entry === "object" ? entry : {};
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
const offsets = entry?.data_offsets;
|
|
1003
|
+
if (!entry || typeof entry.dtype !== "string" || !Array.isArray(entry.shape) || !entry.shape.every(isInt) || !Array.isArray(offsets) || offsets.length !== 2 || !offsets.every(isInt) || offsets[1] < offsets[0]) {
|
|
1004
|
+
problems.push(`"${name}" isn't a tensor entry (dtype, shape and data_offsets are expected)`);
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
const elements = sizeOf(entry.shape);
|
|
1008
|
+
const item = safetensorsItemSize(entry.dtype);
|
|
1009
|
+
const bytes = offsets[1] - offsets[0];
|
|
1010
|
+
if (item === undefined) problems.push(`"${name}" has the dtype ${entry.dtype}, which isn't known`);
|
|
1011
|
+
else if (bytes !== elements * item) problems.push(`"${name}" holds ${bytes} bytes but its shape [${entry.shape}] of ${entry.dtype} needs ${elements * item}`);
|
|
1012
|
+
if (size !== undefined && offsets[1] > size) problems.push(`"${name}" ends at byte ${offsets[1]} of the data, past its end (${size})`);
|
|
1013
|
+
tensors.push({ name, dtype: entry.dtype, shape: entry.shape.slice(), elements, bytes, start: offsets[0], end: offsets[1] });
|
|
1014
|
+
}
|
|
1015
|
+
const byStart = tensors.slice().sort((a, b) => a.start - b.start || a.end - b.end);
|
|
1016
|
+
for (let i = 1; i < byStart.length; i++) if (byStart[i].start < byStart[i - 1].end) problems.push(`"${byStart[i].name}" overlaps "${byStart[i - 1].name}" in the data`);
|
|
1017
|
+
return { metadata, tensors, problems };
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* Read a safetensors file's header without its weights: 8 bytes for the header's length, then the header,
|
|
1022
|
+
* two range reads whatever the file's size. `source` is anything `reader` takes (a URL needs a server that answers
|
|
1023
|
+
* Range requests, and the `fetch` to use: `await tensor.safetensors.header(url, { fetch })` in a pane).
|
|
1024
|
+
*
|
|
1025
|
+
* Returns `{ kind: "safetensors-header", headerBytes, dataStart, size, metadata, tensors, totals, problems, read }`.
|
|
1026
|
+
* `size` is the file's length when the source says (null otherwise), `totals` `{ tensors, parameters, bytes }`,
|
|
1027
|
+
* `read` `{ bytes, requests }` (what this call read).
|
|
1028
|
+
* @param {*} source
|
|
1029
|
+
* @param {{ fetch?: Function, signal?: AbortSignal, size?: number, maxHeader?: number }} [options]
|
|
1030
|
+
*/
|
|
1031
|
+
export async function header(source, options = {}) {
|
|
1032
|
+
const r = reader(source, options);
|
|
1033
|
+
const lead = await r.read(0, 8);
|
|
1034
|
+
if (lead.length < 8) fail("not a safetensors file: it is shorter than the 8 bytes that hold the header's length");
|
|
1035
|
+
const length = Number(new DataView(lead.buffer, lead.byteOffset, 8).getBigUint64(0, true));
|
|
1036
|
+
const limit = options.maxHeader ?? MAX_HEADER;
|
|
1037
|
+
if (length > limit) fail(`not a safetensors file (or too large to read): its header claims ${length} bytes, more than ${limit}`);
|
|
1038
|
+
const raw = await r.read(8, 8 + length);
|
|
1039
|
+
if (raw.length < length) fail(`the safetensors file is cut short: its header is ${length} bytes and only ${raw.length} were there`);
|
|
1040
|
+
let json;
|
|
1041
|
+
try {
|
|
1042
|
+
json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw));
|
|
1043
|
+
} catch {
|
|
1044
|
+
fail("not a safetensors file: the header isn't valid JSON");
|
|
1045
|
+
}
|
|
1046
|
+
const dataStart = 8 + length;
|
|
1047
|
+
const size = r.size;
|
|
1048
|
+
const described = describeHeader(json, size === undefined ? undefined : size - dataStart);
|
|
1049
|
+
const totals = { tensors: described.tensors.length, parameters: described.tensors.reduce((n, t) => n + t.elements, 0), bytes: described.tensors.reduce((n, t) => n + t.bytes, 0) };
|
|
1050
|
+
return { kind: "safetensors-header", headerBytes: length, dataStart, size: size ?? null, metadata: described.metadata, tensors: described.tensors, totals, problems: described.problems, read: { bytes: r.bytesRead, requests: r.requests } };
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/** Is this a value `header()` made (or the plain object a structured clone of one gives)? */
|
|
1054
|
+
export const isHeader = (value) => Boolean(value) && typeof value === "object" && value.kind === "safetensors-header" && Array.isArray(value.tensors) && typeof value.dataStart === "number";
|
|
1055
|
+
|
|
1056
|
+
function floatsFrom(raw, code, count) {
|
|
1057
|
+
const bits = new Uint16Array(copyOf(raw), 0, count);
|
|
1058
|
+
const out = new Float32Array(count);
|
|
1059
|
+
if (code === "F16") for (let i = 0; i < count; i++) out[i] = half(bits[i]);
|
|
1060
|
+
else {
|
|
1061
|
+
const u = new Uint32Array(out.buffer);
|
|
1062
|
+
for (let i = 0; i < count; i++) u[i] = bits[i] << 16;
|
|
1063
|
+
}
|
|
1064
|
+
return out;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/**
|
|
1068
|
+
* Read one tensor of a safetensors file by name, with one range read of just its bytes. `options.header` is a
|
|
1069
|
+
* header from `safetensors.header` (without it the header is read first). F16 and BF16 become float32; the 8-bit
|
|
1070
|
+
* float types can't be read. A tensor over `maxBytes` (default 256 MiB) is refused before any of it is read.
|
|
1071
|
+
* @param {*} source
|
|
1072
|
+
* @param {string} name
|
|
1073
|
+
* @param {{ header?: object, fetch?: Function, signal?: AbortSignal, maxBytes?: number }} [options]
|
|
1074
|
+
*/
|
|
1075
|
+
export async function load(source, name, options = {}) {
|
|
1076
|
+
const r = reader(source, options);
|
|
1077
|
+
const head = options.header ?? (await header(r, options));
|
|
1078
|
+
const entry = head.tensors.find((t) => t.name === name) ?? fail(`the file has no tensor named "${name}" (it has ${head.tensors.slice(0, 8).map((t) => `"${t.name}"`).join(", ")}${head.tensors.length > 8 ? ", …" : ""})`);
|
|
1079
|
+
const limit = options.maxBytes ?? 256 * 1024 * 1024;
|
|
1080
|
+
if (entry.bytes > limit) fail(`"${name}" is ${entry.bytes} bytes, over the ${limit} byte limit (raise it with { maxBytes })`);
|
|
1081
|
+
const info = ST_EXTRA[entry.dtype] ?? (ST_FROM[entry.dtype] ? DTYPES[ST_FROM[entry.dtype]] : fail(`"${name}" has the dtype ${entry.dtype}, which can't be read`));
|
|
1082
|
+
if (!ST_EXTRA[entry.dtype]?.load && ST_EXTRA[entry.dtype]) fail(`"${name}" has the dtype ${entry.dtype}, which can't be read as numbers`);
|
|
1083
|
+
if (entry.bytes !== entry.elements * (ST_EXTRA[entry.dtype]?.size ?? info.size)) fail(`"${name}" holds ${entry.bytes} bytes, which its shape and dtype don't account for`);
|
|
1084
|
+
const raw = await r.read(head.dataStart + entry.start, head.dataStart + entry.end);
|
|
1085
|
+
if (raw.length < entry.bytes) fail(`the file is cut short: "${name}" needs ${entry.bytes} bytes and ${raw.length} were there`);
|
|
1086
|
+
if (ST_EXTRA[entry.dtype]) return build(entry.shape.slice(), "float32", floatsFrom(raw, entry.dtype, entry.elements));
|
|
1087
|
+
const dtype = ST_FROM[entry.dtype];
|
|
1088
|
+
const data = new DTYPES[dtype].array(copyOf(raw), 0, entry.elements);
|
|
1089
|
+
if (dtype === "bool") for (let i = 0; i < data.length; i++) data[i] = data[i] ? 1 : 0;
|
|
1090
|
+
return build(entry.shape.slice(), dtype, data);
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
/**
|
|
1094
|
+
* The bytes of a safetensors file holding `tensors` (an object of name → tensor), with `metadata` (strings) in the
|
|
1095
|
+
* header. Tensors are laid out in the object's key order, each aligned to 8 bytes after the header.
|
|
1096
|
+
* @param {Record<string, any>} tensors
|
|
1097
|
+
* @param {Record<string, string>} [metadata]
|
|
1098
|
+
*/
|
|
1099
|
+
export function encode(tensors, metadata) {
|
|
1100
|
+
if (!tensors || typeof tensors !== "object") fail("safetensors.encode: an object of name → tensor");
|
|
1101
|
+
const head = {};
|
|
1102
|
+
if (metadata) {
|
|
1103
|
+
for (const [k, v] of Object.entries(metadata)) if (typeof v !== "string") fail(`safetensors.encode: metadata "${k}" isn't a string`);
|
|
1104
|
+
head.__metadata__ = { ...metadata };
|
|
1105
|
+
}
|
|
1106
|
+
let offset = 0;
|
|
1107
|
+
const parts = [];
|
|
1108
|
+
for (const [name, t] of Object.entries(tensors)) {
|
|
1109
|
+
if (name === "__metadata__") fail('safetensors.encode: "__metadata__" is the header\'s own key');
|
|
1110
|
+
tensorOf(t, `"${name}"`);
|
|
1111
|
+
const bytes = new Uint8Array(t.data.buffer, t.data.byteOffset, t.data.byteLength);
|
|
1112
|
+
head[name] = { dtype: DTYPES[t.dtype].st, shape: t.shape.slice(), data_offsets: [offset, offset + bytes.length] };
|
|
1113
|
+
parts.push(bytes);
|
|
1114
|
+
offset += bytes.length;
|
|
1115
|
+
}
|
|
1116
|
+
let json = JSON.stringify(head);
|
|
1117
|
+
json += " ".repeat((8 - (json.length % 8)) % 8);
|
|
1118
|
+
const encoded = new TextEncoder().encode(json);
|
|
1119
|
+
const out = new Uint8Array(8 + encoded.length + offset);
|
|
1120
|
+
new DataView(out.buffer).setBigUint64(0, BigInt(encoded.length), true);
|
|
1121
|
+
out.set(encoded, 8);
|
|
1122
|
+
let at_ = 8 + encoded.length;
|
|
1123
|
+
for (const p of parts) (out.set(p, at_), (at_ += p.length));
|
|
1124
|
+
return out;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
/** `tensor.safetensors`: `header`, `load`, `encode`, `describeHeader`, `isHeader`. */
|
|
1128
|
+
export const safetensors = Object.freeze({ header, load, encode, describeHeader, isHeader, MAX_HEADER });
|
|
1129
|
+
|
|
1130
|
+
/** `tensor.npy`: `decode` and `encode`. */
|
|
1131
|
+
export const npy = Object.freeze({ decode: fromNpy, encode: toNpy });
|
|
1132
|
+
|
|
1133
|
+
// ---------------------------------------------------------------------------------------------- loading
|
|
1134
|
+
|
|
1135
|
+
/**
|
|
1136
|
+
* A tensor from a `.npy` file given as bytes, a Blob or File, a media value holding one, a Response, or a URL
|
|
1137
|
+
* (fetched whole, with `fetch`): `await tensor.load(await file())`.
|
|
1138
|
+
* @param {*} source
|
|
1139
|
+
* @param {{ fetch?: Function, signal?: AbortSignal }} [options]
|
|
1140
|
+
*/
|
|
1141
|
+
export async function loadNpy(source, options = {}) {
|
|
1142
|
+
const bytes = toBytes(source);
|
|
1143
|
+
if (bytes) return fromNpy(bytes);
|
|
1144
|
+
if (source && typeof source === "object" && typeof source.arrayBuffer === "function" && typeof source.blob !== "object") return fromNpy(new Uint8Array(await source.arrayBuffer()));
|
|
1145
|
+
if (source && typeof source === "object" && typeof source.blob === "object" && source.blob && typeof source.blob.arrayBuffer === "function") return fromNpy(new Uint8Array(await source.blob.arrayBuffer()));
|
|
1146
|
+
if (typeof source === "string") {
|
|
1147
|
+
const doFetch = options.fetch ?? (typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : fail("reading a URL needs a fetch: tensor.loadNpy(url, { fetch })"));
|
|
1148
|
+
const res = await doFetch(source, options.signal ? { signal: options.signal } : undefined);
|
|
1149
|
+
if (!res.ok) fail(`the server answered ${res.status}${res.statusText ? ` ${res.statusText}` : ""}`);
|
|
1150
|
+
return fromNpy(new Uint8Array(await res.arrayBuffer()));
|
|
1151
|
+
}
|
|
1152
|
+
return fail("tensor.loadNpy: bytes, a Blob or File, a media value, a Response or a URL");
|
|
1153
|
+
}
|