Operations

May 21, 2026 · View on GitHub

Operations are the atomic units of computation in Caramba. Each operation has:

  • A YAML schema in pkg/asset/template/operation/ (defines inputs, outputs, config)
  • A CPU implementation under pkg/backend/device/cpu/ (Go + SIMD)
  • A CUDA implementation under pkg/backend/device/cuda/ (gated by cgo cuda)
  • A Metal implementation under pkg/backend/device/metal/ (gated by darwin && cgo)
  • An XLA implementation under pkg/backend/device/xla/ (gated by cgo xla)

No backend falls back silently. If a kernel is not implemented for a target backend, the build fails.


Device backend contract

Every compute kernel ultimately implements a method on device.Backend in puter/device/interface.go. Backend embeds 25 interfaces (151 methods total). Manifest operation IDs map to these methods directly, as composites, or via per-backend kernel registries (shape, optimizers). See backend-inventory.md for the audited cross-link.

Embedded interfaceMethods
Activation55
Physics9
Causal10
Elementwise11
PosPop5
VSA5
Losses6
Hawkes5
Pool4
Convolution4
ActiveInference4
PredictiveCoding4
Masking3
Attention3
Sampling3
Normalization3
Reduction5
LayerNorm2
RoPE2
Embedding2
Dequant2
Dot1
Matmul1
Dropout1
Quant1

In tables below, manifest op is the Caramba op: ID when one exists; means the method is on device.Backend only (no manifest template yet).


PosPop

Population-count helpers over strings and fixed-width integer buffers.

Backend methodManifest op
CountString
Count8
Count16
Count32
Count64

Activation

Unary and gated activations; packed GLU variants take packed with batch × halfCount, tensor GLU variants take separate gate and up buffers.

Backend methodManifest op
Expmath.exp
Logmath.log
Log1p
Expm1
Sigmoidactivation.sigmoid
LogSigmoid
Tanhactivation.tanh
Silu
Swishactivation.swish
GeluTanh
Geluactivation.gelu
ReLUactivation.relu
LeakyReLUactivation.leaky_relu
ELU
CELU
SELUactivation.selu
Softplus
Mish
Softsign
HardSigmoid
HardSwish
HardTanh
HardGelu
QuickGelu
TanhShrink
Softmaxmath.softmax
LogSoftmax
PReLU
PReLUV
LeakyReLUSlope
ELUAlpha
CELUAlpha
Threshold
HardTanhRange
Snake
SnakeParametric
HardShrink
SoftShrink
RReLU
GLU
GeGLU
GeGLUTanh
SwiGLUactivation.swiglu
ReGLU
SiGLU
GLUTensors
GeGLUTensors
GeGLUTanhTensors
SwiGLUTensors
ReGLUTensors
SiGLUTensors
LinGLU
SeGLU
LinGLUTensors
SeGLUTensors

Elementwise.ReLU duplicates Activation.ReLU on the same Backend surface.


Elementwise

Backend methodManifest op
Addmath.add
Sub
Mulmath.mul
Div
Max
Min
Abs
Neg
Sqrt
ReLUactivation.relu
Axpy

Additional elementwise helpers (math.sin, math.cos, math.sign, math.outer) live in kernel registries and are not separate Backend methods.


Reduction

Backend methodManifest op
Sum
Prod
ReduceMin
ReduceMax
L1Norm

Dot

Backend methodManifest op
Dot

Matmul

Backend methodManifest op
Matmulmath.matmul

projection.fused_qkv composes Matmul with attention wiring (see backend-inventory.md).


Pool

Backend methodManifest op
MaxPool2Dpooling.max_pool2d
AvgPool2Dpooling.avg_pool2d
AdaptiveMaxPool2Dpooling.adaptive_max_pool2d
AdaptiveAvgPool2Dpooling.adaptive_avg_pool2d

Convolution

Backend methodManifest op
Conv2Dconvolution.conv2d
Conv1Dconvolution.conv1d
Conv3Dconvolution.conv3d
ConvTranspose2Dconvolution.conv_transpose2d

Dropout

Backend methodManifest op
Dropoutmath.dropout

Losses

Backend methodManifest op
MSEtrain.loss.mse
MAE
Huber
BinaryCrossEntropy
KLDivergence
CrossEntropytrain.loss.cross_entropy

Gradient variants (train.grad.mse, train.grad.cross_entropy) are kernel-registry ops, not Backend methods.


