driftcal / src /generator.py
fahadhafeezofficial's picture
Upload 21 files
83827f5 verified
Raw History Blame Contribute Delete
10.2 kB
"""
DriftCal generative process.
Everything here is deterministic given a seed. The design intent:
- z in R^12 is a per-example latent "behavior vector", drawn from a
class-conditional Gaussian mixture (one component per family, incl. benign).
- x (observed features) = fixed nonlinear projection of z + noise, so the
projection itself never changes across scenarios -- only the z-generating
distribution or the y-given-z rule changes, which is what lets each shift
mechanism be cleanly defined and later recovered/attributed.
- Spurious features are downstream of the FINAL label y (not of z), so they
carry a real but non-causal correlation with y that a shortcut-learning
model can exploit; the spurious_ablation eval later breaks that
correlation by shuffling these columns.
All "world" parameters (projection matrices, family mean directions) are
fixed by WORLD_SEED so they are identical across every split and scenario;
only per-example noise / per-scenario z-sampling parameters vary.
"""
import hashlib
import numpy as np
Z_DIM = 12
N_CONTINUOUS = 48
N_BINARY = 16
N_SPURIOUS = 6
K_FEATURES = N_CONTINUOUS + N_BINARY + N_SPURIOUS # 70 total observed columns
WORLD_SEED = 20260918
# ---- Family taxonomy -------------------------------------------------
# id 0 = benign. ids 1-12 = 12 malicious families in 4 superfamilies of 3.
# ids 13-14 = 2 novel families, only ever instantiated in ood_test.
SUPERFAMILIES = {
"trojan": [1, 2, 3],
"ransomware": [4, 5, 6],
"spyware": [7, 8, 9],
"worm": [10, 11, 12],
}
FAMILY_TO_SUPERFAMILY = {fid: sf for sf, ids in SUPERFAMILIES.items() for fid in ids}
NOVEL_FAMILIES = [13, 14]
FAMILY_TO_SUPERFAMILY[13] = "novel_a"
FAMILY_TO_SUPERFAMILY[14] = "novel_b"
ALL_TRAIN_FAMILIES = [0] + list(range(1, 13)) # benign + 12 known families
FAMILY_NAMES = {0: "benign"}
for sf, ids in SUPERFAMILIES.items():
for i, fid in enumerate(ids):
FAMILY_NAMES[fid] = f"{sf}_{chr(ord('a') + i)}"
FAMILY_NAMES[13] = "novel_a_x"
FAMILY_NAMES[14] = "novel_b_x"
# Concept-shift designated families: these two flip their binary label
# (malicious -> benign) under the concept_shift mechanism only.
CONCEPT_SHIFT_FLIP_FAMILIES = [3, 9] # one trojan family, one spyware family (default/small-scale)
# Broader pool full-scale generation samples per-batch flip subsets from, so
# T7 (mechanism attribution) sees varied concept-shift severity/composition
# rather than one fixed pair every time -- two families per superfamily.
CONCEPT_FLIP_CANDIDATE_POOL = [2, 3, 5, 6, 8, 9, 11, 12]
DIFFICULTY_SIGMA = {"easy": 0.55, "medium": 0.85, "hard": 1.15, "expert": 1.45}
def _rng(seed: int) -> np.random.Generator:
return np.random.default_rng(seed)
def stable_id(*parts) -> str:
h = hashlib.sha1("|".join(str(p) for p in parts).encode()).hexdigest()
return h[:16]
class World:
"""Fixed, seed-derived generative-process parameters shared by every split."""
def __init__(self, seed: int = WORLD_SEED):
rng = _rng(seed)
n_families = len(FAMILY_NAMES)
# Family mean directions in z-space: superfamilies share a coarse
# direction (small shared offset) so within-superfamily families are
# closer together than across superfamilies -- gives multi-class
# structure that isn't just 13 arbitrary blobs.
self.superfamily_offsets = {}
for sf in list(SUPERFAMILIES.keys()) + ["novel_a", "novel_b"]:
self.superfamily_offsets[sf] = rng.normal(0, 1, size=Z_DIM)
self.superfamily_offsets[sf] /= np.linalg.norm(self.superfamily_offsets[sf])
self.family_means = {}
self.family_means[0] = np.zeros(Z_DIM) # benign centered at origin
separation = 3.2
for fid, name in FAMILY_NAMES.items():
if fid == 0:
continue
sf = FAMILY_TO_SUPERFAMILY[fid]
base = self.superfamily_offsets[sf] * separation
jitter = rng.normal(0, 0.35, size=Z_DIM)
self.family_means[fid] = base + jitter
# Fixed nonlinear projection z -> continuous features
hidden_dim = 24
self.A1 = rng.normal(0, 0.6, size=(N_CONTINUOUS, Z_DIM))
self.A3 = rng.normal(0, 0.6, size=(hidden_dim, Z_DIM))
self.A2 = rng.normal(0, 0.5, size=(N_CONTINUOUS, hidden_dim))
# a fixed set of pairwise interaction terms
self.interaction_pairs = [
(int(i), int(j))
for i, j in rng.integers(0, Z_DIM, size=(18, 2))
if i != j
]
self.A4 = rng.normal(0, 0.35, size=(N_CONTINUOUS, len(self.interaction_pairs)))
# Fixed projection z -> binary feature logits
self.A5 = rng.normal(0, 0.9, size=(N_BINARY, Z_DIM))
self.binary_flip_rate = 0.03
# Spurious features: downstream of y (not z), fixed coefficients
self.spurious_weight = rng.normal(2.0, 0.3, size=N_SPURIOUS)
self.spurious_noise_sd = 1.0
def project(self, z: np.ndarray, rng: np.random.Generator) -> np.ndarray:
"""z (n, Z_DIM) -> continuous+binary features (n, N_CONTINUOUS+N_BINARY)."""
n = z.shape[0]
hidden = np.maximum(z @ self.A3.T, 0) # relu
interaction_feats = np.stack(
[z[:, i] * z[:, j] for i, j in self.interaction_pairs], axis=1
)
cont = (
np.tanh(z @ self.A1.T) * 3.0
+ hidden @ self.A2.T * 0.4
+ interaction_feats @ self.A4.T
+ rng.normal(0, 0.4, size=(n, N_CONTINUOUS))
)
logits = z @ self.A5.T
probs = 1 / (1 + np.exp(-logits))
binary = (rng.random((n, N_BINARY)) < probs).astype(float)
flips = rng.random((n, N_BINARY)) < self.binary_flip_rate
binary = np.where(flips, 1 - binary, binary)
return np.concatenate([cont, binary], axis=1)
def spurious(self, y_binary: np.ndarray, rng: np.random.Generator, sign: float = 1.0) -> np.ndarray:
n = y_binary.shape[0]
base = np.outer(y_binary.astype(float), self.spurious_weight) * sign
return base + rng.normal(0, self.spurious_noise_sd, size=(n, N_SPURIOUS))
CONTINUOUS_COLS = [f"feat_cont_{i:02d}" for i in range(N_CONTINUOUS)]
BINARY_COLS = [f"feat_bin_{i:02d}" for i in range(N_BINARY)]
SPURIOUS_COLS = [f"feat_spurious_{i:02d}" for i in range(N_SPURIOUS)]
FEATURE_COLS = CONTINUOUS_COLS + BINARY_COLS + SPURIOUS_COLS
def sample_families(rng, n, family_weights):
fids = np.array(list(family_weights.keys()))
w = np.array(list(family_weights.values()), dtype=float)
w = w / w.sum()
return rng.choice(fids, size=n, p=w)
def default_family_weights(families):
"""benign gets 50%, remaining families split the other 50% evenly."""
weights = {}
n_other = len(families) - 1 if 0 in families else len(families)
for f in families:
weights[f] = 0.5 if f == 0 else 0.5 / n_other
return weights
def generate_batch(
world: World,
n: int,
families,
seed: int,
difficulty: str = "medium",
shift_type: str = "none",
shift_magnitude: float = 0.0,
family_weights=None,
concept_flip: bool = False,
concept_flip_families=None,
):
"""Generate n rows for a given scenario. Returns a dict of arrays."""
rng = _rng(seed)
if family_weights is None:
family_weights = default_family_weights(families)
if concept_flip_families is None:
concept_flip_families = CONCEPT_SHIFT_FLIP_FAMILIES
fam_ids = sample_families(rng, n, family_weights)
sigma = DIFFICULTY_SIGMA[difficulty]
z = np.zeros((n, Z_DIM))
for fid in np.unique(fam_ids):
mask = fam_ids == fid
mean = world.family_means[fid].copy()
if shift_type == "covariate":
# shift the behavioral profile itself, same family semantics
direction = world.superfamily_offsets.get(FAMILY_TO_SUPERFAMILY.get(fid, "trojan"))
if direction is None:
direction = np.ones(Z_DIM) / np.sqrt(Z_DIM)
mean = mean + direction * shift_magnitude
z[mask] = rng.normal(mean, sigma, size=(mask.sum(), Z_DIM))
x_main = world.project(z, rng)
fam_is_novel = np.isin(fam_ids, NOVEL_FAMILIES)
y_binary_original = (fam_ids != 0).astype(int)
if concept_flip:
flip_mask = np.isin(fam_ids, concept_flip_families)
y_binary = np.where(flip_mask, 1 - y_binary_original, y_binary_original)
else:
y_binary = y_binary_original
# Spurious features are always generated from the ORIGINAL family-based
# association, never from the post-flip label. This is what makes
# concept shift genuinely hard rather than accidentally solvable: the
# spurious cue is a stale correlation that has no way of "knowing" the
# true label was redefined, exactly like a real historical correlate
# would behave under true concept drift.
x_spurious = world.spurious(y_binary_original, _rng(seed + 1))
x = np.concatenate([x_main, x_spurious], axis=1)
return {
"z": z,
"x": x,
"family_id": fam_ids,
"family_is_novel": fam_is_novel,
"y_binary": y_binary,
}
def apply_adversarial_perturbation(x: np.ndarray, y_binary: np.ndarray, direction: np.ndarray, budget: float):
"""Bounded perturbation along a supplied direction vector (a unit vector
over the continuous+spurious feature block; the binary flag block must be
zeroed out in `direction` by the caller, since a continuous perturbation
would break their {0,1} semantics). `direction` is expected to come from
a white-box reference classifier's coefficient vector (an FGSM-style
linear evasion direction), not an arbitrary random vector, or the
perturbation has no reason to actually move a classifier's decision.
Pushes examples toward the opposite predicted class without altering the
true label -- true y is unchanged by construction, which is what keeps
this mechanism distinct from the natural-drift ones."""
sign = np.where(y_binary == 1, -1.0, 1.0) # push malicious toward benign-looking region
perturbation = np.outer(sign, direction) * budget
return x + perturbation