🚀 UniXcoder-base模型卡片
UniXcoder是一个统一的跨模态预训练模型,它利用多模态数据(即代码注释和抽象语法树AST)来预训练代码表示。该模型在代码处理相关任务中具有重要价值,能有效提升代码理解和生成的能力。
🚀 快速开始
依赖安装
pip install torch
pip install transformers
快速上手
我们实现了一个类来使用UniXcoder,你可以按照以下代码构建UniXcoder。
你可以通过以下命令下载该类:
wget https://raw.githubusercontent.com/microsoft/CodeBERT/master/UniXcoder/unixcoder.py
import torch
from unixcoder import UniXcoder
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = UniXcoder("microsoft/unixcoder-base")
model.to(device)
接下来,我们将给出几种不同模式下的零样本示例,包括 代码搜索(仅编码器)、代码补全(仅解码器)、函数名预测(编码器 - 解码器)、API推荐(编码器 - 解码器)、代码摘要(编码器 - 解码器)。
✨ 主要特性
UniXcoder是一个统一的跨模态预训练模型,利用多模态数据(即代码注释和AST)来预训练代码表示。
- 开发者:微软团队
- 共享方(可选):Hugging Face
- 模型类型:特征工程
- 语言(NLP):英语
- 许可证:Apache - 2.0
- 相关模型:
- 更多信息资源:
💻 使用示例
基础用法
仅编码器模式
对于仅编码器模式,我们给出一个 代码搜索 的示例。
代码和自然语言嵌入
以下是一个从CodeBERT获取代码片段嵌入的示例。
func = "def f(a,b): if a>b: return a else return b"
tokens_ids = model.tokenize([func],max_length=512,mode="<encoder-only>")
source_ids = torch.tensor(tokens_ids).to(device)
tokens_embeddings,max_func_embedding = model(source_ids)
func = "def f(a,b): if a<b: return a else return b"
tokens_ids = model.tokenize([func],max_length=512,mode="<encoder-only>")
source_ids = torch.tensor(tokens_ids).to(device)
tokens_embeddings,min_func_embedding = model(source_ids)
nl = "return maximum value"
tokens_ids = model.tokenize([nl],max_length=512,mode="<encoder-only>")
source_ids = torch.tensor(tokens_ids).to(device)
tokens_embeddings,nl_embedding = model(source_ids)
print(max_func_embedding.shape)
print(max_func_embedding)
torch.Size([1, 768])
tensor([[ 8.6533e-01, -1.9796e+00, -8.6849e-01, 4.2652e-01, -5.3696e-01,
-1.5521e-01, 5.3770e-01, 3.4199e-01, 3.6305e-01, -3.9391e-01,
-1.1816e+00, 2.6010e+00, -7.7133e-01, 1.8441e+00, 2.3645e+00,
...,
-2.9188e+00, 1.2555e+00, -1.9953e+00, -1.9795e+00, 1.7279e+00,
6.4590e-01, -5.2769e-02, 2.4965e-01, 2.3962e-02, 5.9996e-02,
2.5659e+00, 3.6533e+00, 2.0301e+00]], device='cuda:0',
grad_fn=<DivBackward0>)
代码和自然语言的相似度
现在,我们计算自然语言和两个函数之间的余弦相似度。尽管两个函数的差异仅在于一个运算符(<
和 >
),但UniXcoder可以区分它们。
norm_max_func_embedding = torch.nn.functional.normalize(max_func_embedding, p=2, dim=1)
norm_min_func_embedding = torch.nn.functional.normalize(min_func_embedding, p=2, dim=1)
norm_nl_embedding = torch.nn.functional.normalize(nl_embedding, p=2, dim=1)
max_func_nl_similarity = torch.einsum("ac,bc->ab",norm_max_func_embedding,norm_nl_embedding)
min_func_nl_similarity = torch.einsum("ac,bc->ab",norm_min_func_embedding,norm_nl_embedding)
print(max_func_nl_similarity)
print(min_func_nl_similarity)
tensor([[0.3002]], device='cuda:0', grad_fn=<ViewBackward>)
tensor([[0.1881]], device='cuda:0', grad_fn=<ViewBackward>)
仅解码器模式
对于仅解码器模式,我们给出一个 代码补全 的示例。
context = """
def f(data,file_path):
# write json data into file_path in python language
"""
tokens_ids = model.tokenize([context],max_length=512,mode="<decoder-only>")
source_ids = torch.tensor(tokens_ids).to(device)
prediction_ids = model.generate(source_ids, decoder_only=True, beam_size=3, max_length=128)
predictions = model.decode(prediction_ids)
print(context+predictions[0][0])
def f(data,file_path):
data = json.dumps(data)
with open(file_path, 'w') as f:
f.write(data)
编码器 - 解码器模式
对于编码器 - 解码器模式,我们给出两个示例,包括:函数名预测、API推荐、代码摘要。
函数名预测
context = """
def <mask0>(data,file_path):
data = json.dumps(data)
with open(file_path, 'w') as f:
f.write(data)
"""
tokens_ids = model.tokenize([context],max_length=512,mode="<encoder-decoder>")
source_ids = torch.tensor(tokens_ids).to(device)
prediction_ids = model.generate(source_ids, decoder_only=False, beam_size=3, max_length=128)
predictions = model.decode(prediction_ids)
print([x.replace("<mask0>","").strip() for x in predictions[0]])
['write_json', 'write_file', 'to_json']
API推荐
context = """
def write_json(data,file_path):
data = <mask0>(data)
with open(file_path, 'w') as f:
f.write(data)
"""
tokens_ids = model.tokenize([context],max_length=512,mode="<encoder-decoder>")
source_ids = torch.tensor(tokens_ids).to(device)
prediction_ids = model.generate(source_ids, decoder_only=False, beam_size=3, max_length=128)
predictions = model.decode(prediction_ids)
print([x.replace("<mask0>","").strip() for x in predictions[0]])
['json.dumps', 'json.loads', 'str']
代码摘要
context = """
# <mask0>
def write_json(data,file_path):
data = json.dumps(data)
with open(file_path, 'w') as f:
f.write(data)
"""
tokens_ids = model.tokenize([context],max_length=512,mode="<encoder-decoder>")
source_ids = torch.tensor(tokens_ids).to(device)
prediction_ids = model.generate(source_ids, decoder_only=False, beam_size=3, max_length=128)
predictions = model.decode(prediction_ids)
print([x.replace("<mask0>","").strip() for x in predictions[0]])
['Write JSON to file', 'Write json to file', 'Write a json file']
📄 许可证
本模型使用的许可证为Apache - 2.0。
📚 详细文档
引用说明
如果你使用此代码或UniXcoder,请考虑引用我们。
@article{guo2022unixcoder,
title={UniXcoder: Unified Cross-Modal Pre-training for Code Representation},
author={Guo, Daya and Lu, Shuai and Duan, Nan and Wang, Yanlin and Zhou, Ming and Yin, Jian},
journal={arXiv preprint arXiv:2203.03850},
year={2022}
}