Skip to main content

Post-Encoder Modules

Overview

Post-encoder modules are optional torch-to-torch processing stages applied after ModelBase::forward() and before channel decoders. They transform a model’s raw output tensor (typically [B, C, H, W]) into a form suitable for decoding — most commonly collapsing spatial dimensions to [B, C].

Post-encoder modules are model-agnostic. They are not owned by GeneralEncoderModel or any other model subclass. SlotAssembler holds the active module as session configuration and applies it to the first output slot of whatever model is loaded — encoders, segmentation models, or JSON-defined RuntimeModel instances.

ModelBase::forward()  →  raw output [B, C, H, W]
        │
        ▼
PostEncoderModule::apply()   (optional — SlotAssembler session config)
        │
        ▼
ChannelDecoder::decode()     (e.g. TensorToFeatureVector, TensorToMask2D)
        │
        ▼
DataManager

Source: src/DeepLearning/post_encoder/

Abstract interface

// src/DeepLearning/post_encoder/PostEncoderModule.hpp

class PostEncoderModule {
public:
    virtual ~PostEncoderModule() = default;

    [[nodiscard]] virtual std::string name() const = 0;

  /// @pre features must be defined
    [[nodiscard]] virtual at::Tensor apply(at::Tensor const & features) const = 0;

  /// @param input_shape Feature shape excluding batch dim, e.g. {384, 7, 7}
    [[nodiscard]] virtual std::vector<int64_t>
    outputShape(std::vector<int64_t> const & input_shape) const = 0;
};

The header forward-declares at::Tensor to remain torch-free at inclusion time. Concrete .cpp files include libtorch directly.

Modules chain via PostEncoderPipeline (itself a PostEncoderModule). An empty pipeline is a pass-through.

Implementations

GlobalAvgPoolModule

[B, C, H, W] → [B, C] via at::adaptive_avg_pool2d({1, 1}) with spatial squeeze.

Registry key: "global_avg_pool". Sets collapses_spatial_dims = true.

apply() validates 4D input with B, C, H, W >= 1. Invalid input throws std::invalid_argument after spdlog::debug logging.

SpatialPointExtractModule

Extracts the C-dimensional feature vector at a 2-D point in source-image coordinates. Registry key: "spatial_point". Also collapses spatial dims.

Mode Mechanics
Nearest Scale point to feature-map pixel, clamp, slice [B, C, iy, ix]
Bilinear Normalise to [-1, 1], grid_sample with align_corners=true, border padding

The module is stateful: call setPoint(Point2D<float>) before each apply(). SlotAssembler::_updateSpatialPoint() reads the first point from SpatialPointModuleParams::point_key at the current frame.

Bilinear mode requires H >= 2 and W >= 2 (normalisation divides by H - 1, W - 1). Constructor requires positive source_image_size.

SpatialPointExtractModule forces single-frame batch inference (requiresSingleFrameBatch() returns true) because the query point is frame-specific.

PostEncoderPipeline

Ordered chain of modules. apply() threads the tensor through each stage. outputShape() propagates shape through all stages.

Registry

PostEncoderModuleRegistry is a singleton mapping keys to metadata, parameter schemas, and factories.

Method Purpose
moduleKeys() Sorted registered keys
getMetadata(key) Display name, description, collapses_spatial_dims
getSchema(key) ParameterSchema for AutoParamWidget
create(key, params_json, source_image_size) Instantiate module
collapsesSpatialDims(key) Whether module maps [B,C,H,W] → [B,C]
outputShape(key, input_shape, ...) Shape propagation without inference

create() returns nullptr for "none", empty key, or unknown keys.

Key Module collapses_spatial_dims
"global_avg_pool" GlobalAvgPoolModule true
"spatial_point" SpatialPointExtractModule true

Modules self-register at static init via RegisterPostEncoderModule<Params> in their .cpp file. Parameter structs live in PostEncoderModuleParams.hpp:

struct GlobalAvgPoolModuleParams {};

struct SpatialPointModuleParams {
    InterpolationMode interpolation = InterpolationMode::Nearest;
    std::string point_key;
};

To add a new module:

  1. Implement PostEncoderModule with outputShape().
  2. Define an rfl params struct (+ ParameterUIHints in PostEncoderParamSchemas.hpp).
  3. Add RegisterPostEncoderModule<Params>(...) in the module .cpp.

Model recommendations

