gyanbhambhani commited on
Commit
a4dd486
·
verified ·
1 Parent(s): 9cbc665

Upload oss-jev-train for hf jobs uv run

Browse files
configs/jobs-a10g-traced.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path A traces continue from noul-v2 (v0.1.9). Distinct Hub id —
2
+ # never overwrite noul-v2 / noul-bin / 10k / main. Short rationale
3
+ # then Answer:\n{code}; L_code + λ_t L_trace. Keep constrained codes.
4
+ # Milder noul mix than v2 so Choice / Noul floors hold.
5
+ model_id: gyanbhambhani/oss-jev-qwen05-decision-noul-v2
6
+ mode: one_token
7
+ max_length: 1024
8
+ batch_size: 2
9
+ learning_rate: 1.0e-5
10
+ max_steps: 2000
11
+ max_train_rows: null
12
+ seed: 42
13
+ fp16: false
14
+ bf16: true
15
+ logging_steps: 50
16
+ save_total_limit: 2
17
+ report_to: none
18
+ use_soft_ce: true
19
+ balance_noul: true
20
+ constrained_codes: true
21
+ # Protect Choice/Noul floors vs v2's heavier noul mix
22
+ noul_n_frac: 0.65
23
+ noul_mix_weight: 2.0
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
+ noul_random_codes: true
29
+ noul_negation_pairs: true
30
+ noul_consistency_weight: 1.0
31
+ noul_binary_head: true
32
+ noul_binary_head_weight: 1.0
33
+ noul_binary_balanced: true
34
+ # Path A traces
35
+ use_traces: true
36
+ trace_loss_weight: 0.25
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.8"
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.9"
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/code_loss.py CHANGED
@@ -189,6 +189,26 @@ def consistency_loss(
189
  return (diff * diff).mean()
190
 
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  class CodeTokenTrainer:
193
  """Lazy wrapper — real subclass built on first instantiate.
194
 
@@ -222,6 +242,7 @@ def _build_trainer_class() -> type:
222
  binary_head_weight: float = 0.0,
223
  binary_head_balanced: bool = False,
224
  score_ordinal_weight: float = 0.0,
 
225
  **kwargs: Any,
226
  ) -> None:
227
  self._custom_train_sampler = train_sampler
@@ -232,6 +253,7 @@ def _build_trainer_class() -> type:
232
  self.binary_head_weight = float(binary_head_weight)
233
  self.binary_head_balanced = bool(binary_head_balanced)
234
  self.score_ordinal_weight = float(score_ordinal_weight)
 
235
 
236
  def _get_train_sampler(self, train_dataset: Any = None):
237
  if self._custom_train_sampler is not None:
@@ -258,11 +280,13 @@ def _build_trainer_class() -> type:
258
  neg_attention = inputs.pop("neg_attention_mask", None)
259
  neg_labels = inputs.pop("neg_labels", None)
260
  neg_soft = inputs.pop("neg_soft_labels", None)
 
261
  inputs.pop("label_id", None)
262
  inputs.pop("has_soft", None)
263
  is_noul = inputs.pop("is_noul", None)
264
  is_score = inputs.pop("is_score", None)
265
  force_soft = inputs.pop("force_soft", None)
 
266
 
267
  labels = inputs.get("labels")
268
  outputs = model(**inputs)
@@ -277,6 +301,16 @@ def _build_trainer_class() -> type:
277
  force_soft_mask=force_soft,
278
  )
279
 
 
 
 
 
 
 
 
 
 
 
280
  # Score ordinal: EMD + expected |level−teacher| (off-by-3 > 1).
281
  if (
282
  self.score_ordinal_weight > 0
 
189
  return (diff * diff).mean()
190
 
191
 
192
+ def trace_token_loss(
193
+ logits: torch.Tensor,
194
+ trace_labels: torch.Tensor,
195
+ ) -> torch.Tensor:
196
+ """Full-vocab CE on rationale tokens (Path A L_trace).
197
+
198
+ ``trace_labels``: [B, T] with -100 mask; only rationale positions
199
+ supervised. HF shift: predict token t from logits[:, t-1].
200
+ """
201
+ shift_logits = logits[:, :-1, :].contiguous()
202
+ shift_labels = trace_labels[:, 1:].contiguous()
203
+ if (shift_labels != -100).sum() == 0:
204
+ return logits.sum() * 0.0
205
+ return F.cross_entropy(
206
+ shift_logits.view(-1, shift_logits.size(-1)),
207
+ shift_labels.view(-1),
208
+ ignore_index=-100,
209
+ )
210
+
211
+
212
  class CodeTokenTrainer:
213
  """Lazy wrapper — real subclass built on first instantiate.
214
 
 
242
  binary_head_weight: float = 0.0,
243
  binary_head_balanced: bool = False,
244
  score_ordinal_weight: float = 0.0,
245
+ trace_loss_weight: float = 0.0,
246
  **kwargs: Any,
247
  ) -> None:
