Views
No views yet
1import torch
2from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
3from peft import PeftModel
4
5model_id = "meta-llama/Meta-Llama-3-8B"
6lora_id = "raicrits/Llama3_ChangeOfTopic"
7
8quantization_config = BitsAndBytesConfig(
9 load_in_8bit=True)
10
11base_model = AutoModelForCausalLM.from_pretrained(model_id,
12 quantization_config=quantization_config,
13 device_map=device)
14model = PeftModel.from_pretrained(base_model, lora_id)
15
16
17tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
18tokenizer.pad_token = tokenizer.eos_token
19tokenizer.padding_side = "right"
20
21terminators = [
22 tokenizer.eos_token_id,
23 tokenizer.convert_tokens_to_ids("<|eot_id|>")
24]
25
26messages = [
27 {"role": "system", "content": "You are an AI assistant able to detect change of topics in given texts."},
28 {"role": "user", "content": f"""Analyze the following text written in italian and in case you detect a change of topic answer just with "1", otherwise, if the topic remains the same within all the given text answer just "0". do not add further text.
29
30Text: {'<text>'}"""
31]
32
33input_ids = tokenizer.apply_chat_template(
34 messages,
35 add_generation_prompt=True,
36 return_tensors="pt").to(model.device)
37
38with torch.no_grad():
39 outputs = model.generate(
40 input_ids,
41 max_new_tokens=1,
42 eos_token_id=terminators,
43 do_sample=True,
44 temperature=0.2
45 )
46 response = outputs[0][input_ids.shape[-1]:]
47print(tokenizer.decode(response, skip_special_tokens=False))