Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

Merge pull request #931 from Swatantra-66/feat/train-cli-csv-loaders

Nandakishor8727248b8221
diff --cc laya/train.py
index 759ca0a0,37199cbe..076b574b
--- a/laya/train.py
+++ b/laya/train.py
@@@ -196,13 -272,15 +294,15 @@@ def make_item(tok, q: Dict[str, Any], t
def items_from_rows(tok, rows: Iterable[Dict[str, Any]], max_len: int,
- head_max_len: int) -> Tuple[List[Dict[str, Any]], Dict[str, int]]:
- """Items from `{state, questions, gold}` rows; returns `(items, skipped)`.
+ head_max_len: int,
+ label_smoothing: float = 0.0) -> Tuple[List[Dict[str, Any]], Dict[str, int]]:
+ """Items from `{state, questions, gold}` or `{state, questions, expected}` rows; returns `(items, skipped)`.
`skipped` counts, by reason, questions that were labelled but could not become an item:
- `invalid_question` and `invalid_target` (a `ValueError` from `to_internal` or
- `target_from_gold`), plus the reasons `make_item` gives. Questions with no gold entry
- are not counted -- the row simply does not label them.
+ `empty_text`, `empty_label`, `invalid_question` and `invalid_target` (a `ValueError` from
- `to_internal`, `target_from_gold` or `target_from_expected`), plus the two reasons `make_item`
- gives (`options_collapsed` and `target_mismatch`).
- Questions with neither `gold` nor `expected` entry are not counted -- the row simply does not label them.
++ `to_internal`, `target_from_gold` or `target_from_expected`), plus the reasons `make_item`
++ gives. Questions with neither a `gold` nor an `expected` entry are not counted -- the row
++ simply does not label them.
"""
items, skipped = [], {}
for row in rows:
@@@ -551,11 -683,11 +768,14 @@@ def finetune(data: str, model_dir: str
model, tok, cfg = load_checkpoint(model_dir)
max_len = config.max_len or cfg.get("max_len", 512)
head_max_len = config.head_max_len or cfg.get("head_max_len", 192)
+ if config.option_layout is not None:
+ cfg = dict(cfg, option_layout=config.option_layout)
+ parallel = uses_parallel_layout(cfg)
- items, skipped = items_from_rows(tok, read_jsonl(data), max_len, head_max_len)
+ rows = read_data(data, text_column=config.text_column, label_column=config.label_column,
+ question_id=config.question_id, instructions=config.instructions)
+ items, skipped = items_from_rows(tok, rows, max_len, head_max_len,
+ label_smoothing=config.label_smoothing)
if not items:
raise ValueError("%s produced no training items (skipped: %r)" % (data, skipped))
train_items, calib_items = split_calibration(items, config.calib_max, config.calib_frac, config.calib_seed)
@@@ -583,9 -708,28 +803,29 @@@
out_cfg.pop("temperature_by_options", None)
if fitted["temperature_by_options"]:
out_cfg["temperature_by_options"] = fitted["temperature_by_options"]
- out_cfg["training"] = dict(out_cfg.get("training") or {}, laya_train=asdict(config))
+ out_cfg["training"] = dict(out_cfg.get("training") or {}, laya_train=asdict(config),
+ laya_train_calibration=calibration)
save_checkpoint(model, tok, out_cfg, output_dir)
+
+ # Save the questions schema alongside the checkpoint for inference reuse
+ sample_questions = {}
+ for r in rows:
+ qs = r.get("questions")
+ if isinstance(qs, dict):
+ for qid, qdef in qs.items():
+ if qid not in sample_questions:
+ sample_questions[qid] = qdef
+ elif sample_questions[qid] != qdef:
+ import warnings
+ warnings.warn("Conflicting schema detected for question %r across rows; keeping first seen definition." % (qid,))
+ if sample_questions:
+ for d in (output_dir, os.path.join(output_dir, "checkpoint_latest")):
+ os.makedirs(d, exist_ok=True)
+ tmp_path = os.path.join(d, "questions.json.tmp")
+ with open(tmp_path, "w", encoding="utf-8") as f:
+ json.dump(sample_questions, f, indent=2)
+ os.replace(tmp_path, os.path.join(d, "questions.json"))
+
return {
"train_items": len(train_items),
"calibration_items": len(calib_items),
@@@ -594,6 -738,37 +834,38 @@@
"temperature": fitted["temperature"],
"temperature_by_options": fitted["temperature_by_options"],
"n_by_bucket": fitted["n_by_bucket"],
+ "calibration": calibration,
"output_dir": output_dir,
}
+
+
+ def dry_run(data: str, model_dir: str, config: Optional[TrainConfig] = None) -> Dict[str, Any]:
+ """Inspect dataset and build items without loading model weights; returns dataset stats."""
+ from transformers import AutoTokenizer
+ from .agent import _fix_tokenizer_config
+
+ config = config or TrainConfig()
+ config.validate()
+ resolved_dir = resolve_checkpoint_dir(model_dir)
+ _fix_tokenizer_config(resolved_dir)
+ tok = AutoTokenizer.from_pretrained(os.path.join(resolved_dir, "tokenizer"))
+ with open(os.path.join(resolved_dir, "rl_agent_config.json"), encoding="utf-8") as f:
+ cfg = json.load(f)
+ max_len = config.max_len or cfg.get("max_len", 512)
+ head_max_len = config.head_max_len or cfg.get("head_max_len", 192)
+
+ rows = read_data(data, text_column=config.text_column, label_column=config.label_column,
+ question_id=config.question_id, instructions=config.instructions)
+ items, skipped = items_from_rows(tok, rows, max_len, head_max_len,
+ label_smoothing=config.label_smoothing)
+ summary = {
+ "data": data,
+ "rows_read": len(rows),
+ "valid_items": len(items),
+ "skipped": skipped,
+ "max_len": max_len,
+ "head_max_len": head_max_len,
+ }
+ print("dry-run: %d rows read, %d valid items, skipped: %r"
+ % (len(rows), len(items), skipped), flush=True)
+ return summary
diff --cc tests/test_train.py
index 2ff10cba,9a60ae9a..bd2ee6a7
--- a/tests/test_train.py
+++ b/tests/test_train.py
@@@ -457,61 -522,71 +588,126 @@@ class EndToEndTests(unittest.TestCase)
with self.assertRaises(ValueError):
train_model(None, self.tok, [], TrainConfig(), torch.device("cpu"), 64, 40)
+ def test_laya_train_cli_parser_and_validation(self):
+ parser = build_train_parser()
+ args = parser.parse_args(["--data", "train.csv", "--out", "./out", "--label-smoothing", "0.1",
+ "--shuffle-options", "--freeze-encoder"])
+ self.assertEqual(args.data, "train.csv")
+ self.assertEqual(args.output_dir, "./out")
+ self.assertEqual(args.label_smoothing, 0.1)
+ self.assertTrue(args.shuffle_options)
+ self.assertTrue(args.freeze_encoder)
+
+ # --out is required when --dry-run is not set
+ code_missing_out = train_cli_main(["--data", "train.csv"])
+ self.assertEqual(code_missing_out, 2)
+
+ # --dry-run without --out succeeds parsing
+ dry_args = parser.parse_args(["--data", "train.csv", "--dry-run"])
+ self.assertIsNone(dry_args.output_dir)
+ self.assertTrue(dry_args.dry_run)
+
+ def test_laya_train_cli_runs_on_csv(self):
+ csv_path = self.root / "tickets.csv"
+ lines = ["text,department"]
+ for s in BILLING_STATES:
+ lines.append(f"{s},billing")
+ for s in TECH_STATES:
+ lines.append(f"{s},technical")
+ csv_path.write_text("\n".join(lines), encoding="utf-8")
+
+ out_dir = self.root / "out_cli"
+ code = train_cli_main([
+ "--data", str(csv_path),
+ "--base", str(self.root / "base"),
+ "--out", str(out_dir),
+ "--text-column", "text",
+ "--label-column", "department",
+ "--epochs", "1",
+ "--micro-batch", "4",
+ "--grad-accum", "1",
+ "--loss", "soft-ce",
+ "--label-smoothing", "0.05",
+ "--device", "cpu",
+ ])
+ self.assertEqual(code, 0)
+ self.assertTrue((out_dir / "model.safetensors").exists())
+ self.assertTrue((out_dir / "rl_agent_config.json").exists())
+ self.assertTrue((out_dir / "questions.json").exists())
+ saved_q = json.loads((out_dir / "questions.json").read_text(encoding="utf-8"))
+ self.assertIn("label", saved_q)
+ self.assertEqual(saved_q["label"]["criteria"], ["billing", "technical"])
+
+ agent = load(str(out_dir), device="cpu")
+ ans = agent.predict("please refund invoice", {"label": {"type": "choice", "instructions": "Classify",
+ "criteria": ["billing", "technical"]}})
+ self.assertIn(ans["answers"]["label"]["choice"], ["billing", "technical"])
+
+ # Test --dry-run
+ dry_code = train_cli_main([
+ "--data", str(csv_path),
+ "--base", str(self.root / "base"),
+ "--text-column", "text",
+ "--label-column", "department",
+ "--dry-run",
+ ])
+ self.assertEqual(dry_code, 0)
+
+class CalibrationReportTests(unittest.TestCase):
+ @staticmethod
+ def records(qtype, n, k=3, scale=1.0):
+ # Logits that favour the target option by `scale`; target one-hot on option 0.
+ return [(qtype, [scale] + [0.0] * (k - 1), [1.0] + [0.0] * (k - 1), k) for _ in range(n)]
+
+ def test_each_kind_of_weak_fit_is_named(self):
+ from laya.train import CALIB_WARN_N, calibration_report
+
+ records = (self.records(QTYPES["choice"], 5) + self.records(QTYPES["noul"], 30, k=2)
+ + self.records(QTYPES["score"], CALIB_WARN_N + 10))
+ report = calibration_report(records, [1.0, 1.0, 2.0]) # choice, score, noul
+ self.assertEqual(report["choice"]["items"], 5)
+ self.assertIn("not fitted", report["choice"]["issues"][0])
+ self.assertEqual(len(report["noul"]["issues"]), 1)
+ self.assertIn("only 30", report["noul"]["issues"][0])
+ self.assertEqual(len(report["score"]["issues"]), 1)
+ self.assertIn("unchanged at 1.0", report["score"]["issues"][0])
+ self.assertAlmostEqual(report["score"]["accuracy"], 1.0)
+
+ def test_clamped_and_healthy_fits(self):
+ from laya.train import CALIB_WARN_N, calibration_report
+
+ n = CALIB_WARN_N
+ records = self.records(QTYPES["choice"], n) + self.records(QTYPES["score"], n)
+ report = calibration_report(records, [TEMP_MIN, 1.3, 1.0]) # choice, score, noul
+ self.assertIn("clamp", report["choice"]["issues"][0])
+ self.assertEqual(report["score"]["issues"], [])
+ # a type absent from the data is reported, but not as a problem
+ self.assertEqual((report["noul"]["items"], report["noul"]["issues"]), (0, []))
+ self.assertNotIn("accuracy", report["noul"])
+ p = torch.softmax(torch.tensor([1.0, 0.0, 0.0]) / 1.3, -1)
+ self.assertAlmostEqual(report["score"]["mean_confidence"], p.max().item(), places=6)
+
+ def test_finetune_warns_and_records_a_weak_calibration(self):
+ with tempfile.TemporaryDirectory() as d:
+ root = Path(d)
+ make_checkpoint(root / "base", make_tokenizer())
+ config = TrainConfig(epochs=1, micro_batch=8, grad_accum=1, calib_frac=0.2, log_every=0)
+ # The rows go straight to finetune through read_jsonl rather than through a file: nothing
+ # here needs the JSONL parsing, which the end-to-end tests above already cover.
+ # warnings.catch_warnings, not assertWarns: assertWarns walks every loaded module, and
+ # transformers' lazy modules then try to import optional packages such as torchvision.
+ with patch("huggingface_hub.snapshot_download", side_effect=AssertionError("unexpected download")), \
+ patch("laya.train.read_jsonl", return_value=rows(2)), \
+ warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ report = finetune("rows.jsonl", str(root / "base"), str(root / "out"), config, device="cpu")
+ saved = json.loads((root / "out" / "rl_agent_config.json").read_text())
+ messages = [str(w.message) for w in caught if issubclass(w.category, RuntimeWarning)]
+ self.assertTrue(any(re.match(r"laya\.train: \w+ calibration: not fitted", m) for m in messages), messages)
+ self.assertEqual(saved["training"]["laya_train_calibration"], report["calibration"])
+ self.assertEqual(sum(e["items"] for e in report["calibration"].values()), report["calibration_items"])
+
+
if __name__ == "__main__":
unittest.main()