To use quantized Mistral models (like Zephyr) via ctransformers, first install the necessary packages:
pip install ctransformers[cuda]
pip install --upgrade git+https://github.com/huggingface/transformers
When loading the model with AutoModelForCausalLM.from_pretrained, use the gpu_layers parameter to offload layers to the GPU (set to 0 if no GPU is available). You must define a prompt template that includes [DOCUMENTS] and [KEYWORDS] tags to guide the model.
from ctransformers import AutoModelForCausalLM
from transformers import AutoTokenizer, pipeline
from bertopic.representation import TextGeneration
from bertopic import BERTopic
# Load quantized model
model = AutoModelForCausalLM.from_pretrained(
"TheBloke/zephyr-7B-alpha-GGUF",
model_file="zephyr-7b-alpha.Q4_K_M.gguf",
model_type="mistral",
gpu_layers=50,
hf=True
)
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-alpha")
# Create pipeline
generator = pipeline(
model=model, tokenizer=tokenizer,
task='text-generation',
max_new_tokens=50,
repetition_penalty=1.1
)
# Define prompt with tags
prompt = """<|system|>You are a helpful, respectful and honest assistant for labeling topics..</s>
<|user|>
I have a topic that contains the following documents:
[DOCUMENTS]
The topic is described by the following keywords: '[KEYWORDS]'.
Based on the information about the topic above, please create a short label of this topic. Make sure you to only return the label and nothing more.</s>
<|assistant|>"""
# Use in BERTopic
zephyr = TextGeneration(generator, prompt=prompt)
representation_model = {"Zephyr": zephyr}
topic_model = BERTopic(representation_model=representation_model, verbose=True)