Hierarchical Engineering & Memory Assembly [BETA]¶
🚧 Beta – Research Module
⚠️ Status: Active development
Core functionality is implemented but still evolving
Some features may be incomplete or subject to change
API is not yet stable
Intended for research use only (not production-ready)
Navigation:
Theory introduction: See the Intro
Related mathematical theory: See the Mathematical Theory
Alignment and groups¶
HierarchicalTAM matches its nodes on (group, date), never on row position (align='strict', the default, raises and lists the first missing keys per node; align='inner' keeps the common keys and warns with the rows dropped per node). Each node is then sorted by (group, date), and additivity_gap_ records, per parent, max |Y_p - sum Y_c| / mean |Y_p| (a gap above 0.1 % is warned once at fit). Without a date_col the nodes are matched by row position and must have the same number of rows.
With a group_col every node keeps its group axis (G, T, F); all nodes must hold the same groups and the same T rows per group. The groups do not interact: the global system is (G, D, D) with D the sum of the node dimensions, and the penalty P of shape (D, D) is shared. fit is _assemble_system followed by _solve:
def fit(self, data: pd.DataFrame) -> 'HierarchicalTAM':
r"""
Fits the global hierarchical system.
Constructs a block-diagonal matrix of all sub-models and adds off-diagonal
terms representing the hierarchical constraints before solving. Uses
memory-safe chunking to prevent VRAM exhaustion.
Args:
data: DataFrame containing data for all nodes (distinguished by node_col).
"""
print("--- Fitting Hierarchical System ---")
system = self._assemble_system(data)
beta_global = self._solve(system)
for node in self.nodes:
start, end = system.node_to_idx[node]
self.sub_models[node].coefficients_ = beta_global[:, start:end, :]
return self
def _align_nodes(self, data: pd.DataFrame) -> pd.DataFrame:
r"""
Matches the nodes on ``(group, date)`` and sorts each node by ``(group, date)``.
Raises:
ValueError: ``"strict"``: the nodes do not hold the same keys (the first missing keys are listed per node).
``"inner"``: no key is common to every node. Either mode: a node repeats a key, or, without a ``date_col``,
the nodes differ in row count.
"""
frames = {node: data[data[self.node_col] == node] for node in self.nodes}
if self.date_col == "__dummy_date__":
counts = {node: len(frame) for node, frame in frames.items()}
if len(set(counts.values())) > 1:
raise ValueError(
"HierarchicalTAM: without a date_col the nodes are matched by row position and must have the same row count, "
f"got {counts}. Pass date_col to match them on (group, date)."
)
return pd.concat(list(frames.values()), ignore_index=True)
keys = {node: set(zip(frame[self.group_col], frame[self.date_col])) for node, frame in frames.items()}
union = set().union(*keys.values())
common = set.intersection(*keys.values())
label = (lambda k: str(pd.Timestamp(k[1]))) if self.group_col == "__dummy_group__" else (lambda k: f"({k[0]}, {pd.Timestamp(k[1])})")
if self.align == "strict":
missing = {node: sorted(union - keys[node]) for node in self.nodes if keys[node] != union}
if missing:
lines = [f" {node}: {len(m)} missing, first: {[label(k) for k in m[:3]]}" for node, m in missing.items()]
raise ValueError(
"HierarchicalTAM: the nodes do not share the same (group, date) keys (align='strict'). "
"Keys that other nodes have and this node lacks:\n" + "\n".join(lines)
+ "\nUse align='inner' to keep the common keys."
)
else:
if not common:
raise ValueError("HierarchicalTAM: align='inner' found no common (group, date) key across the nodes.")
dropped = {node: len(frames[node]) - sum(k in common for k in zip(frames[node][self.group_col], frames[node][self.date_col]))
for node in self.nodes}
dropped = {node: n for node, n in dropped.items() if n}
if dropped:
warnings.warn(
f"HierarchicalTAM align='inner': kept {len(common)} common (group, date) keys; rows dropped per node: "
+ ", ".join(f"{node}: {n}" for node, n in dropped.items()),
UserWarning, stacklevel=3,
)
aligned = []
for node in self.nodes:
frame = frames[node]
if self.align == "inner":
frame = frame[[k in common for k in zip(frame[self.group_col], frame[self.date_col])]]
frame = frame.sort_values([self.group_col, self.date_col], kind="stable")
if len(frame) != len(common if self.align == "inner" else union):
raise ValueError(f"HierarchicalTAM: node {node!r} repeats a (group, date) key; each node needs one row per key.")
aligned.append(frame)
return pd.concat(aligned, ignore_index=True)
def _check_additivity(self, data: pd.DataFrame) -> None:
r"""
Stores ``additivity_gap_`` per parent, :math:`\max |Y_p - \sum_c Y_c| / \operatorname{mean} |Y_p|`, and warns once when
a parent is further than ``_ADDITIVITY_TOLERANCE`` from the sum of its children (``data`` is aligned and sorted).
"""
target = lambda node: data.loc[data[self.node_col] == node, self.sub_models[node].target_col_].to_numpy(dtype=float)
gaps = {}
for parent, children in self.structure.items():
y_parent = target(parent)
difference = np.abs(y_parent - sum(target(child) for child in children)).max()
scale = np.abs(y_parent).mean()
gaps[parent] = float(difference / scale) if scale > 0 else (0.0 if difference == 0 else float("inf"))
self.additivity_gap_ = gaps
off = {parent: gap for parent, gap in gaps.items() if gap > _ADDITIVITY_TOLERANCE}
if off:
warnings.warn(
"HierarchicalTAM: the target of a parent is not the sum of its children's "
f"(max |Y_parent - sum Y_children| / mean |Y_parent|, tolerance {_ADDITIVITY_TOLERANCE:g}): "
+ ", ".join(f"{parent}: {gap:.4g}" for parent, gap in off.items()),
UserWarning, stacklevel=3,
)
def _assemble_system(self, data: pd.DataFrame) -> '_HierarchicalSystem':
r"""
Assembles the global system :math:`(\Sigma_X, \Sigma_{XY}, P)` of the joint fit, one system per group.
Every node keeps its group axis, ``x`` of shape ``(G, T, F)``, and all nodes must hold the same groups and the same ``T`` rows per
group. The dense matrices ``cov_X`` of shape ``(G, D, D)`` (data terms plus the aggregation constraints, within each group) and ``P``
of shape ``(D, D)`` (block-diagonal node penalties, shared by the groups) are built when the ``G * D^2 * 8`` bytes fit in memory.
Otherwise only ``cov_XY`` is accumulated and :meth:`_solve` applies the system matrix-free from the node data, group by group.
"""
data = _ensure_dummies(data, self.group_col, self.date_col)
data = self._align_nodes(data)
self._check_additivity(data)
node_data_dict = {}
node_to_idx = {}
penalty_blocks = []
node_groups = {}
current_idx = 0
for node in self.nodes:
# Isolate data based on the structural hierarchy node, not the tensor group
node_data = data[data[self.node_col] == node].reset_index(drop=True)
x, y, _ = self.sub_models[node]._prepare_data(
node_data, target_col=self.sub_models[node].target_col_
)
node_data_dict[node] = (x, y)
node_groups[node] = list(self.sub_models[node].unique_groups_)
dummy_phi = self.sub_models[node]._build_design_matrix(x[:, 0:1, :])
k = dummy_phi.shape[-1]
node_to_idx[node] = (current_idx, current_idx + k)
current_idx += k
penalty_blocks.append(self.sub_models[node]._build_penalty_matrix())
del dummy_phi
reference = self.nodes[0]
for node in self.nodes[1:]:
if node_groups[node] != node_groups[reference]:
raise ValueError(
f"HierarchicalTAM: all nodes must hold the same groups ({self.group_col}); "
f"{reference!r} has {node_groups[reference]}, {node!r} has {node_groups[node]}."
)
if node_data_dict[node][0].shape[1] != node_data_dict[reference][0].shape[1]:
raise ValueError(
"HierarchicalTAM: all nodes must hold the same number of rows per group, "
f"{reference!r} has {node_data_dict[reference][0].shape[1]}, {node!r} has {node_data_dict[node][0].shape[1]}."
)
total_coeffs = current_idx
n_groups = len(node_groups[reference])
n_samples = node_data_dict[reference][0].shape[1]
run_device = TORCH_DEVICE
is_safe_for_direct = can_fit_dense_matrix(total_coeffs, run_device, batch_size=n_groups)
cov_bytes = n_groups * total_coeffs * total_coeffs * 8 # 8 bytes for float64
available_bytes = hw.get_available_memory()
is_safe_for_dense_cov = cov_bytes < (available_bytes * 0.4)
if is_safe_for_direct or is_safe_for_dense_cov:
cov_X_global = torch.zeros((n_groups, total_coeffs, total_coeffs), device=run_device, dtype=torch.get_default_dtype())
cov_XY_global = torch.zeros((n_groups, total_coeffs, 1), device=run_device, dtype=torch.get_default_dtype())
P_global = torch.zeros((total_coeffs, total_coeffs), device=run_device, dtype=torch.get_default_dtype())
for i, node in enumerate(self.nodes):
start, end = node_to_idx[node]
p_block = penalty_blocks[i].to(run_device)
if p_block.dim() == 3:
p_block = p_block.squeeze(0)
P_global[start:end, start:end] = p_block
safe_batch = max(256, get_safe_chunk_size(n_samples, total_coeffs, run_device, batch_size=n_groups))
start_idx = 0
print("Accumulating Block Matrices and Constraints...")
while start_idx < n_samples:
end_idx = min(start_idx + safe_batch, n_samples)
try:
phi_chunks = {}
y_chunks = {}
for node in self.nodes:
x_full, y_full = node_data_dict[node]
x_chunk = x_full[:, start_idx:end_idx, :].to(run_device)
y_chunks[node] = y_full[:, start_idx:end_idx, :].to(run_device)
phi_chunks[node] = self.sub_models[node]._build_design_matrix(x_chunk)
for node in self.nodes:
start, end = node_to_idx[node]
phi_c = phi_chunks[node]
cov_X_global[:, start:end, start:end] += phi_c.mT @ phi_c
cov_XY_global[:, start:end, :] += phi_c.mT @ y_chunks[node]
for parent, children in self.structure.items():
p_start, p_end = node_to_idx[parent]
phi_p = phi_chunks[parent]
if self.coherence_loss == "sinkhorn":
K_sink = compute_sinkhorn_coherence_matrix(
phi_p.shape[1],
window=self.sinkhorn_window,
eps=self.sinkhorn_eps,
n_iters=self.sinkhorn_iters,
device=phi_p.device,
dtype=phi_p.dtype,
)
phi_p_eff = K_sink @ phi_p
else:
phi_p_eff = phi_p
cov_X_global[:, p_start:p_end, p_start:p_end] += self.lambda_p_hier * (phi_p.mT @ phi_p_eff)
for child in children:
c_start, c_end = node_to_idx[child]
phi_c = phi_chunks[child]
phi_c_eff = (K_sink @ phi_c) if self.coherence_loss == "sinkhorn" else phi_c
cov_X_global[:, c_start:c_end, c_start:c_end] += self.lambda_p_hier * (phi_c.mT @ phi_c_eff)
cross = -self.lambda_p_hier * (phi_p.mT @ phi_c_eff)
cov_X_global[:, p_start:p_end, c_start:c_end] += cross
cov_X_global[:, c_start:c_end, p_start:p_end] += cross.mT
for sibling in children:
if sibling != child:
s_start, s_end = node_to_idx[sibling]
phi_s = phi_chunks[sibling]
phi_s_eff = (K_sink @ phi_s) if self.coherence_loss == "sinkhorn" else phi_s
cov_X_global[:, c_start:c_end, s_start:s_end] += self.lambda_p_hier * (phi_c.mT @ phi_s_eff)
del phi_chunks, y_chunks
start_idx += safe_batch
except (torch.OutOfMemoryError, MemoryError):
safe_batch, run_device = hw.handle_oom(
current_batch=safe_batch,
device=run_device,
context="Hierarchical dense matrix accumulation",
allow_cpu_fallback=False
)
safe_batch = max(256, safe_batch)
continue
return _HierarchicalSystem(
node_data_dict, node_to_idx, penalty_blocks, total_coeffs, n_samples, run_device,
is_safe_for_direct, cov_X_global, cov_XY_global, P_global, n_groups,
)
print(f"Notice: Hierarchical D={total_coeffs} (G={n_groups}) is massive. Routing to CG Solver.")
cov_XY_global = torch.zeros((n_groups, total_coeffs, 1), device=run_device, dtype=torch.get_default_dtype())
safe_batch = max(256, get_safe_chunk_size(n_samples, total_coeffs, run_device))
for g in range(n_groups):
start_idx = 0
while start_idx < n_samples:
end_idx = min(start_idx + safe_batch, n_samples)
try:
for node in self.nodes:
start, end = node_to_idx[node]
x_chunk = node_data_dict[node][0][g, start_idx:end_idx, :].to(run_device)
y_chunk = node_data_dict[node][1][g, start_idx:end_idx, :].to(run_device)
phi_chunk = self.sub_models[node]._build_design_matrix(x_chunk.unsqueeze(0)).squeeze(0)
cov_XY_global[g, start:end, :] += phi_chunk.mT @ y_chunk
start_idx += safe_batch
except (torch.OutOfMemoryError, MemoryError):
safe_batch, run_device = hw.handle_oom(
current_batch=safe_batch,
device=run_device,
context="Hierarchical CG RHS computation",
allow_cpu_fallback=False
)
continue
return _HierarchicalSystem(
node_data_dict, node_to_idx, penalty_blocks, total_coeffs, n_samples, run_device,
False, None, cov_XY_global, None, n_groups,
)
def _solve(self, system: '_HierarchicalSystem') -> torch.Tensor:
r"""
Solves the assembled global system, returning ``(G, D, 1)``.
Direct inversion is one batched solve over the groups. The two CG solvers (dense, or matrix-free from the node data) loop over
the groups, so that only one group's system is ever applied at a time.
"""
node_data_dict, node_to_idx, penalty_blocks = system.node_data_dict, system.node_to_idx, system.penalty_blocks
total_coeffs, n_samples, run_device = system.total_coeffs, system.n_samples, system.run_device
cov_X_global, cov_XY_global, P_global = system.cov_X, system.cov_XY, system.P
if cov_X_global is not None:
if system.direct:
print("Solving Global System via Direct Inversion...")
jitter_scale = 1e-6 * n_samples
A = cov_X_global + n_samples * P_global + jitter_scale * torch.eye(total_coeffs, device=run_device, dtype=torch.get_default_dtype())
return hw.safe_solve(A, cov_XY_global)
print("Notice: LAPACK workspace exceeded. Routing to Fast Dense CG solver...")
def dense_hierarchical_Av(cov_g: torch.Tensor):
def compute_dense_hierarchical_Av(v: torch.Tensor) -> torch.Tensor:
v = v.to(run_device)
jitter_scale = 1e-6 * n_samples
return (cov_g @ v) + n_samples * (P_global @ v) + (jitter_scale * v)
return compute_dense_hierarchical_Av
return torch.stack([
solve_sparse_cg(dense_hierarchical_Av(cov_X_global[g]), cov_XY_global[g], tol=1e-6, max_iter=5000)
for g in range(system.n_groups)
])
def hierarchical_Av(g: int):
def compute_hierarchical_Av(v: torch.Tensor) -> torch.Tensor:
nonlocal run_device
Av = torch.zeros_like(v)
local_start = 0
local_safe_batch = get_safe_chunk_size(n_samples, total_coeffs, run_device)
while local_start < n_samples:
local_end = min(local_start + local_safe_batch, n_samples)
try:
phi_chunks = {}
for node in self.nodes:
x_chunk = node_data_dict[node][0][g, local_start:local_end, :].to(run_device)
phi_chunks[node] = self.sub_models[node]._build_design_matrix(x_chunk.unsqueeze(0)).squeeze(0)
for i, node in enumerate(self.nodes):
start, end = node_to_idx[node]
v_local = v[start:end, :]
phi = phi_chunks[node]
Av[start:end, :] += (phi.mT @ (phi @ v_local))
for parent, children in self.structure.items():
p_start, p_end = node_to_idx[parent]
v_p = v[p_start:p_end, :]
phi_p = phi_chunks[parent]
constraint_diff = phi_p @ v_p
for child in children:
c_start, c_end = node_to_idx[child]
phi_c = phi_chunks[child]
constraint_diff -= (phi_c @ v[c_start:c_end, :])
if self.coherence_loss == "sinkhorn":
K_sink = compute_sinkhorn_coherence_matrix(
phi_p.shape[0],
window=self.sinkhorn_window,
eps=self.sinkhorn_eps,
n_iters=self.sinkhorn_iters,
device=phi_p.device,
dtype=phi_p.dtype,
)
constraint_diff_eff = K_sink @ constraint_diff
else:
constraint_diff_eff = constraint_diff
Av[p_start:p_end, :] += self.lambda_p_hier * (phi_p.mT @ constraint_diff_eff)
for child in children:
c_start, c_end = node_to_idx[child]
phi_c = phi_chunks[child]
Av[c_start:c_end, :] -= self.lambda_p_hier * (phi_c.mT @ constraint_diff_eff)
local_start += local_safe_batch
except (torch.OutOfMemoryError, MemoryError):
local_safe_batch, run_device = hw.handle_oom(
current_batch=local_safe_batch,
device=run_device,
context="Hierarchical Av computation",
allow_cpu_fallback=False
)
continue
for i, node in enumerate(self.nodes):
start, end = node_to_idx[node]
v_local = v[start:end, :]
P = penalty_blocks[i].to(run_device)
if P.dim() == 3:
P = P.squeeze(0)
Av[start:end, :] += n_samples * (P @ v_local)
jitter_scale = 1e-6 * n_samples
return Av + (jitter_scale * v)
return compute_hierarchical_Av
return torch.stack([
solve_sparse_cg(hierarchical_Av(g), cov_XY_global[g], tol=1e-6, max_iter=5000)
for g in range(system.n_groups)
])
The memory check counts the G * D^2 * 8 bytes of the dense covariance against 40 % of the available memory. Direct inversion is one batched solve over the groups; the dense and the matrix-free conjugate-gradient solvers loop over the groups, so one group’s system is applied at a time. Both stop at a relative tolerance of 1e-6, so their coefficients agree with the direct solve to about 1e-3 of the largest coefficient on an ill-conditioned system (predictions to a few 1e-6).
Sinkhorn Coherence Option¶
HierarchicalTAM(..., coherence_loss="sinkhorn", sinkhorn_reg=0.1) constructs the doubly-stochastic Sinkhorn transport matrix via compute_sinkhorn_coherence_matrix and injects the resulting positive semi-definite temporal coherence penalty \(L_{\text{sinkhorn}}^\top L_{\text{sinkhorn}}\) into the joint hierarchical solve.