File size: 11,553 Bytes
083b138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""Deterministic value-to-token mapping for structured transaction features.

Each feature has its own tokenizer that maps raw values to token IDs using
the reserved token convention (D6): 0=MASK, 1=OOV, 2=NULL, 3+=real values.
Categorical features map directly; bucketed features use quantile or uniform
boundaries computed during fit().

OOV handling (D3): values outside the known range map to OOV token (1) and
increment a per-feature counter logged during eval.
"""

import hashlib
import json
from pathlib import Path
from typing import Any

import numpy as np

from src.data.schema import (
    FeatureSchema,
    SchemaConfig,
    MASK_TOKEN,
    NULL_TOKEN,
    OOV_TOKEN,
    VALUES_START,
    load_schema,
)


class FeatureTokenizer:
    """Tokenizer for a single feature. Handles encode, decode, and OOV tracking."""

    def __init__(self, schema: FeatureSchema) -> None:
        self._schema = schema
        self._boundaries: np.ndarray | None = None
        self._oov_count: int = 0
        self._fitted: bool = schema.type != "bucketed"

    @property
    def name(self) -> str:
        return self._schema.name

    @property
    def vocab_size(self) -> int:
        return self._schema.vocab_size

    @property
    def is_fitted(self) -> bool:
        return self._fitted

    @property
    def oov_count(self) -> int:
        return self._oov_count

    def reset_oov_count(self) -> None:
        self._oov_count = 0

    def fit(self, values: np.ndarray) -> None:
        """Compute bucket boundaries from data. Only valid for bucketed features.

        Args:
            values: 1-D array of raw continuous values to compute boundaries from.
        """
        assert self._schema.type == "bucketed", (
            f"fit() only applies to bucketed features, not {self._schema.type}"
        )
        assert self._schema.bucket_range is not None
        assert self._schema.bucket_method is not None

        num_buckets = self._schema.num_values

        if self._schema.bucket_method == "quantile":
            quantiles = np.linspace(0.0, 1.0, num_buckets + 1)
            self._boundaries = np.quantile(values, quantiles).astype(np.float64)
        elif self._schema.bucket_method == "uniform":
            lo, hi = self._schema.bucket_range
            self._boundaries = np.linspace(lo, hi, num_buckets + 1, dtype=np.float64)
        else:
            raise ValueError(f"Unknown bucket_method: {self._schema.bucket_method}")

        self._fitted = True

    def fit_uniform_from_range(self) -> None:
        """Compute uniform boundaries directly from the schema's bucket_range."""
        assert self._schema.type == "bucketed"
        assert self._schema.bucket_range is not None
        lo, hi = self._schema.bucket_range
        self._boundaries = np.linspace(
            lo, hi, self._schema.num_values + 1, dtype=np.float64
        )
        self._fitted = True

    def encode(self, values: np.ndarray) -> np.ndarray:
        """Map raw values to token IDs.

        Args:
            values: array of raw feature values (any shape).

        Returns:
            int16 array of token IDs, same shape as input.
        """
        assert self._fitted, f"Feature '{self.name}' not fitted. Call fit() first."
        original_shape = values.shape
        flat = values.ravel()

        if self._schema.type == "bucketed":
            token_ids, oov_count = self._encode_bucketed(flat)
        else:
            token_ids, oov_count = self._encode_categorical(flat)

        self._oov_count += oov_count
        return token_ids.reshape(original_shape)

    def decode(self, token_ids: np.ndarray) -> np.ndarray:
        """Map token IDs back to values. Bucketed features return bucket centers.

        Special tokens (MASK, OOV, NULL) decode to NaN.

        Args:
            token_ids: array of token IDs (any shape).

        Returns:
            float64 array of decoded values, same shape as input.
        """
        original_shape = token_ids.shape
        flat = token_ids.ravel().astype(np.int64)
        result = np.full(len(flat), np.nan, dtype=np.float64)

        value_mask = flat >= VALUES_START
        value_indices = flat[value_mask] - VALUES_START

        if self._schema.type == "bucketed" and self._boundaries is not None:
            centers = (self._boundaries[:-1] + self._boundaries[1:]) / 2.0
            valid = value_indices < len(centers)
            result_positions = np.where(value_mask)[0]
            result[result_positions[valid]] = centers[value_indices[valid]]
        else:
            result[value_mask] = value_indices.astype(np.float64)

        return result.reshape(original_shape)

    def _encode_categorical(self, values: np.ndarray) -> tuple[np.ndarray, int]:
        """Encode categorical/binary values. Returns (token_ids, oov_count)."""
        int_values = values.astype(np.int64)
        oov_mask = (int_values < 0) | (int_values >= self._schema.num_values)
        token_ids = (int_values + VALUES_START).astype(np.int16)
        token_ids[oov_mask] = OOV_TOKEN
        return token_ids, int(oov_mask.sum())

    def _encode_bucketed(self, values: np.ndarray) -> tuple[np.ndarray, int]:
        """Encode bucketed values using pre-computed boundaries.

        Returns (token_ids, oov_count). Uses np.digitize on internal boundaries
        so bucket index i covers [boundaries[i], boundaries[i+1]).
        The last bucket includes its upper bound: [boundaries[-2], boundaries[-1]].
        """
        assert self._boundaries is not None
        internal_bins = self._boundaries[1:-1]
        bucket_idx = np.digitize(values, internal_bins)
        # bucket_idx in [0, num_values - 1] for values within boundary range.
        # Can be num_values for values above the last internal bin, but np.digitize
        # with N-1 internal bins returns at most N-1 for values < boundaries[-1].
        # Values exactly at boundaries[-1] get num_values - 1 (last bucket).
        bucket_idx = np.clip(bucket_idx, 0, self._schema.num_values - 1)

        oov_mask = (values < self._boundaries[0]) | (values > self._boundaries[-1])
        token_ids = (bucket_idx + VALUES_START).astype(np.int16)
        token_ids[oov_mask] = OOV_TOKEN
        return token_ids, int(oov_mask.sum())

    def get_state(self) -> dict[str, Any]:
        """Serializable state for fingerprinting and persistence."""
        state: dict[str, Any] = {
            "name": self._schema.name,
            "type": self._schema.type,
            "num_values": self._schema.num_values,
            "vocab_size": self._schema.vocab_size,
        }
        if self._boundaries is not None:
            state["boundaries"] = self._boundaries.tolist()
        return state


