跳至主要内容

Qwen(阿里云)教程:入门与微调

Qwen 是由阿里云开发的大型语言和多模态模型家族,面向文本生成、图像理解与对话等多种任务。
· 10分钟 阅读

使用 AI 探索

如果先进的人工智能不再只属于大型科技公司,而是人人可用,会怎样?这正是Qwen背后的核心理念——一个由阿里云创建的全新 AI 模型家族。

Qwen(“通义千问”的英文简称)旨在通过阿里云提供的一系列 AI 工具,让 AI 模型更容易为所有人所用。Qwen 通过以下方式实现这一点:

  • 多种开箱即用的 AI 模型
  • 已完成预训练、易于适配的模型
  • 便于将 AI 集成到项目中的工具

借助 Qwen,您无需投入大量资源或具备深厚专业知识也能使用先进的 AI。

在本教程中,我们将:

  1. 探索 Qwen 模型的关键特性,包括其多语言能力与多模态处理能力。
  2. 带您完成访问与安装 Qwen 模型的流程。
  3. 演示使用 Qwen 进行文本生成与问答等任务的实用示例。
  4. 探讨在自定义数据集上微调 Qwen 模型以用于特定应用。
  5. 讨论 Qwen 的更广泛影响与未来前景。

什么是 Qwen?

Qwen 是一系列在海量多语言与多模态数据集上训练的强大模型。由阿里云开发,Qwen 将 AI 推向新高度,使其在自然语言处理、计算机视觉与音频理解方面更为智能且实用。

这些模型能够执行广泛的任务,包括:

  • 文本生成与理解
  • 问题解答
  • 图像描述与分析
  • 视觉问答
  • 音频处理
  • 工具使用与任务规划

Qwen 模型在多样化数据源上完成预训练,并通过高质量数据的后训练进行优化。

模型家族

Qwen 家族由多种面向不同需求与使用场景的专用模型组成。

Family of Qwen models

Qwen 模型家族强调通用性与易定制,支持针对特定应用或行业进行微调。凭借这种灵活性与强大能力,Qwen 成为各领域应用 AI 技术的优质选择。

Qwen 的关键特性

Qwen 模型家族为多种 AI 应用提供了强大而灵活的工具。以下是使 Qwen 脱颖而出的关键特性:

多语言支持

Qwen 在多语言理解与生成方面表现出色,兼具英语与中文的强大能力,并支持多种其他语言。最新的 Qwen2 模型将其语言覆盖扩展至额外 27 种语言,涵盖西欧、东欧与中欧、中东、东亚与南亚等地区。

广泛的语言支持使 Qwen 能够促进跨文化交流、进行高质量翻译、处理语码转换场景,并为全球应用生成本地化内容。

文本生成

Qwen 模型在多种文本生成任务上能力卓越。典型应用包括:

  • 文章写作: 生成连贯、上下文相关的长篇内容
  • 摘要生成: 将长文本压缩为精炼摘要
  • 诗歌创作: 在节奏与风格上用心创作诗句
  • 代码生成: 以多种编程语言编写可运行代码

模型能够在长序列(最多 32,768 个 token)中保持上下文,从而生成大段且连贯的文本输出。

问答

Qwen 在事实性与开放式问答方面同样表现优异。这使得它可以:

  • 信息检索: 从庞大知识库中快速提取相关事实
  • 分析推理: 对复杂的开放式问题给出深入回答
  • 任务特定回答: 针对不同领域(从常识到专业领域)定制回复

图像理解

借助 Qwen-VL 模型,Qwen 家族将能力扩展至涉及图像的多模态任务。其关键特性包括:

  • 图像描述: 为视觉内容生成描述性文本
  • 视觉问答: 回答有关图像内容的问题
  • 文档理解: 从包含文本与图形的图像中提取信息
  • 多图处理: 处理涉及多张图像的对话
  • 高分辨率支持: 可处理最高 448x448 像素的图像(Qwen-VL-Plus 与 Qwen-VL-Max 甚至支持更高分辨率)

开源

Qwen 最重要的特性之一是其开源属性,为 AI 社区带来多重益处:

  • 可及性: 免费获取并使用模型
  • 透明性: 模型架构与训练过程可公开审视与改进
  • 可定制性: 用户可针对特定应用或领域进行微调
  • 社区驱动开发: 鼓励协作,加速 AI 技术进步
  • 伦理考量: 有助于更广泛地讨论与实践负责任的 AI

