语言:
- 英文
- 代码
标签:
- 代码补全
- 代码生成
许可证: "Apache-2.0"
NLGP文档字符串模型
NLGP文档字符串模型在论文自然语言引导编程中首次提出。该模型基于Jupyter笔记本集合训练而成,可用于根据自然语言意图在特定代码上下文中合成Python代码(参见下方示例)。另请参阅NLGP自然语言模型。
本研究成果由诺基亚贝尔实验室团队完成。
上下文示例
import matplotlib.pyplot as plt
values = [1, 2, 3, 4]
labels = ["a", "b", "c", "d"]
意图描述
模型预测
plt.bar(labels, values)
plt.show()
使用说明
import re
from transformers import GPT2LMHeadModel, GPT2TokenizerFast
tok = GPT2TokenizerFast.from_pretrained("Nokia/nlgp-docstring")
model = GPT2LMHeadModel.from_pretrained("Nokia/nlgp-docstring")
num_spaces = [2, 4, 6, 8, 10, 12, 14, 16, 18]
def preprocess(context, query):
"""
将上下文+查询编码为单个字符串,
并用特殊标记<|2space|>, <|4space|>等替换空白符
"""
input_str = f"{context}\n{query} <|endofcomment|>\n"
indentation_symbols = {n: f"<|{n}space|>" for n in num_spaces}
m = re.match("^[ ]+", input_str)
if not m:
return input_str
leading_whitespace = m.group(0)
N = len(leading_whitespace)
for n in self.num_spaces:
leading_whitespace = leading_whitespace.replace(n * " ", self.indentation_symbols[n])
return leading_whitespace + input_str[N:]
detokenize_pattern = re.compile(fr"<\|(\d+)space\|>")
def postprocess(output):
output = output.split("<|cell|>")[0]
def insert_space(m):
num_spaces = int(m.group(1))
return num_spaces * " "
return detokenize_pattern.sub(insert_space, output)
code_context = """
import matplotlib.pyplot as plt
values = [1, 2, 3, 4]
labels = ["a", "b", "c", "d"]
"""
query = "# 绘制柱状图"
input_str = preprocess(code_context, query)
input_ids = tok(input_str, return_tensors="pt").input_ids
max_length = 150
total_max_length = min(1024 - input_ids.shape[-1], input_ids.shape[-1] + 150)
input_and_output = model.generate(
input_ids=input_ids,
max_length=total_max_length,
min_length=10,
do_sample=False,
num_beams=4,
early_stopping=True,
eos_token_id=tok.encode("<|cell|>")[0]
)
output = input_and_output[:, input_ids.shape[-1]:]
output_str = tok.decode(output[0])
postprocess(output_str)
版权与许可
版权所有 © 2021 诺基亚
基于Apache许可证2.0版本授权
SPDX许可证标识符: Apache-2.0