248
  self._custom_train_sampler = train_sampler
 
253
  self.binary_head_weight = float(binary_head_weight)
254
  self.binary_head_balanced = bool(binary_head_balanced)
255
  self.score_ordinal_weight = float(score_ordinal_weight)
256
+ self.trace_loss_weight = float(trace_loss_weight)
257
 
258
  def _get_train_sampler(self, train_dataset: Any = None):
259
  if self._custom_train_sampler is not None:
 
280
  neg_attention = inputs.pop("neg_attention_mask", None)
281
  neg_labels = inputs.pop("neg_labels", None)
282
  neg_soft = inputs.pop("neg_soft_labels", None)
283
+ trace_labels = inputs.pop("trace_labels", None)
284
  inputs.pop("label_id", None)
285
  inputs.pop("has_soft", None)
286
  is_noul = inputs.pop("is_noul", None)
287
  is_score = inputs.pop("is_score", None)
288
  force_soft = inputs.pop("force_soft", None)
289
+ inputs.pop("has_trace", None)
290
 
291
  labels = inputs.get("labels")
292
  outputs = model(**inputs)
 
301
  force_soft_mask=force_soft,
302
  )
303
 
304
+ # Path A: λ_t L_trace on short rationale tokens.
305
+ if (
306
+ self.trace_loss_weight > 0
307
+ and trace_labels is not None
308
+ ):
309
+ t_loss = trace_token_loss(
310
+ outputs.logits, trace_labels
311
+ )
312
+ loss = loss + self.trace_loss_weight * t_loss
313
+
314
  # Score ordinal: EMD + expected |level−teacher| (off-by-3 > 1).
315
  if (
316
  self.score_ordinal_weight > 0
oss_jev_train/dataset.py CHANGED
@@ -161,6 +161,7 @@ class OneTokenDataset(Dataset):
161
  noul_consistency: bool = False,
162
  score_force_soft: bool = False,
163
  score_loss_weight: float = 1.0,
 
164
  ) -> None:
165
  self.examples = examples
166
  self.tokenizer = tokenizer
@@ -176,6 +177,8 @@ class OneTokenDataset(Dataset):
176
  # Score KL: force soft teacher level dist + row loss weight.
177
  self.score_force_soft = bool(score_force_soft)
178
  self.score_loss_weight = float(score_loss_weight)
 
 
179
  if tokenizer.pad_token_id is None:
180
  tokenizer.pad_token = tokenizer.eos_token
181
  # Cache code → token id (verified single-token upstream).
@@ -193,7 +196,24 @@ class OneTokenDataset(Dataset):
193
  def _encode_supervised(self, ex: "DecisionExample") -> dict[str, Any]:
194
  import torch
195
 
196
- prompt = format_prompt(ex)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  gold_ids = self.tokenizer.encode(
198
  ex.gold_code, add_special_tokens=False
199
  )
@@ -202,11 +222,15 @@ class OneTokenDataset(Dataset):
202
  f"{ex.id}: gold {ex.gold_code!r} → {gold_ids}"
203
  )
204
  gold_id = int(gold_ids[0])
205
- # Reserve 1 slot for gold. Truncate prompt from the LEFT so
206
- # the Answer:\n suffix (and thus next-token position) survives.
207
- import torch
208
-
209
- max_prompt = max(int(self.max_length) - 1, 1)
 
 
 
 
210
  prev_side = getattr(
211
  self.tokenizer, "truncation_side", "right"
212
  )
@@ -229,12 +253,13 @@ class OneTokenDataset(Dataset):
229
  )
230
  if self.tokenizer.pad_token_id is not None:
231
  prompt_ids = prompt_ids[prompt_ids != pad_id]
232
- seq = torch.cat(
233
- [
234
- prompt_ids,
235
- torch.tensor([gold_id], dtype=torch.long),
236
- ]
237
- )
 
238
  if seq.numel() > int(self.max_length):