开源路径促成了众多第三方项目与工具的广泛支持:

Projects and Tools

Qwen:访问与安装

在了解了 Qwen 及其关键特性后,是时候动手实践了!

访问 Qwen 模型

Qwen 模型可在多个平台获取,便于覆盖各类使用场景。

Platforms for Qwen

安装步骤与快速上手

本节将带您通过Hugging Face 使用 Qwen-7B 语言模型。我们将涵盖环境配置、登录 Hugging Face,以及运行模型。

先决条件

  • Python 3.7 或更高版本
  • pip(Python 包管理器)

步骤 1:安装所需库

首先安装必要的库:

pip install transformers torch huggingface_hub

步骤 2:登录 Hugging Face

要访问 Qwen-7B 模型,您需要登录 Hugging Face 账户。由于部分模型可能有使用限制,但您仍可访问自己或组织的私有模型。这有助于监控 API 使用并在必要时实施速率限制。

登录步骤如下:

1. 访问 Hugging Face。

2. 前往个人资料设置并创建访问令牌。

3. 在终端中运行:

huggingface-cli login

4. 按提示输入您的访问令牌。

步骤 3:创建 Python 脚本并导入包

现在,我们将创建一个 Python 文件或 Jupyter Notebook 文件,用于开始编写代码。

首先,从 transformers 库导入两个类:

  • AutoModelForCausalLM:根据您提供的模型名称自动选择合适的模型架构。
  • AutoTokenizer:为所用模型加载正确的分词器。
from transformers import AutoModelForCausalLM, AutoTokenizer

步骤 4:指定模型名称

接下来我们指定要使用的模型。“Qwen/Qwen-7B”指的是托管在 Hugging Face 模型库中的 70 亿参数版本的 Qwen 模型,您也可选择其他 Qwen 模型。

model_name = "Qwen/Qwen-7B"

步骤 5:加载分词器

然后我们需要加载分词器。

tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)

该行代码会加载与 Qwen-7B 模型关联的分词器。参数 trust_remote_code=True 是必要的,因为 Qwen 模型在加载时可能需要执行自定义代码。

步骤 6:加载模型

下一步是加载模型。

model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True)

这会加载实际的 Qwen-7B 模型。同样,我们使用 trust_remote_code=True 以允许运行与模型相关的自定义代码。

步骤 7:示例测试

加载模型后,我们可以通过给定输入来生成文本,以测试其是否正常工作。

input_text = "Once upon a time"
inputs = tokenizer(input_text, return_tensors="pt")

此处我们正在为模型准备输入:

  • 定义字符串 input_text 作为提示词。
  • 使用分词器将该文本转换为模型可理解的格式。参数 return_tensors="pt" 指定输出为 PyTorch 张量格式。

现在生成文本:

outputs = model.generate(**inputs, max_new_tokens=50)
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)

第一行代码指示模型生成文本:

  • 将分词后的 inputs 传入 generate 方法。
  • **inputs 解包分词器返回的字典。
  • max_new_tokens=50 将生成长度限制为最多 50 个新 token。
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)

此步骤将模型输出(token ID 格式)转换为可读文本:

  • outputs 选择第一条(在此例中亦是唯一一条)生成序列。
  • skip_special_tokens=True 指示解码器忽略诸如填充或序列结束等特殊 token。

最后,打印生成文本以查看结果。

print(generated_text)
Once upon a time, in a far-off kingdom, there lived a young princess named Lily. 
She was known throughout the land for her kindness and beauty. Despite living in a grand castle with everything she could ever want, Lily felt something was missing in her life. She longed for adventure and to see the world beyond the castle walls.
One day, while walking in the royal gardens, she stumbled upon a hidden door overgrown with vines. Curiosity got the better of her, and she decided to see where it led. As she pushed open the creaky door, she found herself stepping into a magical forest filled with talking animals and glowing flowers.
Little did Lily know that this discovery would be the beginning of an extraordinary journey that would change her life forever…

注意与提示

