Generated reference › Top K — Machine Learning/Postprocessing
kind: generated#block#machine-learning-postprocessing

Top K — Machine Learning/Postprocessing

Machine_Learning/Postprocessing/Top_K · 1 input / 2 output port(s) at insert · exports to Python, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog, PLC Structured Text

Description#

The block's own DESCRIPTION_HTML, rendered verbatim — the same text the config dialog's info panel and the library navigator show. Fix a wrong sentence in the block's .cpp (R-D9), never here.

Top K

Machine Learning / Postprocessing

Reduces a column of scores to its k largest entries, ranked:

idxp = the position of the p-th largest entry, plus Index Base; valp = that entry's value, for p = 1 … K.

This is Argmax Decision generalised: where that block names the one winning class, this one names the shortlist – the top-5 a recogniser reports, the two candidate modes a supervisor arbitrates between, the runners-up a confidence margin is measured against (val1 − val2).

Ties rank by lowest index first, which is Argmax Decision's rule extended to an order: equal scores come out in the order they appear in u. The result is exactly a stable descending sort truncated to its first K rows.

Ports

  • u – the scores, a column [m,1] with m ≥ K – logits, probabilities or any comparable quantity.
  • idx – a column [K,1]: the ranked positions, best first, each plus Index Base. Carried as real numbers like every other signal in the model; they are always whole ones.
  • val – a column [K,1]: the corresponding values, in whatever units u carried, in descending order. Row p of idx and row p of val always describe the same entry.

Parameters

  • K – how many entries to report, and the height of both outputs. A count: it is rounded to the nearest whole number, so a value arriving as 2.9999999 means 3. It must be at least 1 and no larger than the width of u – a shortlist longer than the list it is drawn from is refused at run start rather than padded, because there is no honest value to pad it with. Default 3.
  • Index Base – what the first element is called:
    • Zero-based (PyTorch, numpy) – the first class is 0. The default, and what a model exported from a Python framework expects.
    • One-based (MATLAB) – the first class is 1, for a graph whose downstream lookup or switch is written in MATLAB's convention.
    It shifts the reported indices and nothing else – the comparisons, the tie rule, the ranking and the val output are identical either way.
  • Sampling Time (s) – zero or less inherits the solver's rate; a positive value runs the block at that period.

Code export

All ten targets: Python, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog and PLC Structured Text. K and the index base are baked into the body at export time – K sizes the output ports, so it could not be tunable on the generated core – and there is no tunable parameter.

The six software targets emit two nested loops. The three HDL targets and PLC ST emit the K passes unrolled, K×m comparisons in all, because a pass reads the previous pass's output row and neither the pass count nor the width is a run-time quantity. The HDL targets are genuine Q16.16 fixed point: the block only compares and copies, with no transcendental and no division in it, and the selection deliberately avoids the data-dependent array write a mask-out-the-winner formulation would need. See the Notes for what fixed point costs at a near-tie.

Simulink bridge

None. The closest block on this installation is dspstat3/Sort, and it was probed in R2026a rather than read from documentation: its dialog offers otype (Value / Index / Value and Index), dir and sortAlg, and no k of any kind. It sorts the whole vector and emits two full-length outputs, so a Top K with K < m – the only interesting case – has no parameter to map onto, and there is nowhere for the row count to cross. Its sortAlg choice (Quick sort / Insertion sort) is a tie-order-visible knob this block does not have either. The bridge reports the block rather than dropping it silently, and it has no parity testbench, which is the documented consequence of Support::None rather than a gap. Code export verification still covers it across all ten languages.

Notes

  • Algebraic and stateless: the outputs depend only on the current input, so the block cannot break an algebraic loop.
  • Nonlinear and discontinuous, and deliberately carries no state space. The indices step rather than vary, so no A/B/C/D describes the block and model reduction correctly refuses it.
  • The ranking is by value alone. Equal values are ordered by index, and nothing else breaks a tie – so the output is deterministic even when the scores are not distinct, which is the property a downstream switch depends on.
  • At a near-tie the HDL targets can rank differently. They compare Q16.16 values, one quantum of which is about 1.5e-5, where the in-app run compares doubles – so two scores closer together than that can come out the other way round. Here that transposes two adjacent rows of both outputs rather than changing one number slightly. This is inherent to reducing a continuous quantity to a discrete ranking in fixed point, not a codegen defect: if your application must agree bit for bit with the simulation at a tie, separate the scores or rank downstream in floating point.

Code facts#

