sharky-workbench / smoke_train.py
luispoveda93's picture
Duplicate from luispoveda93/minicpm4-pcap-kev-workbench
92c44eb
Raw History Blame Contribute Delete
15.7 kB
#!/usr/bin/env python
"""Phase-1 smoke training for kev[serve] on openbmb/MiniCPM4-0.5B (GPU job entry point).
Run on the GPU worker as: python /tmp/smoke_train.py
Runs on CPU too (smoke validation only) - set SMOKE_DEVICE=cpu.
"""
import json, os, random, re, shutil, subprocess, sys
try:
import trackio
trackio.init(project="minicpm4-pcap-kev", space_id="luispoveda93/minicpm4-pcap-kev-trackio")
except ModuleNotFoundError:
class trackio: # CPU validation fallback; the GPU job installs trackio
@staticmethod
def log(*a, **k): pass
@staticmethod
def finish(): pass
BASE = "openbmb/MiniCPM4-0.5B"
DATA_DIR = "/tmp/smoke_data"
RUN_DIR = "/tmp/smoke_run"
# (a) patches - applied in this process AND in the kev.train subprocess via sitecustomize
PATCH_SRC = '''
import kev.model as _km
_km.SPECIAL = ['<|fim_prefix|>', '<|fim_middle|>', '<|execute_start|>', '<|execute_end|>', '<|fim_suffix|>']
import transformers.utils.import_utils as _iu
if not getattr(_iu, '_kev_fx_patched', False):
_iu.is_torch_fx_available = lambda: False
_iu._kev_fx_patched = True
from transformers.modeling_utils import PreTrainedModel as _PTM
if not getattr(_PTM, '_kev_patched', False):
_orig_getewk = _PTM.get_expanded_tied_weights_keys
def _getewk(self, all_submodels=True):
if isinstance(self._tied_weights_keys, list):
self._tied_weights_keys = {'lm_head.weight': 'model.embed_tokens.weight'}
return _orig_getewk(self, all_submodels)
_PTM.get_expanded_tied_weights_keys = _getewk
import torch as _th
import transformers as _tf
import inspect as _insp
def _fix_model(out):
core = out.model if hasattr(out, 'model') else out
# training never uses the cache; transformers-5.x + MiniCPM4 remote code
# raises ValueError on the legacy past_key_values format when use_cache
# defaults to True, so force it off.
try:
core.config.use_cache = False
except Exception as _e:
print('WARN use_cache=False skipped:', repr(_e), flush=True)
import importlib as _il
g = vars(_il.import_module(type(core).__module__))
if '_prepare_4d_causal_attention_mask' in g and not g.get('_kev_mask_passthrough'):
_orig4 = g['_prepare_4d_causal_attention_mask']
def _p4(attention_mask=None, *a, **k):
if attention_mask is not None and getattr(attention_mask, 'dim', lambda: 0)() == 4:
return attention_mask
return _orig4(attention_mask, *a, **k)
g['_prepare_4d_causal_attention_mask'] = _p4
g['_kev_mask_passthrough'] = True
# kv_seq_len fix: MiniCPM4 remote code computes
# kv_seq_len = position_ids.max().item() + 1 in all three attention
# paths, which breaks under kev's restarted per-branch position ids
# (mask/key width != max position). Rewrite the loaded methods to use
# the actual key width, so the fix survives a fresh remote-code cache.
if not g.get('_kev_kvfix'):
import textwrap as _tw
_bad = 'kv_seq_len = position_ids.max().item() + 1'
_good = 'kv_seq_len = key_states.shape[-2]'
_nfix = 0
for _cn, _cls in list(g.items()):
if not isinstance(_cls, type):
continue
for _mn, _m in list(vars(_cls).items()):
if isinstance(_m, (staticmethod, classmethod)):
_fn = _m.__func__
elif _insp.isfunction(_m):
_fn = _m
else:
continue
try:
_src = _insp.getsource(_fn)
except Exception:
continue
if _bad not in _src:
continue
_src = _src.replace(_bad, _good)
_ns = dict(_fn.__globals__)
try:
exec(compile(_tw.dedent(_src), _fn.__code__.co_filename, 'exec'), _ns)
except Exception as _e:
print('WARN kv_seq_len fix exec failed', _cn, _mn, repr(_e), flush=True)
continue
_nf = _ns.get(_fn.__name__)
if _nf is not None:
setattr(_cls, _mn, staticmethod(_nf) if isinstance(_m, staticmethod) else _nf)
_nfix += 1
g['_kev_kvfix'] = True
print('kv_seq_len fix applied to', _nfix, 'methods in', type(core).__module__, flush=True)
# Rotary repair: after from_pretrained's meta-device init, the RoPE
# buffers come back corrupt in TWO ways: non-finite inv_freq on some
# modules, finite-but-garbage inv_freq (absmax up to 2.3e38) with
# dead/NaN cos/sin caches on others. Skip-gate catches both, plus
# uninitialized cos caches that read as normal garbage (~1e-40).
# Re-running __init__ is idempotent and rebuilds consistent buffers.
for m in core.modules():
if hasattr(m, 'inv_freq'):
try:
_bad = (not bool(_th.isfinite(m.inv_freq).all())) or float(m.inv_freq.abs().max()) > 1.0
if hasattr(m, 'cos_cached'):
_bad = _bad or (not bool(_th.isfinite(m.cos_cached).all())) or float(m.cos_cached.abs().max()) < 0.1
if not _bad:
continue
kw = {}
for pname in _insp.signature(type(m).__init__).parameters:
if pname == 'self':
continue
if pname == 'device':
bufs = list(m.buffers()) + list(m.parameters())
kw['device'] = bufs[0].device if bufs else _th.device('cpu')
elif hasattr(m, pname):
kw[pname] = getattr(m, pname)
type(m).__init__(m, **kw)
print('reinit rotary', type(m).__name__, 'inv_freq max', float(m.inv_freq.abs().max()), flush=True)
except Exception as _e:
print('WARN rotary reinit failed', type(m).__name__, repr(_e), flush=True)
_orig_afp2 = _tf.AutoModelForCausalLM.from_pretrained.__func__
def _afp(cls, *args, **kwargs):
kwargs.setdefault('trust_remote_code', True)
kwargs.setdefault('attn_implementation', 'eager')
out = _orig_afp2(cls, *args, **kwargs)
try:
_fix_model(out)
except Exception as _e:
print('WARN model patch skipped:', repr(_e), flush=True)
return out
_tf.AutoModelForCausalLM.from_pretrained = classmethod(_afp)
from transformers import AutoTokenizer as _AT
_orig_tok = _AT.from_pretrained.__func__
def _tokp(cls, *args, **kwargs):
kwargs.setdefault('trust_remote_code', True)
return _orig_tok(cls, *args, **kwargs)
_AT.from_pretrained = classmethod(_tokp)
# LoRA target fix: kev hardcodes target names in DecisionModel.__init__; peft matches
# by suffix. Monkeypatch so every request for the standard projection set
# becomes an explicit, verified list for this base (fully-qualified names verified by
# probe: layers.N.self_attn.{q,k,v,o}_proj, layers.N.mlp.{gate,up,down}_proj).
def _patch_lora():
import peft.tuners.tuners_utils as _tu
_orig_check = _tu.check_target_module_exists
_VALID = {'q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj'}
def _check(cfg, key):
res = _orig_check(cfg, key)
if not res and isinstance(cfg.target_modules, (list, set)) and set(cfg.target_modules) == _VALID:
return key.split('.')[-1] in _VALID
return res
_tu.check_target_module_exists = _check
import peft.tuners.lora.layer as _ll
if hasattr(_ll, 'check_target_module_exists'):
_ll.check_target_module_exists = _check
_patch_lora()
_PTM._kev_patched = True
'''
# textwrap is referenced inside PATCH_SRC; bind it there before exec
PATCH_SRC = "import textwrap as _tw\n" + PATCH_SRC
exec(PATCH_SRC)
from transformers import AutoTokenizer
_scdir = "/tmp/kevpatch"
import os as _os
_os.makedirs(_scdir, exist_ok=True)
with open(_scdir + "/sitecustomize.py", "w") as _f:
_f.write(PATCH_SRC)
os.environ["PYTHONPATH"] = _scdir + os.pathsep + os.environ.get("PYTHONPATH", "")
# (b) synthetic pcap-triage records ------------------------------------------------
DECISION = ["benign", "suspicious", "malicious"]
PROTO = {"6": "TCP", "17": "UDP", "1": "ICMP"}
def fake_record(i, rng):
verdict = rng.choice(DECISION)
src_ip = f"10.0.{rng.randint(0, 255)}.{rng.randint(1, 254)}"
dst_ip = f"192.168.1.{rng.randint(1, 254)}"
n_flow = rng.randint(1, 3)
flows = []
for _ in range(n_flow):
p = rng.choice(list(PROTO))
flows.append({"proto": PROTO[p], "src": src_ip, "dst": dst_ip,
"sport": rng.randint(1024, 65535), "dport": rng.choice([22, 53, 80, 443, 445, 3389, 8080]),
"pkts": rng.randint(1, 200), "bytes": rng.randint(60, 90000),
"dur_ms": rng.randint(0, 60000)})
n_hex = rng.randint(2, 4)
hex_lines = []
for j in range(n_hex):
n_bytes = rng.randint(8, 24)
b = bytes(rng.randrange(256) for _ in range(n_bytes))
if verdict == "malicious":
b = b[:2] + b"\x00\x00" + b[4:] # distinct but deterministic marker
hex_lines.append(f"{j:04x} " + " ".join(f"{x:02x}" for x in b))
fl = flows[0]
extra = " | " + " ; ".join(f"{x['proto']} {x['sport']}->{x['dport']} pkts={x['pkts']}" for x in flows[1:])
state = (f"### Capture summary\n{rng.randint(10, 5000)} frames, {fl['proto']} {src_ip}:{fl['sport']} <- {dst_ip}:{fl['dport']},"
f" duration {fl['dur_ms']}ms, bytes {fl['bytes']}{extra}\n### Packet hex (first {len(hex_lines)} packets, 16 bytes each)\n"
+ "\n".join(hex_lines))
rec = {"state": state, "questions": {
"verdict": {"type": "choice", "instructions": "Which verdict best describes this capture?",
"criteria": {k: f"{k}: traffic class" for k in DECISION}, "label": verdict},
"exploit_evidence": {"type": "noul", "instructions": "Does the capture contain direct evidence of an exploit attempt?",
"label": verdict == "malicious"},
"recon_only": {"type": "noul", "instructions": "Is this capture scan/recon-only with no exploit attempt?",
"label": verdict == "suspicious"},
}}
# v6 fix: kev.data.load_records injects these defaults; hand-built records that
# skip load_records (predictor path) died with KeyError 'src' in materialize.
for q in rec["questions"].values():
q.setdefault("src", f"pcap_smoke_{q['type']}")
rec["_meta"] = {"id": f"pcap_smoke/{i}", "group_id": f"pcap_smoke/{i}", "row": i, "variant": "clean",
"text_sha256": f"smoke{i}"}
return rec
def main():
rng = random.Random(0)
all_recs = [fake_record(i, rng) for i in range(40)]
train_recs, calib_recs, dev_recs = all_recs[:24], all_recs[24:32], all_recs[32:40]
shutil.rmtree(DATA_DIR, ignore_errors=True)
os.makedirs(DATA_DIR, exist_ok=True)
for name, recs in (("train", train_recs), ("calibration", calib_recs), ("development", dev_recs)):
with open(f"{DATA_DIR}/{name}.jsonl", "w", encoding="utf-8") as f:
for r in recs:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
# encode/fits check with the real tokenizer (fast on CPU)
tok = AutoTokenizer.from_pretrained(BASE)
from kev.data import load_records, materialize
from kev.model import fits
n_fit = 0
for part in ("train", "calibration", "development"):
for r in load_records(f"{DATA_DIR}/{part}.jsonl", source="pcap_smoke"):
assert fits(materialize(r), tok), f"record {r['_meta']['id']} does not fit"
n_fit += 1
for r in all_recs: # direct materialize on hand-built records - the path that raised KeyError 'src'
assert fits(materialize(r), tok), f"raw record {r['_meta']['id']} does not fit"
n_fit += 1
print(f"data: 40 records written to {DATA_DIR}, {n_fit} encodes verified (loaded+raw) within the training context", flush=True)
if os.environ.get("SMOKE_DEVICE") == "cpu":
print("SMOKE_DEVICE=cpu: skipping train + predict; SMOKE_OK")
raise SystemExit(0)
# (d) train ---------------------------------------------------------------------
shutil.rmtree(RUN_DIR, ignore_errors=True)
cmd = ["python", "-m", "kev.train",
"--base", BASE,
"--data", f"{DATA_DIR}/train.jsonl",
"--device", "cuda", "--dtype", "bf16",
"--lora", "16", "--head_dim", "256", "--lora_targets", "all",
"--epochs", "1", "--lr", "2e-4",
"--batch", "2", "--accum", "1",
"--out", RUN_DIR]
print("RUN:", " ".join(cmd), flush=True)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
for line in proc.stdout:
print(line, end="", flush=True)
if line.startswith(("ep", "step")):
fl = re.findall(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", line)
if len(fl) >= 2:
try:
trackio.log({"step": float(fl[0]), "loss": float(fl[-1])})
except Exception:
pass
proc.wait()
if proc.returncode != 0:
print("SMOKE_FAIL: kev.train exited with code", proc.returncode)
raise SystemExit(1)
# (e) score the 8 development records -------------------------------------------
from kev.checkpoint import LoadOptions
from kev.predictors import LocalPredictor
predictor = LocalPredictor(RUN_DIR, "cuda", LoadOptions(temperature=1.0))
correct = 0
for r in dev_recs:
out = predictor(r)
p = out["probabilities"]["verdict"]
total = sum(p.values())
assert abs(total - 1.0) < 1e-3, f"verdict probs not softmax-normalized: sum={total}"
pred = max(p, key=p.get)
label = r["questions"]["verdict"]["label"]
print(f"{r['_meta']['id']}: verdict probs " +
" ".join(f"{k}={v:.4f}" for k, v in p.items()) +
f" | exploit_evidence {out['probabilities']['exploit_evidence']}" +
f" | recon_only {out['probabilities']['recon_only']}" +
f" | pred={pred} gold={label} {'OK' if pred == label else 'MISS'}", flush=True)
if pred == label:
correct += 1
print(f"development accuracy: {correct}/8", flush=True)
# final gate: training produced >=1 optimizer step, 8 dev records, K probabilities, normalized
with open(f"{RUN_DIR}/training_metrics.json") as f:
metrics = json.load(f)
steps = int(metrics.get("optimizer_steps", 0))
ok = steps >= 1 and len(dev_recs) == 8 and all(
len(out2["probabilities"]["verdict"]) == 3 and abs(sum(out2["probabilities"]["verdict"].values()) - 1.0) < 1e-3
for out2 in [predictor(r) for r in dev_recs])
trackio.log({"dev_acc": correct / 8.0, "stage": "smoke", "optimizer_steps": steps})
trackio.finish()
print("SMOKE_OK" if ok else "SMOKE_FAIL: gate failed", flush=True)
if not ok:
raise SystemExit(1)
if __name__ == "__main__":
main()