Views
No views yet
facebook/bart-large-cnn model using Low-Rank Adaptation (LoRA) on a financial QA dataset derived from financial_phrasebank. The goal was to improve the model's ability to generate concise, contextually grounded answers.UnstructuredURLLoader and chunked using RecursiveCharacterTextSplitter. Question-Answer pairs were constructed based on these chunks.facebook/bart-large-cnn base model. LoRA allows efficient adaptation of large models using low-rank updates while keeping most base model parameters frozen.r=8lora_alpha=16lora_dropout=0.1task_type=SEQ_2_SEQ_LMtarget_modules=["q_proj", "v_proj"] (Note: target modules depend on the base model architecture)Seq2SeqTrainingArguments):2e-42 (Adjusted based on training logs provided)2 per deviceeval_strategy: "epoch"save_strategy: "epoch"load_best_model_at_end: Truemetric_for_best_model: "eval_loss"Seq2SeqTrainer from the Hugging Face transformers library.facebook/bart-large-cnn model within a simulated RAG context (using financial_phrasebank as the context source for benchmarking).faithfulness, answer_relevancy, and context_precision.financial_phrasebank for the questions asked. However, these benchmark runs were incomplete due to evaluation setup issues (missing API keys for default metric models), resulting in many NaN/failed calculations. Therefore, quantitative scores from these runs are unreliable and not reported here.1import torch
2from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, AutoConfig
3from peft import PeftModel, PeftConfig
4
5# Specify the path to your saved LoRA model repository
6# This could be a local path or a Hugging Face Hub repo ID
7# PEFT_MODEL_PATH = "./bart-lora-finance/best_model" # Local path example
8PEFT_MODEL_PATH = "deoleojr/bart-finance-lora" # HF Hub example (replace if different)
9
10# Determine device
11device = "cuda" if torch.cuda.is_available() else "cpu"
12print(f"Using device: {device}")
13
14# Load the configuration from the PEFT model path
15try:
16 config = PeftConfig.from_pretrained(PEFT_MODEL_PATH)
17 print(f"Base model identified from config: {config.base_model_name_or_path}")
18except Exception as e:
19 print(f"Error loading PeftConfig: {e}")
20 # Fallback or exit if config cannot be loaded
21 config = None # Set config to None or handle error appropriately
22 BASE_MODEL_NAME = "facebook/bart-large-cnn" # Manually specify if needed
23 print(f"Warning: Could not load PeftConfig. Assuming base model: {BASE_MODEL_NAME}")
24
25
26# Load the base model
27if config:
28 BASE_MODEL_NAME = config.base_model_name_or_path
29try:
30 print(f"Loading base model: {BASE_MODEL_NAME}...")
31 base_model = AutoModelForSeq2SeqLM.from_pretrained(BASE_MODEL_NAME)
32 print("Base model loaded.")
33except Exception as e:
34 print(f"Error loading base model '{BASE_MODEL_NAME}': {e}")
35 exit()
36
37# Load the PEFT model (LoRA layers) on top of the base model
38try:
39 print(f"Loading LoRA adapter from: {PEFT_MODEL_PATH}...")
40 # Ensure the base model is loaded before applying adapters
41 model = PeftModel.from_pretrained(base_model, PEFT_MODEL_PATH)
42 model.to(device) # Move the combined model to the device
43 model.eval() # Set model to evaluation mode
44 print("LoRA model loaded and ready.")
45except Exception as e:
46 print(f"Error loading PEFT model: {e}")
47 exit()
48
49# Load the tokenizer (usually saved with the adapters)
50try:
51 print("Loading tokenizer...")
52 tokenizer = AutoTokenizer.from_pretrained(PEFT_MODEL_PATH)
53 print("Tokenizer loaded.")
54except Exception as e:
55 print(f"Error loading tokenizer from {PEFT_MODEL_PATH}: {e}")
56 # Fallback to base model tokenizer if necessary
57 try:
58 print(f"Falling back to base model tokenizer: {BASE_MODEL_NAME}")
59 tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_NAME)
60 print("Base model tokenizer loaded.")
61 except Exception as e_base_tok:
62 print(f"Error loading base tokenizer: {e_base_tok}")
63 exit()
64
65
66# Example usage
67question = "What was the main reason for Tesla's stock rally?"
68context = "Tesla (TSLA.O) rallied 10% after Morgan Stanley upgraded the electric car maker to 'overweight' from 'equal-weight', saying its Dojo supercomputer could boost the company's market value by nearly $600 billion."
69
70# Use the specified prompt format
71prompt = f"Instruction: {question}\n\n[Context Information]\n{context}"
72
73print(f"\nInput Prompt:\n{prompt}")
74
75inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to(device)
76
77# Generate the answer
78with torch.no_grad():
79 # Adjust generation parameters as needed
80 outputs = model.generate(
81 **inputs,
82 max_new_tokens=100, # Max tokens to ADD to the input
83 temperature=0.7, # Controls randomness (lower is more deterministic)
84 top_k=50, # Considers top K tokens
85 top_p=0.95, # Considers tokens cumulative prob > P
86 do_sample=True, # Use sampling (needed for temp, top_k, top_p)
87 num_beams=1 # Use 1 for sampling, >1 for beam search
88 )
89 prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
90
91print(f"\nQuestion: {question}")
92print(f"Generated Answer: {prediction}")Instruction: {question}
[Context Information]
{news_article_chunk}A concise, fact-based answer derived from the provided context.
Example:
"Morgan Stanley upgraded Tesla to 'overweight' from 'equal-weight', citing the potential of its Dojo supercomputer."