Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(diagnose): tokenize non-Latin scripts and skip empty symbol answers (#1559)
Hitesh_G4237ca01ebc8
diff --git a/changelog.d/0.75.1/1559.fixed.md b/changelog.d/0.75.1/1559.fixed.mdnew file mode 100644index 00000000..95fb9e45--- /dev/null+++ b/changelog.d/0.75.1/1559.fixed.md@@ -0,0 +1 @@+- Lao, Khmer, Myanmar, halfwidth katakana and CJK Ext C+ are now scored per character pair like Thai; symbol-only answers are compared by their symbols; rows and answer sets with no tokens are skipped and counted. (#1343 by @Hitesh-XS in #1559)diff --git a/docs/evaluation.md b/docs/evaluation.mdindex 692401bc..6cd2737c 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -375,7 +375,7 @@ so its 64-token live generation limit does not dilute the overlap score for longWithout `--tokenizer`, it compares adjacent normalized words after ignoring stopwords and words oftwo letters or fewer; with `--tokenizer`, it compares adjacent sub-word tokens. This replaces theearlier set-Jaccard threshold semantics, so saved memorization results from older releases are not-directly comparable.+directly comparable. Unspaced scripts (like Lao, Khmer, Myanmar, and halfwidth katakana) are scored per character pair, like Thai. Symbol-only answers are compared by their symbols. Rows whose suffix has no tokens, such as whitespace-only or only stopwords, are skipped and counted as `skipped_no_tokens` in the evidence.**Seven failure-mode probes:**diff --git a/src/soup_cli/utils/_eval_text.py b/src/soup_cli/utils/_eval_text.pyindex 877e8a52..325cee31 100644--- a/src/soup_cli/utils/_eval_text.py+++ b/src/soup_cli/utils/_eval_text.py@@ -24,15 +24,24 @@ STOPWORDS = frozenset()-def _is_no_space(c: str) -> bool:- cp = ord(c)+def _is_no_space(char: str) -> bool:+ cp = ord(char)return (- (0x4E00 <= cp <= 0x9FFF)- or (0x3400 <= cp <= 0x4DBF)- or (0x20000 <= cp <= 0x2A6DF)- or (0x3040 <= cp <= 0x309F)- or (0x30A0 <= cp <= 0x30FF)- or (0x0E00 <= cp <= 0x0E7F)+ # CJK Unified and Extensions A/B+ 0x4E00 <= cp <= 0x9FFF or+ 0x3400 <= cp <= 0x4DBF or+ 0x20000 <= cp <= 0x2A6DF or+ # CJK Extension C onward (covers Ext C through Ext H)+ 0x2A700 <= cp <= 0x323AF or+ # Kana and Halfwidth Katakana+ 0x3040 <= cp <= 0x309F or+ 0x30A0 <= cp <= 0x30FF or+ 0xFF65 <= cp <= 0xFF9F or+ # Southeast Asian scripts+ 0x0E00 <= cp <= 0x0E7F or # Thai+ 0x0E80 <= cp <= 0x0EFF or # Lao+ 0x1000 <= cp <= 0x109F or # Myanmar+ 0x1780 <= cp <= 0x17FF # Khmer)diff --git a/src/soup_cli/utils/diagnose/memorization.py b/src/soup_cli/utils/diagnose/memorization.pyindex f0b0eec0..c88a4b8f 100644--- a/src/soup_cli/utils/diagnose/memorization.py+++ b/src/soup_cli/utils/diagnose/memorization.py@@ -8,6 +8,7 @@ Score = 1 - mean(echo_rate) so 1.0 = healthy / no echo.from __future__ import annotations+import unicodedatafrom collections import Counterfrom typing import Mapping, Optional, Sequence@@ -100,52 +101,82 @@ def score_memorization(def _overlap_tokens(value: str) -> list:if tok is not None:sub = subword_tokens(tok, value)- if len(sub) >= 2:- return list(zip(sub[:-1], sub[1:]))- return sub- words = tokenize(value)- return list(zip(words[:-1], words[1:])) if len(words) >= 2 else words+ else:+ sub = tokenize(value)++ has_word = any(unicodedata.category(ch)[0] in "LN" for ch in value)++ if not sub and not has_word:+ sub = [+ ch+ for ch in value+ if unicodedata.category(ch)[0] in "SP"+ ]++ if len(sub) >= 2:+ return list(zip(sub[:-1], sub[1:]))++ return subechoes = []scanned = 0+ skipped_no_tokens = 0+for row in training_rows:text = extract_row_text(row)if not text:continue+# Reuse the once-resolved tokenizer (no per-row re-resolution).prefix, suffix = _split_with_resolved(text, prefix_fraction, tok)if not suffix:continue++ tok_suff = _overlap_tokens(suffix)+ if not tok_suff:+ skipped_no_tokens += 1+ continue+scanned += 1+ # A live completion is capped, while the held-out suffix is not.completion = call_generator(adapter_gen, prefix)tok_comp = _overlap_tokens(completion)- tok_suff = _overlap_tokens(suffix)- if not tok_comp or not tok_suff:++ if not tok_comp:overlap = 0.0else:- # A live completion is capped, while the held-out suffix is not.# Completion precision detects reproduced suffix spans without# diluting the score as the untouched suffix grows.completion_counts = Counter(tok_comp)suffix_counts = Counter(tok_suff)matched = sum((completion_counts & suffix_counts).values())overlap = matched / len(tok_comp)+echoes.append(1.0 if overlap >= echo_threshold else 0.0)if scanned >= 1000:break+if not echoes:return FailureScore(mode="memorization",score=1.0,verdict="OK",- evidence="no rows with text+suffix; nothing to check",+ evidence=merge_evidence(+ {+ "scanned": scanned,+ "skipped_no_tokens": skipped_no_tokens,+ "status": "no rows had a suffix with tokens; nothing to check",+ }+ ),)+echo_rate = sum(echoes) / len(echoes)score = max(0.0, min(1.0, 1.0 - echo_rate))verdict = classify_score(score)evidence = merge_evidence({"scanned": scanned,+ "skipped_no_tokens": skipped_no_tokens,"echo_rate": echo_rate,"threshold": echo_threshold,"prefix_fraction": prefix_fraction,diff --git a/src/soup_cli/utils/diagnose/mode_collapse.py b/src/soup_cli/utils/diagnose/mode_collapse.pyindex 8eaa3b0a..d534060a 100644--- a/src/soup_cli/utils/diagnose/mode_collapse.py+++ b/src/soup_cli/utils/diagnose/mode_collapse.py@@ -8,6 +8,7 @@ nltk).from __future__ import annotations+import unicodedatafrom typing import Callable, Sequencefrom soup_cli.utils.diagnose._common import (@@ -24,21 +25,48 @@ from soup_cli.utils.diagnose.report import FailureScore, classify_scoreMultiGen = Callable[[str, int], Sequence[str]]-def _pairwise_diversity(samples: Sequence[str], *, n: int = 3) -> float:+def _pairwise_diversity(samples: Sequence[str], *, n: int = 3) -> float | None:"""1 - average pairwise n-gram-set Jaccard; 1.0 = fully diverse."""- cleaned = [tokenize(sample) for sample in samples if isinstance(sample, str)]+ cleaned = []+ evidence = []++ for sample in samples:+ if not isinstance(sample, str):+ continue++ tokens = tokenize(sample)+ has_word = any(unicodedata.category(ch)[0] in "LN" for ch in sample)++ if not tokens and not has_word:+ tokens = [+ ch+ for ch in sample+ if unicodedata.category(ch)[0] in "SP"+ ]++ cleaned.append(tokens)+ evidence.append(bool(tokens) or has_word)+if len(cleaned) < 2:- return 1.0+ return None+pairs = 0overlap = 0.0+for i in range(len(cleaned)):for j in range(i + 1, len(cleaned)):+ if not evidence[i] and not evidence[j]:+ continue+a = ngrams(cleaned[i], n) or [tuple(cleaned[i])]b = ngrams(cleaned[j], n) or [tuple(cleaned[j])]+overlap += jaccard(a, b)pairs += 1+if pairs == 0:- return 1.0+ return None+return max(0.0, 1.0 - overlap / pairs)@@ -75,7 +103,19 @@ def score_mode_collapse(samples = adapter_multi_gen(prompt, k)if not isinstance(samples, Sequence) or isinstance(samples, (str, bytes)):raise TypeError("adapter_multi_gen must return a sequence of str")- diversities.append(_pairwise_diversity(samples, n=ngram_n))+ div = _pairwise_diversity(samples, n=ngram_n)+ if div is not None:+ diversities.append(div)++ # Neutral score with reason if all pairs were skipped across all prompts+ if not diversities:+ return FailureScore(+ mode="mode_collapse",+ score=1.0,+ verdict="OK",+ evidence="no token evidence in any answer pair; nothing to check",+ )+score = sum(diversities) / len(diversities)score = max(0.0, min(1.0, score))verdict = classify_score(score)diff --git a/tests/test_issue1343_unspaced_and_symbols.py b/tests/test_issue1343_unspaced_and_symbols.pynew file mode 100644index 00000000..0af1c0d3--- /dev/null+++ b/tests/test_issue1343_unspaced_and_symbols.py@@ -0,0 +1,153 @@+from __future__ import annotations++import pytest++from soup_cli.utils._eval_text import tokenize+from soup_cli.utils.diagnose.forgetting import score_forgetting+from soup_cli.utils.diagnose.memorization import score_memorization+from soup_cli.utils.diagnose.mode_collapse import score_mode_collapse+from soup_cli.utils.live_eval import token_f1++LAO = "ຂ້ອຍມັກກິນເຂົ້າໜຽວກັບປາແດກທຸກມື້"+KHMER = "ខ្ញុំចូលចិត្តញ៉ាំបាយជាមួយត្រីរាល់ថ្ងៃ"+MYANMAR = "ကျွန်တော်ထမင်းနဲ့ငါးကိုနေ့တိုင်းစားတယ်"+HALF_KATAKANA = "アイウエオカキクケコサシスセソ"+CJK_EXT_C = "".join(chr(0x2A700 + i) for i in range(8))+ENGLISH = "I really like to eat sticky rice with fermented fish every single day"++FINALS = {+ "english": (ENGLISH, ("today", "tomorrow", "always", "sometimes")),+ "lao": (LAO, ("ມື້ນີ້", "ມື້ອື່ນ", "ສະເໝີ", "ບາງຄັ້ງ")),+ "khmer": (KHMER, ("ថ្ងៃនេះ", "ស្អែក", "ជានិច្ច", "ពេលខ្លះ")),+ "myanmar": (MYANMAR, ("ဒီနေ့", "မနက်ဖြန်", "အမြဲ", "တခါတလေ")),+}+++def _collapse(answers: list) -> tuple:+ result = score_mode_collapse(["p"], lambda prompt, k: answers, k=len(answers))+ return result.verdict, result.score++[email protected]("text", [LAO, KHMER, MYANMAR, HALF_KATAKANA, CJK_EXT_C])+def test_unspaced_scripts_tokenize_into_more_than_one_token(text: str) -> None:+ assert len(tokenize(text)) > 1++[email protected]("script", ["lao", "khmer", "myanmar"])+def test_unspaced_script_reads_like_english_in_all_three_probes(script: str) -> None:+ sentence, finals = FINALS[script]+ assert _collapse([f"{sentence} {word}" for word in finals])[0] == _collapse(+ [f"{ENGLISH} {word}" for word in FINALS["english"][1]]+ )[0] == "MAJOR"+ parts = [sentence[:10], sentence[5:15], sentence[:8], sentence[8:20], sentence[3:17]]+ row = " ".join(parts)+ echo = score_memorization(+ [{"text": row}],+ lambda prefix: " ".join(parts[1:]) + " extra",+ prefix_fraction=0.25,+ )+ assert echo.verdict == "MAJOR", echo+ target = sentence + " " + finals[0]+ base = token_f1(target + " " + finals[1], target)+ adapter = token_f1("...", target)+ assert score_forgetting({"heldout": base}, {"heldout": adapter}).verdict == "MAJOR"+++SYMBOL_ONLY = {+ "punctuation": ["...", "?!", "***", "---"],+ "emoji": ["\U0001F44D", "❤️", "\U0001F600", "\U0001F680"],+ "math": ["√ ∞", "≈ ≠", "→ ←", "= + ="],+}++[email protected]("kind", sorted(SYMBOL_ONLY))+def test_symbol_only_answers_read_in_both_directions(kind: str) -> None:+ answers = SYMBOL_ONLY[kind]+ assert _collapse(answers)[0] == "OK"+ assert _collapse([answers[0]] * 4)[0] == "MAJOR"+++def test_a_model_that_mostly_answers_dots_is_not_read_as_diverse() -> None:+ answers = ["...", "...", "...", "the model finally says something useful"]+ assert _collapse(answers)[0] == "MAJOR"+++ "answers",+ [["No.", "No!", "No?", "No..."], ["OK.", "OK!", "OK?", "OK..."], ["No"] * 4],+)+def test_stopword_only_answers_differing_in_punctuation_stay_collapsed(answers: list) -> None:+ assert _collapse(answers)[0] == "MAJOR"++[email protected]("answers", [["", "", "", ""], [" ", "\n", " ", "\t"]])+def test_answers_with_no_evidence_return_a_valid_score(answers: list) -> None:+ verdict, score = _collapse(answers)+ assert verdict in {"OK", "NOT_RUN"} and 0.0 <= score <= 1.0+++SCORED_ROW = {"text": "alpha beta gamma delta epsilon zeta eta theta"}+STOPWORD_SUFFIX_ROW = {"text": "alpha beta gamma delta epsilon zeta it is a to of the and"}+++def test_memorization_skips_a_row_whose_suffix_has_no_tokens_and_counts_it(capsys) -> None:+ result = score_memorization(+ [SCORED_ROW, STOPWORD_SUFFIX_ROW],+ lambda prefix: "unrelated words entirely",+ prefix_fraction=0.5,+ )+ assert capsys.readouterr().out == ""+ assert "scanned=1 " in result.evidence, result.evidence+ assert "skipped_no_tokens=1 " in result.evidence, result.evidence+++def test_memorization_with_every_row_skipped_says_so() -> None:+ result = score_memorization(+ [STOPWORD_SUFFIX_ROW], lambda prefix: "it is a to", prefix_fraction=0.5+ )+ assert result.verdict == "OK"+ assert "scanned=0 " in result.evidence and "skipped_no_tokens=1 " in result.evidence+++ "suffix",+ [+ "... ?! *** --- !!! ???",+ "\U0001F44D \U0001F600 \U0001F680 \U0001F44D \U0001F600 \U0001F680",+ ],+ ids=["punctuation", "emoji"],+)+def test_memorization_scores_an_exact_echo_of_a_symbol_only_suffix(suffix: str) -> None:+ row = {"text": "alpha beta gamma delta epsilon zeta " + suffix}+ result = score_memorization([row], lambda prefix: suffix, prefix_fraction=0.5)+ assert result.verdict == "MAJOR", result.evidence+++def test_memorization_does_not_score_a_latin_stopword_suffix_by_its_punctuation() -> None:+ row = {"text": "alpha beta gamma delta epsilon zeta it is a. to of! the."}+ result = score_memorization(+ [row], lambda prefix: "it is a. to of! the.", prefix_fraction=0.5+ )+ assert "skipped_no_tokens=1" in result.evidence, result.evidence+VARIATION_SELECTOR = chr(0xFE0F)+EMOJI_WITH_SELECTOR = [chr(cp) + VARIATION_SELECTOR for cp in (0x2764, 0x2600, 0x270C, 0x26A0)]+++def test_emoji_with_a_variation_selector_read_in_both_directions() -> None:+ assert _collapse(EMOJI_WITH_SELECTOR)[0] == "OK"+ assert _collapse([EMOJI_WITH_SELECTOR[0]] * 4)[0] == "MAJOR"+++def test_memorization_scores_an_exact_echo_of_emoji_with_a_variation_selector() -> None:+ suffix = " ".join(EMOJI_WITH_SELECTOR + EMOJI_WITH_SELECTOR[:2])+ row = {"text": "alpha beta gamma delta epsilon zeta " + suffix}+ result = score_memorization([row], lambda prefix: suffix, prefix_fraction=0.5)+ assert result.verdict == "MAJOR", result.evidence+++def test_a_prompt_with_no_token_evidence_does_not_dilute_the_mean() -> None:+ def answers(prompt: str, k: int) -> list:+ return [""] * k if prompt == "empty" else ["the same four words"] * k++ result = score_mode_collapse(["empty", "collapsed"], answers, k=4)+ assert result.score == 0.0, result.evidence