Financial Module — architecture

Note

This page publishes oasislmf/pytools/fm/TECHNICAL.md verbatim, by include rather than by copy, so the architecture description cannot drift from the one kept beside the code. Edit that file, not this page.

This document provides detailed technical documentation for the Financial Module (FM) sparse computation implementation. It covers the data structures, algorithms, and computation flow used to calculate insured losses.

Table of Contents

  1. Overview

  2. Data Structures

  3. Computation Flow

  4. Aggregation

  5. Profile Application

  6. Back Allocation

  7. Building Packing

  8. Stream I/O

  9. Memory Management

  10. Performance Considerations


Overview

The FM sparse computation engine processes insurance/reinsurance losses through a hierarchical node structure. It reads ground-up losses (GUL), insurance loss (IL) or previous cycle or re-insurance loss (RI) from an input stream, applies financial terms (deductibles, limits, shares) at each level of the hierarchy, and outputs the computed insured losses.

Key Design Principles

  1. Sparse Storage: Only non-zero loss samples are stored, reducing memory usage significantly

  2. Bottom-Up Traversal: Computation proceeds from items (leaves) up to the root

  3. In-Place Modification: Results are computed in-place to minimize memory allocation

  4. JIT Compilation: Critical functions use Numba for near-native performance

Module Structure

fm/
├── manager.py          # Entry point, orchestrates the computation
├── financial_structure.py  # Parses static input files into computation-ready arrays
├── compute_sparse.py   # Core computation engine
├── back_allocation.py  # Loss distribution back to children
├── stream_sparse.py    # Binary stream reading/writing
├── policy.py           # Financial term calculations (calc rules)
├── policy_extras.py    # Calc rules with extras tracking (deductible, over_limit, under_limit)
├── common.py           # Shared constants and data types
├── cli.py              # fmpy command line entry point
├── compare.py          # Compare two FM output streams
└── portfolio_complexity.py  # Report on the shape of a portfolio's structure

Data Structures

CSR-Inspired Sparse Storage

The computation uses a Compressed Sparse Row (CSR) inspired format to store loss data efficiently. This is crucial because most samples may have zero loss, and storing all samples would waste memory.

For N nodes, each with variable number of samples:

sidx_indptr:  [0, 3, 7, 10, ...]  # Pointers to start of each node's data
sidx_val:     [-3, -1, 5, -3, -1, 2, 8, ...]  # Sample indices
loss_val:     [100, 50, 25, 200, 100, 75, 30, ...]  # Corresponding losses

Node 0: sidx_val[0:3] = [-3, -1, 5], loss_val[0:3] = [100, 50, 25]
Node 1: sidx_val[3:7] = [-3, -1, 2, 8], loss_val[3:7] = [200, 100, 75, 30]

Sample Index (sidx) Values

Special negative indices carry metadata:

sidx

Constant

Meaning

-5

MAX_LOSS_IDX

Maximum possible loss

-4

CHANCE_OF_LOSS_IDX

Probability of non-zero loss

-3

TIV_IDX

Total Insured Value

-2

(ignored)

Standard deviation

-1

MEAN_IDX

Mean/expected loss

1..N

(samples)

Monte Carlo sample indices

Node Array Structure

Each node in nodes_array contains:

nodes_array_dtype = np.dtype([
    ('node_id', np.uint64),          # Unique node identifier
    ('level_id', oasis_int),         # Hierarchy level (1 = items)
    ('agg_id', oasis_int),           # Aggregation ID from fm_programme
    ('layer_len', oasis_int),        # Number of output layers
    ('cross_layer_profile', oasis_int),  # True if one profile covers all layers
    ('profile_len', oasis_int),      # Number of profiles (may differ from layer_len)
    ('profiles', oasis_int),         # Index into node_profiles_array
    ('loss', oasis_int),             # Index into loss_indptr
    ('net_loss', oasis_int),         # Index for net loss storage
    ('extra', oasis_int),            # Index into extras_indptr (or null_index)
    ('is_reallocating', np.uint8),   # Node redistributes its loss to its children
    ('parent_len', oasis_int),       # Number of parents
    ('parent', oasis_int),           # Index into node_parents_array
    ('children', oasis_int),         # Index into children array
    ('output_ids', oasis_int),       # Index into output_array
])

Defined in financial_structure.py.

Computation Index Structure

The compute_idx tracks computation state:

