1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3INSTRUCTION_TEMPLATE = """
4 {instruction}
5
6 Solve the above problem efficiently and clearly. The last line of your response should be of the following format: 'Therefore, the final answer is: $\\boxed{{ANSWER}}$. I hope it is correct' (without quotes) where ANSWER is just the final number or expression that solves the problem. Think step by step before answering.
7 """.strip()
8
9model_name = "PKU-ML/G1-7B"
10
11model = AutoModelForCausalLM.from_pretrained(
12 model_name,
13 torch_dtype="auto",
14 device_map="auto"
15)
16tokenizer = AutoTokenizer.from_pretrained(model_name)
17
18prompt = "The task is to determine the degree centrality of a node in the graph.\n\n"\
19 "Degree centrality for a node is the fraction of nodes it is connected to.\n\n"\
20 "Here is an undirected graph containing nodes from 1 to 15. The edges are: (1, 15), (15, 11), (2, 3), (2, 6), (3, 6), (3, 7), (6, 7), (6, 8), (7, 8), (7, 14), (4, 10), (10, 5), (10, 12), (8, 14), (8, 9), (12, 11), (12, 13).\n\n"\
21 "Question: What is the degree centrality of node 2 in the graph?\n\n"\
22 "You need to format your answer as a float number."
23messages = [
24 {"role": "user", "content": INSTRUCTION_TEMPLATE.format(instruction=prompt)}
25]
26text = tokenizer.apply_chat_template(
27 messages,
28 tokenize=False,
29 add_generation_prompt=True
30)
31model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
32
33generated_ids = model.generate(
34 **model_inputs,
35 max_new_tokens=4096,
36 top_p=0.95,
37 top_k=30,
38 temperature=0.6
39)
40generated_ids = [
41 output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
42]
43
44response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
45print(response)