239
  seq = seq[-int(self.max_length) :]
240
  # Right-pad to max_length.
@@ -245,6 +270,7 @@ class OneTokenDataset(Dataset):
245
  n = int(seq.numel())
246
  input_ids[:n] = seq
247
  attention[:n] = 1
 
248
  labels = input_ids.clone()
249
  labels[attention == 0] = -100
250
  last = n - 1
@@ -255,7 +281,26 @@ class OneTokenDataset(Dataset):
255
  )
256
  labels[:last] = -100
257
 
258
- n = len(ex.codes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  code_token_ids = torch.full(
260
  (MAX_CODES,), -1, dtype=torch.long
261
  )
@@ -300,8 +345,9 @@ class OneTokenDataset(Dataset):
300
  "input_ids": input_ids,
301
  "attention_mask": attention,
302
  "labels": labels,
 
303
  "label_id": ex.label_id,
304
- "n_codes": n,
305
  "code_token_ids": code_token_ids,
306
  "soft_labels": soft_t,
307
  "has_soft": has_soft,
@@ -310,6 +356,7 @@ class OneTokenDataset(Dataset):
310
  "is_score": 1 if is_score else 0,
311
  "force_soft": 1 if (is_score and self.score_force_soft) else 0,
312
  "yes_idx": yes_idx,
 
313
  }
314
 
315
  def __getitem__(self, idx: int) -> dict[str, Any]:
 
161
  noul_consistency: bool = False,
162
  score_force_soft: bool = False,
163
  score_loss_weight: float = 1.0,
164
+ use_traces: bool = False,
165
  ) -> None:
166
  self.examples = examples
167
  self.tokenizer = tokenizer
 
177
  # Score KL: force soft teacher level dist + row loss weight.
178
  self.score_force_soft = bool(score_force_soft)
179
  self.score_loss_weight = float(score_loss_weight)
180
+ # Path A: short rationale before Answer:\n{code}.
181
+ self.use_traces = bool(use_traces)
182
  if tokenizer.pad_token_id is None:
183
  tokenizer.pad_token = tokenizer.eos_token
184
  # Cache code → token id (verified single-token upstream).
 
196
  def _encode_supervised(self, ex: "DecisionExample") -> dict[str, Any]:
197
  import torch
198
 
199
+ if self.use_traces:
200
+ from .traces import ensure_trace
201
+
202
+ ensure_trace(ex, source="template", refresh=True)
203
+ use_tr = self.use_traces and bool(
204
+ (ex.trace or {}).get("text")
205
+ )
206
+ if use_tr:
207
+ prompt = format_prompt(
208
+ ex,
209
+ include_answer_cue=False,
210
+ use_trace_cue=True,
211
+ )
212
+ rationale = str(ex.trace["text"]).strip()
213
+ mid = f"{rationale}\nAnswer:\n"
214
+ else:
215
+ prompt = format_prompt(ex)
216
+ mid = ""
217
  gold_ids = self.tokenizer.encode(
218
  ex.gold_code, add_special_tokens=False
219
  )
 
222
  f"{ex.id}: gold {ex.gold_code!r} → {gold_ids}"
223
  )
224
  gold_id = int(gold_ids[0])
225
+ # Reserve slots for mid (rationale+Answer:\n) + gold. Truncate
226
+ # prompt from the LEFT so the Answer:\n / code position survives.
227
+ mid_ids: list[int] = []
228
+ if mid:
229
+ mid_ids = self.tokenizer.encode(
230
+ mid, add_special_tokens=False
231
+ )
232
+ reserve = 1 + len(mid_ids)
233
+ max_prompt = max(int(self.max_length) - reserve, 1)
234
  prev_side = getattr(
235
  self.tokenizer, "truncation_side", "right"
236
  )
 
253
  )
254
  if self.tokenizer.pad_token_id is not None:
255
  prompt_ids = prompt_ids[prompt_ids != pad_id]
256
+ pieces = [prompt_ids]
257
+ if mid_ids:
258
+ pieces.append(
259
+ torch.tensor(mid_ids, dtype=torch.long)
260
+ )
261
+ pieces.append(torch.tensor([gold_id], dtype=torch.long))
262
+ seq = torch.cat(pieces)
263
  if seq.numel() > int(self.max_length):
264
  seq = seq[-int(self.max_length) :]
265
  # Right-pad to max_length.
 
270
  n = int(seq.numel())
