| import subprocess |
| import tempfile |
| import unittest |
| from pathlib import Path |
| from types import SimpleNamespace |
| from unittest.mock import Mock, patch |
|
|
| from hf_doc_translation.config import load_config |
| from hf_doc_translation.markdown import parse_markdown |
| from hf_doc_translation.protect import protected_values |
| from hf_doc_translation.sync import ( |
| _clone_source, |
| _install_transformers_dependencies, |
| _resolve_checkout, |
| _sentence_parts, |
| _translate_segment_with_retry, |
| _validated_cached_translation, |
| run_sync, |
| ) |
| from hf_doc_translation.translate import ContinuousBatchTranslator, _causal_lm_load_spec |
|
|
|
|
| class SyncTest(unittest.TestCase): |
| def test_structural_retry_splits_existing_protected_text(self): |
| config = SimpleNamespace( |
| glossary=(), |
| validation={ |
| "min_japanese_characters": 1, |
| "max_untranslated_english_ratio": 1.0, |
| "min_length_ratio": 0.1, |
| "max_length_ratio": 4.0, |
| }, |
| continuous_batching={"max_requests_per_batch": 32}, |
| ) |
| page = parse_markdown( |
| Path("page.md"), |
| "First 114,800 and 76. Second speech-to-speech/text.\n", |
| ) |
| segment = page.segments[0] |
|
|
| class Translator: |
| def __init__(self): |
| self.calls = [] |
|
|
| def translate_many(self, texts): |
| self.calls.append(list(texts)) |
| return [ |
| text.replace("First", "最初").replace("Second", "次") |
| for text in texts |
| ] |
|
|
| translator = Translator() |
| metrics = {} |
|
|
| response = _translate_segment_with_retry( |
| segment, |
| translator, |
| config, |
| metrics, |
| initial_error=ValueError("model dropped sentinels"), |
| ) |
|
|
| self.assertTrue(translator.calls) |
| self.assertFalse(any(protected_values(text) for call in translator.calls for text in call)) |
| self.assertEqual( |
| [int(sentinel[5:9]) for sentinel in segment.protected.sentinels], |
| [1, 2, 0, 3], |
| ) |
| self.assertEqual(metrics["retries"], 1) |
| self.assertEqual(metrics["sentinel_safe_retries"], 1) |
| self.assertIn("最初", segment.protected.restore(response)) |
| self.assertIn("次", segment.protected.restore(response)) |
|
|
| def test_single_sentence_retry_does_not_create_an_empty_piece(self): |
| source = "Translate one sentence.\n" |
|
|
| self.assertEqual(_sentence_parts(source), [source]) |
|
|
| def test_retry_does_not_split_inside_a_protected_comment(self): |
| config = SimpleNamespace( |
| glossary=(), |
| validation={}, |
| continuous_batching={"max_requests_per_batch": 32}, |
| ) |
| page = parse_markdown( |
| Path("page.md"), |
| "<!-- A protected sentence. Another protected sentence. -->\n", |
| ) |
| segment = page.segments[0] |
| translator = Mock() |
|
|
| response = _translate_segment_with_retry( |
| segment, |
| translator, |
| config, |
| {}, |
| initial_error=ValueError("model changed protected text"), |
| ) |
|
|
| translator.translate_many.assert_not_called() |
| self.assertEqual(segment.protected.restore(response), segment.source) |
|
|
| def test_sentinel_free_retry_batches_prose_chunks(self): |
| config = SimpleNamespace( |
| glossary=(), |
| validation={"min_length_ratio": 0.1, "max_length_ratio": 4.0}, |
| continuous_batching={"max_requests_per_batch": 2}, |
| ) |
| page = parse_markdown(Path("page.md"), "Alpha 1 beta 2 gamma 3.\n") |
| segment = page.segments[0] |
|
|
| class Translator: |
| def __init__(self): |
| self.calls = [] |
|
|
| def translate_many(self, texts): |
| self.calls.append(list(texts)) |
| return ["訳" * max(1, len(text) // 2) for text in texts] |
|
|
| translator = Translator() |
| response = _translate_segment_with_retry( |
| segment, |
| translator, |
| config, |
| {}, |
| initial_error=ValueError("model changed sentinels"), |
| ) |
|
|
| self.assertGreater(len(translator.calls), 1) |
| self.assertTrue(all(len(call) <= 2 for call in translator.calls)) |
| self.assertFalse(any(protected_values(text) for call in translator.calls for text in call)) |
| restored = segment.protected.restore(response) |
| self.assertTrue(all(value in restored for value in segment.protected.values)) |
|
|
| def test_sentinel_free_retry_never_translates_html_code_contents(self): |
| config = SimpleNamespace( |
| glossary=(), |
| validation={ |
| "min_japanese_characters": 1, |
| "max_untranslated_english_ratio": 1.0, |
| "min_length_ratio": 0.1, |
| "max_length_ratio": 4.0, |
| }, |
| continuous_batching={"max_requests_per_batch": 32}, |
| ) |
| page = parse_markdown( |
| Path("attention_interface.md"), |
| ( |
| '<tr><td><code>"flash_attention_3"</code></td>' |
| '<td>Improves FlashAttention-2.</td></tr>\n' |
| ), |
| ) |
| segment = page.segments[0] |
|
|
| class Translator: |
| def __init__(self): |
| self.calls = [] |
|
|
| def translate_many(self, texts): |
| self.calls.append(list(texts)) |
| return ["改善します。" for _ in texts] |
|
|
| translator = Translator() |
| response = _translate_segment_with_retry( |
| segment, |
| translator, |
| config, |
| {}, |
| initial_error=ValueError("model changed literal tokens"), |
| ) |
|
|
| requests = [text for call in translator.calls for text in call] |
| self.assertFalse(any("flash_attention_3" in text for text in requests)) |
| self.assertIn( |
| '<code>"flash_attention_3"</code>', |
| segment.protected.restore(response), |
| ) |
|
|
| def test_cache_hit_must_match_current_protection_scheme(self): |
| config = SimpleNamespace( |
| validation={ |
| "min_japanese_characters": 1, |
| "max_untranslated_english_ratio": 1.0, |
| "min_length_ratio": 0.1, |
| "max_length_ratio": 4.0, |
| }, |
| ) |
| segment = parse_markdown( |
| Path("page.md"), |
| '<code>"flash_attention_3"</code> backend.\n', |
| ).segments[0] |
| valid = segment.protected.text.replace(" backend", " バックエンド") |
| stale = valid.replace(segment.protected.sentinels[0], "", 1) |
|
|
| self.assertEqual( |
| _validated_cached_translation({"translated": valid}, segment, config), |
| valid, |
| ) |
| self.assertIsNone( |
| _validated_cached_translation({"translated": stale}, segment, config) |
| ) |
|
|
| def test_initial_rollout_disables_graph_and_async_warmup(self): |
| root = Path(__file__).parents[1] |
| for config_name in ("transformers-ja.yml", "transformers-ja-job.yml"): |
| config = load_config(root / "configs" / config_name) |
| self.assertFalse(config.continuous_batching["use_cuda_graph"]) |
| self.assertFalse(config.continuous_batching["use_async_batching"]) |
|
|
| def test_generation_config_preserves_model_eos_and_caps_smoke_output(self): |
| original = SimpleNamespace(eos_token_id=[1, 106], do_sample=True, max_new_tokens=None) |
| translator = ContinuousBatchTranslator(config=SimpleNamespace()) |
| translator.model = SimpleNamespace(generation_config=original) |
|
|
| generation_config = translator._generation_config(32) |
|
|
| self.assertEqual(generation_config.eos_token_id, [1, 106]) |
| self.assertFalse(generation_config.do_sample) |
| self.assertEqual(generation_config.max_new_tokens, 32) |
| self.assertIsNone(original.max_new_tokens) |
|
|
| def test_stop_manager_restores_model_state_before_ordinary_generation(self): |
| manager = SimpleNamespace() |
| manager.stop = Mock() |
| manager.destroy = Mock() |
| translator = ContinuousBatchTranslator(config=SimpleNamespace()) |
| translator.manager = manager |
|
|
| translator._stop_manager() |
|
|
| manager.stop.assert_called_once_with(block=True) |
| manager.destroy.assert_called_once_with() |
| self.assertIsNone(translator.manager) |
|
|
| def test_translate_gemma_uses_text_only_causal_lm_weights(self): |
| text_config = SimpleNamespace(model_type="gemma3_text") |
| parent_config = SimpleNamespace(model_type="gemma3", get_text_config=lambda: text_config) |
|
|
| selected_config, key_mapping = _causal_lm_load_spec(parent_config) |
|
|
| self.assertIs(selected_config, text_config) |
| self.assertEqual(key_mapping, {r"^language_model\.model\.": "model."}) |
|
|
| def test_clone_source_normalizes_github_slug_only(self): |
| self.assertEqual( |
| _clone_source("stevhliu/transformers"), |
| "https://github.com/stevhliu/transformers.git", |
| ) |
| self.assertEqual( |
| _clone_source("https://github.com/stevhliu/transformers.git"), |
| "https://github.com/stevhliu/transformers.git", |
| ) |
| self.assertEqual( |
| _clone_source("git@github.com:stevhliu/transformers.git"), |
| "git@github.com:stevhliu/transformers.git", |
| ) |
| self.assertEqual(_clone_source("../transformers"), "../transformers") |
|
|
| def test_checkout_clones_github_slug_as_url(self): |
| args = SimpleNamespace(checkout=None, base_ref="ja-translation", repository="stevhliu/transformers") |
| with patch("hf_doc_translation.sync.subprocess.run") as run: |
| checkout, temporary = _resolve_checkout(args) |
| try: |
| self.assertEqual( |
| run.call_args.args[0][6], |
| "https://github.com/stevhliu/transformers.git", |
| ) |
| self.assertEqual(checkout.name, "transformers") |
| finally: |
| self.assertIsNotNone(temporary) |
| temporary.cleanup() |
|
|
| def test_runtime_install_uses_exact_transformers_checkout(self): |
| checkout = Path("/tmp/transformers") |
| with patch("hf_doc_translation.sync.subprocess.run") as run: |
| _install_transformers_dependencies(checkout) |
| command = run.call_args.args[0] |
| self.assertEqual(command[-2:], ["--editable", str(checkout)]) |
| self.assertIn("--no-build-isolation", command) |
| self.assertIn("pip", command) |
|
|
| def test_check_only_does_not_mutate_checkout(self): |
| with tempfile.TemporaryDirectory() as directory: |
| root = Path(directory) |
| (root / "docs/source/en").mkdir(parents=True) |
| (root / "docs/source/ja").mkdir(parents=True) |
| (root / "docs/source/en/page.md").write_text("# Page\n\nEnglish prose.\n", encoding="utf-8") |
| (root / "docs/source/en/_toctree.yml").write_text("- local: page\n title: Page\n", encoding="utf-8") |
| (root / "docs/source/ja/legacy.md").write_text("legacy\n", encoding="utf-8") |
| subprocess.run(["git", "init", "-b", "main"], cwd=root, check=True, capture_output=True) |
| subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=root, check=True) |
| subprocess.run(["git", "config", "user.name", "Test"], cwd=root, check=True) |
| subprocess.run(["git", "add", "."], cwd=root, check=True) |
| subprocess.run(["git", "commit", "-m", "fixture"], cwd=root, check=True, capture_output=True) |
| before = subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True) |
| args = SimpleNamespace( |
| config=str(Path(__file__).parents[1] / "configs/transformers-ja.yml"), |
| repository=None, |
| base_ref="main", |
| environment="staging", |
| source="docs/source/en", |
| target="docs/source/ja", |
| checkout=str(root), |
| cache_dir=str(root / "cache"), |
| model_path="/model", |
| runner_revision=None, |
| job_id="fixture", |
| force_backfill=True, |
| check_only=True, |
| no_publish=True, |
| skip_doc_build=True, |
| ) |
| result = run_sync(args) |
| self.assertEqual(result["checks"]["publication"], "not run") |
| self.assertEqual(result["inventory"]["missing_count"], 1) |
| self.assertEqual(result["inventory"]["target_only_count"], 1) |
| self.assertEqual(subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True), before) |
| self.assertEqual((root / "docs/source/ja/legacy.md").read_text(encoding="utf-8"), "legacy\n") |
|
|
|
|
| if __name__ == "__main__": |
| unittest.main() |
|
|