Skip to content

Machine learning

Models small enough to train inside a box, in plain Kotlin, while you watch. Flow matching carries one 2D or 3D point cloud onto another and hands back the deformation between them; the multi-output regression head it trains is usable on its own. See Flow Matching.

26 source file(s), 727 public symbol(s), 444 of them carrying KDoc. Everything below is the documentation that lives beside the code — the same text the completion documentation panel shows in the editor. A blank summary means the declaration has no KDoc yet, not that this page dropped it.

Clip.kt

CLIP, as a source of directions in meaning.

CLIP embeds images and text into one 512-dimensional space. Two separate ONNX graphs — text_model.onnx and vision_model.onnx — each emit an already-projected 512-vector, so no head has to be reimplemented here.

That gives three uses:

  1. Zero-shot classification with no training. Encode a handful of prompts once, cosine them against the live frame, take the best. See ClipVector.classify.
  2. Identity by similarity. A stored vector plus a threshold is a recogniser.
  3. A knob whose units are meaning. clipEncode("storm") - clipEncode("calm") is a direction, and projecting the current frame onto it is a continuous parameter that tracks a semantic axis rather than a pixel statistic. See ClipVector.axisTo.

Encode prompts once, into a val, and the text tower stays out of the per-frame path.

Cosine values are not comparable across modalities

This is why ClipVector.classify ranks prompts rather than thresholding a bare cosine. Measured on this checkpoint:

  • text against text sits in a narrow high cone — cos("storm","calm") = 0.881, cos("a photo of a cat","a photo of a dog") = 0.931. Nothing is ever near 0.
  • image against text sits far lower — around 0.21 for every prompt tried, because the two towers occupy offset regions of the sphere (the "modality gap").

So 0.21 does not mean "unrelated" and 0.88 does not mean "the same". Only rank and difference carry information: compare one image against several prompts, or track how a projection moves over time. An absolute threshold on a raw cosine does not transfer between prompts or scenes.

Cost

Text is ≈5ms per prompt, after the one-off cost of loading the encoder. Vision is ≈36ms at 224x224 on a CPU provider, far cheaper than DepthAnything, but still not free, so drive it from a worker if it is per-frame.

The text tower is ClipText and the vision tower is ClipImage.

src/jvmMain/kotlin/afield/ai/inference/onnx/Clip.kt — read the source

Used in: Depth and CLIP: neural vision in a box

Top-level functions

Declaration Summary
fun clipEncode(text: String): ClipVector Encode a prompt to a unit-length 512-vector.
fun clipEncodeImage(image: java.awt.image.BufferedImage): ClipVector Encode a picture to a unit-length 512-vector, in the same space as clipEncode's prompts.
fun clipEncodeImage(file: java.io.File): ClipVector clipEncodeImage for an image file: anything javax.imageio reads (JPEG, PNG, BMP, GIF).

Clip

object Clip

Shared constants and helpers for the two CLIP towers, ClipText and ClipImage.

Declaration Summary
const val DIMENSION The dimensionality of the shared embedding space for this checkpoint.
const val IMAGE_SIZE Side length the vision tower requires; ViT-B/32's position embeddings are fixed at 7x7+1.
val CLIP_MEAN CLIP's own channel means — not ImageNet's, which DepthAnything uses.
val CLIP_STD CLIP's own channel standard deviations.
const val LOGIT_SCALE The trained temperature for CLIP logits, logit_scale.exp().
val TEXT_MODEL Text tower: input_ids to a projected 512-vector.
val VISION_MODEL Vision tower: pixel_values to a projected 512-vector.
val TOKENIZER The BPE tokenizer, as a plain file rather than a model.

ClipVector

class ClipVector(val values: FloatArray)

A point, or a direction, in CLIP's 512-dimensional space.

Declaration Summary
val norm: Float Euclidean length. 1.0, to within float error, for anything an encoder returned.
fun normalized(): ClipVector Unit-length copy, or a copy of this if the length is too small to divide by.
fun dot(other: ClipVector): Float Inner product. Equal to the cosine when both sides are unit length.
fun cosine(other: ClipVector): Float Cosine similarity, normalising both sides first.
operator fun plus(other: ClipVector)
operator fun minus(other: ClipVector)
operator fun times(scale: Float)
infix fun axisTo(other: ClipVector): ClipVector The unit direction from this towards other — a semantic axis.
fun project(axis: ClipVector): Float Scalar projection of this onto axis, assuming axis is unit length.
fun classify(candidates: Map<String, ClipVector>, logitScale: Float = Clip.LOGIT_SCALE): List<Pair<String, Float>> Softmax over labelled candidates — the correct way to ask "which of these?".
fun best(candidates: Map<String, ClipVector>): Pair<String, Float>? The best-matching label, or null for no candidates. Shorthand for classify.first().
fun toBase64(): String Little-endian fp32, base64 encoded — 2732 characters.
override fun toString(): String
fun fromBase64(encoded: String): ClipVector Inverse of toBase64.
fun mean(vectors: List<ClipVector>): ClipVector The mean of several vectors, renormalised — a prompt ensemble, which CLIP responds well to.

ClipText

object ClipText

The text tower.

Declaration Summary
fun tokenize(text: String): LongArray Token ids the tokenizer produces for text, including CLIP's start and end markers.
fun encode(text: String): ClipVector Encode one prompt to a unit-length 512-vector.
fun encodeAll(texts: List<String>): Map<String, ClipVector> encode for several prompts, sharing the loaded model. Sequential — the model is the cost.

ClipImage

class ClipImage(val provider: OnnxRuntime.OnnxProvider = OnnxRuntime.OnnxProvider.AUTO)

The vision tower.

Declaration Summary
val provider: OnnxRuntime.OnnxProvider
val activeProvider: String The provider actually in force.
var lastInferenceMs: Long Wall time of the last encode, in milliseconds.
fun encode(rgba: ByteBuffer, srcW: Int, srcH: Int): ClipVector Encode one frame to a unit-length 512-vector.

ClipSmokeTest.kt

src/jvmMain/kotlin/afield/ai/inference/onnx/ClipSmokeTest.kt — read the source

ClipSmokeTest

object ClipSmokeTest

CLIP end to end: both towers, the tokenizer, and the vector algebra on top of them.

Declaration Summary
fun main(args: Array<String>)

DepthAnything.kt

Monocular depth, from any image, with no depth camera.

Depth Anything V2 Small is the least demanding useful vision model there is: one image in, one single-channel map out, no anchors, no non-maximum suppression, no decode step and no state between frames, so what it exercises is the ONNX plumbing that harder models reuse.

val depth = DepthAnything(width = 266, height = 266)
depth.infer(webcamRgbaBuffer, srcW = 640, srcH = 480)
// depth.depthFp16 now holds width*height fp16 values in [0,1]

The output is inverse relative depth, in arbitrary units

predicted_depth is not metres and not normalised. On the synthetic frame OnnxSmokeTest uses, the raw range at 518x518 is [1.0353, 2.8187] and at 266x266 it is [1.2826, 1.9854] — both asserted there against a Python onnxruntime reference. The range moves with the content and the resolution, and larger means nearer.

So a usable texture needs a normalisation window, and choosing it per-frame from that frame's own min and max makes the image flicker: a hand entering shot rescales the entire background. DepthAnything instead tracks the window with an exponential moving average (DepthAnything.adaptation) and normalises against the smoothed window, which is the cheap version of the one-euro filter that anything body-tracked eventually needs. DepthStats reports both the raw and the smoothed window so a box can watch that decision rather than guess at it.

Buffers keep their identity

DepthAnything.depthFp16 and DepthAnything.depthRaw are allocated once and refilled in place. That is not just to avoid garbage: afield.graphics.texture.StreamingTexture captures its source buffer at construction and re-reads it every frame, so the buffer has to keep the same identity for the texture to keep working. Uploading to Vulkan is then:

val tex = StreamingTexture(
    depth.depthFp16, depth.width, depth.height,
    imageFormat = VK10.VK_FORMAT_R16_SFLOAT
)

fp16 is the output format because a single-channel depth map has nowhere near 16 bits of real precision in it, and R16_SFLOAT halves the upload against R32_SFLOAT for no visible loss.

Cost

Inference is not frame-rate on a CPU execution provider: ≈388ms at 518x518 and ≈101ms at 266x266 on a 10-core Apple Silicon machine, and see OnnxRuntime for why CoreML does not fix that. Cost is roughly quadratic in resolution, which makes DepthAnything.width and DepthAnything.height the main lever. Anything interactive should drive this through DepthAnythingWorker rather than calling DepthAnything.infer on the render thread.

src/jvmMain/kotlin/afield/ai/inference/onnx/DepthAnything.kt — read the source

Used in: Depth and CLIP: neural vision in a box

DepthAnything

class DepthAnything(val width: Int = 266, val height: Int = 266, val model: OnnxModel = FP32, val provider: OnnxRuntime.OnnxProvider = OnnxRuntime.OnnxProvider.AUTO, var adaptation: Float = 0.1f, var invert: Boolean = false)

Monocular depth estimation with Depth Anything V2 Small, normalised into a reusable fp16 buffer.

Declaration Summary
val width: Int
val height: Int
val model: OnnxModel
val provider: OnnxRuntime.OnnxProvider
var adaptation: Float
var invert: Boolean
val activeProvider: String The provider actually in force, which may not be the one requested.
val depthRaw: FloatBuffer The most recent depth map in the model's own units. Valid until the next infer.
val depthFp16: ByteBuffer The most recent depth map as fp16 in [0,1], ready to upload as VK_FORMAT_R16_SFLOAT.
var framesInferred: Long How many frames have been through infer.
var lastInferenceMs: Long Wall time of the last infer call, in milliseconds, inference and conversion together.
fun infer(rgba: ByteBuffer, srcW: Int, srcH: Int): DepthStats Run one frame.
fun resetAdaptation() Forget the normalisation window, so the next frame sets it from its own range.
val IMAGENET_MEAN ImageNet channel means from the model's own preprocessor_config.json.
val IMAGENET_STD ImageNet channel standard deviations, likewise.
const val PATCH The patch size of the ViT-S/14 backbone, and so the required size granularity.
val FP32 Full-precision weights: 99MB, and faster than FP16 on a CPU provider.
val FP16 Half-precision weights: 49MB.
fun sizeFor(srcW: Int, srcH: Int, longestSide: Int = 266): Pair<Int, Int> The nearest legal input size to a source image, preserving aspect ratio.
fun forSource(srcW: Int, srcH: Int, longestSide: Int = 266, model: OnnxModel = FP32, provider: OnnxRuntime.OnnxProvider = OnnxRuntime.OnnxProvider.AUTO): DepthAnything A DepthAnything sized for a given source image via sizeFor.

DepthStats

data class DepthStats(val rawMin: Float, val rawMax: Float, val windowMin: Float, val windowMax: Float)

The normalisation window one DepthAnything.infer used.

Declaration Summary
val rawMin: Float
val rawMax: Float
val windowMin: Float
val windowMax: Float
val settled: Boolean True once the smoothed window has caught up with this frame's raw range.

DepthAnythingWorker.kt

DepthAnything on its own thread, so a 100–400ms inference cannot stall the renderer.

Depth Anything Small costs ≈101ms at 266x266 and ≈388ms at 518x518 on a CPU execution provider; calling DepthAnything.infer from a render loop turns 60fps into 2.6fps. So the renderer gets staleness instead of latency: the most recent depth map that happens to be finished, which at 266x266 is six frames old at 60fps and looks fine for displacement, parallax and depth-keyed compositing, and looks like lag for anything a hand is steering directly.

// once
val depth = DepthAnythingWorker(width = 266, height = 266)
val tex = StreamingTexture(depth.depthFp16, depth.width, depth.height,
                           imageFormat = VK10.VK_FORMAT_R16_SFLOAT)
// per frame
depth.submit(webcam.frameBuffer, 640, 480)   // returns immediately, drops old frames
if (depth.consume()) tex.recordUpload(commandBuffer)

Frames are dropped, not queued

DepthAnythingWorker.submit overwrites any frame that has not been picked up yet. A queue would be wrong here: it would grow without bound whenever inference is slower than capture, which is always, and every frame it held would be more stale than the one behind it. Dropping means the model is always working on the newest frame available when it became free.

Why consume copies

DepthAnythingWorker.depthFp16 has a fixed identity because StreamingTexture captures its source buffer once, at construction. The worker therefore cannot write into it directly — the renderer could be reading it mid-write and would show a torn map with a visible seam. Instead the worker publishes into an internal buffer, and DepthAnythingWorker.consume copies that into DepthAnythingWorker.depthFp16 under the lock, on the calling thread. The copy is ~537KB at 518x518, tens of microseconds, and it is the only work the render thread does.

src/jvmMain/kotlin/afield/ai/inference/onnx/DepthAnythingWorker.kt — read the source

DepthAnythingWorker

class DepthAnythingWorker(val width: Int = 266, val height: Int = 266, model: OnnxModel = DepthAnything.FP32, provider: OnnxRuntime.OnnxProvider = OnnxRuntime.OnnxProvider.AUTO, invert: Boolean = false, adaptation: Float = 0.1f) : AutoCloseable

Runs DepthAnything on a background thread and hands the renderer the newest finished depth map.

Declaration Summary
val width: Int
val height: Int
val activeProvider: String The provider actually in force.
val depthFp16: ByteBuffer The most recently consumed depth map, fp16 in [0,1], width*height*2 bytes.
var framesSubmitted: Long Frames handed to submit, including ones later dropped.
var framesInferred: Long Frames actually inferred. The difference from framesSubmitted is the drop count.
var framesDropped: Long Frames overwritten in staging because inference was still busy when a newer one arrived.
var lastInferenceMs: Long Wall time of the most recent inference, in milliseconds.
var lastStats: DepthStats? Normalisation window of the most recent inference, or null before the first one completes.
var lastError: Throwable? Whatever the worker thread last failed with, if anything.
fun submit(rgba: ByteBuffer, srcW: Int, srcH: Int) Offer a frame. Returns immediately.
fun consume(): Boolean Publish a finished depth map into depthFp16, if one is waiting.
override fun close() Stop the worker thread and release the model's buffers. The cached session is left alone.