271
  input_ids[:n] = seq
272
  attention[:n] = 1
273
+ # L_code: only the final gold code token is supervised here.
274
  labels = input_ids.clone()
275
  labels[attention == 0] = -100
276
  last = n - 1
 
281
  )
282
  labels[:last] = -100
283
 
284
+ # L_trace: supervise rationale tokens only (not Answer:\n glue).
285
+ trace_labels = torch.full_like(labels, -100)
286
+ if use_tr and mid_ids:
287
+ # Positions of mid tokens in the (possibly left-truncated) seq.
288
+ # mid starts at n - 1 - len(mid_ids); gold is at n-1.
289
+ mid_start = n - 1 - len(mid_ids)
290
+ if mid_start < 0:
291
+ mid_start = 0
292
+ # Encode rationale alone to know how many tokens to supervise.
293
+ rat_ids = self.tokenizer.encode(
294
+ rationale, add_special_tokens=False
295
+ )
296
+ # mid = rationale + "\nAnswer:\n"; supervise rationale prefix.
297
+ n_rat = min(len(rat_ids), len(mid_ids))
298
+ for i in range(n_rat):
299
+ pos = mid_start + i
300
+ if 0 <= pos < last:
301
+ trace_labels[pos] = int(input_ids[pos].item())
302
+
303
+ n_codes = len(ex.codes)
304
  code_token_ids = torch.full(
305
  (MAX_CODES,), -1, dtype=torch.long
306
  )
 
345
  "input_ids": input_ids,
346
  "attention_mask": attention,
347
  "labels": labels,
348
+ "trace_labels": trace_labels,
349
  "label_id": ex.label_id,
350
+ "n_codes": n_codes,
351
  "code_token_ids": code_token_ids,
352
  "soft_labels": soft_t,
353
  "has_soft": has_soft,
 
356
  "is_score": 1 if is_score else 0,
357
  "force_soft": 1 if (is_score and self.score_force_soft) else 0,
358
  "yes_idx": yes_idx,
359
+ "has_trace": 1 if use_tr else 0,
360
  }
361
 
362
  def __getitem__(self, idx: int) -> dict[str, Any]:
oss_jev_train/export_ckpt.py CHANGED
@@ -57,6 +57,8 @@ def write_checkpoint_sidecar(
57
  score_ordinal_weight: float | None = None,
58
  score_loss_weight: float | None = None,
59
  score_mix_weight: float | None = None,
 
 
60
  ) -> Path:
61
  """Write ``decision_head.json`` next to HF weights.
62
 
@@ -120,6 +122,10 @@ def write_checkpoint_sidecar(
120
  meta["score_loss_weight"] = float(score_loss_weight)
121
  if score_mix_weight is not None:
122
  meta["score_mix_weight"] = float(score_mix_weight)
 
 
 
 
123
  path = ckpt_dir / "decision_head.json"
124
  path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
125
 
 
57
  score_ordinal_weight: float | None = None,
58
  score_loss_weight: float | None = None,
59
  score_mix_weight: float | None = None,
60
+ use_traces: bool | None = None,
61
+ trace_loss_weight: float | None = None,
62
  ) -> Path:
63
  """Write ``decision_head.json`` next to HF weights.
64
 
 
122
  meta["score_loss_weight"] = float(score_loss_weight)
123
  if score_mix_weight is not None:
124
  meta["score_mix_weight"] = float(score_mix_weight)
125
+ if use_traces is not None:
126
+ meta["use_traces"] = bool(use_traces)
127
+ if trace_loss_weight is not None:
128
+ meta["trace_loss_weight"] = float(trace_loss_weight)
129
  path = ckpt_dir / "decision_head.json"
130
  path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
131
 
oss_jev_train/prompts.py CHANGED
@@ -74,11 +74,29 @@ def _criteria_block(ex: DecisionExample) -> str:
74
  return ""
75
 
76
 
77
- def format_prompt(ex: DecisionExample) -> str:
78
- """Normative one-token prompt; ends right before the answer code."""
79
- if ex.prompt:
 
 
 
 
 
 
 
 
 
 
 
80
  return ex.prompt
81
  legend = " ".join(ex.codes)
 
 
 
 
 
 
 