Sampling

Backend methodManifest op
GreedySample
TopKSample
TopPSample

Embedding

Backend methodManifest op
Lookupembedding.token
Bag

Normalization

Backend methodManifest op
GroupNorm
InstanceNorm
BatchNormEval

LayerNorm

Backend methodManifest op
LayerNormmath.layernorm
RMSNormmath.rmsnorm

RoPE

Backend methodManifest op
RoPEpositional.rope
RoPEPairs

Hawkes

Backend methodManifest op
HawkesIntensityhawkes.intensity
HawkesKernelMatrixhawkes.kernel_matrix
HawkesLogLikelihoodhawkes.log_likelihood
MarkovMutualInformationmarkov_blanket.mutual_information
MarkovBlanketPartitionmarkov_blanket.partition

hawkes.simulate is a kernel-registry op (not on Backend).


Physics

Spatial-stencil and quantum-hydrodynamics operators. Unlike thermodynamic blocks, these are real Backend kernels (no shape.shift / shape.roll primitive exists).

Backend methodManifest op
Laplacianstencil.laplacian
Laplacian4
Grad1D
Divergence1D
FFT1D
IFFT1D
QuantumPotential
BohmianVelocity
MadelungContinuity

Causal

Backend methodManifest op
Cholesky
BackdoorAdjustmentcausal.backdoor_adjustment
FrontdoorAdjustmentcausal.frontdoor_adjustment
DoIntervenecausal.do_calculus
CATEcausal.cate
Counterfactualcausal.counterfactual
IVEstimatecausal.iv_estimate
DAGMarkovFactorizationcausal.dag_markov_factorization
MarkovFlowActivemarkov_blanket.flow_active
MarkovFlowInternalmarkov_blanket.flow_internal

Masking

Backend methodManifest op
ApplyMaskmasking.apply
CausalMaskmasking.causal
ALiBiBiaspositional.alibi

Attention

Backend methodManifest op
ScaledDotProductAttentionattention.sdpa
FlashAttention
MultiHeadAttentionattention.mqa, attention.gqa (composite)

attention.sliding_window is implemented via attention config / graph wiring, not a separate Backend method.


VSA

Backend methodManifest op
Bindvsa.bind
Bundlevsa.bundle
Permutevsa.permute
InversePermutevsa.inverse_permute
Similarityvsa.similarity

ActiveInference

Backend methodManifest op
FreeEnergyactive_inference.free_energy
ExpectedFreeEnergyactive_inference.expected_free_energy
BeliefUpdateactive_inference.belief_update
PrecisionWeightactive_inference.precision_weight

PredictiveCoding

Backend methodManifest op
Predictionpredictive_coding.prediction
PredictionErrorpredictive_coding.prediction_error
UpdateRepresentationpredictive_coding.update_representation
UpdateWeightspredictive_coding.update_weights

Dequant

Backend methodManifest op
Dequant
Dequant4

Quant

Backend methodManifest op
Quant

Manifest-only operations

These appear in manifests and templates but are not methods on device.Backend (optimizers, shape, control, tokenizer, model editing, benchmarks, etc.).

Attention (graph / config)

Op IDDescription
attention.sdpaScaled dot-product attention
attention.gqaGrouped-query attention
attention.mqaMulti-query attention
attention.sliding_windowSliding-window local attention

Tokenizer

Op IDDescription
tokenizer.loadLoad a tokenizer.json artifact
tokenizer.encodeEncode prompt text to token IDs
tokenizer.decodeDecode token IDs to text

Projection

Op IDDescription
projection.linearLinear projection (weight + optional bias)
projection.fused_qkvFused Q/K/V projection
projection.moeMixture-of-experts routing
model.loraLow-rank adaptation (LoRA)

Shape & control

Op IDDescription
shape.reshapeTensor reshape
shape.transposeTensor transpose
shape.concatConcatenate along a dimension
shape.splitSplit along a dimension
shape.sliceContiguous range extraction
shape.view_as_headsReshape for multi-head layout
shape.merge_headsMerge multi-head layout
control.repeatRepeat tensor along a dimension

Metal shape.slice is handled by operation_executor.applySlice, which currently requires start==0 and leading-dim slicing. The Metal failure maps to:

metal tensor: slice node %q currently supports start=0 with leading-dim slicing only (got start=%d, dim=%d, outer=%d)

Supported on Metal:

