Views
No views yet
1!pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
2!pip install --no-deps xformers "trl<0.9.0" peft accelerate bitsandbytes1
2from unsloth import FastLanguageModel
3from typing import Dict, List, Tuple, Union, Any
4import pandas
5from tqdm import trange, tqdm
6import torch
7
8class FormatPrompt_context_QA():
9 '''format prompt class'''
10 def __init__(self, eos_token:str='</s>') -> None:
11 self.inputs = ['context','question'] # required input fields
12 self.outputs = ['answer'] # for training, and model inference output fields
13 self.eos_token = eos_token
14
15 def __call__(self, instance: Dict[str, Any]) -> str:
16 '''
17 function call operator
18 Args:
19 instance: dictionary with keys: 'context', 'question', 'answer'
20 Returns:
21 prompt: formatted prompt
22 '''
23 return self.formatting_prompt_func(instance)
24
25 def formatting_prompt_func(self, instance: dict) -> str:
26 '''format prompt for domain specific QA
27 note this is for fine-tuning pre-trained model,
28 if starting with instuct tuned model, use `tokenizer.apply_chat_template(messages)` instead
29 '''
30
31 assert all([ item in instance.keys() for item in self.inputs ]), logging.info(f"instance must have {self.inputs}!")
32
33 prompt = f"""<s> [INST] Answer following question based on Context: {str(instance["context"])}\
34 Question: {str(instance["question"])} \
35 Answer: [/INST]"""
36
37 if 'answer' in instance:
38 prompt += str(instance['answer']) + self.eos_token
39 return prompt1formatting_func = FormatPrompt_context_QA()
2
3# pull model from huggingface
4model, tokenizer = FastLanguageModel.from_pretrained(
5 model_name = "jingwang/mistral_context_qa",
6 max_seq_length = 2048,
7 dtype = None,
8 load_in_4bit = True,
9)
10
11
12FastLanguageModel.for_inference(model)
13
14example = {'question': 'What does the graph compare in terms of cumulative total return?',
15 'context': 'the following graph shows a comparison, from january 1, 2019 through december 31, 2023, of the cumulative total return on our common stock, the nasdaq composite index and a group of all public companies sharing the same sic code as us, which is sic code 3711, “ motor vehicles and passenger car bodies ” ( motor vehicles and passenger car bodies public company group ). such returns are based on historical results and are not intended to suggest future performance. data for the nasdaq composite index and the motor vehicles and passenger car bodies public company group assumes an investment of $ 100 on january 1, 2019 and reinvestment of dividends. we have never declared or paid cash dividends on our common stock nor do we anticipate paying any such cash dividends in the foreseeable future. 31',
16 'gold_answer': "The graph compares the cumulative total return from January 1, 2019, through December 31, 2023, of the company's common stock, the NASDAQ Composite Index, and a group of public companies with the same SIC code (3711 - Motor Vehicles and Passenger Car Bodies). The comparison assumes an initial investment of $100 on January 1, 2019, with reinvestment of dividends for the NASDAQ Composite Index and the Motor Vehicles and Passenger Car Bodies public company group.",
17}
18
19inputs = tokenizer([formatting_func(example)], return_tensors="pt", padding=False).to(model.device)
20input_length = inputs.input_ids.shape[-1]
21
22with torch.no_grad():
23 output = model.generate(**inputs,
24 do_sample=False,
25 temperature=0.1,
26 max_new_tokens=64,
27 pad_token_id=tokenizer.eos_token_id,
28 use_cache=False,
29 )
30 response = tokenizer.decode(
31 output[0][input_length::], # response only, remove prompts
32 skip_special_tokens=True,
33 )
34 print(response)
35The graph compares the cumulative total return on our common stock, the NASDAQ Composite Index, and a group of all public companies sharing the same SIC code as us, which is SIC code 3711, "Motor Vehicles and Passenger Car Bodies."