Views
No views yet
1import torch
2from unsloth import FastLanguageModel
3from transformers import AutoTokenizer
4from peft import PeftModel
5
6# The Hugging Face model ID for the fine-tuned adapter
7hf_model_id = "Vihanga445/sinllama-singlis-sentiment-analysis"
8base_model_name = "polyglots/SinLlama_v01"
9
10# 1. Load Tokenizer and Base Model
11tokenizer = AutoTokenizer.from_pretrained(hf_model_id)
12model, _ = FastLanguageModel.from_pretrained(
13 model_name = base_model_name,
14 max_seq_length = 2048,
15 dtype = torch.bfloat16,
16 load_in_4bit = True,
17 resize_model_vocab = 139336,
18)
19
20# 2. Attach Adapters and Prep for Inference
21model = PeftModel.from_pretrained(model, hf_model_id)
22FastLanguageModel.for_inference(model)
23
24# 3. Define the prompt and stopping criteria
25prompt = """### Instruction:
26Analyze the sentiment of the comment enclosed in square brackets, determine if it is positive, neutral, or negative, and return the answer as the corresponding sentiment label "Pos" or "Neu" or "Neg".
27
28### Input:
29[awulak na]
30
31### Response:
32"""
33
34inputs = tokenizer([prompt], return_tensors = "pt").to("cuda")
35
36# Define Llama-3 termination tokens
37terminators = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|eot_id|>")]
38
39# 4. Generate only the label
40outputs = model.generate(
41 **inputs,
42 max_new_tokens = 64,
43 eos_token_id = terminators,
44 pad_token_id = tokenizer.eos_token_id,
45 do_sample = False
46)
47
48# 5. Clean and Display Output
49decoded = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
50final_answer = decoded.split("### Response:\n")[-1].strip().split("\n")[0]
51
52print(f"Sentiment: {final_answer}")