Lpips.kt

LPIPS: how different two pictures look, as a learned perceptual distance.

0 is identical, and larger is more different; for natural images most distances fall between 0 and about 0.8. It is Zhang et al.'s "Learned Perceptual Image Patch Similarity" (CVPR 2018, richzhang/PerceptualSimilarity, BSD-2), version 0.1 with the AlexNet backbone: both images go through AlexNet's five convolution stages, each stage's activations are normalised per position, and the squared differences are weighted by a linear layer trained on human judgements of which of two distortions looks closer to the original. So it compares edges, blobs and textures where they are, not pixel colours.

val d = Lpips.distance(imgFromFile("a.png"), imgFromFile("b.png"))
val ds = Lpips.distances(candidates, target)   // many against one, the target computed once

Both images must be the same size, at least 32 pixels on each side, RGB or grey in 0..1.

Size matters

AlexNet's first stage has stride 4 and the network halves twice more, so at 32x32 the three deepest stages are 1x1: they still see the image, but only as a whole. Measured on fixed pairs (see tools/export_lpips_onnx.py), a yellow disc against a colour ramp is 0.42 at 32 pixels, 0.68 at 64 and 0.83 at 128; the same pair, the same verdict, a compressed scale. Compare distances made at one size with each other, not across sizes.

Where the model comes from

Field exports its own AlexNet LPIPS ONNX file: tools/export_lpips_onnx.py builds it from the lpips package on PyPI (0.1.4, which ships the trained linear weights) and torchvision's ImageNet AlexNet, checks the ONNX graph against the PyTorch module (agreement 1.2e-7 on twelve pairs), and installs a 9.9MB file in the OnnxModel cache. Lpips.ensureModel runs that script through uv the first time it is needed — a one-off of about a minute that downloads PyTorch if uv has not cached it — and checks the result against Lpips.MODEL's pinned sha256, which two exports with the pinned package versions reproduced byte for byte.

Its gradient

Lpips.distanceAndGradientPlanar also returns d distance / d candidate pixel, from a second exported graph (Lpips.GRAD_MODEL) that the same script builds and checks against PyTorch's autograd. That is what lets a fit descend on LPIPS: afield.lang.stacksl.cpu.StackSLFit seeds its per-pixel tapes with it.

src/jvmMain/kotlin/afield/ai/inference/onnx/Lpips.kt — read the source

Lpips

object Lpips

LPIPS perceptual distance between images, with an optional gradient, from an exported ONNX model.

Declaration Summary
val MODEL The exported model: candidate [N,3,H,W], reference [N or 1,3,H,W] in, distanceN`` out.
val GRAD_MODEL The gradient model: the same inputs, distanceN` andgradient [N,3,H,W]out, the gradient being ddistancei/ dcandidateion the0..1` pixels.
const val MIN_SIDE: Int Smallest side the network accepts: AlexNet's deepest stage is 1x1 at 32.
val EXPORT_ARGS: List<String> The command ensureModel runs, with the package versions the pinned digest was made with.
val GRAD_EXPORT_ARGS: List<String> The command ensureGradModel runs: EXPORT_ARGS' environment, the gradient graph only.
fun ensureModel(): Path The model file, exporting it first if it is not in the cache, and checked against MODEL's sha256 once per process.
fun ensureGradModel(): Path The gradient model file, exported on first use and checked against GRAD_MODEL's sha256, exactly as ensureModel does for the forward model.
val session: OnnxRuntime.LoadedSession The cached session.
val gradSession: OnnxRuntime.LoadedSession The cached session of the gradient model.
fun distance(a: Img, b: Img): Double LPIPS distance between a and b, which must be the same size.
fun distances(candidates: List<Img>, reference: Img): DoubleArray LPIPS distance from each of candidates to reference; all must be the same size.
fun distancesPlanar(candidates: FloatArray, n: Int, width: Int, height: Int, reference: FloatArray): DoubleArray The same, on planar data already laid out as the network wants it: candidates is n x 3 x height x width floats in 0..1, reference is one 3 x height x width image. For callers scoring thousands of renders, who should not pay for an Img per render.
fun distanceAndGradientPlanar(candidate: FloatArray, width: Int, height: Int, reference: FloatArray): Pair<Double, FloatArray> The LPIPS distance from candidate to reference and its gradient with respect to every candidate value: planar 3 x height x width floats in 0..1, as distancesPlanar takes them. The gradient has the candidate's layout.
fun distancesAndGradientsPlanar(candidates: FloatArray, n: Int, width: Int, height: Int, references: FloatArray, m: Int = 1): Pair<DoubleArray, FloatArray> Batched distanceAndGradientPlanar: n candidates against references of batch m, which is 1 (one broadcast reference) or n (one each, as the regions of a tiled image are). The gradients come back concatenated, n x 3 x height x width.
fun conform(img: Img, width: Int, height: Int): Img img resampled to width x height and expanded to RGB: the usual way to bring two pictures to one size before comparing them.

LpipsSmokeTest.kt

src/jvmMain/kotlin/afield/ai/inference/onnx/LpipsSmokeTest.kt — read the source

LpipsSmokeTest

object LpipsSmokeTest

Lpips, end to end on the CPU, against PyTorch.

Declaration Summary
fun main(args: Array<String>)

OnnxRuntime.kt

ONNX models, running inside Field.

ONNX Runtime reaches the JVM through Microsoft's own JNI artifact — com.microsoft.onnxruntime:onnxruntime, already on the classpath because afield.ai.retrieval.SemanticRetrievalService embeds text. OnnxRuntime caches each session in a JVM singleton, so re-running a box does not rebuild it.

Session construction is the expensive half of ONNX — hundreds of milliseconds to several seconds, because the graph is parsed, fused and specialised for the execution provider. Frame-time inference is the cheap half. A box that says depthAnything() and gets re-evaluated on every keystroke must not pay session construction on every keystroke, and a recurrent model (RVM, Silero) must not lose its hidden state either.

Field recompiles the box, not the application. The session map lives in an object loaded by the application class loader, so the map outlives every recompilation of the code that reads it — the same discipline afield.audio.synth.FaustEngine uses for compiled DSP. Key a session by something stable (its OnnxRuntime.SessionSpec, i.e. file plus provider plus thread counts) and hot-reload becomes free. Build an OrtSession yourself in box code and every keystroke costs a rebuild.

Measured costs

Apple Silicon, 10 cores, Depth Anything V2 Small at 518x518. These numbers set the defaults:

  • CoreML does not help this model. The provider claims 43 of 848 nodes, across 19 partitions; the boundary crossings cost about what the accelerated nodes save (≈470ms vs ≈388ms for plain CPU — i.e. CoreML is slower). OnnxRuntime.OnnxProvider.AUTO therefore resolves to CPU. CoreML is still worth requesting for transformer encoders, where the partition count is small.
  • fp16 weights are slower than fp32 on CPU, ≈462ms vs ≈388ms, because every operator upcasts. fp16's win is download size (50MB vs 99MB), not speed. Pick it to save disk, not time.
  • Pinning intra-op threads costs throughput. setIntraOpNumThreads(4) measured ≈457ms against ≈388ms for the runtime's own default. OnnxRuntime.SessionSpec.intraOpThreads defaults to 0, meaning "let ORT decide". Set it only when you have measured that the render thread is actually starving.

The general shape: nothing on a CPU execution provider is frame-rate. 388ms is 2.6fps. Inference belongs on its own thread with the renderer reading the most recent finished result — see DepthAnythingWorker — and resolution is a far bigger lever than any provider flag, because cost is roughly quadratic in it.

What is not here

The Java API (1.27.0) has no IoBinding. Outputs are therefore always copies, and zero-copy CUDA/Vulkan interop is not reachable from Java today without dropping to Panama downcalls against the same loaded library. That is fine for everything here: a 518x518 fp32 depth map is 1.07MB, and the copy is invisible beside a 388ms inference.

Model download and caching is OnnxModel; DepthAnything is a capability built on top.

src/jvmMain/kotlin/afield/ai/inference/onnx/OnnxRuntime.kt — read the source

Used in: Depth and CLIP: neural vision in a box

OnnxRuntime

object OnnxRuntime

The process-wide ONNX Runtime environment and its cache of sessions keyed by OnnxRuntime.SessionSpec.

Declaration Summary
val env: OrtEnvironment by lazy The process-global environment.
val liveSessionCount: Int How many sessions are currently cached; useful in tests to prove reuse actually happens.
enum class OnnxProvider Which execution provider to ask for.
data class SessionSpec(val model: Path, val provider: OnnxProvider = OnnxProvider.AUTO, val intraOpThreads: Int = 0, val interOpThreads: Int = 0) Everything that changes the identity of a session, and therefore the cache key.
class LoadedSession internal constructor(val spec: SessionSpec, val session: OrtSession, val provider: String) A session plus the provider it actually got, as opposed to the one that was asked for.
fun session(spec: SessionSpec): LoadedSession The cached session for spec, building it on first request.
fun session(model: Path, provider: OnnxProvider = OnnxProvider.AUTO): LoadedSession Convenience for the common case: a model file and nothing else to say about it.
fun evict(spec: SessionSpec): Boolean Drop and close one cached session.
fun closeAll() Close every cached session. For shutdown and for tests that want a cold measurement.

OnnxModel

data class OnnxModel(val id: String, val url: String, val fileName: String, val sha256: String = "", val note: String = "")

A model that can be fetched once and then found again.

Declaration Summary
val id: String
val url: String
val fileName: String
val sha256: String
val note: String
val localPath: Path Where this model lives once fetched, whether or not it has been.
val isPresent: Boolean True when the weights are already on disk, so ensureLocal will not touch the network.
fun ensureLocal(): Path The local file, downloading it if absent.
fun session(provider: OnnxRuntime.OnnxProvider = OnnxRuntime.OnnxProvider.AUTO): OnnxRuntime.LoadedSession The cached session for this model, fetching the weights first if needed.
val cacheRoot: Path Root of the on-disk model cache.

OnnxSmokeTest.kt

src/jvmMain/kotlin/afield/ai/inference/onnx/OnnxSmokeTest.kt — read the source

OnnxSmokeTest

object OnnxSmokeTest

The ONNX binding, end to end, on the CPU.

Declaration Summary
fun main(args: Array<String>)

deepsets.kt

A learned two-body interaction: the acceleration on a particle as a function of the neighbours around it, fitted by autodiff from examples of any rule that can already be evaluated.

flowMatch learns v(x, t): where a particle should go given only where it is. That can carry a cloud onto a shape, and it is blind to the other particles. An interaction is the other kind of rule:

a_i = phi( v_i, SUM_j psi(x_j - x_i, v_j - v_i), MEAN_j psi(...) )

two small networks and a reduction over neighbours. This is the Deep Sets form, and its aggregation is permutation-invariant over any number of neighbours, so one set of weights works for a particle with three neighbours and a particle with three hundred. Classical boids is one particular choice of psi and phi, so the family contains it.

Why both a sum and a mean

Reynolds separation is a sum: being crowded by twenty neighbours pushes harder than being crowded by two. Alignment and cohesion are means, since they are averages of neighbour velocity and position. A mean-only aggregator cannot represent separation at any width, and a sum-only one makes alignment scale with crowding, so phi is fed both, at a cost of messageWidth extra inputs. DeepSetsWeights.sumScale keeps the summed branch in a sane range.

The feature map is where the physics goes

psi is not fed the raw offset. It is fed interactionFeatures: the offset and velocity difference, plus the unit direction scaled by a small radial basis, u*p and u*p^2, where p is a bounded proximity that rises as neighbours get close.

Separation goes as 1/r over a four-hundred-fold range of r, and a tanh network cannot form the product of a direction and a steep radial profile out of Cartesian components at any practical width. Alignment and cohesion are plain means, and linear in the inputs, so they survive the raw encoding. Measured by ablation against the flocking rule: fed raw Cartesian offsets the model reproduces those two to a relative error of 0.036 and separation only to 0.78, which is barely better than predicting the average.

A radial interaction is a direction times a profile, so handing the network u already multiplied by a couple of profile terms states the form of a two-body law rather than transcribing boids. The profile's coefficients, the velocity dependence, and how the summed and meaned branches combine are all still learned.

Trained by afield.math.autodiff.ADTape, not by Smile

Smile's MLP cannot express this: the gradient has to flow back through a sum over a variable-length neighbour set, and psi is applied once per neighbour with shared weights. autodiff.kt is reverse-mode over a tape, which handles it without knowing anything about networks, since the tape records whatever the forward pass did. Cost is one forward and one backward sweep per batch whatever the neighbour counts are.

The weights come out as MlpWeights

Both halves are packaged in the same flat layout the flow-matching work already uses, so MlpWeights.glsl emits them for the GPU unchanged and the parity machinery in four.neural-field-parity.smoke applies to them without modification.

src/jvmMain/kotlin/afield/ai/learning/deepsets.kt — read the source

Used in: Neural particle systems

Top-level functions

Declaration Summary
fun interactionFeatures(dx: Float, dy: Float, dvx: Float, dvy: Float, radius: Float, velocityScale: Float, minSeparation: Float, into: FloatArray = FloatArray(DeepSetsWeights.PSI_INPUTS)): FloatArray The per-neighbour features psi reads — see the discussion on DeepSetsWeights.
fun trainDeepSets(radius: Float, velocityScale: Float, accelScale: Float, sumScale: Float, minSeparation: Float, options: DeepSetsOptions = DeepSetsOptions(), examples: (Int) -> List<InteractionExample>): DeepSetsWeights Fits a DeepSetsWeights to whatever rule examples embodies, by reverse-mode autodiff.
fun DeepSetsWeights.glsl(prefix: String = "learned"): String GLSL for the whole learned interaction: both networks, the feature map, and the combination.
fun invariantFeatures(dx: Float, dy: Float, dvx: Float, dvy: Float, radius: Float, velocityScale: Float, minSeparation: Float, into: FloatArray = FloatArray(EquivariantWeights.PSI_INVARIANTS)): FloatArray The rotation-invariant description of one neighbour: [r/R, p, p^2, \|dv\|/V, (u . dv)/V].
fun trainEquivariant(radius: Float, velocityScale: Float, accelScale: Float, sumScale: Float, minSeparation: Float, options: DeepSetsOptions = DeepSetsOptions(), examples: (Int) -> List<InteractionExample>): EquivariantWeights Fits an EquivariantWeights to whatever rule examples embodies.
fun EquivariantWeights.glsl(prefix: String = "learned"): String GLSL for the equivariant interaction: both networks, the invariant features, and the combination — the shader half of EquivariantWeights.

