Views
No views yet
1import matplotlib.pyplot as plt
2
3values = [1, 2, 3, 4]
4labels = ["a", "b", "c", "d"]# plot a bart chart1plt.bar(labels, values)
2plt.show()1import re
2from transformers import GPT2LMHeadModel, GPT2TokenizerFast
3
4# load the model
5tok = GPT2TokenizerFast.from_pretrained("Nokia/nlgp-docstring")
6model = GPT2LMHeadModel.from_pretrained("Nokia/nlgp-docstring")
7
8# preprocessing functions
9num_spaces = [2, 4, 6, 8, 10, 12, 14, 16, 18]
10def preprocess(context, query):
11 """
12 Encodes context + query as a single string and
13 replaces whitespace with special tokens <|2space|>, <|4space|>, ...
14 """
15 input_str = f"{context}\n{query} <|endofcomment|>\n"
16 indentation_symbols = {n: f"<|{n}space|>" for n in num_spaces}
17 m = re.match("^[ ]+", input_str)
18 if not m:
19 return input_str
20 leading_whitespace = m.group(0)
21 N = len(leading_whitespace)
22 for n in self.num_spaces:
23 leading_whitespace = leading_whitespace.replace(n * " ", self.indentation_symbols[n])
24 return leading_whitespace + input_str[N:]
25
26detokenize_pattern = re.compile(fr"<\|(\d+)space\|>")
27def postprocess(output):
28 output = output.split("<|cell|>")[0]
29 def insert_space(m):
30 num_spaces = int(m.group(1))
31 return num_spaces * " "
32 return detokenize_pattern.sub(insert_space, output)
33
34# inference
35code_context = """
36import matplotlib.pyplot as plt
37
38values = [1, 2, 3, 4]
39labels = ["a", "b", "c", "d"]
40"""
41query = "# plot a bar chart"
42
43input_str = preprocess(code_context, query)
44input_ids = tok(input_str, return_tensors="pt").input_ids
45
46max_length = 150 # don't generate output longer than this length
47total_max_length = min(1024 - input_ids.shape[-1], input_ids.shape[-1] + 150) # total = input + output
48
49input_and_output = model.generate(
50 input_ids=input_ids,
51 max_length=total_max_length,
52 min_length=10,
53 do_sample=False,
54 num_beams=4,
55 early_stopping=True,
56 eos_token_id=tok.encode("<|cell|>")[0]
57)
58
59output = input_and_output[:, input_ids.shape[-1]:] # remove the tokens that correspond to the input_str
60output_str = tok.decode(output[0])
61postprocess(output_str)