compute_idx_dtype = np.dtype([
    ('level_start_compute_i', int),  # Start of current level (for output)
    ('next_compute_i', int),         # End of current level / start of next
    ('compute_i', int),              # Current node being processed
    ('sidx_i', int),                 # Next sidx array index
    ('sidx_ptr_i', int),             # Next position in sidx_val
    ('loss_ptr_i', int),             # Next position in loss_val
    ('extras_ptr_i', int),           # Next position in extras_val
])

Defined in common.py.

Extras Array

Extras track financial term effects for back allocation:

extras_val[i] = [deductible, overlimit, underlimit]

# deductible: Amount deducted from loss
# overlimit:  Amount exceeding the policy limit
# underlimit: Remaining capacity (limit - loss)

Computation Flow

High-Level Algorithm

For each event:
    1. Read item losses from input stream into sparse arrays
    2. For each level (bottom to top):
        For each node at this level:
            a. AGGREGATE: Sum children losses
            b. APPLY PROFILE: Apply financial terms
            c. BACK ALLOCATE: Distribute results to base children
            d. QUEUE PARENTS: Add parents for next level
    3. Write output losses to stream

Pipeline

fmpy pipeline: static files to financial structure, then reader, compute and writer per event

The financial structure is built once from the static files; the reader, computation and writer then run per event.

Loss Flow Through One Node

Each node repeats the same four steps. Losses move up the hierarchy; the effect of the terms comes back down.

Loss flow through one node: aggregate, apply profile, back allocate, queue parents

With a single child the aggregation is skipped and the child’s storage becomes the node’s, so loss_in already is the child’s array. That is why back allocation can then assign loss_out straight into it rather than computing a ratio.

Level Traversal

The computes array acts as a queue:

Initial state (after reading items):
computes = [item1, item2, item3, 0, ...]
            ^compute_i       ^next_compute_i

After processing level 1:
computes = [item1, item2, item3, 0, parent1, parent2, 0, ...]
                                   ^compute_i        ^next_compute_i

The zero acts as a level delimiter. When computes[compute_i] == 0, we’ve finished the current level.

Children Tracking

The children array tracks which children have been seen for each parent:

children[parent['children']] = count
children[parent['children'] + 1] = child1_id
children[parent['children'] + 2] = child2_id
...

Aggregation

When a node has multiple children, their losses must be aggregated before applying financial terms.

Algorithm