以下是一些实用注意事项与提示:

  1. Qwen-7B 模型体量较大(70 亿参数)。请确保系统内存充足,并尽可能使用 GPU 以加速处理。
  2. 如遇内存问题,可考虑使用更小的模型。
  3. trust_remote_code=True 参数对 Qwen 模型是必需的,因为其正常运行需要自定义代码。
  4. 务必在 Hugging Face 模型页面查看相关许可证与使用限制。
  5. 您已成功完成 Qwen 模型的配置与运行!欢迎尝试不同的输入文本,进一步探索模型能力。

Qwen:部署

Qwen 模型可通过阿里云机器学习平台 PAI 与弹性 AI 推理 EAS 部署。只需几次点击,即可完成 Qwen 模型的部署:

Sequence of steps for deploying a Qwen model

Qwen:示例用法

下面我们通过文本生成与问答任务的实例来了解 Qwen 的实际用法。

文本生成

Qwen 擅长根据给定提示生成连贯且符合语境的文本。示例如下:

基础文本续写

prompt = "The future of artificial intelligence is"
inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(inputs, max_new_tokens=50)
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generated_text)
The future of artificial intelligence is bright and full of potential. As technology continues to advance, AI will play an increasingly important role in various aspects of our lives. From healthcare and education to transportation and entertainment, AI will revolutionize the way we live and work. However, it's crucial to ensure that AI is developed and used responsibly, with proper ethical considerations and safeguards in place.

创意写作

prompt = "Write a short poem about the changing seasons:"
inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(inputs, max_new_tokens=100, temperature=0.7)
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generated_text)
Leaves of gold and crimson fall,
As autumn's whisper fills the air.
Winter's chill soon follows all,
Blanketing the earth with care.
Spring awakens with gentle rain,
Coaxing buds to bloom anew.
Summer's warmth returns again,
Painting skies in vibrant blue.
Nature's cycle, ever turning,
Each season brings its own delight.
In this dance, we're always learning,
Of life's beauty, day and night.

代码生成

prompt = "Write a Python function to calculate the Fibonacci sequence:"
inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(inputs, max_new_tokens=200, temperature=0.2)
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generated_text)
def fibonacci(n):
    """
    Calculate the Fibonacci sequence up to the nth term.
    
    Args:
    n (int): The number of terms in the sequence to calculate.
    
    Returns:
    list: A list containing the Fibonacci sequence up to the nth term.
    """
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    
    fib_sequence = [0, 1]
    for i in range(2, n):
        fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2])
    
    return fib_sequence
# Example usage:
print(fibonacci(10))  
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

问答

Qwen 可用于回答从事实性到开放式/分析性在内的各类问题。示例如下:

事实性问题

question = "What is the capital of France?"
inputs = tokenizer(question, return_tensors="pt")
outputs = model.generate(inputs, max_new_tokens=50)
answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"Q: {question}\nA: {answer}")
Q: What is the capital of France?
A: The capital of France is Paris. Paris is the largest city in France and serves as the country's political, economic, and cultural center. It is known for its iconic landmarks such as the Eiffel Tower, the Louvre Museum, and Notre-Dame Cathedral.

开放式问题

question = "What are the potential ethical concerns surrounding artificial intelligence?"
inputs = tokenizer(question, return_tensors="pt")
outputs = model.generate(inputs, max_new_tokens=200, temperature=0.7)
answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"Q: {question}\nA: {answer}")
Q: What are the potential ethical concerns surrounding artificial intelligence?
A: There are several potential ethical concerns surrounding artificial intelligence (AI):
1. Privacy and data protection: AI systems often require large amounts of data, raising concerns about personal information collection and use.
2. Bias and discrimination: AI algorithms can perpetuate or amplify existing biases in training data, leading to unfair treatment of certain groups.
3. Job displacement: As AI becomes more advanced, it may replace human workers in various industries, potentially leading to unemployment and economic inequality.
4. Accountability and transparency: It can be challenging to understand how AI systems make decisions, making it difficult to assign responsibility for errors or harmful outcomes.
5. Autonomous weapons: The development of AI-powered weapons raises concerns about the ethics of warfare and the potential for uncontrolled escalation.
6. Superintelligence: There are concerns about the potential development of AI systems that surpass human intelligence, potentially posing existential risks to humanity.
7. Human autonomy: As AI systems become more integrated into our lives, there are concerns about the erosion of human decision-making and free will.
8. Security risks: AI systems can be vulnerable to hacking or manipulation, potentially leading to severe consequences in critical applications.
9. Social manipulation: AI-powered systems could be used to influence human behavior on a large scale, raising concerns about democracy and free will.
10. Ethical decision-making: As AI systems are tasked with making complex decisions, there are concerns about their ability to navigate ethical dilemmas appropriately.
Addressing these concerns requires ongoing dialogue between technologists, ethicists, policymakers, and the public to ensure responsible development and deployment of AI technologies.

