Upload oss-jev-train for hf jobs uv run
Browse files- configs/jobs-a10g-noul-aug.yaml +33 -0
- configs/smoke-noul-aug.yaml +26 -0
- oss_jev_train/__init__.py +1 -1
- oss_jev_train/__pycache__/__init__.cpython-312.pyc +0 -0
- oss_jev_train/__pycache__/code_loss.cpython-312.pyc +0 -0
- oss_jev_train/__pycache__/dataset.cpython-312.pyc +0 -0
- oss_jev_train/__pycache__/export_ckpt.cpython-312.pyc +0 -0
- oss_jev_train/__pycache__/noul_augment.cpython-312.pyc +0 -0
- oss_jev_train/__pycache__/prompts.cpython-312.pyc +0 -0
- oss_jev_train/__pycache__/schema.cpython-312.pyc +0 -0
- oss_jev_train/__pycache__/train.cpython-312.pyc +0 -0
- oss_jev_train/code_loss.py +148 -7
- oss_jev_train/dataset.py +69 -11
- oss_jev_train/export_ckpt.py +14 -0
- oss_jev_train/noul_augment.py +184 -0
- oss_jev_train/prompts.py +31 -7
- oss_jev_train/schema.py +6 -2
- oss_jev_train/train.py +130 -13
- pyproject.toml +1 -1
configs/jobs-a10g-noul-aug.yaml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Noul augment continue-from-10k (v0.1.4). Distinct Hub id — never
|
| 2 |
+
# overwrite main / decision-10k. Recipe: 10k fix baseline + negation
|
| 3 |
+
# consistency + randomized yes/no codes. Binary head off unless dry-run
|
| 4 |
+
# shows raw logits still stuck.
|
| 5 |
+
model_id: gyanbhambhani/oss-jev-qwen05-decision-10k
|
| 6 |
+
mode: one_token
|
| 7 |
+
max_length: 1024
|
| 8 |
+
batch_size: 2
|
| 9 |
+
learning_rate: 1.0e-5
|
| 10 |
+
# Short continue: ~0.5 epoch on expanded noul (~2x noul rows)
|
| 11 |
+
max_steps: 2000
|
| 12 |
+
max_train_rows: null
|
| 13 |
+
seed: 42
|
| 14 |
+
fp16: false
|
| 15 |
+
bf16: true
|
| 16 |
+
logging_steps: 50
|
| 17 |
+
save_total_limit: 2
|
| 18 |
+
report_to: none
|
| 19 |
+
# Keep 10k fix recipe levers
|
| 20 |
+
use_soft_ce: true
|
| 21 |
+
balance_noul: true
|
| 22 |
+
constrained_codes: true
|
| 23 |
+
noul_n_frac: 0.50
|
| 24 |
+
noul_hard_ce: false
|
| 25 |
+
noul_loss_weight: 1.0
|
| 26 |
+
noul_n_sample_weight: 1.0
|
| 27 |
+
noul_logit_bias_n: 0.0
|
| 28 |
+
# v0.1.4 attacks
|
| 29 |
+
noul_random_codes: true
|
| 30 |
+
noul_negation_pairs: true
|
| 31 |
+
noul_consistency_weight: 1.0
|
| 32 |
+
noul_binary_head: false
|
| 33 |
+
noul_binary_head_weight: 1.0
|
configs/smoke-noul-aug.yaml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Local / tiny smoke for Noul augments (CPU or short Job).
|
| 2 |
+
model_id: gyanbhambhani/oss-jev-qwen05-decision-10k
|
| 3 |
+
mode: one_token
|
| 4 |
+
max_length: 512
|
| 5 |
+
batch_size: 1
|
| 6 |
+
learning_rate: 1.0e-5
|
| 7 |
+
max_steps: 4
|
| 8 |
+
max_train_rows: 64
|
| 9 |
+
seed: 42
|
| 10 |
+
fp16: false
|
| 11 |
+
bf16: false
|
| 12 |
+
logging_steps: 1
|
| 13 |
+
save_total_limit: 1
|
| 14 |
+
report_to: none
|
| 15 |
+
use_soft_ce: true
|
| 16 |
+
balance_noul: true
|
| 17 |
+
constrained_codes: true
|
| 18 |
+
noul_n_frac: 0.50
|
| 19 |
+
noul_hard_ce: false
|
| 20 |
+
noul_loss_weight: 1.0
|
| 21 |
+
noul_n_sample_weight: 1.0
|
| 22 |
+
noul_logit_bias_n: 0.0
|
| 23 |
+
noul_random_codes: true
|
| 24 |
+
noul_negation_pairs: true
|
| 25 |
+
noul_consistency_weight: 1.0
|
| 26 |
+
noul_binary_head: false
|
oss_jev_train/__init__.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""OSS Jev one-token / decision-head training (HF Jobs ready)."""
|
| 2 |
|
| 3 |
-
__version__ = "0.1.
|
| 4 |
SCHEMA_VERSION = "oss-jev-distill-v1"
|
| 5 |
# Default smoke base; prefer manifest.base_tokenizer_hint for real runs.
|
| 6 |
DEFAULT_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
|
|
|
|
| 1 |
"""OSS Jev one-token / decision-head training (HF Jobs ready)."""
|
| 2 |
|
| 3 |
+
__version__ = "0.1.4"
|
| 4 |
SCHEMA_VERSION = "oss-jev-distill-v1"
|
| 5 |
# Default smoke base; prefer manifest.base_tokenizer_hint for real runs.
|
| 6 |
DEFAULT_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
|
oss_jev_train/__pycache__/__init__.cpython-312.pyc
CHANGED
|
Binary files a/oss_jev_train/__pycache__/__init__.cpython-312.pyc and b/oss_jev_train/__pycache__/__init__.cpython-312.pyc differ
|
|
|
oss_jev_train/__pycache__/code_loss.cpython-312.pyc
CHANGED
|
Binary files a/oss_jev_train/__pycache__/code_loss.cpython-312.pyc and b/oss_jev_train/__pycache__/code_loss.cpython-312.pyc differ
|
|
|
oss_jev_train/__pycache__/dataset.cpython-312.pyc
CHANGED
|
Binary files a/oss_jev_train/__pycache__/dataset.cpython-312.pyc and b/oss_jev_train/__pycache__/dataset.cpython-312.pyc differ
|
|
|
oss_jev_train/__pycache__/export_ckpt.cpython-312.pyc
CHANGED
|
Binary files a/oss_jev_train/__pycache__/export_ckpt.cpython-312.pyc and b/oss_jev_train/__pycache__/export_ckpt.cpython-312.pyc differ
|
|
|
oss_jev_train/__pycache__/noul_augment.cpython-312.pyc
ADDED
|
Binary file (8.19 kB). View file
|
|
|
oss_jev_train/__pycache__/prompts.cpython-312.pyc
CHANGED
|
Binary files a/oss_jev_train/__pycache__/prompts.cpython-312.pyc and b/oss_jev_train/__pycache__/prompts.cpython-312.pyc differ
|
|
|
oss_jev_train/__pycache__/schema.cpython-312.pyc
CHANGED
|
Binary files a/oss_jev_train/__pycache__/schema.cpython-312.pyc and b/oss_jev_train/__pycache__/schema.cpython-312.pyc differ
|
|
|
oss_jev_train/__pycache__/train.cpython-312.pyc
CHANGED
|
Binary files a/oss_jev_train/__pycache__/train.cpython-312.pyc and b/oss_jev_train/__pycache__/train.cpython-312.pyc differ
|
|
|
oss_jev_train/code_loss.py
CHANGED
|
@@ -3,6 +3,9 @@
|
|
| 3 |
Full-vocab next-token CE left relative Y/N logits dominated by the
|
| 4 |
base prior (eval collapse: all Noul → Y). Scoring only code tokens
|
| 5 |
aligns train with infer.
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
from __future__ import annotations
|
|
@@ -13,6 +16,13 @@ import torch
|
|
| 13 |
import torch.nn.functional as F
|
| 14 |
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def code_token_loss(
|
| 17 |
logits: torch.Tensor,
|
| 18 |
labels: torch.Tensor,
|
|
@@ -28,7 +38,6 @@ def code_token_loss(
|
|
| 28 |
``logits``: [B, T, V]; ``labels``: [B, T] with -100 mask (gold at
|
| 29 |
the answer index). HF shift: predict token t from logits[:, t-1].
|
| 30 |
"""
|
| 31 |
-
# Predict position t from logits at t-1.
|
| 32 |
shift_logits = logits[:, :-1, :].contiguous()
|
| 33 |
shift_labels = labels[:, 1:].contiguous()
|
| 34 |
batch = shift_logits.size(0)
|
|
@@ -36,11 +45,9 @@ def code_token_loss(
|
|
| 36 |
weights: list[torch.Tensor] = []
|
| 37 |
|
| 38 |
for b in range(batch):
|
| 39 |
-
|
| 40 |
-
if
|
| 41 |
continue
|
| 42 |
-
# One supervised answer token per row.
|
| 43 |
-
p = int(pos[0].item())
|
| 44 |
k = int(n_codes[b].item())
|
| 45 |
if k < 1:
|
| 46 |
continue
|
|
@@ -52,7 +59,6 @@ def code_token_loss(
|
|
| 52 |
log_p = F.log_softmax(code_logits, dim=-1)
|
| 53 |
loss_b = -(target * log_p).sum()
|
| 54 |
else:
|
| 55 |
-
# Hard label = index of gold among codes (one-hot soft).
|
| 56 |
gold_idx = int(soft_labels[b, :k].argmax().item())
|
| 57 |
loss_b = F.cross_entropy(
|
| 58 |
code_logits.unsqueeze(0),
|
|
@@ -77,6 +83,49 @@ def code_token_loss(
|
|
| 77 |
return (stacked * w).sum() / w.sum().clamp_min(1e-8)
|
| 78 |
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
class CodeTokenTrainer:
|
| 81 |
"""Lazy wrapper — real subclass built on first instantiate.
|
| 82 |
|
|
@@ -105,11 +154,17 @@ def _build_trainer_class() -> type:
|
|
| 105 |
*args: Any,
|
| 106 |
use_soft_ce: bool = False,
|
| 107 |
train_sampler: Any | None = None,
|
|
|
|
|
|
|
|
|
|
| 108 |
**kwargs: Any,
|
| 109 |
) -> None:
|
| 110 |
self._custom_train_sampler = train_sampler
|
| 111 |
super().__init__(*args, **kwargs)
|
| 112 |
self.use_soft_ce = bool(use_soft_ce)
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
def _get_train_sampler(self, train_dataset: Any = None):
|
| 115 |
if self._custom_train_sampler is not None:
|
|
@@ -130,9 +185,15 @@ def _build_trainer_class() -> type:
|
|
| 130 |
n_codes = inputs.pop("n_codes")
|
| 131 |
soft_labels = inputs.pop("soft_labels")
|
| 132 |
sample_weight = inputs.pop("sample_weight", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
inputs.pop("label_id", None)
|
| 134 |
inputs.pop("has_soft", None)
|
| 135 |
-
inputs.pop("is_noul", None)
|
| 136 |
|
| 137 |
labels = inputs.get("labels")
|
| 138 |
outputs = model(**inputs)
|
|
@@ -145,6 +206,86 @@ def _build_trainer_class() -> type:
|
|
| 145 |
use_soft=self.use_soft_ce,
|
| 146 |
sample_weight=sample_weight,
|
| 147 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
return (loss, outputs) if return_outputs else loss
|
| 149 |
|
| 150 |
_TRAINER_CLS = _CodeTokenTrainer
|
|
|
|
| 3 |
Full-vocab next-token CE left relative Y/N logits dominated by the
|
| 4 |
base prior (eval collapse: all Noul → Y). Scoring only code tokens
|
| 5 |
aligns train with infer.
|
| 6 |
+
|
| 7 |
+
Also: Noul consistency (P(yes|Q)+P(yes|¬Q)→1) and optional binary
|
| 8 |
+
head CE on last-token hidden.
|
| 9 |
"""
|
| 10 |
|
| 11 |
from __future__ import annotations
|
|
|
|
| 16 |
import torch.nn.functional as F
|
| 17 |
|
| 18 |
|
| 19 |
+
def _answer_pos(shift_labels: torch.Tensor) -> int | None:
|
| 20 |
+
pos = (shift_labels != -100).nonzero(as_tuple=True)[0]
|
| 21 |
+
if len(pos) == 0:
|
| 22 |
+
return None
|
| 23 |
+
return int(pos[0].item())
|
| 24 |
+
|
| 25 |
+
|
| 26 |
def code_token_loss(
|
| 27 |
logits: torch.Tensor,
|
| 28 |
labels: torch.Tensor,
|
|
|
|
| 38 |
``logits``: [B, T, V]; ``labels``: [B, T] with -100 mask (gold at
|
| 39 |
the answer index). HF shift: predict token t from logits[:, t-1].
|
| 40 |
"""
|
|
|
|
| 41 |
shift_logits = logits[:, :-1, :].contiguous()
|
| 42 |
shift_labels = labels[:, 1:].contiguous()
|
| 43 |
batch = shift_logits.size(0)
|
|
|
|
| 45 |
weights: list[torch.Tensor] = []
|
| 46 |
|
| 47 |
for b in range(batch):
|
| 48 |
+
p = _answer_pos(shift_labels[b])
|
| 49 |
+
if p is None:
|
| 50 |
continue
|
|
|
|
|
|
|
| 51 |
k = int(n_codes[b].item())
|
| 52 |
if k < 1:
|
| 53 |
continue
|
|
|
|
| 59 |
log_p = F.log_softmax(code_logits, dim=-1)
|
| 60 |
loss_b = -(target * log_p).sum()
|
| 61 |
else:
|
|
|
|
| 62 |
gold_idx = int(soft_labels[b, :k].argmax().item())
|
| 63 |
loss_b = F.cross_entropy(
|
| 64 |
code_logits.unsqueeze(0),
|
|
|
|
| 83 |
return (stacked * w).sum() / w.sum().clamp_min(1e-8)
|
| 84 |
|
| 85 |
|
| 86 |
+
def code_yes_probs(
|
| 87 |
+
logits: torch.Tensor,
|
| 88 |
+
labels: torch.Tensor,
|
| 89 |
+
code_token_ids: torch.Tensor,
|
| 90 |
+
n_codes: torch.Tensor,
|
| 91 |
+
yes_idx: torch.Tensor,
|
| 92 |
+
) -> torch.Tensor:
|
| 93 |
+
"""P(yes) from constrained softmax; -1 where not applicable."""
|
| 94 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 95 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 96 |
+
batch = shift_logits.size(0)
|
| 97 |
+
out = torch.full(
|
| 98 |
+
(batch,), -1.0, device=logits.device, dtype=logits.dtype
|
| 99 |
+
)
|
| 100 |
+
for b in range(batch):
|
| 101 |
+
yi = int(yes_idx[b].item()) if yes_idx is not None else -1
|
| 102 |
+
if yi < 0:
|
| 103 |
+
continue
|
| 104 |
+
p = _answer_pos(shift_labels[b])
|
| 105 |
+
if p is None:
|
| 106 |
+
continue
|
| 107 |
+
k = int(n_codes[b].item())
|
| 108 |
+
if k < 2 or yi >= k:
|
| 109 |
+
continue
|
| 110 |
+
ids = code_token_ids[b, :k].long()
|
| 111 |
+
probs = F.softmax(shift_logits[b, p, ids].float(), dim=-1)
|
| 112 |
+
out[b] = probs[yi]
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def consistency_loss(
|
| 117 |
+
p_yes_q: torch.Tensor,
|
| 118 |
+
p_yes_neg: torch.Tensor,
|
| 119 |
+
has_neg: torch.Tensor,
|
| 120 |
+
) -> torch.Tensor:
|
| 121 |
+
"""(P(yes|Q) + P(yes|¬Q) − 1)^2 on rows with a negation twin."""
|
| 122 |
+
mask = (has_neg > 0) & (p_yes_q >= 0) & (p_yes_neg >= 0)
|
| 123 |
+
if not mask.any():
|
| 124 |
+
return p_yes_q.sum() * 0.0
|
| 125 |
+
diff = p_yes_q[mask] + p_yes_neg[mask] - 1.0
|
| 126 |
+
return (diff * diff).mean()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
class CodeTokenTrainer:
|
| 130 |
"""Lazy wrapper — real subclass built on first instantiate.
|
| 131 |
|
|
|
|
| 154 |
*args: Any,
|
| 155 |
use_soft_ce: bool = False,
|
| 156 |
train_sampler: Any | None = None,
|
| 157 |
+
consistency_weight: float = 0.0,
|
| 158 |
+
binary_head: Any | None = None,
|
| 159 |
+
binary_head_weight: float = 0.0,
|
| 160 |
**kwargs: Any,
|
| 161 |
) -> None:
|
| 162 |
self._custom_train_sampler = train_sampler
|
| 163 |
super().__init__(*args, **kwargs)
|
| 164 |
self.use_soft_ce = bool(use_soft_ce)
|
| 165 |
+
self.consistency_weight = float(consistency_weight)
|
| 166 |
+
self.binary_head = binary_head
|
| 167 |
+
self.binary_head_weight = float(binary_head_weight)
|
| 168 |
|
| 169 |
def _get_train_sampler(self, train_dataset: Any = None):
|
| 170 |
if self._custom_train_sampler is not None:
|
|
|
|
| 185 |
n_codes = inputs.pop("n_codes")
|
| 186 |
soft_labels = inputs.pop("soft_labels")
|
| 187 |
sample_weight = inputs.pop("sample_weight", None)
|
| 188 |
+
yes_idx = inputs.pop("yes_idx", None)
|
| 189 |
+
has_neg = inputs.pop("has_neg", None)
|
| 190 |
+
neg_input_ids = inputs.pop("neg_input_ids", None)
|
| 191 |
+
neg_attention = inputs.pop("neg_attention_mask", None)
|
| 192 |
+
neg_labels = inputs.pop("neg_labels", None)
|
| 193 |
+
neg_soft = inputs.pop("neg_soft_labels", None)
|
| 194 |
inputs.pop("label_id", None)
|
| 195 |
inputs.pop("has_soft", None)
|
| 196 |
+
is_noul = inputs.pop("is_noul", None)
|
| 197 |
|
| 198 |
labels = inputs.get("labels")
|
| 199 |
outputs = model(**inputs)
|
|
|
|
| 206 |
use_soft=self.use_soft_ce,
|
| 207 |
sample_weight=sample_weight,
|
| 208 |
)
|
| 209 |
+
|
| 210 |
+
# Negation consistency + CE on ¬Q (dual forward).
|
| 211 |
+
if (
|
| 212 |
+
self.consistency_weight > 0
|
| 213 |
+
and neg_input_ids is not None
|
| 214 |
+
and has_neg is not None
|
| 215 |
+
and (has_neg > 0).any()
|
| 216 |
+
):
|
| 217 |
+
neg_out = model(
|
| 218 |
+
input_ids=neg_input_ids,
|
| 219 |
+
attention_mask=neg_attention,
|
| 220 |
+
)
|
| 221 |
+
loss = loss + code_token_loss(
|
| 222 |
+
neg_out.logits,
|
| 223 |
+
neg_labels,
|
| 224 |
+
code_token_ids,
|
| 225 |
+
n_codes,
|
| 226 |
+
neg_soft if neg_soft is not None else soft_labels,
|
| 227 |
+
use_soft=self.use_soft_ce,
|
| 228 |
+
sample_weight=sample_weight,
|
| 229 |
+
)
|
| 230 |
+
if yes_idx is not None:
|
| 231 |
+
p_q = code_yes_probs(
|
| 232 |
+
outputs.logits,
|
| 233 |
+
labels,
|
| 234 |
+
code_token_ids,
|
| 235 |
+
n_codes,
|
| 236 |
+
yes_idx,
|
| 237 |
+
)
|
| 238 |
+
p_n = code_yes_probs(
|
| 239 |
+
neg_out.logits,
|
| 240 |
+
neg_labels,
|
| 241 |
+
code_token_ids,
|
| 242 |
+
n_codes,
|
| 243 |
+
yes_idx,
|
| 244 |
+
)
|
| 245 |
+
cons = consistency_loss(p_q, p_n, has_neg)
|
| 246 |
+
loss = loss + self.consistency_weight * cons
|
| 247 |
+
|
| 248 |
+
# Optional dedicated binary head on last non-pad hidden.
|
| 249 |
+
if (
|
| 250 |
+
self.binary_head is not None
|
| 251 |
+
and self.binary_head_weight > 0
|
| 252 |
+
and is_noul is not None
|
| 253 |
+
and yes_idx is not None
|
| 254 |
+
):
|
| 255 |
+
hidden = outputs.hidden_states
|
| 256 |
+
if hidden is None:
|
| 257 |
+
# Re-forward with hidden states if model omitted them.
|
| 258 |
+
outputs2 = model(
|
| 259 |
+
**{
|
| 260 |
+
k: v
|
| 261 |
+
for k, v in inputs.items()
|
| 262 |
+
if k
|
| 263 |
+
in ("input_ids", "attention_mask")
|
| 264 |
+
},
|
| 265 |
+
output_hidden_states=True,
|
| 266 |
+
)
|
| 267 |
+
hidden = outputs2.hidden_states
|
| 268 |
+
if hidden is not None:
|
| 269 |
+
h = hidden[-1]
|
| 270 |
+
attn = inputs["attention_mask"]
|
| 271 |
+
# Last non-pad index per row.
|
| 272 |
+
lengths = attn.long().sum(dim=1) - 1
|
| 273 |
+
b_idx = torch.arange(h.size(0), device=h.device)
|
| 274 |
+
pooled = h[b_idx, lengths.clamp_min(0)]
|
| 275 |
+
logits2 = self.binary_head(pooled)
|
| 276 |
+
# Target: 1 if gold is yes-code else 0.
|
| 277 |
+
gold = soft_labels.argmax(dim=-1)
|
| 278 |
+
target = (gold == yes_idx.clamp_min(0)).long()
|
| 279 |
+
# Only noul rows.
|
| 280 |
+
mask = is_noul > 0
|
| 281 |
+
if mask.any():
|
| 282 |
+
bce = F.cross_entropy(
|
| 283 |
+
logits2[mask], target[mask]
|
| 284 |
+
)
|
| 285 |
+
loss = (
|
| 286 |
+
loss + self.binary_head_weight * bce
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
return (loss, outputs) if return_outputs else loss
|
| 290 |
|
| 291 |
_TRAINER_CLS = _CodeTokenTrainer
|
oss_jev_train/dataset.py
CHANGED
|
@@ -58,6 +58,13 @@ def assert_single_token_codes(
|
|
| 58 |
)
|
| 59 |
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
def noul_balance_weights(
|
| 62 |
examples: list[DecisionExample],
|
| 63 |
*,
|
|
@@ -68,16 +75,17 @@ def noul_balance_weights(
|
|
| 68 |
v0.1.1 equal Y/N mass *upweighted Y* (train is already ~65% N) and
|
| 69 |
eval stayed all-Y. v0.1.2 defaults to heavy N oversampling (~80% N
|
| 70 |
mass among noul ≈ 4:1 N:Y). Non-noul rows keep weight 1.0.
|
|
|
|
| 71 |
"""
|
| 72 |
n_y = sum(
|
| 73 |
1
|
| 74 |
for ex in examples
|
| 75 |
-
if ex.primitive == "noul" and ex
|
| 76 |
)
|
| 77 |
n_n = sum(
|
| 78 |
1
|
| 79 |
for ex in examples
|
| 80 |
-
if ex.primitive == "noul" and
|
| 81 |
)
|
| 82 |
n_y = max(n_y, 1)
|
| 83 |
n_n = max(n_n, 1)
|
|
@@ -90,7 +98,7 @@ def noul_balance_weights(
|
|
| 90 |
for ex in examples:
|
| 91 |
if ex.primitive != "noul":
|
| 92 |
out.append(1.0)
|
| 93 |
-
elif ex
|
| 94 |
out.append(float(w_y))
|
| 95 |
else:
|
| 96 |
out.append(float(w_n))
|
|
@@ -137,6 +145,7 @@ class OneTokenDataset(Dataset):
|
|
| 137 |
noul_hard_ce: bool = True,
|
| 138 |
noul_loss_weight: float = 2.0,
|
| 139 |
noul_n_sample_weight: float = 2.0,
|
|
|
|
| 140 |
) -> None:
|
| 141 |
self.examples = examples
|
| 142 |
self.tokenizer = tokenizer
|
|
@@ -147,6 +156,8 @@ class OneTokenDataset(Dataset):
|
|
| 147 |
self.noul_hard_ce = bool(noul_hard_ce)
|
| 148 |
self.noul_loss_weight = float(noul_loss_weight)
|
| 149 |
self.noul_n_sample_weight = float(noul_n_sample_weight)
|
|
|
|
|
|
|
| 150 |
if tokenizer.pad_token_id is None:
|
| 151 |
tokenizer.pad_token = tokenizer.eos_token
|
| 152 |
# Cache code → token id (verified single-token upstream).
|
|
@@ -161,13 +172,19 @@ class OneTokenDataset(Dataset):
|
|
| 161 |
def __len__(self) -> int:
|
| 162 |
return len(self.examples)
|
| 163 |
|
| 164 |
-
def
|
| 165 |
import torch
|
| 166 |
|
| 167 |
-
ex = self.examples[idx]
|
| 168 |
prompt = format_prompt(ex)
|
| 169 |
-
#
|
| 170 |
full = prompt + ex.gold_code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
enc = self.tokenizer(
|
| 172 |
full,
|
| 173 |
truncation=True,
|
|
@@ -179,11 +196,15 @@ class OneTokenDataset(Dataset):
|
|
| 179 |
attention = enc["attention_mask"].squeeze(0)
|
| 180 |
labels = input_ids.clone()
|
| 181 |
labels[attention == 0] = -100
|
| 182 |
-
# Mask everything before the last non-pad token (the gold code).
|
| 183 |
nonzero = (attention == 1).nonzero(as_tuple=True)[0]
|
| 184 |
if len(nonzero) == 0:
|
| 185 |
raise ValueError(f"empty encoding for {ex.id}")
|
| 186 |
last = int(nonzero[-1].item())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
labels[:last] = -100
|
| 188 |
|
| 189 |
n = len(ex.codes)
|
|
@@ -193,8 +214,6 @@ class OneTokenDataset(Dataset):
|
|
| 193 |
for i, code in enumerate(ex.codes):
|
| 194 |
code_token_ids[i] = self._code_id[code]
|
| 195 |
|
| 196 |
-
# Noul: prefer hard one-hot (teacher soft still puts ~0.13 on Y
|
| 197 |
-
# for N-gold; that softens the N gradient under Y base prior).
|
| 198 |
use_soft_row = self.use_soft and not (
|
| 199 |
ex.primitive == "noul" and self.noul_hard_ce
|
| 200 |
)
|
|
@@ -208,15 +227,19 @@ class OneTokenDataset(Dataset):
|
|
| 208 |
soft_t[ex.label_id] = 1.0
|
| 209 |
has_soft = 0
|
| 210 |
|
| 211 |
-
|
|
|
|
| 212 |
if ex.primitive == "noul":
|
|
|
|
| 213 |
base = self.noul_loss_weight
|
| 214 |
-
if ex.gold_code ==
|
| 215 |
sample_weight = base * self.noul_n_sample_weight
|
| 216 |
else:
|
| 217 |
sample_weight = base
|
|
|
|
| 218 |
else:
|
| 219 |
sample_weight = 1.0
|
|
|
|
| 220 |
|
| 221 |
return {
|
| 222 |
"input_ids": input_ids,
|
|
@@ -229,8 +252,43 @@ class OneTokenDataset(Dataset):
|
|
| 229 |
"has_soft": has_soft,
|
| 230 |
"sample_weight": float(sample_weight),
|
| 231 |
"is_noul": 1 if ex.primitive == "noul" else 0,
|
|
|
|
| 232 |
}
|
| 233 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
class ClassificationDataset(Dataset):
|
| 236 |
"""Optional ablation: linear head over last hidden state."""
|
|
|
|
| 58 |
)
|
| 59 |
|
| 60 |
|
| 61 |
+
def _noul_is_yes_gold(ex: DecisionExample) -> bool:
|
| 62 |
+
from .noul_augment import _yes_no_codes
|
| 63 |
+
|
| 64 |
+
yes_c, _ = _yes_no_codes(ex)
|
| 65 |
+
return ex.gold_code == yes_c
|
| 66 |
+
|
| 67 |
+
|
| 68 |
def noul_balance_weights(
|
| 69 |
examples: list[DecisionExample],
|
| 70 |
*,
|
|
|
|
| 75 |
v0.1.1 equal Y/N mass *upweighted Y* (train is already ~65% N) and
|
| 76 |
eval stayed all-Y. v0.1.2 defaults to heavy N oversampling (~80% N
|
| 77 |
mass among noul ≈ 4:1 N:Y). Non-noul rows keep weight 1.0.
|
| 78 |
+
Works with randomized yes/no codes (not only literal Y/N).
|
| 79 |
"""
|
| 80 |
n_y = sum(
|
| 81 |
1
|
| 82 |
for ex in examples
|
| 83 |
+
if ex.primitive == "noul" and _noul_is_yes_gold(ex)
|
| 84 |
)
|
| 85 |
n_n = sum(
|
| 86 |
1
|
| 87 |
for ex in examples
|
| 88 |
+
if ex.primitive == "noul" and not _noul_is_yes_gold(ex)
|
| 89 |
)
|
| 90 |
n_y = max(n_y, 1)
|
| 91 |
n_n = max(n_n, 1)
|
|
|
|
| 98 |
for ex in examples:
|
| 99 |
if ex.primitive != "noul":
|
| 100 |
out.append(1.0)
|
| 101 |
+
elif _noul_is_yes_gold(ex):
|
| 102 |
out.append(float(w_y))
|
| 103 |
else:
|
| 104 |
out.append(float(w_n))
|
|
|
|
| 145 |
noul_hard_ce: bool = True,
|
| 146 |
noul_loss_weight: float = 2.0,
|
| 147 |
noul_n_sample_weight: float = 2.0,
|
| 148 |
+
noul_consistency: bool = False,
|
| 149 |
) -> None:
|
| 150 |
self.examples = examples
|
| 151 |
self.tokenizer = tokenizer
|
|
|
|
| 156 |
self.noul_hard_ce = bool(noul_hard_ce)
|
| 157 |
self.noul_loss_weight = float(noul_loss_weight)
|
| 158 |
self.noul_n_sample_weight = float(noul_n_sample_weight)
|
| 159 |
+
# Dual-forward consistency on Q and ¬Q (same item).
|
| 160 |
+
self.noul_consistency = bool(noul_consistency)
|
| 161 |
if tokenizer.pad_token_id is None:
|
| 162 |
tokenizer.pad_token = tokenizer.eos_token
|
| 163 |
# Cache code → token id (verified single-token upstream).
|
|
|
|
| 172 |
def __len__(self) -> int:
|
| 173 |
return len(self.examples)
|
| 174 |
|
| 175 |
+
def _encode_supervised(self, ex: "DecisionExample") -> dict[str, Any]:
|
| 176 |
import torch
|
| 177 |
|
|
|
|
| 178 |
prompt = format_prompt(ex)
|
| 179 |
+
# Prompt must end so gold is its own token (see prompts.Answer:\n).
|
| 180 |
full = prompt + ex.gold_code
|
| 181 |
+
gold_ids = self.tokenizer.encode(
|
| 182 |
+
ex.gold_code, add_special_tokens=False
|
| 183 |
+
)
|
| 184 |
+
if len(gold_ids) != 1:
|
| 185 |
+
raise ValueError(
|
| 186 |
+
f"{ex.id}: gold {ex.gold_code!r} → {gold_ids}"
|
| 187 |
+
)
|
| 188 |
enc = self.tokenizer(
|
| 189 |
full,
|
| 190 |
truncation=True,
|
|
|
|
| 196 |
attention = enc["attention_mask"].squeeze(0)
|
| 197 |
labels = input_ids.clone()
|
| 198 |
labels[attention == 0] = -100
|
|
|
|
| 199 |
nonzero = (attention == 1).nonzero(as_tuple=True)[0]
|
| 200 |
if len(nonzero) == 0:
|
| 201 |
raise ValueError(f"empty encoding for {ex.id}")
|
| 202 |
last = int(nonzero[-1].item())
|
| 203 |
+
if int(input_ids[last].item()) != int(gold_ids[0]):
|
| 204 |
+
raise ValueError(
|
| 205 |
+
f"{ex.id}: last token {int(input_ids[last])} != "
|
| 206 |
+
f"gold id {gold_ids[0]} (prompt/code glue bug)"
|
| 207 |
+
)
|
| 208 |
labels[:last] = -100
|
| 209 |
|
| 210 |
n = len(ex.codes)
|
|
|
|
| 214 |
for i, code in enumerate(ex.codes):
|
| 215 |
code_token_ids[i] = self._code_id[code]
|
| 216 |
|
|
|
|
|
|
|
| 217 |
use_soft_row = self.use_soft and not (
|
| 218 |
ex.primitive == "noul" and self.noul_hard_ce
|
| 219 |
)
|
|
|
|
| 227 |
soft_t[ex.label_id] = 1.0
|
| 228 |
has_soft = 0
|
| 229 |
|
| 230 |
+
from .noul_augment import _yes_no_codes, noul_yes_index
|
| 231 |
+
|
| 232 |
if ex.primitive == "noul":
|
| 233 |
+
yes_c, no_c = _yes_no_codes(ex)
|
| 234 |
base = self.noul_loss_weight
|
| 235 |
+
if ex.gold_code == no_c:
|
| 236 |
sample_weight = base * self.noul_n_sample_weight
|
| 237 |
else:
|
| 238 |
sample_weight = base
|
| 239 |
+
yes_idx = int(noul_yes_index(ex))
|
| 240 |
else:
|
| 241 |
sample_weight = 1.0
|
| 242 |
+
yes_idx = -1
|
| 243 |
|
| 244 |
return {
|
| 245 |
"input_ids": input_ids,
|
|
|
|
| 252 |
"has_soft": has_soft,
|
| 253 |
"sample_weight": float(sample_weight),
|
| 254 |
"is_noul": 1 if ex.primitive == "noul" else 0,
|
| 255 |
+
"yes_idx": yes_idx,
|
| 256 |
}
|
| 257 |
|
| 258 |
+
def __getitem__(self, idx: int) -> dict[str, Any]:
|
| 259 |
+
import torch
|
| 260 |
+
|
| 261 |
+
from .noul_augment import make_negated_noul
|
| 262 |
+
|
| 263 |
+
ex = self.examples[idx]
|
| 264 |
+
item = self._encode_supervised(ex)
|
| 265 |
+
|
| 266 |
+
# Consistency: attach ¬Q tensors on non-negated noul rows only
|
| 267 |
+
# (twins already in the expanded set skip dual-forward).
|
| 268 |
+
already_neg = bool((ex.meta or {}).get("noul_negated"))
|
| 269 |
+
if (
|
| 270 |
+
self.noul_consistency
|
| 271 |
+
and ex.primitive == "noul"
|
| 272 |
+
and not already_neg
|
| 273 |
+
):
|
| 274 |
+
twin = make_negated_noul(ex)
|
| 275 |
+
neg = self._encode_supervised(twin)
|
| 276 |
+
item["neg_input_ids"] = neg["input_ids"]
|
| 277 |
+
item["neg_attention_mask"] = neg["attention_mask"]
|
| 278 |
+
item["neg_labels"] = neg["labels"]
|
| 279 |
+
item["neg_soft_labels"] = neg["soft_labels"]
|
| 280 |
+
item["has_neg"] = 1
|
| 281 |
+
else:
|
| 282 |
+
# Pad-shaped placeholders so default collator stacks.
|
| 283 |
+
z = item["input_ids"]
|
| 284 |
+
item["neg_input_ids"] = torch.zeros_like(z)
|
| 285 |
+
item["neg_attention_mask"] = torch.zeros_like(z)
|
| 286 |
+
item["neg_labels"] = torch.full_like(z, -100)
|
| 287 |
+
item["neg_soft_labels"] = torch.zeros_like(item["soft_labels"])
|
| 288 |
+
item["has_neg"] = 0
|
| 289 |
+
|
| 290 |
+
return item
|
| 291 |
+
|
| 292 |
|
| 293 |
class ClassificationDataset(Dataset):
|
| 294 |
"""Optional ablation: linear head over last hidden state."""
|
oss_jev_train/export_ckpt.py
CHANGED
|
@@ -20,6 +20,10 @@ def write_checkpoint_sidecar(
|
|
| 20 |
noul_logit_bias_n: float | None = None,
|
| 21 |
noul_n_frac: float | None = None,
|
| 22 |
noul_hard_ce: bool | None = None,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
) -> Path:
|
| 24 |
"""Write ``decision_head.json`` next to HF weights.
|
| 25 |
|
|
@@ -65,6 +69,16 @@ def write_checkpoint_sidecar(
|
|
| 65 |
meta["noul_n_frac"] = float(noul_n_frac)
|
| 66 |
if noul_hard_ce is not None:
|
| 67 |
meta["noul_hard_ce"] = bool(noul_hard_ce)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
path = ckpt_dir / "decision_head.json"
|
| 69 |
path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
|
| 70 |
|
|
|
|
| 20 |
noul_logit_bias_n: float | None = None,
|
| 21 |
noul_n_frac: float | None = None,
|
| 22 |
noul_hard_ce: bool | None = None,
|
| 23 |
+
noul_random_codes: bool | None = None,
|
| 24 |
+
noul_negation_pairs: bool | None = None,
|
| 25 |
+
noul_consistency_weight: float | None = None,
|
| 26 |
+
noul_binary_head: bool | None = None,
|
| 27 |
) -> Path:
|
| 28 |
"""Write ``decision_head.json`` next to HF weights.
|
| 29 |
|
|
|
|
| 69 |
meta["noul_n_frac"] = float(noul_n_frac)
|
| 70 |
if noul_hard_ce is not None:
|
| 71 |
meta["noul_hard_ce"] = bool(noul_hard_ce)
|
| 72 |
+
if noul_random_codes is not None:
|
| 73 |
+
meta["noul_random_codes"] = bool(noul_random_codes)
|
| 74 |
+
if noul_negation_pairs is not None:
|
| 75 |
+
meta["noul_negation_pairs"] = bool(noul_negation_pairs)
|
| 76 |
+
if noul_consistency_weight is not None:
|
| 77 |
+
meta["noul_consistency_weight"] = float(
|
| 78 |
+
noul_consistency_weight
|
| 79 |
+
)
|
| 80 |
+
if noul_binary_head is not None:
|
| 81 |
+
meta["noul_binary_head"] = bool(noul_binary_head)
|
| 82 |
path = ckpt_dir / "decision_head.json"
|
| 83 |
path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
|
| 84 |
|
oss_jev_train/noul_augment.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Noul train augments: negation twins + randomized answer codes.
|
| 2 |
+
|
| 3 |
+
Attack 1 — negation: for Q with P(yes)=p, build ¬Q with teacher 1-p and
|
| 4 |
+
flipped gold. Optional consistency: (P(yes|Q)+P(yes|¬Q)-1)^2 → 0.
|
| 5 |
+
|
| 6 |
+
Attack 2 — random codes: per-example single-token yes/no codes from a
|
| 7 |
+
letter pool (not Y/N) so CE cannot ride the base Y-prior.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import copy
|
| 13 |
+
import random
|
| 14 |
+
import re
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
from .schema import DecisionExample
|
| 18 |
+
|
| 19 |
+
# Letters that are single tokens on Qwen2.5; exclude Y/N (prior) and O/I
|
| 20 |
+
# (digit-like confusion). Verified at assert_single_token_codes time.
|
| 21 |
+
NOUL_CODE_POOL = tuple("ABCDEFGHJKLMNPQRSTUVWXZ")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def negate_instructions(instructions: Any) -> Any:
|
| 25 |
+
"""Wrap instructions so the yes-answer means the opposite claim."""
|
| 26 |
+
if isinstance(instructions, str):
|
| 27 |
+
text = instructions.strip()
|
| 28 |
+
if re.match(r"(?i)^is the opposite true of:", text):
|
| 29 |
+
return text
|
| 30 |
+
return f"Is the opposite true of: {text}"
|
| 31 |
+
return {
|
| 32 |
+
"negated": True,
|
| 33 |
+
"original": instructions,
|
| 34 |
+
"ask": "Answer yes only if the original claim is false.",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _yes_no_codes(ex: DecisionExample) -> tuple[str, str]:
|
| 39 |
+
"""Return (yes_code, no_code) from code_to_key / canonical Y,N."""
|
| 40 |
+
yes_c = no_c = None
|
| 41 |
+
for c in ex.codes:
|
| 42 |
+
key = str(ex.code_to_key.get(c, "")).lower()
|
| 43 |
+
if key in ("true", "yes", "y"):
|
| 44 |
+
yes_c = c
|
| 45 |
+
elif key in ("false", "no", "n"):
|
| 46 |
+
no_c = c
|
| 47 |
+
if yes_c is None or no_c is None:
|
| 48 |
+
if set(ex.codes) == {"Y", "N"}:
|
| 49 |
+
return "Y", "N"
|
| 50 |
+
if len(ex.codes) == 2:
|
| 51 |
+
return ex.codes[0], ex.codes[1]
|
| 52 |
+
raise ValueError(f"{ex.id}: cannot resolve yes/no codes")
|
| 53 |
+
return yes_c, no_c
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def make_negated_noul(ex: DecisionExample) -> DecisionExample:
|
| 57 |
+
"""Logical ¬Q: flipped gold + teacher; same answer codes as Q."""
|
| 58 |
+
if ex.primitive != "noul":
|
| 59 |
+
raise ValueError(f"{ex.id}: negate only for noul")
|
| 60 |
+
yes_c, no_c = _yes_no_codes(ex)
|
| 61 |
+
twin = copy.deepcopy(ex)
|
| 62 |
+
twin.id = f"{ex.id}::neg"
|
| 63 |
+
twin.instructions = negate_instructions(ex.instructions)
|
| 64 |
+
twin.prompt = None
|
| 65 |
+
# Flip gold meaning.
|
| 66 |
+
twin.gold_code = no_c if ex.gold_code == yes_c else yes_c
|
| 67 |
+
teacher = dict(twin.teacher or {})
|
| 68 |
+
p_yes = None
|
| 69 |
+
if "noul" in teacher:
|
| 70 |
+
p_yes = 1.0 - float(teacher["noul"])
|
| 71 |
+
teacher["noul"] = p_yes
|
| 72 |
+
probs = teacher.get("probabilities")
|
| 73 |
+
if p_yes is None and isinstance(probs, dict) and probs:
|
| 74 |
+
for k, v in probs.items():
|
| 75 |
+
kl = str(k).lower()
|
| 76 |
+
if kl in ("true", "yes", "y") or k == yes_c:
|
| 77 |
+
p_yes = 1.0 - float(v)
|
| 78 |
+
break
|
| 79 |
+
if p_yes is not None:
|
| 80 |
+
teacher["noul"] = float(p_yes)
|
| 81 |
+
teacher["probabilities"] = {
|
| 82 |
+
"true": float(p_yes),
|
| 83 |
+
"false": 1.0 - float(p_yes),
|
| 84 |
+
yes_c: float(p_yes),
|
| 85 |
+
no_c: 1.0 - float(p_yes),
|
| 86 |
+
}
|
| 87 |
+
twin.teacher = teacher
|
| 88 |
+
twin.meta = dict(twin.meta or {})
|
| 89 |
+
twin.meta["noul_negated"] = True
|
| 90 |
+
twin.meta["noul_pair_id"] = ex.meta.get("noul_pair_id") or ex.id
|
| 91 |
+
# Flip criteria true/false text if present.
|
| 92 |
+
if isinstance(twin.criteria, dict):
|
| 93 |
+
crit = dict(twin.criteria)
|
| 94 |
+
if "true" in crit or "false" in crit:
|
| 95 |
+
t, f = crit.get("true"), crit.get("false")
|
| 96 |
+
if t is not None:
|
| 97 |
+
crit["false"] = t
|
| 98 |
+
if f is not None:
|
| 99 |
+
crit["true"] = f
|
| 100 |
+
twin.criteria = crit
|
| 101 |
+
twin.validate()
|
| 102 |
+
return twin
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def randomize_noul_codes(
|
| 106 |
+
ex: DecisionExample,
|
| 107 |
+
rng: random.Random,
|
| 108 |
+
*,
|
| 109 |
+
pool: tuple[str, ...] = NOUL_CODE_POOL,
|
| 110 |
+
) -> DecisionExample:
|
| 111 |
+
"""Replace Y/N with a random single-token code pair (yes, no)."""
|
| 112 |
+
if ex.primitive != "noul":
|
| 113 |
+
return ex
|
| 114 |
+
yes_c, no_c = _yes_no_codes(ex)
|
| 115 |
+
pick = rng.sample(list(pool), 2)
|
| 116 |
+
new_yes, new_no = pick[0], pick[1]
|
| 117 |
+
out = copy.deepcopy(ex)
|
| 118 |
+
out.codes = [new_yes, new_no]
|
| 119 |
+
out.code_to_key = {new_yes: "true", new_no: "false"}
|
| 120 |
+
out.gold_code = new_yes if ex.gold_code == yes_c else new_no
|
| 121 |
+
out.prompt = None
|
| 122 |
+
# Remap teacher probs keyed by Y/N or true/false onto new codes.
|
| 123 |
+
teacher = dict(out.teacher or {})
|
| 124 |
+
probs = teacher.get("probabilities")
|
| 125 |
+
if isinstance(probs, dict) and probs:
|
| 126 |
+
p_yes = None
|
| 127 |
+
for k, v in probs.items():
|
| 128 |
+
kl = str(k).lower()
|
| 129 |
+
if kl in ("true", "yes", "y") or k == yes_c:
|
| 130 |
+
p_yes = float(v)
|
| 131 |
+
break
|
| 132 |
+
if p_yes is None and "noul" in teacher:
|
| 133 |
+
p_yes = float(teacher["noul"])
|
| 134 |
+
if p_yes is not None:
|
| 135 |
+
teacher["probabilities"] = {
|
| 136 |
+
"true": p_yes,
|
| 137 |
+
"false": 1.0 - p_yes,
|
| 138 |
+
new_yes: p_yes,
|
| 139 |
+
new_no: 1.0 - p_yes,
|
| 140 |
+
}
|
| 141 |
+
out.teacher = teacher
|
| 142 |
+
out.meta = dict(out.meta or {})
|
| 143 |
+
out.meta["noul_random_codes"] = True
|
| 144 |
+
out.meta["noul_yes_code"] = new_yes
|
| 145 |
+
out.meta["noul_no_code"] = new_no
|
| 146 |
+
out.meta["noul_pair_id"] = out.meta.get("noul_pair_id") or ex.id
|
| 147 |
+
out.validate()
|
| 148 |
+
return out
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def apply_noul_augments(
|
| 152 |
+
examples: list[DecisionExample],
|
| 153 |
+
*,
|
| 154 |
+
random_codes: bool = False,
|
| 155 |
+
negation_pairs: bool = False,
|
| 156 |
+
seed: int = 42,
|
| 157 |
+
) -> list[DecisionExample]:
|
| 158 |
+
"""Return possibly expanded/remapped train list.
|
| 159 |
+
|
| 160 |
+
Order: randomize codes on originals first (shared codes for any twin),
|
| 161 |
+
then optionally append negated twins.
|
| 162 |
+
"""
|
| 163 |
+
rng = random.Random(int(seed))
|
| 164 |
+
out: list[DecisionExample] = []
|
| 165 |
+
twins: list[DecisionExample] = []
|
| 166 |
+
for ex in examples:
|
| 167 |
+
row = ex
|
| 168 |
+
if ex.primitive == "noul":
|
| 169 |
+
row = copy.deepcopy(ex)
|
| 170 |
+
row.meta = dict(row.meta or {})
|
| 171 |
+
row.meta["noul_pair_id"] = ex.id
|
| 172 |
+
if random_codes:
|
| 173 |
+
row = randomize_noul_codes(row, rng)
|
| 174 |
+
if negation_pairs:
|
| 175 |
+
twins.append(make_negated_noul(row))
|
| 176 |
+
out.append(row)
|
| 177 |
+
if negation_pairs:
|
| 178 |
+
out.extend(twins)
|
| 179 |
+
return out
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def noul_yes_index(ex: DecisionExample) -> int:
|
| 183 |
+
yes_c, _ = _yes_no_codes(ex)
|
| 184 |
+
return ex.codes.index(yes_c)
|
oss_jev_train/prompts.py
CHANGED
|
@@ -28,13 +28,30 @@ def _criteria_block(ex: DecisionExample) -> str:
|
|
| 28 |
if isinstance(criteria, dict):
|
| 29 |
true_desc = str(criteria.get("true", true_desc))
|
| 30 |
false_desc = str(criteria.get("false", false_desc))
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
# Counter base-model yes-bias / all-Y collapse on eval.
|
| 34 |
-
# v0.1.2: forbid defaulting to Y (v0.1.1 caution was too soft).
|
| 35 |
lines.append(
|
| 36 |
-
"Default to
|
| 37 |
-
"evidence in the state; do not guess
|
| 38 |
)
|
| 39 |
return "\n".join(lines)
|
| 40 |
if ex.primitive == "choice" and isinstance(criteria, dict):
|
|
@@ -74,7 +91,10 @@ def format_prompt(ex: DecisionExample) -> str:
|
|
| 74 |
"### Answer",
|
| 75 |
"Reply with exactly one code character.",
|
| 76 |
f"Codes: {legend}",
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
| 78 |
]
|
| 79 |
return "\n".join(p for p in parts if p is not None)
|
| 80 |
|
|
@@ -87,7 +107,11 @@ def soft_targets(ex: DecisionExample) -> list[float] | None:
|
|
| 87 |
p_yes = float(ex.teacher["noul"])
|
| 88 |
out = []
|
| 89 |
for c in ex.codes:
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
return out
|
| 92 |
return None
|
| 93 |
out: list[float] = []
|
|
|
|
| 28 |
if isinstance(criteria, dict):
|
| 29 |
true_desc = str(criteria.get("true", true_desc))
|
| 30 |
false_desc = str(criteria.get("false", false_desc))
|
| 31 |
+
# Use actual codes (Y/N or randomized train pair).
|
| 32 |
+
for code in ex.codes:
|
| 33 |
+
key = str(ex.code_to_key.get(code, "")).lower()
|
| 34 |
+
if key in ("true", "yes", "y") or (
|
| 35 |
+
set(ex.codes) == {"Y", "N"} and code == "Y"
|
| 36 |
+
):
|
| 37 |
+
lines.append(f"{code}: yes — {true_desc}")
|
| 38 |
+
else:
|
| 39 |
+
lines.append(f"{code}: no — {false_desc}")
|
| 40 |
+
yes_c = next(
|
| 41 |
+
(
|
| 42 |
+
c
|
| 43 |
+
for c in ex.codes
|
| 44 |
+
if str(ex.code_to_key.get(c, "")).lower()
|
| 45 |
+
in ("true", "yes", "y")
|
| 46 |
+
or (set(ex.codes) == {"Y", "N"} and c == "Y")
|
| 47 |
+
),
|
| 48 |
+
ex.codes[0],
|
| 49 |
+
)
|
| 50 |
+
no_c = next((c for c in ex.codes if c != yes_c), ex.codes[-1])
|
| 51 |
# Counter base-model yes-bias / all-Y collapse on eval.
|
|
|
|
| 52 |
lines.append(
|
| 53 |
+
f"Default to {no_c}. Answer {yes_c} only with clear "
|
| 54 |
+
f"affirmative evidence in the state; do not guess {yes_c}."
|
| 55 |
)
|
| 56 |
return "\n".join(lines)
|
| 57 |
if ex.primitive == "choice" and isinstance(criteria, dict):
|
|
|
|
| 91 |
"### Answer",
|
| 92 |
"Reply with exactly one code character.",
|
| 93 |
f"Codes: {legend}",
|
| 94 |
+
# Trailing newline: Qwen merges `Answer:N` into `:N` (not code
|
| 95 |
+
# token 45). `Answer:\n` + code keeps Y/N/letters single tokens
|
| 96 |
+
# and matches infer next-token position.
|
| 97 |
+
"Answer:\n",
|
| 98 |
]
|
| 99 |
return "\n".join(p for p in parts if p is not None)
|
| 100 |
|
|
|
|
| 107 |
p_yes = float(ex.teacher["noul"])
|
| 108 |
out = []
|
| 109 |
for c in ex.codes:
|
| 110 |
+
key = str(ex.code_to_key.get(c, "")).lower()
|
| 111 |
+
is_yes = key in ("true", "yes", "y") or (
|
| 112 |
+
set(ex.codes) == {"Y", "N"} and c == "Y"
|
| 113 |
+
)
|
| 114 |
+
out.append(p_yes if is_yes else 1.0 - p_yes)
|
| 115 |
return out
|
| 116 |
return None
|
| 117 |
out: list[float] = []
|
oss_jev_train/schema.py
CHANGED
|
@@ -45,8 +45,12 @@ class DecisionExample:
|
|
| 45 |
raise ValueError(
|
| 46 |
f"{self.id}: gold_code {self.gold_code!r} not in codes"
|
| 47 |
)
|
| 48 |
-
if self.primitive == "noul"
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
if self.primitive == "choice" and len(self.codes) > 26:
|
| 51 |
raise ValueError(f"{self.id}: choice cap is 26 codes")
|
| 52 |
if self.primitive == "score" and not (2 <= len(self.codes) <= 10):
|
|
|
|
| 45 |
raise ValueError(
|
| 46 |
f"{self.id}: gold_code {self.gold_code!r} not in codes"
|
| 47 |
)
|
| 48 |
+
if self.primitive == "noul":
|
| 49 |
+
if len(self.codes) != 2 or self.codes[0] == self.codes[1]:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
f"{self.id}: noul needs exactly 2 distinct codes"
|
| 52 |
+
)
|
| 53 |
+
# Canonical Y/N or train-time random single-token pair.
|
| 54 |
if self.primitive == "choice" and len(self.codes) > 26:
|
| 55 |
raise ValueError(f"{self.id}: choice cap is 26 codes")
|
| 56 |
if self.primitive == "score" and not (2 <= len(self.codes) <= 10):
|
oss_jev_train/train.py
CHANGED
|
@@ -27,6 +27,7 @@ from .dataset import (
|
|
| 27 |
make_noul_balanced_sampler,
|
| 28 |
)
|
| 29 |
from .export_ckpt import write_checkpoint_sidecar
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
def _env(name: str, default: str | None = None) -> str | None:
|
|
@@ -236,6 +237,33 @@ def build_argparser() -> argparse.ArgumentParser:
|
|
| 236 |
default=None,
|
| 237 |
help="Subsample train JSONL to this many rows (seed from cfg)",
|
| 238 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
return p
|
| 240 |
|
| 241 |
|
|
@@ -287,6 +315,12 @@ def merge_config(args: argparse.Namespace) -> dict[str, Any]:
|
|
| 287 |
"noul_hard_ce": True,
|
| 288 |
"noul_logit_bias_n": 2.5,
|
| 289 |
"max_train_rows": None,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
}
|
| 291 |
if args.config:
|
| 292 |
with open(args.config, encoding="utf-8") as f:
|
|
@@ -333,6 +367,20 @@ def merge_config(args: argparse.Namespace) -> dict[str, Any]:
|
|
| 333 |
cfg["noul_hard_ce"] = False
|
| 334 |
if args.noul_logit_bias_n is not None:
|
| 335 |
cfg["noul_logit_bias_n"] = float(args.noul_logit_bias_n)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
env_model = _env("OSS_JEV_MODEL_ID")
|
| 337 |
if env_model and args.model_id is None and not (
|
| 338 |
args.config and cfg.get("model_id")
|
|
@@ -362,18 +410,45 @@ def check_manifest(paths: dict[str, Path]) -> dict[str, Any] | None:
|
|
| 362 |
return manifest
|
| 363 |
|
| 364 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
def run_dry(paths: dict[str, Path], cfg: dict[str, Any]) -> int:
|
| 366 |
from transformers import AutoTokenizer
|
| 367 |
|
| 368 |
examples = load_jsonl(paths["train"])
|
| 369 |
n_full = len(examples)
|
| 370 |
-
examples =
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
)
|
| 375 |
check_manifest(paths)
|
| 376 |
-
tok = AutoTokenizer.from_pretrained(
|
|
|
|
|
|
|
| 377 |
assert_single_token_codes(examples, tok)
|
| 378 |
print(
|
| 379 |
json.dumps(
|
|
@@ -385,6 +460,9 @@ def run_dry(paths: dict[str, Path], cfg: dict[str, Any]) -> int:
|
|
| 385 |
"mode": cfg["mode"],
|
| 386 |
"n_train": len(examples),
|
| 387 |
"n_train_full": n_full,
|
|
|
|
|
|
|
|
|
|
| 388 |
"max_train_rows": cfg.get("max_train_rows"),
|
| 389 |
"train_path": str(paths["train"]),
|
| 390 |
"output_dir": str(paths["output_dir"]),
|
|
@@ -401,6 +479,18 @@ def run_dry(paths: dict[str, Path], cfg: dict[str, Any]) -> int:
|
|
| 401 |
"noul_logit_bias_n": float(
|
| 402 |
cfg.get("noul_logit_bias_n", 2.5)
|
| 403 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
},
|
| 405 |
indent=2,
|
| 406 |
)
|
|
@@ -422,20 +512,20 @@ def train_one_token(
|
|
| 422 |
check_manifest(paths)
|
| 423 |
examples = load_jsonl(paths["train"])
|
| 424 |
n_full = len(examples)
|
| 425 |
-
examples =
|
| 426 |
-
examples,
|
| 427 |
-
cfg.get("max_train_rows"),
|
| 428 |
-
int(cfg.get("seed", 42)),
|
| 429 |
-
)
|
| 430 |
print(
|
| 431 |
f"train rows={len(examples)} (full={n_full} "
|
| 432 |
-
f"max_train_rows={cfg.get('max_train_rows')}
|
|
|
|
|
|
|
| 433 |
flush=True,
|
| 434 |
)
|
| 435 |
eval_examples = (
|
| 436 |
load_jsonl(paths["eval"]) if paths["eval"].is_file() else None
|
| 437 |
)
|
| 438 |
-
tok = AutoTokenizer.from_pretrained(
|
|
|
|
|
|
|
| 439 |
if tok.pad_token is None:
|
| 440 |
tok.pad_token = tok.eos_token
|
| 441 |
assert_single_token_codes(examples, tok)
|
|
@@ -448,11 +538,15 @@ def train_one_token(
|
|
| 448 |
noul_lw = float(cfg.get("noul_loss_weight", 2.0))
|
| 449 |
noul_nw = float(cfg.get("noul_n_sample_weight", 2.0))
|
| 450 |
noul_bias = float(cfg.get("noul_logit_bias_n", 2.5))
|
|
|
|
|
|
|
|
|
|
| 451 |
print(
|
| 452 |
f"one_token soft_ce={use_soft} constrained_codes={constrained} "
|
| 453 |
f"balance_noul={balance} noul_n_frac={noul_n_frac} "
|
| 454 |
f"noul_hard_ce={noul_hard} noul_loss_w={noul_lw} "
|
| 455 |
-
f"noul_n_w={noul_nw} noul_logit_bias_n={noul_bias}"
|
|
|
|
| 456 |
flush=True,
|
| 457 |
)
|
| 458 |
|
|
@@ -461,12 +555,20 @@ def train_one_token(
|
|
| 461 |
trust_remote_code=True,
|
| 462 |
torch_dtype=torch.float32 if device == "cpu" else "auto",
|
| 463 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
ds_kw = dict(
|
| 465 |
max_length=int(cfg["max_length"]),
|
| 466 |
use_soft=use_soft,
|
| 467 |
noul_hard_ce=noul_hard,
|
| 468 |
noul_loss_weight=noul_lw,
|
| 469 |
noul_n_sample_weight=noul_nw,
|
|
|
|
| 470 |
)
|
| 471 |
train_ds = OneTokenDataset(examples, tok, **ds_kw)
|
| 472 |
eval_ds = (
|
|
@@ -517,6 +619,9 @@ def train_one_token(
|
|
| 517 |
trainer = CodeTokenTrainer(
|
| 518 |
use_soft_ce=use_soft,
|
| 519 |
train_sampler=train_sampler,
|
|
|
|
|
|
|
|
|
|
| 520 |
**trainer_kwargs,
|
| 521 |
)
|
| 522 |
else:
|
|
@@ -546,6 +651,12 @@ def train_one_token(
|
|
| 546 |
"label_id",
|
| 547 |
"has_soft",
|
| 548 |
"is_noul",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 549 |
):
|
| 550 |
inputs.pop(k, None)
|
| 551 |
return super().compute_loss(
|
|
@@ -568,6 +679,12 @@ def train_one_token(
|
|
| 568 |
noul_logit_bias_n=noul_bias,
|
| 569 |
noul_n_frac=noul_n_frac,
|
| 570 |
noul_hard_ce=noul_hard,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 571 |
)
|
| 572 |
if cfg.get("push_to_hub") and cfg.get("hub_model_id"):
|
| 573 |
trainer.push_to_hub()
|
|
|
|
| 27 |
make_noul_balanced_sampler,
|
| 28 |
)
|
| 29 |
from .export_ckpt import write_checkpoint_sidecar
|
| 30 |
+
from .noul_augment import apply_noul_augments
|
| 31 |
|
| 32 |
|
| 33 |
def _env(name: str, default: str | None = None) -> str | None:
|
|
|
|
| 237 |
default=None,
|
| 238 |
help="Subsample train JSONL to this many rows (seed from cfg)",
|
| 239 |
)
|
| 240 |
+
p.add_argument(
|
| 241 |
+
"--noul_random_codes",
|
| 242 |
+
action="store_true",
|
| 243 |
+
help="Per-example random yes/no codes (not Y/N)",
|
| 244 |
+
)
|
| 245 |
+
p.add_argument(
|
| 246 |
+
"--noul_negation_pairs",
|
| 247 |
+
action="store_true",
|
| 248 |
+
help="Append negated noul twins (flipped gold/teacher)",
|
| 249 |
+
)
|
| 250 |
+
p.add_argument(
|
| 251 |
+
"--noul_consistency_weight",
|
| 252 |
+
type=float,
|
| 253 |
+
default=None,
|
| 254 |
+
help="Weight for (P(yes|Q)+P(yes|¬Q)-1)^2 (0=off)",
|
| 255 |
+
)
|
| 256 |
+
p.add_argument(
|
| 257 |
+
"--noul_binary_head",
|
| 258 |
+
action="store_true",
|
| 259 |
+
help="Extra linear head on last hidden for noul (ablation)",
|
| 260 |
+
)
|
| 261 |
+
p.add_argument(
|
| 262 |
+
"--noul_binary_head_weight",
|
| 263 |
+
type=float,
|
| 264 |
+
default=None,
|
| 265 |
+
help="Weight for binary-head CE (default 1.0 if head on)",
|
| 266 |
+
)
|
| 267 |
return p
|
| 268 |
|
| 269 |
|
|
|
|
| 315 |
"noul_hard_ce": True,
|
| 316 |
"noul_logit_bias_n": 2.5,
|
| 317 |
"max_train_rows": None,
|
| 318 |
+
# v0.1.4 Noul augments (off by default; 10k scale recipe unchanged).
|
| 319 |
+
"noul_random_codes": False,
|
| 320 |
+
"noul_negation_pairs": False,
|
| 321 |
+
"noul_consistency_weight": 0.0,
|
| 322 |
+
"noul_binary_head": False,
|
| 323 |
+
"noul_binary_head_weight": 1.0,
|
| 324 |
}
|
| 325 |
if args.config:
|
| 326 |
with open(args.config, encoding="utf-8") as f:
|
|
|
|
| 367 |
cfg["noul_hard_ce"] = False
|
| 368 |
if args.noul_logit_bias_n is not None:
|
| 369 |
cfg["noul_logit_bias_n"] = float(args.noul_logit_bias_n)
|
| 370 |
+
if args.noul_random_codes:
|
| 371 |
+
cfg["noul_random_codes"] = True
|
| 372 |
+
if args.noul_negation_pairs:
|
| 373 |
+
cfg["noul_negation_pairs"] = True
|
| 374 |
+
if args.noul_consistency_weight is not None:
|
| 375 |
+
cfg["noul_consistency_weight"] = float(
|
| 376 |
+
args.noul_consistency_weight
|
| 377 |
+
)
|
| 378 |
+
if args.noul_binary_head:
|
| 379 |
+
cfg["noul_binary_head"] = True
|
| 380 |
+
if args.noul_binary_head_weight is not None:
|
| 381 |
+
cfg["noul_binary_head_weight"] = float(
|
| 382 |
+
args.noul_binary_head_weight
|
| 383 |
+
)
|
| 384 |
env_model = _env("OSS_JEV_MODEL_ID")
|
| 385 |
if env_model and args.model_id is None and not (
|
| 386 |
args.config and cfg.get("model_id")
|
|
|
|
| 410 |
return manifest
|
| 411 |
|
| 412 |
|
| 413 |
+
def prepare_train_examples(
|
| 414 |
+
examples: list,
|
| 415 |
+
cfg: dict[str, Any],
|
| 416 |
+
) -> list:
|
| 417 |
+
"""Subsample then apply Noul augments (random codes / negation)."""
|
| 418 |
+
examples = subsample_examples(
|
| 419 |
+
examples,
|
| 420 |
+
cfg.get("max_train_rows"),
|
| 421 |
+
int(cfg.get("seed", 42)),
|
| 422 |
+
)
|
| 423 |
+
return apply_noul_augments(
|
| 424 |
+
examples,
|
| 425 |
+
random_codes=bool(cfg.get("noul_random_codes", False)),
|
| 426 |
+
negation_pairs=bool(cfg.get("noul_negation_pairs", False)),
|
| 427 |
+
seed=int(cfg.get("seed", 42)),
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
def run_dry(paths: dict[str, Path], cfg: dict[str, Any]) -> int:
|
| 432 |
from transformers import AutoTokenizer
|
| 433 |
|
| 434 |
examples = load_jsonl(paths["train"])
|
| 435 |
n_full = len(examples)
|
| 436 |
+
examples = prepare_train_examples(examples, cfg)
|
| 437 |
+
n_noul = sum(1 for e in examples if e.primitive == "noul")
|
| 438 |
+
n_neg = sum(
|
| 439 |
+
1
|
| 440 |
+
for e in examples
|
| 441 |
+
if (e.meta or {}).get("noul_negated")
|
| 442 |
+
)
|
| 443 |
+
n_rand = sum(
|
| 444 |
+
1
|
| 445 |
+
for e in examples
|
| 446 |
+
if (e.meta or {}).get("noul_random_codes")
|
| 447 |
)
|
| 448 |
check_manifest(paths)
|
| 449 |
+
tok = AutoTokenizer.from_pretrained(
|
| 450 |
+
cfg["model_id"], trust_remote_code=True
|
| 451 |
+
)
|
| 452 |
assert_single_token_codes(examples, tok)
|
| 453 |
print(
|
| 454 |
json.dumps(
|
|
|
|
| 460 |
"mode": cfg["mode"],
|
| 461 |
"n_train": len(examples),
|
| 462 |
"n_train_full": n_full,
|
| 463 |
+
"n_noul": n_noul,
|
| 464 |
+
"n_noul_negated": n_neg,
|
| 465 |
+
"n_noul_random_codes": n_rand,
|
| 466 |
"max_train_rows": cfg.get("max_train_rows"),
|
| 467 |
"train_path": str(paths["train"]),
|
| 468 |
"output_dir": str(paths["output_dir"]),
|
|
|
|
| 479 |
"noul_logit_bias_n": float(
|
| 480 |
cfg.get("noul_logit_bias_n", 2.5)
|
| 481 |
),
|
| 482 |
+
"noul_random_codes": bool(
|
| 483 |
+
cfg.get("noul_random_codes", False)
|
| 484 |
+
),
|
| 485 |
+
"noul_negation_pairs": bool(
|
| 486 |
+
cfg.get("noul_negation_pairs", False)
|
| 487 |
+
),
|
| 488 |
+
"noul_consistency_weight": float(
|
| 489 |
+
cfg.get("noul_consistency_weight", 0.0)
|
| 490 |
+
),
|
| 491 |
+
"noul_binary_head": bool(
|
| 492 |
+
cfg.get("noul_binary_head", False)
|
| 493 |
+
),
|
| 494 |
},
|
| 495 |
indent=2,
|
| 496 |
)
|
|
|
|
| 512 |
check_manifest(paths)
|
| 513 |
examples = load_jsonl(paths["train"])
|
| 514 |
n_full = len(examples)
|
| 515 |
+
examples = prepare_train_examples(examples, cfg)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 516 |
print(
|
| 517 |
f"train rows={len(examples)} (full={n_full} "
|
| 518 |
+
f"max_train_rows={cfg.get('max_train_rows')} "
|
| 519 |
+
f"noul_random={cfg.get('noul_random_codes')} "
|
| 520 |
+
f"noul_neg={cfg.get('noul_negation_pairs')})",
|
| 521 |
flush=True,
|
| 522 |
)
|
| 523 |
eval_examples = (
|
| 524 |
load_jsonl(paths["eval"]) if paths["eval"].is_file() else None
|
| 525 |
)
|
| 526 |
+
tok = AutoTokenizer.from_pretrained(
|
| 527 |
+
cfg["model_id"], trust_remote_code=True
|
| 528 |
+
)
|
| 529 |
if tok.pad_token is None:
|
| 530 |
tok.pad_token = tok.eos_token
|
| 531 |
assert_single_token_codes(examples, tok)
|
|
|
|
| 538 |
noul_lw = float(cfg.get("noul_loss_weight", 2.0))
|
| 539 |
noul_nw = float(cfg.get("noul_n_sample_weight", 2.0))
|
| 540 |
noul_bias = float(cfg.get("noul_logit_bias_n", 2.5))
|
| 541 |
+
cons_w = float(cfg.get("noul_consistency_weight", 0.0))
|
| 542 |
+
use_bin = bool(cfg.get("noul_binary_head", False))
|
| 543 |
+
bin_w = float(cfg.get("noul_binary_head_weight", 1.0))
|
| 544 |
print(
|
| 545 |
f"one_token soft_ce={use_soft} constrained_codes={constrained} "
|
| 546 |
f"balance_noul={balance} noul_n_frac={noul_n_frac} "
|
| 547 |
f"noul_hard_ce={noul_hard} noul_loss_w={noul_lw} "
|
| 548 |
+
f"noul_n_w={noul_nw} noul_logit_bias_n={noul_bias} "
|
| 549 |
+
f"cons_w={cons_w} binary_head={use_bin}",
|
| 550 |
flush=True,
|
| 551 |
)
|
| 552 |
|
|
|
|
| 555 |
trust_remote_code=True,
|
| 556 |
torch_dtype=torch.float32 if device == "cpu" else "auto",
|
| 557 |
)
|
| 558 |
+
binary_head = None
|
| 559 |
+
if use_bin:
|
| 560 |
+
import torch.nn as nn
|
| 561 |
+
|
| 562 |
+
binary_head = nn.Linear(model.config.hidden_size, 2)
|
| 563 |
+
model.add_module("noul_binary_head", binary_head)
|
| 564 |
+
model.config.output_hidden_states = True
|
| 565 |
ds_kw = dict(
|
| 566 |
max_length=int(cfg["max_length"]),
|
| 567 |
use_soft=use_soft,
|
| 568 |
noul_hard_ce=noul_hard,
|
| 569 |
noul_loss_weight=noul_lw,
|
| 570 |
noul_n_sample_weight=noul_nw,
|
| 571 |
+
noul_consistency=cons_w > 0,
|
| 572 |
)
|
| 573 |
train_ds = OneTokenDataset(examples, tok, **ds_kw)
|
| 574 |
eval_ds = (
|
|
|
|
| 619 |
trainer = CodeTokenTrainer(
|
| 620 |
use_soft_ce=use_soft,
|
| 621 |
train_sampler=train_sampler,
|
| 622 |
+
consistency_weight=cons_w,
|
| 623 |
+
binary_head=binary_head,
|
| 624 |
+
binary_head_weight=bin_w if use_bin else 0.0,
|
| 625 |
**trainer_kwargs,
|
| 626 |
)
|
| 627 |
else:
|
|
|
|
| 651 |
"label_id",
|
| 652 |
"has_soft",
|
| 653 |
"is_noul",
|
| 654 |
+
"yes_idx",
|
| 655 |
+
"has_neg",
|
| 656 |
+
"neg_input_ids",
|
| 657 |
+
"neg_attention_mask",
|
| 658 |
+
"neg_labels",
|
| 659 |
+
"neg_soft_labels",
|
| 660 |
):
|
| 661 |
inputs.pop(k, None)
|
| 662 |
return super().compute_loss(
|
|
|
|
| 679 |
noul_logit_bias_n=noul_bias,
|
| 680 |
noul_n_frac=noul_n_frac,
|
| 681 |
noul_hard_ce=noul_hard,
|
| 682 |
+
noul_random_codes=bool(cfg.get("noul_random_codes", False)),
|
| 683 |
+
noul_negation_pairs=bool(
|
| 684 |
+
cfg.get("noul_negation_pairs", False)
|
| 685 |
+
),
|
| 686 |
+
noul_consistency_weight=cons_w,
|
| 687 |
+
noul_binary_head=use_bin,
|
| 688 |
)
|
| 689 |
if cfg.get("push_to_hub") and cfg.get("hub_model_id"):
|
| 690 |
trainer.push_to_hub()
|
pyproject.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
[project]
|
| 2 |
name = "oss-jev-train"
|
| 3 |
-
version = "0.1.
|
| 4 |
description = "Qwen one-token decision-head train for OSS Jev distill (HF Jobs image)"
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.10"
|
|
|
|
| 1 |
[project]
|
| 2 |
name = "oss-jev-train"
|
| 3 |
+
version = "0.1.4"
|
| 4 |
description = "Qwen one-token decision-head train for OSS Jev distill (HF Jobs image)"
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.10"
|