def aggregate_children(node, children_count, ...):
    # Use dense temporary array for accumulation
    temp_node_loss.fill(0)

    for each child:
        child_sidx = sidx_val[child's range]
        child_loss = loss_val[child's range]

        for i, sidx in enumerate(child_sidx):
            temp_node_sidx[sidx] = True  # Mark as present
            temp_node_loss[sidx] += child_loss[i]  # Accumulate

    # Convert back to sparse storage
    for sidx in all_sidx:
        if temp_node_sidx[sidx]:
            sidx_val[ptr] = sidx
            loss_val[ptr] = temp_node_loss[sidx]
            ptr += 1

Single Child Optimization

When a node has only one child, no aggregation is needed. The child’s storage can be reused directly:

if children_count == 1:
    storage_node = child  # Reuse child's arrays
else:
    storage_node = parent  # Create new storage

Profile Application

Financial profiles define the calc rules (deductibles, limits, shares) applied at each node.

Profile Types

  1. Per-Layer Profiles: Each layer has its own profile

    • profile_len == layer_len

    • cross_layer_profile = False

  2. Cross-Layer Profiles: One profile applies to merged layers

    • cross_layer_profile = True

    • Losses summed across layers, profile applied, then back-allocated

    • Extras are not summed: they are merged by maximum (see Extras Across Layers)

  3. Step Policies: Multiple profile steps for one layer

    • node_profile['i_start'] < node_profile['i_end']

    • Steps applied sequentially

A cross-layer profile sums both loss and extras across the layers to recover the node’s total, applies its terms once, and back-allocates the result to each layer.

Per-layer storage

A branch computed with one layer gets per-layer storage lazily, the first time a node above it has layers of its own. The trigger is pointer equality — loss_indptr[child + 1] == loss_indptr[child] means nothing has split this branch yet — and the initialisation is:

new layers start as

loss

a copy of layer 0

extras

zero

The asymmetry is forced by the cross-layer merge above. Every layer is offered the whole loss and then carves its own slice out of it through its attachment and limit, so summing the layers afterwards gives the true total. Extras are carved by nothing: they are a single accumulated quantity, and the invariant is

sum over layers of extras == the node's accumulated extras

Layer 0 already holds the whole amount when the layers are created, so the others have to start at zero. Copying would make each of them hold it in full and the merge would count it once per layer — which shows up as a deductible applied once but charged N times.

Three places do this and they all apply the same rule: first_time_layer / first_time_layer_extra for the base children of a branch, the single-child path in compute_event for the branch’s own node, and the base-level path for a leaf that already has layers. base_children_count > 1 gates the first of these, but only as “is there anything below this node still to initialise” — with one base child that child is the node, already handled. It is not a policy switch.

Profile Application Flow

for profile_i in range(profile_len):
    profile = get_profile(node, profile_i)

    if profile has steps (i_start < i_end):
        loss_in = current_loss
        loss_out = temp_array

        for step_i in range(i_start, i_end):
            calc(fm_profile[step_i], loss_out, loss_in, ...)

        # Back allocate results
        back_alloc(...)

Calc Rules

The calc function applies financial terms based on calcrule_id:

Rule

Description

1

Deductible and limit

2

Deductible, attachment, limit and share

3

Franchise deductible and limit

12

Deductible only

14

Limit only

…

(see policy.py for full list)


Back Allocation

After applying financial terms at an aggregate level, results must be distributed back to individual items.

Allocation Rules

Rule

Description

Factor Calculation

0

No allocation

Output at aggregate level only

1

Proportional to input

factor = output / sum(original_input)

2

Pro-rata (proportional to computed)

factor = output / input at each level

3

Alias of rule 2

mapped to 2 on entry; the distinction is in the ground-up stage

Algorithm

def back_alloc_a2(base_children_count, storage_is_base_child, ...):
    if base_children_count == 1 and storage_is_base_child:
        loss_in[:] = loss_out  # Direct assignment
    else:
        # Compute factor for each sample
        for sidx in node_sidx:
            factor[sidx] = loss_out[sidx] / loss_in[sidx]

        # Apply factor to each child
        for child in children:
            for sidx in child_sidx:
                child_loss[sidx] *= factor[sidx]

The two back-allocation paths: direct assignment when the node's storage is the single base child, otherwise a per-sample factor applied to every base child

The direct assignment writes the post-profile loss straight to the node’s input storage, which is only correct when that storage belongs to the single base child. storage_is_base_child says whether it does; a forced aggregation can give a node one base child whose storage is somewhere else.

A level that does not write back (see back_alloc_level below) passes a count of 1 whatever the node really has, meaning “take the direct assignment”, without walking the node’s subtree. The flag is set alongside it so the pair agrees — the two arguments must describe the same node, or the caller asks for a state that has no meaning.

That holds only while nothing reads an item before the top, and a root_start link (a negative from_agg_id) does: generation writes one when a level splits a location more finely than the level below, linking each item straight to its node at that level. From there the item carries the loss of every level below the link, so under every rule those levels back-allocate as rule 2 does, extras included. It has to be every one of them, not only the node the link skips over: back_alloc_a2 and back_alloc_extra_a2 scale the children relative to the node’s input, so the children must already sum to it. compute_info['back_alloc_level'] is the highest level that writes back: max_level under rule 2, one below the highest root_start link under rules 0 and 1, and -1 when there is none. Which levels back-allocate is the only difference in the computation between the rules; rules 0, 1 and 2 give the same totals at the top.

Rule 1’s last step is unaffected. It allocates the top node’s loss by each item’s input loss, kept in net_loss, which nothing writes after the item is read.

Outputs under rule 0

fm_xref lists the items, whatever the rule. Under rule 0 the output is a top-level node, which is one policy layer of one account, so each of its layers is written under the output_id an item of that node has for that layer. Every such item shares the node’s portfolio, account and policy, so summaries at those levels are exact; a per-location breakdown does not exist under rule 0. The layer ids are read from an item too: a top-level node can be a cross-layer node, whose one profile spans layers only the levels below list.

Reinsurance needs the insured loss of each item, so a model run refuses insured-loss rule 0 when reinsurance is requested.

Extras Back Allocation

When tracking extras (deductible, overlimit, underlimit), allocation is more complex:

# Deductible change
deductible_delta = extra_after - extra_before

if deductible_delta >= 0:
    # Deductible increased: allocate by loss
    ded_factor = delta / loss_in
else:
    # Deductible decreased: reallocated to loss
    if underlimit > 0:
        ded_factor = delta / underlimit  # By remaining capacity
    else:
        ded_factor = delta / deductible  # By existing deductible

The sign convention:

  • Positive factor: additive (child_value += factor * base)

  • Negative factor: multiplicative (child_value *= -factor)

Layer Back Allocation

For cross-layer profiles, the merged result is distributed to layers:

# loss_in = sum of all layers (merged)
# loss_out = after profile application

factor = loss_out / loss_in

for layer in layers:
    layer_loss_after = layer_loss_before * factor

The extras are allocated back to the layers as well, see below.

Extras Across Layers

Loss and extras behave differently across layers, and getting this wrong has produced real bugs in both directions (#2209, and the first attempt at fixing it in #2212).

The rule: every layer holds the whole accumulated extras. In OED a layer is a policy (PolNumber), and policy terms apply to the whole loss before the layer terms carve out that policy’s range. Each layer is therefore offered the whole loss. It applies its own policy terms, then its attachment, limit and participation, so the layers’ results add up to no more than the input loss. The extras are the deductible already taken, the loss already cut off by limits, and the room still left under those limits, by everything below the node. That is one quantity, not something split between the layers, so each layer of the node gets a full copy. The copy is made by the single-child path in compute_event, by first_time_layer_extra, and by aggregate_children_extras, whose children’s new layers still point at layer 0.

The items under a node follow the same rule. When first_time_layer_extra creates layers for several base children, those are the items, and each item’s new layers are copies of its layer 0. Back allocation reads them: when a per-layer profile gives deductible back (a maximum deductible below the deductible already taken), back_alloc_extra_a2 shares the returned amount between the items in proportion to each item’s own deductible or underlimit. Items left at zero receive none of it, and allocation rule 2, which reports the items, comes out short:

acc107: 1 location, building 1.7M + contents 300k, LocDed6All 100k
        layer 2: PolMaxDed6All 30k, attachment 200k, participation 0.5

layer 2 enters with loss 1.9M and deductible 100k
  max ded: total 100k > 30k   -> 70k given back   -> 1.97M
  layer:   (1.97M - 200k) * 0.5                     = 885,000   correct

with the items' layer 2 extras at zero (stable/2.4.x, 2.5.8 and earlier):
  the items get none of the 70k: 1.9M * 885k / 1.97M = 853,553   wrong

A minimum deductible or a limit only adds to the extras, and an addition is shared in proportion to loss, so neither reads the items’ extras. Only amounts given back do.

Why each layer needs a full copy: min and max deductibles act on the total. A minimum or maximum deductible is not applied on top of what was taken below. It bounds the total deductible taken so far (deductible_under_min / deductible_over_max in policy_extras.py):

  • minimum: if the total is under the minimum, it is topped up to the minimum, first from the over-limit pool (loss already cut off by a limit below), then from the loss;

  • maximum: if the total is over the maximum, the excess is given back to the loss, up to the underlimit (the room left under the limits below); the rest goes to over-limit.

A per-layer profile carrying one of these therefore reads its layer’s extras. If those were zero, the full minimum would be taken again on top of the deductible already taken.

Per-layer policy terms only exist when the layers’ terms differ. Policy terms identical on every layer are prepared as a single profile, applied once before the layers are created.

Each layer moves its own effective deductible. With 60k taken below and maximum deductibles of 10k on layer 1 and 20k on layer 2, layer 1 gives back 50k and layer 2 gives back 40k. That is not 90k returned out of 60k taken: each policy’s deductible is now 10k and 20k respectively, and each applies to its own copy of the loss.

acc105: 1 location, GUL 1.7M, LocDed6All 100k
        layer 2: PolMinDed6All 250k, attachment 200k, participation 0.5

layer 2 enters with loss 1.6M and deductible 100k (a full copy)
  min ded: total 100k < 250k  -> top up by 150k   -> 1.45M
  layer:   (1.45M - 200k) * 0.5                     = 625,000   correct

with the layer's extras zeroed instead (#2212):
  min ded: total 0 < 250k     -> top up by 250k   -> 1.35M
  layer:   (1.35M - 200k) * 0.5                     = 575,000   wrong

The cross-layer merge: loss is summed, extras take the maximum. A cross-layer profile (account terms over several layers) merges the layers, applies the profile once, and allocates the result back. Summing the loss is right because the slices add up. Summing the extras would count the same deductible once per layer. The merge takes the per-layer maximum instead, which is the node’s value whether the layers hold copies or only layer 0 holds it (the base-level path, where everything is still zero).

acc49 (75% damage): 2 locations, LocDed6All 5k each; 2 layers; account deductible
                    10% of loss, min 20k, max 60k

layers after their terms: loss 150,000 + 462,000 = 612,000; each holds deductible 10,000
  merged deductible (max)          10,000
  account ded 10% of 612,000     + 61,200 = 71,200 > max 60k -> total 60,000
  taken at this level              50,000 -> 562,000 -> 281,000 per location   correct

summing the extras instead (#2209):
  merged deductible (sum)          20,000
  account ded                    + 61,200 = 81,200 > max 60k -> total 60,000
  taken at this level              40,000 -> 572,000 -> 286,000 per location   wrong (+5,000)

Back to the layers (back_alloc_layer_extra). Account terms apply after the layer terms, to the sum of the layers’ losses, so the change they make is shared back between the layers’ losses. The layer terms are not re-applied.

  • When the profile reduces the loss (deductible taken, limit), the loss is scaled back to each layer in proportion, and the added deductible or overlimit is shared in proportion to each layer’s loss.

  • When the profile returns deductible (a maximum deductible below the accumulated deductible), the returned amount is shared in proportion to each layer’s own deductible or underlimit. The denominator is the sum over layers, so the shares add up to what was returned.

  • When the profile reduces the overlimit or underlimit, each layer’s value is scaled by the ratio after / before. When the layers hold the same values, that leaves each at the merged value.

Which combinations are exact

Combination

What the FM computes

Status

Per-layer policy terms (different deductible, min/max deductible or limit per layer), no account terms

Each layer applies its own terms to the whole loss, starting from the full deductible carried forward, then its layer terms.

Exact (acc105, acc106, acc107, acc108)

Account deductible, minimum deductible or limit over layers, with no per-layer terms in between

The layers hold the same extras, so the merged value is the deductible actually taken below. Account terms apply to the summed layer losses, and the change is shared back as above. A maximum deductible is included as long as it does not return deductible taken below.

Exact (acc49 and the insurance_account group)

Account maximum deductible below the deductible taken below, over layers

The excess over the maximum is added to the summed layer losses and shared between the layers in proportion to their deductible. The exact result would re-run each layer’s terms on the larger loss, which the FM cannot do because account terms apply after layer terms. See the example below.

Approximate (acc109 locks in the FM result)

Account terms over layers whose per-layer terms differ

See below.

Computed, but not defined by OED

Account maximum deductible returning deductible over layers. The exact result would push the returned deductible through each layer’s terms again. The FM adds it to the layers’ losses instead:

acc109 (100% damage): 1 location, GUL 1.7M, LocDed6All 100k
layer 1: attachment 0, unlimited, participation 1       -> 1,600,000
layer 2: attachment 200k, unlimited, participation 0.5  -> 700,000
account: AccMaxDed6All 50k -> 50k of the 100k is returned

FM:    50k shared by deductible (equal)  -> 1,625,000 / 725,000   (+50k)
exact: layers re-run on 1.65M            -> 1,650,000 / 725,000   (+75k)

Account terms over layers whose per-layer terms differ. After different per-layer terms, the layers carry different effective deductibles, for example 150k on one and 130k on the other. Each is that policy’s own view of the deductible taken. OED does not define what “the deductible already taken” means for an account term that spans policies with different deductibles. The FM uses the largest of the layers’ values and applies the account terms to the summed layer losses:

1 location, GUL 1M, LocDed6All 100k
layer 1: PolDed6All 50k, attachment 0, limit 500k  -> deductible 150k, loss 500,000
layer 2: PolDed6All 30k, attachment 500k, unlimited -> deductible 130k, loss 370,000
account: AccMinDed6All 200k

merged: loss 870,000, deductible max(150k, 130k) = 150k
min ded tops up by 50k -> 820,000, shared back in proportion: 471,264 / 348,736

Other choices would give other results: the sum of the layers’ deductibles (280k, which double counts the 100k taken below) gives 870,000, and the shared 100k plus each layer’s own part (180k) gives 850,000. None of them follows from the OED definition. No error is raised, but results for this combination should be read with that in mind, and no validation unit covers it.


Building Packing

A location’s buildings can arrive multiplexed into the sample dimension of a single item rather than as one item each. The financial module applies the site levels’ terms per building and then collapses them.

The packed sample index

An item carrying N buildings encodes building b (1-based), sample s, at sidx = (b - 1) * S + s, and the negative specials at sidx = local - (b - 1) * NUM_SPECIAL_SIDX. Building 1 is the identity encoding, so an item carrying one building is an ordinary item.

Structure info

Generation writes two files alongside the other static ones. coverage_buildings.bin carries the per-coverage count, one (coverage_id, n_building) record each, with n_building signed: a negative count marks a location whose buildings are kept separate and so arrive as their own blocks, a positive one a location summed at source. It is absent whenever every location has a single building.

fm_structure_info.bin carries the portfolio-wide figures the arena is sized on, in one 20-byte record:

Field

Meaning

site_collapse_level

Last level whose aggregation key includes risk_id. 0 means no level does

max_buildings

Largest building count any one item carries. Sizes the dense temporaries, which are indexed by sidx VALUE and so span the whole packed range

total_packed_buildings

SUM of those counts over the items that keep their buildings separate

packed_node_slots

Packed slices the arena owes over the packable levels

None of it can be derived here: fm_programme levels are compacted, so which level is the last risk-keyed one varies per portfolio, and the arena has to be sized before any item is read. load_fm_structure_info returns (0, 1, 0, 0) when the file is absent, which is every structure generated without packing.

TIV

The coverage TIV in coverages.bin is one building’s share: generation divides a location’s TIV by its building count in every mode except none, so items and samples write the same value. Whoever needs more than one building’s worth multiplies by |n_building| itself. For a node in the financial structure the rule is:

Node

TIV it owes per coverage

at or below site_collapse_level, buildings kept separate (n_building < 0)

the stored TIV: the node holds one building

anywhere else, including any node over a location summed at source (n_building > 0)

the stored TIV × `

Two places apply it, and they must agree. Generation turns %TIV deductibles and limits into amounts with it (tiv_buildings_site/tiv_buildings_above in il_inputs.py), so they reach fm already absolute. The step policies keep their triggers and payouts as fractions of TIV, and get_tiv_csr applies the same rule when extract_financial_structure scales them.

The ground-up tools follow it too: each building block’s loss and its sidx -3 exposure value use the stored per-building TIV, and the blocks of a location summed at source are added up.

Where the buildings collapse

Two paths, chosen in manager.py from the structure info:

No level applies terms per building — site_collapse_level < max(1, start_level). The reader sums the buildings away as it reads (collapse_on_read): each record is added into a one-row buffer at its local sidx, and the item is stored from it at its delimiter. The computation sees an ordinary stream, and an item takes one sample row of the arena however many buildings it carries – the arena is sized for no more. 0 is the “no risk-keyed level” marker rather than a level number, hence max(1, ...).

A site level does apply terms per building — the building dimension is carried up to and including site_collapse_level. Once a node at that level has applied its terms and back-allocated, collapse_site_node() sums its building blocks onto the local sidx they decode to, and its leaves’ with them (see Leaves). Every node above therefore aggregates children whose sidx are already ordinary, and needs no decode of its own.

Where a packed item's buildings collapse: the site levels carry a building dimension, the levels above see one collapsed loss

Leaves

Nothing aggregates a leaf, so a packed leaf keeps its packed storage. Leaves are read again after their site node: with an allocation rule above 0, back-allocation writes to them and the output is read from them; under any rule, an item linked straight to a level above the collapse (root_start) is aggregated again there. Either way they would carry packed sample indices past the collapse – to the output, or into terms that apply per building what should apply once per location. collapse_site_node() gives them collapsed storage once their terms have been applied, whatever the allocation rule. Rule 0 pays for it on items no level reads again, which costs one pass over them and nothing in memory: the arena budget for the copies does not depend on the rule.

The storage cannot be collapsed where it lies: the arrays are one arena and a node’s range is [sidx_indptr[i], sidx_indptr[i + 1]), whose end is the next node’s start. Fresh storage is appended at the bump pointer and the leaf repointed, exactly as an aggregation does for a parent. The old slice becomes dead space that the capacity bound already allows for.

This runs before back-allocation, which is what keeps back-allocation unchanged: the factor is looked up by sample index, and a collapsed leaf’s indices line up with its node’s.

A layer that arrives aliased onto layer 0 is repointed at the new layer 0 rather than given a copy of its own. Its values are layer 0’s by construction, since the collapse read both from the same slice, and the aliasing is load-bearing: a node whose profile_len is below its layer_len leaves the surplus layers aliased deliberately, and that is how the first node above with layers of its own detects that per-layer storage has yet to be created beneath it (see Per-layer storage). De-aliasing here would report the layers as already split when nothing had split them, leaving the upper layers sharing layer 0’s storage.

Arena capacity

packable_node_len counts the nodes at or below the collapse level, and is 0 unless the structure is packed. Each such node needs room for its own packed blocks, plus the collapsed copy appended rather than shrunk in place:

extra_slots = packable_nodes * max_buildings * max_sidx_count
extra_layer_slots = extra_slots * (max_layer + 1)   # one slice per layer, plus net_loss

sidx_val takes extra_slots; loss_val and extras_val take extra_layer_slots, since a packable node may carry several layers and the net-loss slice lives in loss_val beside them. sidx_indptr gains one entry per packable node, because each appended slice is a further allocation.


Stream I/O

Input Stream Format

Header:
  stream_type: int32 (GUL_STREAM_ID, FM_STREAM_ID, or LOSS_STREAM_ID)
  max_sidx: int32

Per item:
  event_id: int32
  item_id: int32
  [sidx: int32, loss: float32]*  # Repeated until delimiter
  delimiter: sidx=0, loss=0.0

Reading State Machine

State: HEADER (item_id == 0)
    Read event_id, item_id
    Initialize node storage
    Transition to: DATA

State: DATA (item_id != 0)
    Read sidx, loss
    If sidx == 0: delimiter -> HEADER
    If sidx == -2: ignore (std dev)
    If sidx == -4: store in pass_through
    Else: add to sparse arrays

Output Stream Format

Same format as input. The writer iterates through output nodes:

for node in output_nodes:
    write(event_id, output_id)
    write(-5, max_loss)  # Special indices first
    write(-4, chance_of_loss)
    write(-3, tiv)
    write(-1, mean_loss)
    for sidx in positive_samples:
        if loss[sidx] > 0:
            write(sidx, loss[sidx])
    write(0, 0.0)  # Delimiter

Memory Management

Array Sizing

Arrays are pre-allocated based on worst-case estimates:

max_sidx_count = max_sidx_val + EXTRA_SIDX_COUNT  # Per node
sidx_val_size = node_count * max_sidx_count
loss_val_size = loss_pointer_count * max_sidx_count

Low Memory Mode

When low_memory=True, large arrays use memory-mapped files:

if low_memory:
    sidx_val = np.memmap(path, mode='w+', shape=size, dtype=dtype)
else:
    sidx_val = np.zeros(size, dtype=dtype)

Per-Event Reset

After each event, dynamic arrays are reset:

def reset_variable(children, compute_idx, computes):
    computes[:compute_idx['next_compute_i']].fill(0)
    children.fill(0)
    compute_idx['next_compute_i'] = 0

Performance Considerations

Numba JIT Compilation

All critical inner loops use @njit(cache=True):

  • First run compiles and caches

  • Subsequent runs use cached machine code

  • fastmath=True enables SIMD optimizations

Sparse vs Dense Trade-offs

Operation

Sparse

Dense

Storage

O(nnz)

O(n)

Random access

O(log n)

O(1)

Iteration

O(nnz)

O(n)

Aggregation

Requires conversion

Direct

The implementation converts sparse to dense for aggregation, then back to sparse for storage.

Memory Access Patterns

  • Sequential access: sidx_val, loss_val iteration

  • Random access: temp_node_loss[sidx] during aggregation

  • Cache efficiency: Process nodes in order to maximize locality

Avoiding Python Overhead

  • No Python objects in hot paths

  • Pre-allocated arrays (no dynamic allocation in loops)

  • Numba-compatible data types only


Debugging Tips

Error Handling

On computation error, event_error.json is written:

{
    "event_index": 42,
    "event_id": 12345,
    "agg_id": 7,
    "node_level_id": 3
}

Enabling Debug Output

Uncomment print statements in compute_sparse.py:

# print('level', level, compute_node['agg_id'], ...)
# print('ba', child['level_id'], child['agg_id'], ...)

Verifying Results

Use compare.py to compare two FM output streams:

from fm.compare import compare_streams
result = compare_streams(gul_stream, fm_stream1, fm_stream2, precision=5)