op: shape.slice
config: { dim: 1, start: 0, end: 4096 } # shape [1, 4112, 64], outer=1

Unsupported on Metal:

op: shape.slice
config: { dim: 1, start: 64, end: 128 } # start != 0

Run non-prefix slices on CPU or avoid them until Metal strided-copy support exists.

Math helpers (kernel registry)

Op IDDescription
math.sinElementwise sine
math.cosElementwise cosine
math.signElementwise sign
math.outerOuter product
math.logsumexpLog-sum-exp reduction
math.inv_sqrt_dim_scale1/sqrt(dim) scaling

Model & data

Op IDDescription
model.loadLoad weights checkpoint
model.freezeFreeze parameter nodes
model.graftGraft subgraph weights
model.adapterAdapter injection
model.surgeryStructural model surgery
data.huggingfaceHugging Face dataset binding
train.checkpoint.loadTraining checkpoint load
train.checkpoint.saveTraining checkpoint save

Benchmarks

Op IDDescription
bench.metric.accuracyClassification accuracy
bench.metric.perplexityLanguage-model perplexity
bench.metric.f1F1 score

Hawkes (registry)

Op IDDescription
hawkes.simulateSimulate Hawkes event sequences

Research / esoteric blocks

Composite blocks in pkg/asset/template/block/ bundle resident ops; they do not add device.Backend methods.

Energy-based models

Block IDDescription
block.energy.boltzmann_distributionEnergies → Boltzmann probabilities
block.energy.free_energy-beta^{-1} logsumexp(-beta E)
block.energy.langevin_stepOne externally differentiated sampler step
block.energy.contrastive_phasePer-sample positive/negative phase deltas

Optimizers

Optimizer steps are required IR ops but live in per-backend kernel registries, not on device.Backend. Templates: pkg/asset/template/operation/train/optimizer/.

OptimizerOp ID
Adamtrain.optimizer.adam
AdamWtrain.optimizer.adamw
SGDtrain.optimizer.sgd
Liontrain.optimizer.lion
AdaGradtrain.optimizer.adagrad
AdaDeltatrain.optimizer.adadelta
AdaMaxtrain.optimizer.adamax
RMSProptrain.optimizer.rmsprop
LAMBtrain.optimizer.lamb
LARStrain.optimizer.lars
L-BFGStrain.optimizer.lbfgs
Hebbiantrain.optimizer.hebbian

Operation schema format

Each operation is described by a YAML schema that drives the frontend node graph editor and the manifest compiler:

# pkg/asset/template/operation/attention/sdpa.yml
kind: Operation
category: attention
op: attention.sdpa
name: Scaled Dot-Product Attention

inputs:
  - name: query
    type: tensor
    required: true
  - name: key
    type: tensor
    required: true
  - name: value
    type: tensor
    required: true
  - name: mask
    type: mask
    required: false

outputs:
  - name: out
    type: tensor

config:
  d_model:
    type: int
    required: true
  n_heads:
    type: int
    required: true
  dropout:
    type: float
    default: 0.0
  causal:
    type: bool
    default: false

Adding a new operation

  1. Add the YAML schema in pkg/asset/template/operation/<category>/<name>.yml
  2. Implement the CPU kernel under pkg/backend/device/cpu/
    • Pure Go reference (always)
    • SIMD assembly where performance-critical (_amd64.s, _arm64.s)
  3. Wire device.Backend — add or extend a method in puter/device/interface.go when the op is compute
  4. Implement CUDA under pkg/backend/device/cuda/
  5. Implement Metal under pkg/backend/device/metal/
  6. Implement XLA under pkg/backend/device/xla/
  7. Register the operation in the manifest registry
  8. Write tests in a _test.go mirror, GoConvey, parity against scalar reference

The operation is then available in manifests as <category>.<name> and in the frontend operation picker.


Template blocks

Beyond individual operations, Caramba provides pre-wired blocks—composite subgraphs that appear as a single collapsed node. Blocks live in pkg/asset/template/block/:

Block categoryExamples
active_inferenceFree energy minimization block
causalCausal temporal block
energyBoltzmann normalization, EBM free energy, sampler steps
hawkesHawkes process attention block
markov_blanketMarkov blanket hierarchy block
memoryExternal memory read/write block
predictive_codingHierarchical prediction error block
vsaVSA bind-bundle-query block

Full model templates live in pkg/asset/template/model/ (llm, vision, audio, diffusion, etc.).