| |
| """ |
| SASS-augmented trace dataloader stub. |
| |
| Cross-attention architecture: trace queries, SASS keys/values -> per-timestep |
| features. |
| |
| This stub is the data-side contract for that architecture. It loads |
| `tensor_input.npz` (the [24, T] ViT input) and `sass_modality.npz` (per-kernel |
| [N_pc, F] SASS matrices) for a single motif and yields the tensors a future |
| torch `nn.Module` would consume. No torch dependency — this host is CPU-only |
| and torch isn't installed; the same shapes carry over to PyTorch one-to-one. |
| |
| Shape contract per sample: |
| |
| trace_input : float32 [C=24, T=512] ViT input image |
| regime_family : float32 [T=512, F=4] per-bin one-hot family |
| subregime : float32 [T=512, Z=20] multi-hot within family |
| structural : float32 [T=512, K=17] per-kernel structural attrs |
| boundaries : float32 [T=512] Gaussian-smoothed transition target |
| gt_segments : list[(start, end, fam, sub[20], struct[17])] TAS transcript |
| workload_l1 : int64 [T=512] per-bin single L1 id (-1 idle) |
| workload_l2 : int64 [T=512] per-bin single L2 id (-1 idle) |
| workload_l1_multihot : float32 [T=512, 12] per-bin multi-hot L1 (overlap) |
| workload_l2_multihot : float32 [T=512, 73] per-bin multi-hot L2 (overlap) |
| multihot_n_active : float32 [T=512] # concurrent L1 classes per bin |
| mask_any : float32 [T=512] 1 = some kernel runs |
| bin_kernel_id : int64 [T=512] which kernel (-1 = idle) |
| sass_matrix : float32 [K, N_pc_max, F=9] per-kernel SASS, padded |
| sass_pc_mask : float32 [K, N_pc_max] 1 on real PCs, 0 on pad |
| |
| Cross-attention wiring (forward-pass pseudocode in the docstring below): |
| Q = trace_patch_embeddings [B, S_q, d] from the ViT trunk |
| K = sass_proj(sass_matrix[bin_k]) [B, N_pc, d] per-bin kernel lookup |
| V = sass_proj(sass_matrix[bin_k]) [B, N_pc, d] |
| attn = softmax(Q K^T / sqrt(d)) * sass_pc_mask |
| out = attn @ V [B, S_q, d] |
| |
| The per-bin kernel index is the bridge between the time grid (from nsys |
| kernel_intervals) and the SASS matrix store (per-kernel-function). For |
| unprofiled bins (`bin_kernel_id == -1`) the convention is to set Q's attention |
| output to zero — i.e. the trace-only path is preserved when SASS isn't |
| applicable. |
| |
| Usage: |
| python tools/sass_dataloader_stub.py kernels/vector_add/_out |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import sys |
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Optional |
|
|
| import numpy as np |
|
|
|
|
| @dataclass |
| class SASSSample: |
| """One motif's worth of data, in the shape a SASS-augmented ViT consumes.""" |
|
|
| trace_input: np.ndarray |
| counter_names: list[str] |
| time_edges_ns: np.ndarray |
| regime_family: Optional[np.ndarray] |
| regime_family_names: Optional[list[str]] |
| subregime: Optional[np.ndarray] |
| subregime_names: Optional[list[str]] |
| subregime_family_idx: Optional[np.ndarray] |
| structural: Optional[np.ndarray] |
| structural_names: Optional[list[str]] |
| boundaries: Optional[np.ndarray] |
| gt_segments: Optional[np.ndarray] |
| mask_any: Optional[np.ndarray] |
| mask_profiled: Optional[np.ndarray] |
| |
| workload_l1: Optional[np.ndarray] |
| workload_l2: Optional[np.ndarray] |
| workload_l1_multihot: Optional[np.ndarray] |
| workload_l2_multihot: Optional[np.ndarray] |
| multihot_n_active: Optional[np.ndarray] |
| mask_multilabel: Optional[np.ndarray] |
| vocab_l1: Optional[list[str]] |
| vocab_l2: Optional[list[str]] |
| bin_kernel_id: np.ndarray |
| sass_matrix: np.ndarray |
| sass_pc_mask: np.ndarray |
| sass_column_names: list[str] |
| sass_kernel_names: list[str] |
|
|
|
|
| def _bin_kernel_index(time_edges_ns: np.ndarray, |
| kernels: np.ndarray) -> np.ndarray: |
| """For each time bin, return the index (into `kernels`) of the kernel that |
| overlaps the bin's center, or -1 if no kernel overlaps. |
| |
| Bins are half-open [edges[t], edges[t+1]); kernel intervals are inclusive. |
| """ |
| if kernels.size == 0: |
| return np.full(time_edges_ns.shape[0] - 1, -1, dtype=np.int64) |
| centers = (time_edges_ns[:-1] + time_edges_ns[1:]) // 2 |
| starts = kernels[:, 0] |
| ends = kernels[:, 1] |
| idx = np.clip(np.searchsorted(starts, centers, side="right") - 1, |
| 0, len(kernels) - 1) |
| inside = (centers >= starts[idx]) & (centers <= ends[idx]) |
| return np.where(inside, idx, -1).astype(np.int64) |
|
|
|
|
| def _bin_kernel_function_index( |
| bin_kernel_id: np.ndarray, kernels: np.ndarray, |
| sass_kernel_names: list[str], |
| nsys_kernel_names: Optional[list[str]], |
| launch_function_index: Optional[np.ndarray] = None, |
| ) -> np.ndarray: |
| """Map per-bin kernel-launch index -> per-bin kernel-function index. |
| |
| SASS matrices are keyed by kernel *function*, not by individual launch. |
| Two precomputed inputs let us avoid the legacy "function-0 for every |
| active bin" fallback on heterogeneous traces: |
| - `launch_function_index[K]`: the per-launch function index already |
| baked into `tensor_input.npz` (post-migration). When present, every |
| active bin's index is just a gather from this array. |
| - `nsys_kernel_names[K]`: per-launch mangled name, used to compute the |
| function index from `sass_kernel_names` when no precomputed index is |
| attached. |
| Final fallback: function-0 for every active bin. |
| """ |
| T = bin_kernel_id.shape[0] |
| out = np.full(T, -1, dtype=np.int64) |
| if not sass_kernel_names: |
| return out |
| if launch_function_index is not None and len(launch_function_index) > 0: |
| active = bin_kernel_id >= 0 |
| if active.any(): |
| out[active] = launch_function_index[bin_kernel_id[active]] |
| return out |
| if nsys_kernel_names is None: |
| out[bin_kernel_id >= 0] = 0 |
| return out |
| name_to_fn = {n: i for i, n in enumerate(sass_kernel_names)} |
| for t in range(T): |
| k = int(bin_kernel_id[t]) |
| if k < 0 or k >= len(nsys_kernel_names): |
| continue |
| out[t] = name_to_fn.get(nsys_kernel_names[k], -1) |
| return out |
|
|
|
|
| def _pad_sass_matrices(matrices: list[np.ndarray]) -> tuple[np.ndarray, np.ndarray]: |
| """Stack per-kernel [N_pc_k, F] matrices into one padded [K, N_pc_max, F]. |
| |
| Returns (sass_matrix, sass_pc_mask). |
| """ |
| if not matrices: |
| return (np.zeros((0, 0, 0), dtype=np.float32), |
| np.zeros((0, 0), dtype=np.float32)) |
| F = matrices[0].shape[1] |
| N_pc_max = max(M.shape[0] for M in matrices) |
| K = len(matrices) |
| out = np.zeros((K, N_pc_max, F), dtype=np.float32) |
| mask = np.zeros((K, N_pc_max), dtype=np.float32) |
| for k, M in enumerate(matrices): |
| out[k, :M.shape[0]] = M.astype(np.float32) |
| mask[k, :M.shape[0]] = 1.0 |
| return out, mask |
|
|
|
|
| def load_motif(out_dir: Path) -> SASSSample: |
| """Load tensor_input + (optional) labels + sass_modality for one motif.""" |
| tin_path = out_dir / "input" / "tensor_input.npz" |
| sass_path = out_dir / "sass" / "sass_modality.npz" |
| if not tin_path.exists(): |
| raise FileNotFoundError(tin_path) |
| if not sass_path.exists(): |
| raise FileNotFoundError(sass_path) |
|
|
| tin = np.load(tin_path, allow_pickle=True) |
| trace_input = tin["data"].astype(np.float32) |
| counter_names = list(tin["counter_names"]) |
| edges = tin["time_edges_ns"].astype(np.int64) |
| kernels = tin["kernels"].astype(np.int64) |
| nsys_kernel_names = ( |
| list(tin["kernel_names"]) if "kernel_names" in tin.files else None |
| ) |
| launch_function_index = ( |
| tin["kernel_function_index"].astype(np.int64) |
| if "kernel_function_index" in tin.files else None |
| ) |
|
|
| labels_path = out_dir / "labels" / "labels.npz" |
| regime_family = subregime = structural = None |
| regime_family_names = subregime_names = structural_names = None |
| subregime_family_idx = None |
| boundaries = None |
| gt_segments = None |
| mask_any = mask_prof = None |
| workload_l1 = workload_l2 = None |
| workload_l1_multihot = workload_l2_multihot = None |
| multihot_n_active = mask_multilabel = None |
| vocab_l1 = vocab_l2 = None |
| if labels_path.exists(): |
| lab = np.load(labels_path, allow_pickle=True) |
| |
| |
| |
| def _opt(key, cast=None): |
| if key not in lab.files: |
| return None |
| v = lab[key] |
| return v.astype(cast) if cast is not None else v |
|
|
| regime_family = _opt("regime_family", np.float32) |
| regime_family_names = list(lab["regime_family_names"]) \ |
| if "regime_family_names" in lab.files else None |
| subregime = _opt("subregime", np.float32) |
| subregime_names = list(lab["subregime_names"]) \ |
| if "subregime_names" in lab.files else None |
| subregime_family_idx = _opt("subregime_family_idx", np.int64) |
| structural = _opt("structural", np.float32) |
| structural_names = list(lab["structural_names"]) \ |
| if "structural_names" in lab.files else None |
| mask_any = _opt("mask_any_kernel", np.float32) |
| mask_prof = _opt("mask_profiled", np.float32) |
| boundaries = _opt("boundaries", np.float32) |
| if "gt_segments" in lab.files: |
| gt_segments = lab["gt_segments"] |
|
|
| |
| workload_l1 = _opt("workload_l1", np.int64) |
| workload_l2 = _opt("workload_l2", np.int64) |
| |
| |
| |
| |
| |
| workload_l1_multihot = _opt("workload_l1_multihot", np.float32) |
| workload_l2_multihot = _opt("workload_l2_multihot", np.float32) |
| multihot_n_active = _opt("multihot_n_active", np.float32) |
| if multihot_n_active is not None: |
| |
| mask_multilabel = (multihot_n_active > 0).astype(np.float32) |
| vocab_l1 = list(lab["vocab_l1"]) if "vocab_l1" in lab.files else None |
| vocab_l2 = list(lab["vocab_l2"]) if "vocab_l2" in lab.files else None |
|
|
| sass = np.load(sass_path, allow_pickle=True) |
| sass_matrices = [np.asarray(m) for m in sass["matrices"]] |
| sass_kernel_names = list(sass["kernel_names"]) |
| sass_column_names = list(sass["column_names"]) |
| sass_matrix, sass_pc_mask = _pad_sass_matrices(sass_matrices) |
|
|
| launch_idx = _bin_kernel_index(edges, kernels) |
| bin_kernel_id = _bin_kernel_function_index( |
| launch_idx, kernels, sass_kernel_names, nsys_kernel_names, |
| launch_function_index=launch_function_index, |
| ) |
|
|
| return SASSSample( |
| trace_input=trace_input, |
| counter_names=counter_names, |
| time_edges_ns=edges, |
| regime_family=regime_family, |
| regime_family_names=regime_family_names, |
| subregime=subregime, |
| subregime_names=subregime_names, |
| subregime_family_idx=subregime_family_idx, |
| structural=structural, |
| structural_names=structural_names, |
| boundaries=boundaries, |
| gt_segments=gt_segments, |
| mask_any=mask_any, |
| mask_profiled=mask_prof, |
| workload_l1=workload_l1, |
| workload_l2=workload_l2, |
| workload_l1_multihot=workload_l1_multihot, |
| workload_l2_multihot=workload_l2_multihot, |
| multihot_n_active=multihot_n_active, |
| mask_multilabel=mask_multilabel, |
| vocab_l1=vocab_l1, |
| vocab_l2=vocab_l2, |
| bin_kernel_id=bin_kernel_id, |
| sass_matrix=sass_matrix, |
| sass_pc_mask=sass_pc_mask, |
| sass_column_names=sass_column_names, |
| sass_kernel_names=sass_kernel_names, |
| ) |
|
|
|
|
| def cross_attention_shapes_demo(sample: SASSSample, |
| d_model: int = 64, |
| patch_shape: tuple[int, int] = (4, 16)) -> None: |
| """Print the shapes a forward pass would touch. No actual attention is run.""" |
| C, T = sample.trace_input.shape |
| P_c, P_t = patch_shape |
| assert C % P_c == 0 and T % P_t == 0, \ |
| f"patch {patch_shape} doesn't divide ({C}, {T})" |
| n_tokens = (C // P_c) * (T // P_t) |
| K, N_pc_max, F = sample.sass_matrix.shape |
|
|
| print(f"trace_input {sample.trace_input.shape} dtype={sample.trace_input.dtype}") |
| print(f" -> patches ({n_tokens}, {P_c * P_t}) " |
| f"= ({C // P_c} * {T // P_t}, {P_c} * {P_t})") |
| print(f" -> Q ({n_tokens}, {d_model}) via patch_embed Linear") |
| print(f"sass_matrix ({K}, {N_pc_max}, {F})") |
| print(f" -> K = V ({K}, {N_pc_max}, {d_model}) via sass_proj Linear") |
| print(f"bin_kernel_id {sample.bin_kernel_id.shape} " |
| f"range=[{sample.bin_kernel_id.min()}, {sample.bin_kernel_id.max()}]") |
| print(f" -> per-token kernel index: ({n_tokens},) " |
| f"(replicate the time-bin's kernel across the {C // P_c} channel patches)") |
| print(f"attn output ({n_tokens}, {d_model}) " |
| f"= softmax(Q K^T / sqrt(d)) @ V, masked by sass_pc_mask") |
|
|
| |
| if sample.workload_l1_multihot is not None: |
| mh1 = sample.workload_l1_multihot |
| mh2 = sample.workload_l2_multihot |
| na = sample.multihot_n_active |
| n_overlap = int((na >= 2).sum()) if na is not None else 0 |
| print(f"workload_l1_multihot {mh1.shape} dtype={mh1.dtype} " |
| f"(sigmoid head target; BCEWithLogits over {mh1.shape[1]} L1 classes)") |
| print(f"workload_l2_multihot {mh2.shape} dtype={mh2.dtype} " |
| f"({mh2.shape[1]} L2 classes)") |
| print(f" -> bins with >=2 concurrent L1 classes: {n_overlap}/{mh1.shape[0]} " |
| f"(0 for the sequential corpus; >0 only on fused/overlapping traces)") |
| else: |
| print("workload_l*_multihot (absent — labels.npz pre-dates the " |
| "multi-hot fields; re-run tools/build_labels.py)") |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser( |
| description=__doc__, |
| formatter_class=argparse.RawDescriptionHelpFormatter, |
| ) |
| ap.add_argument("out_dir", type=Path) |
| ap.add_argument("--d-model", type=int, default=64) |
| args = ap.parse_args() |
| sample = load_motif(args.out_dir.resolve()) |
| print(f"motif: {args.out_dir}") |
| print(f" counter_names ({len(sample.counter_names)}): " |
| f"{sample.counter_names[:3]} ... {sample.counter_names[-2:]}") |
| print(f" sass kernel functions ({len(sample.sass_kernel_names)}): " |
| f"{sample.sass_kernel_names}") |
| print(f" sass columns ({len(sample.sass_column_names)}): " |
| f"{sample.sass_column_names}") |
| print() |
| cross_attention_shapes_demo(sample, d_model=args.d_model) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|