DeepSetsWeights

class DeepSetsWeights(val psi: MlpWeights, val phi: MlpWeights, val messageWidth: Int, val radius: Float, val velocityScale: Float, val accelScale: Float, val sumScale: Float, val minSeparation: Float)

A trained interaction in the plain Cartesian form: psi and phi, the width of the message between them, and the five scales that normalise a neighbourhood into the networks and the answer back out to world units. EquivariantWeights is the same model constrained so that rotating a neighbourhood rotates the answer with it.

Declaration Summary
val psi: MlpWeights Applied per neighbour. Inputs (dx, dy, dvx, dvy) normalised; outputs messageWidth.
val phi: MlpWeights Applied once. Inputs (vx, vy, sum…, mean…) normalised; outputs a normalised acceleration.
val messageWidth: Int How wide a single neighbour's message is.
val radius: Float Interaction radius, in world units. Offsets are divided by this.
val velocityScale: Float Velocity differences are divided by this.
val accelScale: Float The output is multiplied by this to get a world-units acceleration.
val sumScale: Float The summed branch is divided by this, so a typical crowd lands near 1.
val minSeparation: Float Closest approach used by the proximity feature — the same floor the rule itself uses.
val parameterCount: Int How many weights and biases in total.
fun evaluate(vx: Float, vy: Float, neighbours: List<FloatArray>): Pair<Float, Float> The acceleration on a particle with velocity (vx, vy) given its neighbours, in fp32 and in the same order a shader would accumulate it — the reference the GPU is held to.
override fun toString(): String Both network shapes and the parameter total. The GLSL emitter writes this line into the shader as a comment, so a generated source names the weights it was generated from.
const val PSI_INPUTS How many features interactionFeatures produces, and therefore psi's input width.

InteractionExample

class InteractionExample(val velocity: FloatArray, val neighbours: List<FloatArray>, val target: FloatArray)

One training example: a neighbourhood and the acceleration the rule being imitated produces.

Declaration Summary
val velocity: FloatArray The centre particle's velocity, in world units.
val neighbours: List<FloatArray> (dx, dy, dvx, dvy) per neighbour, in world units.
val target: FloatArray The target acceleration, in world units.

DeepSetsOptions

data class DeepSetsOptions(val steps: Int = 4000, val batch: Int = 16, val messageWidth: Int = 6, val psiHidden: IntArray = intArrayOf(16, 16), val phiHidden: IntArray = intArrayOf(16, 16), val learningRate: Double = 3e-3, val finalLearningRate: Double = 2e-4, val seed: Long = 1L, val onProgress: ((Int, Double) -> Unit)? = null, val progressEvery: Int = 200)

The knobs trainDeepSets takes.

Declaration Summary
val steps: Int Adam steps to take. Each one calls examples for a fresh batch.
val batch: Int How many examples a batch is expected to hold. trainDeepSets divides its loss by the size of the list examples actually returned and only checks this is positive; trainEquivariant divides by this number, so a batch of a different size there rescales the gradient.
val messageWidth: Int How many numbers psi emits per neighbour, and so how wide the summed and the meaned branch phi reads each are. trainEquivariant reads it as a count of vector channels instead.
val psiHidden: IntArray Hidden layer widths of the per-neighbour network. tanh between them, linear out.
val phiHidden: IntArray Hidden layer widths of the combining network.
val learningRate: Double Adam's rate at the first step.
val finalLearningRate: Double Decayed linearly to this by the last step. Same reasoning as FlowMatchOptions.
val seed: Long Seeds the Xavier initialisation, and nothing else: examples draws its own randomness.
val onProgress: ((Int, Double) -> Unit)? Called with the step number and that step's loss, or null to train silently.
val progressEvery: Int How often onProgress fires, in steps. The last step reports only if it lands on one.

EquivariantWeights

class EquivariantWeights(val psi: MlpWeights, val phi: MlpWeights, val channels: Int, val radius: Float, val velocityScale: Float, val accelScale: Float, val sumScale: Float, val minSeparation: Float)

A learned interaction that is rotationally equivariant by construction — a(R x) = R a(x) holds exactly, not approximately.

Declaration Summary
val psi: MlpWeights Invariants to 2 * channels scalars: a_k then b_k.
val phi: MlpWeights Aggregate invariants to 2 * channels + 1 scalars: the sum weights, mean weights, and v.
val channels: Int How many vector channels are aggregated.
val radius: Float Interaction radius, in world units. Neighbour distances are divided by this.
val velocityScale: Float Divides velocity differences, and the centre particle's own speed, into the invariants.
val accelScale: Float The output is multiplied by this to get a world-units acceleration.
val sumScale: Float The summed channels are divided by this, so a typical crowd lands near 1.
val minSeparation: Float Closest approach used by the proximity invariant, the same floor the rule itself uses.
val parameterCount: Int How many weights and biases in total.
fun evaluate(vx: Float, vy: Float, neighbours: List<FloatArray>): Pair<Float, Float> The acceleration, in world units. Equivariant to fp32.
override fun toString(): String Both network shapes, the channel count and the parameter total. The GLSL emitter writes this line into the shader as a comment.
const val PSI_INVARIANTS [r/R, p, p^2, \|dv\|/V, (u . dv)/V] — see invariantFeatures.

flowmatching.kt

Flow matching over 2D and 3D point clouds — flowMatch trains a velocity field that carries one distribution onto another, and the field it returns can be sampled, integrated part-way, or drawn.

The idea is small enough to state completely. Pick a point x0 from where you are starting and a point x1 from where you want to end up, and declare that the straight line between them is the path a particle should take: at time t it is at xt = (1-t)·x0 + t·x1, travelling at x1 - x0. Now fit a network v(x, t) to that velocity by least squares over many random (x0, x1, t) triples. No two straight lines agree where they cross, so the fit cannot reproduce any single one of them; what it converges to is the average velocity through each point at each time, and integrating that average from t = 0 to t = 1 transports the whole starting distribution onto the whole target one. That is the entire trick, and it is why there is no adversary, no sampler in the training loop, and nothing to diverge — the loss is a plain regression MSE.

val target = flowSamples(myLine, 600, jitter = 4.0)   // sampled FLine + noise
val field = flowMatch(target, options = FlowMatchOptions(steps = 6000))
val cloud = field.sample(600)                         // fresh points from the same shape
val threads = field.paths(80)                         // the trajectories, as FLines

With a from cloud supplied it becomes a morph instead of a generator, and FlowMatchField.transport runs the ODE only part-way: transport(a, to = 0.5) is a genuine half-way shape rather than a vertex-wise average of two point lists.

val morph = flowMatch(to = flowSamples(lineB, 600), from = flowSamples(lineA, 600))
val halfway = morph.transport(flowSamples(lineA, 600), to = 0.5)

Coordinates

Training happens in a normalised frame — the target cloud (both clouds, for a morph) is centred and isotropically scaled to roughly unit variance — because a Gaussian source has to be commensurate with the data for any of this to work, and FLine coordinates are usually in the hundreds. The scaling is a single factor rather than per-axis, so it cannot squash a shape's aspect ratio. FlowMatchField converts at its boundary, so everything you pass in and get back is in the coordinates you started with.

2D and 3D are distinguished by the data, not by a flag: a cloud whose z never varies is trained as a 2D problem and its points come back on that same z plane. Pass FlowMatchOptions.dimension to override. It matters — a 2D shape trained as 3D gets a Gaussian's worth of spread in z that the field then has to learn to collapse.