这些示例展示了 Qwen 如何处理多种类型的文本生成与问答任务。

您可以调节 max_new_tokens 与 temperature 等参数,以控制生成回复的长度与创造性,以适配您的具体需求。

微调 Qwen 模型

微调 Qwen 模型使您能够将其适配到特定任务,从而可能提升在您特定用例上的表现。该过程是在自定义数据集上继续训练预训练模型,使其在保留通用语言理解能力的同时,学习任务特定知识。

本节我们将演示在自定义数据集上微调 Qwen-7B 模型的过程。我们将采用高效微调技术,使大型模型的微调亦可控可行。示例中,我们将微调模型以提升其在翻译任务与事实性问答方面的表现。该过程允许模型从自定义数据集中学习,并保留其通用语言理解能力。

先决条件

开始之前,请确保已安装以下内容:

pip install datasets torch accelerate peft

步骤 1:准备数据集

首先将数据集整理为 JSON 格式。每条记录应包含 "prompt" 与 "completion" 字段。保存为 custom_dataset.json。我们将使用以下示例:

[
  {
    "prompt": "Translate to French: 'Hello, how are you?'",
    "completion": "Bonjour, comment allez-vous?"
  },
  {
    "prompt": "What is the capital of Spain?",
    "completion": "The capital of Spain is Madrid."
  }
]

步骤 2:设置微调脚本

接下来添加如下导入:

import torch
from transformers import TrainingArguments, Trainer
from datasets import load_dataset
from peft import LoraConfig, get_peft_model

步骤 3:准备数据集

我们定义一个函数来预处理数据集,并使用 Hugging Face datasets 库加载它:

def preprocess_function(examples):
    inputs = [f"{prompt}\n" for prompt in examples["prompt"]]
    targets = [f"{completion}\n" for completion in examples["completion"]]
    model_inputs = tokenizer(inputs, max_length=512, truncation=True, padding="max_length")
    labels = tokenizer(targets, max_length=512, truncation=True, padding="max_length")
    model_inputs["labels"] = labels["input_ids"]
    return model_inputs
dataset = load_dataset("json", data_files="custom_dataset.json")
tokenized_dataset = dataset["train"].train_test_split(test_size=0.1)
tokenized_dataset = tokenized_dataset.map(preprocess_function, batched=True, remove_columns=dataset["train"].column_names)

步骤 4:使用 LoRA 进行高效微调

为提升微调效率,我们将使用LoRA(低秩适配)。该技术可在更少参数下完成大型模型的微调:

lora_config = LoraConfig(
    r=8,
    lora_alpha=32,
    target_modules=["q_proj", "v_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)

步骤 5:定义训练参数

现在设置训练参数,以控制微调过程的各个方面:

training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=4,
    per_device_eval_batch_size=4,
    warmup_steps=500,
    weight_decay=0.01,
    logging_dir="./logs",
    logging_steps=10,
    evaluation_strategy="steps",
    eval_steps=500,
    save_strategy="steps",
    save_steps=1000,
    learning_rate=1e-4,
    fp16=True,
    gradient_checkpointing=True,
    gradient_accumulation_steps=4,
)

步骤 6:创建 Trainer 并开始微调

准备好数据集与训练参数后,我们就可以创建 Trainer 对象并启动微调流程:

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset["train"],
    eval_dataset=tokenized_dataset["test"],
    tokenizer=tokenizer,
)
trainer.train()

步骤 8:保存微调后的模型

微调完成后,将模型保存以便后续使用:

trainer.save_model("./fine_tuned_qwen")

在自定义数据集上微调 Qwen-7B 模型,将提升其在与训练数据相似任务上的表现。本例中,模型应在英文到法文翻译与城市首都类事实性问答方面得到改进。

使用微调后的模型

微调完成后,可用于推理:

