sgci 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sgci/__init__.py +20 -0
- sgci/__main__.py +4 -0
- sgci/_files.py +20 -0
- sgci/_version.py +1 -0
- sgci/activity.py +187 -0
- sgci/activity_workflow.py +247 -0
- sgci/classification.py +172 -0
- sgci/cli.py +222 -0
- sgci/comparison.py +231 -0
- sgci/diagnostics.py +87 -0
- sgci/dynamics.py +102 -0
- sgci/forecasting/__init__.py +10 -0
- sgci/forecasting/data.py +181 -0
- sgci/forecasting/scoring.py +143 -0
- sgci/forecasting/training.py +101 -0
- sgci/graph.py +49 -0
- sgci/invariance.py +125 -0
- sgci/response.py +158 -0
- sgci/selection.py +111 -0
- sgci/sensor.py +102 -0
- sgci-0.2.0.dist-info/METADATA +122 -0
- sgci-0.2.0.dist-info/RECORD +27 -0
- sgci-0.2.0.dist-info/WHEEL +5 -0
- sgci-0.2.0.dist-info/entry_points.txt +2 -0
- sgci-0.2.0.dist-info/licenses/LICENSE +15 -0
- sgci-0.2.0.dist-info/licenses/NOTICE +7 -0
- sgci-0.2.0.dist-info/top_level.txt +1 -0
sgci/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Structure-guided counterfactual invariance for sequential models."""
|
|
2
|
+
from ._version import __version__
|
|
3
|
+
from .activity_workflow import ActivityPredictor, compare_activity, compare_activity_predictions, fit_activity
|
|
4
|
+
from .classification import ActivityClassifier, fit_activity_classifier
|
|
5
|
+
from .comparison import compare_forecasts, summarize_forecast_pairs
|
|
6
|
+
from .diagnostics import rank_directions
|
|
7
|
+
from .dynamics import StructuredDynamics
|
|
8
|
+
from .forecasting import fit_forecaster, prepare_custom_forecast_data, prepare_forecast_data, score_forecast
|
|
9
|
+
from .invariance import invariance_penalty
|
|
10
|
+
from .response import measure_direction
|
|
11
|
+
from .selection import ProbePolicy
|
|
12
|
+
from .sensor import SensorForecaster, fit_sensor_forecaster
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"__version__", "ActivityClassifier", "ActivityPredictor", "ProbePolicy", "SensorForecaster",
|
|
16
|
+
"StructuredDynamics", "compare_activity", "compare_activity_predictions", "compare_forecasts",
|
|
17
|
+
"fit_activity", "fit_activity_classifier", "fit_forecaster", "fit_sensor_forecaster",
|
|
18
|
+
"invariance_penalty", "measure_direction", "prepare_custom_forecast_data", "prepare_forecast_data",
|
|
19
|
+
"rank_directions", "score_forecast", "summarize_forecast_pairs",
|
|
20
|
+
]
|
sgci/__main__.py
ADDED
sgci/_files.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Write a completed file atomically in its destination directory."""
|
|
2
|
+
from contextlib import contextmanager
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import tempfile
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@contextmanager
|
|
9
|
+
def output_file(path, *, binary=False):
|
|
10
|
+
path = Path(path)
|
|
11
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
12
|
+
with tempfile.NamedTemporaryFile(mode="wb" if binary else "w", encoding=None if binary else "utf-8",
|
|
13
|
+
delete=False, dir=path.parent) as f:
|
|
14
|
+
temporary = Path(f.name)
|
|
15
|
+
try:
|
|
16
|
+
yield f
|
|
17
|
+
f.close()
|
|
18
|
+
os.replace(temporary, path)
|
|
19
|
+
finally:
|
|
20
|
+
temporary.unlink(missing_ok=True)
|
sgci/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|
sgci/activity.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Activity model from the matched HAR study (§6–7)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import copy
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
from torch import nn
|
|
8
|
+
import torch.nn.functional as F
|
|
9
|
+
|
|
10
|
+
from .dynamics import StructuredDynamics
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TemporalEncoder(nn.Module):
|
|
15
|
+
"""Compact convolutional encoder retained for backward compatibility."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, input_dim: int, latent_dim: int, hidden_dim: int = 64) -> None:
|
|
18
|
+
super().__init__()
|
|
19
|
+
self.net = nn.Sequential(
|
|
20
|
+
nn.Conv1d(input_dim, hidden_dim, kernel_size=5, padding=2),
|
|
21
|
+
nn.BatchNorm1d(hidden_dim),
|
|
22
|
+
nn.SiLU(),
|
|
23
|
+
nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1),
|
|
24
|
+
nn.BatchNorm1d(hidden_dim),
|
|
25
|
+
nn.SiLU(),
|
|
26
|
+
nn.Conv1d(hidden_dim, latent_dim, kernel_size=3, padding=1),
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
30
|
+
if x.ndim != 3:
|
|
31
|
+
raise ValueError(f"Expected x=[batch,time,channels], got {tuple(x.shape)}")
|
|
32
|
+
return self.net(x.transpose(1, 2)).transpose(1, 2)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class InceptionBlock(nn.Module):
|
|
36
|
+
"""InceptionTime-style residual block with same-length temporal outputs."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, in_channels: int, filters: int = 32, kernels=(9, 19, 39)) -> None:
|
|
39
|
+
super().__init__()
|
|
40
|
+
bottleneck_channels = filters if in_channels > 1 else in_channels
|
|
41
|
+
self.bottleneck = nn.Conv1d(in_channels, bottleneck_channels, 1, bias=False)
|
|
42
|
+
self.branches = nn.ModuleList(
|
|
43
|
+
[
|
|
44
|
+
nn.Conv1d(
|
|
45
|
+
bottleneck_channels,
|
|
46
|
+
filters,
|
|
47
|
+
kernel_size=int(k),
|
|
48
|
+
padding=int(k) // 2,
|
|
49
|
+
bias=False,
|
|
50
|
+
)
|
|
51
|
+
for k in kernels
|
|
52
|
+
]
|
|
53
|
+
)
|
|
54
|
+
self.pool_branch = nn.Sequential(
|
|
55
|
+
nn.MaxPool1d(kernel_size=3, stride=1, padding=1),
|
|
56
|
+
nn.Conv1d(in_channels, filters, kernel_size=1, bias=False),
|
|
57
|
+
)
|
|
58
|
+
out_channels = filters * (len(kernels) + 1)
|
|
59
|
+
self.norm = nn.BatchNorm1d(out_channels)
|
|
60
|
+
self.residual = (
|
|
61
|
+
nn.Identity()
|
|
62
|
+
if in_channels == out_channels
|
|
63
|
+
else nn.Sequential(
|
|
64
|
+
nn.Conv1d(in_channels, out_channels, kernel_size=1, bias=False),
|
|
65
|
+
nn.BatchNorm1d(out_channels),
|
|
66
|
+
)
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
70
|
+
b = self.bottleneck(x)
|
|
71
|
+
parts = [branch(b) for branch in self.branches]
|
|
72
|
+
parts.append(self.pool_branch(x))
|
|
73
|
+
y = self.norm(torch.cat(parts, dim=1))
|
|
74
|
+
return F.silu(y + self.residual(x))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class InceptionTemporalEncoder(nn.Module):
|
|
78
|
+
"""Stronger sequence backbone that preserves a latent state at every time step."""
|
|
79
|
+
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
input_dim: int,
|
|
83
|
+
latent_dim: int,
|
|
84
|
+
filters: int = 32,
|
|
85
|
+
blocks: int = 3,
|
|
86
|
+
) -> None:
|
|
87
|
+
super().__init__()
|
|
88
|
+
modules: list[nn.Module] = []
|
|
89
|
+
channels = input_dim
|
|
90
|
+
for _ in range(int(blocks)):
|
|
91
|
+
block = InceptionBlock(channels, filters=filters)
|
|
92
|
+
modules.append(block)
|
|
93
|
+
channels = filters * 4
|
|
94
|
+
self.blocks = nn.Sequential(*modules)
|
|
95
|
+
self.project = nn.Sequential(
|
|
96
|
+
nn.Conv1d(channels, latent_dim, kernel_size=1, bias=False),
|
|
97
|
+
nn.BatchNorm1d(latent_dim),
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
101
|
+
if x.ndim != 3:
|
|
102
|
+
raise ValueError(f"Expected x=[batch,time,channels], got {tuple(x.shape)}")
|
|
103
|
+
y = self.blocks(x.transpose(1, 2))
|
|
104
|
+
return self.project(y).transpose(1, 2)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class ActivityClassifier(nn.Module):
|
|
108
|
+
"""Classify completed activity windows [N, time, channels] with an EMA teacher.
|
|
109
|
+
|
|
110
|
+
Defaults implement the paper's matched HAR architecture. The classifier reads
|
|
111
|
+
pooled encoder states. The transition is a training regularizer; the encoder
|
|
112
|
+
uses both sides of a window and is intended for completed-window labels.
|
|
113
|
+
"""
|
|
114
|
+
def __init__(
|
|
115
|
+
self,
|
|
116
|
+
input_dim: int = 9,
|
|
117
|
+
latent_dim: int = 32,
|
|
118
|
+
output_dim: int = 6,
|
|
119
|
+
encoder_hidden_dim: int = 64,
|
|
120
|
+
dynamics_hidden_dim: int = 64,
|
|
121
|
+
use_spectral_norm: bool = False,
|
|
122
|
+
encoder_type: str = "inception",
|
|
123
|
+
inception_filters: int = 32,
|
|
124
|
+
inception_blocks: int = 3,
|
|
125
|
+
head_hidden_dim: int = 128,
|
|
126
|
+
use_ema_target: bool = True,
|
|
127
|
+
ema_decay: float = 0.99,
|
|
128
|
+
) -> None:
|
|
129
|
+
super().__init__()
|
|
130
|
+
self.task = "classification"
|
|
131
|
+
self.latent_dim = int(latent_dim)
|
|
132
|
+
self.use_ema_target = bool(use_ema_target)
|
|
133
|
+
self.ema_decay = float(ema_decay)
|
|
134
|
+
if not 0.0 <= self.ema_decay <= 1.0:
|
|
135
|
+
raise ValueError("ema_decay must lie in [0, 1]")
|
|
136
|
+
if encoder_type == "inception":
|
|
137
|
+
self.encoder = InceptionTemporalEncoder(
|
|
138
|
+
input_dim=input_dim,
|
|
139
|
+
latent_dim=latent_dim,
|
|
140
|
+
filters=int(inception_filters),
|
|
141
|
+
blocks=int(inception_blocks),
|
|
142
|
+
)
|
|
143
|
+
elif encoder_type == "conv":
|
|
144
|
+
self.encoder = TemporalEncoder(input_dim, latent_dim, encoder_hidden_dim)
|
|
145
|
+
else:
|
|
146
|
+
raise ValueError(f"Unknown encoder_type={encoder_type}")
|
|
147
|
+
|
|
148
|
+
self.target_encoder = copy.deepcopy(self.encoder)
|
|
149
|
+
self.target_encoder.requires_grad_(False)
|
|
150
|
+
self.target_encoder.eval()
|
|
151
|
+
|
|
152
|
+
self.dynamics = StructuredDynamics(
|
|
153
|
+
latent_dim, hidden_dim=dynamics_hidden_dim, use_spectral_norm=use_spectral_norm
|
|
154
|
+
)
|
|
155
|
+
hidden = max(int(head_hidden_dim), latent_dim)
|
|
156
|
+
self.head = nn.Sequential(
|
|
157
|
+
nn.LayerNorm(latent_dim),
|
|
158
|
+
nn.Linear(latent_dim, hidden),
|
|
159
|
+
nn.SiLU(),
|
|
160
|
+
nn.Dropout(0.1),
|
|
161
|
+
nn.Linear(hidden, output_dim),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def train(self, mode: bool = True):
|
|
165
|
+
super().train(mode)
|
|
166
|
+
# The EMA teacher must always use frozen normalization statistics.
|
|
167
|
+
self.target_encoder.eval()
|
|
168
|
+
return self
|
|
169
|
+
|
|
170
|
+
@torch.no_grad()
|
|
171
|
+
def update_target_encoder(self) -> None:
|
|
172
|
+
if not self.use_ema_target:
|
|
173
|
+
self.target_encoder.load_state_dict(self.encoder.state_dict())
|
|
174
|
+
return
|
|
175
|
+
decay = self.ema_decay
|
|
176
|
+
online_params = dict(self.encoder.named_parameters())
|
|
177
|
+
for name, target_param in self.target_encoder.named_parameters():
|
|
178
|
+
target_param.mul_(decay).add_(online_params[name], alpha=1.0 - decay)
|
|
179
|
+
# BatchNorm running statistics are buffers; copying them avoids stale normalization.
|
|
180
|
+
online_buffers = dict(self.encoder.named_buffers())
|
|
181
|
+
for name, target_buffer in self.target_encoder.named_buffers():
|
|
182
|
+
target_buffer.copy_(online_buffers[name])
|
|
183
|
+
|
|
184
|
+
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
|
185
|
+
z = self.encoder(x)
|
|
186
|
+
task_out = self.head(z.mean(dim=1))
|
|
187
|
+
return task_out, z
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Train and reuse a completed-window activity classifier in sensor units."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from inspect import signature
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from ._files import output_file
|
|
11
|
+
from .activity import ActivityClassifier
|
|
12
|
+
from .classification import ActivityFit, fit_activity_classifier
|
|
13
|
+
from .selection import ProbePolicy
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _windows(values, *, channels=None):
|
|
17
|
+
if isinstance(values, torch.Tensor):
|
|
18
|
+
values = values.detach().cpu()
|
|
19
|
+
if values.dtype == torch.bfloat16:
|
|
20
|
+
values = values.float()
|
|
21
|
+
values = values.numpy()
|
|
22
|
+
x = np.asarray(values)
|
|
23
|
+
if (x.ndim != 3 or min(x.shape) < 1 or x.shape[1] < 2
|
|
24
|
+
or x.dtype.kind not in "iuf" or not np.isfinite(x).all()):
|
|
25
|
+
raise ValueError("windows must be finite numeric [N, T >= 2, C]")
|
|
26
|
+
if channels is not None and x.shape[2] != channels:
|
|
27
|
+
raise ValueError(f"expected {channels} input channels in training order, received {x.shape[2]}")
|
|
28
|
+
return x
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _vector(values, name):
|
|
32
|
+
if isinstance(values, torch.Tensor):
|
|
33
|
+
values = values.detach().cpu().numpy()
|
|
34
|
+
# Preserve heterogeneous types for the validation instead of silently
|
|
35
|
+
# converting mixed integers and strings to the same string label.
|
|
36
|
+
values = np.asarray(values, dtype=object)
|
|
37
|
+
if values.ndim != 1 or len(values) == 0:
|
|
38
|
+
raise ValueError(f"{name} must be a nonempty vector")
|
|
39
|
+
if all(isinstance(v, (int, np.integer)) and not isinstance(v, (bool, np.bool_)) for v in values):
|
|
40
|
+
ints = [int(v) for v in values]
|
|
41
|
+
array = np.array(ints)
|
|
42
|
+
# Mixing large unsigned IDs and negative IDs can make NumPy select
|
|
43
|
+
# float64, which rounds distinct integers above 2**53 to the same ID.
|
|
44
|
+
return np.array(ints, dtype=object) if array.dtype.kind == "f" else array
|
|
45
|
+
if all(isinstance(v, str) and v.strip() for v in values):
|
|
46
|
+
return np.array(values.tolist(), dtype=str)
|
|
47
|
+
raise ValueError(f"{name} must contain integer labels or nonempty string labels of one type")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _scale(x, mean, scale):
|
|
51
|
+
result = np.ascontiguousarray((x - mean) / scale, dtype=np.float32)
|
|
52
|
+
if not np.isfinite(result).all():
|
|
53
|
+
raise ValueError("standardized windows exceed the finite float32 range")
|
|
54
|
+
return torch.from_numpy(result)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _architecture(channels, classes, options):
|
|
58
|
+
if options is not None and not isinstance(options, dict):
|
|
59
|
+
raise ValueError("model_options must be a dictionary of ActivityClassifier options")
|
|
60
|
+
options = dict(options or {})
|
|
61
|
+
if "input_dim" in options or "output_dim" in options:
|
|
62
|
+
raise ValueError("input_dim and output_dim are inferred from the training data")
|
|
63
|
+
args = signature(ActivityClassifier).bind(input_dim=channels, output_dim=classes, **options)
|
|
64
|
+
args.apply_defaults()
|
|
65
|
+
config = dict(args.arguments)
|
|
66
|
+
for name in ("latent_dim", "encoder_hidden_dim", "dynamics_hidden_dim", "inception_filters",
|
|
67
|
+
"inception_blocks", "head_hidden_dim"):
|
|
68
|
+
if type(config[name]) is not int or config[name] < 1:
|
|
69
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
70
|
+
return config
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class ActivityPredictor:
|
|
75
|
+
"""Model, label vocabulary and training channel scales for future windows.
|
|
76
|
+
|
|
77
|
+
Windows must have the training channel order and measurement units. Probability
|
|
78
|
+
column j denotes classes[j]. Saving stores inference state and probe selection.
|
|
79
|
+
"""
|
|
80
|
+
fit: ActivityFit
|
|
81
|
+
classes: np.ndarray
|
|
82
|
+
mean: np.ndarray
|
|
83
|
+
scale: np.ndarray
|
|
84
|
+
_config: dict
|
|
85
|
+
|
|
86
|
+
@torch.inference_mode()
|
|
87
|
+
def predict_proba(self, windows, *, batch_size=128):
|
|
88
|
+
"""Predict one probability vector per input window, preserving input order."""
|
|
89
|
+
if type(batch_size) is not int or batch_size < 1:
|
|
90
|
+
raise ValueError("batch_size must be a positive integer")
|
|
91
|
+
x = _windows(windows, channels=len(self.mean))
|
|
92
|
+
model = self.fit.model
|
|
93
|
+
device = next(model.parameters()).device
|
|
94
|
+
model.eval()
|
|
95
|
+
batches = []
|
|
96
|
+
for start in range(0, len(x), batch_size):
|
|
97
|
+
chunk = _scale(x[start:start + batch_size], self.mean, self.scale)
|
|
98
|
+
logits, _ = model(chunk.to(device))
|
|
99
|
+
batches.append(logits.softmax(dim=1).cpu().numpy())
|
|
100
|
+
return np.concatenate(batches, axis=0)
|
|
101
|
+
|
|
102
|
+
def predict(self, windows, *, batch_size=128):
|
|
103
|
+
"""Return the original integer or string labels rather than class indices."""
|
|
104
|
+
return self.classes[self.predict_proba(windows, batch_size=batch_size).argmax(axis=1)]
|
|
105
|
+
|
|
106
|
+
def save(self, path):
|
|
107
|
+
"""Atomically save a portable checkpoint using tensors and plain metadata."""
|
|
108
|
+
payload = {
|
|
109
|
+
"format": "sgci.activity.1", "config": self._config, "classes": self.classes.tolist(),
|
|
110
|
+
"mean": torch.as_tensor(self.mean).cpu(), "scale": torch.as_tensor(self.scale).cpu(),
|
|
111
|
+
"state": {k: v.detach().cpu() for k, v in self.fit.model.state_dict().items()},
|
|
112
|
+
"steps": self.fit.steps, "warmup_gates": self.fit.warmup_gates.detach().cpu(),
|
|
113
|
+
"policy": self.fit.policy.state_dict() if self.fit.policy is not None else None,
|
|
114
|
+
}
|
|
115
|
+
with output_file(path, binary=True) as handle:
|
|
116
|
+
torch.save(payload, handle)
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def load(cls, path, *, device="cpu"):
|
|
120
|
+
"""Load an SGCI activity checkpoint and restore evaluation mode."""
|
|
121
|
+
saved = torch.load(path, map_location="cpu", weights_only=True)
|
|
122
|
+
if not isinstance(saved, dict) or saved.get("format") != "sgci.activity.1":
|
|
123
|
+
raise ValueError("expected an sgci.activity.1 checkpoint")
|
|
124
|
+
config = saved["config"]
|
|
125
|
+
classes = _vector(saved["classes"], "stored classes")
|
|
126
|
+
mean, scale = saved["mean"].numpy(), saved["scale"].numpy()
|
|
127
|
+
if (mean.shape != (config["input_dim"],) or scale.shape != mean.shape
|
|
128
|
+
or not np.isfinite(mean).all() or not np.isfinite(scale).all() or (scale <= 0).any()
|
|
129
|
+
or len(classes) != config["output_dim"] or len(np.unique(classes)) != len(classes)):
|
|
130
|
+
raise ValueError("checkpoint class or channel metadata is inconsistent")
|
|
131
|
+
with torch.random.fork_rng(devices=[]):
|
|
132
|
+
model = ActivityClassifier(**config).float()
|
|
133
|
+
model.load_state_dict(saved["state"], strict=True)
|
|
134
|
+
snapshot = saved["warmup_gates"]
|
|
135
|
+
if snapshot.shape != (model.latent_dim, model.latent_dim):
|
|
136
|
+
raise ValueError("checkpoint warm-up gate shape does not match latent dimension")
|
|
137
|
+
policy = ProbePolicy.from_state_dict(saved["policy"]) if saved["policy"] is not None else None
|
|
138
|
+
if policy is not None:
|
|
139
|
+
policy.candidate_mask(snapshot)
|
|
140
|
+
fit = ActivityFit(model.to(device).eval(), policy, snapshot, saved["steps"])
|
|
141
|
+
return cls(fit, classes, mean, scale, config)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def fit_activity(windows, labels, *, policy="fixed_learned", protected_fraction=1/3,
|
|
145
|
+
epochs=80, batch_size=128, seed=0, device="cpu", model_options=None):
|
|
146
|
+
"""Train on complete labelled windows, fitting scaling and classes on training rows only.
|
|
147
|
+
|
|
148
|
+
labels may be strings or arbitrary integer IDs, including sparse and negative IDs.
|
|
149
|
+
Each channel is centered by its training mean and divided by population SD + 1e-6.
|
|
150
|
+
For a constant training channel the divisor is one. Model dimensions follow the
|
|
151
|
+
input; optional architecture settings (e.g. latent_dim) go in model_options.
|
|
152
|
+
"""
|
|
153
|
+
x = _windows(windows)
|
|
154
|
+
y = _vector(labels, "labels")
|
|
155
|
+
if len(x) != len(y):
|
|
156
|
+
raise ValueError("expected one class label per training window")
|
|
157
|
+
if type(seed) is not int or seed < 0:
|
|
158
|
+
raise ValueError("seed must be a nonnegative integer")
|
|
159
|
+
classes, encoded = np.unique(y, return_inverse=True)
|
|
160
|
+
if len(classes) < 2:
|
|
161
|
+
raise ValueError("training windows must include at least two distinct activity labels")
|
|
162
|
+
mean = x.mean(axis=(0, 1), dtype=np.float64)
|
|
163
|
+
std = x.std(axis=(0, 1), dtype=np.float64)
|
|
164
|
+
scale = np.where(std > 0, std + 1e-6, 1.0)
|
|
165
|
+
config = _architecture(x.shape[-1], len(classes), model_options)
|
|
166
|
+
with torch.random.fork_rng(devices=[]):
|
|
167
|
+
torch.random.default_generator.manual_seed(seed)
|
|
168
|
+
model = ActivityClassifier(**config).float()
|
|
169
|
+
fit = fit_activity_classifier(_scale(x, mean, scale), encoded, model=model, policy=policy,
|
|
170
|
+
protected_fraction=protected_fraction, epochs=epochs,
|
|
171
|
+
batch_size=batch_size, seed=seed, device=device)
|
|
172
|
+
return ActivityPredictor(fit, classes, mean, scale, config)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def compare_activity_predictions(y_true, reference, learned, *, groups=None):
|
|
176
|
+
"""Compare paired decisions on the same ordered windows.
|
|
177
|
+
|
|
178
|
+
Accuracy is a fraction; delta_accuracy_pp is learned minus reference in
|
|
179
|
+
percentage points. indices are zero-based positions in the supplied vectors.
|
|
180
|
+
Population summaries weight windows equally; group rows show each group separately.
|
|
181
|
+
"""
|
|
182
|
+
y, ref, new = (_vector(v, name) for v, name in
|
|
183
|
+
[(y_true, "y_true"), (reference, "reference"), (learned, "learned")])
|
|
184
|
+
if not len(y) == len(ref) == len(new):
|
|
185
|
+
raise ValueError("truth and both prediction vectors must have the same length")
|
|
186
|
+
if (y.dtype.kind == "U") != (ref.dtype.kind == "U") or (y.dtype.kind == "U") != (new.dtype.kind == "U"):
|
|
187
|
+
raise ValueError("truth and predictions must have the same label type")
|
|
188
|
+
ref_ok, new_ok = y == ref, y == new
|
|
189
|
+
categories = {"corrected": ~ref_ok & new_ok, "introduced": ref_ok & ~new_ok,
|
|
190
|
+
"both_right": ref_ok & new_ok, "both_wrong": ~ref_ok & ~new_ok}
|
|
191
|
+
|
|
192
|
+
def summary(rows):
|
|
193
|
+
n = len(ref_ok[rows])
|
|
194
|
+
counts = {key: int(arr[rows].sum()) for key, arr in categories.items()}
|
|
195
|
+
return {"n": n, "reference_accuracy": float(ref_ok[rows].mean()),
|
|
196
|
+
"learned_accuracy": float(new_ok[rows].mean()),
|
|
197
|
+
"delta_accuracy_pp": 100 * (counts["corrected"] - counts["introduced"]) / n,
|
|
198
|
+
"counts": counts}
|
|
199
|
+
|
|
200
|
+
result = summary(slice(None))
|
|
201
|
+
result["indices"] = {key: np.flatnonzero(arr).tolist() for key, arr in categories.items()}
|
|
202
|
+
result["by_group"] = []
|
|
203
|
+
if groups is not None:
|
|
204
|
+
g = _vector(groups, "groups")
|
|
205
|
+
if len(g) != len(y):
|
|
206
|
+
raise ValueError("groups must contain one group identifier per window")
|
|
207
|
+
result["by_group"] = [{"group": group, **summary(g == group)} for group in np.unique(g).tolist()]
|
|
208
|
+
return result
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def compare_activity(train_x, train_y, test_x, test_y, *, groups=None, seed=0, epochs=80,
|
|
212
|
+
batch_size=128, model_options=None, device="cpu", protected_fraction=1/3):
|
|
213
|
+
"""Train matched fixed-random and fixed-learned controls and compare held-out decisions.
|
|
214
|
+
|
|
215
|
+
Supply separate training and evaluation windows in their original sensor units.
|
|
216
|
+
Both policies use identical training rows, architecture, initial seed, minibatch
|
|
217
|
+
order and number of updates. Only probe selection changes. groups, if provided,
|
|
218
|
+
identifies the participant of each evaluation window. It does not define a split.
|
|
219
|
+
"""
|
|
220
|
+
train_x = _windows(train_x)
|
|
221
|
+
test_x = _windows(test_x, channels=train_x.shape[2])
|
|
222
|
+
train_y, test_y = _vector(train_y, "train_y"), _vector(test_y, "test_y")
|
|
223
|
+
if len(train_x) != len(train_y) or len(test_x) != len(test_y):
|
|
224
|
+
raise ValueError("expected one label for each training and evaluation window")
|
|
225
|
+
unseen = sorted(set(test_y.tolist()) - set(train_y.tolist()))
|
|
226
|
+
if unseen:
|
|
227
|
+
raise ValueError(f"evaluation labels absent from the training vocabulary: {unseen!r}")
|
|
228
|
+
if groups is not None:
|
|
229
|
+
groups = _vector(groups, "groups")
|
|
230
|
+
if len(groups) != len(test_y):
|
|
231
|
+
raise ValueError("groups must contain one group identifier per evaluation window")
|
|
232
|
+
|
|
233
|
+
fit_options = dict(seed=seed, epochs=epochs, batch_size=batch_size, model_options=model_options,
|
|
234
|
+
device=device, protected_fraction=protected_fraction)
|
|
235
|
+
reference = fit_activity(train_x, train_y, policy="fixed_random", **fit_options)
|
|
236
|
+
ref_predictions = reference.predict(test_x, batch_size=batch_size)
|
|
237
|
+
ref_snapshot, ref_steps = reference.fit.warmup_gates, reference.fit.steps
|
|
238
|
+
del reference # Only one model needs to reside on the accelerator at a time.
|
|
239
|
+
learned = fit_activity(train_x, train_y, policy="fixed_learned", **fit_options)
|
|
240
|
+
if ref_steps != learned.fit.steps or not torch.equal(ref_snapshot, learned.fit.warmup_gates):
|
|
241
|
+
raise RuntimeError("paired fits diverged before probe selection or used different budgets; "
|
|
242
|
+
"run on CPU to obtain a deterministic comparison")
|
|
243
|
+
report = compare_activity_predictions(test_y, ref_predictions,
|
|
244
|
+
learned.predict(test_x, batch_size=batch_size), groups=groups)
|
|
245
|
+
report.update(seed=seed, comparator="fixed_random", learned_policy="fixed_learned",
|
|
246
|
+
warmup_matched=True, steps_per_fit=ref_steps)
|
|
247
|
+
return report
|
sgci/classification.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Matched HAR objective and a final-epoch classifier fit on complete windows."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
from torch.nn import functional as F
|
|
9
|
+
|
|
10
|
+
from .activity import ActivityClassifier
|
|
11
|
+
from .invariance import invariance_penalty
|
|
12
|
+
from .selection import ProbePolicy
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class ActivityLoss:
|
|
17
|
+
total: torch.Tensor
|
|
18
|
+
classification: torch.Tensor
|
|
19
|
+
dynamics: torch.Tensor
|
|
20
|
+
sparsity: torch.Tensor
|
|
21
|
+
invariance: torch.Tensor
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def activity_loss(model: ActivityClassifier, windows: torch.Tensor, labels: torch.Tensor,
|
|
25
|
+
*, policy: ProbePolicy | None, dynamics_weight: float = .1,
|
|
26
|
+
invariance_weight: float = .1, sparsity_weight: float = .005,
|
|
27
|
+
pair_generator=None, donor_generator=None, row_generator=None) -> ActivityLoss:
|
|
28
|
+
"""Compute cross-entropy, EMA transition loss and the standardized HAR probe.
|
|
29
|
+
|
|
30
|
+
Set invariance_weight to zero during warm-up. Rows are layer-normalized
|
|
31
|
+
latent states, with at most 512 rows and 16 directions per update. Call
|
|
32
|
+
model.update_target_encoder() after the optimizer step.
|
|
33
|
+
"""
|
|
34
|
+
weights = (dynamics_weight, invariance_weight, sparsity_weight)
|
|
35
|
+
if any(not math.isfinite(v) or v < 0 for v in weights):
|
|
36
|
+
raise ValueError("Loss weights must be finite and nonnegative")
|
|
37
|
+
if invariance_weight and policy is None:
|
|
38
|
+
raise ValueError("Provide a probe policy for a positive invariance weight")
|
|
39
|
+
logits, latent = model(windows)
|
|
40
|
+
ce = F.cross_entropy(logits, labels)
|
|
41
|
+
dynamics = invariant = ce.new_zeros(())
|
|
42
|
+
sparsity = model.dynamics.graph.sparsity_loss()
|
|
43
|
+
if dynamics_weight or invariance_weight:
|
|
44
|
+
if latent.shape[1] < 2:
|
|
45
|
+
raise ValueError("The transition objective needs at least two time steps")
|
|
46
|
+
with torch.autocast(latent.device.type, enabled=False):
|
|
47
|
+
rows = F.layer_norm(latent.float(), (model.latent_dim,))[:, :-1].reshape(-1, model.latent_dim)
|
|
48
|
+
if dynamics_weight:
|
|
49
|
+
with torch.no_grad():
|
|
50
|
+
teacher = model.target_encoder(windows) if model.use_ema_target else latent.detach()
|
|
51
|
+
with torch.autocast(latent.device.type, enabled=False):
|
|
52
|
+
targets = F.layer_norm(teacher.float(), (model.latent_dim,))[:, 1:].reshape_as(rows)
|
|
53
|
+
dynamics = F.smooth_l1_loss(model.dynamics(rows), targets)
|
|
54
|
+
if invariance_weight:
|
|
55
|
+
with torch.autocast(latent.device.type, enabled=False):
|
|
56
|
+
invariant = invariance_penalty(
|
|
57
|
+
model.dynamics, rows, policy, num_pairs=16, row_limit=512, protocol="har",
|
|
58
|
+
pair_generator=pair_generator, donor_generator=donor_generator,
|
|
59
|
+
row_generator=row_generator,
|
|
60
|
+
).loss
|
|
61
|
+
total = ce + dynamics_weight * dynamics + sparsity_weight * sparsity + invariance_weight * invariant
|
|
62
|
+
return ActivityLoss(total, ce, dynamics, sparsity, invariant)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class ActivityFit:
|
|
67
|
+
"""Final model in evaluation mode, policy and CPU gate snapshot at warm-up."""
|
|
68
|
+
model: ActivityClassifier
|
|
69
|
+
policy: ProbePolicy | None
|
|
70
|
+
warmup_gates: torch.Tensor
|
|
71
|
+
steps: int
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _ramp(step, warmup, duration):
|
|
75
|
+
if step < warmup:
|
|
76
|
+
return 0.
|
|
77
|
+
return .1 if duration == 0 else .1 * min(1., (step - warmup) / duration)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def fit_activity_classifier(windows, labels, *, model: ActivityClassifier | None = None,
|
|
81
|
+
policy: str = "fixed_learned", protected_fraction: float = 1/3,
|
|
82
|
+
epochs: int = 80, batch_size: int = 128, seed: int = 0,
|
|
83
|
+
device: str | torch.device = "cpu") -> ActivityFit:
|
|
84
|
+
"""Fit on training windows [N,T,C], with zero-based integer class labels [N].
|
|
85
|
+
|
|
86
|
+
Accepts a caller-initialized model, including a model restored from a shared
|
|
87
|
+
starting state. Defaults use the HAR objective and schedules. This helper
|
|
88
|
+
runs in FP32 and returns the final epoch. It does not select on test data.
|
|
89
|
+
"""
|
|
90
|
+
kinds = {"fixed_learned", "fixed_random", "dynamic_learned", "reversed_half", "all", "baseline"}
|
|
91
|
+
if policy not in kinds or not 0 < protected_fraction < 1:
|
|
92
|
+
raise ValueError(f"Choose a policy in {sorted(kinds)} and a fraction in (0,1)")
|
|
93
|
+
x = torch.as_tensor(windows, dtype=torch.float32)
|
|
94
|
+
y = torch.as_tensor(labels)
|
|
95
|
+
if x.ndim != 3 or min(x.shape) < 1 or x.shape[1] < 2 or not torch.isfinite(x).all():
|
|
96
|
+
raise ValueError("windows must be finite [N, T>=2, channels]")
|
|
97
|
+
if (y.ndim != 1 or y.shape[0] != len(x) or y.is_floating_point() or
|
|
98
|
+
y.is_complex() or y.dtype == torch.bool or (y < 0).any()):
|
|
99
|
+
raise ValueError("labels must be a vector of nonnegative integers, one per window")
|
|
100
|
+
if type(epochs) is not int or type(batch_size) is not int or min(epochs, batch_size) < 1:
|
|
101
|
+
raise ValueError("epochs and batch_size must be positive integers")
|
|
102
|
+
device = torch.device(device)
|
|
103
|
+
if device.type not in {"cpu", "cuda"}:
|
|
104
|
+
raise ValueError("device must be cpu or cuda")
|
|
105
|
+
if type(seed) is not int or seed < 0:
|
|
106
|
+
raise ValueError("seed must be a nonnegative integer")
|
|
107
|
+
if policy == "reversed_half" and protected_fraction != .5:
|
|
108
|
+
raise ValueError("reversed_half requires protected_fraction=0.5")
|
|
109
|
+
classes = int(y.max()) + 1
|
|
110
|
+
if model is not None and classes > model.head[-1].out_features:
|
|
111
|
+
raise ValueError("An input label exceeds the model's class count")
|
|
112
|
+
# A symmetric donor probe needs two current states. For two-step
|
|
113
|
+
# windows, merge a one-window tail into its neighbour.
|
|
114
|
+
if x.shape[1] == 2 and policy != "baseline":
|
|
115
|
+
if len(x) < 2:
|
|
116
|
+
raise ValueError("SGCI needs at least two training transitions")
|
|
117
|
+
batch_size = max(2, batch_size)
|
|
118
|
+
steps_per_epoch = math.ceil(len(x) / batch_size)
|
|
119
|
+
if x.shape[1] == 2 and policy != "baseline" and steps_per_epoch > 1 and len(x) % batch_size == 1:
|
|
120
|
+
steps_per_epoch -= 1
|
|
121
|
+
total = epochs * steps_per_epoch
|
|
122
|
+
capture = int(.3 * epochs)
|
|
123
|
+
rngs = [torch.Generator(device="cpu").manual_seed(offset + seed)
|
|
124
|
+
for offset in (410000, 510000, 610000)]
|
|
125
|
+
cuda_devices = [device.index if device.index is not None else torch.cuda.current_device()] if device.type == "cuda" else []
|
|
126
|
+
rule = None
|
|
127
|
+
with torch.random.fork_rng(devices=cuda_devices):
|
|
128
|
+
torch.random.default_generator.manual_seed(seed)
|
|
129
|
+
if model is None:
|
|
130
|
+
model = ActivityClassifier(input_dim=x.shape[2], output_dim=classes)
|
|
131
|
+
model = model.to(device).train()
|
|
132
|
+
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=.001, weight_decay=.0001)
|
|
133
|
+
for epoch in range(epochs):
|
|
134
|
+
if epoch == capture:
|
|
135
|
+
snapshot = model.dynamics.edge_probabilities().detach().cpu().clone()
|
|
136
|
+
if policy == "fixed_learned":
|
|
137
|
+
rule = ProbePolicy.fixed(snapshot, protected_fraction)
|
|
138
|
+
elif policy == "fixed_random":
|
|
139
|
+
rule = ProbePolicy.random(len(snapshot), 310000 + seed, protected_fraction)
|
|
140
|
+
elif policy == "dynamic_learned":
|
|
141
|
+
rule = ProbePolicy.dynamic(protected_fraction)
|
|
142
|
+
elif policy == "reversed_half":
|
|
143
|
+
rule = ProbePolicy.reversed_half(snapshot)
|
|
144
|
+
elif policy == "all":
|
|
145
|
+
rule = ProbePolicy.all()
|
|
146
|
+
lr = .00001 + .5 * (.001 - .00001) * (1 + math.cos(math.pi * epoch / max(1, epochs - 1)))
|
|
147
|
+
for group in opt.param_groups:
|
|
148
|
+
group["lr"] = lr
|
|
149
|
+
rng = torch.Generator(device="cpu").manual_seed(110000 + seed * 1000 + epoch * 3)
|
|
150
|
+
order = torch.randperm(len(x), generator=rng)
|
|
151
|
+
for batch in range(steps_per_epoch):
|
|
152
|
+
first = batch * batch_size
|
|
153
|
+
stop = len(x) if batch + 1 == steps_per_epoch else first + batch_size
|
|
154
|
+
indices = order[first:stop]
|
|
155
|
+
step = epoch * steps_per_epoch + batch
|
|
156
|
+
dropout_seed = 210000 + seed * 100000 + step * 3
|
|
157
|
+
torch.random.default_generator.manual_seed(dropout_seed)
|
|
158
|
+
if cuda_devices:
|
|
159
|
+
with torch.cuda.device(cuda_devices[0]):
|
|
160
|
+
torch.cuda.manual_seed(dropout_seed)
|
|
161
|
+
opt.zero_grad(set_to_none=True)
|
|
162
|
+
out = activity_loss(
|
|
163
|
+
model, x[indices].to(device), y[indices].to(device, dtype=torch.long),
|
|
164
|
+
policy=rule, dynamics_weight=_ramp(step, int(.1*total), int(.2*total)),
|
|
165
|
+
invariance_weight=_ramp(step, int(.3*total), int(.2*total)) if rule is not None else 0.,
|
|
166
|
+
pair_generator=rngs[0], donor_generator=rngs[1], row_generator=rngs[2],
|
|
167
|
+
)
|
|
168
|
+
out.total.backward()
|
|
169
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 2., error_if_nonfinite=True)
|
|
170
|
+
opt.step()
|
|
171
|
+
model.update_target_encoder()
|
|
172
|
+
return ActivityFit(model.eval(), rule, snapshot, total)
|