82
  parts = [
83
  "### State",
84
  _state_text(ex.state),
@@ -89,13 +107,14 @@ def format_prompt(ex: DecisionExample) -> str:
89
  _criteria_block(ex),
90
  "",
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
 
101
 
 
74
  return ""
75
 
76
 
77
+ def format_prompt(
78
+ ex: DecisionExample,
79
+ *,
80
+ include_answer_cue: bool = True,
81
+ use_trace_cue: bool = False,
82
+ ) -> str:
83
+ """Normative one-token prompt; ends right before the answer code.
84
+
85
+ ``use_trace_cue``: Path A — ask for a short reason before the code;
86
+ caller appends ``{rationale}\\nAnswer:\\n`` then the code token.
87
+ When ``include_answer_cue`` is False, omit the final ``Answer:\\n``
88
+ so the dataset can insert the rationale first.
89
+ """
90
+ if ex.prompt and include_answer_cue and not use_trace_cue:
91
  return ex.prompt
92
  legend = " ".join(ex.codes)
93
+ if use_trace_cue:
94
+ reply_line = (
95
+ "Reason in 1-2 short sentences, then reply with "
96
+ "exactly one code character."
97
+ )
98
+ else:
99
+ reply_line = "Reply with exactly one code character."
100
  parts = [
101
  "### State",
102
  _state_text(ex.state),
 
107
  _criteria_block(ex),
108
  "",
109
  "### Answer",
110
+ reply_line,
111
  f"Codes: {legend}",
112
+ ]
113
+ if include_answer_cue:
114
  # Trailing newline: Qwen merges `Answer:N` into `:N` (not code
115
  # token 45). `Answer:\n` + code keeps Y/N/letters single tokens
116
  # and matches infer next-token position.
117
+ parts.append("Answer:\n")
 
118
  return "\n".join(p for p in parts if p is not None)
119
 
120
 
oss_jev_train/schema.py CHANGED
@@ -26,6 +26,8 @@ class DecisionExample:
26
  split: str = "train"
27
  prompt: str | None = None
28
  meta: dict[str, Any] = field(default_factory=dict)
 
 
29
 
30
  @property
31
  def label_id(self) -> int:
@@ -94,6 +96,7 @@ def from_dict(row: dict[str, Any]) -> DecisionExample:
94
  split=str(row.get("split") or "train"),
95
  prompt=row.get("prompt"),
96
  meta=dict(row.get("meta") or {}),
 
97
  )
98
  ex.validate()
99
  return ex
 
26
  split: str = "train"
27
  prompt: str | None = None
28
  meta: dict[str, Any] = field(default_factory=dict)
29
+ # Optional Path A decision trace (short rationale before code).
30
+ trace: dict[str, Any] = field(default_factory=dict)
31
 
32
  @property
33
  def label_id(self) -> int:
 
96
  split=str(row.get("split") or "train"),
97
  prompt=row.get("prompt"),
98
  meta=dict(row.get("meta") or {}),
99
+ trace=dict(row.get("trace") or {}),
100
  )
101
  ex.validate()
102
  return ex
