CodeTF是一个基于Python转换器的一站式库,用于代码大型语言模型(Code LLM)和代码智能,为代码智能任务(如代码摘要,翻译,代码生成等)的训练和推理提供了无缝接口。它旨在促进SOTA CodeLLMs与实际应用程序的轻松集成。
除了LLM的核心代码功能外,CodeTF还提供了用于跨各种语言的代码操作的实用程序,包括轻松提取代码属性。使用树坐者作为其核心 AST 解析器,它可以解析函数名称、注释和变量名称等属性。提供多种语言的预构建库,无需复杂的解析器设置。因此,CodeTF 可确保为代码智能任务提供用户友好且可访问的环境。
该库的当前版本提供:
下表显示了支持的模型及其大小以及模型支持的任务。这是一项持续的努力,我们正在努力进一步扩大名单。
型 | 大小 | 任务 |
---|---|---|
代码T5 | Base, Base-multi-sum, Base-translate-cs, Base-translate-java, Base-sum, Base-clone, Base-defect | 预训练,NL到代码,精炼,翻译(CS到Java,Java到CS),摘要(Python,Go,PHP,JavaScript,Java,Ruby),克隆检测,缺陷预测 |
CodeT5+ | 加指令-16B, 加-16B, 加-6B, 加-2B, 加-770M-python, 加-770M, 加-220M | 预训练、NL 到编码、优化、缺陷预测 |
代码生成 | 单声道: 350M, 2B, 6B, 1B, 3.7B, 7B, 16B 多声道: 350M, 2B, 6B 荷兰: 350M, 2B |
预训练 |
星码器 | 15.5乙 | 预训练 |
圣诞老人 | 1.1乙 | 预训练 |
GPT-NeoX | 20乙 | 预训练 |
GPT-Neo | 1.3乙 | 预训练 |
GPT-J | 6乙 | 预训练 |
编码器 | 6乙 | 预训练 |
代码鹦鹉 | 小蟒蛇 (110M), 小多(110M), 1.5B | 预训练 |
代码伯特 | CodeBERT-base, UnixCoder-base, CodeBERTa-small | 预训练 |
conda create -n codetf python=3.8
conda activate codetf
pip install salesforce-codetf==1.0.1.1
git clone https://github.com/salesforce/CodeTF.git
cd CodeTF
pip install -e .
此外,为了确保量化功能运行良好,还要安装以下依赖项:
pip install -q -U git+https://github.com/huggingface/transformers.git
pip install -q -U git+https://github.com/huggingface/peft.git
pip install -q -U git+https://github.com/huggingface/accelerate.git
对于某些型号,例如StarCoder,需要登录Huggingface。请获取拥抱面孔令牌并登录:
huggingface-cli login
使用我们的模型加载管道功能,开始使用 CodeTF 既简单又快速。以下示例显示了如何加载 codet5+ 模型并对代码生成任务执行推理:
load_model_pipeline()
from codetf.models import load_model_pipeline
code_generation_model = load_model_pipeline(model_name="codet5", task="pretrained",
model_type="plus-770M-python", is_eval=True,
load_in_8bit=True, load_in_4bit=False, weight_sharding=False)
result = code_generation_model.predict(["def print_hello_world():"])
print(result)
有几个值得注意的论点需要考虑:
model_name:型号名称、当前支持和 。
codet5
causal-lm
model_type:每个型号名称的型号类型,例如、、等。
base
codegen-350M-mono
j-6B
load_in_8bit和:继承拥抱面量化的动态量化特征。
load_in_4bit
weight_sharding:我们的高级功能,利用HuggingFace分片检查点将大型模型拆分为不同GPU中的几个较小分片。如果你正在处理大型模型,请考虑使用它。
你可能需要查看所有受支持的模型。为此,你可以使用:
model_zoo()
from codetf.models import model_zoo
print(model_zoo)
# ============================================================================================================
# Architectures Types Tasks
# ============================================================================================================
# causallm codegen-350M-mono pretrained
# codegen-350M-multi pretrained
# codegen-350M-nl pretrained
# codegen-2B-mono pretrained
# codegen-2B-multi pretrained
# codegen-2B-nl pretrained
# codegen-6B-mono pretrained
# codegen-6B-nl pretrained
# codegen-6B-multi pretrained
# starcoder-15.5B pretrained
# gpt-neox-20B pretrained
# gpt-neo-1.3B pretrained
# gpt-j-6B pretrained
# incoder-6B pretrained
# codegen2-1B pretrained
# codegen2-3.7B pretrained
# codegen2-7B pretrained
# codegen2-16B pretrained
# codet5 base-multi-sum pretrained
# base nl2code
# base refine
# base translate_cs_java
# base translate_java_cs
# base sum_python
# base sum_go
# base sum_php
# base sum_javascript
# base sum_java
# base sum_ruby
# base clone
# base defect
# plus-instruct-16B pretrained
# plus-16B pretrained
# plus-6B pretrained
# plus-2B pretrained
# plus-770M-python pretrained
# plus-770M pretrained
# plus-220M pretrained
# bert codebert-base pretrained
# unixcoder-base pretrained
# codeberta-small pretrained
想要为代码训练自定义 LLM?我们为你提供保障。下面是一个使用 微调 CodeT5+ 预训练模型的示例,以及我们的数据集实用程序,可以轻松使用 CodeXGLUE 数据集微调模型。下面是一个示例:
Seq2SeqTrainer
from codetf.trainer.codet5_trainer import CodeT5Seq2SeqTrainer
from codetf.data_utility.codexglue_dataset import CodeXGLUEDataset
from codetf.models import load_model_pipeline
from codetf.performance.evaluation_metric import EvaluationMetric
from codetf.data_utility.base_dataset import CustomDataset
model_class = load_model_pipeline(model_name="codet5", task="pretrained",
model_type="plus-220M", is_eval=True)
dataset = CodeXGLUEDataset(tokenizer=model_class.get_tokenizer())
train, test, validation = dataset.load(subset="text-to-code")
train_dataset= CustomDataset(train[0], train[1])
test_dataset= CustomDataset(test[0], test[1])
val_dataset= CustomDataset(validation[0], validation[1])
evaluator = EvaluationMetric(metric="bleu", tokenizer=model_class.tokenizer)
# peft can be in ["lora", "prefixtuning"]
trainer = CodeT5Seq2SeqTrainer(train_dataset=train_dataset,
validation_dataset=val_dataset,
peft="lora",
pretrained_model_or_path=model_class.get_model(),
tokenizer=model_class.tokenizer)
trainer.train()
与 StarCoder 的这个脚本相比,它需要 ~300 个 LOC 来微调模型,我们只需要 14 个 LOC 来执行相同的!!!
计划重现众所周知的基准测试的结果,例如,但努力无法达到与原始论文中报告的相同数字?担心复杂的评估过程?别担心,我们为你提供了直观、易于使用的界面。下面是一个示例代码段,演示如何使用 pass@k (k=[1,10,100]) 作为指标来评估人类评估:
Human-Eval
from codetf.models import load_model_pipeline
from codetf.data_utility.human_eval_dataset import HumanEvalDataset
from codetf.performance.model_evaluator import ModelEvaluator
os.environ["HF_ALLOW_CODE_EVAL"] = "1"
os.environ["TOKENIZERS_PARALLELISM"] = "true"
model_class = load_model_pipeline(model_name="causal-lm", task="pretrained",
model_type="codegen-350M-mono", is_eval=True,
load_in_8bit=True, weight_sharding=False)
dataset = HumanEvalDataset(tokenizer=model_class.get_tokenizer())
prompt_token_ids, prompt_attention_masks, references= dataset.load()
problems = TensorDataset(prompt_token_ids, prompt_attention_masks)
evaluator = ModelEvaluator(model_class)
avg_pass_at_k = evaluator.evaluate_pass_k(problems=problems, unit_tests=references)
print("Pass@k: ", avg_pass_at_k)
与HuggingFace的这个脚本相比,它需要~230个LOC来评估pass@k,我们只需要14个LOC来做同样的!!!
CodeTF为几个著名的数据集提供了数据集实用程序,例如CodeXGLUE,Human Eval,MBPP和APPS。下面是如何加载 CodeXGLUE 数据集的示例:
from codetf.data_utility.codexglue_dataset import CodeXGLUEDataset
from transformers import RobertaTokenizer
tokenizer = RobertaTokenizer.from_pretrained("Salesforce/codet5-base", use_fast=True)
dataset = CodeXGLUEDataset(tokenizer=tokenizer)
train, test, validation = dataset.load(subset="text-to-code")
、 以 Pytorch 张量的形式返回,为用户提供灵活性,将其包装到更高杠杆的包装器中,用于他们自己的用例。
train
test
validation
除了为LLM提供实用程序外,CodeTF还为用户提供了有效操作源代码的工具。这在代码智能管道中至关重要,其中通常需要将代码解析为抽象语法树 (AST) 或提取代码属性(如函数名称或标识符)等操作 (CodeT5)。这些任务可能难以执行,尤其是在需要设置和多语言支持时。我们的代码实用程序界面提供了一个简化的解决方案,便于从 15+ 种语言的代码中轻松解析和提取属性。
CodeTF包括与多种编程语言兼容的AST解析器。下面是一个示例,展示了如何将 Apex 代码解析为 AST 的过程:
from codetf.code_utility.apex.apex_code_utility import ApexCodeUtility
apex_code_utility = ApexCodeUtility()
sample_code = """
public class SampleClass {
public Integer myNumber;
**
* This is a method that returns the value of myNumber.
* @return An integer value
*/
public Integer getMyNumber() {
// Return the current value of myNumber
return this.myNumber;
}
}
"""
ast = apex_code_utility.parse(sample_code)
# This will print the tree-sitter AST object
print(ast)
然后你可以使用py-tree-sitter的界面遍历树
root_node = ast.root_node assert root_node.type == 'module' assert root_node.start_point == (1, 0) assert root_node.end_point == (3, 13)
还有其他用于Java,Python等的实用程序可以执行相同的操作。
CodeTF 提供了一个接口来轻松提取代码属性。以下是提取 Python 函数的函数名称的示例:
code_attributes = apex_code_utility.get_code_attributes(sample_code)
print(code_attributes)
这将打印:
{'class_names': ['AccountWithContacts'], 'method_names': ['getAccountsWithContacts'], 'comments': [], 'variable_names': ['acc', 'accounts', 'con', 'System', 'debug', 'Contacts', 'Id', 'Name', 'Account', 'Email', 'LastName']}
还有其他现有的实用程序,例如从代码中删除注释:
new_code_snippet = apex_code_utility.remove_comments(sample_code)
print(new_code_snippet)
这将打印:
public class SampleClass {
public Integer myNumber;
public Integer getMyNumber() {
return this.myNumber;
}
}
请注意,这是一个持续的过程,我们将在将来添加更多功能来提取复杂的代码属性。更多示例可以在这里找到。
你可以找到每个用例的更多示例:
CodeTF 虽然功能强大,但不能保证万无一失的代码智能功能。用户可能会遇到不准确或偏见,可能导致误解或不良行为。风险包括生成不安全的代码、传播不良编码实践或无意中泄露敏感数据。我们强烈建议用户在实际采用之前检查预训练的模型和系统。CodeTF 有助于有效的代码分析、预测和调试,促进可重现的研究和开发。我们鼓励负责任地使用它来提高软件质量和开发人员的生产力。
但是,滥用可能会导致不道德的结果,例如未经授权的代码操作、隐私泄露或不安全的编码实践。在使用 CodeTF 之前,用户应熟悉负责任 AI 的准则。我们的承诺是通过识别和减少潜在的偏见和不当行为来不断完善库。用户应在实际实施之前审查模型和系统,并为完善库做出贡献,以确保合乎道德的使用。
你可以在我们的技术报告中找到更多详细信息。
如果你在研究或应用中使用 CodeTF,请使用此 BibTeX 引用:
@misc{nghi2023codetf,
title={CodeTF: A Transformer-based Library for CodeLLM & Code Intelligence},
author={Nghi D. Q. Bui, Henry Le, Yue Wang, Akhilesh Deepak Gotmare, Junnan Li, Steven Hoi.},
year={2023},
eprint={2209.09019},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
如果你有任何问题,意见或建议,请随时与我们联系 codetf@salesforce.com。