File size: 12,922 Bytes
1864088 655ec26 1864088 4742cb1 f0c2f84 51e68cc f0c2f84 7c939e1 f0c2f84 470d44a f0c2f84 4742cb1 1864088 f0c2f84 7c939e1 f0c2f84 7c939e1 f0c2f84 7c939e1 f0c2f84 7c939e1 51e68cc f0c2f84 7c939e1 f0c2f84 7c939e1 470d44a 4742cb1 655ec26 dc53713 7c61acd 7105268 1864088 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | 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()
|