ledgerfm 0.1.1__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.
- ledgerfm/__init__.py +20 -0
- ledgerfm/blend.py +51 -0
- ledgerfm/cli.py +36 -0
- ledgerfm/data.py +90 -0
- ledgerfm/hub.py +54 -0
- ledgerfm/infer.py +40 -0
- ledgerfm/metrics.py +50 -0
- ledgerfm/model.py +100 -0
- ledgerfm/tokens.py +126 -0
- ledgerfm-0.1.1.dist-info/METADATA +93 -0
- ledgerfm-0.1.1.dist-info/RECORD +15 -0
- ledgerfm-0.1.1.dist-info/WHEEL +5 -0
- ledgerfm-0.1.1.dist-info/entry_points.txt +2 -0
- ledgerfm-0.1.1.dist-info/licenses/LICENSE +202 -0
- ledgerfm-0.1.1.dist-info/top_level.txt +1 -0
ledgerfm/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""LedgerFM: open foundation model for transaction sequences (fraud / AML).
|
|
2
|
+
|
|
3
|
+
from ledgerfm import load, embed, Blend
|
|
4
|
+
"""
|
|
5
|
+
__version__ = "0.1.1"
|
|
6
|
+
|
|
7
|
+
from .blend import Blend
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def load(*a, **k):
|
|
11
|
+
from .hub import load as _load
|
|
12
|
+
return _load(*a, **k)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def embed(*a, **k):
|
|
16
|
+
from .hub import embed as _embed
|
|
17
|
+
return _embed(*a, **k)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
__all__ = ["load", "embed", "Blend", "__version__"]
|
ledgerfm/blend.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Blend a fine-tuned LedgerFM with an existing model (e.g. XGBoost); the weight is chosen on validation.
|
|
2
|
+
|
|
3
|
+
from ledgerfm import Blend
|
|
4
|
+
b = Blend().fit(y_val, p_fm_val, p_xgb_val) # probabilities in (0, 1)
|
|
5
|
+
p = b.predict(p_fm_new, p_xgb_new) # blended score (higher = riskier, not a probability)
|
|
6
|
+
b.w, b.curve # chosen weight on LedgerFM and val PR-AUC per weight
|
|
7
|
+
|
|
8
|
+
Each model's logit is standardised with its validation mean/std (fixed constants after fit), then
|
|
9
|
+
score = w * z_fm + (1 - w) * z_other. If LedgerFM adds nothing on your data, fit() picks w = 0.
|
|
10
|
+
"""
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _logit(p):
|
|
15
|
+
p = np.clip(np.asarray(p, np.float64), 1e-7, 1 - 1e-7)
|
|
16
|
+
return np.log(p / (1 - p))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _pr_auc(y, s):
|
|
20
|
+
"""Average precision (same definition as sklearn.metrics.average_precision_score)."""
|
|
21
|
+
y = np.asarray(y).astype(bool); o = np.argsort(-np.asarray(s), kind="mergesort")
|
|
22
|
+
y = y[o]; tp = np.cumsum(y); P = tp[-1]
|
|
23
|
+
if P == 0:
|
|
24
|
+
return float("nan")
|
|
25
|
+
s = np.asarray(s)[o]
|
|
26
|
+
last = np.r_[np.flatnonzero(np.diff(s)), len(s) - 1] # last index of each distinct score
|
|
27
|
+
prec = tp[last] / (last + 1); rec = tp[last] / P
|
|
28
|
+
return float(np.sum(np.diff(np.r_[0, rec]) * prec))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Blend:
|
|
32
|
+
def __init__(self, grid=None):
|
|
33
|
+
self.grid = grid if grid is not None else [round(x, 1) for x in np.linspace(0, 1, 11)]
|
|
34
|
+
self.w = None
|
|
35
|
+
|
|
36
|
+
def fit(self, y_val, p_fm, p_other):
|
|
37
|
+
lf, lo = _logit(p_fm), _logit(p_other)
|
|
38
|
+
self.norm_fm, self.norm_other = (lf.mean(), lf.std() or 1.0), (lo.mean(), lo.std() or 1.0)
|
|
39
|
+
zf, zo = self._z(lf, self.norm_fm), self._z(lo, self.norm_other)
|
|
40
|
+
self.curve = {w: _pr_auc(y_val, w * zf + (1 - w) * zo) for w in self.grid}
|
|
41
|
+
self.w = max(self.grid, key=lambda w: self.curve[w])
|
|
42
|
+
return self
|
|
43
|
+
|
|
44
|
+
@staticmethod
|
|
45
|
+
def _z(l, n):
|
|
46
|
+
return (l - n[0]) / n[1]
|
|
47
|
+
|
|
48
|
+
def predict(self, p_fm, p_other):
|
|
49
|
+
if self.w is None:
|
|
50
|
+
raise RuntimeError("call fit() on validation data first")
|
|
51
|
+
return self.w * self._z(_logit(p_fm), self.norm_fm) + (1 - self.w) * self._z(_logit(p_other), self.norm_other)
|
ledgerfm/cli.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Command line: ledgerfm embed transactions.parquet embeddings.parquet [--pca 32] [--model tripathyShaswata/LedgerFM]
|
|
2
|
+
|
|
3
|
+
Input: Parquet or CSV in the canonical schema (see README). Output: Parquet with txn_id + emb* columns.
|
|
4
|
+
--pca k reduces to k dimensions (PCA fitted on the input rows), the form that worked best as XGBoost features.
|
|
5
|
+
"""
|
|
6
|
+
import argparse, sys
|
|
7
|
+
import numpy as np, polars as pl
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _read(path):
|
|
11
|
+
return pl.read_csv(path, try_parse_dates=True) if str(path).lower().endswith(".csv") else pl.read_parquet(path)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main(argv=None):
|
|
15
|
+
ap = argparse.ArgumentParser(prog="ledgerfm")
|
|
16
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
17
|
+
e = sub.add_parser("embed", help="embed transactions with LedgerFM")
|
|
18
|
+
e.add_argument("input"); e.add_argument("output")
|
|
19
|
+
e.add_argument("--model", default="tripathyShaswata/LedgerFM")
|
|
20
|
+
e.add_argument("--pca", type=int, default=0); e.add_argument("--device", default=None)
|
|
21
|
+
a = ap.parse_args(argv)
|
|
22
|
+
from .hub import load, embed
|
|
23
|
+
df = _read(a.input)
|
|
24
|
+
E = embed(load(a.model, device=a.device), df)
|
|
25
|
+
if a.pca:
|
|
26
|
+
X = E.drop("txn_id").to_numpy().astype(np.float32); mu = X.mean(0)
|
|
27
|
+
_, _, Vt = np.linalg.svd(X[np.random.default_rng(0).choice(len(X), min(len(X), 200_000), replace=False)] - mu,
|
|
28
|
+
full_matrices=False)
|
|
29
|
+
Z = (X - mu) @ Vt[:a.pca].T
|
|
30
|
+
E = pl.DataFrame({"txn_id": E["txn_id"]}).with_columns([pl.Series(f"fm{j}", Z[:, j]) for j in range(a.pca)])
|
|
31
|
+
E.write_parquet(a.output)
|
|
32
|
+
print(f"wrote {E.height:,} rows x {E.width - 1} dims to {a.output}", file=sys.stderr)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
if __name__ == "__main__":
|
|
36
|
+
main()
|
ledgerfm/data.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Packed-sequence batches from data/tokens/<ds>.
|
|
2
|
+
|
|
3
|
+
A *chunk* is a contiguous slice of one account's time-ordered history (<= L rows).
|
|
4
|
+
Chunks are packed into rows of length L; each chunk gets its own segment id.
|
|
5
|
+
"""
|
|
6
|
+
import pathlib
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
|
11
|
+
TOK = ROOT / "data/tokens"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TokenStore:
|
|
15
|
+
def __init__(self, name):
|
|
16
|
+
d = TOK / name
|
|
17
|
+
self.name = name
|
|
18
|
+
self.ints = np.load(d / "ints.npy", mmap_mode="r")
|
|
19
|
+
self.floats = np.load(d / "floats.npy", mmap_mode="r")
|
|
20
|
+
self.label = np.load(d / "label.npy", mmap_mode="r")
|
|
21
|
+
self.split = np.load(d / "split.npy", mmap_mode="r")
|
|
22
|
+
self.txn_id = np.load(d / "txn_id.npy", mmap_mode="r")
|
|
23
|
+
self.offsets = np.load(d / "offsets.npy")
|
|
24
|
+
self.N = len(self.label)
|
|
25
|
+
|
|
26
|
+
def train_chunks(self, L, rng=None, lo=0, hi=0):
|
|
27
|
+
"""Chunks over each account's rows with lo <= split <= hi (split is time-monotone within an account,
|
|
28
|
+
so these rows are contiguous). Long histories start with a random-length first chunk so borders
|
|
29
|
+
move between epochs."""
|
|
30
|
+
s0, s1 = self.offsets[:-1], self.offsets[1:]
|
|
31
|
+
sp = np.asarray(self.split)
|
|
32
|
+
c_lo = np.r_[0, np.cumsum(sp < lo)]; c_in = np.r_[0, np.cumsum((sp >= lo) & (sp <= hi))]
|
|
33
|
+
first = s0 + (c_lo[s1] - c_lo[s0])
|
|
34
|
+
n_ok = c_in[s1] - c_in[s0]
|
|
35
|
+
starts, lens = [], []
|
|
36
|
+
for a, n in zip(first[n_ok > 0], n_ok[n_ok > 0]):
|
|
37
|
+
b = 0
|
|
38
|
+
if n > L:
|
|
39
|
+
b = int(rng.integers(1, L + 1)) if rng is not None else L
|
|
40
|
+
starts.append(a); lens.append(b)
|
|
41
|
+
while b < n:
|
|
42
|
+
e = min(n, b + L)
|
|
43
|
+
starts.append(a + b); lens.append(e - b); b = e
|
|
44
|
+
return np.array(starts, np.int64), np.array(lens, np.int64)
|
|
45
|
+
|
|
46
|
+
def eval_chunks(self, L):
|
|
47
|
+
"""Overlapping windows (stride L/2) so every scored row sees >= L/2 rows of history.
|
|
48
|
+
Returns starts, lens, score_from (offset inside chunk from which rows are scored)."""
|
|
49
|
+
H = L // 2
|
|
50
|
+
st, ln, sf = [], [], []
|
|
51
|
+
for a, b in zip(self.offsets[:-1], self.offsets[1:]):
|
|
52
|
+
n = b - a
|
|
53
|
+
s = 0
|
|
54
|
+
while True:
|
|
55
|
+
e = min(n, s + L)
|
|
56
|
+
st.append(a + s); ln.append(e - s); sf.append(0 if s == 0 else H)
|
|
57
|
+
if e == n:
|
|
58
|
+
break
|
|
59
|
+
s += H
|
|
60
|
+
return np.array(st, np.int64), np.array(ln, np.int64), np.array(sf, np.int64)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def pack(lens, L, order):
|
|
64
|
+
"""Greedy sequential packing. Returns list of rows, each a list of chunk indices."""
|
|
65
|
+
rows, cur, used = [], [], 0
|
|
66
|
+
for i in order:
|
|
67
|
+
if used + lens[i] > L and cur:
|
|
68
|
+
rows.append(cur); cur, used = [], 0
|
|
69
|
+
cur.append(i); used += lens[i]
|
|
70
|
+
if cur:
|
|
71
|
+
rows.append(cur)
|
|
72
|
+
return rows
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def make_batch(store, starts, lens, rows, L, extra=None):
|
|
76
|
+
"""rows: list of lists of chunk ids. Returns tensors (ints, floats, seg, pos, idx) with idx=-1 for padding."""
|
|
77
|
+
B = len(rows)
|
|
78
|
+
idx = np.full((B, L), -1, np.int64); seg = np.zeros((B, L), np.int64); pos = np.zeros((B, L), np.int64)
|
|
79
|
+
for r, chunks in enumerate(rows):
|
|
80
|
+
c = 0
|
|
81
|
+
for s_id, ch in enumerate(chunks, 1):
|
|
82
|
+
n = lens[ch]
|
|
83
|
+
idx[r, c:c + n] = np.arange(starts[ch], starts[ch] + n)
|
|
84
|
+
seg[r, c:c + n] = s_id; pos[r, c:c + n] = np.arange(n); c += n
|
|
85
|
+
flat = idx.reshape(-1); ok = flat >= 0
|
|
86
|
+
ints = np.zeros((B * L, store.ints.shape[1]), np.int64); fl = np.zeros((B * L, store.floats.shape[1]), np.float32)
|
|
87
|
+
sel = np.sort(flat[ok]); inv = np.searchsorted(sel, flat[ok])
|
|
88
|
+
ints[ok] = np.asarray(store.ints[sel], np.int64)[inv]; fl[ok] = np.asarray(store.floats[sel], np.float32)[inv]
|
|
89
|
+
t = lambda a: torch.from_numpy(a)
|
|
90
|
+
return t(ints.reshape(B, L, -1)), t(fl.reshape(B, L, -1)), t(seg), t(pos), t(idx)
|
ledgerfm/hub.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Load released LedgerFM weights and embed transactions given as a polars DataFrame.
|
|
2
|
+
|
|
3
|
+
from ledgerfm.hub import load, embed
|
|
4
|
+
fm = load("tripathyShaswata/LedgerFM") # or a local folder with model.safetensors + config.json
|
|
5
|
+
E = embed(fm, df) # df in the canonical schema (see README) -> polars frame
|
|
6
|
+
|
|
7
|
+
Each output row is the embedding of one transaction given its own fields and the sender's earlier history.
|
|
8
|
+
"""
|
|
9
|
+
import json, pathlib
|
|
10
|
+
import numpy as np, polars as pl, torch
|
|
11
|
+
|
|
12
|
+
from .model import LedgerFM, Config
|
|
13
|
+
from .tokens import context_columns, tokenize
|
|
14
|
+
from .infer import run_rows
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def load(repo_or_dir="tripathyShaswata/LedgerFM", device=None):
|
|
18
|
+
p = pathlib.Path(repo_or_dir)
|
|
19
|
+
if not p.exists():
|
|
20
|
+
from huggingface_hub import snapshot_download
|
|
21
|
+
p = pathlib.Path(snapshot_download(repo_or_dir, allow_patterns=["model.safetensors", "config.json"]))
|
|
22
|
+
from safetensors.torch import load_file
|
|
23
|
+
fm = LedgerFM(Config(**json.load(open(p / "config.json"))["cfg"]))
|
|
24
|
+
fm.load_state_dict(load_file(p / "model.safetensors"))
|
|
25
|
+
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
|
26
|
+
return fm.to(device).eval()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _Store:
|
|
30
|
+
"""In-memory stand-in for data.TokenStore (rows grouped by account, time-ordered)."""
|
|
31
|
+
def __init__(self, ints, floats, account):
|
|
32
|
+
self.ints, self.floats = ints.astype(np.int64), floats.astype(np.float32)
|
|
33
|
+
self.N = len(ints); self.split = np.zeros(self.N, np.int8)
|
|
34
|
+
starts = np.flatnonzero(np.r_[True, account[1:] != account[:-1]])
|
|
35
|
+
self.offsets = np.r_[starts, self.N].astype(np.int64)
|
|
36
|
+
|
|
37
|
+
from .data import TokenStore as _T
|
|
38
|
+
eval_chunks = _T.eval_chunks
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def embed(fm, df: pl.DataFrame, bs=64) -> pl.DataFrame:
|
|
42
|
+
"""df: canonical rows (txn_id, ts, account, counterparty, amount, currency, ... see README).
|
|
43
|
+
Returns txn_id + emb0..emb{d-1} (float32), one row per input transaction."""
|
|
44
|
+
ctx = context_columns(df)
|
|
45
|
+
ints, fl = tokenize(ctx)
|
|
46
|
+
st = _Store(ints, fl, ctx["account"].to_numpy())
|
|
47
|
+
H = np.full((st.N, fm.c.d), np.nan, np.float32)
|
|
48
|
+
dev = next(fm.parameters()).device.type
|
|
49
|
+
|
|
50
|
+
def fn(h, idx):
|
|
51
|
+
H[idx] = h.cpu().numpy()
|
|
52
|
+
run_rows(fm, st, fm.c.max_len, {0}, fn, bs=bs, device=dev)
|
|
53
|
+
return pl.DataFrame({"txn_id": ctx["txn_id"]}).with_columns(
|
|
54
|
+
[pl.Series(f"emb{j}", H[:, j]) for j in range(fm.c.d)])
|
ledgerfm/infer.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Inference over every row of a TokenStore with full causal history (overlapping windows)."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
import torch
|
|
4
|
+
from .data import pack, make_batch
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def scored_windows(store, L, splits):
|
|
8
|
+
"""Eval windows whose scored part contains rows from `splits`. Returns starts, lens, score_from."""
|
|
9
|
+
st, ln, sf = store.eval_chunks(L)
|
|
10
|
+
sp = np.isin(np.asarray(store.split), list(splits))
|
|
11
|
+
cum = np.r_[0, np.cumsum(sp)]
|
|
12
|
+
keep = (cum[st + ln] - cum[st + sf]) > 0
|
|
13
|
+
return st[keep], ln[keep], sf[keep]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@torch.no_grad()
|
|
17
|
+
def run_rows(model, store, L, splits, fn, bs=128, device="cuda"):
|
|
18
|
+
"""Call fn(h [n,d] tensor, row_idx [n] numpy) for every row in `splits`, each scored exactly once."""
|
|
19
|
+
st, ln, sf = scored_windows(store, L, splits)
|
|
20
|
+
rows = pack(ln, L, np.arange(len(st)))
|
|
21
|
+
sp = np.asarray(store.split); want = np.isin(sp, list(splits))
|
|
22
|
+
model.eval()
|
|
23
|
+
for i in range(0, len(rows), bs):
|
|
24
|
+
r = rows[i:i + bs]
|
|
25
|
+
ints, fl, seg, pos, idx = make_batch(store, st, ln, r, L)
|
|
26
|
+
# mark which positions are scored: pos >= score_from of its chunk
|
|
27
|
+
sfrom = np.zeros(idx.shape, np.int64)
|
|
28
|
+
for b, chunks in enumerate(r):
|
|
29
|
+
c = 0
|
|
30
|
+
for ch in chunks:
|
|
31
|
+
sfrom[b, c:c + ln[ch]] = sf[ch]; c += ln[ch]
|
|
32
|
+
idx_np = idx.numpy()
|
|
33
|
+
m = (idx_np >= 0) & (pos.numpy() >= sfrom)
|
|
34
|
+
m[m] &= want[idx_np[m]]
|
|
35
|
+
if not m.any():
|
|
36
|
+
continue
|
|
37
|
+
with torch.autocast(device, dtype=torch.bfloat16):
|
|
38
|
+
h = model.encode(ints.to(device), fl.to(device), seg.to(device), pos.to(device))
|
|
39
|
+
mt = torch.from_numpy(m).to(device)
|
|
40
|
+
fn(h[mt].float(), idx_np[m])
|
ledgerfm/metrics.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Shared evaluation metrics (fixed before any test run)."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from sklearn.metrics import average_precision_score, roc_auc_score, roc_curve, precision_recall_curve
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def recall_at_fpr(y, s, fpr_target):
|
|
7
|
+
fpr, tpr, _ = roc_curve(y, s)
|
|
8
|
+
return float(np.interp(fpr_target, fpr, tpr))
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def best_f1_threshold(y, s):
|
|
12
|
+
p, r, t = precision_recall_curve(y, s)
|
|
13
|
+
f1 = 2 * p * r / np.clip(p + r, 1e-12, None)
|
|
14
|
+
i = int(np.nanargmax(f1[:-1]))
|
|
15
|
+
return float(t[i]), float(f1[i])
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def f1_at(y, s, thr):
|
|
19
|
+
pred = s >= thr
|
|
20
|
+
tp = float((pred & (y == 1)).sum()); fp = float((pred & (y == 0)).sum()); fn = float((~pred & (y == 1)).sum())
|
|
21
|
+
return 2 * tp / max(2 * tp + fp + fn, 1)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def evaluate(y, s, thr=None):
|
|
25
|
+
"""PR-AUC is primary. If thr is None, F1 uses the best threshold on this set (only allowed on val)."""
|
|
26
|
+
y = np.asarray(y).astype(int); s = np.asarray(s, dtype=float)
|
|
27
|
+
out = {
|
|
28
|
+
"n": int(len(y)), "pos": int(y.sum()),
|
|
29
|
+
"pr_auc": float(average_precision_score(y, s)),
|
|
30
|
+
"roc_auc": float(roc_auc_score(y, s)),
|
|
31
|
+
"rec@0.1%fpr": recall_at_fpr(y, s, 0.001),
|
|
32
|
+
"rec@1%fpr": recall_at_fpr(y, s, 0.01),
|
|
33
|
+
}
|
|
34
|
+
if thr is None:
|
|
35
|
+
thr, f1 = best_f1_threshold(y, s)
|
|
36
|
+
out.update(f1=f1, thr=thr)
|
|
37
|
+
else:
|
|
38
|
+
out.update(f1=f1_at(y, s, thr), thr=thr)
|
|
39
|
+
return out
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def label_keep(txn_id, frac, seed=0):
|
|
43
|
+
"""Low-label regime: deterministic subset of labelled training rows, shared by every model.
|
|
44
|
+
splitmix64 hash of txn_id; keeps rows with hash % 1000 < frac*1000."""
|
|
45
|
+
x = (np.asarray(txn_id, dtype=np.uint64) + np.uint64(0x9E3779B97F4A7C15) * np.uint64(seed + 1))
|
|
46
|
+
with np.errstate(over="ignore"):
|
|
47
|
+
x = (x ^ (x >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
|
|
48
|
+
x = (x ^ (x >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
|
|
49
|
+
x = x ^ (x >> np.uint64(31))
|
|
50
|
+
return (x % np.uint64(1000)) < np.uint64(int(round(frac * 1000)))
|
ledgerfm/model.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""LedgerFM encoder: field-embedding transaction tokens -> causal transformer over an account's history.
|
|
2
|
+
|
|
3
|
+
Several accounts can be packed into one row; attention is causal *within* a segment only.
|
|
4
|
+
Output at position t = embedding of transaction t given its own fields and the account's past.
|
|
5
|
+
"""
|
|
6
|
+
import math
|
|
7
|
+
import torch, torch.nn as nn, torch.nn.functional as F
|
|
8
|
+
from .tokens import INT_FIELDS, FLOAT_FIELDS, MASK_TARGETS, NEXT_TARGETS
|
|
9
|
+
|
|
10
|
+
FIELDS = list(INT_FIELDS)
|
|
11
|
+
FIDX = {k: i for i, k in enumerate(FIELDS)}
|
|
12
|
+
FLIDX = {k: i for i, k in enumerate(FLOAT_FIELDS)}
|
|
13
|
+
# float columns that would leak a masked int field
|
|
14
|
+
MASK_FLOAT_LEAK = {"amt_b": ["lamt", "s_dev"], "hour": ["hsin", "hcos"]}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Config:
|
|
18
|
+
def __init__(self, d=256, layers=6, heads=8, ff=4, max_len=128, dropout=0.1):
|
|
19
|
+
self.d, self.layers, self.heads, self.ff, self.max_len, self.dropout = d, layers, heads, ff, max_len, dropout
|
|
20
|
+
|
|
21
|
+
def to_dict(self):
|
|
22
|
+
return dict(vars(self))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Block(nn.Module):
|
|
26
|
+
def __init__(self, c):
|
|
27
|
+
super().__init__()
|
|
28
|
+
self.ln1, self.ln2 = nn.LayerNorm(c.d), nn.LayerNorm(c.d)
|
|
29
|
+
self.qkv, self.proj = nn.Linear(c.d, 3 * c.d), nn.Linear(c.d, c.d)
|
|
30
|
+
self.ff = nn.Sequential(nn.Linear(c.d, c.ff * c.d), nn.GELU(), nn.Linear(c.ff * c.d, c.d))
|
|
31
|
+
self.h, self.drop = c.heads, c.dropout
|
|
32
|
+
|
|
33
|
+
def forward(self, x, mask):
|
|
34
|
+
B, L, D = x.shape
|
|
35
|
+
q, k, v = self.qkv(self.ln1(x)).view(B, L, 3, self.h, D // self.h).permute(2, 0, 3, 1, 4)
|
|
36
|
+
a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=self.drop if self.training else 0.0)
|
|
37
|
+
x = x + F.dropout(self.proj(a.transpose(1, 2).reshape(B, L, D)), self.drop, self.training)
|
|
38
|
+
return x + F.dropout(self.ff(self.ln2(x)), self.drop, self.training)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class LedgerFM(nn.Module):
|
|
42
|
+
def __init__(self, c: Config):
|
|
43
|
+
super().__init__()
|
|
44
|
+
self.c = c
|
|
45
|
+
self.emb = nn.ModuleDict({k: nn.Embedding(v, c.d) for k, v in INT_FIELDS.items()})
|
|
46
|
+
self.flt = nn.Linear(len(FLOAT_FIELDS), c.d)
|
|
47
|
+
self.pos = nn.Embedding(c.max_len, c.d)
|
|
48
|
+
self.blocks = nn.ModuleList(Block(c) for _ in range(c.layers))
|
|
49
|
+
self.ln = nn.LayerNorm(c.d)
|
|
50
|
+
self.mask_heads = nn.ModuleDict({k: nn.Linear(c.d, INT_FIELDS[k]) for k in MASK_TARGETS})
|
|
51
|
+
self.next_heads = nn.ModuleDict({k: nn.Linear(c.d, INT_FIELDS[k]) for k in NEXT_TARGETS})
|
|
52
|
+
self.apply(self._init)
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def _init(m):
|
|
56
|
+
if isinstance(m, (nn.Linear, nn.Embedding)):
|
|
57
|
+
nn.init.normal_(m.weight, std=0.02)
|
|
58
|
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
|
59
|
+
nn.init.zeros_(m.bias)
|
|
60
|
+
|
|
61
|
+
def encode(self, ints, floats, seg, pos):
|
|
62
|
+
"""ints [B,L,Fi] long, floats [B,L,Ff], seg [B,L] (0 = padding), pos [B,L]. Returns [B,L,d]."""
|
|
63
|
+
x = sum(self.emb[k](ints[..., i]) for i, k in enumerate(FIELDS)) + self.flt(floats) + self.pos(pos)
|
|
64
|
+
L = ints.shape[1]
|
|
65
|
+
causal = torch.ones(L, L, dtype=torch.bool, device=ints.device).tril()
|
|
66
|
+
same = (seg[:, :, None] == seg[:, None, :]) & (seg[:, :, None] > 0)
|
|
67
|
+
mask = (same & causal)[:, None]
|
|
68
|
+
mask = mask | torch.eye(L, dtype=torch.bool, device=ints.device) # padding rows attend to self (no NaN)
|
|
69
|
+
for b in self.blocks:
|
|
70
|
+
x = b(x, mask)
|
|
71
|
+
return self.ln(x)
|
|
72
|
+
|
|
73
|
+
def pretrain_loss(self, ints, floats, seg, pos, p_mask=0.15):
|
|
74
|
+
"""Masked-field + next-transaction losses. Returns total, dict of parts."""
|
|
75
|
+
valid = seg > 0
|
|
76
|
+
m = (torch.rand(ints.shape[:2] + (len(MASK_TARGETS),), device=ints.device) < p_mask) & valid[..., None]
|
|
77
|
+
ints_in, fl_in = ints.clone(), floats.clone()
|
|
78
|
+
for j, k in enumerate(MASK_TARGETS):
|
|
79
|
+
ints_in[..., FIDX[k]] = ints_in[..., FIDX[k]].masked_fill(m[..., j], 0)
|
|
80
|
+
for fk in MASK_FLOAT_LEAK.get(k, []):
|
|
81
|
+
fl_in[..., FLIDX[fk]] = fl_in[..., FLIDX[fk]].masked_fill(m[..., j], 0)
|
|
82
|
+
h = self.encode(ints_in, fl_in, seg, pos)
|
|
83
|
+
parts = {}
|
|
84
|
+
for j, k in enumerate(MASK_TARGETS):
|
|
85
|
+
tgt = ints[..., FIDX[k]]
|
|
86
|
+
sel = m[..., j] & (tgt > 0)
|
|
87
|
+
if sel.any():
|
|
88
|
+
parts[f"m_{k}"] = F.cross_entropy(self.mask_heads[k](h[sel]).float(), tgt[sel])
|
|
89
|
+
nxt = valid[:, :-1] & (seg[:, 1:] == seg[:, :-1])
|
|
90
|
+
hn = h[:, :-1][nxt]
|
|
91
|
+
for k in NEXT_TARGETS:
|
|
92
|
+
tgt = ints[:, 1:, FIDX[k]][nxt]
|
|
93
|
+
ok = (tgt > 0) if k != "flags" else torch.ones_like(tgt, dtype=torch.bool)
|
|
94
|
+
if ok.any():
|
|
95
|
+
parts[f"n_{k}"] = F.cross_entropy(self.next_heads[k](hn[ok]).float(), tgt[ok])
|
|
96
|
+
return sum(parts.values()) / max(len(parts), 1), parts
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def n_params(m):
|
|
100
|
+
return sum(p.numel() for p in m.parameters())
|
ledgerfm/tokens.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Canonical rows -> LedgerFM transaction tokens.
|
|
2
|
+
|
|
3
|
+
Each transaction becomes
|
|
4
|
+
ints [N, len(INT_FIELDS)] categorical codes (stable md5 hashing, fixed transforms)
|
|
5
|
+
floats [N, len(FLOAT_FIELDS)] continuous values with fixed (dataset-free) scaling
|
|
6
|
+
The transforms use no dataset statistics, so the same code tokenises any new institution's data.
|
|
7
|
+
Needs per-row causal context columns; `context_columns(df)` computes them from canonical rows.
|
|
8
|
+
"""
|
|
9
|
+
import hashlib
|
|
10
|
+
import numpy as np
|
|
11
|
+
import polars as pl
|
|
12
|
+
|
|
13
|
+
# field name -> vocabulary size (code 0 is reserved for missing / masked)
|
|
14
|
+
INT_FIELDS = {
|
|
15
|
+
"amt_b": 64, "gap_b": 32, "hour": 25, "wday": 8,
|
|
16
|
+
"category": 4096, "channel": 512, "location": 2048, "currency": 256, "currency_recv": 256,
|
|
17
|
+
"errors": 256, "cp": 32768, "flags": 64, "r_n_b": 32, "r_gap_b": 32,
|
|
18
|
+
}
|
|
19
|
+
FLOAT_FIELDS = ["lamt", "lgap", "r_lnprev", "r_lcnt24", "r_mlamt", "r_has", "s_dev", "s_lcnt24",
|
|
20
|
+
"hsin", "hcos", "dsin", "dcos"]
|
|
21
|
+
# pretraining targets: masked-field and next-transaction heads predict these
|
|
22
|
+
MASK_TARGETS = ["amt_b", "category", "channel", "location", "currency", "cp", "hour"]
|
|
23
|
+
NEXT_TARGETS = ["amt_b", "category", "channel", "gap_b", "flags"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# currency names -> ISO 4217 (anything else is upper-cased and kept)
|
|
27
|
+
ISO = {"US Dollar": "USD", "Euro": "EUR", "Swiss Franc": "CHF", "Yuan": "CNY", "Shekel": "ILS", "Rupee": "INR",
|
|
28
|
+
"UK Pound": "GBP", "Yen": "JPY", "Ruble": "RUB", "Bitcoin": "BTC", "Canadian Dollar": "CAD",
|
|
29
|
+
"Australian Dollar": "AUD", "Mexican Peso": "MXN", "Saudi Riyal": "SAR", "Brazil Real": "BRL"}
|
|
30
|
+
# fixed approximate USD per unit (about 2020-21 levels; consistent with the IBM AML generator).
|
|
31
|
+
# Only used to put amounts on one scale; unknown currencies count as 1.
|
|
32
|
+
USD_RATE = {"USD": 1.0, "EUR": 1.17, "CHF": 1.09, "CNY": 0.149, "ILS": 0.296, "INR": 0.0136, "GBP": 1.29,
|
|
33
|
+
"JPY": 0.0095, "RUB": 0.0129, "BTC": 11900.0, "CAD": 0.758, "AUD": 0.708, "MXN": 0.0473,
|
|
34
|
+
"SAR": 0.267, "BRL": 0.177}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def normalise_currency(s: pl.Series) -> pl.Series:
|
|
38
|
+
s = s.cast(pl.String)
|
|
39
|
+
return s.replace(ISO).str.to_uppercase()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def stable_hash(s: pl.Series, buckets: int, salt: str) -> np.ndarray:
|
|
43
|
+
"""md5-based hash into [1, buckets-1]; 0 = null. Stable across machines and library versions."""
|
|
44
|
+
s = s.cast(pl.String)
|
|
45
|
+
uniq = s.drop_nulls().unique()
|
|
46
|
+
codes = np.fromiter((int.from_bytes(hashlib.md5((salt + v).encode()).digest()[:8], "little") % (buckets - 1) + 1
|
|
47
|
+
for v in uniq), dtype=np.int64, count=len(uniq))
|
|
48
|
+
m = pl.DataFrame({"v": uniq, "c": codes})
|
|
49
|
+
return (pl.DataFrame({"v": s}).join(m, on="v", how="left", maintain_order="left")["c"]
|
|
50
|
+
.fill_null(0).to_numpy().astype(np.int32))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def context_columns(df: pl.DataFrame) -> pl.DataFrame:
|
|
54
|
+
"""Causal per-row context from canonical rows (any order). Returns rows sorted by (account, ts, txn_id)."""
|
|
55
|
+
rate = normalise_currency(df["currency"]).replace_strict(USD_RATE, default=1.0, return_dtype=pl.Float64)
|
|
56
|
+
df = df.with_columns((pl.col("amount") * rate).alias("amount_usd"))
|
|
57
|
+
la = pl.col("amount_usd").abs().log1p()
|
|
58
|
+
one = pl.col("amount_usd").is_not_null().cast(pl.Int32)
|
|
59
|
+
rc = df.sort("counterparty", "ts", "txn_id").select(
|
|
60
|
+
"txn_id",
|
|
61
|
+
pl.int_range(pl.len()).over("counterparty").alias("r_n_prev"),
|
|
62
|
+
pl.col("ts").diff().over("counterparty").dt.total_seconds().alias("r_gap_s"),
|
|
63
|
+
((la.cum_sum().over("counterparty") - la) / pl.int_range(pl.len()).over("counterparty")).alias("r_mean_lamt_prev"),
|
|
64
|
+
one.rolling_sum_by("ts", window_size="24h").over("counterparty").alias("r_cnt_24h"),
|
|
65
|
+
)
|
|
66
|
+
df = df.sort("account", "ts", "txn_id")
|
|
67
|
+
df = df.with_columns(
|
|
68
|
+
pl.col("ts").diff().over("account").dt.total_seconds().alias("s_gap_s"),
|
|
69
|
+
((la.cum_sum().over("account") - la) / pl.int_range(pl.len()).over("account")).alias("s_mean_lamt_prev"),
|
|
70
|
+
one.rolling_sum_by("ts", window_size="24h").over("account").alias("s_cnt_24h"),
|
|
71
|
+
)
|
|
72
|
+
npair = df.sort("account", "counterparty", "ts", "txn_id").select(
|
|
73
|
+
"txn_id", (pl.int_range(pl.len()).over("account", "counterparty") == 0).cast(pl.Int8).alias("new_pair"))
|
|
74
|
+
df = df.join(npair, on="txn_id", maintain_order="left").join(rc, on="txn_id", maintain_order="left")
|
|
75
|
+
return df
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _logb(x, scale, n):
|
|
79
|
+
"""log bucket: 0 = missing, 1.. = floor(log1p(x)*scale)+1 clipped."""
|
|
80
|
+
v = np.floor(np.log1p(np.clip(np.nan_to_num(x, nan=-1), 0, None)) * scale).astype(np.int64) + 1
|
|
81
|
+
v = np.clip(v, 1, n - 1)
|
|
82
|
+
return np.where(np.isnan(x), 0, v).astype(np.int32)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def tokenize(df: pl.DataFrame):
|
|
86
|
+
"""df must come from context_columns(). Returns ints [N,F_int] int32, floats [N,F_float] float32."""
|
|
87
|
+
N = df.height
|
|
88
|
+
f = lambda c: df[c].cast(pl.Float64).to_numpy()
|
|
89
|
+
ccy, ccyr = normalise_currency(df["currency"]), normalise_currency(df["currency_recv"])
|
|
90
|
+
amt = f("amount_usd")
|
|
91
|
+
lamt = np.log1p(np.abs(amt))
|
|
92
|
+
gap = f("s_gap_s"); rgap = f("r_gap_s"); rn = f("r_n_prev")
|
|
93
|
+
hour = df["ts"].dt.hour().to_numpy().astype(np.int32); wday = df["ts"].dt.weekday().to_numpy().astype(np.int32)
|
|
94
|
+
flags = (
|
|
95
|
+
(amt < 0).astype(np.int32)
|
|
96
|
+
| (df["account"] == df["counterparty"]).fill_null(False).to_numpy().astype(np.int32) << 1
|
|
97
|
+
| ((ccyr.is_not_null()) & (ccy != ccyr)).fill_null(False).to_numpy().astype(np.int32) << 2
|
|
98
|
+
| (df["src_bank"] != df["dst_bank"]).fill_null(False).to_numpy().astype(np.int32) << 3
|
|
99
|
+
| ((np.abs(amt) % 1) == 0).astype(np.int32) << 4
|
|
100
|
+
| df["new_pair"].cast(pl.Int32).to_numpy() << 5
|
|
101
|
+
)
|
|
102
|
+
ints = np.zeros((N, len(INT_FIELDS)), np.int32)
|
|
103
|
+
col = {k: i for i, k in enumerate(INT_FIELDS)}
|
|
104
|
+
ints[:, col["amt_b"]] = np.clip(np.floor(lamt * 4).astype(np.int64) + 1, 1, 63)
|
|
105
|
+
ints[:, col["gap_b"]] = _logb(gap, 2.0, 32)
|
|
106
|
+
ints[:, col["hour"]] = hour + 1
|
|
107
|
+
ints[:, col["wday"]] = wday # polars weekday is 1..7
|
|
108
|
+
for k in ("category", "channel", "location", "errors"):
|
|
109
|
+
ints[:, col[k]] = stable_hash(df[k], INT_FIELDS[k], k)
|
|
110
|
+
ints[:, col["currency"]] = stable_hash(ccy, INT_FIELDS["currency"], "currency")
|
|
111
|
+
ints[:, col["currency_recv"]] = stable_hash(ccyr, INT_FIELDS["currency_recv"], "currency")
|
|
112
|
+
ints[:, col["cp"]] = stable_hash(df["counterparty"], INT_FIELDS["cp"], "cp")
|
|
113
|
+
ints[:, col["flags"]] = flags # 6 bits, 0..63 all valid
|
|
114
|
+
ints[:, col["r_n_b"]] = _logb(rn, 2.0, 32)
|
|
115
|
+
ints[:, col["r_gap_b"]] = _logb(rgap, 2.0, 32)
|
|
116
|
+
|
|
117
|
+
rm = f("r_mean_lamt_prev"); sm = f("s_mean_lamt_prev")
|
|
118
|
+
fl = np.stack([
|
|
119
|
+
lamt / 10, np.log1p(np.nan_to_num(np.clip(gap, 0, None), nan=0)) / 15,
|
|
120
|
+
np.log1p(rn) / 10, np.log1p(f("r_cnt_24h")) / 7,
|
|
121
|
+
np.nan_to_num(rm, nan=0) / 10, (~np.isnan(rm)).astype(float),
|
|
122
|
+
np.nan_to_num(lamt - sm, nan=0) / 5, np.log1p(f("s_cnt_24h")) / 7,
|
|
123
|
+
np.sin(2 * np.pi * hour / 24), np.cos(2 * np.pi * hour / 24),
|
|
124
|
+
np.sin(2 * np.pi * wday / 7), np.cos(2 * np.pi * wday / 7),
|
|
125
|
+
], 1).astype(np.float32)
|
|
126
|
+
return ints, np.nan_to_num(fl)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ledgerfm
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Open foundation model for transaction sequences (fraud / anti-money-laundering)
|
|
5
|
+
Author: Shaswata Tripathy
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/ShaswataTripathy/LedgerFM
|
|
8
|
+
Project-URL: Model, https://huggingface.co/tripathyShaswata/LedgerFM
|
|
9
|
+
Project-URL: Issues, https://github.com/ShaswataTripathy/LedgerFM/issues
|
|
10
|
+
Keywords: fraud-detection,anti-money-laundering,aml,transactions,foundation-model,embeddings
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: torch>=2.4
|
|
20
|
+
Requires-Dist: polars>=1.0
|
|
21
|
+
Requires-Dist: numpy>=1.26
|
|
22
|
+
Requires-Dist: safetensors>=0.4
|
|
23
|
+
Requires-Dist: huggingface_hub>=0.24
|
|
24
|
+
Provides-Extra: train
|
|
25
|
+
Requires-Dist: xgboost>=2.0; extra == "train"
|
|
26
|
+
Requires-Dist: scikit-learn>=1.4; extra == "train"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# ledgerfm
|
|
30
|
+
|
|
31
|
+
An open foundation model for **transaction sequences**, for fraud detection and anti-money-laundering (AML).
|
|
32
|
+
|
|
33
|
+
LedgerFM reads an account's transaction history and returns a 256-dimensional embedding for every transaction. Use the embeddings as extra features, fine-tune the model, or blend its scores with the XGBoost model you already run.
|
|
34
|
+
|
|
35
|
+
- Weights (Apache-2.0, 26.6M parameters) on Hugging Face: https://huggingface.co/tripathyShaswata/LedgerFM
|
|
36
|
+
- Code, training pipeline and every result: https://github.com/ShaswataTripathy/LedgerFM
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install ledgerfm
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Embed transactions
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import polars as pl
|
|
46
|
+
from ledgerfm import load, embed
|
|
47
|
+
|
|
48
|
+
fm = load() # downloads the v0.1 weights from Hugging Face once
|
|
49
|
+
df = pl.read_parquet("transactions.parquet")
|
|
50
|
+
E = embed(fm, df) # txn_id, emb0 .. emb255
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Or from the command line, reducing to 32 dimensions for use as XGBoost features:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
ledgerfm embed transactions.parquet embeddings.parquet --pca 32
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Input columns
|
|
60
|
+
|
|
61
|
+
| column | type | |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| `txn_id` | int | unique id |
|
|
64
|
+
| `ts` | datetime | transaction time |
|
|
65
|
+
| `account` | str | sender / card / customer (the model reads this account's history) |
|
|
66
|
+
| `counterparty` | str | receiver / merchant |
|
|
67
|
+
| `amount`, `currency` | float, str | |
|
|
68
|
+
| `amount_recv`, `currency_recv`, `category`, `channel`, `location`, `instrument`, `src_bank`, `dst_bank`, `errors` | optional | may be null |
|
|
69
|
+
|
|
70
|
+
The tokenizer uses no dataset statistics, so you don't need to refit anything for your own data.
|
|
71
|
+
|
|
72
|
+
## Blend with your existing model
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from ledgerfm import Blend
|
|
76
|
+
b = Blend().fit(y_val, p_ledgerfm_val, p_xgb_val) # picks the weight on validation
|
|
77
|
+
score = b.predict(p_ledgerfm_new, p_xgb_new)
|
|
78
|
+
print(b.w, b.curve)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
If LedgerFM adds nothing on your data, the blend picks weight 0 and you keep your XGBoost result.
|
|
82
|
+
|
|
83
|
+
## How good is it?
|
|
84
|
+
|
|
85
|
+
On a simulated banking world the model never saw (IBM AML HI-Large, 22.6M transactions), test PR-AUC with full labels:
|
|
86
|
+
|
|
87
|
+
| model | test PR-AUC |
|
|
88
|
+
|---|---|
|
|
89
|
+
| XGBoost | 0.289 |
|
|
90
|
+
| LedgerFM v0.1, fine-tuned | 0.332 |
|
|
91
|
+
| blend of the two | 0.338 |
|
|
92
|
+
|
|
93
|
+
Limits: it was trained mostly on synthetic data; XGBoost wins on short account histories and with few labels. Full results and limitations are in the [GitHub README](https://github.com/ShaswataTripathy/LedgerFM).
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ledgerfm/__init__.py,sha256=VYevDHbeURg8Rml8NgoqNq-xz9p3njxbY5TF-6E2OXQ,395
|
|
2
|
+
ledgerfm/blend.py,sha256=duEAXiGM723_cHddh0C_c_Hn6dC4iX3snDZkhwqJP9E,2181
|
|
3
|
+
ledgerfm/cli.py,sha256=0WCZFXMjqEvlqscZgz45Ll1qtQzXFrwu4fP8Zg1VNik,1651
|
|
4
|
+
ledgerfm/data.py,sha256=3d_vVj9Q_OFcC432SyUWLGiei8iRXeosAvPGlfDimtA,3979
|
|
5
|
+
ledgerfm/hub.py,sha256=eGZA5omzOKWLEph7BuOjnLN14_v3tUKoSuCriqlH8rs,2398
|
|
6
|
+
ledgerfm/infer.py,sha256=uoHxkD7qef3Ev-FtcbOP1oFOkuTbz_DFVQqHsOVVo0M,1676
|
|
7
|
+
ledgerfm/metrics.py,sha256=_g3b2SQXDRqhwBDFdkyDPyI5412VWNk3T8LtRvhkgzk,1944
|
|
8
|
+
ledgerfm/model.py,sha256=0sI3OjrGYkJT-lFakBzXEuqB7TOmkxoYVGN04TK1-bg,4734
|
|
9
|
+
ledgerfm/tokens.py,sha256=XB3lyqbpLTV4kFA43XApiCvxFwABprupIwUSqW172hg,7143
|
|
10
|
+
ledgerfm-0.1.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
11
|
+
ledgerfm-0.1.1.dist-info/METADATA,sha256=6jlkeKJ0mECigQBnEQipQDMgqpql5tDJoyH69l0E6qk,3620
|
|
12
|
+
ledgerfm-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
ledgerfm-0.1.1.dist-info/entry_points.txt,sha256=NQU2OgTSMCwTBTpZgGf0i0R2hko042vQ9obpQ2ui3lU,47
|
|
14
|
+
ledgerfm-0.1.1.dist-info/top_level.txt,sha256=XJriFQoj2KWV38bXh4pkKnRfiMmZO6NDLvP1KV-eRZQ,9
|
|
15
|
+
ledgerfm-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ledgerfm
|