Models may suggest a default post-encoder via ModelBase::recommendedPostEncoderModule():

Model Recommended key
GeneralEncoderModel "global_avg_pool"
RuntimeModel RuntimeModelSpec::recommended_post_encoder (optional JSON field)
Other models "" (none)

ModelInfo::recommended_post_encoder aggregates this for the widget. On model selection, DeepLearningPropertiesWidget pre-selects the recommended module in DeepLearningState::post_encoder_params. The user can override via PostEncoderWidget for any loaded model.

Integration with SlotAssembler

Post-encoder is owned by SlotAssembler::Impl::post_encoder_module, configured through:

void configurePostEncoderModule(
    dl::PostEncoderStepDescriptor const & params,
    ImageSize source_image_size = {});

PostEncoderStepDescriptor (SlotBindingTypes.hpp):

struct PostEncoderStepDescriptor {
    std::string module_key = "none";   // "none" or empty → no module
    std::string parameters_json = "{}";
};

Per-frame pipeline

Every inference mode follows the same pattern:

_updateSpatialPoint()          // spatial_point only
    → ModelBase::forward()
    → applyPostEncoderToFirstOutputSlot()   // first output slot only
    → decodeOutputs()

Free functions in PostEncoderOutputTransform.hpp:

  • applyPostEncoderToFirstOutputSlot() — transform first output tensor
  • effectiveOutputSlots() — propagate shapes for decoder UI and validation

ModelBase::outputSlots() always reports raw model shapes. SlotAssembler::currentModelInfo() uses effectiveOutputSlots() so output binding widgets reflect post-encoder shape changes.

Lifecycle

  • loadModel() and resetModel() clear post_encoder_module
  • PostEncoderWidget::syncToAssembler() re-applies saved params after weights load (_loadModelIfReady())
  • Parameter changes call configurePostEncoderModule() immediately when a model is loaded (weights not required for configuration)

Targeting: post-encoder applies to the first model output slot only. Per-slot targeting is planned.

Recurrent inference: recurrent tensor bindings cache the post-encoder output tensor (the same tensor passed to decoders) for the next frame’s input injection.

Decoder consistency

dl::constraints::validDecodersForPostEncoder() queries collapsesSpatialDims():

Post-encoder Allowed decoders
"none" or spatial-preserving Mask, Point, Line, FeatureVector
Spatial-collapsing (global_avg_pool, spatial_point) FeatureVectorDecoderParams only

DeepLearningPropertiesWidget::_enforcePostEncoderDecoderConsistency() updates output slot decoder combos when the post-encoder module changes.

See Session Constraints.

Widget UI

The Post-Encoder Module section is rendered by PostEncoderWidget in the dynamic slot panels — placed after memory inputs and before outputs (matching the inference pipeline order).

Component Role
Module combo PostEncoderModuleRegistry::moduleKeys() + (None)
Description label getMetadata(key).description
Parameter panel AutoParamWidget from getSchema(key)
point_key combo Dynamic DataManager combo (ParameterUIHints)

Data flow

On construction:

  1. Populate module combo from registry
  2. Restore from DeepLearningState::postEncoderParams()
  3. Rebuild parameter panel for selected key

On parameter change:

  1. Read {module_key, parameters_json} from combo + AutoParamWidget::toJson()
  2. Update DeepLearningState::setPostEncoderParams() (workspace JSON)
  3. Call configurePostEncoderModule() when model is loaded
  4. Enforce decoder consistency on output slot widgets

See PostEncoderWidget and Schema-Driven Forms.

Batch inference and TensorData output

For batch runs with TensorToFeatureVector, ResultProcessor collects (frame_index, std::vector<float>) pairs and merges them into a single TensorData::createOrdinal2D matrix at batch completion. Each row is one frame; each column is one feature channel.

Future work

  • Per-output-slot targeting — bind post-encoder to a named output slot on multi-output models
  • prepareFrame(DataManager&, int) on modules — move spatial-point lookup into the module interface
  • Decoder-roundtrip recurrent feedback — decode → re-encode for models that feed decoded results back as inputs

Testing

Test file Coverage
tests/DeepLearning/post_encoder/PostEncoderModules.test.cpp Modules, pipeline, registry
tests/DeepLearning/post_encoder/PostEncoderOutputTransform.test.cpp applyPostEncoderToFirstOutputSlot, effectiveOutputSlots
ctest --preset linux-clang-release -R "post_encoder"