Views
No views yet
1from peft import PeftModel
2from transformers import AutoModelForSeq2SeqLM
3from transformers import AutoTokenizer
4import torch
5
6base_model = AutoModelForSeq2SeqLM.from_pretrained("t5-small")
7my_model = PeftModel.from_pretrained(base_model, "Lakshan2003/finetuned-t5-xsum")
8
9def test_peft_summarizer(text, model, max_length=128, min_length=30):
10 """
11 Test the PEFT-loaded summarization model
12
13 Args:
14 text (str): Input text to summarize
15 model: The loaded PEFT model
16 max_length (int): Maximum length of the summary
17 min_length (int): Minimum length of the summary
18 """
19 # Load tokenizer for t5-small (base model)
20 tokenizer = AutoTokenizer.from_pretrained("Lakshan2003/finetuned-t5-xsum")
21
22 # Move model to GPU if available
23 device = "cuda" if torch.cuda.is_available() else "cpu"
24 model = model.to(device)
25
26 # Prepare the input text
27 prefix = "summarize: "
28 input_text = prefix + text
29
30 # Tokenize
31 inputs = tokenizer(input_text, return_tensors="pt", max_length=512, truncation=True)
32 inputs = {k: v.to(device) for k, v in inputs.items()}
33
34 # Generate summary
35 with torch.no_grad():
36 output_ids = model.generate(
37 input_ids=inputs["input_ids"],
38 attention_mask=inputs["attention_mask"],
39 max_length=max_length,
40 min_length=min_length,
41 num_beams=4,
42 length_penalty=2.0,
43 early_stopping=True,
44 no_repeat_ngram_size=3
45 )
46
47 # Decode the summary
48 summary = tokenizer.decode(output_ids[0], skip_special_tokens=True)
49
50 return summary
51
52# Test text
53test_text = """
54The United Nations has warned that climate change poses an unprecedented threat to human civilization. In a landmark report, scientists detailed how rising temperatures are affecting everything from weather patterns to food production. The report emphasizes that without immediate and substantial action to reduce greenhouse gas emissions, the world faces severe consequences including rising sea levels, more frequent extreme weather events, and widespread ecosystem collapse. Many countries have pledged to reduce their carbon emissions, but experts say current commitments fall short of what's needed to prevent the worst impacts of climate change. The report also highlights the disproportionate effect of climate change on developing nations, which often lack the resources to adapt to changing conditions.
55"""
56
57# Generate summary
58summary = test_peft_summarizer(test_text, my_model)
59
60print("Original Text:")
61print(test_text)
62print("\nGenerated Summary:")
63print(summary)