test_bge_model_loader.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from pathlib import Path
  2. from types import SimpleNamespace
  3. from zbt.infrastructure.embedding.bge_model import (
  4. clear_bge_m3_model_cache,
  5. load_bge_m3_model,
  6. resolve_local_huggingface_snapshot,
  7. )
  8. def _create_complete_snapshot(cache_root: Path, revision: str = "revision-01") -> Path:
  9. repository = cache_root / "models--BAAI--bge-m3"
  10. snapshot = repository / "snapshots" / revision
  11. snapshot.mkdir(parents=True)
  12. (repository / "refs").mkdir()
  13. (repository / "refs" / "main").write_text(revision, encoding="utf-8")
  14. for filename in (
  15. "config.json",
  16. "tokenizer_config.json",
  17. "tokenizer.json",
  18. "model.safetensors",
  19. ):
  20. (snapshot / filename).write_text("fixture", encoding="utf-8")
  21. return snapshot
  22. def test_resolve_local_huggingface_snapshot_uses_complete_cached_model(
  23. tmp_path: Path,
  24. ) -> None:
  25. snapshot = _create_complete_snapshot(tmp_path)
  26. result = resolve_local_huggingface_snapshot("BAAI/bge-m3", cache_dir=tmp_path)
  27. assert result == str(snapshot.resolve())
  28. def test_resolve_local_huggingface_snapshot_keeps_remote_id_when_cache_incomplete(
  29. tmp_path: Path,
  30. ) -> None:
  31. repository = tmp_path / "models--BAAI--bge-m3" / "snapshots" / "incomplete"
  32. repository.mkdir(parents=True)
  33. (repository / "config.json").write_text("fixture", encoding="utf-8")
  34. result = resolve_local_huggingface_snapshot("BAAI/bge-m3", cache_dir=tmp_path)
  35. assert result == "BAAI/bge-m3"
  36. def test_load_bge_m3_model_reuses_one_process_instance(
  37. monkeypatch,
  38. tmp_path: Path,
  39. ) -> None:
  40. snapshot = _create_complete_snapshot(tmp_path)
  41. created_with: list[tuple[str, str]] = []
  42. class FakeBgeM3FlagModel:
  43. def __init__(self, model_path: str, **options: object) -> None:
  44. created_with.append((model_path, str(options["devices"])))
  45. monkeypatch.setitem(
  46. __import__("sys").modules,
  47. "FlagEmbedding",
  48. SimpleNamespace(BGEM3FlagModel=FakeBgeM3FlagModel),
  49. )
  50. clear_bge_m3_model_cache()
  51. first = load_bge_m3_model(
  52. "BAAI/bge-m3",
  53. "cpu",
  54. cache_dir=tmp_path,
  55. )
  56. second = load_bge_m3_model(
  57. "BAAI/bge-m3",
  58. "cpu",
  59. cache_dir=tmp_path,
  60. )
  61. assert first is second
  62. assert created_with == [(str(snapshot.resolve()), "cpu")]
  63. clear_bge_m3_model_cache()