FactValue
registered typeMachine_Learning/Postprocessing/Top_K
familyMachine_Learning/Postprocessing
solver environment classICoreBlock_0_Machine_Learning_1_Postprocessing_2_Top_K
sourcesrc/ICoreSDK/ICoreBlockLibrary/Blocks/Machine_Learning/Postprocessing/Top_K/ICoreBlock_0_Machine_Learning_1_Postprocessing_2_Top_K.cpp
headersrc/ICoreSDK/ICoreBlockLibrary/Blocks/Machine_Learning/Postprocessing/Top_K/ICoreBlock_0_Machine_Learning_1_Postprocessing_2_Top_K.h
default size on canvas120 × 85 px
ports at insert1 in, 2 out
code generators implementedPython, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog, PLC Structured Text

Ports#

#DirectionSignal typeDescription label
1inICoreDoubleu
2outICoreDoubleidx
3outICoreDoubleval

Ports the constructor creates. A block whose port list changes with its configuration adds or removes ports at load time; the count above is the one a freshly inserted block has.

Configuration variables#

Config variableDefaultSimulink parameter
K3
Index BaseZero-based (PyTorch, numpy)%~%One-based (MATLAB)~~Zero-ba…

Every block also carries Sampling Time (s) from ICoreBlockSolverEnvironment: zero or less inherits the solver's rate, a positive value runs the block at that period.

supportSupport::None
Simulink path
port-count rulePortsParam::None
SampleTime parameteryes

Caveat (shown to the user): no Simulink equivalent: dspstat3/Sort, the closest block installed here, sorts the WHOLE vector and its dialog carries no k of any kind -- probed in R2026a -- so a shortlist of K rows has no parameter to map onto and no way for the output height to cross; its sortAlg choice also leaves the tie order unspecified, where this block fixes it at lowest-index-first

Catalog contract: src/ICoreSDK/ICoreCoder/ICoreCommandSystem/SimulinkBridge/ICoreSimulinkBlockCatalog.h

Description vs code#

The checker has a blind spot here — it could not resolve something (a grouped port bullet, a computed config name), which is reported and never counted as a pass. A reader has to settle it:

  • B0 every stimulus in the sample errored — cross-checks skipped

The verdict above is tools/docs/check_block_descriptions.py (P7.1), which compares LISTS. It cannot read a sentence: "stateless" on a block with a state, an initial-value semantic the recursion does not implement, a "not synthesizable" caveat the HDL banner contradicts. That is the agent audit (P7.3) on BLOCK_DESCRIPTION_AUDIT.md, and this tool's green is not a substitute for one.

File banner (developer view)#

The top comment of the block's .cpp — the maths, the realization and the export strategy, addressed to whoever changes it. It must not contradict the description above (P7.5).

Top K — the k highest-scoring classes, in order idx[p] = the p-th ranked position + base val[p] = that entry's value (ties: the LOWEST index ranks first -- Argmax Decision's rule, extended to an order)

Pass 0 IS Argmax Decision's scan. Every pass after it takes the largest entry that is lexicographically below the previous pick:

eligible(i) <=> u[i] < prevVal OR (u[i] = prevVal AND idx(i) > prevIdx)

and, among the eligible, the first strictly greatest -- which again puts the lowest index first. That is exactly a stable descending sort truncated to k rows, computed without one.

⚠ Why the lexicographic form rather than "mask the winner out and rescan": masking needs a mutable copy of the input and a data-dependent WRITE into it, scratch[winner] = -inf. The winner is a run-time value, so that is an indexed write the three HDL targets cannot express without a mux over every element -- and the sentinel itself has no honest Q16.16 spelling. The lexicographic test needs neither: it compares against the PREVIOUS OUTPUT ROW, which is already sitting there. Both equality operands are copies of input elements rather than results of arithmetic, so = is exact in all ten languages including fixed point.

⚠ Why there is no sentinel for "no candidate found yet". The software targets carry a fnd flag. The four statement targets carry none: they seed row p from row p-1, so "not yet found" is exactly idx[p] = idx[p-1], an equality on two whole numbers. Indices are distinct, so the test cannot false-positive once a candidate has been taken.

Zero scratch anywhere. The OUTPUT ELEMENTS are the accumulators in the three HDLs and in PLC ST, which is legal because those are process VARIABLES (VHDL :=, Verilog/SV blocking =, ST :=) read back within the same tick. §4's registered-write rule does not apply: nothing here crosses a clock edge. Reference for the whole shape: Argmax Decision.

Sample results#

No stimulus produced a sampled output in this rig — Invalid "K" at: ICore Blocks/Home/Top K. That is a fact about the single-block rig, not a verdict on the block: an offline batch fit, a block whose output only appears at onSolverFinish, or one that needs a driven environment cannot be exercised alone.

Category unsampled · sample time 0.1 · 60 steps · commit ccf005c8 · produced by docsSample --out <folder> --steps 60

Sample data: docs/generated/samples/Machine_Learning__Postprocessing__Top_K.json