class TransactionTokenizer:
    """Orchestrates tokenization across all features in the schema.

    Usage:
        schema = load_schema("data/schema.yaml")
        tokenizer = TransactionTokenizer(schema)

        # Fit bucketed features from raw data
        tokenizer.fit_feature("amount", raw_amounts)
        tokenizer.fit_feature("days_since_last", raw_days)

        # Encode
        token_ids = tokenizer.encode_feature("amount", raw_values)

        # Save state and compute fingerprint
        tokenizer.save_state("data/synthetic/tokenizer_state.json")
        fp = tokenizer.compute_fingerprint("data/schema.yaml")
    """

    def __init__(self, schema: SchemaConfig) -> None:
        self._schema = schema
        self._tokenizers: dict[str, FeatureTokenizer] = {}
        for feature in schema.features:
            self._tokenizers[feature.name] = FeatureTokenizer(feature)

    @property
    def feature_names(self) -> list[str]:
        return self._schema.feature_names()

    @property
    def num_features(self) -> int:
        return self._schema.num_features

    def get_feature_tokenizer(self, name: str) -> FeatureTokenizer:
        return self._tokenizers[name]

    def fit_feature(self, name: str, values: np.ndarray) -> None:
        """Fit bucket boundaries for a single bucketed feature."""
        self._tokenizers[name].fit(values)

    def is_all_fitted(self) -> bool:
        return all(t.is_fitted for t in self._tokenizers.values())

    def encode_feature(self, name: str, values: np.ndarray) -> np.ndarray:
        """Encode raw values for one feature. Returns int16 token IDs."""
        return self._tokenizers[name].encode(values)

    def decode_feature(self, name: str, token_ids: np.ndarray) -> np.ndarray:
        """Decode token IDs for one feature. Returns float64 values."""
        return self._tokenizers[name].decode(token_ids)

    def inject_nulls(
        self, token_ids: np.ndarray, null_mask: np.ndarray
    ) -> np.ndarray:
        """Replace positions where null_mask is True with NULL token.

        Args:
            token_ids: int16 array of token IDs.
            null_mask: boolean array, same shape as token_ids.

        Returns:
            Copy of token_ids with NULLs injected.
        """
        result = token_ids.copy()
        result[null_mask] = NULL_TOKEN
        return result

    @property
    def oov_counts(self) -> dict[str, int]:
        return {name: t.oov_count for name, t in self._tokenizers.items()}

    def reset_oov_counts(self) -> None:
        for t in self._tokenizers.values():
            t.reset_oov_count()

    def get_state(self) -> dict[str, Any]:
        """Full tokenizer state for persistence and fingerprinting."""
        return {
            "num_features": self._schema.num_features,
            "num_transactions": self._schema.num_transactions,
            "features": [
                self._tokenizers[name].get_state()
                for name in self._schema.feature_names()
            ],
        }

    def save_state(self, path: str | Path) -> None:
        """Save tokenizer state to JSON for fingerprint computation (D4)."""
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        state = self.get_state()
        with open(path, "w") as fh:
            json.dump(state, fh, indent=2, sort_keys=True)

    @classmethod
    def from_state(cls, state_path: str | Path, schema: SchemaConfig) -> "TransactionTokenizer":
        """Reconstruct tokenizer from saved state."""
        with open(state_path) as fh:
            state = json.load(fh)

        tokenizer = cls(schema)
        for feat_state in state["features"]:
            name = feat_state["name"]
            ft = tokenizer._tokenizers[name]
            if "boundaries" in feat_state:
                ft._boundaries = np.array(feat_state["boundaries"], dtype=np.float64)
                ft._fitted = True
        return tokenizer

    def compute_fingerprint(self, *config_paths: str | Path) -> str:
        """SHA256 fingerprint of tokenizer state plus config files (D4).

        The fingerprint includes the tokenizer's bucket boundaries and vocab
        sizes, plus the raw bytes of any additional config files (schema,
        generator config, split indices). Eval refuses to run if fingerprints
        don't match.

        Args:
            config_paths: paths to config files to include in the hash.

        Returns:
            Hex-encoded SHA256 digest.
        """
        hasher = hashlib.sha256()

        state_bytes = json.dumps(self.get_state(), sort_keys=True).encode("utf-8")
        hasher.update(state_bytes)

        for path in sorted(str(p) for p in config_paths):
            with open(path, "rb") as fh:
                hasher.update(fh.read())

        return hasher.hexdigest()