Text Generation
PEFT
Safetensors
PyTorch
English
causal-lm
lora
qwen
sft
dpo
seal
self-adaptation
hitl
Instructions to use aaronr43210/MiniSEAL with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use aaronr43210/MiniSEAL with PEFT:
Task type is invalid.
- Notebooks
- Google Colab
- Kaggle
Upload tests
Browse files- tests/__init__.py +0 -0
- tests/test_logic.py +152 -0
- tests/test_lora_roundtrip.py +156 -0
- tests/test_training_math.py +143 -0
tests/__init__.py
ADDED
|
File without changes
|
tests/test_logic.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Torch-free verification tests for MiniSEAL logic.
|
| 3 |
+
|
| 4 |
+
Run (no pytest needed):
|
| 5 |
+
python3 -m tests.test_logic
|
| 6 |
+
|
| 7 |
+
Covers:
|
| 8 |
+
- token-F1 reward used by the SEAL accept/reject gate
|
| 9 |
+
- PII IP-address regex (must not false-positive on version strings)
|
| 10 |
+
- canonical prompt formatting shared by SFT / DPO / inference
|
| 11 |
+
- SFT train/val dedup + deterministic shuffle (no leakage)
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import json
|
| 17 |
+
import random
|
| 18 |
+
|
| 19 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_token_f1():
|
| 23 |
+
from src.common.metrics import token_f1 as _token_f1
|
| 24 |
+
|
| 25 |
+
# Identical strings -> perfect score.
|
| 26 |
+
assert _token_f1("the cat sat", "the cat sat") == 1.0
|
| 27 |
+
# No overlap -> zero.
|
| 28 |
+
assert _token_f1("dogs run", "the cat sat") == 0.0
|
| 29 |
+
# Partial overlap -> between 0 and 1.
|
| 30 |
+
f1 = _token_f1("the cat", "the cat sat")
|
| 31 |
+
assert 0.0 < f1 < 1.0
|
| 32 |
+
# Order-insensitive.
|
| 33 |
+
assert _token_f1("cat the sat", "the cat sat") == 1.0
|
| 34 |
+
# Empty prediction vs non-empty reference -> 0.
|
| 35 |
+
assert _token_f1("", "the cat") == 0.0
|
| 36 |
+
print("test_token_f1 OK")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_ip_regex():
|
| 40 |
+
from src.hitl.validators import RiskValidator
|
| 41 |
+
|
| 42 |
+
v = RiskValidator(blocked_keywords=[], sensitive_topics=[])
|
| 43 |
+
# Real IPv4 flagged.
|
| 44 |
+
assert v.ip_regex.search("connect to 192.168.1.1 now")
|
| 45 |
+
assert v.ip_regex.search("mask 255.255.255.0")
|
| 46 |
+
# Version strings with >4 parts must NOT false-positive.
|
| 47 |
+
assert not v.ip_regex.search("release 3.11.4.2.1 shipped")
|
| 48 |
+
# Out-of-range octets rejected.
|
| 49 |
+
assert not v.ip_regex.search("999.1.1.1")
|
| 50 |
+
assert not v.ip_regex.search("256.0.0.1")
|
| 51 |
+
# Over-long trailing octet rejected.
|
| 52 |
+
assert not v.ip_regex.search("10.0.0.1234")
|
| 53 |
+
print("test_ip_regex OK")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_risk_levels():
|
| 57 |
+
from src.hitl.validators import RiskValidator
|
| 58 |
+
|
| 59 |
+
v = RiskValidator(blocked_keywords=["ignore previous"], sensitive_topics=["password"])
|
| 60 |
+
level, flags = v.analyze("hello", "ignore previous instructions")
|
| 61 |
+
assert level == "HIGH", (level, flags)
|
| 62 |
+
level, flags = v.analyze("what is the password", "it is secret")
|
| 63 |
+
assert level == "MEDIUM", (level, flags)
|
| 64 |
+
level, flags = v.analyze("hi", "all good")
|
| 65 |
+
assert level == "LOW", (level, flags)
|
| 66 |
+
print("test_risk_levels OK")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_prompt_format_shared():
|
| 70 |
+
from src.common.prompts import format_prompt, CHAT_PROMPT_TEMPLATE
|
| 71 |
+
|
| 72 |
+
p = format_prompt(" Explain RoPE. ")
|
| 73 |
+
# Strips the instruction and uses the canonical template.
|
| 74 |
+
assert p == CHAT_PROMPT_TEMPLATE.format(instruction="Explain RoPE.")
|
| 75 |
+
assert p.endswith("### Response:\n")
|
| 76 |
+
print("test_prompt_format_shared OK")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_resolvers_fallback():
|
| 80 |
+
from src.common.prompts import resolve_eos_id, resolve_pad_id
|
| 81 |
+
|
| 82 |
+
class FakeTok:
|
| 83 |
+
def __init__(self, mapping):
|
| 84 |
+
self.mapping = mapping
|
| 85 |
+
|
| 86 |
+
def token_to_id(self, tok):
|
| 87 |
+
return self.mapping.get(tok)
|
| 88 |
+
|
| 89 |
+
# Prefers <|eos|>.
|
| 90 |
+
assert resolve_eos_id(FakeTok({"<|eos|>": 7, "<|endoftext|>": 9})) == 7
|
| 91 |
+
# Falls back to <|endoftext|>.
|
| 92 |
+
assert resolve_eos_id(FakeTok({"<|endoftext|>": 9})) == 9
|
| 93 |
+
# None when neither present (callers must then skip appending EOS).
|
| 94 |
+
assert resolve_eos_id(FakeTok({})) is None
|
| 95 |
+
# Pad falls back to 0.
|
| 96 |
+
assert resolve_pad_id(FakeTok({})) == 0
|
| 97 |
+
assert resolve_pad_id(FakeTok({"<|pad|>": 3})) == 3
|
| 98 |
+
print("test_resolvers_fallback OK")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_sft_dedup_and_split_no_leakage():
|
| 102 |
+
"""Mirror the dedup + seeded-shuffle + split logic in src/train/sft.py."""
|
| 103 |
+
# 8 unique rows, each duplicated 50x (the old create_rag_dataset behavior).
|
| 104 |
+
base = [{"prompt": f"q{i}", "response": f"a{i}"} for i in range(8)]
|
| 105 |
+
sft_data = base * 50
|
| 106 |
+
|
| 107 |
+
seen = set()
|
| 108 |
+
unique = []
|
| 109 |
+
for row in sft_data:
|
| 110 |
+
key = json.dumps(row, sort_keys=True)
|
| 111 |
+
if key not in seen:
|
| 112 |
+
seen.add(key)
|
| 113 |
+
unique.append(row)
|
| 114 |
+
assert len(unique) == 8, len(unique)
|
| 115 |
+
|
| 116 |
+
rng = random.Random(1234)
|
| 117 |
+
rng.shuffle(unique)
|
| 118 |
+
split_idx = int(len(unique) * 0.9)
|
| 119 |
+
train, val = unique[:split_idx], unique[split_idx:]
|
| 120 |
+
|
| 121 |
+
# No row appears in both splits -> no train/val leakage.
|
| 122 |
+
train_keys = {json.dumps(r, sort_keys=True) for r in train}
|
| 123 |
+
val_keys = {json.dumps(r, sort_keys=True) for r in val}
|
| 124 |
+
assert train_keys.isdisjoint(val_keys)
|
| 125 |
+
assert len(val) >= 1
|
| 126 |
+
|
| 127 |
+
# Deterministic under a fixed seed.
|
| 128 |
+
u2 = list(base)
|
| 129 |
+
random.Random(1234).shuffle(u2)
|
| 130 |
+
# Same seed + same input order -> same permutation.
|
| 131 |
+
ref = list(base)
|
| 132 |
+
random.Random(1234).shuffle(ref)
|
| 133 |
+
assert u2 == ref
|
| 134 |
+
print("test_sft_dedup_and_split_no_leakage OK")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def main():
|
| 138 |
+
tests = [
|
| 139 |
+
test_token_f1,
|
| 140 |
+
test_ip_regex,
|
| 141 |
+
test_risk_levels,
|
| 142 |
+
test_prompt_format_shared,
|
| 143 |
+
test_resolvers_fallback,
|
| 144 |
+
test_sft_dedup_and_split_no_leakage,
|
| 145 |
+
]
|
| 146 |
+
for t in tests:
|
| 147 |
+
t()
|
| 148 |
+
print(f"\nAll {len(tests)} torch-free tests passed.")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
main()
|
tests/test_lora_roundtrip.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Torch-dependent tests that the SEAL adapter loop actually closes:
|
| 3 |
+
a trained LoRA adapter can be saved and re-loaded onto a fresh base model,
|
| 4 |
+
reproducing the adapted model's outputs bit-for-bit.
|
| 5 |
+
|
| 6 |
+
Run on a torch box:
|
| 7 |
+
python3 -m tests.test_lora_roundtrip
|
| 8 |
+
|
| 9 |
+
Covers:
|
| 10 |
+
- save_lora_adapter -> load_lora_adapter reproduces identical logits.
|
| 11 |
+
- A fresh base model (no adapter) differs from the adapted one (sanity: the
|
| 12 |
+
adapter is actually doing something), and loading recovers the adapted output.
|
| 13 |
+
- load_lora_state_dict raises on a config mismatch (wrong rank).
|
| 14 |
+
- merge_lora_weights produces outputs equal to the unmerged LoRA forward.
|
| 15 |
+
- Legacy bare-state-dict adapters still load via the back-compat path.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import tempfile
|
| 21 |
+
|
| 22 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
from src.model.config import ModelConfig
|
| 27 |
+
from src.model.llm import DecoderOnlyTransformer
|
| 28 |
+
from src.lora.lora import (
|
| 29 |
+
inject_lora,
|
| 30 |
+
save_lora_adapter,
|
| 31 |
+
load_lora_adapter,
|
| 32 |
+
load_lora_state_dict,
|
| 33 |
+
get_lora_state_dict,
|
| 34 |
+
merge_lora_weights,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
TARGETS = ["q_proj", "v_proj"]
|
| 38 |
+
RANK, ALPHA = 8, 16
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _fresh_model(seed=0):
|
| 42 |
+
torch.manual_seed(seed)
|
| 43 |
+
cfg = ModelConfig(vocab_size=32, n_layer=2, n_head=2, n_embd=16, block_size=32)
|
| 44 |
+
m = DecoderOnlyTransformer(cfg)
|
| 45 |
+
m.eval()
|
| 46 |
+
return m
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _logits(model, ids):
|
| 50 |
+
with torch.no_grad():
|
| 51 |
+
out = model(ids)
|
| 52 |
+
return out[0] if isinstance(out, tuple) else out
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_adapter_roundtrip_reproduces_outputs():
|
| 56 |
+
ids = torch.randint(0, 32, (1, 6))
|
| 57 |
+
|
| 58 |
+
# 1. Base model + injected LoRA, then perturb the adapter so it's non-trivial
|
| 59 |
+
# (B starts at zero -> no-op; fill it to simulate "trained" deltas).
|
| 60 |
+
model = _fresh_model(seed=0)
|
| 61 |
+
base_logits = _logits(model, ids).clone()
|
| 62 |
+
|
| 63 |
+
inject_lora(model, target_keywords=TARGETS, rank=RANK, alpha=ALPHA, dropout=0.0)
|
| 64 |
+
with torch.no_grad():
|
| 65 |
+
for name, p in model.named_parameters():
|
| 66 |
+
if "lora_B" in name:
|
| 67 |
+
p.normal_(0, 0.1) # pretend training moved B away from zero
|
| 68 |
+
adapted_logits = _logits(model, ids).clone()
|
| 69 |
+
|
| 70 |
+
# Adapter must actually change the output, else the test proves nothing.
|
| 71 |
+
assert not torch.allclose(base_logits, adapted_logits, atol=1e-5)
|
| 72 |
+
|
| 73 |
+
# 2. Save adapter, build a FRESH base, load adapter back.
|
| 74 |
+
with tempfile.TemporaryDirectory() as d:
|
| 75 |
+
path = os.path.join(d, "adapter.pt")
|
| 76 |
+
save_lora_adapter(model, path, rank=RANK, alpha=ALPHA,
|
| 77 |
+
target_keywords=TARGETS, dropout=0.0,
|
| 78 |
+
meta={"source": "test"})
|
| 79 |
+
|
| 80 |
+
fresh = _fresh_model(seed=0) # same init as the original base
|
| 81 |
+
fresh = load_lora_adapter(fresh, path, device="cpu")
|
| 82 |
+
reloaded_logits = _logits(fresh, ids)
|
| 83 |
+
|
| 84 |
+
# 3. Reloaded == adapted (the loop closes).
|
| 85 |
+
assert torch.allclose(adapted_logits, reloaded_logits, atol=1e-5), \
|
| 86 |
+
(adapted_logits - reloaded_logits).abs().max()
|
| 87 |
+
print("test_adapter_roundtrip_reproduces_outputs OK")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_load_rejects_config_mismatch():
|
| 91 |
+
model = _fresh_model(seed=1)
|
| 92 |
+
inject_lora(model, target_keywords=TARGETS, rank=RANK, alpha=ALPHA, dropout=0.0)
|
| 93 |
+
sd = get_lora_state_dict(model)
|
| 94 |
+
|
| 95 |
+
# Inject with a DIFFERENT rank -> shapes/keys won't line up -> must raise.
|
| 96 |
+
other = _fresh_model(seed=1)
|
| 97 |
+
inject_lora(other, target_keywords=TARGETS, rank=RANK * 2, alpha=ALPHA, dropout=0.0)
|
| 98 |
+
try:
|
| 99 |
+
load_lora_state_dict(other, sd, strict=True)
|
| 100 |
+
except (RuntimeError, KeyError):
|
| 101 |
+
print("test_load_rejects_config_mismatch OK")
|
| 102 |
+
return
|
| 103 |
+
raise AssertionError("expected a mismatch error on wrong rank")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_merge_matches_unmerged():
|
| 107 |
+
ids = torch.randint(0, 32, (1, 5))
|
| 108 |
+
model = _fresh_model(seed=2)
|
| 109 |
+
inject_lora(model, target_keywords=TARGETS, rank=RANK, alpha=ALPHA, dropout=0.0)
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
for name, p in model.named_parameters():
|
| 112 |
+
if "lora_B" in name:
|
| 113 |
+
p.normal_(0, 0.1)
|
| 114 |
+
unmerged = _logits(model, ids).clone()
|
| 115 |
+
|
| 116 |
+
merge_lora_weights(model)
|
| 117 |
+
merged = _logits(model, ids)
|
| 118 |
+
assert torch.allclose(unmerged, merged, atol=1e-5), (unmerged - merged).abs().max()
|
| 119 |
+
print("test_merge_matches_unmerged OK")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_legacy_bare_state_dict_loads():
|
| 123 |
+
ids = torch.randint(0, 32, (1, 4))
|
| 124 |
+
model = _fresh_model(seed=3)
|
| 125 |
+
inject_lora(model, target_keywords=TARGETS, rank=16, alpha=32, dropout=0.0) # legacy defaults
|
| 126 |
+
with torch.no_grad():
|
| 127 |
+
for name, p in model.named_parameters():
|
| 128 |
+
if "lora_B" in name:
|
| 129 |
+
p.normal_(0, 0.1)
|
| 130 |
+
adapted = _logits(model, ids).clone()
|
| 131 |
+
|
| 132 |
+
with tempfile.TemporaryDirectory() as d:
|
| 133 |
+
path = os.path.join(d, "legacy.pt")
|
| 134 |
+
torch.save(get_lora_state_dict(model), path) # bare dict, no wrapper/config
|
| 135 |
+
|
| 136 |
+
fresh = _fresh_model(seed=3)
|
| 137 |
+
fresh = load_lora_adapter(fresh, path, device="cpu") # falls back to defaults
|
| 138 |
+
reloaded = _logits(fresh, ids)
|
| 139 |
+
assert torch.allclose(adapted, reloaded, atol=1e-5)
|
| 140 |
+
print("test_legacy_bare_state_dict_loads OK")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def main():
|
| 144 |
+
tests = [
|
| 145 |
+
test_adapter_roundtrip_reproduces_outputs,
|
| 146 |
+
test_load_rejects_config_mismatch,
|
| 147 |
+
test_merge_matches_unmerged,
|
| 148 |
+
test_legacy_bare_state_dict_loads,
|
| 149 |
+
]
|
| 150 |
+
for t in tests:
|
| 151 |
+
t()
|
| 152 |
+
print(f"\nAll {len(tests)} LoRA round-trip tests passed.")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
main()
|
tests/test_training_math.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Torch-dependent verification tests for MiniSEAL training math.
|
| 3 |
+
|
| 4 |
+
Requires torch. Run on the GPU/training box (no pytest needed):
|
| 5 |
+
python3 -m tests.test_training_math
|
| 6 |
+
|
| 7 |
+
Covers:
|
| 8 |
+
- DPO loss: zero at init (policy == reference), positive, decreases as the
|
| 9 |
+
policy prefers chosen over rejected; chosen-accuracy signal is correct.
|
| 10 |
+
- get_batch_logps: ignores -100 label positions and shifts correctly.
|
| 11 |
+
- SFT causal-shift masking: prompt tokens (-100) contribute no loss.
|
| 12 |
+
- RMSNorm: numerically stable and dtype-preserving under autocast dtypes.
|
| 13 |
+
- generate(): batched EOS stopping returns the right shapes.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
|
| 19 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_dpo_loss_properties():
|
| 26 |
+
from src.train.dpo import dpo_loss
|
| 27 |
+
|
| 28 |
+
beta = 0.1
|
| 29 |
+
# At initialization policy == reference -> logits diff is 0 -> loss = -log(0.5).
|
| 30 |
+
z = torch.zeros(4)
|
| 31 |
+
loss, acc = dpo_loss(z.clone(), z.clone(), z.clone(), z.clone(), beta=beta)
|
| 32 |
+
assert abs(loss.item() - (-F.logsigmoid(torch.tensor(0.0)).item())) < 1e-6
|
| 33 |
+
assert abs(loss.item() - 0.6931) < 1e-3
|
| 34 |
+
|
| 35 |
+
# Policy strongly prefers chosen over rejected relative to ref -> lower loss.
|
| 36 |
+
pc = torch.tensor([2.0, 2.0, 2.0, 2.0]) # policy chosen logps
|
| 37 |
+
pr = torch.tensor([-2.0, -2.0, -2.0, -2.0]) # policy rejected logps
|
| 38 |
+
rc = torch.zeros(4)
|
| 39 |
+
rr = torch.zeros(4)
|
| 40 |
+
good_loss, good_acc = dpo_loss(pc, pr, rc, rr, beta=beta)
|
| 41 |
+
assert good_loss.item() < loss.item()
|
| 42 |
+
assert good_acc.item() == 1.0 # chosen logratio > rejected everywhere
|
| 43 |
+
|
| 44 |
+
# Reversed preference -> higher loss and zero accuracy.
|
| 45 |
+
bad_loss, bad_acc = dpo_loss(pr, pc, rc, rr, beta=beta)
|
| 46 |
+
assert bad_loss.item() > loss.item()
|
| 47 |
+
assert bad_acc.item() == 0.0
|
| 48 |
+
print("test_dpo_loss_properties OK")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_get_batch_logps_masks_prompt():
|
| 52 |
+
from src.train.dpo import get_batch_logps
|
| 53 |
+
|
| 54 |
+
torch.manual_seed(0)
|
| 55 |
+
B, T, V = 2, 5, 7
|
| 56 |
+
logits = torch.randn(B, T, V)
|
| 57 |
+
|
| 58 |
+
labels = torch.randint(0, V, (B, T))
|
| 59 |
+
masked = labels.clone()
|
| 60 |
+
masked[:, :2] = -100 # mask first two "prompt" positions
|
| 61 |
+
|
| 62 |
+
lp_full = get_batch_logps(logits, labels)
|
| 63 |
+
lp_masked = get_batch_logps(logits, masked)
|
| 64 |
+
|
| 65 |
+
# Masked version sums over fewer tokens, so logps (negative CE sum) must be >=.
|
| 66 |
+
assert torch.all(lp_masked >= lp_full - 1e-4)
|
| 67 |
+
|
| 68 |
+
# If ALL labels are masked, logps must be exactly 0 (no supervised tokens).
|
| 69 |
+
all_masked = torch.full_like(labels, -100)
|
| 70 |
+
assert torch.allclose(get_batch_logps(logits, all_masked), torch.zeros(B))
|
| 71 |
+
print("test_get_batch_logps_masks_prompt OK")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_sft_shift_ignores_prompt():
|
| 75 |
+
# Loss on a sequence where prompt labels are -100 must equal loss computed
|
| 76 |
+
# only over the response positions.
|
| 77 |
+
torch.manual_seed(1)
|
| 78 |
+
V = 10
|
| 79 |
+
logits = torch.randn(1, 6, V)
|
| 80 |
+
labels = torch.tensor([[-100, -100, -100, 3, 4, 5]])
|
| 81 |
+
|
| 82 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 83 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 84 |
+
loss_all = F.cross_entropy(
|
| 85 |
+
shift_logits.view(-1, V), shift_labels.view(-1), ignore_index=-100
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# Manual: only positions where shifted label != -100.
|
| 89 |
+
mask = shift_labels.view(-1) != -100
|
| 90 |
+
manual = F.cross_entropy(
|
| 91 |
+
shift_logits.view(-1, V)[mask], shift_labels.view(-1)[mask]
|
| 92 |
+
)
|
| 93 |
+
assert torch.allclose(loss_all, manual, atol=1e-5)
|
| 94 |
+
print("test_sft_shift_ignores_prompt OK")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_rmsnorm_stability_and_dtype():
|
| 98 |
+
from src.model.layers import RMSNorm
|
| 99 |
+
|
| 100 |
+
norm = RMSNorm(16, eps=1e-5)
|
| 101 |
+
x = torch.randn(2, 4, 16)
|
| 102 |
+
out = norm(x)
|
| 103 |
+
assert out.shape == x.shape
|
| 104 |
+
assert torch.isfinite(out).all()
|
| 105 |
+
|
| 106 |
+
# Preserves input dtype even though variance is computed in fp32.
|
| 107 |
+
if torch.cuda.is_available():
|
| 108 |
+
xb = x.to(torch.bfloat16)
|
| 109 |
+
ob = norm(xb)
|
| 110 |
+
assert ob.dtype == torch.bfloat16
|
| 111 |
+
print("test_rmsnorm_stability_and_dtype OK")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_generate_batched_shapes():
|
| 115 |
+
from src.model.config import ModelConfig
|
| 116 |
+
from src.model.llm import DecoderOnlyTransformer
|
| 117 |
+
|
| 118 |
+
cfg = ModelConfig(vocab_size=32, n_layer=2, n_head=2, n_embd=16, block_size=32)
|
| 119 |
+
model = DecoderOnlyTransformer(cfg)
|
| 120 |
+
model.eval()
|
| 121 |
+
|
| 122 |
+
ids = torch.randint(0, 32, (3, 4)) # batch of 3
|
| 123 |
+
out = model.generate(ids, max_new_tokens=5, temperature=1.0, top_k=4)
|
| 124 |
+
assert out.shape[0] == 3
|
| 125 |
+
assert out.shape[1] == 4 + 5
|
| 126 |
+
print("test_generate_batched_shapes OK")
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def main():
|
| 130 |
+
tests = [
|
| 131 |
+
test_dpo_loss_properties,
|
| 132 |
+
test_get_batch_logps_masks_prompt,
|
| 133 |
+
test_sft_shift_ignores_prompt,
|
| 134 |
+
test_rmsnorm_stability_and_dtype,
|
| 135 |
+
test_generate_batched_shapes,
|
| 136 |
+
]
|
| 137 |
+
for t in tests:
|
| 138 |
+
t()
|
| 139 |
+
print(f"\nAll {len(tests)} torch math tests passed.")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
if __name__ == "__main__":
|
| 143 |
+
main()
|