oss_jev_train/traces.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Short decision-trace (rationale) templates for Path A.
2
+
3
+ Style: 1–2 sentences that name the chosen option / polarity, then the
4
+ model still ends with Answer:\\n{code}. Source=template (no teacher LLM).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any
11
+
12
+ from .schema import DecisionExample
13
+
14
+
15
+ def _clip(text: str, n: int = 72) -> str:
16
+ text = re.sub(r"\s+", " ", str(text)).strip()
17
+ if len(text) <= n:
18
+ return text
19
+ return text[: n - 1].rstrip() + "…"
20
+
21
+
22
+ def _choice_key_desc(ex: DecisionExample) -> tuple[str, str]:
23
+ key = str(ex.code_to_key.get(ex.gold_code, ex.gold_code))
24
+ desc = ""
25
+ if isinstance(ex.criteria, dict):
26
+ raw = ex.criteria.get(key, "")
27
+ if raw not in (None, ""):
28
+ desc = _clip(str(raw), 64)
29
+ return key, desc
30
+
31
+
32
+ def _noul_polarity(ex: DecisionExample) -> tuple[str, str]:
33
+ """Return (yes|no, brief criteria side)."""
34
+ key = str(ex.code_to_key.get(ex.gold_code, "")).lower()
35
+ is_yes = key in ("true", "yes", "y") or (
36
+ set(ex.codes) == {"Y", "N"} and ex.gold_code == "Y"
37
+ )
38
+ side = "yes" if is_yes else "no"
39
+ hint = ""
40
+ if isinstance(ex.criteria, dict):
41
+ crit_key = "true" if is_yes else "false"
42
+ raw = ex.criteria.get(crit_key, "")
43
+ if raw not in (None, ""):
44
+ hint = _clip(str(raw), 56)
45
+ return side, hint
46
+
47
+
48
+ def _score_level_desc(ex: DecisionExample) -> tuple[str, str]:
49
+ key = str(ex.code_to_key.get(ex.gold_code, ex.gold_code))
50
+ desc = ""
51
+ if isinstance(ex.criteria, list):
52
+ try:
53
+ desc = _clip(str(ex.criteria[int(key)]), 56)
54
+ except (ValueError, IndexError, TypeError):
55
+ desc = ""
56
+ return key, desc
57
+
58
+
59
+ def template_rationale(ex: DecisionExample) -> str:
60
+ """Deterministic short rationale bound to gold_code (not fluff)."""
61
+ if ex.primitive == "choice":
62
+ key, desc = _choice_key_desc(ex)
63
+ if desc:
64
+ return f"{key}: {desc}."
65
+ return f"Best match is {key}."
66
+ if ex.primitive == "noul":
67
+ side, hint = _noul_polarity(ex)
68
+ if hint:
69
+ return f"Evidence supports {side} — {hint}."
70
+ return f"State supports {side}."
71
+ if ex.primitive == "score":
72
+ lvl, desc = _score_level_desc(ex)
73
+ if desc:
74
+ return f"Level {lvl}: {desc}."
75
+ return f"Rubric level {lvl}."
76
+ return f"Answer code {ex.gold_code}."
77
+
78
+
79
+ def ensure_trace(
80
+ ex: DecisionExample,
81
+ *,
82
+ style: str = "short_rationale",
83
+ source: str = "template",
84
+ refresh: bool = False,
85
+ ) -> DecisionExample:
86
+ """Attach ``ex.trace`` bound to current gold_code.
87
+
88
+ Template source always refreshes so negation twins / remapped
89
+ codes stay faithful to gold (not a stale deepcopy).
90
+ """
91
+ existing = ex.trace or {}
92
+ if (
93
+ not refresh
94
+ and source != "template"
95
+ and existing.get("text")
96
+ ):
97
+ return ex
98
+ text = template_rationale(ex)
99
+ ex.trace = {
100
+ "text": text,
101
+ "style": style,
102
+ "source": source,
103
+ }
104
+ return ex
105
+
106
+
107
+ def apply_traces(
108
+ examples: list[DecisionExample],
109
+ *,
110
+ enabled: bool,
111
+ style: str = "short_rationale",
112
+ source: str = "template",
113
+ ) -> list[DecisionExample]:
114
+ if not enabled:
115
+ return examples
116
+ out: list[DecisionExample] = []
117
+ for ex in examples:
118
+ ensure_trace(ex, style=style, source=source)
119
+ out.append(ex)
120
+ return out
121
+
122
+
123
+ def stub_rationale() -> str:
124
+ """Neutral cue for code-only eval when train used traces."""
125
+ return "Considering the state and criteria."
oss_jev_train/train.py CHANGED
@@ -28,6 +28,7 @@ from .dataset import (
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:
@@ -298,6 +299,17 @@ def build_argparser() -> argparse.ArgumentParser:
298
  default=None,
299
  help="Upsample Score vs choice in sampler (default 1)",
300
  )
 
 
 
 
 
 
 
 
 
 
 
301
  return p
302
 
303
 
@@ -362,6 +374,9 @@ def merge_config(args: argparse.Namespace) -> dict[str, Any]:
362
  "score_ordinal_weight": 0.0,
363
  "score_loss_weight": 1.0,
364
  "score_mix_weight": 1.0,
 
 
 
365
  }
366
  if args.config:
367
  with open(args.config, encoding="utf-8") as f:
@@ -434,6 +449,10 @@ def merge_config(args: argparse.Namespace) -> dict[str, Any]:
434
  cfg["score_loss_weight"] = float(args.score_loss_weight)
435
  if args.score_mix_weight is not None:
436
  cfg["score_mix_weight"] = float(args.score_mix_weight)
 
 
 
 
437
  env_model = _env("OSS_JEV_MODEL_ID")
