Views
No views yet
google/gemma-2b base model. It is designed to be lightweight and efficient while retaining the capabilities of the base model.peft and transformers libraries. Since this is a LoRA adapter, you must load the base model first.1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer
3from peft import PeftModel
4
5# 1. Load Model & Adapter
6base_model = "google/gemma-2b"
7adapter_repo = "indrajeet77/sentiment-analyzer"
8
9tokenizer = AutoTokenizer.from_pretrained(base_model)
10
11model = AutoModelForCausalLM.from_pretrained(
12 base_model,
13 device_map="auto",
14 torch_dtype=torch.float16
15)
16
17model = PeftModel.from_pretrained(model, adapter_repo)
18
19
20# 2. Inference Function
21def get_sentiment(text):
22 # We use "Few-Shot Prompting" to force the model to give a one-word answer
23 prompt = f"""Classify the sentiment as positive, negative, or neutral.
24
25Text: The movie was terrible and boring.
26Sentiment: negative
27
28Text: I am so happy with this result!
29Sentiment: positive
30
31Text: {text}
32Sentiment:"""
33
34 inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
35
36 with torch.no_grad():
37 outputs = model.generate(
38 **inputs,
39 max_new_tokens=2,
40 do_sample=False,
41 pad_token_id=tokenizer.eos_token_id
42 )
43
44 # Decode and clean the output
45 response = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
46 return response.strip().lower()
47
48# 3. Run It
49print("Model Loaded. Testing...")
50text = "The product quality is amazing"
51print(f"Text: {text}")
52print(f"Prediction: {get_sentiment(text)}")