Views
No views yet
1'''
2This function generates prompts using the problem description and input.
3@param1 instruction: str - text problem description
4@param2 inputs: str - input to the program
5'''
6def generate_prompt(instruction, inputs=""):
7 text = ("Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"
8 "### Instruction:\n"
9 f"{instruction}\n\n"
10 "### Input:\n"
11 f"{inputs}\n\n"
12 "### Output:\n")
13 return text1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3# load model and tokenizer
4model = AutoModelForCausalLM.from_pretrained("iamtarun/codegen-350M-mono-4bit-qlora", device_map="auto")
5tokenizer = AutoTokenizer.from_pretrained("iamtarun/codegen-350M-mono-4bit-qlora")
6
7# loading model for inference
8model.eval()
9
10# inference function
11'''
12This function takes text prompt as input which is generated from the generate_prompt function and returns the generated response
13
14@param1 prompt: str - text prompt generated using generate_prompt function.
15'''
16def pipe(prompt):
17 device = "cuda"
18 inputs = tokenizer(prompt, return_tensors="pt").to(device)
19 with torch.no_grad():
20 output = model.generate(**inputs,
21 max_length=512,
22 do_sample=True,
23 temperature=0.5,
24 top_p=0.95,
25 repetition_penalty=1.15)
26 return tokenizer.decode(output[0].tolist(),
27 skip_special_tokens=True,
28 clean_up_tokenization_space=False)
29
30# generating code for a problem description
31instruction = "Write a function to calculate square of a number in python"
32inputs = "number = 5"
33prompt = generate_prompt(instruction, inputs)
34print(pipe(prompt))
35print("\n", "="*100)