438
  if env_model and args.model_id is None and not (
439
  args.config and cfg.get("model_id")
@@ -467,18 +486,22 @@ def prepare_train_examples(
467
  examples: list,
468
  cfg: dict[str, Any],
469
  ) -> list:
470
- """Subsample then apply Noul augments (random codes / negation)."""
471
  examples = subsample_examples(
472
  examples,
473
  cfg.get("max_train_rows"),
474
  int(cfg.get("seed", 42)),
475
  )
476
- return apply_noul_augments(
477
  examples,
478
  random_codes=bool(cfg.get("noul_random_codes", False)),
479
  negation_pairs=bool(cfg.get("noul_negation_pairs", False)),
480
  seed=int(cfg.get("seed", 42)),
481
  )
 
 
 
 
482
 
483
 
484
  def run_dry(paths: dict[str, Path], cfg: dict[str, Any]) -> int:
@@ -562,9 +585,18 @@ def run_dry(paths: dict[str, Path], cfg: dict[str, Any]) -> int:
562
  "score_mix_weight": float(
563
  cfg.get("score_mix_weight", 1.0)
564
  ),
 
 
 
 
565
  "n_score": sum(
566
  1 for e in examples if e.primitive == "score"
567
  ),
 
 
 
 
 
568
  },
569
  indent=2,
570
  )
@@ -621,6 +653,8 @@ def train_one_token(
621
  score_ord_w = float(cfg.get("score_ordinal_weight", 0.0))
622
  score_lw = float(cfg.get("score_loss_weight", 1.0))
623
  score_mix = float(cfg.get("score_mix_weight", 1.0))
 
 
624
  print(
625
  f"one_token soft_ce={use_soft} constrained_codes={constrained} "
626
  f"balance_noul={balance} noul_n_frac={noul_n_frac} "
@@ -629,7 +663,8 @@ def train_one_token(
629
  f"noul_logit_bias_n={noul_bias} cons_w={cons_w} "
630
  f"binary_head={use_bin} binary_bal={bin_bal} "
631
  f"score_force_soft={score_force} score_ord_w={score_ord_w} "
632
- f"score_loss_w={score_lw} score_mix_w={score_mix}",
 
633
  flush=True,
634
  )
635
 
@@ -670,6 +705,7 @@ def train_one_token(
670
  noul_consistency=cons_w > 0,
671
  score_force_soft=score_force,
672
  score_loss_weight=score_lw,
 
673
  )
674
  train_ds = OneTokenDataset(examples, tok, **ds_kw)
675
  eval_ds = (
@@ -730,6 +766,7 @@ def train_one_token(
730
  binary_head_weight=bin_w if use_bin else 0.0,
731
  binary_head_balanced=bin_bal if use_bin else False,
732
  score_ordinal_weight=score_ord_w,
 
733
  **trainer_kwargs,
734
  )
735
  else:
@@ -767,6 +804,8 @@ def train_one_token(
767
  "neg_attention_mask",
768
  "neg_labels",
769
  "neg_soft_labels",
 
 
770
  ):
771
  inputs.pop(k, None)
772
  return super().compute_loss(
@@ -799,6 +838,8 @@ def train_one_token(
799
  score_ordinal_weight=score_ord_w,
800
  score_loss_weight=score_lw,
801
  score_mix_weight=score_mix,
 
 
802
  )
803
  if binary_head is not None:
804
  from .export_ckpt import (
 
28
  )
29
  from .export_ckpt import write_checkpoint_sidecar
30
  from .noul_augment import apply_noul_augments
31
+ from .traces import apply_traces
32
 
33
 
34
  def _env(name: str, default: str | None = None) -> str | None:
 
299
  default=None,
300
  help="Upsample Score vs choice in sampler (default 1)",
301
  )
302
+ p.add_argument(
303
+ "--use_traces",
304
+ action="store_true",
305
+ help="Path A: short rationale before Answer:\\n{code}",
306
+ )
307
+ p.add_argument(
308
+ "--trace_loss_weight",
309
+ type=float,
310
+ default=None,
311
+ help="λ_t for L_trace on rationale tokens (default 0.25)",
312
+ )
313
  return p
314
 
315
 
 
374
  "score_ordinal_weight": 0.0,
375
  "score_loss_weight": 1.0,
376
  "score_mix_weight": 1.0,
377
+ # v0.1.9 Path A decision traces (off by default).
378
+ "use_traces": False,
379
+ "trace_loss_weight": 0.25,
380
  }
381
  if args.config:
382
  with open(args.config, encoding="utf-8") as f:
 
449
  cfg["score_loss_weight"] = float(args.score_loss_weight)
450
  if args.score_mix_weight is not None:
451
  cfg["score_mix_weight"] = float(args.score_mix_weight)
452
+ if args.use_traces:
453
+ cfg["use_traces"] = True
454
+ if args.trace_loss_weight is not None:
455
+ cfg["trace_loss_weight"] = float(args.trace_loss_weight)
456
  env_model = _env("OSS_JEV_MODEL_ID")
457
  if env_model and args.model_id is None and not (
458
  args.config and cfg.get("model_id")
 
486
  examples: list,
487
  cfg: dict[str, Any],
488
  ) -> list:
489
+ """Subsample, Noul augments, then optional Path A traces."""
490
  examples = subsample_examples(
491
  examples,
492
  cfg.get("max_train_rows"),
493
  int(cfg.get("seed", 42)),
494
  )
495
+ examples = apply_noul_augments(
496
  examples,
497
  random_codes=bool(cfg.get("noul_random_codes", False)),
498
  negation_pairs=bool(cfg.get("noul_negation_pairs", False)),
499
  seed=int(cfg.get("seed", 42)),
500
  )
501
+ return apply_traces(
502
+ examples,
503
+ enabled=bool(cfg.get("use_traces", False)),
504
+ )
505
 
506
 
507
  def run_dry(paths: dict[str, Path], cfg: dict[str, Any]) -> int:
 
585
  "score_mix_weight": float(
586
  cfg.get("score_mix_weight", 1.0)
587
  ),
588
+ "use_traces": bool(cfg.get("use_traces", False)),
589
+ "trace_loss_weight": float(
590
+ cfg.get("trace_loss_weight", 0.25)
591
+ ),
592
  "n_score": sum(
593
  1 for e in examples if e.primitive == "score"
594
  ),
595
+ "n_with_trace": sum(
596
+ 1
597
+ for e in examples
598
+ if (e.trace or {}).get("text")
599
+ ),
600
  },
601
  indent=2,
602
  )
 