What this is not

  • Not a big model. The default is two hidden layers of 64 leaky units trained by RMSProp, which is right for a few thousand points in two or three dimensions and nothing like enough for images. Training is single-threaded and per-sample (Smile's MLP has no batched matmul), so cost scales with steps × batch; see the timings in FlowMatchingTest.
  • Not able to change topology. Integrating a velocity field is a continuous invertible map, so it cannot tear a loop open or join two strands into one — a flow can only deform. With FlowCoupling.PAIRED this stops being an abstraction and starts being the dominant error term: asking a straight segment to become a closed ring makes the mean landing error fifteen times worse than asking a small circle to do it, because the two ends of the segment are pulled to the same place and their paths have to cross. Give a closed target a closed source.
  • Not exact. The field is an average over crossing paths, so samples land near the target distribution, not on it. Sharp corners smooth off, and thin structure needs more steps and more hidden before it resolves. FlowMatchField.loss is the training MSE, which measures the velocity fit and not the quality of the samples — judge those by looking, or with chamferDistance.
  • Not ordered. FlowMatchField.sample returns an unordered cloud. Recovering an FLine from it is a separate problem; FlowMatchField.transport sidesteps it by moving points you already have, which keeps whatever order they came in.
  • Not conditional. There is no class label or text prompt input — one field carries one distribution onto one other.

src/jvmMain/kotlin/afield/ai/learning/flowmatching.kt — read the source

Used in: Flow Matching, Neural particle systems, A Generator, Graded by Datalog

Top-level functions

Declaration Summary
fun flowMatch(to: List<Vec3>, from: List<Vec3>? = null, options: FlowMatchOptions = FlowMatchOptions()): FlowMatchField Trains a velocity field that carries from onto to, and returns it.
fun flowMatch(line: FLine, samples: Int = 600, jitter: Double? = null, options: FlowMatchOptions = FlowMatchOptions()): FlowMatchField Trains a field that generates points shaped like line — the common case, spelled out.
fun flowSamples(line: FLine, count: Int = 600, jitter: Double = 0.0, seed: Long? = null): List<Vec3> Samples count points evenly along line's arc length, displaced by Gaussian noise of standard deviation jitter.
fun contourComponents(lines: List<FLine>, total: Int = 3500, minimum: Int = 24, jitter: Double = 0.0, seed: Long? = null): List<List<Vec3>> Splits lines into their closed subpaths and samples each one in arc-length order, in proportion to its length — the components mixtureSource wants, prepared the way that matters.
fun mixtureSource(components: List<List<Vec3>>, shrink: Double = 1.0, jitter: Double = 0.0, alignPhase: Boolean = true, seed: Long? = null): FlowPairing Builds a source cloud whose topology matches the target's: one closed curve per component, in point-for-point correspondence with the component it has to become.
fun chamferDistance(a: List<Vec3>, b: List<Vec3>): Double Symmetric mean nearest-neighbour distance between two point clouds — how far apart two shapes are, in input coordinates.

VectorMLP

class VectorMLP(val inputs: Int, val outputs: Int, hidden: IntArray = intArrayOf(96, 96), val activation: String = "tanh") : MultilayerPerceptron(*mlpLayers(inputs, hidden, outputs, activation))

A multi-output regression MLP, which is the one thing Smile's own smile.regression.MLP will not do — it fixes the output layer at a single neuron and predict returns a Double.

Declaration Summary
val inputs: Int Width of the input vector.
val outputs: Int Width of the predicted vector.
val activation: String The hidden activation, kept because exportWeights has to name it and Smile does not.
fun predict(x: DoubleArray, into: DoubleArray = DoubleArray(outputs)): DoubleArray Runs the network forward, writing outputs values into into, which is returned.
fun accumulate(x: DoubleArray, y: DoubleArray): Double Adds one sample's gradient to the batch, returning that sample's squared error.
fun step(batchSize: Int) Applies the accumulated gradient of a batch of batchSize samples and advances the clock.
fun configure(learningRate: Double, momentum: Double, rho: Double, epsilon: Double = 1e-7) Configures RMSProp, momentum and learning rate together, the combination flowMatch uses.
fun configure(learningRate: TimeFunction, momentum: Double, rho: Double, epsilon: Double = 1e-7) As configure, but with a learning-rate schedule — TimeFunction.linear(from, steps, to) and friends, indexed by the step count.
fun parameterCount(): Int How many parameters — weights plus biases — the network is fitting.
fun exportWeights(): MlpWeights A flat snapshot of every weight and bias, in the layout MlpWeights documents — which is what afield.ai.learning.glsl turns into a shader.

FlowCoupling

enum class FlowCoupling

How flowMatch decides which x0 travels to which x1.

Constants: INDEPENDENT, MINIBATCH_OT, PAIRED.

FlowIntegrator

enum class FlowIntegrator

Which integrator FlowMatchField uses to follow the velocity field.

Constants: EULER, MIDPOINT.

FlowMatchOptions

data class FlowMatchOptions(val steps: Int = 3000, val batch: Int = 48, val hidden: IntArray = intArrayOf(64, 64), val activation: String = "leaky", val learningRate: Double = 1e-2, val finalLearningRate: Double? = 3e-4, val momentum: Double = 0.0, val rho: Double = 0.9, val timeFeatures: Int = 4, val coupling: FlowCoupling = FlowCoupling.INDEPENDENT, val jitter: Double = 0.0, val seed: Long? = null, val dimension: Int? = null, val onProgress: ((Int, Double) -> Unit)? = null, val progressEvery: Int = 100)

The knobs flowMatch takes, bundled so that a call that only wants to change one of them does not have to name the rest positionally.

Declaration Summary
val steps: Int Gradient steps to take. The dominant cost and the dominant quality lever.
val batch: Int Samples per gradient step.
val hidden: IntArray Hidden layer widths.
val activation: String Hidden activation: leaky, relu, tanh, sigmoid or linear.
val learningRate: Double RMSProp learning rate at the first step.
val finalLearningRate: Double? Learning rate at the last step, decayed linearly from learningRate; null to hold it constant.
val momentum: Double Momentum, or 0 to disable. flowMatch refuses it unless rho is 0.
val rho: Double RMSProp decay, or 0 to fall back to plain SGD. See momentum before changing either.
val timeFeatures: Int How many sin/cos octaves of the time input the network sees, on top of raw t.
val coupling: FlowCoupling How x0 is paired with x1.
val jitter: Double Standard deviation of noise added to each drawn data point, in input coordinates.
val seed: Long? Seed for the training draws. null takes an unpredictable one.
val dimension: Int? Override the inferred 2-or-3 dimensionality.
val onProgress: ((Int, Double) -> Unit)? Called every progressEvery steps with the step index and the running mean loss.
val progressEvery: Int How often onProgress fires.
override fun equals(other: Any?): Boolean Two option sets are equal when they print the same. hidden is an IntArray, which compares by identity, so the equality a data class generates would call two identical settings different.
override fun hashCode(): Int Hashes the same string equals compares, so equal option sets land in the same bucket.

FlowPairing

class FlowPairing(val from: List<Vec3>, val to: List<Vec3>)

A source cloud and a target cloud of the same length, in correspondence — what FlowCoupling.PAIRED wants, and what mixtureSource builds.

Declaration Summary
val from: List<Vec3> Where the particles start. The i-th point travels to to[i](workspace.md#stdlib-kt--i).
val to: List<Vec3> Where they end up.
val size: Int How many pairs.

FlowMatchField

class FlowMatchField internal constructor(val dimension: Int, private val net: VectorMLP, private val timeFeatures: Int, private val frame: FlowFrame, private val sourcePoints: Array<DoubleArray>?, val losses: DoubleArray)

A trained velocity field, as returned by flowMatch — the thing you integrate.

Declaration Summary
val dimension: Int 2 or 3 — whether z is part of the problem.
val losses: DoubleArray The mean squared velocity error of every training step, in order.
val loss: Double The training loss of the final step.
fun loss(count: Int): Double Mean training loss over the last count steps — steadier to read than loss alone.
val hasSourceCloud: Boolean Whether this field was trained to morph from a supplied cloud rather than from a Gaussian.
val parameterCount: Int How many weights and biases the field is made of.
val network: MlpWeights The trained network itself, flattened for a shader — see MlpWeights.
fun export(): FlowMatchExport Everything a shader needs to reproduce velocity — the network plus the three things around it: how wide the position is, how t is encoded, and the frame the training happened in.
fun velocity(at: Vec3, t: Double): Vec3 The velocity the field predicts at at and time t, in input coordinates.
fun sample(count: Int, steps: Int = 32, integrator: FlowIntegrator = FlowIntegrator.MIDPOINT, seed: Long? = null): List<Vec3> Draws count points from the source and follows the field to t = 1.
fun transport(points: List<Vec3>, from: Double = 0.0, to: Double = 1.0, steps: Int = 32, integrator: FlowIntegrator = FlowIntegrator.MIDPOINT): List<Vec3> Carries points along the field from time from to time to.
fun paths(count: Int, steps: Int = 32, integrator: FlowIntegrator = FlowIntegrator.MIDPOINT, seed: Long? = null): List<FLine> The trajectories of count fresh samples, one FLine each, from t = 0 to t = 1.
fun pathsFrom(points: List<Vec3>, from: Double = 0.0, to: Double = 1.0, steps: Int = 32, integrator: FlowIntegrator = FlowIntegrator.MIDPOINT): List<FLine> The trajectories of points specifically, from time from to time to — see paths.

corpora.kt

Synthetic drawings to teach a learned pen: Hershey plotter fonts and four drawing generators, and a writer that turns a list of drawings into a corpus python/fieldpen can train on.

Every generator draws in the order a hand (or a plotter) would, which is the one thing a pen needs from its training data and the one thing a scanned drawing cannot supply. PenCorpus resamples each drawing exactly the way Pen.feed reads a line, so a pen trained on a corpus sees the same spacing when it is later shown a line. Tests: PenCorporaTest.

src/jvmMain/kotlin/afield/ai/learning/pen/corpora.kt — read the source

Used in: Teaching a pen, A pen that sees

Top-level functions

Declaration Summary
fun curliness(line: FLine, scale: Double = 8.0, step: Double = 0.35, shortest: Int = 6): Double Mean absolute turn per unit length along line's marks, a rough measure of how curly it is, taken after resampling the way a pen reads a line (PenCorpus.strokes). Measured on the raw points instead, it mostly counts the small jitter between close points, and choosing by it picks the shakiest lines rather than the curliest. Marks of fewer than shortest resampled points are left out, so a line of dots does not count as curly either.
fun PenModel.probe(drawings: List<FLine>, labels: List<List<Int>>, scale: Double = 8.0, step: Double = 0.35): List<Pair<Int, Double>> Which memory cells track a label: show model each of drawings (a fresh pen per drawing), and correlate every cell's output with the label of the subpath being drawn, labels[d](workspace.md#stdlib-collections-kt--s) for subpath s of drawing d. Returns every cell with its correlation, strongest (positive or negative) first.
fun following(line: FLine, within: Double = 8.0, recent: Int = 8, scale: Double = 8.0, step: Double = 0.35): Double How much of line runs alongside ink it drew earlier: the share of its points (resampled the way a pen reads a line) with an earlier point, more than recent points back, within within drawing units. Hatching scores high; a single wandering line scores near zero.
fun joins(line: FLine, within: Double = 4.0, recent: Int = 8, scale: Double = 8.0, step: Double = 0.35): Double How many of line's strokes end on other ink: the share of its subpaths whose last point is within within drawing units of a point of any earlier subpath, or of this one more than recent points back. A web of cracks scores high; strokes that stop in mid-air score low.

HersheyFont

class HersheyFont private constructor(val name: String, private val glyphs: List<Glyph>)

One of the Hershey fonts: single-stroke vector lettering from 1967, drawn as a pen plotter draws it, stroke by stroke.

Declaration Summary
fun strokes(c: Char): List<List<IntArray>>? The strokes of c in font units (y down, about 32 units from ascender to descender), or null.
fun text(text: String, size: Double = 24.0, at: Vec3 = Vec3(0f, 0f, 0f)): FLine text as one FLine, a subpath per stroke, starting at at. size is the height of a capital in drawing units.
val names The fonts that ship with Field.
fun load(name: String): HersheyFont Load one of names.

PenDrawings

object PenDrawings

Generators of ordered drawings for training a pen. Each takes a seed and returns one drawing at a size that suits the default scale of 8 drawing units per model unit.

Declaration Summary
fun word(random: Random, length: Int = random.nextInt(2, 8)): String A made-up word of length letters, alternating consonants and vowels often enough to look like one.
fun hershey(seed: Long, font: String = "scripts", words: Int = 5, size: Double = 22.0): FLine A line of made-up words in a Hershey font: words words, capitals size units tall.
fun harmonograph(seed: Long, radius: Double = 70.0, turns: Double = 14.0): FLine A harmonograph: two damped pendulums per axis, summed, drawn as one long decaying stroke. The frequencies sit near small whole-number ratios, which is what makes the figure close up.
fun plant(seed: Long, generations: Int = 4, height: Double = 140.0): FLine A branching plant from an L-system, drawn by a turtle in one unbroken stroke: each branch is drawn out to its tip and back down to its fork, the way a hand draws a twig.
fun truchet(seed: Long, columns: Int = 9, rows: Int = 5, cell: Double = 18.0): FLine Truchet tiles: a grid of squares, each holding two quarter-circle arcs one way or the other, whose arcs join into long winding curves. Each curve is one stroke, traced end to end.
fun boids(seed: Long, count: Int = 10, steps: Int = 160, size: Double = 160.0): FLine Flocking trails: a dozen boids that steer towards each other, align and keep apart, wandering a box. Each boid's path is one stroke, drawn one boid after another.
fun michaux(seed: Long, columns: Int = 2, lines: Int = 14, length: Double = 200.0, gap: Double = 5.0): FLine After Henri Michaux's mescaline drawings: columns of fine, trembling lines, each laid down beside the last at a small gap and following its undulation, a little changed, so the field accumulates. A column is one unbroken stroke going down, turning, and coming back up beside itself, the way hatching is drawn; now and then a pass leans into its neighbour and touches it.
fun cracks(seed: Long, size: Double = 110.0, count: Int = 26): FLine A web of cracks: a wobbling outline, then crack after crack, each starting on the ink near the last one and wandering until it meets a line, where it stops. Every crack ends in a join: the thing a sensing pen can learn and a blind one cannot.
fun echoes(seed: Long, guides: Int = 3, passes: Int = 7, gap: Double = 5.0): FLine Echo hatching: a few guide strokes (a stroke of a Hershey letter, a smooth curve, or a closed blob, each at a random angle), each followed by passes laid alongside it at a small gap, back and forth in one unbroken stroke with a tremor, outwards from the guide. A pass is cut short where it would run into other ink, so hatching stops at the lines around it.
fun twoHands(seed: Long, words: Int = 6, hands: MutableList<Int>? = null): FLine A line in two hands: words that are either chains of small loops (hand 0) or sharp zigzags (hand 1), the hand changing every word or two. hands gets the hand of each word, one entry per subpath of the result, which is what a probe needs to find the cell that tracks it.

PenCorpus

object PenCorpus

A corpus of drawings for python/fieldpen: one JSON file per drawing, split into train/ and valid/ under a folder.

Declaration Summary
fun write(folder: String, drawings: List<FLine>, scale: Double = 8.0, step: Double = 0.35, validEvery: Int = 10): Int Write drawings under folder, every validEveryth one into valid/. Returns the number of points written.
fun strokes(line: FLine, scale: Double = 8.0, step: Double = 0.35): List<List<Vec3>> line's subpaths resampled every step model units: what the pen is shown.

PenCorpora

object PenCorpora

Writes the corpora Field's bundled synthetic pens were trained on: run-jvm-main afield.ai.learning.pen.PenCorpora --arg <folder> makes one sub-folder per corpus, which tools/train_pen_corpora.py then trains and exports.

Declaration Summary
fun all(): Map<String, () -> List<FLine>> Every corpus by name: the drawings to write.
fun rounder(candidates: Int = 2400, keep: Int = 300): List<FLine> The handwriting pen's own output, kept only where it is curliest: 2400 short unprimed scribbles of 120 points, the top eighth by curliness. Fine-tuning on it is a pen learning a taste from its own work.
fun main(args: Array<String>)

guide.kt

Guided sampling for a learned pen: the pen proposes several next points and a PenGuide picks one. The pen keeps its hand (its tremor, its rhythm, its habits) while the guide decides where it goes. FollowGuide keeps a pen a set distance from the ink beside it, which is hatching. Tests: PenHatchTest.

src/jvmMain/kotlin/afield/ai/learning/pen/guide.kt — read the source

Used in: A pen that sees

PenGuide

interface PenGuide

Chooses among a pen's proposals for its next point; set one on PenLine.guide.

Declaration Summary
val candidates: Int How many proposals the pen makes each point.
fun score(from: Vec3, to: Vec3, lift: Boolean, penUp: Boolean): Double How bad a proposal is, lower is better: a step from from to to in drawing units, after which the pen lifts if lift. penUp says whether this step is a move rather than a mark.
fun drawn(at: Vec3, lift: Boolean) The pen drew the chosen point; a guide that tracks ink records it here.

FollowGuide

class FollowGuide(val gap: Double = 4.0, override val candidates: Int = 12, val recent: Int = 10, val reach: Double = 30.0, val liftCost: Double = 2.0, val longest: Double = 6.0) : PenGuide

Keeps a pen gap drawing units from the ink beside it, without crossing any: hatching.

Declaration Summary
val gap: Double
override val candidates: Int
val recent: Int
val reach: Double
val liftCost: Double
val longest: Double
fun see(lines: List<FLine>, spacing: Double = 2.0) Ink the pen should keep its distance from, visible at once: the drawing being hatched.
override fun drawn(at: Vec3, lift: Boolean)
override fun score(from: Vec3, to: Vec3, lift: Boolean, penUp: Boolean): Double

hatch.kt

Hatching around a drawing with a sensing pen: every stroke of the drawing gets passes of the pen's own trembling line laid beside it, which keep clear of the other strokes and of the hatching already done.

A pen cannot remember which strokes it has not hatched yet, so Hatcher chooses: it hands the pen one stroke at a time as a finished primer, with everything else on the page as surroundings, and moves on when the pen has drawn enough or wandered off. Tests: PenHatchTest.

src/jvmMain/kotlin/afield/ai/learning/pen/hatch.kt — read the source

Top-level functions

Declaration Summary
fun hatch(lines: List<FLine>, model: StrokeModel = PenModel.bundled("echoes"), passes: Int = 6, seed: Long = 0, controls: PenControls = PenControls(temperature = 1.0, noise = 1.0), gap: Double? = 4.0): List<FLine> Hatch around lines with a sensing pen and return the hatching, one FLine per stroke: Hatcher run to the end.

Hatcher

class Hatcher(lines: List<FLine>, val model: StrokeModel = PenModel.bundled("echoes"), val passes: Int = 6, val scale: Double = 8.0, var controls: PenControls = PenControls(temperature = 1.0, noise = 1.0), val seed: Long = 0, val step: Double = 0.35, val wander: Double = 40.0, val gap: Double? = 4.0)

Hatches lines stroke by stroke with model, grow points at a time, so a box can watch it.

Declaration Summary
val model: StrokeModel
val passes: Int
val scale: Double
var controls: PenControls
val seed: Long
val step: Double
val wander: Double
val gap: Double?
val hatching: MutableList<FLine> The hatching so far, one FLine per stroke started.
val done: Boolean True once every stroke has been hatched.
val current: FLine? The stroke being hatched now, or null when done.
fun grow(steps: Int = 8): Boolean Draw up to steps more points; returns false once everything is hatched.
fun finish(): List<FLine> Hatch everything; returns hatching.

pen.kt

A learned pen: a recurrent network that has watched people write and draws the next point.

PenModel is a one-layer (or deeper) LSTM whose output is a mixture of 2D Gaussians for the next pen displacement plus a probability that the pen lifts. PenModel.distill is the handwriting model from Carter, Ha, Johnson and Olah, Experiments in Handwriting with a Neural Network (Distill, 2016), bundled with Field. PenModel.load reads a model retrained or fine-tuned with the optional Python package python/fieldpen and exported with fieldpen.export_for_field.

The everyday call is continueWith: hand it an FLine and get back the next few hundred points the pen would have drawn. Pen is the state underneath, for when you want to feed, step, fork or edit the pen yourself. Tests: PenModelTest.

src/jvmMain/kotlin/afield/ai/learning/pen/pen.kt — read the source

Used in: A learned pen, Teaching a pen, A pen that sees

Top-level functions

Declaration Summary
fun FLine.continueWith(model: StrokeModel = PenModel.distill, steps: Int = 300, scale: Double = 8.0, controls: PenControls = PenControls(), seed: Long = 0, step: Double = 0.35, liftAtEnd: Boolean = false): FLine Continue this line with a learned pen: the next steps points it would draw, as a new FLine that starts where this one ends.
fun FLine.futuresWith(model: StrokeModel = PenModel.distill, count: Int = 16, steps: Int = 60, scale: Double = 8.0, controls: PenControls = PenControls(), seed: Long = 1, step: Double = 0.35): List<FLine> Several continuations of this line at once: count different futures of steps points, each a fresh FLine from this line's end. Futures share the pen's reading of the line and differ only in the random choices after it.

StrokeModel

interface StrokeModel

Anything that can continue a stroke one displacement at a time.

Declaration Summary
fun pen(seed: Long = 0): StrokePen A fresh pen that has seen nothing, sampling with a generator seeded by seed.

StrokePen

interface StrokePen

The running state of a StrokeModel: everything it has drawn or been shown so far.

Declaration Summary
fun feed(dx: Double, dy: Double, lift: Boolean) Show the pen a displacement in model units; lift means the pen comes up after this point.
fun next(controls: PenControls = PenControls()): PenStep Sample the next displacement and feed it back, as though the pen had drawn it.
fun fork(seed: Long): StrokePen An independent copy: the same memory, its own random generator seeded by seed.

PenStep

data class PenStep(val dx: Double, val dy: Double, val lift: Boolean)

One step of a pen, in model units: move by (dx, dy), then lift if lift.

PenControls

data class PenControls(val temperature: Double = 0.65, val noise: Double = 0.65, val liftBias: Double = 0.0, val driftX: Double = 0.0, val driftY: Double = 0.0)

How a pen samples its next step.

Declaration Summary
val temperature: Double
val noise: Double
val liftBias: Double
val driftX: Double
val driftY: Double

PenDistribution

class PenDistribution(val weights: DoubleArray, val meanX: DoubleArray, val meanY: DoubleArray, val sigmaX: DoubleArray, val sigmaY: DoubleArray, val correlation: DoubleArray, val liftProbability: Double)

A pen's prediction for its next step: a mixture of 2D Gaussians and a lift probability.

Declaration Summary
val weights: DoubleArray
val meanX: DoubleArray
val meanY: DoubleArray
val sigmaX: DoubleArray
val sigmaY: DoubleArray
val correlation: DoubleArray
val liftProbability: Double
val size: Int The number of mixture components.
fun toDrawing(at: Vec3, scale: Double) The same distribution, moved to at and scaled by scale: drawing coordinates.

PenMoment

class PenMoment(val from: Vec3, val to: Vec3, val mark: Boolean, val lifted: Boolean, val liftProbability: Double, val cells: FloatArray?, val hidden: FloatArray?)

One point a PenLine drew: from from to to in drawing units, as a mark or (when mark is false) a move with the pen up. liftProbability is the chance the pen gave of lifting after this point, read before it was drawn. cells and hidden are the pen's memory just after the point, kept only when the PenLine was made with recordMemory = true.

Declaration Summary
val from: Vec3
val to: Vec3
val mark: Boolean
val lifted: Boolean
val liftProbability: Double
val cells: FloatArray?
val hidden: FloatArray?

PenModel

class PenModel internal constructor(val hidden: Int, val mixtures: Int, val layers: Int, private val gates: List<FloatArray>, private val gateBias: List<FloatArray>, private val headWeight: FloatArray, private val headBias: FloatArray, val inputs: Int = 3, val sectors: Int = 0, val senseRadius: Double = 0.0, val senseRecent: Int = 0) : StrokeModel

The weights of an LSTM pen model, shared by every Pen made from it.

Declaration Summary
val hidden: Int
val mixtures: Int
val layers: Int
val inputs: Int 3 for a pen that reads only its own displacements, 3 + sectors + 2 for one that also sees the ink around it (PenSense), in sectors directions out to senseRadius model units, ignoring its last senseRecent points.
val sectors: Int
val senseRadius: Double
val senseRecent: Int
override fun pen(seed: Long): Pen
fun pen(primer: FLine, scale: Double = 8.0, step: Double = 0.35, seed: Long = 0): Pen A pen that has already been shown primer (see Pen.feed for scale and step).
val distill: PenModel by lazy The Distill handwriting model: 500 cells, 20 mixture components, trained on the IAM On-Line Handwriting Database. Loaded once, on first use, from Field's resources.
fun load(path: String): PenModel Read a model: a .fieldpen.json written by fieldpen.export_for_field, or a file in the Distill article's own quantized format.
fun bundled(name: String): PenModel One of the pens that ship with Field, trained on a synthetic corpus: "hershey", "harmonograph", "plants", "truchet", "boids", "mixed" or "rounder" (see the Teaching a pen docs page), or one that senses the ink around it, "michaux" and "cracks", each with a blind twin trained on the same drawings, "michaux-blind" and "cracks-blind", and "echoes", the hand Hatcher hatches with (the A pen that sees page). Loaded once each.

Pen

class Pen internal constructor(val model: PenModel, seed: Long) : StrokePen

The state of one PenModel: its memory, where it is, whether its pen is up, and its random generator.

Declaration Summary
var sense: PenSense? The ink a sensing pen sees; null for a pen that does not sense.
var x0 Pen position in model units, the sum of every displacement fed so far.
var y0 The y of x0.
var penUp Whether the pen is off the paper, so the next step is a move rather than a mark.
var count Steps fed or drawn, not counting the start-of-sequence step.
override fun feed(dx: Double, dy: Double, lift: Boolean)
fun addInk(points: List<Pair<Double, Double>>) Let a sensing pen see ink it did not draw: points in model units, in the pen's own coordinates (its first point is the origin). Does nothing for a pen that does not sense.
fun feed(line: FLine, scale: Double = 8.0, step: Double = 0.35, liftAtEnd: Boolean = false) Show the pen line, so that what it draws next continues it.
override fun next(controls: PenControls): PenStep
fun propose(controls: PenControls = PenControls()): PenStep A sample of the next step, as next would draw it, without drawing it: the pen is unchanged apart from its random generator. Calling this several times and then feeding one is how a PenGuide chooses among proposals.
override fun fork(seed: Long): Pen
fun distribution(controls: PenControls = PenControls()): PenDistribution The pen's prediction for its next step, in model units relative to where it is: one weight, mean, spread and correlation per mixture component, with controls' temperature applied to the weights and its noise to the spreads, as next would sample them.
val liftProbability: Double The probability that the pen lifts after its next step, before any PenControls.liftBias.
fun cells(layer: Int = model.layers - 1): FloatArray A copy of layer layer's cell memory (the LSTM's c), one value per cell.
fun hidden(layer: Int = model.layers - 1): FloatArray A copy of layer layer's hidden output (the LSTM's h).
fun setCell(cell: Int, value: Double, layer: Int = model.layers - 1) Overwrite one memory cell, the Distill article's fourth experiment. The change shows up from the step after next: the head has already read the current output.
fun rawOutput(): FloatArray The head's raw output for the next step (see PenModel for its layout).