fine_tuned_model = AutoModelForCausalLM.from_pretrained("./fine_tuned_qwen", trust_remote_code=True)
fine_tuned_tokenizer = AutoTokenizer.from_pretrained("./fine_tuned_qwen", trust_remote_code=True)
def generate_response(prompt):
    inputs = fine_tuned_tokenizer(prompt, return_tensors="pt").to(fine_tuned_model.device)
    outputs = fine_tuned_model.generate(**inputs, max_new_tokens=50)
    return fine_tuned_tokenizer.decode(outputs[0], skip_special_tokens=True)
# Example usage
prompt = "Translate to French: 'Good morning, have a nice day!'"
response = generate_response(prompt)
print(f"Prompt: {prompt}\n Response: {response}")
Prompt: Translate to French: 'Good morning, have a nice day!'
Response: Bonjour, passez une bonne journée !

高效微调的提示

以下建议有助于提升微调效果:

  • 确保自定义数据集高质量且能代表目标任务。
  • 更大的数据集通常效果更好,但即便只有数百条样本,也能对特定任务有所裨益。
  • 尝试不同的学习率、批大小与训练轮数以优化性能。
  • 定期在留出的验证集上评估模型,防止过拟合。
  • 若 GPU 显存有限,可使用梯度累积来模拟更大的批大小。
  • 使用混合精度训练,加速微调并降低显存占用。
  • 对于垂直领域任务,可在领域数据上继续预训练,然后再在任务数据集上进行微调。

在自定义数据集上微调 Qwen,能让您获得在特定任务上表现突出的专用模型,同时保留原始预训练模型的广泛知识与能力。这种方法将大型语言模型的力量用于您的独特应用与领域。

Qwen:未来展望

随着 Qwen 不断演进,我们可以期待以下令人振奋的发展:

  • 未来版本的 Qwen 模型将在语言理解、生成与多模态处理方面更进一步。
  • 持续的研究或将带来更高效的模型,以更低算力需求实现高性能。
  • 随着社区对 Qwen 的探索与实验不断深入,各行业与领域有望涌现出更多创新应用。
  • 伦理 AI 进步:Qwen 的开放属性有助于就 AI 伦理开展更广泛的审视与协作,推动更负责任与更公平的 AI 系统。

结语

通过本次对 Qwen 的探索可以看出,这些 AI 工具在可用性、强大性与多样性方面实现了重要跃升。Qwen 不仅是一组强大的 AI 模型,更代表着让先进 AI 为所有人可用且可适配的愿景。通过以开源形式提供这些工具,阿里云正推动 AI 技术的创新与发展。

Qwen AI Summary

如果您想持续了解 AI 前沿动态,推荐阅读以下文章:

FAQs

Qwen 模型有哪些不同的规模可选?

Qwen 提供多种参数规模的模型,包括 0.5B、1.5B、4B、7B、14B、32B、72B 和 110B。

Qwen 模型能处理长上下文吗?

是的,Qwen 模型支持长上下文。例如,所有规模的 Qwen 1.5 模型均支持 32K token 的上下文长度;部分模型如 Qwen2-7B-Instruct 与 Qwen2-72B-Instruct 可处理多达 128K token。

Qwen 的分词器与其他语言模型有何不同?

Qwen 采用独特的分词器,词表规模超过 15 万。由此更好地处理多种语言,并可能更高效地处理文本输入。

在商业应用中使用 Qwen 模型的许可条款是什么?

许可条款因模型规模而异。例如,Qwen-72B、Qwen-14B 与 Qwen-7B 在商业使用时需要填写表单,而 Qwen-1.8B 采用研究许可协议。用户应查看拟使用模型的具体许可。

什么是 Qwen-Agent?它可以如何使用?

Qwen-Agent 是基于 Qwen 模型构建 LLM 应用的框架。它利用模型在指令跟随、工具使用、规划与记忆方面的能力,来创建可执行各类任务的 AI 代理。

Dr Ana Rojo-Echeburúa

作者

Dr Ana Rojo-Echeburúa

Ana Rojo Echeburúa 是一位人工智能与数据专家,拥有应用数学博士学位。她热衷于将数据转化为可执行的洞见,并在带领技术团队方面拥有丰富经验。Ana 喜欢与客户密切合作,解决其业务难题并打造创新的 AI 解决方案。她以出色的问题解决能力和清晰的沟通著称,对人工智能,尤其是生成式 AI 充满热情。Ana 致力于持续学习与负责任的 AI 开发,同时专注于简化复杂问题,并以通俗易懂的方式解释技术。

主题