653
  score_ord_w = float(cfg.get("score_ordinal_weight", 0.0))
654
  score_lw = float(cfg.get("score_loss_weight", 1.0))
655
  score_mix = float(cfg.get("score_mix_weight", 1.0))
656
+ use_tr = bool(cfg.get("use_traces", False))
657
+ trace_w = float(cfg.get("trace_loss_weight", 0.25))
658
  print(
659
  f"one_token soft_ce={use_soft} constrained_codes={constrained} "
660
  f"balance_noul={balance} noul_n_frac={noul_n_frac} "
 
663
  f"noul_logit_bias_n={noul_bias} cons_w={cons_w} "
664
  f"binary_head={use_bin} binary_bal={bin_bal} "
665
  f"score_force_soft={score_force} score_ord_w={score_ord_w} "
666
+ f"score_loss_w={score_lw} score_mix_w={score_mix} "
667
+ f"use_traces={use_tr} trace_w={trace_w}",
668
  flush=True,
669
  )
670
 
 
705
  noul_consistency=cons_w > 0,
706
  score_force_soft=score_force,
707
  score_loss_weight=score_lw,
708
+ use_traces=use_tr,
709
  )
710
  train_ds = OneTokenDataset(examples, tok, **ds_kw)
711
  eval_ds = (
 
766
  binary_head_weight=bin_w if use_bin else 0.0,
767
  binary_head_balanced=bin_bal if use_bin else False,
768
  score_ordinal_weight=score_ord_w,
769
+ trace_loss_weight=trace_w if use_tr else 0.0,
770
  **trainer_kwargs,
771
  )
772
  else:
 
804
  "neg_attention_mask",
805
  "neg_labels",
806
  "neg_soft_labels",
807
+ "trace_labels",
808
+ "has_trace",
809
  ):
810
  inputs.pop(k, None)
811
  return super().compute_loss(
 
838
  score_ordinal_weight=score_ord_w,
839
  score_loss_weight=score_lw,
840
  score_mix_weight=score_mix,
841
+ use_traces=use_tr,
842
+ trace_loss_weight=trace_w if use_tr else 0.0,
843
  )
844
  if binary_head is not None:
845
  from .export_ckpt import (
pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
  [project]
2
  name = "oss-jev-train"
3
- version = "0.1.8"
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.9"
4
  description = "Qwen one-token decision-head train for OSS Jev distill (HF Jobs image)"
5
  readme = "README.md"
6
  requires-python = ">=3.10"