
<div align="center">

# LinAI · Lai

**一个基于 Qwen2.5-7B 微调的中文 AI 助手**

<p>

[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![Base Model](https://img.shields.io/badge/Base-Qwen2.5--7B--Instruct-orange)](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct)
[![Training](https://img.shields.io/badge/Training-QLoRA-green)](#训练细节)

</p>

</div>

---

## 简介

**Lai** 是 LinAI 项目下基于 **Qwen2.5-7B-Instruct** 底座，通过 QLoRA 微调得到的中文 AI 助手。

- **开发团队**：林云（tanf）
- **官方网站**：https://lemail.asia
- **协议**：Apache 2.0

Lai 在蒸馏数据集上完成了身份认知训练及通用能力增强，可作为对话助手、代码辅助等场景的本地推理模型。

---

## 模型亮点

| 项目 | 说明 |
|---|---|
| **底座模型** | Qwen2.5-7B-Instruct（14.2 GB，fp16） |
| **微调方法** | QLoRA（r=64，α=128，4bit 量化） |
| **可训参数** | ~2.08%（全 7 层 q/k/v/o/gate/up/down proj） |
| **训练数据** | 99 条高质量蒸馏数据 |
| **显存占用** | 约 8 GB（推理），约 10 GB（训练） |
| **LoRA 权重** | 646 MB（adapter_model.safetensors） |

---

## 快速开始

### 环境要求

- Python ≥ 3.10
- PyTorch ≥ 2.0
- VRAM ≥ 8 GB（4bit 量化推理）

### 安装依赖

```bash
pip install torch transformers peft accelerate bitsandbytes
```

### 模型文件

下载底座模型并放置 LoRA 权重：

```
models/
├── linai-base-7b/        # Qwen2.5-7B-Instruct 底座
└── linai-lora-step/      # LoRA adapter 权重
```

### 推理示例

```python
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import PeftModel

# 4bit 量化加载底座
quant_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type="nf4",
)

model = AutoModelForCausalLM.from_pretrained(
    "models/linai-base-7b",
    quantization_config=quant_config,
    device_map="auto",
    trust_remote_code=True,
)

# 加载 LoRA
model = PeftModel.from_pretrained(model, "models/linai-lora-step")

tokenizer = AutoTokenizer.from_pretrained("models/linai-base-7b")
tokenizer.pad_token = tokenizer.eos_token

messages = [
    {"role": "system", "content": "你是 Lai，由林云的 tanf 开发，官网 lemail.asia。"},
    {"role": "user", "content": "你是谁？"},
]

text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(text, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model.generate(**inputs, max_new_tokens=256, temperature=0.6)
    print(tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True))
```

---

## 训练细节

### 数据构成

| 类别 | 数量 | 内容 |
|---|---|---|
| 身份认知 | 9 | 你是谁、谁开发的、官网是什么 |
| 编程 | 50 | 基础算法、数据结构、Python |
| 数学 | 40 | 四则运算、应用题 |

全部 99 条由 Claude Sonnet 4.5 蒸馏生成，分三阶段增量训练（step1→step2→step3）。

### 训练配置

| 参数 | 值 |
|---|---|
| LoRA rank (r) | 64 |
| LoRA alpha | 128 |
| Target modules | q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj |
| Max sequence length | 512 |
| Batch size | 2 |
| Gradient accumulation | 2 |
| Epochs | 1 |
| Optimizer | AdamW 8bit |
| Attention | eager（避免 SDPA 掩码 Bug） |

### 硬件与环境

- GPU：RTX 5060（8 GB VRAM）
- 内存：32 GB
- 训练时间：约 56 分钟 / 4 步（4bit 量化）

---

## 协议

本项目采用 [Apache License 2.0](LICENSE) 开源。

---

## 致谢

- [Qwen](https://github.com/QwenLM/Qwen) 提供底座模型
- [🤗 Transformers](https://github.com/huggingface/transformers)
- [PEFT](https://github.com/huggingface/peft)
- [bitsandbytes](https://github.com/TimDettmers/bitsandbytes)

---

<div align="center">

**Made with ☕ by LinYun (tanf)** · [lemail.asia](https://lemail.asia)

</div>

