tuneweights 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ dist/
2
+ .venv/
3
+ __pycache__/
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.5
2
+ Name: tuneweights
3
+ Version: 0.1.0
4
+ Summary: Check fine-tuning datasets before you train. From Tuneweights, fine-tuning for open-weight models.
5
+ Project-URL: Homepage, https://tuneweights.com
6
+ Project-URL: Documentation, https://tuneweights.com/docs
7
+ License: MIT
8
+ Requires-Python: >=3.9
9
+ Provides-Extra: exact
10
+ Requires-Dist: jinja2; extra == 'exact'
11
+ Requires-Dist: transformers; extra == 'exact'
12
+ Description-Content-Type: text/markdown
13
+
14
+ # tuneweights
15
+
16
+ Check a fine-tuning dataset before you train on it. Finds broken records, duplicates and examples that are too
17
+ long, estimates tokens, and shows how the file will split into training and held-out examples. Runs on your
18
+ machine; nothing is uploaded.
19
+
20
+ ```bash
21
+ pip install tuneweights
22
+ tuneweights check data.jsonl
23
+ ```
24
+
25
+ ```
26
+ data.jsonl: 1,200 examples, 609,385 tokens (estimate; --exact for the real count)
27
+ split: 1,068 to train, 132 held back to measure the result
28
+ Ready to train on. Start a job at https://tuneweights.com/app (your first job is free).
29
+ ```
30
+
31
+ ## Commands
32
+
33
+ | Command | What it does |
34
+ |---|---|
35
+ | `tuneweights check FILE` | Checks a `.jsonl` or `.csv` dataset. Exit code 0 if ready, 1 if not, so it works in CI |
36
+ | `tuneweights check FILE --max-len 4096` | Longest allowed example: 512, 1024, 2048 (default) or 4096 tokens |
37
+ | `tuneweights check FILE --exact` | Exact token counts with the Qwen3-8B tokenizer (`pip install 'tuneweights[exact]'`) |
38
+ | `tuneweights check FILE --json` | The report as JSON |
39
+ | `tuneweights sample` | Writes `sample.jsonl`, 20 examples to start from |
40
+
41
+ ## Dataset format
42
+
43
+ JSONL, one example per line, in the chat format or as prompt and completion:
44
+
45
+ ```json
46
+ {"messages": [{"role": "user", "content": "My debit card was charged twice."}, {"role": "assistant", "content": "duplicate_transaction"}]}
47
+ {"prompt": "My debit card was charged twice.", "completion": "duplicate_transaction"}
48
+ ```
49
+
50
+ Or a CSV with `input` and `output` columns (and an optional `system` column). The model learns the last assistant
51
+ message of each example. These are the same rules [tuneweights.com](https://tuneweights.com) applies before training.
52
+
53
+ The sample data is from PolyAI's Banking77 dataset (CC BY 4.0).
@@ -0,0 +1,40 @@
1
+ # tuneweights
2
+
3
+ Check a fine-tuning dataset before you train on it. Finds broken records, duplicates and examples that are too
4
+ long, estimates tokens, and shows how the file will split into training and held-out examples. Runs on your
5
+ machine; nothing is uploaded.
6
+
7
+ ```bash
8
+ pip install tuneweights
9
+ tuneweights check data.jsonl
10
+ ```
11
+
12
+ ```
13
+ data.jsonl: 1,200 examples, 609,385 tokens (estimate; --exact for the real count)
14
+ split: 1,068 to train, 132 held back to measure the result
15
+ Ready to train on. Start a job at https://tuneweights.com/app (your first job is free).
16
+ ```
17
+
18
+ ## Commands
19
+
20
+ | Command | What it does |
21
+ |---|---|
22
+ | `tuneweights check FILE` | Checks a `.jsonl` or `.csv` dataset. Exit code 0 if ready, 1 if not, so it works in CI |
23
+ | `tuneweights check FILE --max-len 4096` | Longest allowed example: 512, 1024, 2048 (default) or 4096 tokens |
24
+ | `tuneweights check FILE --exact` | Exact token counts with the Qwen3-8B tokenizer (`pip install 'tuneweights[exact]'`) |
25
+ | `tuneweights check FILE --json` | The report as JSON |
26
+ | `tuneweights sample` | Writes `sample.jsonl`, 20 examples to start from |
27
+
28
+ ## Dataset format
29
+
30
+ JSONL, one example per line, in the chat format or as prompt and completion:
31
+
32
+ ```json
33
+ {"messages": [{"role": "user", "content": "My debit card was charged twice."}, {"role": "assistant", "content": "duplicate_transaction"}]}
34
+ {"prompt": "My debit card was charged twice.", "completion": "duplicate_transaction"}
35
+ ```
36
+
37
+ Or a CSV with `input` and `output` columns (and an optional `system` column). The model learns the last assistant
38
+ message of each example. These are the same rules [tuneweights.com](https://tuneweights.com) applies before training.
39
+
40
+ The sample data is from PolyAI's Banking77 dataset (CC BY 4.0).
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "tuneweights"
7
+ version = "0.1.0"
8
+ description = "Check fine-tuning datasets before you train. From Tuneweights, fine-tuning for open-weight models."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ dependencies = []
13
+
14
+ [project.optional-dependencies]
15
+ exact = ["transformers", "jinja2"] # exact token counts with the Qwen3-8B tokenizer
16
+
17
+ [project.scripts]
18
+ tuneweights = "tuneweights.cli:main"
19
+
20
+ [project.urls]
21
+ Homepage = "https://tuneweights.com"
22
+ Documentation = "https://tuneweights.com/docs"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/tuneweights"]
26
+
27
+ [tool.pytest.ini_options]
28
+ pythonpath = ["src"]
@@ -0,0 +1,2 @@
1
+ """Tuneweights: fine-tune open-weight models on your data. https://tuneweights.com"""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,116 @@
1
+ """tuneweights: check a fine-tuning dataset before you train.
2
+
3
+ tuneweights check data.jsonl broken records, duplicates, examples that are too long, token estimate
4
+ tuneweights check data.csv --max-len 4096 --exact
5
+ tuneweights sample writes sample.jsonl (20 Banking77 examples, CC BY 4.0)
6
+
7
+ Exit code 0 when the file is ready to train on, 1 when it has problems: usable in CI.
8
+ Same rules as the trainer at tuneweights.com. Nothing is uploaded.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from . import __version__, dataset
18
+
19
+ # Qwen3-8B as Tuneweights trains it: same revision, thinking off. Used only with --exact.
20
+ MODEL = {"repo": "Qwen/Qwen3-8B", "revision": "b968826d9c46dd6066d109eabc6255188de91218", "chat": {"enable_thinking": False}}
21
+ LENGTHS = [512, 1024, 2048, 4096]
22
+
23
+
24
+ def estimate_tokens(msgs: list) -> int:
25
+ """Without a tokenizer: about 4 characters a token, plus chat-template overhead. Same as the website."""
26
+ return -(-sum(len(m["content"]) for m in msgs) // 4) + 8 * len(msgs) + 8
27
+
28
+
29
+ def check(args) -> int:
30
+ path = Path(args.file)
31
+ if not path.is_file():
32
+ print(f"No such file: {path}", file=sys.stderr)
33
+ return 2
34
+ text = path.read_text(encoding="utf-8")
35
+ tok = None
36
+ if args.exact:
37
+ try:
38
+ from transformers import AutoTokenizer
39
+ except ImportError:
40
+ print("--exact needs transformers: pip install 'tuneweights[exact]'", file=sys.stderr)
41
+ return 2
42
+ tok = AutoTokenizer.from_pretrained(MODEL["repo"], revision=MODEL["revision"])
43
+ report, examples = dataset.check(text, path.name, tok, MODEL["chat"], args.max_len)
44
+ if tok is None: # estimate tokens and lengths the same way the website does
45
+ report.tokens = 0
46
+ report.too_long, report.too_long_count = [], 0
47
+ for n, msgs, err in dataset.parse(text, path.name):
48
+ if err:
49
+ continue
50
+ t = estimate_tokens(msgs)
51
+ report.tokens += t
52
+ if t > args.max_len:
53
+ report.too_long_count += 1
54
+ if len(report.too_long) < dataset.MAX_PROBLEMS_SHOWN:
55
+ report.too_long.append({"record": n, "tokens": t})
56
+ train, val = dataset.split(examples)
57
+
58
+ if args.json:
59
+ out = report.as_dict() | {"train": len(train), "validation": len(val), "tokens_exact": tok is not None}
60
+ out.pop("preview", None)
61
+ print(json.dumps(out, indent=1))
62
+ return 0 if report.ok() else 1
63
+
64
+ tokens = f"{report.tokens:,} tokens" + ("" if tok else " (estimate; --exact for the real count)")
65
+ print(f"{path.name}: {report.valid:,} examples, {tokens}")
66
+ print(f" split: {len(train):,} to train, {len(val):,} held back to measure the result")
67
+ if report.duplicates:
68
+ print(f" {report.duplicates:,} exact duplicates (allowed; copies stay on the same side of the split)")
69
+ for p in report.invalid:
70
+ print(f" record {p['record']}: {p['reason']}")
71
+ if report.invalid_count > len(report.invalid):
72
+ print(f" ...and {report.invalid_count - len(report.invalid):,} more broken records")
73
+ for p in report.too_long:
74
+ print(f" record {p['record']}: about {p['tokens']:,} tokens, over --max-len {args.max_len}")
75
+ if report.too_long_count > len(report.too_long):
76
+ print(f" ...and {report.too_long_count - len(report.too_long):,} more that are too long")
77
+ if report.ok():
78
+ print("Ready to train on. Start a job at https://tuneweights.com/app (your first job is free).")
79
+ return 0
80
+ if report.valid == 0:
81
+ print("No usable examples. See https://tuneweights.com/docs#dataset for the format.")
82
+ else:
83
+ print("Fix the records above, then check again.")
84
+ return 1
85
+
86
+
87
+ def sample(args) -> int:
88
+ out = Path(args.output)
89
+ if out.exists() and not args.force:
90
+ print(f"{out} already exists. Use --force to overwrite.", file=sys.stderr)
91
+ return 2
92
+ out.write_text((Path(__file__).parent / "sample.jsonl").read_text(encoding="utf-8"), encoding="utf-8")
93
+ print(f"Wrote {out}: 20 Banking77 examples (CC BY 4.0) in the chat format. Try: tuneweights check {out}")
94
+ return 0
95
+
96
+
97
+ def main(argv: list | None = None) -> int:
98
+ ap = argparse.ArgumentParser(prog="tuneweights", description="Check fine-tuning datasets before you train. https://tuneweights.com")
99
+ ap.add_argument("--version", action="version", version=f"tuneweights {__version__}")
100
+ sub = ap.add_subparsers(dest="cmd", required=True)
101
+ c = sub.add_parser("check", help="check a .jsonl or .csv dataset")
102
+ c.add_argument("file")
103
+ c.add_argument("--max-len", type=int, default=2048, choices=LENGTHS, help="longest example in tokens (default 2048)")
104
+ c.add_argument("--exact", action="store_true", help="count tokens with the Qwen3-8B tokenizer (needs tuneweights[exact])")
105
+ c.add_argument("--json", action="store_true", help="print the report as JSON")
106
+ c.set_defaults(fn=check)
107
+ s = sub.add_parser("sample", help="write a small sample dataset")
108
+ s.add_argument("-o", "--output", default="sample.jsonl")
109
+ s.add_argument("--force", action="store_true")
110
+ s.set_defaults(fn=sample)
111
+ args = ap.parse_args(argv)
112
+ return args.fn(args)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ sys.exit(main())
@@ -0,0 +1,162 @@
1
+ """Read, check and split a fine-tuning dataset. Runs before any GPU is started, so bad data costs nothing.
2
+
3
+ Accepted input, one example per record:
4
+ JSONL {"messages": [{"role": "system"|"user"|"assistant", "content": "..."}, ...]} last message from the assistant
5
+ {"prompt": "...", "completion": "..."}
6
+ CSV columns "input" and "output" (any case), optional "system"
7
+
8
+ Every example becomes a list of chat messages. The model learns only the last assistant message.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import csv
13
+ import hashlib
14
+ import io
15
+ import json
16
+ from dataclasses import dataclass, field
17
+
18
+ ROLES = {"system", "user", "assistant"}
19
+ MAX_PROBLEMS_SHOWN = 20
20
+
21
+
22
+ @dataclass
23
+ class Report:
24
+ total: int = 0 # records read (non-empty lines or CSV rows)
25
+ valid: int = 0
26
+ invalid: list = field(default_factory=list) # [{"record": n, "reason": "..."}], first MAX_PROBLEMS_SHOWN
27
+ invalid_count: int = 0
28
+ duplicates: int = 0 # valid examples that repeat an earlier one exactly
29
+ too_long: list = field(default_factory=list) # [{"record": n, "tokens": t}], first MAX_PROBLEMS_SHOWN
30
+ too_long_count: int = 0
31
+ tokens: int | None = None # prompt + answer tokens over valid examples, if a tokenizer was given
32
+ preview: list = field(default_factory=list) # first 5 valid examples
33
+
34
+ def ok(self) -> bool:
35
+ """Training can start: at least one usable example and nothing rejected."""
36
+ return self.valid > 0 and self.invalid_count == 0 and self.too_long_count == 0
37
+
38
+ def as_dict(self) -> dict:
39
+ return {k: getattr(self, k) for k in self.__dataclass_fields__} | {"ok": self.ok()}
40
+
41
+
42
+ def _check_messages(msgs) -> str | None:
43
+ if not isinstance(msgs, list) or len(msgs) < 2:
44
+ return "\"messages\" must be a list with at least a user and an assistant message"
45
+ for m in msgs:
46
+ if not isinstance(m, dict) or m.get("role") not in ROLES:
47
+ return "each message needs a role of system, user or assistant"
48
+ if not isinstance(m.get("content"), str) or not m["content"].strip():
49
+ return f"a {m['role']} message has empty or non-text content"
50
+ if msgs[-1]["role"] != "assistant":
51
+ return "the last message must be from the assistant (the answer to learn)"
52
+ if not any(m["role"] == "user" for m in msgs[:-1]):
53
+ return "there is no user message before the answer"
54
+ return None
55
+
56
+
57
+ def _from_json(obj) -> tuple[list | None, str | None]:
58
+ if not isinstance(obj, dict):
59
+ return None, "each line must be a JSON object"
60
+ if "messages" in obj:
61
+ err = _check_messages(obj["messages"])
62
+ return (None, err) if err else ([{"role": m["role"], "content": m["content"]} for m in obj["messages"]], None)
63
+ if "prompt" in obj or "completion" in obj:
64
+ p, c = obj.get("prompt"), obj.get("completion")
65
+ if not isinstance(p, str) or not p.strip() or not isinstance(c, str) or not c.strip():
66
+ return None, "\"prompt\" and \"completion\" must both be non-empty text"
67
+ return [{"role": "user", "content": p}, {"role": "assistant", "content": c}], None
68
+ return None, "expected \"messages\", or \"prompt\" and \"completion\""
69
+
70
+
71
+ def parse(text: str, filename: str) -> list[tuple[int, list | None, str | None]]:
72
+ """(record number, messages or None, reason or None) for every record in the file."""
73
+ if filename.lower().endswith(".csv"):
74
+ reader = csv.DictReader(io.StringIO(text))
75
+ cols = {c.strip().lower(): c for c in (reader.fieldnames or [])}
76
+ if "input" not in cols or "output" not in cols:
77
+ return [(1, None, "the CSV needs \"input\" and \"output\" columns")]
78
+ out = []
79
+ for n, row in enumerate(reader, start=1):
80
+ i, o, s = row.get(cols["input"]) or "", row.get(cols["output"]) or "", row.get(cols.get("system", ""), "") or ""
81
+ if not i.strip() or not o.strip():
82
+ out.append((n, None, "\"input\" and \"output\" must both be filled in"))
83
+ continue
84
+ msgs = ([{"role": "system", "content": s}] if s.strip() else []) + \
85
+ [{"role": "user", "content": i}, {"role": "assistant", "content": o}]
86
+ out.append((n, msgs, None))
87
+ return out
88
+ if not filename.lower().endswith(".jsonl"):
89
+ return [(1, None, "upload a .jsonl or .csv file")]
90
+ out = []
91
+ n = 0
92
+ for line in text.splitlines():
93
+ if not line.strip():
94
+ continue
95
+ n += 1
96
+ try:
97
+ msgs, err = _from_json(json.loads(line))
98
+ except json.JSONDecodeError:
99
+ msgs, err = None, "not valid JSON"
100
+ out.append((n, msgs, err))
101
+ return out
102
+
103
+
104
+ def key(msgs: list) -> str:
105
+ """Identity of an example: exact duplicates share a key."""
106
+ return hashlib.sha256(json.dumps(msgs, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
107
+
108
+
109
+ def render(msgs: list, tokenizer, chat_kwargs: dict) -> dict:
110
+ """{prompt, completion} as the model sees them at inference: prompt = the chat up to the answer with the
111
+ generation prompt, completion = the answer and end of turn. Loss is on the completion only."""
112
+ prompt = tokenizer.apply_chat_template(msgs[:-1], tokenize=False, add_generation_prompt=True, **chat_kwargs)
113
+ full = tokenizer.apply_chat_template(msgs, tokenize=False, **chat_kwargs)
114
+ if not full.startswith(prompt):
115
+ raise ValueError("the chat template renders the prompt differently inside a full conversation")
116
+ return {"prompt": prompt, "completion": full[len(prompt):]}
117
+
118
+
119
+ def check(text: str, filename: str, tokenizer=None, chat_kwargs: dict | None = None, max_seq_len: int = 2048) -> tuple[Report, list]:
120
+ """Report on the file and the valid examples (messages lists, in file order)."""
121
+ r, seen, examples = Report(), set(), []
122
+ for n, msgs, err in parse(text, filename):
123
+ r.total += 1
124
+ if err:
125
+ r.invalid_count += 1
126
+ if len(r.invalid) < MAX_PROBLEMS_SHOWN:
127
+ r.invalid.append({"record": n, "reason": err})
128
+ continue
129
+ if tokenizer is not None:
130
+ ex = render(msgs, tokenizer, chat_kwargs or {})
131
+ t = len(tokenizer(ex["prompt"] + ex["completion"], add_special_tokens=False)["input_ids"])
132
+ r.tokens = (r.tokens or 0) + t
133
+ if t > max_seq_len:
134
+ r.too_long_count += 1
135
+ if len(r.too_long) < MAX_PROBLEMS_SHOWN:
136
+ r.too_long.append({"record": n, "tokens": t})
137
+ k = key(msgs)
138
+ if k in seen:
139
+ r.duplicates += 1
140
+ seen.add(k)
141
+ r.valid += 1
142
+ if len(r.preview) < 5:
143
+ r.preview.append(msgs)
144
+ examples.append(msgs)
145
+ return r, examples
146
+
147
+
148
+ def split(examples: list, val_percent: int = 10) -> tuple[list, list]:
149
+ """Reproducible train/validation split by hash of each example, so the same file always splits the same way
150
+ and duplicates always land on the same side. Keeps at least one example on each side when there are two or more."""
151
+ train, val = [], []
152
+ for msgs in examples:
153
+ (val if int(key(msgs)[:8], 16) % 100 < val_percent else train).append(msgs)
154
+ def move(src, dst): # move one example and every copy of it
155
+ k = key(src[-1])
156
+ dst.extend(m for m in src if key(m) == k)
157
+ src[:] = [m for m in src if key(m) != k]
158
+ if not val and len({key(m) for m in train}) > 1:
159
+ move(train, val)
160
+ if not train and len({key(m) for m in val}) > 1:
161
+ move(val, train)
162
+ return train, val
@@ -0,0 +1,20 @@
1
+ {"messages": [{"role": "user", "content": "Do you need my birthdate?"}, {"role": "assistant", "content": "why_verify_identity"}]}
2
+ {"messages": [{"role": "user", "content": "Why was my cash withdrawal cancelled at the ATM?"}, {"role": "assistant", "content": "declined_cash_withdrawal"}]}
3
+ {"messages": [{"role": "user", "content": "Why was I charged an extra fee when using an ATM?"}, {"role": "assistant", "content": "cash_withdrawal_charge"}]}
4
+ {"messages": [{"role": "user", "content": "I believe there is a mistake because a payment I didn't make shows in my app."}, {"role": "assistant", "content": "card_payment_not_recognised"}]}
5
+ {"messages": [{"role": "user", "content": "What went wrong with my transfer?"}, {"role": "assistant", "content": "declined_transfer"}]}
6
+ {"messages": [{"role": "user", "content": "Am I able to Top Up with Apply Pay?"}, {"role": "assistant", "content": "apple_pay_or_google_pay"}]}
7
+ {"messages": [{"role": "user", "content": "My app says I withdraw funds from my account through an ATM."}, {"role": "assistant", "content": "cash_withdrawal_not_recognised"}]}
8
+ {"messages": [{"role": "user", "content": "I got charged a service fee on my account. Can it be waived since I didn't know about it before?"}, {"role": "assistant", "content": "card_payment_fee_charged"}]}
9
+ {"messages": [{"role": "user", "content": "Why was my transfer stopped ?"}, {"role": "assistant", "content": "beneficiary_not_allowed"}]}
10
+ {"messages": [{"role": "user", "content": "What foreign exchange rate will I get?"}, {"role": "assistant", "content": "exchange_rate"}]}
11
+ {"messages": [{"role": "user", "content": "I have a reverted top up I made and wanted to know why it didn't go through."}, {"role": "assistant", "content": "top_up_reverted"}]}
12
+ {"messages": [{"role": "user", "content": "How can I add money to my account from another account I have?"}, {"role": "assistant", "content": "transfer_into_account"}]}
13
+ {"messages": [{"role": "user", "content": "I have a transfer that was declined."}, {"role": "assistant", "content": "declined_transfer"}]}
14
+ {"messages": [{"role": "user", "content": "Can I cancel a transfer I made"}, {"role": "assistant", "content": "cancel_transfer"}]}
15
+ {"messages": [{"role": "user", "content": "Would I be charged any fees if I added money to my account using an international card?"}, {"role": "assistant", "content": "top_up_by_card_charge"}]}
16
+ {"messages": [{"role": "user", "content": "I made a transfer from France two days ago now but there hasn't made it there yet. Do international transfers take longer?"}, {"role": "assistant", "content": "balance_not_updated_after_bank_transfer"}]}
17
+ {"messages": [{"role": "user", "content": "I want to get a Visa and Mastercard, is it possible to get both from you?"}, {"role": "assistant", "content": "visa_or_mastercard"}]}
18
+ {"messages": [{"role": "user", "content": "There are a couple payments with my card shown in the app that i really didn't make myself. What's happenning with this, does someone has access to my card?!"}, {"role": "assistant", "content": "card_payment_not_recognised"}]}
19
+ {"messages": [{"role": "user", "content": "How do I exchange currencies with this"}, {"role": "assistant", "content": "exchange_via_app"}]}
20
+ {"messages": [{"role": "user", "content": "How long does it take for a top up to be approved?"}, {"role": "assistant", "content": "pending_top_up"}]}
@@ -0,0 +1,47 @@
1
+ import json
2
+ from pathlib import Path
3
+
4
+ from tuneweights import cli
5
+
6
+ ROOT = Path(__file__).resolve().parents[2]
7
+
8
+
9
+ def test_dataset_module_matches_trainer():
10
+ """The CLI ships a copy of the trainer's dataset rules; they must stay identical."""
11
+ a = (ROOT / "trainer" / "tuneweights" / "dataset.py").read_text()
12
+ b = (ROOT / "cli" / "src" / "tuneweights" / "dataset.py").read_text()
13
+ assert a == b, "copy trainer/tuneweights/dataset.py to cli/src/tuneweights/dataset.py"
14
+
15
+
16
+ def test_sample_then_check_ok(tmp_path, capsys):
17
+ out = tmp_path / "s.jsonl"
18
+ assert cli.main(["sample", "-o", str(out)]) == 0
19
+ assert cli.main(["check", str(out)]) == 0
20
+ text = capsys.readouterr().out
21
+ assert "20 examples" in text and "Ready to train on" in text
22
+
23
+
24
+ def test_problems_exit_1(tmp_path, capsys):
25
+ f = tmp_path / "bad.jsonl"
26
+ f.write_text('{"prompt": "a", "completion": "b"}\nnot json\n{"messages": [{"role": "user", "content": "hi"}]}\n')
27
+ assert cli.main(["check", str(f)]) == 1
28
+ text = capsys.readouterr().out
29
+ assert "record 2: not valid JSON" in text and "record 3:" in text
30
+
31
+
32
+ def test_too_long_and_json(tmp_path, capsys):
33
+ f = tmp_path / "long.jsonl"
34
+ f.write_text(json.dumps({"prompt": "x " * 2000, "completion": "y"}) + "\n")
35
+ assert cli.main(["check", str(f), "--max-len", "512", "--json"]) == 1
36
+ r = json.loads(capsys.readouterr().out)
37
+ assert r["too_long_count"] == 1 and r["valid"] == 1 and r["ok"] is False
38
+
39
+
40
+ def test_csv(tmp_path, capsys):
41
+ f = tmp_path / "d.csv"
42
+ f.write_text('input,output\n"Card charged twice, help",duplicate_transaction\n')
43
+ assert cli.main(["check", str(f)]) == 0
44
+
45
+
46
+ def test_missing_file(capsys):
47
+ assert cli.main(["check", "/nonexistent.jsonl"]) == 2