Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Make transformers package optional for minimal install, closes #1091

davidmezzettib14229c1dae9
diff --git a/Makefile b/Makefile
index 471a788c..1a754b7b 100644
--- a/Makefile
+++ b/Makefile
@@ -52,7 +52,7 @@ coverage:
coverage run -m unittest discover -v -k testpipeline.testtrain -s ${TEST_DIR}
coverage run -m unittest discover -v -k testscoring -s ${TEST_DIR}
coverage run -m unittest discover -v -k testserialize -s ${TEST_DIR}
- coverage run -m unittest discover -v -k testtorch -s ${TEST_DIR}
+ coverage run -m unittest discover -v -k testtransformers -s ${TEST_DIR}
coverage run -m unittest discover -v -k testvectors -s ${TEST_DIR}
coverage run -m unittest discover -v -k testworkflow -s ${TEST_DIR}
coverage combine
diff --git a/setup.py b/setup.py
index 440db395..a2249fdd 100644
--- a/setup.py
+++ b/setup.py
@@ -8,13 +8,10 @@ with open("README.md", "r", encoding="utf-8") as f:
DESCRIPTION = "".join([line for line in f if "gh-dark-mode-only" not in line])
# Required dependencies
-install = ["transformers>=4.56.2"]
-
-# Required dependencies that are also base transformers dependencies
-install += ["huggingface-hub>=0.34.0", "numpy>=1.18.4", "pyyaml>=5.3", "regex>=2022.8.17", "safetensors>=0.4.5"]
+install = ["huggingface-hub>=0.34.0", "numpy>=1.18.4", "pyyaml>=5.3", "regex>=2022.8.17", "safetensors>=0.4.5"]
# Default dependencies
-default = ["faiss-cpu>=1.7.1.post2", "msgpack>=1.0.7", "torch>=2.4"]
+default = ["faiss-cpu>=1.7.1.post2", "msgpack>=1.0.7", "torch>=2.4", "transformers>=4.56.2"]
# Optional dependencies
extras = {}
diff --git a/src/python/txtai/ann/dense/torch.py b/src/python/txtai/ann/dense/torch.py
index be736088..c46ec8ff 100644
--- a/src/python/txtai/ann/dense/torch.py
+++ b/src/python/txtai/ann/dense/torch.py
@@ -22,10 +22,10 @@ except ImportError:
from .numpy import NumPy
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import TransformersLib
-torch = TorchLib().torch()
+torch = TransformersLib().torch()
class Torch(NumPy):
diff --git a/src/python/txtai/data/tokens.py b/src/python/txtai/data/tokens.py
index 67b9af96..671bb648 100644
--- a/src/python/txtai/data/tokens.py
+++ b/src/python/txtai/data/tokens.py
@@ -2,9 +2,10 @@
Tokens module
"""
-from ..util import TorchLib
+# Conditional imports
+from ..util import TransformersLib
-Dataset = TorchLib().dataset()
+Dataset = TransformersLib().dataset()
class Tokens(Dataset):
diff --git a/src/python/txtai/embeddings/search/query.py b/src/python/txtai/embeddings/search/query.py
index 13748379..29872acf 100644
--- a/src/python/txtai/embeddings/search/query.py
+++ b/src/python/txtai/embeddings/search/query.py
@@ -2,7 +2,10 @@
Query module
"""
-from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, T5ForConditionalGeneration
+# Conditional imports
+from ...util import TransformersLib
+
+transformers = TransformersLib().transformers()
class Query:
@@ -20,11 +23,11 @@ class Query:
maxlength: max sequence length to generate
"""
- self.tokenizer = AutoTokenizer.from_pretrained(path)
- self.model = AutoModelForSeq2SeqLM.from_pretrained(path)
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(path)
+ self.model = transformers.AutoModelForSeq2SeqLM.from_pretrained(path)
# Default prefix if not provided for T5 models
- if not prefix and isinstance(self.model, T5ForConditionalGeneration):
+ if not prefix and isinstance(self.model, transformers.T5ForConditionalGeneration):
prefix = "translate English to SQL: "
self.prefix = prefix
diff --git a/src/python/txtai/models/models.py b/src/python/txtai/models/models.py
index d2e532de..5d43e6b9 100644
--- a/src/python/txtai/models/models.py
+++ b/src/python/txtai/models/models.py
@@ -4,22 +4,14 @@ Models module
import os
-from transformers import (
- AutoConfig,
- AutoModel,
- AutoModelForQuestionAnswering,
- AutoModelForSeq2SeqLM,
- AutoModelForSequenceClassification,
- AutoTokenizer,
-)
-from transformers.models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
-
from .onnx import OnnxModel
-# Conditional torch imports
-from ..util import TorchLib
+# Conditional imports
+from ..util import TransformersLib
-torch = TorchLib().torch()
+transformerslib = TransformersLib()
+torch = transformerslib.torch()
+transformers = transformerslib.transformers()
class Models:
@@ -206,12 +198,12 @@ class Models:
# Transformer models
models = {
- "default": AutoModel.from_pretrained,
- "question-answering": AutoModelForQuestionAnswering.from_pretrained,
- "summarization": AutoModelForSeq2SeqLM.from_pretrained,
- "text2text-generation": AutoModelForSeq2SeqLM.from_pretrained,
- "text-classification": AutoModelForSequenceClassification.from_pretrained,
- "zero-shot-classification": AutoModelForSequenceClassification.from_pretrained,
+ "default": transformers.AutoModel.from_pretrained,
+ "question-answering": transformers.AutoModelForQuestionAnswering.from_pretrained,
+ "summarization": transformers.AutoModelForSeq2SeqLM.from_pretrained,
+ "text2text-generation": transformers.AutoModelForSeq2SeqLM.from_pretrained,
+ "text-classification": transformers.AutoModelForSequenceClassification.from_pretrained,
+ "zero-shot-classification": transformers.AutoModelForSequenceClassification.from_pretrained,
}
# Pass modelargs as keyword arguments
@@ -233,7 +225,7 @@ class Models:
tokenizer
"""
- return AutoTokenizer.from_pretrained(path, **kwargs) if isinstance(path, str) else path
+ return transformers.AutoTokenizer.from_pretrained(path, **kwargs) if isinstance(path, str) else path
@staticmethod
def task(path, **kwargs):
@@ -253,14 +245,17 @@ class Models:
if isinstance(path, (list, tuple)) and hasattr(path[0], "config"):
config = path[0].config
elif isinstance(path, str):
- config = AutoConfig.from_pretrained(path, **kwargs)
+ config = transformers.AutoConfig.from_pretrained(path, **kwargs)
+
+ # Image models
+ imagemodels = transformers.models.auto.modeling_auto.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
# Attempt to resolve task using configuration
task = None
if config:
architecture = config.architectures[0] if config.architectures else None
if architecture:
- if architecture in MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.values():
+ if architecture in imagemodels.values():
task = "vision"
elif any(x for x in ["LMHead", "CausalLM"] if x in architecture):
task = "language-generation"
diff --git a/src/python/txtai/models/onnx.py b/src/python/txtai/models/onnx.py
index 728ff4b1..e17e9327 100644
--- a/src/python/txtai/models/onnx.py
+++ b/src/python/txtai/models/onnx.py
@@ -12,19 +12,16 @@ except ImportError:
import numpy as np
-import transformers
-
-from transformers import AutoConfig
-from transformers.configuration_utils import PretrainedConfig
-
from .registry import Registry
-# Conditional torch imports
-from ..util import TorchLib
+# Conditional imports
+from ..util import TransformersLib
-torchlib = TorchLib()
-torch = torchlib.torch()
-PreTrainedModel = torchlib.pretrained()
+transformerslib = TransformersLib()
+torch = transformerslib.torch()
+transformers = transformerslib.transformers()
+PretrainedConfig = transformerslib.config()
+PreTrainedModel = transformerslib.model()
# pylint: disable=W0223
@@ -46,7 +43,7 @@ class OnnxModel(PreTrainedModel):
if not ONNX_RUNTIME:
raise ImportError('onnxruntime is not available - install "model" extra to enable')
- super().__init__(AutoConfig.from_pretrained(config) if config else OnnxConfig())
+ super().__init__(transformers.AutoConfig.from_pretrained(config) if config else OnnxConfig())
# Create ONNX session
self.model = ort.InferenceSession(model, ort.SessionOptions(), self.providers())
diff --git a/src/python/txtai/models/pooling/base.py b/src/python/txtai/models/pooling/base.py
index ee0c4794..ed39c612 100644
--- a/src/python/txtai/models/pooling/base.py
+++ b/src/python/txtai/models/pooling/base.py
@@ -7,16 +7,15 @@ import json
import numpy as np
from huggingface_hub.errors import HFValidationError
-from transformers.utils import cached_file
from ..models import Models
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import Download, TransformersLib
-torchlib = TorchLib()
-torch = torchlib.torch()
-Module = torchlib.module()
+transformerslib = TransformersLib()
+torch = transformerslib.torch()
+Module = transformerslib.module()
class Pooling(Module):
@@ -173,7 +172,7 @@ class Pooling(Module):
# Download file and parse JSON
config = None
try:
- path = cached_file(path_or_repo_id=path, filename=name)
+ path = Download()(path, name)
if path:
with open(path, encoding="utf-8") as f:
config = json.load(f)
diff --git a/src/python/txtai/models/pooling/factory.py b/src/python/txtai/models/pooling/factory.py
index 15509908..92fcde8c 100644
--- a/src/python/txtai/models/pooling/factory.py
+++ b/src/python/txtai/models/pooling/factory.py
@@ -6,7 +6,6 @@ import json
import os
from huggingface_hub.errors import HFValidationError
-from transformers.utils import cached_file
from .base import Pooling
from .cls import ClsPooling
@@ -14,6 +13,8 @@ from .last import LastPooling
from .late import LatePooling
from .mean import MeanPooling
+from ...util import Download
+
class PoolingFactory:
"""
@@ -141,7 +142,7 @@ class PoolingFactory:
# Download file and parse JSON
config = None
try:
- path = cached_file(path_or_repo_id=path, filename=name)
+ path = Download()(path, name)
if path:
with open(path, encoding="utf-8") as f:
config = json.load(f)
diff --git a/src/python/txtai/models/pooling/last.py b/src/python/txtai/models/pooling/last.py
index b203b610..81aed4ca 100644
--- a/src/python/txtai/models/pooling/last.py
+++ b/src/python/txtai/models/pooling/last.py
@@ -4,10 +4,10 @@ Last module
from .base import Pooling
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import TransformersLib
-torch = TorchLib().torch()
+torch = TransformersLib().torch()
class LastPooling(Pooling):
diff --git a/src/python/txtai/models/pooling/late.py b/src/python/txtai/models/pooling/late.py
index f325e52f..fccae3d0 100644
--- a/src/python/txtai/models/pooling/late.py
+++ b/src/python/txtai/models/pooling/late.py
@@ -5,16 +5,15 @@ Late module
import numpy as np
from safetensors import safe_open
-from transformers.utils import cached_file
from .base import Pooling
from .muvera import Muvera
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import Download, TransformersLib
-torchlib = TorchLib()
-torch = torchlib.torch()
+transformerslib = TransformersLib()
+torch = transformerslib.torch()
class LatePooling(Pooling):
@@ -44,7 +43,7 @@ class LatePooling(Pooling):
self.qprefix, self.qlength, self.dprefix, self.dlength = self.settings(path, config)
# Load linear layer
- path = cached_file(path_or_repo_id=path, filename=name)
+ path = Download()(path, name)
with safe_open(filename=path, framework="pt") as f:
weights = f.get_tensor("linear.weight")
diff --git a/src/python/txtai/models/pooling/mean.py b/src/python/txtai/models/pooling/mean.py
index b6011168..bf83a367 100644
--- a/src/python/txtai/models/pooling/mean.py
+++ b/src/python/txtai/models/pooling/mean.py
@@ -4,10 +4,10 @@ Mean module
from .base import Pooling
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import TransformersLib
-torch = TorchLib().torch()
+torch = TransformersLib().torch()
class MeanPooling(Pooling):
diff --git a/src/python/txtai/models/registry.py b/src/python/txtai/models/registry.py
index 24d64f4d..1e3f3e03 100644
--- a/src/python/txtai/models/registry.py
+++ b/src/python/txtai/models/registry.py
@@ -2,8 +2,10 @@
Registry module
"""
-from transformers import AutoModel, AutoModelForQuestionAnswering, AutoModelForSequenceClassification
-from transformers.models.auto.tokenization_auto import TOKENIZER_MAPPING
+# Conditional imports
+from ..util import TransformersLib
+
+transformers = TransformersLib().transformers()
class Registry:
@@ -29,9 +31,10 @@ class Registry:
model.__class__.config_class = config
# Add references for this class to supported AutoModel classes
- for mapping in [AutoModel, AutoModelForQuestionAnswering, AutoModelForSequenceClassification]:
+ for mapping in [transformers.AutoModel, transformers.AutoModelForQuestionAnswering, transformers.AutoModelForSequenceClassification]:
mapping.register(config, model.__class__)
# Add references for this class to support pipeline AutoTokenizers
- if hasattr(model, "config") and type(model.config) not in TOKENIZER_MAPPING:
- TOKENIZER_MAPPING.register(type(model.config), type(model.config).__name__)
+ mappings = transformers.models.auto.tokenization_auto.TOKENIZER_MAPPING
+ if hasattr(model, "config") and type(model.config) not in mappings:
+ mappings.register(type(model.config), type(model.config).__name__)
diff --git a/src/python/txtai/models/tokendetection.py b/src/python/txtai/models/tokendetection.py
index 6283d710..a98f9acc 100644
--- a/src/python/txtai/models/tokendetection.py
+++ b/src/python/txtai/models/tokendetection.py
@@ -5,12 +5,12 @@ Token Detection module
import inspect
import os
-# Conditional torch imports
-from ..util import TorchLib
+# Conditional imports
+from ..util import TransformersLib
-torchlib = TorchLib()
-torch = torchlib.torch()
-PreTrainedModel = torchlib.pretrained()
+transformerslib = TransformersLib()
+torch = transformerslib.torch()
+PreTrainedModel = transformerslib.model()
class TokenDetection(PreTrainedModel):
diff --git a/src/python/txtai/pipeline/audio/texttospeech.py b/src/python/txtai/pipeline/audio/texttospeech.py
index 5eb8cc51..1a1cb936 100644
--- a/src/python/txtai/pipeline/audio/texttospeech.py
+++ b/src/python/txtai/pipeline/audio/texttospeech.py
@@ -25,15 +25,15 @@ import yaml
import numpy as np
from huggingface_hub.errors import HFValidationError
-from transformers import SpeechT5Processor
-from transformers.utils import cached_file
from ..base import Pipeline
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import Download, TransformersLib
-torch = TorchLib().torch()
+transformerslib = TransformersLib()
+torch = transformerslib.torch()
+transformers = transformerslib.transformers()
# Logging configuration
logger = logging.getLogger(__name__)
@@ -135,7 +135,7 @@ class TextToSpeech(Pipeline):
exists = False
try:
# Check if file exists
- exists = cached_file(path_or_repo_id=path, filename=name) is not None
+ exists = Download()(path, name) is not None
except (HFValidationError, OSError):
return False
@@ -252,8 +252,9 @@ class ESPnet(SpeechPipeline):
"""
# Get path to model and config
- config = cached_file(path_or_repo_id=path, filename="config.yaml")
- model = cached_file(path_or_repo_id=path, filename="model.onnx")
+ download = Download()
+ config = download(path, "config.yaml")
+ model = download(path, "model.onnx")
# Read yaml config
with open(config, "r", encoding="utf-8") as f:
@@ -327,8 +328,9 @@ class Kokoro(SpeechPipeline):
"""
# Get path to model and config
- voices = cached_file(path_or_repo_id=path, filename="voices.json")
- model = cached_file(path_or_repo_id=path, filename="model.onnx")
+ download = Download()
+ voices = download(path, "voices.json")
+ model = download(path, "model.onnx")
# Read voices config
with open(voices, "r", encoding="utf-8") as f:
@@ -406,12 +408,13 @@ class SpeechT5(SpeechPipeline):
providers: list of supported ONNX providers
"""
- self.encoder = ort.InferenceSession(cached_file(path_or_repo_id=path, filename="encoder_model.onnx"), providers=providers)
- self.decoder = ort.InferenceSession(cached_file(path_or_repo_id=path, filename="decoder_model_merged.onnx"), providers=providers)
- self.vocoder = ort.InferenceSession(cached_file(path_or_repo_id=path, filename="decoder_postnet_and_vocoder.onnx"), providers=providers)
+ download = Download()
+ self.encoder = ort.InferenceSession(download(path, "encoder_model.onnx"), providers=providers)
+ self.decoder = ort.InferenceSession(download(path, "decoder_model_merged.onnx"), providers=providers)
+ self.vocoder = ort.InferenceSession(download(path, "decoder_postnet_and_vocoder.onnx"), providers=providers)
- self.processor = SpeechT5Processor.from_pretrained(path)
- self.defaultspeaker = np.load(cached_file(path_or_repo_id=path, filename="speaker.npy"), allow_pickle=False)
+ self.processor = transformers.SpeechT5Processor.from_pretrained(path)
+ self.defaultspeaker = np.load(download(path, "speaker.npy"), allow_pickle=False)
# Max number of input tokens model can handle
self.maxtokens = maxtokens
diff --git a/src/python/txtai/pipeline/hfmodel.py b/src/python/txtai/pipeline/hfmodel.py
index a7aafc48..152f8b17 100644
--- a/src/python/txtai/pipeline/hfmodel.py
+++ b/src/python/txtai/pipeline/hfmodel.py
@@ -2,11 +2,14 @@
Hugging Face Transformers model wrapper module
"""
-from transformers import AutoTokenizer
-
from ..models import Models
+from ..util import TransformersLib
+
from .tensors import Tensors
+# Conditional transformers import
+transformers = TransformersLib().transformers()
+
class HFModel(Tensors):
"""
@@ -61,7 +64,7 @@ class HFModel(Tensors):
model = self.prepare(model)
# Load tokenizer
- tokenizer = AutoTokenizer.from_pretrained(tokenizer) if isinstance(tokenizer, str) else tokenizer
+ tokenizer = transformers.AutoTokenizer.from_pretrained(tokenizer) if isinstance(tokenizer, str) else tokenizer
return model, tokenizer
diff --git a/src/python/txtai/pipeline/hfpipeline.py b/src/python/txtai/pipeline/hfpipeline.py
index 64d2b461..8a4c7ee9 100644
--- a/src/python/txtai/pipeline/hfpipeline.py
+++ b/src/python/txtai/pipeline/hfpipeline.py
@@ -4,13 +4,15 @@ Hugging Face Transformers pipeline wrapper module
import inspect
-from transformers import pipeline
from ..models import Models
-from ..util import Resolver
+from ..util import Resolver, TransformersLib
from .tensors import Tensors
+# Conditional imports
+transformers = TransformersLib().transformers()
+
class HFPipeline(Tensors):
"""
@@ -51,9 +53,9 @@ class HFPipeline(Tensors):
# Load model
model = Models.load(path[0], config, task)
- self.pipeline = pipeline(task, model=model, tokenizer=path[1], device=device, model_kwargs=modelargs, **kwargs)
+ self.pipeline = transformers.pipeline(task, model=model, tokenizer=path[1], device=device, model_kwargs=modelargs, **kwargs)
else:
- self.pipeline = pipeline(task, model=path, device=device, model_kwargs=modelargs, **kwargs)
+ self.pipeline = transformers.pipeline(task, model=path, device=device, model_kwargs=modelargs, **kwargs)
# Model quantization. Compresses model to int8 precision, improves runtime performance. Only supported on CPU.
if deviceid == -1 and quantize:
@@ -75,7 +77,7 @@ class HFPipeline(Tensors):
"""
# Get pipeline method arguments
- args = inspect.getfullargspec(pipeline).args
+ args = inspect.getfullargspec(transformers.pipeline).args
# Resolve torch dtype, if necessary
dtype = kwargs.get("dtype")
diff --git a/src/python/txtai/pipeline/image/caption.py b/src/python/txtai/pipeline/image/caption.py
index 25a87783..6ecf20ee 100644
--- a/src/python/txtai/pipeline/image/caption.py
+++ b/src/python/txtai/pipeline/image/caption.py
@@ -10,10 +10,13 @@ try:
except ImportError:
PIL = False
-from transformers import AutoModelForImageTextToText, AutoImageProcessor, AutoTokenizer
-
from ..hfmodel import HFModel
+from ...util import TransformersLib
+
+# Conditional imports
+transformers = TransformersLib().transformers()
+
class Caption(HFModel):
"""
@@ -34,9 +37,9 @@ class Caption(HFModel):
if isinstance(path, tuple):
self.model, self.tokenizer, self.processor = path
else:
- self.model = AutoModelForImageTextToText.from_pretrained(path, **kwargs)
- self.tokenizer = AutoTokenizer.from_pretrained(path)
- self.processor = AutoImageProcessor.from_pretrained(path)
+ self.model = transformers.AutoModelForImageTextToText.from_pretrained(path, **kwargs)
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(path)
+ self.processor = transformers.AutoImageProcessor.from_pretrained(path)
# Move model to device
self.model = self.model.to(self.device)
diff --git a/src/python/txtai/pipeline/llm/huggingface.py b/src/python/txtai/pipeline/llm/huggingface.py
index dad5a21c..d22db150 100644
--- a/src/python/txtai/pipeline/llm/huggingface.py
+++ b/src/python/txtai/pipeline/llm/huggingface.py
@@ -4,8 +4,6 @@ Hugging Face module
from threading import Thread
-from transformers import AutoModelForImageTextToText, TextIteratorStreamer
-
from ...models import Models
from ..hfmodel import HFModel
@@ -13,6 +11,11 @@ from ..hfpipeline import HFPipeline
from .generation import Generation
+from ...util import TransformersLib
+
+# Conditional import
+transformers = TransformersLib().transformers()
+
class HFGeneration(Generation):
"""
@@ -112,7 +115,7 @@ class HFLLM(HFPipeline):
True if this is a vision model
"""
- return isinstance(self.pipeline.model, AutoModelForImageTextToText)
+ return isinstance(self.pipeline.model, transformers.AutoModelForImageTextToText)
def parameters(self, texts, maxlength, workers, stop, **kwargs):
"""
@@ -228,7 +231,7 @@ class StreamingResponse:
def __init__(self, pipeline, texts, stop, **kwargs):
# Create streamer
- self.stream = TextIteratorStreamer(pipeline.tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=5)
+ self.stream = transformers.TextIteratorStreamer(pipeline.tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=5)
kwargs["streamer"] = self.stream
kwargs["stop_strings"] = stop
diff --git a/src/python/txtai/pipeline/llm/litellm.py b/src/python/txtai/pipeline/llm/litellm.py
index ee7faa8d..03098c26 100644
--- a/src/python/txtai/pipeline/llm/litellm.py
+++ b/src/python/txtai/pipeline/llm/litellm.py
@@ -2,8 +2,6 @@
LiteLLM module
"""
-from transformers.utils import cached_file
-
# Conditional import
try:
import litellm as api
@@ -14,6 +12,8 @@ except ImportError:
from .generation import Generation
+from ...util import Download
+
class LiteLLM(Generation):
"""
@@ -61,7 +61,7 @@ class LiteLLM(Generation):
# pylint: disable=W0702
try:
- return cached_file(path_or_repo_id=path, filename="config.json") is not None if "/" in path else False
+ return Download()(path, "config.json") is not None if "/" in path else False
except:
return False
diff --git a/src/python/txtai/pipeline/llm/llama.py b/src/python/txtai/pipeline/llm/llama.py
index 7e20cfaa..572cffdf 100644
--- a/src/python/txtai/pipeline/llm/llama.py
+++ b/src/python/txtai/pipeline/llm/llama.py
@@ -4,8 +4,6 @@ Llama module
import os
-from huggingface_hub import hf_hub_download
-
# Conditional import
try:
import llama_cpp as llama
@@ -14,6 +12,8 @@ try:
except ImportError:
LLAMA_CPP = False
+from ...util import Download
+
from .generation import Generation
@@ -43,7 +43,7 @@ class LlamaCpp(Generation):
raise ImportError('llama.cpp is not available - install "pipeline" extra to enable')
# Check if this is a local path, otherwise download from the HF Hub
- path = path if os.path.exists(path) else self.download(path)
+ path = path if os.path.exists(path) else Download()(path)
# Create llama.cpp instance
self.llm = self.create(path, **kwargs)
@@ -56,26 +56,6 @@ class LlamaCpp(Generation):
else self.prompt(text, maxlength, stream, stop, **kwargs)
)
- def download(self, path):
- """
- Downloads path from the Hugging Face Hub.
-
- Args:
- path: full model path
-
- Returns:
- local cached model path
- """
-
- # Split into parts
- parts = path.split("/")
-
- # Calculate repo id split
- repo = 2 if len(parts) > 2 else 1
-
- # Download and cache file
- return hf_hub_download(repo_id="/".join(parts[:repo]), filename="/".join(parts[repo:]))
-
def create(self, path, **kwargs):
"""
Creates a new llama.cpp model instance.
diff --git a/src/python/txtai/pipeline/llm/opencode.py b/src/python/txtai/pipeline/llm/opencode.py
index eef30d26..037b31fb 100644
--- a/src/python/txtai/pipeline/llm/opencode.py
+++ b/src/python/txtai/pipeline/llm/opencode.py
@@ -2,8 +2,6 @@
OpenCode module
"""
-from transformers.utils import cached_file
-
# Conditional import
try:
import httpx
@@ -15,6 +13,8 @@ except ImportError:
from .generation import Generation
+from ...util import Download
+
class OpenCode(Generation):
"""
@@ -49,7 +49,7 @@ class OpenCode(Generation):
# pylint: disable=W0702
try:
- return cached_file(path_or_repo_id=path, filename="config.json") is not None if "/" in path else False
+ return Download()(path, "config.json") is not None if "/" in path else False
except:
return False
diff --git a/src/python/txtai/pipeline/tensors.py b/src/python/txtai/pipeline/tensors.py
index 43a7f1c4..aff532cd 100644
--- a/src/python/txtai/pipeline/tensors.py
+++ b/src/python/txtai/pipeline/tensors.py
@@ -4,10 +4,10 @@ Tensor processing framework module
from .base import Pipeline
-# Conditional torch imports
-from ..util import TorchLib
+# Conditional imports
+from ..util import TransformersLib
-torch = TorchLib().torch()
+torch = TransformersLib().torch()
class Tensors(Pipeline):
diff --git a/src/python/txtai/pipeline/text/entity.py b/src/python/txtai/pipeline/text/entity.py
index 12ec712e..b52dd70e 100644
--- a/src/python/txtai/pipeline/text/entity.py
+++ b/src/python/txtai/pipeline/text/entity.py
@@ -11,9 +11,10 @@ except ImportError:
GLINER = False
from huggingface_hub.errors import HFValidationError
-from transformers.utils import cached_file
from ...models import Models
+from ...util import Download
+
from ..hfpipeline import HFPipeline
@@ -86,7 +87,7 @@ class Entity(HFPipeline):
try:
# Test if this model has a gliner_config.json file
- return cached_file(path_or_repo_id=path, filename="gliner_config.json") is not None
+ return Download()(path, "gliner_config.json") is not None
# Ignore this error - invalid repo or directory
except (HFValidationError, OSError):
diff --git a/src/python/txtai/pipeline/text/lateencoder.py b/src/python/txtai/pipeline/text/lateencoder.py
index 118f950c..a0085088 100644
--- a/src/python/txtai/pipeline/text/lateencoder.py
+++ b/src/python/txtai/pipeline/text/lateencoder.py
@@ -7,10 +7,10 @@ import numpy as np
from ...models import Models, PoolingFactory
from ..base import Pipeline
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import TransformersLib
-torch = TorchLib().torch()
+torch = TransformersLib().torch()
class LateEncoder(Pipeline):
diff --git a/src/python/txtai/pipeline/text/questions.py b/src/python/txtai/pipeline/text/questions.py
index d05768f5..cfc221a4 100644
--- a/src/python/txtai/pipeline/text/questions.py
+++ b/src/python/txtai/pipeline/text/questions.py
@@ -5,9 +5,9 @@ Questions module
from ..hfmodel import HFModel
# Conditional torch imports
-from ...util import TorchLib
+from ...util import TransformersLib
-torch = TorchLib().torch()
+torch = TransformersLib().torch()
class Questions(HFModel):
diff --git a/src/python/txtai/pipeline/train/hfonnx.py b/src/python/txtai/pipeline/train/hfonnx.py
index 5ad081ef..633ef44e 100644
--- a/src/python/txtai/pipeline/train/hfonnx.py
+++ b/src/python/txtai/pipeline/train/hfonnx.py
@@ -15,17 +15,16 @@ try:
except ImportError:
ONNX_RUNTIME = False
-from transformers import AutoModel, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer
-
from ...models import PoolingFactory
from ..tensors import Tensors
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import TransformersLib
-torchlib = TorchLib()
-torch = torchlib.torch()
-Module = torchlib.module()
+transformerslib = TransformersLib()
+torch = transformerslib.torch()
+transformers = transformerslib.transformers()
+Module = transformerslib.module()
class HFOnnx(Tensors):
@@ -55,7 +54,7 @@ class HFOnnx(Tensors):
model = model.cpu()
else:
model = model(path)
- tokenizer = AutoTokenizer.from_pretrained(path)
+ tokenizer = transformers.AutoTokenizer.from_pretrained(path)
# Generate dummy inputs
dummy = dict(tokenizer(["test inputs"], return_tensors="pt"))
@@ -141,7 +140,7 @@ class HFOnnx(Tensors):
)
config = {
- "default": (OrderedDict({"last_hidden_state": {0: "batch", 1: "sequence"}}), AutoModel.from_pretrained),
+ "default": (OrderedDict({"last_hidden_state": {0: "batch", 1: "sequence"}}), transformers.AutoModel.from_pretrained),
"pooling": (OrderedDict({"embeddings": {0: "batch", 1: "sequence"}}), lambda x: PoolingFactory.create({"path": x, "device": -1})),
"question-answering": (
OrderedDict(
@@ -150,9 +149,9 @@ class HFOnnx(Tensors):
"end_logits": {0: "batch", 1: "sequence"},
}
),
- AutoModelForQuestionAnswering.from_pretrained,
+ transformers.AutoModelForQuestionAnswering.from_pretrained,
),
- "text-classification": (OrderedDict({"logits": {0: "batch"}}), AutoModelForSequenceClassification.from_pretrained),
+ "text-classification": (OrderedDict({"logits": {0: "batch"}}), transformers.AutoModelForSequenceClassification.from_pretrained),
}
# Aliases
diff --git a/src/python/txtai/pipeline/train/hftrainer.py b/src/python/txtai/pipeline/train/hftrainer.py
index 33870b26..4418699a 100644
--- a/src/python/txtai/pipeline/train/hftrainer.py
+++ b/src/python/txtai/pipeline/train/hftrainer.py
@@ -5,19 +5,6 @@ Hugging Face Transformers trainer wrapper module
import os
import sys
-from transformers import (
- AutoConfig,
- AutoModelForCausalLM,
- AutoModelForMaskedLM,
- AutoModelForQuestionAnswering,
- AutoModelForPreTraining,
- AutoModelForSeq2SeqLM,
- AutoModelForSequenceClassification,
- AutoTokenizer,
-)
-from transformers import DataCollatorForLanguageModeling, DataCollatorForSeq2Seq, Trainer, set_seed
-from transformers import TrainingArguments as HFTrainingArguments
-
# Conditional import
try:
from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training
@@ -33,10 +20,13 @@ from ...data import Labels, Questions, Sequences, Texts
from ...models import Models, TokenDetection
from ..tensors import Tensors
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import TransformersLib
-torch = TorchLib().torch()
+transformerslib = TransformersLib()
+torch = transformerslib.torch()
+transformers = transformerslib.transformers()
+HFTrainingArguments = transformerslib.arguments()
class HFTrainer(Tensors):
@@ -95,7 +85,7 @@ class HFTrainer(Tensors):
args = self.parse(args)
# Set seed for model reproducibility
- set_seed(args.seed)
+ transformers.set_seed(args.seed)
# Load model configuration, tokenizer and max sequence length
config, tokenizer, maxlength = self.load(base, maxlength)
@@ -123,7 +113,7 @@ class HFTrainer(Tensors):
collator.model = model
# Build trainer
- trainer = Trainer(
+ trainer = transformers.Trainer(
model=model,
processing_class=tokenizer,
data_collator=collator,
@@ -185,10 +175,10 @@ class HFTrainer(Tensors):
config = model.config
else:
# Load config
- config = AutoConfig.from_pretrained(base)
+ config = transformers.AutoConfig.from_pretrained(base)
# Load tokenizer
- tokenizer = AutoTokenizer.from_pretrained(base)
+ tokenizer = transformers.AutoTokenizer.from_pretrained(base)
# Detect unbounded tokenizer
Models.checklength(config, tokenizer)
@@ -221,15 +211,15 @@ class HFTrainer(Tensors):
if task == "language-generation":
process = Texts(tokenizer, columns, maxlength, merge)
- collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8 if fp16 else None)
+ collator = transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8 if fp16 else None)
elif task in ("language-modeling", "token-detection"):
process = Texts(tokenizer, columns, maxlength, merge)
- collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8 if fp16 else None)
+ collator = transformers.DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8 if fp16 else None)
elif task == "question-answering":
process = Questions(tokenizer, columns, maxlength, stride)
elif task == "sequence-sequence":
process = Sequences(tokenizer, columns, maxlength, prefix)
- collator = DataCollatorForSeq2Seq(tokenizer, pad_to_multiple_of=8 if fp16 else None)
+ collator = transformers.DataCollatorForSeq2Seq(tokenizer, pad_to_multiple_of=8 if fp16 else None)
else:
process = Labels(tokenizer, columns, maxlength)
labels = process.labels(train)
@@ -267,22 +257,24 @@ class HFTrainer(Tensors):
if isinstance(base, (list, tuple)) and not isinstance(base[0], str):
return base[0]
if task == "language-generation":
- return AutoModelForCausalLM.from_pretrained(base, config=config, quantization_config=quantization)
+ return transformers.AutoModelForCausalLM.from_pretrained(base, config=config, quantization_config=quantization)
if task == "language-modeling":
- return AutoModelForMaskedLM.from_pretrained(base, config=config, quantization_config=quantization)
+ return transformers.AutoModelForMaskedLM.from_pretrained(base, config=config, quantization_config=quantization)
if task == "question-answering":
- return AutoModelForQuestionAnswering.from_pretrained(base, config=config, quantization_config=quantization)
+ return transformers.AutoModelForQuestionAnswering.from_pretrained(base, config=config, quantization_config=quantization)
if task == "sequence-sequence":
- return AutoModelForSeq2SeqLM.from_pretrained(base, config=config, quantization_config=quantization)
+ return transformers.AutoModelForSeq2SeqLM.from_pretrained(base, config=config, quantization_config=quantization)
if task == "token-detection":
return TokenDetection(
- AutoModelForMaskedLM.from_pretrained(base, config=config, quantization_config=quantization, attn_implementation="eager"),
- AutoModelForPreTraining.from_pretrained(base, config=config, quantization_config=quantization, attn_implementation="eager"),
+ transformers.AutoModelForMaskedLM.from_pretrained(base, config=config, quantization_config=quantization, attn_implementation="eager"),
+ transformers.AutoModelForPreTraining.from_pretrained(
+ base, config=config, quantization_config=quantization, attn_implementation="eager"
+ ),
tokenizer,
)
# Default task
- return AutoModelForSequenceClassification.from_pretrained(base, config=config, quantization_config=quantization)
+ return transformers.AutoModelForSequenceClassification.from_pretrained(base, config=config, quantization_config=quantization)
def quantization(self, quantize):
"""
diff --git a/src/python/txtai/util/__init__.py b/src/python/txtai/util/__init__.py
index edccbf30..b6bcbce3 100644
--- a/src/python/txtai/util/__init__.py
+++ b/src/python/txtai/util/__init__.py
@@ -2,7 +2,8 @@
Utility imports
"""
+from .download import Download
from .resolver import Resolver
from .sparsearray import SparseArray
from .template import TemplateFormatter
-from .torchlib import TorchLib
+from .transformerslib import TransformersLib
diff --git a/src/python/txtai/util/download.py b/src/python/txtai/util/download.py
new file mode 100644
index 00000000..01330fd4
--- /dev/null
+++ b/src/python/txtai/util/download.py
@@ -0,0 +1,44 @@
+"""
+Download module
+"""
+
+import os
+
+from huggingface_hub import hf_hub_download
+
+
+class Download:
+ """
+ Downloads files from the Hugging Face Hub. This method also supports local file paths that exist.
+ """
+
+ def __call__(self, path, name=None):
+ """
+ Downloads path from the Hugging Face Hub. Supports local file paths.
+
+ Args:
+ path: model path or repo
+ name: file name to load
+
+ Returns:
+ local cached model path, if available
+ """
+
+ # Reject invalid input
+ if not isinstance(path, str) or (name and not isinstance(name, str)):
+ return None
+
+ # Split into repo and name components
+ if not name:
+ # Split into parts
+ parts = path.split("/")
+
+ # Calculate repo id split
+ repo = 2 if len(parts) > 2 else 1
+
+ # Set path and name components
+ path, name = "/".join(parts[:repo]), "/".join(parts[repo:])
+
+ # Download (if necessary) and return local file path
+ local = os.path.join(path, name)
+ return local if os.path.exists(local) else hf_hub_download(repo_id=path, filename=name)
diff --git a/src/python/txtai/util/torchlib.py b/src/python/txtai/util/transformerslib.py
similarity index 52%
rename from src/python/txtai/util/torchlib.py
rename to src/python/txtai/util/transformerslib.py
index 1135aecd..71418edf 100644
--- a/src/python/txtai/util/torchlib.py
+++ b/src/python/txtai/util/transformerslib.py
@@ -1,14 +1,51 @@
"""
-TorchLib module
+TransformersLib module
"""
# pylint: disable=C0415
-class TorchLib:
+class TransformersLib:
"""
- Imports torch dependencies with fallbacks when the library is not installed.
+ Imports transformers and dependencies with fallbacks when the library is not installed.
"""
+ def arguments(self):
+ """
+ Imports transformers.TrainingArguments
+ """
+
+ try:
+ from transformers import TrainingArguments
+
+ except ImportError:
+
+ class TrainingArguments:
+ """
+ Stub for TrainingArguments
+ """
+
+ return TrainingArguments
+
+ def config(self):
+ """
+ Imports transformers.configuration_utils.PretrainedConfig.
+
+ Returns:
+ PreTrainedConfig
+ """
+
+ try:
+ from transformers.configuration_utils import PretrainedConfig
+
+ except ImportError:
+
+ class PretrainedConfig:
+ """
+ Stub for PretrainedConfig
+ """
+
+ return PretrainedConfig
+
def dataset(self):
"""
Import torch.utils.data.Dataset.
@@ -29,6 +66,26 @@ class TorchLib:
return Dataset
+ def model(self):
+ """
+ Imports transformers.modeling_utils.PreTrainedModel.
+
+ Returns:
+ PreTrainedModel
+ """
+
+ try:
+ from transformers.modeling_utils import PreTrainedModel
+
+ except ImportError:
+
+ class PreTrainedModel:
+ """
+ Stub for PreTrainedModel
+ """
+
+ return PreTrainedModel
+
def module(self):
"""
Imports torch.nn.Module
@@ -52,47 +109,52 @@ class TorchLib:
return Module
- def pretrained(self):
+ def torch(self):
"""
- Imports transformers.modeling_utils.PreTrainedModel.
+ Imports torch.
Returns:
- PreTrainedModel
+ torch
"""
try:
- from transformers.modeling_utils import PreTrainedModel
+ import torch
except ImportError:
- class PreTrainedModel:
+ class Torch:
"""
- Stub for PreTrainedModel
+ Stub for torch
"""
- return PreTrainedModel
+ def __getattr__(self, name):
+ raise ImportError("Torch is not installed, install torch to use this module")
- def torch(self):
+ torch = Torch()
+
+ return torch
+
+ def transformers(self):
"""
- Imports torch.
+ Imports transformers.
Returns:
- torch
+ transformers
"""
try:
- import torch
+ import transformers
except ImportError:
- class Torch:
+ class Transformers:
"""
- Stub for torch
+ Stub for transformers
"""
def __getattr__(self, name):
- raise ImportError("Torch is not installed, install torch to use this module")
+ raise ImportError("Transformers is not installed, install transformers to use this module")
- torch = Torch()
+ transformers = Transformers()
- return torch
+ return transformers
diff --git a/src/python/txtai/vectors/dense/litellm.py b/src/python/txtai/vectors/dense/litellm.py
index 50a5b363..538c64e4 100644
--- a/src/python/txtai/vectors/dense/litellm.py
+++ b/src/python/txtai/vectors/dense/litellm.py
@@ -4,8 +4,6 @@ LiteLLM module
import numpy as np
-from transformers.utils import cached_file
-
# Conditional import
try:
import litellm as api
@@ -14,6 +12,8 @@ try:
except ImportError:
LITELLM = False
+from ...util import Download
+
from ..base import Vectors
@@ -63,7 +63,7 @@ class LiteLLM(Vectors):
# pylint: disable=W0702
try:
- return cached_file(path_or_repo_id=path, filename="config.json") is not None if "/" in path else False
+ return Download()(path, "config.json") is not None if "/" in path else False
except:
return False
diff --git a/src/python/txtai/vectors/dense/llama.py b/src/python/txtai/vectors/dense/llama.py
index 0cdcfb48..e66ee065 100644
--- a/src/python/txtai/vectors/dense/llama.py
+++ b/src/python/txtai/vectors/dense/llama.py
@@ -6,8 +6,6 @@ import os
import numpy as np
-from huggingface_hub import hf_hub_download
-
# Conditional import
try:
import llama_cpp as llama
@@ -16,6 +14,8 @@ try:
except ImportError:
LLAMA_CPP = False
+from ...util import Download
+
from ..base import Vectors
@@ -47,7 +47,7 @@ class LlamaCpp(Vectors):
def loadmodel(self, path):
# Check if this is a local path, otherwise download from the HF Hub
- path = path if os.path.exists(path) else self.download(path)
+ path = path if os.path.exists(path) else Download()(path)
# Additional model arguments
modelargs = self.config.get("vectors", {})
@@ -71,23 +71,3 @@ class LlamaCpp(Vectors):
# Generate embeddings and return as a NumPy array
# llama-cpp-python has it's own batching built-in using n_batch parameter
return np.array(self.model.embed(data), dtype=np.float32)
-
- def download(self, path):
- """
- Downloads path from the Hugging Face Hub.
-
- Args:
- path: full model path
-
- Returns:
- local cached model path
- """
-
- # Split into parts
- parts = path.split("/")
-
- # Calculate repo id split
- repo = 2 if len(parts) > 2 else 1
-
- # Download and cache file
- return hf_hub_download(repo_id="/".join(parts[:repo]), filename="/".join(parts[repo:]))
diff --git a/src/python/txtai/vectors/dense/m2v.py b/src/python/txtai/vectors/dense/m2v.py
index fa44e4a7..17f5cddf 100644
--- a/src/python/txtai/vectors/dense/m2v.py
+++ b/src/python/txtai/vectors/dense/m2v.py
@@ -5,7 +5,6 @@ Model2Vec module
import json
from huggingface_hub.errors import HFValidationError
-from transformers.utils import cached_file
# Conditional import
try:
@@ -15,6 +14,7 @@ try:
except ImportError:
MODEL2VEC = False
+from ...util import Download
from ..base import Vectors
@@ -37,7 +37,7 @@ class Model2Vec(Vectors):
try:
# Download file and parse JSON
- path = cached_file(path_or_repo_id=path, filename="config.json")
+ path = Download()(path, "config.json")
if path:
with open(path, encoding="utf-8") as f:
config = json.load(f)
diff --git a/src/python/txtai/vectors/dense/words.py b/src/python/txtai/vectors/dense/words.py
index b748e990..f94555d9 100644
--- a/src/python/txtai/vectors/dense/words.py
+++ b/src/python/txtai/vectors/dense/words.py
@@ -12,7 +12,6 @@ from multiprocessing import Pool
import numpy as np
from huggingface_hub.errors import HFValidationError
-from transformers.utils import cached_file
# Conditional import
try:
@@ -23,6 +22,7 @@ except ImportError:
STATICVECTORS = False
from ...pipeline import Tokenizer
+from ...util import Download
from ..base import Vectors
@@ -92,7 +92,7 @@ class WordVectors(Vectors):
try:
# Download file and parse JSON
- path = cached_file(path_or_repo_id=path, filename="config.json")
+ path = Download()(path, "config.json")
if path:
with open(path, encoding="utf-8") as f:
config = json.load(f)
diff --git a/src/python/txtai/workflow/execute.py b/src/python/txtai/workflow/execute.py
index 2c8b65df..c384c1e0 100644
--- a/src/python/txtai/workflow/execute.py
+++ b/src/python/txtai/workflow/execute.py
@@ -4,10 +4,10 @@ Execute module
from multiprocessing.pool import Pool, ThreadPool
-# Conditional torch imports
-from ..util import TorchLib
+# Conditional imports
+from ..util import TransformersLib
-torch = TorchLib().torch()
+torch = TransformersLib().torch()
class Execute:
diff --git a/src/python/txtai/workflow/task/base.py b/src/python/txtai/workflow/task/base.py
index e212d6ee..5a1ca65f 100644
--- a/src/python/txtai/workflow/task/base.py
+++ b/src/python/txtai/workflow/task/base.py
@@ -8,10 +8,10 @@ import types
import numpy as np
-# Conditional torch imports
-from ...util import TorchLib
+# Conditional imports
+from ...util import TransformersLib
-torch = TorchLib().torch()
+torch = TransformersLib().torch()
# Logging configuration
logger = logging.getLogger(__name__)
diff --git a/test/python/testtorch.py b/test/python/testtransformers.py
similarity index 67%
rename from test/python/testtorch.py
rename to test/python/testtransformers.py
index 3f8aa7b6..33dfb5cc 100644
--- a/test/python/testtorch.py
+++ b/test/python/testtransformers.py
@@ -1,5 +1,5 @@
"""
-Torch module tests
+Transformers module tests
"""
import sys
@@ -9,18 +9,20 @@ import unittest
import txtai
-class TestTorch(unittest.TestCase):
+class TestTransformers(unittest.TestCase):
"""
- Simulates torch not being installed. Even though torch is a required dependency, txtai can operate without it gracefully.
+ Simulates transformers not being installed.
"""
@classmethod
def setUpClass(cls):
"""
- Simulate torch not being installed
+ Simulate transformers not being installed
"""
modules = [
+ "transformers",
+ "transformers.configuration_utils",
"transformers.modeling_utils",
"transformers.modeling_outputs",
"torch",
@@ -58,21 +60,23 @@ class TestTorch(unittest.TestCase):
else:
del sys.modules[key]
- def testTorch(self):
+ def testTransformers(self):
"""
- Test torch not installed
+ Test transformers not installed
"""
- from txtai.util import TorchLib
+ from txtai.util import TransformersLib
- torchlib = TorchLib()
+ lib = TransformersLib()
- # Test torch stubs
- self.assertTrue(torchlib.dataset().__module__.endswith("torchlib"))
- self.assertTrue(torchlib.module().__module__.endswith("torchlib"))
- self.assertTrue(torchlib.pretrained().__module__.endswith("torchlib"))
- self.assertTrue(torchlib.torch())
+ # Test transformers stubs
+ for x in [lib.arguments(), lib.config(), lib.dataset(), lib.module(), lib.model()]:
+ self.assertTrue(x.__module__.endswith("transformerslib"))
# pylint: disable=W0106
with self.assertRaises(ImportError):
- torchlib.torch().device
+ lib.transformers().AutoModel
+
+ # pylint: disable=W0106
+ with self.assertRaises(ImportError):
+ lib.torch().device
diff --git a/test/python/testvectors/testdense/testwordvectors.py b/test/python/testvectors/testdense/testwordvectors.py
index 7ee98e4b..f378cf89 100644
--- a/test/python/testvectors/testdense/testwordvectors.py
+++ b/test/python/testvectors/testdense/testwordvectors.py
@@ -12,7 +12,7 @@ import numpy as np
from huggingface_hub.errors import HFValidationError
from txtai.vectors import VectorsFactory
-from txtai.vectors.dense.words import create, transform
+from txtai.vectors.dense.words import create, transform, WordVectors
class TestWordVectors(unittest.TestCase):
@@ -147,10 +147,13 @@ class TestWordVectors(unittest.TestCase):
Test loading model that doesn't exist
"""
- # Test non-existent path raises an exception
+ # Test non-existent local path raises an exception
with self.assertRaises((IOError, HFValidationError)):
VectorsFactory.create({"method": "words", "path": os.path.join(tempfile.gettempdir(), "noexist")}, None)
+ # Test non-existent hub path is handled properly
+ self.assertFalse(WordVectors.ismodel("invalid/user/noexist"))
+
def testTransform(self):
"""
Test word vector transform