PenLine

class PenLine(primer: FLine? = null, val model: StrokeModel = PenModel.distill, val scale: Double = 8.0, var controls: PenControls = PenControls(), seed: Long = 0, step: Double = 0.35, start: Vec3 = Vec3(0f, 0f, 0f), val recordMemory: Boolean = false, surroundings: List<FLine> = emptyList(), liftAtEnd: Boolean = false)

A line that a pen keeps drawing: the primer you gave it, then everything the pen added.

Declaration Summary
val model: StrokeModel
val scale: Double
var controls: PenControls
val recordMemory: Boolean Also keep each step's memory (cells and hidden) in history, for colouring by a cell.
var pen: StrokePen The pen underneath, for Pen.setCell or forking by hand.
val line: FLine The primer followed by what has been drawn so far.
val drawn: FLine Only the pen's own contribution, without the primer.
val history: MutableList<PenMoment> One PenMoment per point the pen has drawn, oldest first.
val tip: Vec3 Where the pen is now, in drawing units.
val penUp: Boolean Whether the pen is off the paper, so its next point starts a new stroke.
fun grow(steps: Int = 1): FLine Draw steps more points onto line (and drawn); returns line.
var guide: PenGuide? Steers the pen without taking its hand: each point, the pen proposes PenGuide.candidates next steps (by forking itself) and the guide's choice is the one drawn. null, the default, lets the pen draw as it would.
fun distribution(): PenDistribution? What the pen expects next, in drawing units around tip: its mixture of Gaussians, with controls' temperature and noise applied. null if the pen is not a PenModel's.
fun futures(count: Int = 16, steps: Int = 40, seed: Long = 1): List<FLine> Ask what the pen might do next without letting it do it: count independent continuations of steps points each, from here. line and the pen are unchanged.
fun sense(lines: List<FLine>, step: Double = 0.35) Let a sensing pen see lines from now on, as ink already on the page: other strokes to join, follow or stop at. Resampled at the pen's own spacing. Does nothing for a pen that does not sense.
fun lift() Make the pen lift now, so the next point starts a new stroke.

penviz.kt

Pictures of what a learned pen is thinking: its next-step distribution as ellipses, a stroke coloured by one memory cell or drawn thick where the pen is sure to stay down, and the density of hundreds of possible futures as an image.

Everything here reads a PenLine: its PenLine.history for what it has drawn and PenLine.distribution for what it expects next. Tests: PenVizTest.

src/jvmMain/kotlin/afield/ai/learning/pen/penviz.kt — read the source

Used in: A learned pen, Teaching a pen, A pen that sees

Top-level functions

Declaration Summary
fun PenDistribution.ellipses(sigmas: Double = 2.0, minWeight: Double = 0.01, color: Vec4 = Vec4(0.55f, 0.85f, 1f, 1f)): List<FLine> One ellipse per mixture component, at sigmas standard deviations, with opacity following the component's weight; components lighter than minWeight are left out. Read it as "where the next point will land": a tight cluster is a pen that knows, a spread of faint rings one that is choosing.
fun PenLine.coloredBy(bands: Int = 16, low: Vec4 = Vec4(0.2f, 0.45f, 1f, 1f), high: Vec4 = Vec4(1f, 0.55f, 0.2f, 1f), range: ClosedFloatingPointRange<Double>? = null, thickness: Double = 1.5, value: (PenMoment) -> Double): List<FLine> The pen's marks, split into bands FLines by value, each coloured between low and high. range is the span of values mapped onto the colours; by default, the values' own.
fun PenLine.coloredByCell(cell: Int, bands: Int = 16, thickness: Double = 1.5, range: ClosedFloatingPointRange<Double>? = -1.0..1.0): List<FLine> The pen's marks coloured by memory cell cell's output (the LSTM's h): blue where it is low, orange where it is high. range is the span of outputs the colours cover, by default all of it, -1 to 1; null spreads them over the values this cell actually took, for a cell that never moves far. Needs a PenLine made with recordMemory = true.
fun PenLine.widthByLift(bands: Int = 12, thinnest: Double = 0.3, thickest: Double = 4.0, color: Vec4 = Vec4(0.9f, 0.92f, 1f, 1f), smoothing: Int = 4): List<FLine> The pen's marks drawn thick where it was sure the pen would stay on the paper and thin where it expected to lift: the lift probability read as pressure. It was never trained on pressure, so this is the model's confidence, not a hand's. Widths follow the logarithm of the probability, averaged over smoothing points either side and spread over this line's own range of it.
fun PenLine.liveliestCells(count: Int = 12): List<Int> The count memory cells whose output changed most while drawing, most variable first: the place to start looking for a cell that means something. Needs recordMemory = true.
fun PenLine.futuresDensity(area: DoubleArray? = null, count: Int = 400, steps: Int = 60, width: Int = 1040, height: Int = 520, seed: Long = 1, ink: Vec4 = Vec4(1f, 0.85f, 0.3f, 1f)): ByteArray Where the pen might go: count futures of steps points from here, accumulated into an image of width by height pixels over area (drawing coordinates, x, y, w, h), on a log scale so a single stray future still shows. line and extra are drawn on top in ink. Returns PNG bytes for display(...).
fun framing(lines: List<FLine>, aspect: Double): DoubleArray A rectangle (x, y, w, h) around lines's points, padded by a tenth, widened or heightened to aspect (width over height) so nothing is stretched. Ignores the farthest 1% of points, so one wild future does not shrink everything else.
fun PenLine.tail(points: Int = 20): FLine The last points points the pen drew, as an FLine ending at PenLine.tip: the context for a close-up.
fun PenLine.closeUp(points: Int = 8): PenCloseUp This moment, as a PenCloseUp over the last points points.
fun sideBySide(groups: List<List<FLine>>, gap: Double = 12.0, y: Double = 0.0): List<FLine> groups laid out left to right, each moved so it starts gap after the previous one ends and sits with its top at y: small multiples that never overlap, whatever their sizes.
fun stacked(groups: List<List<FLine>>, gap: Double = 12.0, x: Double = 0.0): List<FLine> groups stacked top to bottom, each starting gap below the previous one's lowest point.
fun PenLine.seeing(color: Vec4 = Vec4(1f, 0.6f, 0.3f, 1f)): List<FLine> What a sensing pen sees from where it is now: a faint circle as far as it can see, and a ray in each direction that has ink in reach, out to the nearest ink there, brighter the closer it is. Empty for a pen that does not sense.

Top-level values

Declaration Summary
val PenDistribution.uncertainty: Double How unsure a distribution is, in squared drawing units: the spread of where the next point could land, counting both each component's own spread and how far apart the components sit. Use it to find the moments worth a close-up.

DensityImage

class DensityImage(val width: Int, val height: Int, val area: DoubleArray)

Accumulates FLines into a grid of counts over a region of drawing coordinates and tone-maps them into an image: futuresDensity's canvas, usable on its own for any pile of lines.

Declaration Summary
fun add(line: FLine, weight: Float = 1f) Add line's marks, one unit of ink per pixel of length, anti-aliased.
fun toneMapped(): IntArray Counts as ARGB pixels: black through blue to white, logarithmically.
fun ink(line: FLine, color: Vec4, pixels: IntArray) Draw line solidly over pixels in color.

PenCloseUp

class PenCloseUp(val tail: FLine, val penUp: Boolean, val distribution: PenDistribution)

One moment of a PenLine: its last few points, whether its pen was up, and what it expected next.

Declaration Summary
fun lines(color: Vec4 = Vec4(0.85f, 0.9f, 1f, 1f)): List<FLine> The tail in color and the distribution's ellipses.

sense.kt

What a sensing pen sees of the ink around it: the Kotlin half of python/fieldpen/sense.py, which has the canonical definition. PenModelTest holds the two together.

At each point the pen sees every point drawn before it except its own last recent, plus any ink added from outside with addInk. Around the pen, sectors equal wedges of direction (sector k covers atan2(dy, dx) in [-pi + k * 2pi / sectors, -pi + (k + 1) * 2pi / sectors)) each report 1 - d / radius for their nearest visible point within radius, or 0. Two more values follow, the way to the middle of all the visible ink, tanh((cx - x) / CENTRE_SCALE) and the same for y: what is close, then where the mass of the drawing is. Units are model units throughout.

src/jvmMain/kotlin/afield/ai/learning/pen/sense.kt — read the source

PenSense

class PenSense(val sectors: Int, val radius: Double, val recent: Int)

The ink a pen has drawn or been shown, kept in a grid of cells radius wide so that a look around the pen touches only the nine cells near it.

Declaration Summary
fun add(x: Double, y: Double) Record the point the pen has just reached, and make the points recent back visible.
fun addInk(x: Double, y: Double) Add ink the pen did not draw, visible at once: lines around it it should sense.
fun features(x: Double, y: Double, out: FloatArray, offset: Int) Write what the pen sees from (x, y) into out from offset, size values.
fun copy(): PenSense An independent copy, for a forked pen.
fun points(): List<Pair<Double, Double>> Every point the pen has drawn or been shown, in model units: for drawing what it senses.
const val CENTRE_SCALE Model units over which the pull towards the middle of the ink saturates (fieldpen.sense).
fun sectorOf(dx: Double, dy: Double, sectors: Int): Int The wedge a direction falls in, exactly as fieldpen.sense.sector_of computes it.

ChatHistory.kt

src/jvmMain/kotlin/afield/ai/memory/ChatHistory.kt — read the source

ChatHistory

class ChatHistory private constructor(val workspace: File)

The saved AI4 chats of one workspace, searchable from any AI4 turn: the transcript layer under UserMemory.

Declaration Summary
data class Hit(val chat: String, val address: String, val kind: String, val snippet: String) One matching block: the chat it is in, its address there, its kind, and a snippet around the match.
fun forDocument(documentDir: File): ChatHistory The history of the workspace holding the document folder documentDir.
fun forWorkspace(workspace: File): ChatHistory
fun offeredFor(documentPath: String?): ChatHistory? The history an interactive AI4 turn on the document at documentPath is offered: null when memory is off (AFIELD_AI4_MEMORY) or there is no document.
fun splitCitation(citation: String): Pair<String, String?> Splits chat@address into its two halves; a bare chat name has a null address.
data class Turn(val chat: String, val node: String, val ts: Long, val first: String, val last: String, val request: String, val onHead: Boolean) One saved turn: the chat, its session-tree node, when it was saved, the stretch of blocks it added (as addresses), what the person asked, and whether it is on the chat's current branch (false: rewound away).
fun turnsSince(since: Long): List<Turn> Every turn the person started that was saved after since (epoch ms), oldest first.
fun chats(): List<String> The chats, as name · N turns.
fun search(query: String, chat: String = "", limit: Int = 30): List<Hit> Blocks containing query (case-insensitive), at most limit, walking the chats in document-name order. chat narrows to one chat, or to chats whose name starts with it.
fun read(chat: String, from: String, to: String, maxChars: Int): ChatLogViews.Page A stretch of chat as text, each block headed by its address. from may be a chat@address citation, in which case chat may be blank. With to blank and from set, reads from from to the end of its branch.

Dreaming.kt

src/jvmMain/kotlin/afield/ai/memory/Dreaming.kt — read the source

Dreaming

object Dreaming

Dreaming: an AI4 turn, with nobody present, that consolidates memory against the transcripts

Declaration Summary
const val MAX_ROUNDS
const val FIRST_LOOKBACK_MS
const val IDLE_QUIET_MS
const val MIN_INTERVAL_MS
const val MIN_NEW_TURNS
const val MAX_LISTED_TURNS The brief lists at most this many turns, newest kept; the rest are still searchable.
const val LOG_DIR
fun mode(): String off, manual or idle (the default), from AFIELD_AI4_DREAM.
data class State(val watermarks: Map<String, Long> = emptyMap(), val lastAttemptAt: Map<String, Long> = emptyMap()) What is remembered between passes, per workspace: how far the chats have been read, and when a pass last ran.
data class Report(val ok: Boolean, val message: String, val turnsRead: Int = 0, val created: List<String> = emptyList(), val updated: List<String> = emptyList(), val deleted: List<String> = emptyList(), val rounds: Int = 0, val log: String = "") What a pass did, for the palette's notification, the backdoor's reply and the log.
fun readState(memory: UserMemory): State
fun pending(memory: UserMemory, history: ChatHistory, now: Long = System.currentTimeMillis()): Pair<Long, List<ChatHistory.Turn>> The turns a pass over history would read now, and the watermark it starts from.
fun idleDue(memory: UserMemory, history: ChatHistory, now: Long = System.currentTimeMillis()): Boolean Whether an idle pass is due now: see the class comment.
val INSTRUCTIONS: String What the dreaming turn is told, as its instructions.
fun brief(memory: UserMemory, history: ChatHistory, since: Long, turns: List<ChatHistory.Turn>): String The turn's request: the index, and the conversations since the last pass.
fun run(memory: UserMemory, history: ChatHistory, bridge: LlmBridge, trigger: String, now: Long = System.currentTimeMillis(), maxRounds: Int = MAX_ROUNDS): Report One dream pass over history for memory, with bridge as the model. Synchronous; one pass at a time across Field (running). trigger names what started it, for the log.
fun startIdleWatcher(workspace: () -> File?, quiet: () -> Boolean, bridge: () -> LlmBridge) Starts the daemon that dreams when Field is idle (see the class comment), over the server's workspace. Does nothing unless memory is on and mode is idle. quiet reports quiet mode; bridge makes the model for each pass.

UserMemory.kt

src/jvmMain/kotlin/afield/ai/memory/UserMemory.kt — read the source

Top-level values

Declaration Summary
const val MEMORY_CONTRACT: String What every AI4 turn with memory is told about it: what memory is for, deliberately not a set of rules about what to record (see UserMemory). It does not change from turn to turn.
const val HISTORY_CONTRACT: String What a turn is told about ChatHistory.

UserMemory

class UserMemory(val dir: File, private val commitEachChange: Boolean = true)

AI4's memory of the person it works with, across sessions and documents

Declaration Summary
val dir: File
data class Note(val name: String, val description: String, val kind: String, val status: String, val sources: List<String>, val updated: String, val body: String, val revision: String) One note as parsed from disk. revision is the SHA-256 of the file's bytes.
data class Outcome(val ok: Boolean, val message: String, val note: Note? = null, val conflict: Boolean = false) What a write or delete did: ok false carries the reason, and conflict marks a stale or missing revision.
const val MAX_INDEX_CHARS The index added to the instructions is cut at this many characters, with a pointer to the rest.
const val MAX_DESCRIPTION_CHARS
const val MAX_BODY_CHARS
const val INDEX_FILE
val KINDS The kinds a note may have, in the order the index lists them.
val STATUSES
fun enabled(): Boolean Whether memory is on: AFIELD_AI4_MEMORY is not off/0/false/no.
fun defaultDir(): File AFIELD_AI4_MEMORY_DIR, else ~/.afield/ai4/memory.
fun forPerson(): UserMemory? The person's memory, or null when memory is off. One instance per folder, so writes serialise.
fun at(dir: File): UserMemory The memory kept in dir (an eval's own folder, say).
fun nameProblem(name: String): String?
fun notes(): List<Note> Every note, newest first within each kind, in KINDS order. Unparseable files are skipped.
fun read(name: String): Note?
fun write(name: String, description: String, body: String, kind: String, status: String, sources: List<String>, revision: String, reason: String = ""): Outcome Create the note name, or replace it. Replacing needs the revision from the last read, so a note a person edited by hand meanwhile is not overwritten; creating needs a blank one.
fun delete(name: String, reason: String): Outcome
fun index(notes: List<Note> = notes()): String The index the instructions carry: one line per note, name (kind, status): description, cut at MAX_INDEX_CHARS with a count of what was left out. Empty string when there are no notes.
fun commitAll(message: String): Unit Commit whatever the folder holds now, as one change: what a dream pass does at its end.
fun indexText(index: String = index()): String The memory index as the instructions carry it, under a heading. It changes whenever a note does, so it is sent as a volatile fragment and does not disturb the prompt cache.

MarkdownChunker.kt

Markdown cut into the pieces semantic search indexes and an embedder can read whole.

Four things go wrong when a page is cut on its # lines and indexed raw, and each has an answer here. A # line inside a code fence is a comment rather than a heading, so headings count only outside fences. The generated reference pages carry their <span class=…> markup into the indexed text, so markup outside code is reduced to the text it wraps. A section longer than the window the embedder reads (around 512 tokens, which DEFAULT_MAX_CHARS approximates) loses its end, so a long section is split on paragraph boundaries. And a section alone says nothing about where it sits ("Kotlin side", of what?), so every chunk carries a breadcrumb of page title, parent headings and its own.

src/jvmMain/kotlin/afield/ai/retrieval/MarkdownChunker.kt — read the source

RelatedContextDiscovery.kt

Suggests the guides and example files most related to a source path, for AI tools that hand an agent a symbol or file.

RelatedContextDiscovery.forPath scores the Markdown files and the .kt/.kts files under an examples/ directory beneath src, dev_docs, public and docs in the checkout against the path's directory and camel-case name tokens, and returns up to six of each, best first. The file list is walked once and each path's answer is cached. An afield:// path gets the connected compute-and-render example.

src/jvmMain/kotlin/afield/ai/retrieval/RelatedContextDiscovery.kt — read the source

RelatedContextHints

data class RelatedContextHints(val guides: List<String> = emptyList(), val examples: List<String> = emptyList())

Up to six related guide paths and six example paths, best match first.

Declaration Summary
val guides: List<String>
val examples: List<String>

RelatedContextDiscovery

object RelatedContextDiscovery

Process-wide related-context lookup rooted at the current working directory.

Declaration Summary
fun forPath(rawPath: String?): RelatedContextHints

RetrievalEval.kt

How well documentation search answers the questions the repository already asks of it.

Queries and answers come from two sources the authors wrote for readers rather than for a benchmark: the text of every cross-link between authored docs pages ([drawing with FLines](fline_examples.md) is a query whose answer is fline_examples.md; the standard anchor-text method), and the why text of each docs: entry in the agent transcripts (dev_docs/agents/transcripts/<name>.yaml), each of which says what a page explains. An anchor is left out when its text is generic (here, this page, api) or points at three or more different pages; the page a link sits on is not counted against it, since it contains the anchor text by construction.

src/jvmMain/kotlin/afield/ai/retrieval/RetrievalEval.kt — read the source

Top-level functions

Declaration Summary
fun main(args: Array<String>) Score documentation search on RetrievalEval.cases. Run from a checkout with an isolated index: -Dafield.semanticSearch.cacheRoot=<dir with config.json + models> and -Dafield.semanticSearch.indexPath=<dir>; -Dafield.semanticSearch.corpora=documentation keeps the build to minutes. Arguments: rebuild to (re)build first; then fusion modes to compare (default: hybrid lexical dense). Writes per-case ranks to build/retrieval-eval/<mode>.tsv.

RetrievalEval

object RetrievalEval

Query sets built from the repository's own prose, and the hit@1, hit@5 and MRR over them.

Declaration Summary
data class Case(val set: String, val query: String, val pages: Set<String>, val excludePage: String = "")
fun anchorCases(docsRoot: File): List<Case> Cross-links between authored pages (not the generated reference, not assets).
fun whyCases(transcriptsDir: File): List<Case> docs: [{page, why}] in the agent transcripts: what a page explains, in its author's words.
data class Lesson(val title: String, val files: List<String>, val summary: String)
fun graphicsLessons(index: File): List<Lesson> The graphics curriculum's lessons from its generated index: the lesson table and the reverse API index.
fun tutorialCases(checkout: Path): List<Case> Tutorial search, from the transcripts' docs links: the title a docs page's own author gave it is a query, and the tutorials that link to that page answer it. The summaries indexed for tutorials leave these links out.
fun cases(checkout: Path): List<Case>
data class Score(val set: String, val n: Int, val hit1: Int, val hit5: Int, val mrr: Double)
fun rank(case: Case, results: List<String>): Int? Rank of the first result on an answering page, counting pages once and skipping Case.excludePage. search returns result paths relative to the checkout (public/docs/...), best first.
fun score(cases: List<Case>, search: (String) -> List<String>): Pair<List<Score>, List<Pair<Case, Int?>>>

SemanticRetrievalService.kt

Hybrid semantic search over Field's own source, the open workspace and the documentation, backed by a local Lucene index and an ONNX embedding model.

Each indexed item is a SemanticCapsule carrying an intent text, an implementation text and a lexical text. SemanticRetrievalService.query runs BM25 and symbol matches alongside vector nearest-neighbour searches on the intent and implementation embeddings, fuses the ranks, and filters by corpus (field-internals, workspace, documentation), path, kind, document, box and property.

Models and cache

OnnxSemanticEmbedder implements SemanticEmbedder with a Hugging Face tokenizer and ONNX Runtime. The model presets download from Hugging Face through SemanticRetrievalService.downloadPreset; models, settings and the index live under ~/.afield/semantic-search unless afield.semanticSearch.cacheRoot (or AFIELD_SEMANTIC_SEARCH_CACHE_ROOT) says otherwise.

Rebuilding

SemanticRetrievalService.rebuild and SemanticRetrievalService.startRebuild rebuild the index; SemanticRetrievalService.startIdleRebuildWatcher rebuilds when workspace documents change.

src/jvmMain/kotlin/afield/ai/retrieval/SemanticRetrievalService.kt — read the source

SemanticRetrievalStatus

data class SemanticRetrievalStatus(val enabled: Boolean, val indexPath: String, val indexExists: Boolean, val indexedDocuments: Int = 0, val indexedCapsules: Int = 0, val capsuleBackend: String = "source-index-capsules", val embedderBackend: String = "disabled", val embeddingDimension: Int = 0, val lastBuildEpochMs: Long = 0, val workspaceRoot: String = "", val workspaceDocuments: Int = 0, val workspaceSidecarFiles: Int = 0, val corpusFingerprint: String = "", val currentCorpusFingerprint: String = "", val indexStale: Boolean = false, val staleDocuments: Int = -1, val message: String = "")

Declaration Summary
val enabled: Boolean
val indexPath: String
val indexExists: Boolean
val indexedDocuments: Int
val indexedCapsules: Int
val capsuleBackend: String
val embedderBackend: String
val embeddingDimension: Int
val lastBuildEpochMs: Long
val workspaceRoot: String
val workspaceDocuments: Int
val workspaceSidecarFiles: Int
val corpusFingerprint: String
val currentCorpusFingerprint: String
val indexStale: Boolean
val staleDocuments: Int
val message: String

SemanticRetrievalConfig

data class SemanticRetrievalConfig(val enabled: Boolean = true, val presetId: String = "granite-97m-r2-quantized", val modelPath: String = "", val tokenizerPath: String = "", val dimension: Int = 384, val maxTokens: Int = 512, val queryPrefix: String = "", val documentPrefix: String = "")

Declaration Summary
val enabled: Boolean
val presetId: String
val modelPath: String
val tokenizerPath: String
val dimension: Int
val maxTokens: Int
val queryPrefix: String
val documentPrefix: String

SemanticRetrievalModelPreset

data class SemanticRetrievalModelPreset(val id: String, val label: String, val modelUrl: String, val tokenizerUrl: String, val modelFileName: String, val tokenizerFileName: String, val dimension: Int, val maxTokens: Int, val queryPrefix: String = "", val documentPrefix: String = "", val note: String = "")

Declaration Summary
val id: String
val label: String
val modelUrl: String
val tokenizerUrl: String
val modelFileName: String
val tokenizerFileName: String
val dimension: Int
val maxTokens: Int
val queryPrefix: String
val documentPrefix: String
val note: String

SemanticRetrievalFileState

data class SemanticRetrievalFileState(val path: String = "", val exists: Boolean = false, val sizeBytes: Long = 0, val lastModifiedEpochMs: Long = 0)

Declaration Summary
val path: String
val exists: Boolean
val sizeBytes: Long
val lastModifiedEpochMs: Long

SemanticRetrievalSettingsStatus

data class SemanticRetrievalSettingsStatus(val config: SemanticRetrievalConfig, val status: SemanticRetrievalStatus, val model: SemanticRetrievalModelInfo, val presets: List<SemanticRetrievalModelPreset>, val modelFile: SemanticRetrievalFileState, val tokenizerFile: SemanticRetrievalFileState, val indexSizeBytes: Long, val modelCacheSizeBytes: Long, val configPath: String, val cacheRoot: String, val downloadRunning: Boolean = false, val rebuild: SemanticRetrievalBuildStatus = SemanticRetrievalBuildStatus(), val message: String = "")

Declaration Summary
val config: SemanticRetrievalConfig
val status: SemanticRetrievalStatus
val model: SemanticRetrievalModelInfo
val presets: List<SemanticRetrievalModelPreset>
val modelFile: SemanticRetrievalFileState
val tokenizerFile: SemanticRetrievalFileState
val indexSizeBytes: Long
val modelCacheSizeBytes: Long
val configPath: String
val cacheRoot: String
val downloadRunning: Boolean
val rebuild: SemanticRetrievalBuildStatus
val message: String

SemanticRetrievalBuildStatus

data class SemanticRetrievalBuildStatus(val running: Boolean = false, val status: String = "idle", val startedAtEpochMs: Long = 0, val finishedAtEpochMs: Long = 0, val message: String = "", val step: String = "", val indexedCapsules: Int = 0)

Declaration Summary
val running: Boolean
val status: String
val startedAtEpochMs: Long
val finishedAtEpochMs: Long
val message: String
val step: String
val indexedCapsules: Int

SemanticRetrievalBuildResult

data class SemanticRetrievalBuildResult(val success: Boolean, val message: String, val status: SemanticRetrievalStatus, val rebuild: SemanticRetrievalBuildStatus = SemanticRetrievalBuildStatus())

Declaration Summary
val success: Boolean
val message: String
val status: SemanticRetrievalStatus
val rebuild: SemanticRetrievalBuildStatus

SemanticRetrievalQueryRequest

data class SemanticRetrievalQueryRequest(val query: String, val limit: Int = 10, val corpus: String = "", val corpora: List<String> = emptyList(), val pathPrefix: String = "", val kinds: List<String> = emptyList(), val documentName: String = "", val boxId: String = "", val property: String = "", val rebuildIfEmpty: Boolean = true, val includeCapsule: Boolean = false, val includeSource: Boolean = false)

Declaration Summary
val query: String
val limit: Int
val corpus: String
val corpora: List<String>
val pathPrefix: String
val kinds: List<String>
val documentName: String
val boxId: String
val property: String
val rebuildIfEmpty: Boolean
val includeCapsule: Boolean
val includeSource: Boolean

SemanticRetrievalQueryResult

data class SemanticRetrievalQueryResult(val success: Boolean, val message: String, val status: SemanticRetrievalStatus, val results: List<SemanticRetrievalHit> = emptyList())

Declaration Summary
val success: Boolean
val message: String
val status: SemanticRetrievalStatus
val results: List<SemanticRetrievalHit>

SemanticRetrievalHit

data class SemanticRetrievalHit(val id: String, val scale: String, val corpus: String, val kind: String, val symbol: String, val title: String, val path: String, val line: Int, val endLine: Int = 0, val parentId: String = "", val documentName: String = "", val boxName: String = "", val boxId: String = "", val property: String = "", val language: String = "", val score: Double, val vectorRank: Int = 0, val bm25Rank: Int = 0, val symbolRank: Int = 0, val vectorScore: Float = 0f, val bm25Score: Float = 0f, val symbolScore: Float = 0f, val capsule: String = "", val sourcePreview: String = "")

Declaration Summary
val id: String
val scale: String
val corpus: String
val kind: String
val symbol: String
val title: String
val path: String
val line: Int
val endLine: Int
val parentId: String
val documentName: String
val boxName: String
val boxId: String
val property: String
val language: String
val score: Double
val vectorRank: Int
val bm25Rank: Int
val symbolRank: Int
val vectorScore: Float
val bm25Score: Float
val symbolScore: Float
val capsule: String
val sourcePreview: String

SemanticRetrievalModelInfo

data class SemanticRetrievalModelInfo(val backend: String, val dimension: Int, val modelPath: String = "", val tokenizerPath: String = "", val queryPrefix: String = "", val documentPrefix: String = "", val message: String = "")

Declaration Summary
val backend: String
val dimension: Int
val modelPath: String
val tokenizerPath: String
val queryPrefix: String
val documentPrefix: String
val message: String

SemanticRetrievalDownloadRequest

data class SemanticRetrievalDownloadRequest(val presetId: String = "granite-97m-r2-quantized")

Declaration Summary
val presetId: String

SemanticRetrievalConfigSaveRequest

data class SemanticRetrievalConfigSaveRequest(val enabled: Boolean? = null, val presetId: String? = null, val modelPath: String? = null, val tokenizerPath: String? = null, val dimension: Int? = null, val maxTokens: Int? = null, val queryPrefix: String? = null, val documentPrefix: String? = null)

Declaration Summary
val enabled: Boolean?
val presetId: String?
val modelPath: String?
val tokenizerPath: String?
val dimension: Int?
val maxTokens: Int?
val queryPrefix: String?
val documentPrefix: String?

SemanticRetrievalDeleteCacheRequest

data class SemanticRetrievalDeleteCacheRequest(val target: String = "index")

Declaration Summary
val target: String

SemanticCapsule

data class SemanticCapsule(val id: String, val scale: String, val corpus: String, val kind: String, val symbol: String, val title: String, val path: String, val line: Int, val endLine: Int = 0, val parentId: String = "", val documentName: String = "", val boxName: String = "", val boxId: String = "", val property: String = "", val language: String = "", val signature: String = "", val documentation: String = "", val metadata: String = "", val source: String = "")

Declaration Summary
val id: String
val scale: String
val corpus: String
val kind: String
val symbol: String
val title: String
val path: String
val line: Int
val endLine: Int
val parentId: String
val documentName: String
val boxName: String
val boxId: String
val property: String
val language: String
val signature: String
val documentation: String
val metadata: String
val source: String
fun intentText(): String
fun implementationText(): String
fun lexicalText(): String

SemanticEmbedder

interface SemanticEmbedder : AutoCloseable

Declaration Summary
val dimension: Int
val backend: String
fun encodeQueries(texts: List<String>): List<FloatArray>
fun encodeDocuments(texts: List<String>): List<FloatArray>

SemanticRetrievalService

object SemanticRetrievalService

Declaration Summary
val availableCorpora: List<String>
val presets: List<SemanticRetrievalModelPreset>
fun modelInfo(): SemanticRetrievalModelInfo
fun status(): SemanticRetrievalStatus
fun settingsStatus(): SemanticRetrievalSettingsStatus
fun settingsStatusSnapshot(): SemanticRetrievalSettingsStatus Non-blocking counterpart to settingsStatus for the welcome screen. Returns the last computed status immediately (or a cheap placeholder before the first compute finishes) and refreshes in the background when stale. Keeps the one-time corpus-fingerprint rescan and the Lucene/directory-size walks off the caller's thread so they can't stall the shared workspace-search dispatcher — and, through it, a document the user opens right after.
fun saveConfig(request: SemanticRetrievalConfigSaveRequest): SemanticRetrievalSettingsStatus
fun downloadPreset(request: SemanticRetrievalDownloadRequest): SemanticRetrievalSettingsStatus
fun deleteCache(request: SemanticRetrievalDeleteCacheRequest): SemanticRetrievalSettingsStatus
fun rebuild(): SemanticRetrievalBuildResult
fun startRebuild(): SemanticRetrievalBuildResult
fun query(request: SemanticRetrievalQueryRequest): SemanticRetrievalQueryResult
fun startIdleRebuildWatcher() Starts a daemon that rebuilds a stale index once the workspace has been quiet for IDLE_QUIET_MS. It only touches an index this workspace built (the meta's workspaceRoot), since the index is shared machine-wide and an automation server has a workspace of its own. AFIELD_SEMANTIC_IDLE_REBUILD=0 turns it off.

OnnxSemanticEmbedder

class OnnxSemanticEmbedder private constructor(private val config: Config, private val env: OrtEnvironment, private val session: OrtSession, private val tokenizer: HuggingFaceTokenizer, private val actualProvider: String) : SemanticEmbedder

Declaration Summary
override val dimension: Int
override val backend: String
override fun encodeQueries(texts: List<String>): List<FloatArray>
override fun encodeDocuments(texts: List<String>): List<FloatArray>
override fun close()
data class Config(val modelPath: Path?, val tokenizerPath: Path?, val dimension: Int, val maxTokens: Int, val queryPrefix: String, val documentPrefix: String, val provider: String, val fixedTokenLength: Int, val fixedBatchSize: Int)

stippletransport.kt

Runs a learned stipple transport on the CPU: a small SiLU network, trained by the optional PyTorch tool in optional/transport-flow, that moves points from a uniform source rectangle toward an image's density.

loadStippleTransport reads the exported JSON model. StippleTransport.transport and StippleTransport.flowMap integrate points through the learned velocity field (Euler or midpoint steps), StippleTransport.pathsFrom returns each point's path as an FLine, and StippleTransport.sourceParticles draws the source points. A temporal model also takes a movie time, so you can draw source points once and re-transport the same list for each frame. StippleTransportTest covers loading and integration.

src/jvmMain/kotlin/afield/geometry/spatial/stippletransport.kt — read the source

Used in: Stipple transport

Top-level functions

Declaration Summary
fun loadStippleTransport(file: File): StippleTransport Loads the optional PyTorch stipple trainer's portable field.transport-flow.v1 model.
fun loadStippleTransport(path: String): StippleTransport Convenience spelling of loadStippleTransport for a filename.

StippleTransport

class StippleTransport private constructor(private val data: StippleTransportData)

A reusable density-conditioned coordinate warp, independent of its training stipples.

Declaration Summary
val temporal: Boolean Whether the network has a fourth input for movie time.
val frameTimes: List<Double> Discrete movie times used for training, copied so callers cannot alter the model.
val parameterCount: Int Number of learned scalar weights and biases.
val sourceHalfExtent: List<Double> Half-width and half-height of the uniform canonical source rectangle.
fun velocity(at: Vec3, transportTime: Double, movieTime: Double = 0.0): Vec3 Predicts (vx,vy,0) at any point, at two independent times.
fun transport(points: List<Vec3>, transportTime: Double = 1.0, movieTime: Double = 0.0, steps: Int = 32, fromTransportTime: Double = 0.0, integrator: FlowIntegrator = FlowIntegrator.MIDPOINT): List<Vec3> Integrates arbitrary particles, curve vertices or lattice samples. No training-point lookup. fromTransportTime can exceed transportTime for inversion; both can overshoot 0..1.
fun flowMap(at: Vec3, transportTime: Double = 1.0, movieTime: Double = 0.0, steps: Int = 32): Vec3 Single-point flow map, with the same semantics as transport.
fun pathsFrom(points: List<Vec3>, transportTime: Double = 1.0, movieTime: Double = 0.0, steps: Int = 32, fromTransportTime: Double = 0.0, integrator: FlowIntegrator = FlowIntegrator.MIDPOINT): List<FLine> Traces supplied geometry in transport time, one FLine per input point.
fun sourceParticles(count: Int, seed: Long = 1L, grid: Boolean = false): List<Vec3> Draw once and retain the returned list for persistent movie identity.
fun unsafeBlendWeights(other: StippleTransport, amount: Double): StippleTransport Deliberately unsafe weight interpolation; matching metadata does not align hidden neurons. Prefer conditioning one shared model on movie time. Sequential fine-tuning gives checkpoints shared ancestry but still supplies no guarantee. amount is not clamped.
fun fromJson(json: String): StippleTransport Parses a portable model without requiring a filesystem path.

neuralparticles.kt

Taking a small trained network to the GPU: MlpWeights is a flat, layer-major snapshot of a multilayer perceptron's weights, and MlpWeights.glsl emits a GLSL function that evaluates the same network out of a storage buffer.

What that buys is a particle whose update rule was trained rather than written. flowMatch (see flowmatching.kt) already fits a velocity field v(x, t) in a couple of seconds of pure Kotlin; a compute shader stepping a buffer of particles can evaluate that field per particle per frame, provided the two sides agree about what the network is. This file is that agreement, and afield.examples.four.NeuralFieldParitySmoke measures that it holds on real hardware.

Nothing here is particle-specific: a net that takes a position and returns a velocity, a net that takes a neighbour offset and returns an interaction term, and a net that takes anything and returns anything are all the same object. The particle system is what consumes it.

Two comparisons, not one

There are two distinct errors between "the network Smile trained" and "the network the GPU runs", they have very different sizes, and conflating them makes the unavoidable one look like a bug.

  • Precision. Smile evaluates in Double; a shader evaluates in float. Agreement is therefore limited to fp32 by construction — a few parts in a million, relative, and rather more for an output that is a cancelling sum. MlpWeights.evaluate is the fp32 reference in Kotlin, so this error can be measured on its own with no GPU present at all.
  • Transcription. The order of the layers, the orientation of each weight matrix, the slope of the leaky ReLU, whether the output layer has an activation. Every one of these is either exactly right or grossly wrong, and a grossly wrong one still produces smooth, plausible, entirely fictional output.

So the GPU is compared against MlpWeights.evaluate, fp32 against fp32, where the only remaining freedom is the order the hardware chooses to accumulate a dot product in; and evaluate is compared against Smile separately. A single comparison against Double would have to be loose enough to absorb the precision gap, which is a tolerance wide enough to hide a transposed matrix in a small network.

The weight layout

MlpWeights.flat runs layer by layer from the first hidden layer to the output layer. Each layer contributes its weight matrix, row-major with one row per output neuron, then its bias vector. So for a layer with n outputs over p inputs, the weight from input i to output o is at weightOffset(layer) + o * p + i, and its bias is at biasOffset(layer) + o. The input layer contributes nothing — it holds no weights.

This is the layout a shader wants to read, and it is also the layout Smile happens to store. The two are not relied on to coincide: VectorMLP.exportWeights in flowmatching.kt reads element by element through DenseMatrix.get(row, column) rather than copying memory, so a change of storage order upstream cannot silently transpose the network.

src/jvmMain/kotlin/afield/simulation/particles/neuralparticles.kt — read the source

Used in: Neural particle systems

Top-level functions

Declaration Summary
fun MlpWeights.blendWith(other: MlpWeights, t: Float): MlpWeights Two networks of the same shape, averaged weight by weight — (1-t)·this + t·other.
fun FlowMatchExport.blendWith(other: FlowMatchExport, t: Float): FlowMatchExport MlpWeights.blendWith for a whole field, carrying the training frame and source with it.
fun MlpWeights.glsl(name: String = "neuralField"): String GLSL that evaluates this network out of a storage buffer, as a buffer_reference type and a function named name.
fun FlowMatchExport.glsl(name: String = "neuralField"): String GLSL for the whole field: the network from MlpWeights.glsl, the time encoding, and a neuralVelocity that converts in and out of the training frame.

MlpWeights

class MlpWeights(val inputs: Int, val outputs: Int, val hidden: IntArray, val activation: MlpActivation, val flat: FloatArray)

A flat, layer-major snapshot of a trained multilayer perceptron: the layer widths, the hidden activation, and one FloatArray holding every weight and bias.

Declaration Summary
val inputs: Int Width of the input vector.
val outputs: Int Width of the output vector.
val hidden: IntArray Hidden layer widths, in order.
val activation: MlpActivation The activation applied after every hidden layer. The output layer is always linear.
val flat: FloatArray Every weight and bias, laid out as described above.
val layerWidths: IntArray The width of each weight-bearing layer's output: the hidden widths, then outputs.
val layerInputs: IntArray The width of each weight-bearing layer's input: inputs, then the hidden widths.
val layerCount: Int How many weight-bearing layers there are — one more than the number of hidden layers.
fun weightOffset(layer: Int): Int Index into flat of the first weight of layer, which is layer's row 0, column 0.
fun biasOffset(layer: Int): Int Index into flat of the first bias of layer.
fun evaluate(x: FloatArray, into: FloatArray = FloatArray(outputs)): FloatArray The network's output for x, in Float, accumulated in exactly the order glsl accumulates it — bias first, then one multiply-add per input in index order.
val parameterCount: Int How many weights and biases this network is, which is flat.size.
override fun toString(): String
fun floatCount(inputs: Int, layerWidths: IntArray): Int The number of floats a network of these widths needs.

MlpActivation

enum class MlpActivation(val smileName: String)

The hidden activations this file can evaluate on both sides of the CPU/GPU line.

Constants: LEAKY, RELU, TANH, SIGMOID, LINEAR.

Declaration Summary
val smileName: String The name smile.base.mlp.Layer.builder knows this activation by.
fun apply(v: Float): Float This activation applied to one value, in Float.
const val LEAKY_SLOPE The negative-side slope of LEAKY, matching Smile's default.
fun of(smileName: String): MlpActivation The activation Smile calls smileName, or a failure naming the ones that exist.

FlowMatchExport

class FlowMatchExport(val network: MlpWeights, val dimension: Int, val timeFeatures: Int, val center: FloatArray, val scale: Float, val source: FloatArray? = null)

A trained velocity field packaged for a shader: the network, plus the three things around it that decide what its numbers mean.

Declaration Summary
val network: MlpWeights The trained network. Its inputs are dimension positions followed by the time encoding.
val dimension: Int 2 or 3 — how many position components the network takes.
val timeFeatures: Int How many sin/cos octaves of t follow raw t in the input vector.
val center: FloatArray The centre of the frame training happened in, in input coordinates.
val scale: Float The isotropic scale of that frame. One number, not one per axis.
val source: FloatArray? The cloud the field was trained to start from, interleaved by dimension and already in the normalised frame — or null if it was trained from a standard Gaussian.
val sourceCount: Int How many points are in source, or 0 if the field starts from a Gaussian.
override fun toString(): String

MlpAgreement

data class MlpAgreement(val worstRelative: Double, val worstAbsolute: Double, val worstAt: FloatArray, val comparisons: Int)

The largest relative disagreement between two evaluations of the same network, and the input it happened at — the statistic both halves of the parity test report.

Declaration Summary
val worstRelative: Double The largest relative disagreement seen.
val worstAbsolute: Double The largest absolute disagreement seen, in output units.
val worstAt: FloatArray The input at which worstRelative occurred.
val comparisons: Int How many outputs were compared in total.
override fun toString(): String
val nothing The neutral element: nothing compared yet.
fun accumulate(worst: MlpAgreement, at: FloatArray, expected: FloatArray, actual: FloatArray): MlpAgreement worst widened to include the disagreement between expected and actual at at.

neuralparticles_system.kt

A particle system driven by a trained velocity field: ShaderNeuralParticles integrates a buffer of particles along the field in a compute pass and draws the same allocation as points, with no copy between the two.

neuralparticles.kt settles what a network is on both sides of the CPU/GPU line and emits the GLSL that evaluates one; this file is what consumes that GLSL. The chain from a target shape to a moving cloud is flowMatch, then FlowMatchField.export(), then ShaderNeuralParticles and installInto. afield.examples.four.NeuralParticlesSmoke is the GPU smoke over that whole path, and the neural_particles agent transcript is that chain as three boxes.

Two of the design decisions reach the caller, so they are stated here rather than only on the declarations that implement them:

  • Positions are stored in the training frame, not in the coordinates the field was authored in, because integrating in input coordinates would convert into the frame and back out again on every step to reach the same answer. So NeuralParticleSettings's viewScale and viewCenter are in normalised units, where a scale of about 2.6 frames a cloud of roughly unit variance.
  • A particle is travelling a journey, not wandering a force field. A flow is a map: each particle goes from one specific source point to wherever the field takes it by t = 1, then starts again. That is why it carries a start and a t, and why reset has to seed from the field's own source cloud whenever the field has one.

Which settings are live follows from where each one is read. particleCount sizes the particle buffer, the compute dispatch and the point mesh at construction, so it cannot be raised afterwards, and name is written into the module and buffer names there. phaseSpread, sourceJitter and randomSeed are read by reset, which fills the buffer, so changing one takes a reset call. Everything else is read through a push-constant lambda every frame and takes effect on the next one, including stepsPerCycle and dwellCycles.

src/jvmMain/kotlin/afield/simulation/particles/neuralparticles_system.kt — read the source

Used in: Neural particle systems

NeuralParticleSettings

data class NeuralParticleSettings(var name: String = "neuralParticles", var particleCount: Int = 200_000, var stepsPerCycle: Int = 150, var dwellCycles: Float = 3f, var phaseSpread: Float = 1f, var pointSize: Float = 1.5f, var sourceColor: Vec4 = vec(0.15, 0.45, 1.0, 1.0), var targetColor: Vec4 = vec(1.0, 0.62, 0.22, 1.0), var intensity: Float = 0.5f, var arrivalBias: Float = 0.8f, var viewScale: Float = 2.6f, var viewCenter: Vector2f = Vector2f(0f, 0f), var flipY: Boolean = true, var sourceJitter: Float = 0.02f, var randomSeed: Long = 1L)

The knobs ShaderNeuralParticles takes.

Declaration Summary
var name: String Names the modules and buffers, so two systems in one renderer do not collide.
var particleCount: Int How many particles. A few hundred thousand is comfortable; see the class KDoc for cost.
var stepsPerCycle: Int Frames a particle takes to travel from t = 0 to t = 1.
var dwellCycles: Float How long a particle rests on the target once it arrives, as a multiple of the travel time.
var phaseSpread: Float How far apart in the cycle the particles start, as a fraction of a whole cycle.
var pointSize: Float Point size in pixels.
var sourceColor: Vec4 Colour a particle leaves the source with.
var targetColor: Vec4 Colour it arrives at the target with.
var intensity: Float Overall brightness. With additive blending this is the exposure control.
var arrivalBias: Float How strongly a particle's brightness is weighted toward the end of its journey, 0..1.
var viewScale: Float Half-height of the visible region, in the field's normalised units.
var viewCenter: Vector2f Centre of the visible region, in the field's normalised units.
var flipY: Boolean Whether to negate y on the way to clip space. On by default.
var sourceJitter: Float Gaussian spread, in the field's normalised units, added to each particle's source point.
var randomSeed: Long Seed for the source draw, so a scene reloads identically.

ShaderNeuralParticles

class ShaderNeuralParticles(val export: FlowMatchExport, val renderer: Renderer = fromContext(), configure: NeuralParticleSettings.() -> Unit = {})

A particle system whose velocity field is a trained network rather than a written rule.

Declaration Summary
val export: FlowMatchExport The trained field, from FlowMatchField.export().
val renderer: Renderer The renderer both passes are built against; the box's own by default.
val settings The settings configure produced, kept live.
val particleBuffer: FrameBufferGroup The particle state. Read by both passes, owned by neither.
val weightBuffer: FrameBufferGroup The network's weights, swappable between frames without recompiling anything.
val computeModule: ComputeModulePointer The integrator.
val drawModule: ModulePointer The draw.
val computeSource: String The compute shader source, as installed — editable.
val vertexSource: String The vertex shader source, as installed — editable.
val fragmentSource: String The fragment shader source, as installed — editable.
fun reset(seed: Long = settings.randomSeed) Redraws every particle's source point and restarts the cycle.
fun updateWeights(network: MlpWeights) Replaces the weights in place, with no recompilation — the network may be retrained live.
fun installInto(renderTarget: RenderTarget = renderer.renderList) Adds both passes to renderTarget's renderer: the integrator, then the draw.
fun removeFrom(renderTarget: RenderTarget = renderer.renderList) Takes both passes back out again.