mirror of
https://github.com/hiyouga/LLaMA-Factory.git
synced 2026-08-17 13:35:44 +08:00
Compare commits
177 Commits
v0.9.4
...
1b47415a2f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b47415a2f | ||
|
|
9ce6b663e9 | ||
|
|
2ebe7be611 | ||
|
|
3f77101580 | ||
|
|
19e9fe3ced | ||
|
|
d0eaa10b0c | ||
|
|
a17afe5e1b | ||
|
|
ef2d8f9da6 | ||
|
|
5f653cb96a | ||
|
|
d1049d650a | ||
|
|
8489928769 | ||
|
|
b61140db3e | ||
|
|
ea31c43d80 | ||
|
|
76a0391ddd | ||
|
|
445163ab5e | ||
|
|
d58ec6a0bc | ||
|
|
5987a8dd68 | ||
|
|
a61cfa692a | ||
|
|
7a83d28ce3 | ||
|
|
c8a082e0e3 | ||
|
|
a48af5cc69 | ||
|
|
c383c0d067 | ||
|
|
50ff45176a | ||
|
|
9c0b4b3835 | ||
|
|
b7615dbdc9 | ||
|
|
666ee0ca78 | ||
|
|
aca54c7f17 | ||
|
|
48aa9ef084 | ||
|
|
c928c1cb21 | ||
|
|
c35b7d7f55 | ||
|
|
802bcfe969 | ||
|
|
8792f06161 | ||
|
|
8669a22e9c | ||
|
|
897a44386c | ||
|
|
7a1e9630f2 | ||
|
|
cabe59a343 | ||
|
|
9ca4026efe | ||
|
|
0b7aaf8f6a | ||
|
|
8a4f6a3da5 | ||
|
|
409e8a477f | ||
|
|
053d43c0ac | ||
|
|
a98a1ef101 | ||
|
|
8ef7335b6a | ||
|
|
7af909522a | ||
|
|
e016d2480e | ||
|
|
7d719182c9 | ||
|
|
01398eb18d | ||
|
|
8e68764b65 | ||
|
|
16ff5a23cb | ||
|
|
bdcb92d035 | ||
|
|
7e20db5735 | ||
|
|
2322bf1cc2 | ||
|
|
368c48968f | ||
|
|
8b5ea65770 | ||
|
|
40e786d016 | ||
|
|
6b9df75ab9 | ||
|
|
ca50f22c38 | ||
|
|
53e77a9bfa | ||
|
|
55bd4944b6 | ||
|
|
7e09152275 | ||
|
|
1e503a982d | ||
|
|
8752280dd7 | ||
|
|
468723c5d9 | ||
|
|
887ee2b121 | ||
|
|
6b08b948c9 | ||
|
|
f7f3bfcbd7 | ||
|
|
3475198d1e | ||
|
|
50945ef850 | ||
|
|
2f0bef207a | ||
|
|
2092abc217 | ||
|
|
99464b3d03 | ||
|
|
9a0cfdccfa | ||
|
|
c8890c32db | ||
|
|
79c8332e4c | ||
|
|
e0bc3c1971 | ||
|
|
ecca167eb4 | ||
|
|
28a6ea1cdc | ||
|
|
f5d739b132 | ||
|
|
c4bbac49b2 | ||
|
|
c5aecaf31d | ||
|
|
436d26bc28 | ||
|
|
c109c061e5 | ||
|
|
fa09c01c36 | ||
|
|
eae6f0b541 | ||
|
|
acac63ef35 | ||
|
|
e5e8546493 | ||
|
|
97433c53b6 | ||
|
|
b5afabe3d2 | ||
|
|
df2e6edb7e | ||
|
|
d02fcd3588 | ||
|
|
c340aa2a33 | ||
|
|
1e536733c6 | ||
|
|
97d479fa92 | ||
|
|
ffbff33af3 | ||
|
|
833f6027b1 | ||
|
|
d91d8af89e | ||
|
|
e67ab9e2f2 | ||
|
|
2c4f121817 | ||
|
|
487f8b8191 | ||
|
|
78cad1e332 | ||
|
|
70653026f5 | ||
|
|
246192abd2 | ||
|
|
0258dc14d0 | ||
|
|
3045adf0ba | ||
|
|
a3d44e3152 | ||
|
|
edeb953bc7 | ||
|
|
d045794387 | ||
|
|
9501c3308a | ||
|
|
0ee1c42c2b | ||
|
|
3061f48d55 | ||
|
|
2d9bd2aa14 | ||
|
|
c0245c43fc | ||
|
|
eb976d75a2 | ||
|
|
b5cb7cb0e6 | ||
|
|
0779846513 | ||
|
|
45d335c709 | ||
|
|
816480012f | ||
|
|
d3bf882e87 | ||
|
|
589da21d32 | ||
|
|
122cd46084 | ||
|
|
2b8b871475 | ||
|
|
aab9b400bb | ||
|
|
50599c719b | ||
|
|
a0f3ad0cee | ||
|
|
f80e15dbb4 | ||
|
|
991267fd3b | ||
|
|
5c52afa30d | ||
|
|
675ce8cc7f | ||
|
|
ab073f4c13 | ||
|
|
184304b5b4 | ||
|
|
d3ebd5678d | ||
|
|
1d5e8ebcd0 | ||
|
|
ea644d04ec | ||
|
|
92fa3df4c4 | ||
|
|
8bedfafa4e | ||
|
|
1a02717fa8 | ||
|
|
e7cb145f5d | ||
|
|
b53d7037c2 | ||
|
|
bf04ca6af8 | ||
|
|
762b480131 | ||
|
|
9640f79ae5 | ||
|
|
7ef19eea00 | ||
|
|
f9f11dcb97 | ||
|
|
641bfdd482 | ||
|
|
e70651ac58 | ||
|
|
db2f794f7b | ||
|
|
44eadbda1c | ||
|
|
9829ae0a77 | ||
|
|
958b9c3468 | ||
|
|
4d3621e3d3 | ||
|
|
a296723697 | ||
|
|
15b87f3125 | ||
|
|
9f73a6eb23 | ||
|
|
b2effbd77c | ||
|
|
d7d734d54c | ||
|
|
8abb8fb533 | ||
|
|
766d5ae6ad | ||
|
|
5cccaeec82 | ||
|
|
5fb5d7ebd3 | ||
|
|
03a70ba8dd | ||
|
|
5cfd804b59 | ||
|
|
4c1eb922e2 | ||
|
|
958fb523a2 | ||
|
|
b4e051bea4 | ||
|
|
d43e1007e8 | ||
|
|
f89d9367e5 | ||
|
|
d22de0d4bf | ||
|
|
ea0b4e2466 | ||
|
|
e944dc442c | ||
|
|
68119e5522 | ||
|
|
f60a6e3d01 | ||
|
|
81b8a50aa5 | ||
|
|
8600530002 | ||
|
|
9ae62c6fc0 | ||
|
|
0087bc253b | ||
|
|
355d5c5e5a | ||
|
|
6fe6bd290b |
105
.ai/CLAUDE.md
Normal file
105
.ai/CLAUDE.md
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Code style (auto-fix)
|
||||||
|
make style
|
||||||
|
|
||||||
|
# Code quality check (no modifications)
|
||||||
|
make quality
|
||||||
|
|
||||||
|
# Run all tests
|
||||||
|
make test
|
||||||
|
|
||||||
|
# Run a single test file
|
||||||
|
WANDB_DISABLED=true pytest -vv --import-mode=importlib tests/path/to/test_file.py
|
||||||
|
|
||||||
|
# Run tests matching a pattern
|
||||||
|
WANDB_DISABLED=true pytest -vv --import-mode=importlib tests/ -k "test_name"
|
||||||
|
|
||||||
|
# License header check
|
||||||
|
make license
|
||||||
|
|
||||||
|
# Build package
|
||||||
|
make build
|
||||||
|
```
|
||||||
|
|
||||||
|
The project uses `uv` as the preferred package manager. Commands automatically use `uv run` / `uvx` if `uv` is available.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
LlamaFactory has two parallel architectures controlled by the `USE_V1` environment variable:
|
||||||
|
|
||||||
|
- **v0 (default):** `api, webui > chat, eval, train > data, model > hparams > extras`
|
||||||
|
- **v1 (experimental, `USE_V1=1`):** `trainers > core > accelerator, plugins, config > utils`
|
||||||
|
|
||||||
|
Most active development happens in v0. The v1 architecture lives in `src/llamafactory/v1/`.
|
||||||
|
|
||||||
|
### Entry Points
|
||||||
|
|
||||||
|
CLI entry point is `llamafactory-cli` / `lmf` → `src/llamafactory/cli.py:main()`, which dispatches to `launcher.py` based on `USE_V1`.
|
||||||
|
|
||||||
|
Available subcommands: `train`, `chat`, `api`, `export`, `webchat`, `webui`, `env`, `version`, `help`.
|
||||||
|
|
||||||
|
### Training Flow (v0)
|
||||||
|
|
||||||
|
```
|
||||||
|
run_exp() [tuner.py]
|
||||||
|
→ read_args() → parse YAML/JSON config
|
||||||
|
→ get_train_args() → produces typed argument dataclasses
|
||||||
|
→ routes to: run_sft / run_dpo / run_ppo / run_rm / run_pt / run_kto
|
||||||
|
→ optional: export_model()
|
||||||
|
```
|
||||||
|
|
||||||
|
Training is invoked with a YAML config: `llamafactory-cli train examples/train_lora/llama3_lora_sft.yaml`
|
||||||
|
|
||||||
|
### Configuration System
|
||||||
|
|
||||||
|
All training parameters are YAML/JSON config files. Argument parsing in `src/llamafactory/hparams/parser.py` produces four typed dataclasses:
|
||||||
|
- `ModelArguments` — model/tokenizer selection, quantization
|
||||||
|
- `DataArguments` — datasets, templates, preprocessing
|
||||||
|
- `FinetuningArguments` — LoRA rank/target, training method (sft/dpo/ppo/rm/pt/kto)
|
||||||
|
- `TrainingArguments` — extends HuggingFace's `TrainingArguments`
|
||||||
|
|
||||||
|
### Key Modules
|
||||||
|
|
||||||
|
| Module | Purpose |
|
||||||
|
|--------|---------|
|
||||||
|
| `src/llamafactory/model/loader.py` | Loads model + tokenizer; applies quantization, LoRA, patches |
|
||||||
|
| `src/llamafactory/model/patcher.py` | Model-specific compatibility patches |
|
||||||
|
| `src/llamafactory/data/template.py` | Prompt templates; `TEMPLATES` dict maps model family → format |
|
||||||
|
| `src/llamafactory/data/mm_plugin.py` | Multi-modal (image/video/audio) data handling |
|
||||||
|
| `src/llamafactory/data/processor/` | Per-stage data processors (supervised, pairwise, pretrain, etc.) |
|
||||||
|
| `src/llamafactory/train/sft/` | SFT trainer; other stages follow same structure |
|
||||||
|
| `src/llamafactory/chat/` | Inference engines: `hf_engine`, `vllm_engine`, `sglang_engine`, `kt_engine` |
|
||||||
|
| `src/llamafactory/extras/constants.py` | Enums and constants used across the project |
|
||||||
|
|
||||||
|
### Adding Support for a New Model
|
||||||
|
|
||||||
|
1. Add a prompt template to `src/llamafactory/data/template.py` in the `TEMPLATES` dict
|
||||||
|
2. Add any necessary model patches in `src/llamafactory/model/patcher.py`
|
||||||
|
3. Add multi-modal support in `src/llamafactory/data/mm_plugin.py` if needed
|
||||||
|
|
||||||
|
### Distributed Training
|
||||||
|
|
||||||
|
Multi-GPU automatically uses `torchrun`. Additional backends:
|
||||||
|
- **Ray:** Optional Ray cluster support
|
||||||
|
- **HyperParallel FSDP2:** `src/llamafactory/train/hyper_parallel/`
|
||||||
|
- **Megatron-core:** `src/llamafactory/train/mca/`
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
|
||||||
|
- `tests/` — v0 tests; `tests_v1/` — v1 tests
|
||||||
|
- Most training tests require GPU hardware
|
||||||
|
- pytest markers: `@pytest.mark.slow`, `@pytest.mark.runs_on(['cuda'])`
|
||||||
|
- Always set `WANDB_DISABLED=true` when running tests
|
||||||
|
|
||||||
|
### Code Style
|
||||||
|
|
||||||
|
- Ruff for linting and formatting (line length 119, Google-style docstrings)
|
||||||
|
- Python 3.11+ syntax
|
||||||
|
- Double quotes for strings
|
||||||
|
- All new files must include Apache 2.0 license header (checked by `make license`)
|
||||||
366
.claude/skills/llamafactory-sft/SKILL.md
Normal file
366
.claude/skills/llamafactory-sft/SKILL.md
Normal file
@@ -0,0 +1,366 @@
|
|||||||
|
---
|
||||||
|
name: llamafactory-sft
|
||||||
|
description: One-stop guided LlamaFactory SFT workflow — data prep, model prep, fine-tuning config/method selection, background training, loss visualization, effect validation and model export. TRIGGER when the user wants to fine-tune / SFT a model with LlamaFactory, run a full LlamaFactory training pipeline, or asks to "微调" / "用 llamafactory 做 sft" / "train a LoRA". SKIP for general questions about the codebase or non-training tasks.
|
||||||
|
---
|
||||||
|
|
||||||
|
# LlamaFactory One-Stop SFT Workflow
|
||||||
|
|
||||||
|
Guide the user through a complete LlamaFactory SFT run: **data prep → model prep → fine-tuning config → background training → loss visualization → (optional) effect validation → (optional) model export**.
|
||||||
|
|
||||||
|
The core of this skill is **interactive guidance**: at every key decision point use `AskUserQuestion` and never make irreversible assumptions on the user's behalf.
|
||||||
|
|
||||||
|
The working directory defaults to the current directory (`./`, the repo root). Run all commands via `llamafactory-cli` (or `lmf`).
|
||||||
|
|
||||||
|
> **Artifacts directory (keep generated files out of model / checkpoint folders).** All skill-generated **yaml configs** (train / inference / export) and **run logs** (download / train / export) MUST be written to a single dedicated directory, NOT inside `./models/` (downloaded weights) or the training `output_dir` (saved checkpoints). Use `./llamafactory_runs/<run_id>/` where `<run_id>` is `<model>_<method>_YYYYMMDD_HHMM` (e.g. `./llamafactory_runs/qwen3-4b_lora_20260615_0807/`). Create it once at the start of the CLI route and place every config + log file there. The training `output_dir` (the actual model checkpoints) stays separate under `saves/...`, and downloaded base models stay under `./models/...`. This keeps configs/logs, checkpoints, and weights cleanly separated.
|
||||||
|
|
||||||
|
> Language: communicate with the user in whatever language they request, or otherwise follow the active language setting/preference. Do not hardcode a fixed conversation language.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Progress board (show only when progress changes)
|
||||||
|
|
||||||
|
This workflow has many stages, so the user must always be able to see **where we are**: which steps are done, which is in progress, and which remain.
|
||||||
|
|
||||||
|
**Rule:** Render the **progress board** only when the board state changes, or when the user explicitly asks for status/progress. A board state changes when any step marker changes (`[ ]` / `[~]` / `[x]` / `[-]`) or when Stage 0 changes the branch shape (e.g. skipped validation/export for "SFT only"). Do **not** repeat the board on routine status updates, repeated confirmations, log polling, or consecutive messages within the same stage if the markers are unchanged.
|
||||||
|
|
||||||
|
Use these markers:
|
||||||
|
- `[x]` done
|
||||||
|
- `[~]` in progress (the step you are working on right now)
|
||||||
|
- `[ ]` not started
|
||||||
|
- `[-]` skipped (e.g. validation/export when the user chose "SFT only", or download when the model is already local)
|
||||||
|
|
||||||
|
Render it as a compact checklist inside a fenced code block. **Always wrap the entire progress board in triple backticks** (use `text` as the info string, or no info string) so Markdown preserves every line break and marker exactly. **The board's language must follow the active conversation language / the user's request — it is NOT required to be Chinese.** The example below is in Chinese only for illustration; render the title and step labels in whatever language the user is using (e.g. English: a "Progress" board with "0. Confirm overall flow", "1. Data preparation", ...):
|
||||||
|
|
||||||
|
```
|
||||||
|
进度看板
|
||||||
|
[x] 0. 确认整体流程(范围 / 执行方式)
|
||||||
|
[x] 1. 数据准备
|
||||||
|
[~] 2. 模型准备
|
||||||
|
[ ] 3. 微调配置
|
||||||
|
[ ] 4. SFT 训练
|
||||||
|
[ ] 5. 效果验证
|
||||||
|
[ ] 6. 模型导出
|
||||||
|
```
|
||||||
|
|
||||||
|
Guidelines:
|
||||||
|
- The step list above is the canonical set. Loss visualization is part of **SFT 训练** (it happens automatically once training finishes) — you know to handle it, but do NOT show it as a separate line on the board.
|
||||||
|
- Mark steps `[-]` instead of dropping them when they don't apply to the chosen flow (e.g. "SFT only" skips 5 & 6; WebUI route collapses 3–6 into the UI).
|
||||||
|
- After Stage 0, adapt the board to the chosen branch (mark skipped steps `[-]`) and keep that shape for the rest of the run.
|
||||||
|
- Do **not** render the board as plain paragraph text or as Markdown task-list checkboxes (`- [x] ...`); both can change the intended layout or marker semantics.
|
||||||
|
- Keep it terse — one line per step. When the board is shown, put it at the **top** of your message, then continue with the actual content / question below it.
|
||||||
|
- Update markers as soon as a step's status changes; show the updated board once at that transition, and never show a stale board.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 0: Confirm the overall flow
|
||||||
|
|
||||||
|
Before doing anything, use a **single `AskUserQuestion` call that asks all three of the most important branches together** (one question object each, in the same call) so the user can settle the whole shape of the run in one step:
|
||||||
|
|
||||||
|
1. **Flow scope**:
|
||||||
|
- SFT only (data prep + model prep + fine-tuning)
|
||||||
|
- Full flow (also includes effect validation + model export)
|
||||||
|
|
||||||
|
2. **Execution mode**:
|
||||||
|
- Run everything via CLI commands
|
||||||
|
- Launch a **WebUI** for the SFT / validation / export parts and let the user operate it
|
||||||
|
|
||||||
|
3. **Fine-tuning type** — which SFT fine-tuning type to use, so you can match the corresponding official example yaml directory:
|
||||||
|
- **LoRA** → base config from `examples/train_lora/` (recommended default)
|
||||||
|
- **Full** (full-parameter) → base config from `examples/train_full/`
|
||||||
|
- **QLoRA** (quantized LoRA) → base config from `examples/train_qlora/`
|
||||||
|
|
||||||
|
Notes on the fine-tuning-type answer:
|
||||||
|
- The type only matters for the **all-CLI** route. If the user picked **WebUI** in question 2, **ignore their fine-tuning-type answer** (the type is selected inside the UI) — it does no harm to have asked.
|
||||||
|
- For the **all-CLI** route, record the chosen type and use it (together with the model family resolved in Stage 2) to pick the base example yaml in Stage 3.
|
||||||
|
|
||||||
|
Record the user's choices and branch the later stages accordingly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 1: Data preparation
|
||||||
|
|
||||||
|
Use `AskUserQuestion` to ask about the data source:
|
||||||
|
|
||||||
|
- **Use LlamaFactory built-in data**: list selectable datasets from `data/dataset_info.json` (e.g. `identity`, `alpaca_zh_demo`, `alpaca_en_demo`, ...). Allow multi-select and join into `dataset: a,b,c`.
|
||||||
|
- **Use custom data**: ask for the data file path(s) (multiple allowed).
|
||||||
|
|
||||||
|
### Custom data validation & onboarding
|
||||||
|
|
||||||
|
For each custom data file:
|
||||||
|
|
||||||
|
1. **Read and validate the format.** LlamaFactory supports `alpaca` and `sharegpt` formats; file types may be json/jsonl/csv/parquet/arrow.
|
||||||
|
- **Alpaca format** key fields: `instruction` (required), `input` (optional), `output` (required), `system`/`history` (optional).
|
||||||
|
- **ShareGPT format** key fields: a `conversations` list whose elements contain `from` (human/gpt) and `value`; multimodal data adds `images`/`videos`/`audios`.
|
||||||
|
- Full field definitions are in `data/README.md` / `data/README_zh.md`; read them when needed.
|
||||||
|
2. **If it does not meet the requirements, fix it**: with the user's consent, convert the data into a compliant format (write a NEW file, never destroy the user's original data in place).
|
||||||
|
3. **Copy it into the `data/` directory.**
|
||||||
|
4. **Update `data/dataset_info.json`**: add a dataset description entry. Minimal form:
|
||||||
|
```json
|
||||||
|
"my_dataset": { "file_name": "my_dataset.json" }
|
||||||
|
```
|
||||||
|
For sharegpt or custom column names, also add `formatting` / `columns` / `tags`.
|
||||||
|
When editing this JSON, keep it valid (use Edit for precise insertion; verify braces/commas).
|
||||||
|
|
||||||
|
### identity.json and other templated datasets
|
||||||
|
|
||||||
|
If the user picks `identity.json` (contains template variables like `{{name}}`, `{{author}}`), use `AskUserQuestion` to ask whether to do a global replacement. If yes:
|
||||||
|
- **Use `AskUserQuestion` to collect the concrete replacement values for the `{{name}}` and `{{author}}` variables** (one question per variable, e.g. "模型名 {{name}}" and "作者/机构 {{author}}"), plus any other template variables the file contains. Do not assume or hardcode these values — always ask the user.
|
||||||
|
- **Recommend copying first, then replacing** (e.g. `data/identity_custom.json`) to avoid polluting the repo's built-in file, and register the new name in `dataset_info.json`.
|
||||||
|
- Use Edit with `replace_all` to perform the replacement.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 2: Model preparation
|
||||||
|
|
||||||
|
Use `AskUserQuestion` to ask for the model choice, and **offer a default recommendation** (e.g. `Qwen/Qwen3-4B-Instruct-2507`, matching `examples/train_lora/qwen3_lora_sft.yaml`).
|
||||||
|
|
||||||
|
Once the model is decided:
|
||||||
|
1. **Verify the model type against LlamaFactory's own model list, and use it to pick the matching default yaml.** Before downloading or configuring anything, look up the chosen model in LlamaFactory's built-in registry rather than guessing:
|
||||||
|
- `SUPPORTED_MODELS` and `DEFAULT_TEMPLATE` live in `src/llamafactory/extras/constants.py` (registered via `register_model_group(...)`, each group sharing one `template=`). This is the authoritative list of which models LlamaFactory supports and which template each uses.
|
||||||
|
- Match the user's model (by HF/ModelScope id or model name) to an entry there to learn its **model family / type and default `template`** (e.g. a Qwen3 model → `qwen3` / `qwen3_nothink`). Cross-check `src/llamafactory/data/template.py` (the `TEMPLATES` dict) if needed.
|
||||||
|
- **Use the resolved family/template — together with the fine-tuning type chosen in Stage 0 (LoRA → `examples/train_lora/`, Full → `examples/train_full/`, QLoRA → `examples/train_qlora/`) — to select the closest official example yaml** (and the matching `examples/inference/`, `examples/merge_lora/`) as the base config for Stage 3 — e.g. a Qwen3 model with LoRA → `examples/train_lora/qwen3_lora_sft.yaml`. If there is no exact example for that family/type, pick the nearest supported one and note that you adapted it.
|
||||||
|
- **If the model is NOT in the supported list** (no entry / no matching template), clearly tell the user it is unsupported, so they can switch to a supported model or define a custom template — do not silently proceed.
|
||||||
|
2. **Check whether it already exists locally** (HF cache `~/.cache/huggingface/hub`, or a user-specified local path).
|
||||||
|
- **Verify completeness, not just existence — beware empty shells.** A cached directory can exist while being only a few KB (an empty shell where the real download never finished). After finding a local copy, verify it: total size is in the expected GB range, all `*.safetensors` shards referenced by `model.safetensors.index.json` are present, and there are no `*.incomplete` files. Only treat the model as available if it passes; otherwise treat it as NOT downloaded and proceed to download.
|
||||||
|
3. **If not present locally**: first use `AskUserQuestion` to confirm the **download source**:
|
||||||
|
- **Hugging Face Hub**
|
||||||
|
- **ModelScope** (often faster in mainland China)
|
||||||
|
- **Let the agent decide** (pick automatically based on network reachability / region)
|
||||||
|
|
||||||
|
Then **start a download task concurrently** via `Agent` / Bash with `run_in_background`:
|
||||||
|
```bash
|
||||||
|
# Hugging Face (modern CLI; `huggingface-cli` is deprecated — use `hf download`)
|
||||||
|
# Enable Xet high-performance transfer for much faster downloads:
|
||||||
|
HF_XET_HIGH_PERFORMANCE=1 hf download <model_id> --local-dir <path>
|
||||||
|
# ModelScope (set USE_MODELSCOPE_HUB=1 to also let LlamaFactory auto-download at train time)
|
||||||
|
modelscope download --model <model_id> --local_dir <path>
|
||||||
|
```
|
||||||
|
Notes:
|
||||||
|
- `huggingface-cli download` is **deprecated** in recent `huggingface_hub` versions and may just print help text — always use `hf download`.
|
||||||
|
- The old `HF_HUB_ENABLE_HF_TRANSFER=1` is **deprecated** too; use `HF_XET_HIGH_PERFORMANCE=1` instead.
|
||||||
|
- If a download source is slow (e.g. ModelScope < ~1 MB/s), consider switching to the other source rather than waiting hours. In practice HF + Xet is often dramatically faster.
|
||||||
|
|
||||||
|
You may instead rely on auto-download at train time (set `USE_MODELSCOPE_HUB=1` for ModelScope).
|
||||||
|
Keep advancing the config work while it downloads, and report download progress to the user periodically (interval ≤ 100 seconds).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 2.5: GPU selection (detect free GPU(s) once before running)
|
||||||
|
|
||||||
|
**Before the first command that uses the GPU** (SFT training, and later validation / export), **detect GPU status once, pick the device(s) to use, and reuse that exact choice** for SFT, validation, and export. Never assume a GPU is free — other jobs may already be using the machine. **Detect only once here** — do NOT re-detect before every run; the index/indices chosen now are reused for the whole workflow.
|
||||||
|
|
||||||
|
1. **Detect GPUs and their load.** Try AMD/ROCm first, then NVIDIA. Wrap the call in `timeout` so a live-refreshing monitor can never hang the agent (plain `amd-smi` without a subcommand only prints help and lacks the `VRAM_USAGE` / `GFX%` snapshot, so keep the `monitor` subcommand for the one-shot table):
|
||||||
|
```bash
|
||||||
|
timeout 10 amd-smi monitor 2>/dev/null || rocm-smi 2>/dev/null || nvidia-smi
|
||||||
|
```
|
||||||
|
Read each GPU's **VRAM usage** and **utilization**. Treat a GPU as **free** when its VRAM usage is near-empty (e.g. ≲ 1 GB) and utilization is low (e.g. ≲ a few %). Also list any running training/inference processes if helpful (e.g. `pgrep -af "llamafactory-cli"`).
|
||||||
|
2. **Decide which device(s) to use:**
|
||||||
|
- **No free GPU:** do NOT silently queue onto a busy card — tell the user which GPUs are busy (and roughly by how much VRAM / what is running) and use `AskUserQuestion` to let them choose: wait for one to free up, share a partially-used GPU anyway, or specify a particular index.
|
||||||
|
- **Exactly one free GPU:** use it (single-card).
|
||||||
|
- **Multiple free GPUs:** use `AskUserQuestion` to ask the user whether to run **single-card** or **multi-card** (list the free indices). If the user picks multi-card, use the selected free indices together.
|
||||||
|
3. **Record the chosen index/indices and reuse them for every GPU command** (training, validation, export) by exporting the platform's visibility env var:
|
||||||
|
- **AMD/ROCm:** `HIP_VISIBLE_DEVICES=<idx>` (multi-card: comma-separated, e.g. `HIP_VISIBLE_DEVICES=0,1`)
|
||||||
|
- **NVIDIA/CUDA:** `CUDA_VISIBLE_DEVICES=<idx>` (multi-card: comma-separated)
|
||||||
|
|
||||||
|
Caveat: the visibility-env index follows the smi enumeration, and the selected device becomes index 0 *inside* the process. The mapping between `HIP_VISIBLE_DEVICES` and the `amd-smi` physical order may not be 1:1 — after launching, confirm the **intended** card's VRAM actually rises in `amd-smi` (and not some other card) before trusting it.
|
||||||
|
|
||||||
|
Tell the user **which GPU(s) you selected and why** (free vs busy, single vs multi), and surface it in the relevant status updates.
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
- **Progress board:** GPU selection is part of **模型准备** prep work — handle it before the first run, but do NOT add a separate board line for it.
|
||||||
|
- **WebUI route:** you don't drive the runs yourself, but still detect and **tell the user which GPU is free** so they can set it in the UI / launch env.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 3A: WebUI route (user chose WebUI)
|
||||||
|
|
||||||
|
If the user chose WebUI in Stage 0:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
llamafactory-cli webui
|
||||||
|
```
|
||||||
|
|
||||||
|
- Launch in the background, redirecting logs to a log file.
|
||||||
|
- Read the actual listening **port** from the log (default 7860) and tell the user.
|
||||||
|
- If on a remote SSH environment, explain port forwarding:
|
||||||
|
```bash
|
||||||
|
ssh -L 7860:localhost:7860 user@remote_host
|
||||||
|
```
|
||||||
|
then open `http://localhost:7860` in the local browser.
|
||||||
|
- Tell the user that subsequent SFT / validation / export are done in the UI.
|
||||||
|
- **After the UI is up, print a "建议在 WebUI 中填写的配置 / Suggested WebUI settings" table** that maps the choices already made in earlier stages onto the fields the user will fill in the WebUI, so they don't have to remember them. Derive the values from what was resolved earlier — do NOT re-ask. Include at least:
|
||||||
|
|
||||||
|
| WebUI 字段 | 建议值 | 来源 |
|
||||||
|
|-----------|--------|------|
|
||||||
|
| Model path (模型路径) | `<resolved local model path or HF/MS id>` | Stage 2 模型准备 |
|
||||||
|
| Template (对话模板) | `<resolved template>` | Stage 2 注册表解析(与训练一致) |
|
||||||
|
| Dataset (数据集) | `<dataset a,b,c>` | Stage 1 数据准备 |
|
||||||
|
| Finetuning method (微调方法) | `<lora / full / qlora>` | Stage 0 微调类型 |
|
||||||
|
|
||||||
|
Add any other already-known values that map to UI fields (e.g. dataset dir if custom data was onboarded). Make clear these are **suggestions to enter in the UI** (LlamaFactory's WebUI does not auto-load them), and that the user can still adjust everything in the interface. If something was not resolved yet (e.g. the model path because the user deferred to train-time auto-download), say so instead of inventing a value.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 3B: CLI route (user chose all-CLI)
|
||||||
|
|
||||||
|
If the user chose all-CLI:
|
||||||
|
|
||||||
|
1. Using the official example that matches **both the chosen model family AND the fine-tuning type selected in Stage 0** (LoRA → `examples/train_lora/`, Full → `examples/train_full/`, QLoRA → `examples/train_qlora/`; e.g. a Qwen3 + LoRA run → `examples/train_lora/qwen3_lora_sft.yaml`) as a template, **match the default yaml to the chosen model**. **Prefer the official example's default parameters** — treat the example yaml as the source of truth and change as little as possible. Any field may still be changed when the user's needs or data selection call for it (including `template`), but **every change must be tracked and justified** (see step 3).
|
||||||
|
- If the repo has no ready-made config for that model, check whether it is supported (template list). If unsupported, report back to the user.
|
||||||
|
2. **Print the key parameters to the user for confirmation** as a table: `model_name_or_path`, `stage: sft`, `finetuning_type` (lora/full/qlora), `lora_rank`/`lora_target`, `dataset`, `template`, `cutoff_len`, `output_dir`, `per_device_train_batch_size`, `gradient_accumulation_steps`, `learning_rate`, `num_train_epochs`, `bf16`, etc.
|
||||||
|
3. **If you changed ANY value away from the official example's default**, then *after* the full parameter table, also show a **separate "差异 / Diff vs. default" table** listing only the changed fields, in the form `| parameter | default value | new value | reason |`. The reason must state *why* it changed — e.g. user-specified, required adaptation to the chosen model/dataset, or another concrete cause. This makes every deviation explicit and reviewable. If nothing was changed from the defaults, say so explicitly and omit the diff table.
|
||||||
|
4. Use `AskUserQuestion` to ask whether the fine-tuning **method/parameters** need adjusting (finetuning_type, lora_rank, learning rate, number of epochs, etc.), and modify as needed. When you do adjust, update the diff table accordingly.
|
||||||
|
|
||||||
|
> **Small-dataset hyperparameter reminder.** For very small datasets (e.g. `identity` with ~91 rows), the example defaults can produce too few steps: total_steps ≈ ceil(num_rows / (batch_size × grad_accum)) × epochs. If total_steps is tiny (single digits) or `logging_steps` ≥ total_steps, you will get too few loss points to plot a curve, and the model may underfit. Conversely, cranking epochs very high on a single tiny dataset causes **overfitting / catastrophic forgetting** (the model memorizes identity but its general language ability degrades — garbled or wrong-language output). Recommended mitigation: mix in a general dataset (e.g. `identity_custom,alpaca_zh_demo,alpaca_en_demo`), keep epochs moderate, and set `logging_steps` small enough to capture several points. Surface this trade-off to the user when relevant.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 4: Generate yaml and run training
|
||||||
|
|
||||||
|
1. **Generate the final yaml** into the **artifacts directory** (`./llamafactory_runs/<run_id>/`, see the top-of-file convention), NOT into the checkpoint or model folders. Use a **distinguishing suffix** so multiple runs do not collide — combine the **model name + fine-tuning method + date/time stamp**, e.g. `llamafactory_runs/<run_id>/sft.yaml` where `<run_id>` = `<model>_<method>_YYYYMMDD_HHMM` (build the stamp with `date +%Y%m%d_%H%M`). The yaml's `output_dir` (the actual checkpoints) is a separate location under `saves/<model>/<method>/sft_YYYYMMDD_HHMM`. Show the yaml to the user for **final confirmation**. Make sure `plot_loss: true` so loss can be plotted later.
|
||||||
|
2. After confirmation, **run SFT in the background on the GPU(s) chosen in Stage 2.5**, writing the log into the same artifacts directory:
|
||||||
|
```bash
|
||||||
|
TS=$(date +%Y%m%d_%H%M)
|
||||||
|
RUN_ID="<model>_<method>_${TS}"
|
||||||
|
RUN_DIR="llamafactory_runs/${RUN_ID}"
|
||||||
|
mkdir -p "${RUN_DIR}"
|
||||||
|
# Prefix with the selected GPU's visibility env var (HIP_VISIBLE_DEVICES for AMD, CUDA_VISIBLE_DEVICES for NVIDIA):
|
||||||
|
HIP_VISIBLE_DEVICES=<idx> nohup llamafactory-cli train "${RUN_DIR}/sft.yaml" > "${RUN_DIR}/train.log" 2>&1 &
|
||||||
|
```
|
||||||
|
Use Bash with `run_in_background`, or `nohup ... &`.
|
||||||
|
- **Beware the "fake completion" notification.** When you launch training with `nohup ... &` (or a backgrounded wrapper), the wrapper shell exits immediately and the harness may emit a `<task-notification> ... completed (exit code 0)` event — but the **real training process is still running** (it was detached). Do NOT treat that notification as "training finished". Training is only truly done when you confirm it via the actual process/log: `pgrep -f "llamafactory-cli train"` shows no process AND the log contains `Training completed` / a `train_runtime` line / the final `train metrics`. Until then, keep polling.
|
||||||
|
3. **Periodically check task status and report to the user** (interval ≤ 100 seconds): tail the log file, check the process is alive (and optionally `amd-smi` / `nvidia-smi`). **Each status report must include BOTH the current run state AND the current loss.**
|
||||||
|
- Progress (`current step / total steps`) comes from the tqdm progress-bar lines, which use `\r`; convert `\r`→`\n` first, e.g. `tr '\r' '\n' < "${RUN_DIR}/train.log" | grep -oE "[0-9]+/[0-9]+ \[[^]]*\]" | tail -1` (reference the log path directly — a literal `<log>` placeholder would be parsed by bash as a redirection operator and error out).
|
||||||
|
- Loss is logged as dict lines like `{'loss': '5.227', 'grad_norm': '4.634', 'learning_rate': '9.924e-05', 'epoch': '5'}` (emitted every `logging_steps`). Extract the latest with e.g. `grep -aoE "\{'loss':[^}]*\}" "${RUN_DIR}/train.log" | tail -1`, and report the latest `loss` value (optionally with `epoch`) to the user alongside the step progress.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 5: Loss visualization
|
||||||
|
|
||||||
|
After training finishes:
|
||||||
|
- `output_dir` will contain `training_loss.png` (because `plot_loss: true`); **just tell the user the image path** — do NOT render the loss curve on the command line.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 6: Effect validation (optional, if user chose full flow)
|
||||||
|
|
||||||
|
Load the fine-tuned checkpoint for inference validation.
|
||||||
|
|
||||||
|
**Up front — before asking the user for test questions — tell them about interactive self-testing.** Explain that interactive `chat` can't be driven in this agent environment, so validation here uses a non-interactive script, but if they want to test interactively themselves they can run the following in their own terminal (mention this once at the very start of this stage, before step 2's question, and again in the closing summary after validation finishes):
|
||||||
|
```bash
|
||||||
|
llamafactory-cli chat llamafactory_runs/<run_id>/infer.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Generate an inference config into the **artifacts directory** (`./llamafactory_runs/<run_id>/infer.yaml`). **The config differs by the `finetuning_type` chosen in Stage 0 — branch accordingly:**
|
||||||
|
|
||||||
|
- **LoRA / QLoRA** (the training `output_dir` is a LoRA *adapter*, not a full model) — base it on `examples/inference/qwen3_lora_sft.yaml` and use `adapter_name_or_path`:
|
||||||
|
```yaml
|
||||||
|
model_name_or_path: <base_model>
|
||||||
|
adapter_name_or_path: <output_dir> # LoRA adapter path (the training output_dir)
|
||||||
|
template: <template> # MUST match the template used at training time
|
||||||
|
infer_backend: huggingface
|
||||||
|
trust_remote_code: true
|
||||||
|
```
|
||||||
|
- **Full** (the training `output_dir` is already a complete set of model weights — there is NO adapter) — base it on `examples/inference/qwen3_full_sft.yaml` and point `model_name_or_path` directly at the `output_dir`, with **NO `adapter_name_or_path` field at all**:
|
||||||
|
```yaml
|
||||||
|
model_name_or_path: <output_dir> # the full fine-tuned model (training output_dir)
|
||||||
|
template: <template> # MUST match the template used at training time
|
||||||
|
infer_backend: huggingface
|
||||||
|
trust_remote_code: true
|
||||||
|
```
|
||||||
|
Adding an `adapter_name_or_path` for a Full run is wrong (there is no adapter to load) and will fail or silently load nothing.
|
||||||
|
|
||||||
|
- **Keep `template` identical to the training config.** A mismatch (e.g. trained with `qwen3_nothink` but inferred with `qwen3`) activates think / tool-call special tokens the model never saw in training and produces garbled output.
|
||||||
|
- **Show the inference config as a table and get user confirmation before running.** Just like the training yaml, after generating `infer.yaml` print its key parameters as a table (for LoRA/QLoRA: `model_name_or_path`, `adapter_name_or_path`, `template`, `infer_backend`, `trust_remote_code`; for Full: `model_name_or_path`, `template`, `infer_backend`, `trust_remote_code`) and use `AskUserQuestion` to let the user confirm (or request changes) before you run any inference. Do not start validation until the user confirms.
|
||||||
|
2. Ask the user to provide **test text** (and test image path(s) for multimodal models).
|
||||||
|
3. **Use a non-interactive batch inference script** (preferred). `llamafactory-cli chat` is an **interactive** REPL and cannot be driven in this agent / background environment, so validation is done with a short script (write it into the artifacts dir) that loads `ChatModel` with the **same args as `infer.yaml`** (so it must follow the same LoRA/QLoRA-vs-Full branching — include `adapter_name_or_path` only for LoRA/QLoRA, never for Full) and feeds the test prompts, e.g. for a LoRA/QLoRA run:
|
||||||
|
```python
|
||||||
|
from llamafactory.chat import ChatModel
|
||||||
|
chat = ChatModel({
|
||||||
|
"model_name_or_path": "<base_model>",
|
||||||
|
"adapter_name_or_path": "<output_dir>", # LoRA/QLoRA only — OMIT this key for Full
|
||||||
|
"template": "<template>",
|
||||||
|
"infer_backend": "huggingface",
|
||||||
|
"trust_remote_code": True,
|
||||||
|
})
|
||||||
|
for q in ["你是谁?", "Who are you?"]:
|
||||||
|
print(q, "->", chat.chat([{"role": "user", "content": q}])[0].response_text)
|
||||||
|
```
|
||||||
|
For a **Full** run, drop the `adapter_name_or_path` key and set `"model_name_or_path": "<output_dir>"`.
|
||||||
|
Running this in the foreground is fine (only training really needs background); **run it on the GPU(s) chosen in Stage 2.5** by prefixing the command with the visibility env var, e.g. `HIP_VISIBLE_DEVICES=<idx> python <script>` (or `CUDA_VISIBLE_DEVICES=<idx>` on NVIDIA); just **report the outputs to the user** when it finishes.
|
||||||
|
- **After validation finishes, state the interactive self-test command again** (the same `llamafactory-cli chat llamafactory_runs/<run_id>/infer.yaml` shown at the start of this stage), so the user has it both before and after validation.
|
||||||
|
4. Multimodal: pass images together with the prompt and show the model's answer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 7: Model export (optional)
|
||||||
|
|
||||||
|
If the user wants to export, **the meaning of "export" depends on the `finetuning_type` chosen in Stage 0 — branch accordingly:**
|
||||||
|
|
||||||
|
- **LoRA / QLoRA** — export *merges* the LoRA adapter into the base model and writes a standalone full model. This is the classic `merge_lora` flow.
|
||||||
|
- **Full** — there is **no adapter and nothing to merge**; the training `output_dir` is already a complete model. "Export" here just re-saves / tidies those full weights (plus tokenizer, generation config, etc.) into a clean user-specified directory. Do NOT describe this as "merging".
|
||||||
|
|
||||||
|
1. Ask for the **export name/directory** (user-specified). This is where the exported model weights go (e.g. under `./models/...`) — it is the model output, separate from the artifacts directory.
|
||||||
|
- For **LoRA / QLoRA**, **prefer a `merged` suffix** in the recommended name (e.g. `./models/<base_model>-merged`, or `<base_model>-<identity>-merged`) so the merged output is clearly distinguishable from the base weights.
|
||||||
|
- For **Full**, `merged` is misleading (nothing was merged) — recommend a plain descriptive suffix instead (e.g. `./models/<base_model>-sft`, or `<base_model>-<identity>`).
|
||||||
|
- The user can always override.
|
||||||
|
2. Generate an export config into the **artifacts directory** (`./llamafactory_runs/<run_id>/export.yaml`), based on `examples/merge_lora/*.yaml`. **The config differs by finetuning_type:**
|
||||||
|
|
||||||
|
- **LoRA / QLoRA** — point `model_name_or_path` at the base model and `adapter_name_or_path` at the adapter (`output_dir`):
|
||||||
|
```yaml
|
||||||
|
model_name_or_path: <base_model>
|
||||||
|
adapter_name_or_path: <output_dir>
|
||||||
|
template: <template> # MUST match the training template
|
||||||
|
trust_remote_code: true
|
||||||
|
export_dir: <user-specified name>
|
||||||
|
export_size: 5
|
||||||
|
export_device: auto # auto = use the GPU chosen in Stage 2.5; cpu is much slower
|
||||||
|
export_legacy_format: false
|
||||||
|
```
|
||||||
|
Note: when merging LoRA/QLoRA, do **not** load a quantized model or set `quantization_bit` — merging into a quantized base produces a broken model. Merge into the full-precision base, then quantize separately if needed.
|
||||||
|
- **Full** — point `model_name_or_path` directly at the `output_dir` and use **NO `adapter_name_or_path`**:
|
||||||
|
```yaml
|
||||||
|
model_name_or_path: <output_dir> # the full fine-tuned model (training output_dir)
|
||||||
|
template: <template> # MUST match the training template
|
||||||
|
trust_remote_code: true
|
||||||
|
export_dir: <user-specified name>
|
||||||
|
export_size: 5
|
||||||
|
export_device: auto # auto = use the GPU chosen in Stage 2.5; cpu is much slower
|
||||||
|
export_legacy_format: false
|
||||||
|
```
|
||||||
|
- **`export_device` controls whether the merge/save runs on GPU or CPU.** `export_device: cpu` does the whole merge on CPU — it does **not** use the GPU even if you set a visibility env var, and for some models it can be very slow or appear to stall. To actually use the GPU chosen in Stage 2.5, set **`export_device: auto`** (it will place the model on the visible GPU). Prefer `auto` when a GPU is free; only fall back to `cpu` when no GPU is available (and warn the user it will be slow).
|
||||||
|
- **Show the export config as a table and get user confirmation before running.** Just like the training yaml, after generating `export.yaml` print its key parameters as a table (for LoRA/QLoRA include `adapter_name_or_path`; for Full omit it — list `model_name_or_path`, `template`, `export_dir`, `export_size`, `export_device`, `export_legacy_format`, etc.) and use `AskUserQuestion` to let the user confirm (or request changes) before you run the export. Do not start the export until the user confirms.
|
||||||
|
3. Run (export is usually quick — foreground is fine; only training really needs background). **Run it on the GPU(s) chosen in Stage 2.5** by prefixing with the visibility env var, and tee the output into the artifacts dir for the record:
|
||||||
|
```bash
|
||||||
|
# HIP_VISIBLE_DEVICES for AMD, CUDA_VISIBLE_DEVICES for NVIDIA; pair with export_device: auto to use the GPU.
|
||||||
|
HIP_VISIBLE_DEVICES=<idx> llamafactory-cli export llamafactory_runs/<run_id>/export.yaml 2>&1 | tee llamafactory_runs/<run_id>/export.log
|
||||||
|
```
|
||||||
|
4. When export completes, tell the user the final model path.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Final summary (end of the whole workflow)
|
||||||
|
|
||||||
|
When all chosen stages are finished, give a concise closing summary and then **stop**. The summary may include ONLY:
|
||||||
|
|
||||||
|
- the produced artifacts (config/log dir, LoRA adapter, loss curve image path, merged-model export dir);
|
||||||
|
- the training result (steps / epochs / final loss / runtime);
|
||||||
|
- the validation result (if validation ran);
|
||||||
|
- the export directory (if export ran);
|
||||||
|
- the ready-to-run command for interactive self-testing (e.g. `llamafactory-cli chat ...`).
|
||||||
|
|
||||||
|
**Do NOT propose or offer any follow-up work** — no suggestions about quantization, GGUF conversion, deployment, serving as an API, further training, or anything similar. Do not end with questions like "需要我帮你……吗?". Simply describe what was produced and stop.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## General requirements
|
||||||
|
|
||||||
|
- Ask first with `AskUserQuestion` at every irreversible or ambiguous decision; do not assume.
|
||||||
|
- **Confirm before every yaml write — no exceptions.** Before writing ANY yaml config to disk (train / inference / export), you MUST first print its key parameters as a table AND call `AskUserQuestion` to get the user's explicit confirmation. Only write the file after the user confirms. This applies to every config in every stage, not just training — do not "save time" by writing infer.yaml or export.yaml directly. If the user requests changes, update the table and re-confirm before writing.
|
||||||
|
- Run **long-running** commands (model download, training) **in the background + report periodically** (interval ≤ 100 seconds). Inference validation and export are usually quick and do NOT need background — run them in the foreground.
|
||||||
|
- **Detect GPU status once before running and pin the free device(s)** (see Stage 2.5). Detect a single time at the start, pick the device(s) — if multiple are free, ask single-vs-multi — then reuse the same index/indices for SFT / validation / export via the platform's visibility env var (`HIP_VISIBLE_DEVICES` for AMD, `CUDA_VISIBLE_DEVICES` for NVIDIA). Do NOT re-detect before each run. Never silently launch onto a busy card — if none are free, ask the user. For export to actually use the GPU, also set `export_device: auto` (not `cpu`).
|
||||||
|
- **Keep generated yaml configs and logs in the artifacts directory** (`./llamafactory_runs/<run_id>/`); do not write them into `./models/` (downloaded weights) or the training `output_dir` (saved checkpoints).
|
||||||
|
- **Prefer official-example defaults; track every deviation.** When generating the training yaml, start from the official example and change as little as possible. List any changed field in a "diff vs. default" table with a concrete reason (user-specified, model/dataset adaptation, etc.).
|
||||||
|
- **Keep `template` consistent across train / inference / export.** Use the template from the official example unless there's a tracked reason to change it; a train/infer mismatch produces garbled output.
|
||||||
|
- Never destroy the user's original data files in place; do not pollute the repo's built-in `data/*.json` — prefer copies.
|
||||||
|
- Keep `dataset_info.json` valid JSON after edits.
|
||||||
38
.github/workflows/docker.yml
vendored
38
.github/workflows/docker.yml
vendored
@@ -29,8 +29,6 @@ jobs:
|
|||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- device: "cuda"
|
- device: "cuda"
|
||||||
- device: "npu-a2"
|
|
||||||
- device: "npu-a3"
|
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
@@ -50,7 +48,7 @@ jobs:
|
|||||||
docker-images: false
|
docker-images: false
|
||||||
|
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
- name: Get llamafactory version
|
- name: Get llamafactory version
|
||||||
id: version
|
id: version
|
||||||
@@ -71,14 +69,6 @@ jobs:
|
|||||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
- name: Login to Quay
|
|
||||||
if: ${{ github.event_name != 'pull_request' && startsWith(matrix.device, 'npu') }}
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
registry: quay.io
|
|
||||||
username: ${{ vars.QUAY_ASCEND_USERNAME }}
|
|
||||||
password: ${{ secrets.QUAY_ASCEND_TOKEN }}
|
|
||||||
|
|
||||||
- name: Build and push Docker image (CUDA)
|
- name: Build and push Docker image (CUDA)
|
||||||
if: ${{ matrix.device == 'cuda' }}
|
if: ${{ matrix.device == 'cuda' }}
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
@@ -88,29 +78,3 @@ jobs:
|
|||||||
push: ${{ github.event_name != 'pull_request' }}
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
tags: |
|
tags: |
|
||||||
docker.io/hiyouga/llamafactory:${{ steps.version.outputs.tag }}
|
docker.io/hiyouga/llamafactory:${{ steps.version.outputs.tag }}
|
||||||
|
|
||||||
- name: Build and push Docker image (NPU-A2)
|
|
||||||
if: ${{ matrix.device == 'npu-a2' }}
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
file: ./docker/docker-npu/Dockerfile
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
tags: |
|
|
||||||
docker.io/hiyouga/llamafactory:${{ steps.version.outputs.tag }}-npu-a2
|
|
||||||
quay.io/ascend/llamafactory:${{ steps.version.outputs.tag }}-npu-a2
|
|
||||||
|
|
||||||
- name: Build and push Docker image (NPU-A3)
|
|
||||||
if: ${{ matrix.device == 'npu-a3' }}
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
file: ./docker/docker-npu/Dockerfile
|
|
||||||
build-args: |
|
|
||||||
BASE_IMAGE=quay.io/ascend/cann:8.3.rc2-a3-ubuntu22.04-py3.11
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
tags: |
|
|
||||||
docker.io/hiyouga/llamafactory:${{ steps.version.outputs.tag }}-npu-a3
|
|
||||||
quay.io/ascend/llamafactory:${{ steps.version.outputs.tag }}-npu-a3
|
|
||||||
|
|||||||
115
.github/workflows/docker_npu.yml
vendored
Normal file
115
.github/workflows/docker_npu.yml
vendored
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
name: docker-npu
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
schedule:
|
||||||
|
- cron: "17 2 * * *"
|
||||||
|
timezone: "Asia/Shanghai"
|
||||||
|
release:
|
||||||
|
types:
|
||||||
|
- published
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- device: "npu-a2"
|
||||||
|
os: "ubuntu"
|
||||||
|
base_image: "quay.io/ascend/cann:9.0.0-910b-ubuntu22.04-py3.11"
|
||||||
|
- device: "npu-a3"
|
||||||
|
os: "ubuntu"
|
||||||
|
base_image: "quay.io/ascend/cann:9.0.0-a3-ubuntu22.04-py3.11"
|
||||||
|
- device: "npu-a2"
|
||||||
|
os: "openeuler"
|
||||||
|
base_image: "quay.io/ascend/cann:9.0.0-910b-openeuler24.03-py3.11"
|
||||||
|
- device: "npu-a3"
|
||||||
|
os: "openeuler"
|
||||||
|
base_image: "quay.io/ascend/cann:9.0.0-a3-openeuler24.03-py3.11"
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.device }}-${{ matrix.os }}
|
||||||
|
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||||
|
|
||||||
|
environment:
|
||||||
|
name: docker
|
||||||
|
url: https://hub.docker.com/r/hiyouga/llamafactory
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Free up disk space
|
||||||
|
uses: jlumbroso/free-disk-space@v1.3.1
|
||||||
|
with:
|
||||||
|
tool-cache: true
|
||||||
|
docker-images: false
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Get llamafactory version
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
if [ "${{ github.event_name }}" = "release" ]; then
|
||||||
|
echo "tag=$(grep -oP 'VERSION = "\K[^"]+' src/llamafactory/extras/env.py)" >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
echo "tag=latest" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Get NPU image tag
|
||||||
|
id: npu_tag
|
||||||
|
env:
|
||||||
|
BASE_IMAGE: ${{ matrix.base_image }}
|
||||||
|
DEVICE: ${{ matrix.device }}
|
||||||
|
MATRIX_OS: ${{ matrix.os }}
|
||||||
|
LLAMAFACTORY_VERSION: ${{ steps.version.outputs.tag }}
|
||||||
|
run: |
|
||||||
|
base_image_tag="${BASE_IMAGE##*:}"
|
||||||
|
cann_version="${base_image_tag%%-*}"
|
||||||
|
torch_npu_version="$(sed -nE 's/^torch[-_]npu==([0-9]+(\.[0-9]+)*).*/\1/p' requirements/npu.txt)"
|
||||||
|
accelerator="${DEVICE#npu-}"
|
||||||
|
accelerator="${accelerator^^}"
|
||||||
|
operating_system="$(grep -oE '(ubuntu|openeuler)' <<< "${base_image_tag}" | head -n 1)"
|
||||||
|
python_version="$(grep -oE 'py[0-9]+\.[0-9]+' <<< "${base_image_tag}" | head -n 1)"
|
||||||
|
|
||||||
|
if [[ -z "${cann_version}" || -z "${torch_npu_version}" || -z "${operating_system}" || -z "${python_version}" ]]; then
|
||||||
|
echo "Failed to derive the NPU image tag from ${BASE_IMAGE} and requirements/npu.txt" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "${operating_system}" != "${MATRIX_OS}" ]]; then
|
||||||
|
echo "Operating system ${operating_system} derived from ${BASE_IMAGE} does not match matrix OS ${MATRIX_OS}" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "tag=${LLAMAFACTORY_VERSION}-cann${cann_version}-torch_npu${torch_npu_version}-${accelerator}-${operating_system}-${python_version}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Login to Docker Hub
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Login to Quay
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: quay.io
|
||||||
|
username: ${{ vars.QUAY_ASCEND_USERNAME }}
|
||||||
|
password: ${{ secrets.QUAY_ASCEND_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build and push Docker image (${{ matrix.device }}-${{ matrix.os }})
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
file: ./docker/docker-npu/Dockerfile
|
||||||
|
build-args: |
|
||||||
|
BASE_IMAGE=${{ matrix.base_image }}
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
docker.io/hiyouga/llamafactory:${{ steps.npu_tag.outputs.tag }}
|
||||||
|
quay.io/ascend/llamafactory:${{ steps.npu_tag.outputs.tag }}
|
||||||
77
.github/workflows/docs.yml
vendored
Normal file
77
.github/workflows/docs.yml
vendored
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
name: Build and Deploy Sphinx Docs
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ["main"]
|
||||||
|
paths:
|
||||||
|
- "docs/**"
|
||||||
|
pull_request:
|
||||||
|
branches: ["main"]
|
||||||
|
paths:
|
||||||
|
- "docs/**"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pages: write
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: "pages"
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.10'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
pip install -r docs/requirements.txt
|
||||||
|
|
||||||
|
- name: Build Sphinx
|
||||||
|
run: |
|
||||||
|
sphinx-build -b html docs/zh docs/_build/html/zh
|
||||||
|
sphinx-build -b html docs/en docs/_build/html/en
|
||||||
|
|
||||||
|
printf '%s\n' \
|
||||||
|
'<!DOCTYPE html>' \
|
||||||
|
'<html>' \
|
||||||
|
' <head>' \
|
||||||
|
' <meta charset="utf-8" />' \
|
||||||
|
' <meta http-equiv="refresh" content="0; url=zh/index.html" />' \
|
||||||
|
' <script>window.location.href="zh/index.html"+window.location.search+window.location.hash;</script>' \
|
||||||
|
' <title>Redirecting...</title>' \
|
||||||
|
' </head>' \
|
||||||
|
' <body>' \
|
||||||
|
' <a href="zh/index.html">Redirecting...</a>' \
|
||||||
|
' </body>' \
|
||||||
|
'</html>' \
|
||||||
|
> docs/_build/html/index.html
|
||||||
|
|
||||||
|
touch docs/_build/html/.nojekyll
|
||||||
|
|
||||||
|
- name: Setup Pages
|
||||||
|
uses: actions/configure-pages@v5
|
||||||
|
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-pages-artifact@v3
|
||||||
|
with:
|
||||||
|
path: docs/_build/html
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
environment:
|
||||||
|
name: github-pages
|
||||||
|
url: ${{ steps.deployment.outputs.page_url }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: build
|
||||||
|
steps:
|
||||||
|
- name: Deploy to GitHub Pages
|
||||||
|
id: deployment
|
||||||
|
uses: actions/deploy-pages@v4
|
||||||
2
.github/workflows/publish.yml
vendored
2
.github/workflows/publish.yml
vendored
@@ -21,7 +21,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@v7
|
uses: astral-sh/setup-uv@v7
|
||||||
|
|||||||
24
.github/workflows/tests.yml
vendored
24
.github/workflows/tests.yml
vendored
@@ -35,15 +35,12 @@ jobs:
|
|||||||
transformers:
|
transformers:
|
||||||
- ""
|
- ""
|
||||||
include: # test backward compatibility
|
include: # test backward compatibility
|
||||||
- python: "3.11"
|
|
||||||
os: "ubuntu-latest"
|
|
||||||
transformers: "4.51.0"
|
|
||||||
- python: "3.11"
|
|
||||||
os: "ubuntu-latest"
|
|
||||||
transformers: "4.53.0"
|
|
||||||
- python: "3.11"
|
- python: "3.11"
|
||||||
os: "ubuntu-latest"
|
os: "ubuntu-latest"
|
||||||
transformers: "4.55.0"
|
transformers: "4.55.0"
|
||||||
|
- python: "3.11"
|
||||||
|
os: "ubuntu-latest"
|
||||||
|
transformers: "4.57.1"
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
|
|
||||||
@@ -54,10 +51,11 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||||
OS_NAME: ${{ matrix.os }}
|
OS_NAME: ${{ matrix.os }}
|
||||||
|
UV_NO_SYNC: 1
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@v7
|
uses: astral-sh/setup-uv@v7
|
||||||
@@ -70,7 +68,8 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
uv venv
|
uv venv
|
||||||
uv pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
|
uv pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
|
||||||
uv pip install -e ".[dev]"
|
uv pip install -e .
|
||||||
|
uv pip install -r requirements/dev.txt
|
||||||
|
|
||||||
- name: Install transformers
|
- name: Install transformers
|
||||||
if: ${{ matrix.transformers }}
|
if: ${{ matrix.transformers }}
|
||||||
@@ -79,7 +78,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Cache files
|
- name: Cache files
|
||||||
id: hf-hub-cache
|
id: hf-hub-cache
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v5
|
||||||
with:
|
with:
|
||||||
path: ${{ runner.temp }}/huggingface
|
path: ${{ runner.temp }}/huggingface
|
||||||
key: huggingface-${{ matrix.os }}-${{ matrix.python }}-${{ matrix.transformers }}-${{ hashFiles('tests/version.txt') }}
|
key: huggingface-${{ matrix.os }}-${{ matrix.python }}-${{ matrix.transformers }}-${{ hashFiles('tests/version.txt') }}
|
||||||
@@ -87,25 +86,18 @@ jobs:
|
|||||||
- name: Check quality
|
- name: Check quality
|
||||||
run: |
|
run: |
|
||||||
make style && make quality
|
make style && make quality
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
|
|
||||||
- name: Check license
|
- name: Check license
|
||||||
run: |
|
run: |
|
||||||
make license
|
make license
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
|
|
||||||
- name: Check build
|
- name: Check build
|
||||||
run: |
|
run: |
|
||||||
make build
|
make build
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
|
|
||||||
- name: Test with pytest
|
- name: Test with pytest
|
||||||
run: |
|
run: |
|
||||||
make test
|
make test
|
||||||
env:
|
env:
|
||||||
UV_NO_SYNC: 1
|
|
||||||
HF_HOME: ${{ runner.temp }}/huggingface
|
HF_HOME: ${{ runner.temp }}/huggingface
|
||||||
HF_HUB_OFFLINE: "${{ steps.hf-hub-cache.outputs.cache-hit == 'true' && '1' || '0' }}"
|
HF_HUB_OFFLINE: "${{ steps.hf-hub-cache.outputs.cache-hit == 'true' && '1' || '0' }}"
|
||||||
|
|||||||
30
.github/workflows/tests_cuda.yml
vendored
30
.github/workflows/tests_cuda.yml
vendored
@@ -35,9 +35,16 @@ jobs:
|
|||||||
group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.os }}-${{ matrix.python }}
|
group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.os }}-${{ matrix.python }}
|
||||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||||
|
|
||||||
|
env:
|
||||||
|
HF_HOME: "${{ github.workspace }}/../.runner_cache/huggingface"
|
||||||
|
UV_CACHE_DIR: "${{ github.workspace }}/../.runner_cache/uv"
|
||||||
|
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||||
|
OS_NAME: ${{ matrix.os }}
|
||||||
|
UV_NO_SYNC: 1
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@v7
|
uses: astral-sh/setup-uv@v7
|
||||||
@@ -52,37 +59,22 @@ jobs:
|
|||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
uv venv
|
uv venv
|
||||||
uv pip install -e ".[dev]"
|
uv pip install -e .
|
||||||
|
uv pip install -r requirements/dev.txt
|
||||||
- name: Cache HuggingFace models
|
uv pip install -r requirements/bitsandbytes.txt
|
||||||
id: hf-hub-cache
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ${{ runner.temp }}/huggingface
|
|
||||||
key: hf-cache-${{ runner.os }}-${{ hashFiles('tests/version.txt') }}
|
|
||||||
|
|
||||||
- name: Check quality
|
- name: Check quality
|
||||||
run: |
|
run: |
|
||||||
make style && make quality
|
make style && make quality
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
|
|
||||||
- name: Check license
|
- name: Check license
|
||||||
run: |
|
run: |
|
||||||
make license
|
make license
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
|
|
||||||
- name: Check build
|
- name: Check build
|
||||||
run: |
|
run: |
|
||||||
make build
|
make build
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
|
|
||||||
- name: Test with pytest
|
- name: Test with pytest
|
||||||
run: |
|
run: |
|
||||||
make test
|
make test
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
HF_HOME: ${{ runner.temp }}/huggingface
|
|
||||||
HF_HUB_OFFLINE: "${{ steps.hf-hub-cache.outputs.cache-hit == 'true' && '1' || '0' }}"
|
|
||||||
|
|||||||
35
.github/workflows/tests_npu.yml
vendored
35
.github/workflows/tests_npu.yml
vendored
@@ -38,15 +38,22 @@ jobs:
|
|||||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||||
|
|
||||||
container:
|
container:
|
||||||
image: ascendai/cann:8.3.rc2-910b-ubuntu22.04-py3.11
|
image: ascendai/cann:9.0.0-910b-ubuntu22.04-py3.11
|
||||||
env:
|
env:
|
||||||
HF_ENDPOINT: https://hf-mirror.com
|
HF_ENDPOINT: https://hf-mirror.com
|
||||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||||
OS_NAME: ${{ matrix.os }}
|
OS_NAME: ${{ matrix.os }}
|
||||||
|
UV_NO_SYNC: 1
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
|
- name: Set nginx-cache for Ascend CI
|
||||||
|
run: |
|
||||||
|
sed -Ei 's@(ports|archive).ubuntu.com@cache-service.nginx-pypi-cache.svc.cluster.local:8081@g' /etc/apt/sources.list
|
||||||
|
pip config set global.index-url http://cache-service.nginx-pypi-cache.svc.cluster.local/pypi/simple
|
||||||
|
pip config set global.trusted-host cache-service.nginx-pypi-cache.svc.cluster.local
|
||||||
|
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@v7
|
uses: astral-sh/setup-uv@v7
|
||||||
@@ -58,8 +65,9 @@ jobs:
|
|||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
uv venv
|
uv venv
|
||||||
uv pip install torch-npu==${{matrix.pytorch_npu}}
|
uv pip install -e .
|
||||||
uv pip install -e ".[dev]"
|
uv pip install -r requirements/npu.txt
|
||||||
|
uv pip install -r requirements/dev.txt
|
||||||
|
|
||||||
- name: Install node
|
- name: Install node
|
||||||
run: |
|
run: |
|
||||||
@@ -68,35 +76,20 @@ jobs:
|
|||||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||||
apt-get install -y nodejs
|
apt-get install -y nodejs
|
||||||
|
|
||||||
- name: Cache files
|
|
||||||
id: hf-hub-cache
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ${{ runner.temp }}/huggingface
|
|
||||||
key: huggingface-${{ matrix.os }}-${{ matrix.python }}-${{ hashFiles('tests/version.txt') }}
|
|
||||||
|
|
||||||
- name: Check quality
|
- name: Check quality
|
||||||
run: |
|
run: |
|
||||||
make style && make quality
|
make style && make quality
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
|
|
||||||
- name: Check license
|
- name: Check license
|
||||||
run: |
|
run: |
|
||||||
make license
|
make license
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
|
|
||||||
- name: Check build
|
- name: Check build
|
||||||
run: |
|
run: |
|
||||||
make build
|
make build
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
|
|
||||||
- name: Test with pytest
|
- name: Test with pytest
|
||||||
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
|
source /usr/local/Ascend/ascend-toolkit/set_env.sh
|
||||||
make test
|
make test
|
||||||
env:
|
|
||||||
UV_NO_SYNC: 1
|
|
||||||
HF_HOME: /root/.cache/huggingface
|
|
||||||
HF_HUB_OFFLINE: "${{ steps.hf-hub-cache.outputs.cache-hit == 'true' && '1' || '0' }}"
|
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -176,6 +176,7 @@ llamaboard_cache/
|
|||||||
llamaboard_config/
|
llamaboard_config/
|
||||||
saves/
|
saves/
|
||||||
output/
|
output/
|
||||||
|
outputs/
|
||||||
wandb/
|
wandb/
|
||||||
swanlog/
|
swanlog/
|
||||||
generated_predictions.jsonl
|
generated_predictions.jsonl
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ repos:
|
|||||||
args: [--py39-plus]
|
args: [--py39-plus]
|
||||||
|
|
||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
rev: v0.13.2
|
rev: v0.15.5
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff
|
- id: ruff
|
||||||
args: [--fix]
|
args: [--fix]
|
||||||
|
|||||||
11
Makefile
11
Makefile
@@ -2,9 +2,12 @@
|
|||||||
|
|
||||||
check_dirs := scripts src tests tests_v1
|
check_dirs := scripts src tests tests_v1
|
||||||
|
|
||||||
|
ruff_version := 0.15.5
|
||||||
|
|
||||||
RUN := $(shell command -v uv >/dev/null 2>&1 && echo "uv run" || echo "")
|
RUN := $(shell command -v uv >/dev/null 2>&1 && echo "uv run" || echo "")
|
||||||
BUILD := $(shell command -v uv >/dev/null 2>&1 && echo "uv build" || echo "python -m build")
|
BUILD := $(shell command -v uv >/dev/null 2>&1 && echo "uv build" || echo "python -m build")
|
||||||
TOOL := $(shell command -v uv >/dev/null 2>&1 && echo "uvx" || echo "")
|
TOOL := $(shell command -v uv >/dev/null 2>&1 && echo "uvx" || echo "")
|
||||||
|
RUFF := $(shell command -v uv >/dev/null 2>&1 && echo "uvx ruff@$(ruff_version)" || echo "ruff")
|
||||||
|
|
||||||
build:
|
build:
|
||||||
$(BUILD)
|
$(BUILD)
|
||||||
@@ -17,12 +20,12 @@ license:
|
|||||||
$(RUN) python3 tests/check_license.py $(check_dirs)
|
$(RUN) python3 tests/check_license.py $(check_dirs)
|
||||||
|
|
||||||
quality:
|
quality:
|
||||||
$(TOOL) ruff check $(check_dirs)
|
$(RUFF) check $(check_dirs)
|
||||||
$(TOOL) ruff format --check $(check_dirs)
|
$(RUFF) format --check $(check_dirs)
|
||||||
|
|
||||||
style:
|
style:
|
||||||
$(TOOL) ruff check $(check_dirs) --fix
|
$(RUFF) check $(check_dirs) --fix
|
||||||
$(TOOL) ruff format $(check_dirs)
|
$(RUFF) format $(check_dirs)
|
||||||
|
|
||||||
test:
|
test:
|
||||||
WANDB_DISABLED=true $(RUN) pytest -vv --import-mode=importlib tests/ tests_v1/
|
WANDB_DISABLED=true $(RUN) pytest -vv --import-mode=importlib tests/ tests_v1/
|
||||||
|
|||||||
162
README.md
162
README.md
@@ -15,13 +15,25 @@
|
|||||||
|
|
||||||
[](https://colab.research.google.com/drive/1eRTPn37ltBbYsISy9Aw2NuI2Aq5CQrD9?usp=sharing)
|
[](https://colab.research.google.com/drive/1eRTPn37ltBbYsISy9Aw2NuI2Aq5CQrD9?usp=sharing)
|
||||||
[](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory)
|
[](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory)
|
||||||
[](https://www.lab4ai.cn/course/detail?id=7c13e60f6137474eb40f6fd3983c0f46&utm_source=LLaMA-Factory)
|
|
||||||
[](https://www.llamafactory.com.cn/?utm_source=LLaMA-Factory)
|
|
||||||
[](https://huggingface.co/spaces/hiyouga/LLaMA-Board)
|
[](https://huggingface.co/spaces/hiyouga/LLaMA-Board)
|
||||||
[](https://modelscope.cn/studios/hiyouga/LLaMA-Board)
|
[](https://modelscope.cn/studios/hiyouga/LLaMA-Board)
|
||||||
[](https://novita.ai/templates-library/105981?sharer=88115474-394e-4bda-968e-b88e123d0c47)
|
[](https://novita.ai/templates-library/105981?sharer=88115474-394e-4bda-968e-b88e123d0c47)
|
||||||
|
|
||||||
### Used by [Amazon](https://aws.amazon.com/cn/blogs/machine-learning/how-apoidea-group-enhances-visual-information-extraction-from-banking-documents-with-multimodal-models-using-llama-factory-on-amazon-sagemaker-hyperpod/), [NVIDIA](https://developer.nvidia.com/rtx/ai-toolkit), [Aliyun](https://help.aliyun.com/zh/pai/use-cases/fine-tune-a-llama-3-model-with-llama-factory), etc.
|
### Used by [Amazon](https://aws.amazon.com/cn/blogs/machine-learning/how-apoidea-group-enhances-visual-information-extraction-from-banking-documents-with-multimodal-models-using-llama-factory-on-amazon-sagemaker-hyperpod/), [NVIDIA](https://build.nvidia.com/spark/llama-factory), [Aliyun](https://help.aliyun.com/zh/pai/use-cases/fine-tune-a-llama-3-model-with-llama-factory), etc.
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
|
<div align="center" markdown="1">
|
||||||
|
|
||||||
|
### Check our new open-source project —<br>🐧 [PenguinHarness](https://github.com/Prism-Shadow/penguin-harness): Your desktop agent that automatically builds agents for just $0.02 of tokens!
|
||||||
|
|
||||||
|
Follow our project: https://github.com/Prism-Shadow/penguin-harness
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
https://github.com/user-attachments/assets/9b7033e8-f08a-4c3f-bd33-547896664e6e
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
<div align="center" markdown="1">
|
<div align="center" markdown="1">
|
||||||
|
|
||||||
@@ -34,11 +46,11 @@
|
|||||||
|
|
||||||
### Easily fine-tune 100+ large language models with zero-code [CLI](#quickstart) and [Web UI](#fine-tuning-with-llama-board-gui-powered-by-gradio)
|
### Easily fine-tune 100+ large language models with zero-code [CLI](#quickstart) and [Web UI](#fine-tuning-with-llama-board-gui-powered-by-gradio)
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
👋 Join our [WeChat](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/main.jpg), [NPU](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/npu.jpg), [Lab4AI](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/lab4ai.jpg), [LLaMA Factory Online](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/online.jpg) user group.
|
👋 Join our [WeChat](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/main.jpg) and [NPU](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/npu.jpg) user groups.
|
||||||
|
|
||||||
\[ English | [中文](README_zh.md) \]
|
\[ English | [中文](README_zh.md) \]
|
||||||
|
|
||||||
@@ -52,14 +64,13 @@ Start local training:
|
|||||||
Start cloud training:
|
Start cloud training:
|
||||||
- **Colab (free)**: https://colab.research.google.com/drive/1eRTPn37ltBbYsISy9Aw2NuI2Aq5CQrD9?usp=sharing
|
- **Colab (free)**: https://colab.research.google.com/drive/1eRTPn37ltBbYsISy9Aw2NuI2Aq5CQrD9?usp=sharing
|
||||||
- **PAI-DSW (free trial)**: https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory
|
- **PAI-DSW (free trial)**: https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory
|
||||||
- **LLaMA Factory Online**: https://www.llamafactory.com.cn/?utm_source=LLaMA-Factory
|
- **AMD GPU Cloud (free credits)**: https://github.com/AMD-AIM/AMD_Developers_Notebooks/blob/main/en/AMD_developer_LLaMAFactory_note_en.md
|
||||||
- **Alaya NeW (cloud GPU deal)**: https://docs.alayanew.com/docs/documents/useGuide/LLaMAFactory/mutiple/?utm_source=LLaMA-Factory
|
|
||||||
|
|
||||||
Read technical notes:
|
Read technical notes:
|
||||||
- **Documentation (WIP)**: https://llamafactory.readthedocs.io/en/latest/
|
- **Documentation (WIP)**: https://llamafactory.readthedocs.io/en/latest/
|
||||||
- **Documentation (AMD GPU)**: https://rocm.docs.amd.com/projects/ai-developer-hub/en/latest/notebooks/fine_tune/llama_factory_llama3.html
|
- **Documentation (AMD GPU)**: https://rocm.docs.amd.com/projects/ai-developer-hub/en/latest/notebooks/fine_tune/llama_factory_llama3.html
|
||||||
|
- **Documentation (ASCEND NPU)**: https://llamafactory.readthedocs.io/en/latest/multibackend/npu/index.html
|
||||||
- **Official Blog**: https://blog.llamafactory.net/en/
|
- **Official Blog**: https://blog.llamafactory.net/en/
|
||||||
- **Official Course**: https://www.lab4ai.cn/course/detail?id=7c13e60f6137474eb40f6fd3983c0f46&utm_source=LLaMA-Factory
|
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> Except for the above links, all other websites are unauthorized third-party websites. Please carefully use them.
|
> Except for the above links, all other websites are unauthorized third-party websites. Please carefully use them.
|
||||||
@@ -78,7 +89,6 @@ Read technical notes:
|
|||||||
- [Data Preparation](#data-preparation)
|
- [Data Preparation](#data-preparation)
|
||||||
- [Quickstart](#quickstart)
|
- [Quickstart](#quickstart)
|
||||||
- [Fine-Tuning with LLaMA Board GUI](#fine-tuning-with-llama-board-gui-powered-by-gradio)
|
- [Fine-Tuning with LLaMA Board GUI](#fine-tuning-with-llama-board-gui-powered-by-gradio)
|
||||||
- [LLaMA Factory Online](#llama-factory-online)
|
|
||||||
- [Build Docker](#build-docker)
|
- [Build Docker](#build-docker)
|
||||||
- [Deploy with OpenAI-style API and vLLM](#deploy-with-openai-style-api-and-vllm)
|
- [Deploy with OpenAI-style API and vLLM](#deploy-with-openai-style-api-and-vllm)
|
||||||
- [Download from ModelScope Hub](#download-from-modelscope-hub)
|
- [Download from ModelScope Hub](#download-from-modelscope-hub)
|
||||||
@@ -92,7 +102,7 @@ Read technical notes:
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Various models**: LLaMA, LLaVA, Mistral, Mixtral-MoE, Qwen, Qwen2-VL, DeepSeek, Yi, Gemma, ChatGLM, Phi, etc.
|
- **Various models**: LLaMA, LLaVA, Mistral, Mixtral-MoE, Qwen3, Qwen3-VL, DeepSeek, Gemma, GLM, Phi, etc.
|
||||||
- **Integrated methods**: (Continuous) pre-training, (multimodal) supervised fine-tuning, reward modeling, PPO, DPO, KTO, ORPO, etc.
|
- **Integrated methods**: (Continuous) pre-training, (multimodal) supervised fine-tuning, reward modeling, PPO, DPO, KTO, ORPO, etc.
|
||||||
- **Scalable resources**: 16-bit full-tuning, freeze-tuning, LoRA and 2/3/4/5/6/8-bit QLoRA via AQLM/AWQ/GPTQ/LLM.int8/HQQ/EETQ.
|
- **Scalable resources**: 16-bit full-tuning, freeze-tuning, LoRA and 2/3/4/5/6/8-bit QLoRA via AQLM/AWQ/GPTQ/LLM.int8/HQQ/EETQ.
|
||||||
- **Advanced algorithms**: [GaLore](https://github.com/jiaweizzhao/GaLore), [BAdam](https://github.com/Ledzy/BAdam), [APOLLO](https://github.com/zhuhanqing/APOLLO), [Adam-mini](https://github.com/zyushun/Adam-mini), [Muon](https://github.com/KellerJordan/Muon), [OFT](https://github.com/huggingface/peft/tree/main/src/peft/tuners/oft), DoRA, LongLoRA, LLaMA Pro, Mixture-of-Depths, LoRA+, LoftQ and PiSSA.
|
- **Advanced algorithms**: [GaLore](https://github.com/jiaweizzhao/GaLore), [BAdam](https://github.com/Ledzy/BAdam), [APOLLO](https://github.com/zhuhanqing/APOLLO), [Adam-mini](https://github.com/zyushun/Adam-mini), [Muon](https://github.com/KellerJordan/Muon), [OFT](https://github.com/huggingface/peft/tree/main/src/peft/tuners/oft), DoRA, LongLoRA, LLaMA Pro, Mixture-of-Depths, LoRA+, LoftQ and PiSSA.
|
||||||
@@ -117,15 +127,13 @@ Read technical notes:
|
|||||||
|
|
||||||
- 💡 [KTransformers Fine-Tuning × LLaMA Factory: Fine-tuning 1000 Billion models with 2 4090-GPU + CPU](https://blog.llamafactory.net/en/posts/ktransformers/) (English)
|
- 💡 [KTransformers Fine-Tuning × LLaMA Factory: Fine-tuning 1000 Billion models with 2 4090-GPU + CPU](https://blog.llamafactory.net/en/posts/ktransformers/) (English)
|
||||||
- 💡 [Easy Dataset × LLaMA Factory: Enabling LLMs to Efficiently Learn Domain Knowledge](https://buaa-act.feishu.cn/wiki/GVzlwYcRFiR8OLkHbL6cQpYin7g) (English)
|
- 💡 [Easy Dataset × LLaMA Factory: Enabling LLMs to Efficiently Learn Domain Knowledge](https://buaa-act.feishu.cn/wiki/GVzlwYcRFiR8OLkHbL6cQpYin7g) (English)
|
||||||
- [Fine-tune a mental health LLM using LLaMA-Factory](https://www.lab4ai.cn/project/detail?id=25cce32ec131497b9e06a93336a0817f&type=project&utm_source=LLaMA-Factory) (Chinese)
|
- 💡 [DataFlow × LLaMA Factory: Producing High-Quality Data for LLM Training with a Data Preparation Pipeline](https://wcny4qa9krto.feishu.cn/wiki/LWkkwTDBfiiRKqkDSvucG6yjnbW) (English) | [中文](https://wcny4qa9krto.feishu.cn/wiki/LlMxweUAJimrmykRD5qcGuswnHd)
|
||||||
- [Fine-tune GPT-OSS for Role-Playing using LLaMA-Factory](https://docs.llamafactory.com.cn/docs/documents/best-practice/gptroleplay/?utm_source=LLaMA-Factory) (Chinese)
|
- 💡 [DataFlex × LLaMA Factory: A Data-Centric Dynamic Training System Built on LLaMA-Factory](https://wcny4qa9krto.feishu.cn/wiki/OlREwPQWdi9K6ZkJNHIciLhtnkv) (English) | [中文](https://wcny4qa9krto.feishu.cn/wiki/H2A9wSsbCinzavkT2oyc2C5Vn0e)
|
||||||
- [A One-Stop Code-Free Model Reinforcement Learning and Deployment Platform based on LLaMA-Factory and EasyR1](https://aws.amazon.com/cn/blogs/china/building-llm-model-hub-based-on-llamafactory-and-easyr1/) (Chinese)
|
- [A One-Stop Code-Free Model Reinforcement Learning and Deployment Platform based on LLaMA-Factory and EasyR1](https://aws.amazon.com/cn/blogs/china/building-llm-model-hub-based-on-llamafactory-and-easyr1/) (Chinese)
|
||||||
- [How Apoidea Group enhances visual information extraction from banking documents with multimodal models using LLaMA-Factory on Amazon SageMaker HyperPod](https://aws.amazon.com/cn/blogs/machine-learning/how-apoidea-group-enhances-visual-information-extraction-from-banking-documents-with-multimodal-models-using-llama-factory-on-amazon-sagemaker-hyperpod/) (English)
|
- [How Apoidea Group enhances visual information extraction from banking documents with multimodal models using LLaMA-Factory on Amazon SageMaker HyperPod](https://aws.amazon.com/cn/blogs/machine-learning/how-apoidea-group-enhances-visual-information-extraction-from-banking-documents-with-multimodal-models-using-llama-factory-on-amazon-sagemaker-hyperpod/) (English)
|
||||||
|
|
||||||
<details><summary>All Blogs</summary>
|
<details><summary>All Blogs</summary>
|
||||||
|
|
||||||
- [Fine-tune Llama3.1-70B for Medical Diagnosis using LLaMA-Factory](https://docs.alayanew.com/docs/documents/bestPractice/bigModel/llama70B/?utm_source=LLaMA-Factory) (Chinese)
|
|
||||||
- [Fine-tune Qwen2.5-VL for Autonomous Driving using LLaMA-Factory](https://docs.alayanew.com/docs/documents/useGuide/LLaMAFactory/mutiple/?utm_source=LLaMA-Factory) (Chinese)
|
|
||||||
- [LLaMA Factory: Fine-tuning the DeepSeek-R1-Distill-Qwen-7B Model for News Classifier](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory_deepseek_r1_distill_7b) (Chinese)
|
- [LLaMA Factory: Fine-tuning the DeepSeek-R1-Distill-Qwen-7B Model for News Classifier](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory_deepseek_r1_distill_7b) (Chinese)
|
||||||
- [A One-Stop Code-Free Model Fine-Tuning \& Deployment Platform based on SageMaker and LLaMA-Factory](https://aws.amazon.com/cn/blogs/china/a-one-stop-code-free-model-fine-tuning-deployment-platform-based-on-sagemaker-and-llama-factory/) (Chinese)
|
- [A One-Stop Code-Free Model Fine-Tuning \& Deployment Platform based on SageMaker and LLaMA-Factory](https://aws.amazon.com/cn/blogs/china/a-one-stop-code-free-model-fine-tuning-deployment-platform-based-on-sagemaker-and-llama-factory/) (Chinese)
|
||||||
- [LLaMA Factory Multi-Modal Fine-Tuning Practice: Fine-Tuning Qwen2-VL for Personal Tourist Guide](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory_qwen2vl) (Chinese)
|
- [LLaMA Factory Multi-Modal Fine-Tuning Practice: Fine-Tuning Qwen2-VL for Personal Tourist Guide](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory_qwen2vl) (Chinese)
|
||||||
@@ -279,11 +287,10 @@ Read technical notes:
|
|||||||
| Model | Model size | Template |
|
| Model | Model size | Template |
|
||||||
| ----------------------------------------------------------------- | -------------------------------- | -------------------- |
|
| ----------------------------------------------------------------- | -------------------------------- | -------------------- |
|
||||||
| [BLOOM/BLOOMZ](https://huggingface.co/bigscience) | 560M/1.1B/1.7B/3B/7.1B/176B | - |
|
| [BLOOM/BLOOMZ](https://huggingface.co/bigscience) | 560M/1.1B/1.7B/3B/7.1B/176B | - |
|
||||||
| [Command R](https://huggingface.co/CohereForAI) | 35B/104B | cohere |
|
|
||||||
| [DeepSeek (LLM/Code/MoE)](https://huggingface.co/deepseek-ai) | 7B/16B/67B/236B | deepseek |
|
| [DeepSeek (LLM/Code/MoE)](https://huggingface.co/deepseek-ai) | 7B/16B/67B/236B | deepseek |
|
||||||
| [DeepSeek 3-3.2](https://huggingface.co/deepseek-ai) | 236B/671B | deepseek3 |
|
| [DeepSeek 3-3.2](https://huggingface.co/deepseek-ai) | 236B/671B | deepseek3 |
|
||||||
| [DeepSeek R1 (Distill)](https://huggingface.co/deepseek-ai) | 1.5B/7B/8B/14B/32B/70B/671B | deepseekr1 |
|
| [DeepSeek R1 (Distill)](https://huggingface.co/deepseek-ai) | 1.5B/7B/8B/14B/32B/70B/671B | deepseekr1 |
|
||||||
| [ERNIE-4.5](https://huggingface.co/baidu) | 0.3B/21B/300B | ernie/ernie_nothink |
|
| [ERNIE-4.5](https://huggingface.co/baidu) | 0.3B/21B/300B | ernie_nothink |
|
||||||
| [Falcon/Falcon H1](https://huggingface.co/tiiuae) | 0.5B/1.5B/3B/7B/11B/34B/40B/180B | falcon/falcon_h1 |
|
| [Falcon/Falcon H1](https://huggingface.co/tiiuae) | 0.5B/1.5B/3B/7B/11B/34B/40B/180B | falcon/falcon_h1 |
|
||||||
| [Gemma/Gemma 2/CodeGemma](https://huggingface.co/google) | 2B/7B/9B/27B | gemma/gemma2 |
|
| [Gemma/Gemma 2/CodeGemma](https://huggingface.co/google) | 2B/7B/9B/27B | gemma/gemma2 |
|
||||||
| [Gemma 3/Gemma 3n](https://huggingface.co/google) | 270M/1B/4B/6B/8B/12B/27B | gemma3/gemma3n |
|
| [Gemma 3/Gemma 3n](https://huggingface.co/google) | 270M/1B/4B/6B/8B/12B/27B | gemma3/gemma3n |
|
||||||
@@ -292,12 +299,13 @@ Read technical notes:
|
|||||||
| [GPT-2](https://huggingface.co/openai-community) | 0.1B/0.4B/0.8B/1.5B | - |
|
| [GPT-2](https://huggingface.co/openai-community) | 0.1B/0.4B/0.8B/1.5B | - |
|
||||||
| [GPT-OSS](https://huggingface.co/openai) | 20B/120B | gpt_oss |
|
| [GPT-OSS](https://huggingface.co/openai) | 20B/120B | gpt_oss |
|
||||||
| [Granite 3-4](https://huggingface.co/ibm-granite) | 1B/2B/3B/7B/8B | granite3/granite4 |
|
| [Granite 3-4](https://huggingface.co/ibm-granite) | 1B/2B/3B/7B/8B | granite3/granite4 |
|
||||||
| [Hunyuan (MT)](https://huggingface.co/tencent/) | 7B | hunyuan |
|
| [Hunyuan/Hunyuan1.5 (MT)](https://huggingface.co/tencent/) | 0.5B/1.8B/4B/7B/13B | hunyuan/hunyuan_small|
|
||||||
| [InternLM 2-3](https://huggingface.co/internlm) | 7B/8B/20B | intern2 |
|
| [InternLM 2-3](https://huggingface.co/internlm) | 7B/8B/20B | intern2 |
|
||||||
| [InternVL 2.5-3.5](https://huggingface.co/OpenGVLab) | 1B/2B/4B/8B/14B/30B/38B/78B/241B | intern_vl |
|
| [InternVL 2.5-3.5](https://huggingface.co/OpenGVLab) | 1B/2B/4B/8B/14B/30B/38B/78B/241B | intern_vl |
|
||||||
| [InternLM/Intern-S1-mini](https://huggingface.co/internlm/) | 8B | intern_s1 |
|
| [Intern-S1-mini](https://huggingface.co/internlm/) | 8B | intern_s1 |
|
||||||
| [Kimi-VL](https://huggingface.co/moonshotai) | 16B | kimi_vl |
|
| [Kimi-VL](https://huggingface.co/moonshotai) | 16B | kimi_vl |
|
||||||
| [Ling 2.0 (mini/flash)](https://huggingface.co/inclusionAI) | 16B/100B | bailing_v2 |
|
| [Ling 2.0 (mini/flash)](https://huggingface.co/inclusionAI) | 16B/100B | bailing_v2 |
|
||||||
|
| [LFM 2.5 (VL)](https://huggingface.co/LiquidAI) | 1.2B/1.6B | lfm2/lfm2_vl |
|
||||||
| [Llama](https://github.com/facebookresearch/llama) | 7B/13B/33B/65B | - |
|
| [Llama](https://github.com/facebookresearch/llama) | 7B/13B/33B/65B | - |
|
||||||
| [Llama 2](https://huggingface.co/meta-llama) | 7B/13B/70B | llama2 |
|
| [Llama 2](https://huggingface.co/meta-llama) | 7B/13B/70B | llama2 |
|
||||||
| [Llama 3-3.3](https://huggingface.co/meta-llama) | 1B/3B/8B/70B | llama3 |
|
| [Llama 3-3.3](https://huggingface.co/meta-llama) | 1B/3B/8B/70B | llama3 |
|
||||||
@@ -307,19 +315,21 @@ Read technical notes:
|
|||||||
| [LLaVA-NeXT](https://huggingface.co/llava-hf) | 7B/8B/13B/34B/72B/110B | llava_next |
|
| [LLaVA-NeXT](https://huggingface.co/llava-hf) | 7B/8B/13B/34B/72B/110B | llava_next |
|
||||||
| [LLaVA-NeXT-Video](https://huggingface.co/llava-hf) | 7B/34B | llava_next_video |
|
| [LLaVA-NeXT-Video](https://huggingface.co/llava-hf) | 7B/34B | llava_next_video |
|
||||||
| [MiMo](https://huggingface.co/XiaomiMiMo) | 7B/309B | mimo/mimo_v2 |
|
| [MiMo](https://huggingface.co/XiaomiMiMo) | 7B/309B | mimo/mimo_v2 |
|
||||||
| [MiniCPM 1-4.1](https://huggingface.co/openbmb) | 0.5B/1B/2B/4B/8B | cpm/cpm3/cpm4 |
|
| [MiniCPM 4/5](https://huggingface.co/openbmb) | 0.5B/1B/8B | cpm4/empty |
|
||||||
| [MiniCPM-o-2.6/MiniCPM-V-2.6](https://huggingface.co/openbmb) | 8B | minicpm_o/minicpm_v |
|
| [MiniCPM-o/MiniCPM-V 4.5](https://huggingface.co/openbmb) | 8B/9B | minicpm_o/minicpm_v |
|
||||||
|
| [MiniCPM-V 4.6](https://huggingface.co/openbmb) | 3B/8B | minicpm_v_4_6 |
|
||||||
| [MiniMax-M1/MiniMax-M2](https://huggingface.co/MiniMaxAI/models) | 229B/456B | minimax1/minimax2 |
|
| [MiniMax-M1/MiniMax-M2](https://huggingface.co/MiniMaxAI/models) | 229B/456B | minimax1/minimax2 |
|
||||||
| [Ministral 3](https://huggingface.co/mistralai) | 3B/8B/14B | ministral3 |
|
| [Ministral 3](https://huggingface.co/mistralai) | 3B/8B/14B | ministral3 |
|
||||||
| [Mistral/Mixtral](https://huggingface.co/mistralai) | 7B/8x7B/8x22B | mistral |
|
| [Mistral/Mixtral](https://huggingface.co/mistralai) | 7B/8x7B/8x22B | mistral |
|
||||||
| [OLMo](https://huggingface.co/allenai) | 1B/7B | - |
|
|
||||||
| [PaliGemma/PaliGemma2](https://huggingface.co/google) | 3B/10B/28B | paligemma |
|
| [PaliGemma/PaliGemma2](https://huggingface.co/google) | 3B/10B/28B | paligemma |
|
||||||
| [Phi-3/Phi-3.5](https://huggingface.co/microsoft) | 4B/14B | phi |
|
| [Phi-3/Phi-3.5](https://huggingface.co/microsoft) | 4B/14B | phi |
|
||||||
| [Phi-3-small](https://huggingface.co/microsoft) | 7B | phi_small |
|
| [Phi-3-small](https://huggingface.co/microsoft) | 7B | phi_small |
|
||||||
| [Phi-4](https://huggingface.co/microsoft) | 14B | phi4 |
|
| [Phi-4-mini/Phi-4](https://huggingface.co/microsoft) | 3.8B/14B | phi4_mini/phi4 |
|
||||||
| [Pixtral](https://huggingface.co/mistralai) | 12B | pixtral |
|
| [Pixtral](https://huggingface.co/mistralai) | 12B | pixtral |
|
||||||
| [Qwen (1-2.5) (Code/Math/MoE/QwQ)](https://huggingface.co/Qwen) | 0.5B/1.5B/3B/7B/14B/32B/72B/110B | qwen |
|
| [Qwen2 (Code/Math/MoE/QwQ)](https://huggingface.co/Qwen) | 0.5B/1.5B/3B/7B/14B/32B/72B/110B | qwen |
|
||||||
| [Qwen3 (MoE/Instruct/Thinking/Next)](https://huggingface.co/Qwen) | 0.6B/1.7B/4B/8B/14B/32B/80B/235B | qwen3/qwen3_nothink |
|
| [Qwen3 (MoE/Instruct/Thinking/Next)](https://huggingface.co/Qwen) | 0.6B/1.7B/4B/8B/14B/32B/80B/235B | qwen3/qwen3_nothink |
|
||||||
|
| [Qwen3.5](https://huggingface.co/Qwen) | 0.8B/2B/4B/9B/27B/35B/122B/397B | qwen3_5/qwen3_5_nothink |
|
||||||
|
| [Qwen3.6](https://huggingface.co/Qwen) | 27B/35B | qwen3_6 |
|
||||||
| [Qwen2-Audio](https://huggingface.co/Qwen) | 7B | qwen2_audio |
|
| [Qwen2-Audio](https://huggingface.co/Qwen) | 7B | qwen2_audio |
|
||||||
| [Qwen2.5-Omni](https://huggingface.co/Qwen) | 3B/7B | qwen2_omni |
|
| [Qwen2.5-Omni](https://huggingface.co/Qwen) | 3B/7B | qwen2_omni |
|
||||||
| [Qwen3-Omni](https://huggingface.co/Qwen) | 30B | qwen3_omni |
|
| [Qwen3-Omni](https://huggingface.co/Qwen) | 30B | qwen3_omni |
|
||||||
@@ -327,8 +337,7 @@ Read technical notes:
|
|||||||
| [Qwen3-VL](https://huggingface.co/Qwen) | 2B/4B/8B/30B/32B/235B | qwen3_vl |
|
| [Qwen3-VL](https://huggingface.co/Qwen) | 2B/4B/8B/30B/32B/235B | qwen3_vl |
|
||||||
| [Seed (OSS/Coder)](https://huggingface.co/ByteDance-Seed) | 8B/36B | seed_oss/seed_coder |
|
| [Seed (OSS/Coder)](https://huggingface.co/ByteDance-Seed) | 8B/36B | seed_oss/seed_coder |
|
||||||
| [StarCoder 2](https://huggingface.co/bigcode) | 3B/7B/15B | - |
|
| [StarCoder 2](https://huggingface.co/bigcode) | 3B/7B/15B | - |
|
||||||
| [VibeThinker-1.5B](https://huggingface.co/WeiboAI) | 1.5B | qwen3 |
|
| [TeleChat 2-2.5](https://huggingface.co/Tele-AI) | 3B/7B/35B/115B | telechat2 |
|
||||||
| [Yi/Yi-1.5 (Code)](https://huggingface.co/01-ai) | 1.5B/6B/9B/34B | yi |
|
|
||||||
| [Yuan 2](https://huggingface.co/IEITYuan) | 2B/51B/102B | yuan |
|
| [Yuan 2](https://huggingface.co/IEITYuan) | 2B/51B/102B | yuan |
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
@@ -474,7 +483,7 @@ huggingface-cli login
|
|||||||
|
|
||||||
| Mandatory | Minimum | Recommend |
|
| Mandatory | Minimum | Recommend |
|
||||||
| ------------ | ------- | --------- |
|
| ------------ | ------- | --------- |
|
||||||
| python | 3.9 | 3.10 |
|
| python | 3.11 | >=3.11 |
|
||||||
| torch | 2.0.0 | 2.6.0 |
|
| torch | 2.0.0 | 2.6.0 |
|
||||||
| torchvision | 0.15.0 | 0.21.0 |
|
| torchvision | 0.15.0 | 0.21.0 |
|
||||||
| transformers | 4.49.0 | 4.50.0 |
|
| transformers | 4.49.0 | 4.50.0 |
|
||||||
@@ -514,12 +523,13 @@ huggingface-cli login
|
|||||||
#### Install from Source
|
#### Install from Source
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
|
git clone --depth 1 https://github.com/hiyouga/LlamaFactory.git
|
||||||
cd LLaMA-Factory
|
cd LlamaFactory
|
||||||
pip install -e ".[metrics]"
|
pip install -e .
|
||||||
|
pip install -r requirements/metrics.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
Optional dependencies available: `metrics`, `deepspeed`. Install with: `pip install -e ".[metrics,deepspeed]"`
|
Optional dependencies available: `metrics`, `deepspeed`. Install with: `pip install -e . && pip install -r requirements/metrics.txt -r requirements/deepspeed.txt`
|
||||||
|
|
||||||
Additional dependencies for specific features are available in `examples/requirements/`.
|
Additional dependencies for specific features are available in `examples/requirements/`.
|
||||||
|
|
||||||
@@ -563,7 +573,24 @@ Try `dataloader_num_workers: 0` if you encounter `Can't pickle local object` err
|
|||||||
|
|
||||||
#### Install BitsAndBytes
|
#### Install BitsAndBytes
|
||||||
|
|
||||||
If you want to enable the quantized LoRA (QLoRA) on the Windows platform, you need to install a pre-built version of `bitsandbytes` library, which supports CUDA 11.1 to 12.2, please select the appropriate [release version](https://github.com/jllllll/bitsandbytes-windows-webui/releases/tag/wheels) based on your CUDA version.
|
To enable Quantized LoRA (QLoRA) on Windows, you need to install bitsandbytes.
|
||||||
|
|
||||||
|
For most users, it is recommended to install the latest official release:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install bitsandbytes
|
||||||
|
```
|
||||||
|
|
||||||
|
If you are using uv to manage your virtual environment, it is recommended to install bitsandbytes after installing the GPU-enabled version of PyTorch:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv pip install bitsandbytes --no-deps
|
||||||
|
```
|
||||||
|
|
||||||
|
[!IMPORTANT]
|
||||||
|
Pay attention to the CUDA Toolkit version when installing bitsandbytes. Official bitsandbytes releases are built for specific CUDA Toolkit versions. On Windows x86-64, separate builds are currently provided for CUDA 11.8–12.6 and CUDA 12.8–12.9. Support for NVIDIA RTX 50 Series GPUs (e.g., RTX 5060 Ti, sm_120) requires the CUDA 12.8–12.9 builds.
|
||||||
|
|
||||||
|
If your environment uses an older CUDA version, or you need compatibility with older Windows / PyTorch combinations, you can install the third-party precompiled Windows wheel:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.2.post2-py3-none-win_amd64.whl
|
pip install https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.2.post2-py3-none-win_amd64.whl
|
||||||
@@ -577,36 +604,25 @@ To enable FlashAttention-2 on the Windows platform, please use the script from [
|
|||||||
|
|
||||||
<details><summary>For Ascend NPU users</summary>
|
<details><summary>For Ascend NPU users</summary>
|
||||||
|
|
||||||
To install LLaMA Factory on Ascend NPU devices, please upgrade Python to version 3.10 or higher: `pip install -e . torch-npu==2.7.1`. Additionally, you need to install the **[Ascend CANN Toolkit and Kernels](https://www.hiascend.com/developer/download/community/result?module=cann)**. Please follow the [installation tutorial](https://www.hiascend.com/document/detail/en/CANNCommunityEdition/600alphaX/softwareinstall/instg/atlasdeploy_03_0031.html) or use the following commands:
|
To install LLaMA Factory on Ascend NPU devices, please upgrade Python to version 3.10 or higher: `pip install -r requirements/npu.txt`. Additionally, you need to install the **Ascend CANN Toolkit and Kernels**. Please follow the [installation tutorial](https://llamafactory.readthedocs.io/en/latest/multibackend/npu/npu_installation.html).
|
||||||
|
|
||||||
|
|
||||||
|
You can also download the pre-built Docker images:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# replace the url according to your CANN version and devices
|
# Docker Hub
|
||||||
# install CANN Toolkit
|
docker pull hiyouga/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
wget https://ascend-repo.obs.cn-east-2.myhuaweicloud.com/Milan-ASL/Milan-ASL%20V100R001C20SPC702/Ascend-cann-toolkit_8.0.0.alpha002_linux-"$(uname -i)".run
|
docker pull hiyouga/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A3-ubuntu-py3.11
|
||||||
bash Ascend-cann-toolkit_8.0.0.alpha002_linux-"$(uname -i)".run --install
|
docker pull hiyouga/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-openeuler-py3.11
|
||||||
|
docker pull hiyouga/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A3-openeuler-py3.11
|
||||||
|
|
||||||
# install CANN Kernels
|
# quay.io
|
||||||
wget https://ascend-repo.obs.cn-east-2.myhuaweicloud.com/Milan-ASL/Milan-ASL%20V100R001C20SPC702/Ascend-cann-kernels-910b_8.0.0.alpha002_linux-"$(uname -i)".run
|
docker pull quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
bash Ascend-cann-kernels-910b_8.0.0.alpha002_linux-"$(uname -i)".run --install
|
docker pull quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A3-ubuntu-py3.11
|
||||||
|
docker pull quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-openeuler-py3.11
|
||||||
# set env variables
|
docker pull quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A3-openeuler-py3.11
|
||||||
source /usr/local/Ascend/ascend-toolkit/set_env.sh
|
|
||||||
```
|
```
|
||||||
|
|
||||||
| Requirement | Minimum | Recommend |
|
|
||||||
| ------------ | ------- | -------------- |
|
|
||||||
| CANN | 8.0.RC1 | 8.0.0.alpha002 |
|
|
||||||
| torch | 2.1.0 | 2.7.1 |
|
|
||||||
| torch-npu | 2.1.0 | 2.7.1 |
|
|
||||||
| deepspeed | 0.13.2 | 0.13.2 |
|
|
||||||
| vllm-ascend | - | 0.7.3 |
|
|
||||||
|
|
||||||
Remember to use `ASCEND_RT_VISIBLE_DEVICES` instead of `CUDA_VISIBLE_DEVICES` to specify the device to use.
|
|
||||||
|
|
||||||
If you cannot infer model on NPU devices, try setting `do_sample: false` in the configurations.
|
|
||||||
|
|
||||||
Download the pre-built Docker images: [32GB](http://mirrors.cn-central-221.ovaijisuan.com/detail/130.html) | [64GB](http://mirrors.cn-central-221.ovaijisuan.com/detail/131.html)
|
|
||||||
|
|
||||||
#### Install BitsAndBytes
|
#### Install BitsAndBytes
|
||||||
|
|
||||||
To use QLoRA based on bitsandbytes on Ascend NPU, please follow these 3 steps:
|
To use QLoRA based on bitsandbytes on Ascend NPU, please follow these 3 steps:
|
||||||
@@ -675,10 +691,6 @@ See [examples/README.md](examples/README.md) for advanced usage (including distr
|
|||||||
llamafactory-cli webui
|
llamafactory-cli webui
|
||||||
```
|
```
|
||||||
|
|
||||||
### LLaMA Factory Online
|
|
||||||
|
|
||||||
Read our [documentation](https://docs.llamafactory.com.cn/docs/documents/quickstart/getstarted/?utm_source=LLaMA-Factory).
|
|
||||||
|
|
||||||
### Build Docker
|
### Build Docker
|
||||||
|
|
||||||
For CUDA users:
|
For CUDA users:
|
||||||
@@ -689,12 +701,28 @@ docker compose up -d
|
|||||||
docker compose exec llamafactory bash
|
docker compose exec llamafactory bash
|
||||||
```
|
```
|
||||||
|
|
||||||
For Ascend NPU users:
|
For Ascend NPU users (A2 with Ubuntu by default):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd docker/docker-npu/
|
cd docker/docker-npu/
|
||||||
docker compose up -d
|
docker compose up -d llamafactory-a2-ubuntu
|
||||||
docker compose exec llamafactory bash
|
docker compose exec llamafactory-a2-ubuntu bash
|
||||||
|
```
|
||||||
|
|
||||||
|
Other NPU variants can be started with their corresponding profiles and services:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# A3 with Ubuntu
|
||||||
|
docker compose --profile a3 up -d llamafactory-a3-ubuntu
|
||||||
|
docker compose exec llamafactory-a3-ubuntu bash
|
||||||
|
|
||||||
|
# A2 with openEuler
|
||||||
|
docker compose --profile openeuler up -d llamafactory-a2-openeuler
|
||||||
|
docker compose exec llamafactory-a2-openeuler bash
|
||||||
|
|
||||||
|
# A3 with openEuler
|
||||||
|
docker compose --profile a3-openeuler up -d llamafactory-a3-openeuler
|
||||||
|
docker compose exec llamafactory-a3-openeuler bash
|
||||||
```
|
```
|
||||||
|
|
||||||
For AMD ROCm users:
|
For AMD ROCm users:
|
||||||
@@ -852,7 +880,7 @@ If you have a project that should be incorporated, please contact via email or c
|
|||||||
1. Choi et al. FACT-GPT: Fact-Checking Augmentation via Claim Matching with LLMs. 2024. [[arxiv]](https://arxiv.org/abs/2402.05904)
|
1. Choi et al. FACT-GPT: Fact-Checking Augmentation via Claim Matching with LLMs. 2024. [[arxiv]](https://arxiv.org/abs/2402.05904)
|
||||||
1. Zhang et al. AutoMathText: Autonomous Data Selection with Language Models for Mathematical Texts. 2024. [[arxiv]](https://arxiv.org/abs/2402.07625)
|
1. Zhang et al. AutoMathText: Autonomous Data Selection with Language Models for Mathematical Texts. 2024. [[arxiv]](https://arxiv.org/abs/2402.07625)
|
||||||
1. Lyu et al. KnowTuning: Knowledge-aware Fine-tuning for Large Language Models. 2024. [[arxiv]](https://arxiv.org/abs/2402.11176)
|
1. Lyu et al. KnowTuning: Knowledge-aware Fine-tuning for Large Language Models. 2024. [[arxiv]](https://arxiv.org/abs/2402.11176)
|
||||||
1. Yang et al. LaCo: Large Language Model Pruning via Layer Collaps. 2024. [[arxiv]](https://arxiv.org/abs/2402.11187)
|
1. Yang et al. LaCo: Large Language Model Pruning via Layer Collapse. 2024. [[arxiv]](https://arxiv.org/abs/2402.11187)
|
||||||
1. Bhardwaj et al. Language Models are Homer Simpson! Safety Re-Alignment of Fine-tuned Language Models through Task Arithmetic. 2024. [[arxiv]](https://arxiv.org/abs/2402.11746)
|
1. Bhardwaj et al. Language Models are Homer Simpson! Safety Re-Alignment of Fine-tuned Language Models through Task Arithmetic. 2024. [[arxiv]](https://arxiv.org/abs/2402.11746)
|
||||||
1. Yang et al. Enhancing Empathetic Response Generation by Augmenting LLMs with Small-scale Empathetic Models. 2024. [[arxiv]](https://arxiv.org/abs/2402.11801)
|
1. Yang et al. Enhancing Empathetic Response Generation by Augmenting LLMs with Small-scale Empathetic Models. 2024. [[arxiv]](https://arxiv.org/abs/2402.11801)
|
||||||
1. Yi et al. Generation Meets Verification: Accelerating Large Language Model Inference with Smart Parallel Auto-Correct Decoding. ACL 2024 Findings. [[arxiv]](https://arxiv.org/abs/2402.11809)
|
1. Yi et al. Generation Meets Verification: Accelerating Large Language Model Inference with Smart Parallel Auto-Correct Decoding. ACL 2024 Findings. [[arxiv]](https://arxiv.org/abs/2402.11809)
|
||||||
@@ -946,7 +974,7 @@ If you have a project that should be incorporated, please contact via email or c
|
|||||||
|
|
||||||
This repository is licensed under the [Apache-2.0 License](LICENSE).
|
This repository is licensed under the [Apache-2.0 License](LICENSE).
|
||||||
|
|
||||||
Please follow the model licenses to use the corresponding model weights: [Baichuan 2](https://huggingface.co/baichuan-inc/Baichuan2-7B-Base/blob/main/Community%20License%20for%20Baichuan%202%20Model.pdf) / [BLOOM](https://huggingface.co/spaces/bigscience/license) / [ChatGLM3](https://github.com/THUDM/ChatGLM3/blob/main/MODEL_LICENSE) / [Command R](https://cohere.com/c4ai-cc-by-nc-license) / [DeepSeek](https://github.com/deepseek-ai/DeepSeek-LLM/blob/main/LICENSE-MODEL) / [Falcon](https://huggingface.co/tiiuae/falcon-180B/blob/main/LICENSE.txt) / [Gemma](https://ai.google.dev/gemma/terms) / [GLM-4](https://huggingface.co/THUDM/glm-4-9b/blob/main/LICENSE) / [GPT-2](https://github.com/openai/gpt-2/blob/master/LICENSE) / [Granite](LICENSE) / [Index](https://huggingface.co/IndexTeam/Index-1.9B/blob/main/LICENSE) / [InternLM](https://github.com/InternLM/InternLM#license) / [Llama](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) / [Llama 2](https://ai.meta.com/llama/license/) / [Llama 3](https://llama.meta.com/llama3/license/) / [Llama 4](https://github.com/meta-llama/llama-models/blob/main/models/llama4/LICENSE) / [MiniCPM](https://github.com/OpenBMB/MiniCPM/blob/main/MiniCPM%20Model%20License.md) / [Mistral/Mixtral/Pixtral](LICENSE) / [OLMo](LICENSE) / [Phi-1.5/Phi-2](https://huggingface.co/microsoft/phi-1_5/resolve/main/Research%20License.docx) / [Phi-3/Phi-4](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/blob/main/LICENSE) / [Qwen](https://github.com/QwenLM/Qwen/blob/main/Tongyi%20Qianwen%20LICENSE%20AGREEMENT) / [Skywork](https://huggingface.co/Skywork/Skywork-13B-base/blob/main/Skywork%20Community%20License.pdf) / [StarCoder 2](https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement) / [TeleChat2](https://huggingface.co/Tele-AI/telechat-7B/blob/main/TeleChat%E6%A8%A1%E5%9E%8B%E7%A4%BE%E5%8C%BA%E8%AE%B8%E5%8F%AF%E5%8D%8F%E8%AE%AE.pdf) / [XVERSE](https://github.com/xverse-ai/XVERSE-13B/blob/main/MODEL_LICENSE.pdf) / [Yi](https://huggingface.co/01-ai/Yi-6B/blob/main/LICENSE) / [Yi-1.5](LICENSE) / [Yuan 2](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/LICENSE-Yuan)
|
Please follow the model licenses to use the corresponding model weights: [BLOOM](https://huggingface.co/spaces/bigscience/license) / [DeepSeek](https://github.com/deepseek-ai/DeepSeek-LLM/blob/main/LICENSE-MODEL) / [Falcon](https://huggingface.co/tiiuae/falcon-180B/blob/main/LICENSE.txt) / [Gemma](https://ai.google.dev/gemma/terms) / [GLM-4](https://huggingface.co/THUDM/glm-4-9b/blob/main/LICENSE) / [GPT-2](https://github.com/openai/gpt-2/blob/master/LICENSE) / [Granite](LICENSE) / [InternLM](https://github.com/InternLM/InternLM#license) / [Llama](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) / [Llama 2](https://ai.meta.com/llama/license/) / [Llama 3](https://llama.meta.com/llama3/license/) / [Llama 4](https://github.com/meta-llama/llama-models/blob/main/models/llama4/LICENSE) / [MiniCPM](https://github.com/OpenBMB/MiniCPM/blob/main/MiniCPM%20Model%20License.md) / [Mistral/Mixtral/Pixtral](LICENSE) / [Phi-3/Phi-4](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/blob/main/LICENSE) / [Qwen](https://github.com/QwenLM/Qwen/blob/main/Tongyi%20Qianwen%20LICENSE%20AGREEMENT) / [StarCoder 2](https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement) / [TeleChat2](https://huggingface.co/Tele-AI/telechat-7B/blob/main/TeleChat%E6%A8%A1%E5%9E%8B%E7%A4%BE%E5%8C%BA%E8%AE%B8%E5%8F%AF%E5%8D%8F%E8%AE%AE.pdf) / [Yuan 2](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/LICENSE-Yuan)
|
||||||
|
|
||||||
## Citation
|
## Citation
|
||||||
|
|
||||||
@@ -967,7 +995,3 @@ If this work is helpful, please kindly cite as:
|
|||||||
## Acknowledgement
|
## Acknowledgement
|
||||||
|
|
||||||
This repo benefits from [PEFT](https://github.com/huggingface/peft), [TRL](https://github.com/huggingface/trl), [QLoRA](https://github.com/artidoro/qlora) and [FastChat](https://github.com/lm-sys/FastChat). Thanks for their wonderful works.
|
This repo benefits from [PEFT](https://github.com/huggingface/peft), [TRL](https://github.com/huggingface/trl), [QLoRA](https://github.com/artidoro/qlora) and [FastChat](https://github.com/lm-sys/FastChat). Thanks for their wonderful works.
|
||||||
|
|
||||||
## Star History
|
|
||||||
|
|
||||||

|
|
||||||
|
|||||||
162
README_zh.md
162
README_zh.md
@@ -15,13 +15,25 @@
|
|||||||
|
|
||||||
[](https://colab.research.google.com/drive/1d5KQtbemerlSDSxZIfAaWXhKr30QypiK?usp=sharing)
|
[](https://colab.research.google.com/drive/1d5KQtbemerlSDSxZIfAaWXhKr30QypiK?usp=sharing)
|
||||||
[](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory)
|
[](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory)
|
||||||
[](https://www.lab4ai.cn/course/detail?id=7c13e60f6137474eb40f6fd3983c0f46&utm_source=LLaMA-Factory)
|
|
||||||
[](https://www.llamafactory.com.cn/?utm_source=LLaMA-Factory)
|
|
||||||
[](https://huggingface.co/spaces/hiyouga/LLaMA-Board)
|
[](https://huggingface.co/spaces/hiyouga/LLaMA-Board)
|
||||||
[](https://modelscope.cn/studios/hiyouga/LLaMA-Board)
|
[](https://modelscope.cn/studios/hiyouga/LLaMA-Board)
|
||||||
[](https://novita.ai/templates-library/105981?sharer=88115474-394e-4bda-968e-b88e123d0c47)
|
[](https://novita.ai/templates-library/105981?sharer=88115474-394e-4bda-968e-b88e123d0c47)
|
||||||
|
|
||||||
### 获得[亚马逊](https://aws.amazon.com/cn/blogs/china/a-one-stop-code-free-model-fine-tuning-deployment-platform-based-on-sagemaker-and-llama-factory/)、[英伟达](https://developer.nvidia.cn/rtx/ai-toolkit)、[阿里云](https://help.aliyun.com/zh/pai/use-cases/fine-tune-a-llama-3-model-with-llama-factory)等的应用。
|
### 获得[亚马逊](https://aws.amazon.com/cn/blogs/china/a-one-stop-code-free-model-fine-tuning-deployment-platform-based-on-sagemaker-and-llama-factory/)、[英伟达](https://build.nvidia.com/spark/llama-factory)、[阿里云](https://help.aliyun.com/zh/pai/use-cases/fine-tune-a-llama-3-model-with-llama-factory)等的应用。
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
|
<div align="center" markdown="1">
|
||||||
|
|
||||||
|
### 欢迎关注我们全新的开源项目——<br>🐧 [PenguinHarness](https://github.com/Prism-Shadow/penguin-harness):只需 0.2 元的 Token,即可自动构建 Agent 的桌面级 Agent!
|
||||||
|
|
||||||
|
点击关注项目:https://github.com/Prism-Shadow/penguin-harness
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
https://github.com/user-attachments/assets/604eb626-0a5d-4a62-87e3-14ebade1cd5f
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
<div align="center" markdown="1">
|
<div align="center" markdown="1">
|
||||||
|
|
||||||
@@ -34,11 +46,11 @@
|
|||||||
|
|
||||||
### 使用零代码[命令行](#快速开始)与 [Web UI](#llama-board-可视化微调由-gradio-驱动) 轻松微调百余种大模型
|
### 使用零代码[命令行](#快速开始)与 [Web UI](#llama-board-可视化微调由-gradio-驱动) 轻松微调百余种大模型
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
👋 加入我们的[微信群](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/main.jpg)、[NPU 用户群](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/npu.jpg)、[大模型实验室群](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/lab4ai.jpg) 或 [LLaMA Factory Online 用户群](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/online.png)。
|
👋 加入我们的[微信群](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/main.jpg)和 [NPU 用户群](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/npu.jpg)。
|
||||||
|
|
||||||
\[ [English](README.md) | 中文 \]
|
\[ [English](README.md) | 中文 \]
|
||||||
|
|
||||||
@@ -52,16 +64,14 @@ https://github.com/user-attachments/assets/43b700c6-a178-41db-b1f8-8190a5d3fcfc
|
|||||||
开始云端训练:
|
开始云端训练:
|
||||||
- **Colab(免费)**:https://colab.research.google.com/drive/1d5KQtbemerlSDSxZIfAaWXhKr30QypiK?usp=sharing
|
- **Colab(免费)**:https://colab.research.google.com/drive/1d5KQtbemerlSDSxZIfAaWXhKr30QypiK?usp=sharing
|
||||||
- **PAI-DSW(免费试用)**:https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory
|
- **PAI-DSW(免费试用)**:https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory
|
||||||
- **LLaMA Factory Online(在线微调)**:https://www.llamafactory.com.cn/?utm_source=LLaMA-Factory
|
- **AMD GPU Cloud (免费试用)**: https://github.com/AMD-AIM/AMD_Developers_Notebooks/blob/main/zh/AMD_developer_LLaMAFactory_note_zh.md
|
||||||
- **九章智算云(算力优惠活动)**:https://docs.alayanew.com/docs/documents/useGuide/LLaMAFactory/mutiple/?utm_source=LLaMA-Factory
|
|
||||||
|
|
||||||
阅读技术文档:
|
阅读技术文档:
|
||||||
- **入门教程**:https://zhuanlan.zhihu.com/p/695287607
|
- **入门教程**:https://zhuanlan.zhihu.com/p/695287607
|
||||||
- **微调视频教程**:https://www.bilibili.com/video/BV1djgRzxEts/
|
- **微调视频教程**:https://www.bilibili.com/video/BV1djgRzxEts/
|
||||||
- **框架文档**:https://llamafactory.readthedocs.io/zh-cn/latest/
|
- **框架文档**:https://llamafactory.readthedocs.io/zh-cn/latest/
|
||||||
- **框架文档(昇腾 NPU)**:https://ascend.github.io/docs/sources/llamafactory/
|
- **框架文档(昇腾 NPU)**:https://llamafactory.readthedocs.io/zh-cn/latest/multibackend/npu/index.html
|
||||||
- **官方博客**:https://blog.llamafactory.net/
|
- **官方博客**:https://blog.llamafactory.net/
|
||||||
- **官方课程**:https://www.lab4ai.cn/course/detail?id=7c13e60f6137474eb40f6fd3983c0f46&utm_source=LLaMA-Factory
|
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> 除上述链接以外的其他网站均为未经许可的第三方网站,请小心甄别。
|
> 除上述链接以外的其他网站均为未经许可的第三方网站,请小心甄别。
|
||||||
@@ -80,7 +90,6 @@ https://github.com/user-attachments/assets/43b700c6-a178-41db-b1f8-8190a5d3fcfc
|
|||||||
- [数据准备](#数据准备)
|
- [数据准备](#数据准备)
|
||||||
- [快速开始](#快速开始)
|
- [快速开始](#快速开始)
|
||||||
- [LLaMA Board 可视化微调](#llama-board-可视化微调由-gradio-驱动)
|
- [LLaMA Board 可视化微调](#llama-board-可视化微调由-gradio-驱动)
|
||||||
- [LLaMA Factory Online 在线微调](#llama-factory-online-在线微调)
|
|
||||||
- [构建 Docker](#构建-docker)
|
- [构建 Docker](#构建-docker)
|
||||||
- [利用 vLLM 部署 OpenAI API](#利用-vllm-部署-openai-api)
|
- [利用 vLLM 部署 OpenAI API](#利用-vllm-部署-openai-api)
|
||||||
- [从魔搭社区下载](#从魔搭社区下载)
|
- [从魔搭社区下载](#从魔搭社区下载)
|
||||||
@@ -94,7 +103,7 @@ https://github.com/user-attachments/assets/43b700c6-a178-41db-b1f8-8190a5d3fcfc
|
|||||||
|
|
||||||
## 项目特色
|
## 项目特色
|
||||||
|
|
||||||
- **多种模型**:LLaMA、LLaVA、Mistral、Mixtral-MoE、Qwen、Qwen2-VL、DeepSeek、Yi、Gemma、ChatGLM、Phi 等等。
|
- **多种模型**:LLaMA、LLaVA、Mistral、Mixtral-MoE、Qwen3、Qwen3-VL、DeepSeek、Gemma、GLM、Phi 等等。
|
||||||
- **集成方法**:(增量)预训练、(多模态)指令监督微调、奖励模型训练、PPO 训练、DPO 训练、KTO 训练、ORPO 训练等等。
|
- **集成方法**:(增量)预训练、(多模态)指令监督微调、奖励模型训练、PPO 训练、DPO 训练、KTO 训练、ORPO 训练等等。
|
||||||
- **多种精度**:16 比特全参数微调、冻结微调、LoRA 微调和基于 AQLM/AWQ/GPTQ/LLM.int8/HQQ/EETQ 的 2/3/4/5/6/8 比特 QLoRA 微调。
|
- **多种精度**:16 比特全参数微调、冻结微调、LoRA 微调和基于 AQLM/AWQ/GPTQ/LLM.int8/HQQ/EETQ 的 2/3/4/5/6/8 比特 QLoRA 微调。
|
||||||
- **先进算法**:[GaLore](https://github.com/jiaweizzhao/GaLore)、[BAdam](https://github.com/Ledzy/BAdam)、[APOLLO](https://github.com/zhuhanqing/APOLLO)、[Adam-mini](https://github.com/zyushun/Adam-mini)、[Muon](https://github.com/KellerJordan/Muon)、[OFT](https://github.com/huggingface/peft/tree/main/src/peft/tuners/oft)、DoRA、LongLoRA、LLaMA Pro、Mixture-of-Depths、LoRA+、LoftQ 和 PiSSA。
|
- **先进算法**:[GaLore](https://github.com/jiaweizzhao/GaLore)、[BAdam](https://github.com/Ledzy/BAdam)、[APOLLO](https://github.com/zhuhanqing/APOLLO)、[Adam-mini](https://github.com/zyushun/Adam-mini)、[Muon](https://github.com/KellerJordan/Muon)、[OFT](https://github.com/huggingface/peft/tree/main/src/peft/tuners/oft)、DoRA、LongLoRA、LLaMA Pro、Mixture-of-Depths、LoRA+、LoftQ 和 PiSSA。
|
||||||
@@ -119,15 +128,13 @@ https://github.com/user-attachments/assets/43b700c6-a178-41db-b1f8-8190a5d3fcfc
|
|||||||
|
|
||||||
- 💡 [KTransformers Fine-Tuning × LLaMA Factory: 用2张4090级的GPU+CPU 微调 1000B规模的超大模型](https://swcil84qspu.feishu.cn/wiki/Z1sSwb2poijybxkyPEkcDG6enVc) (中文)
|
- 💡 [KTransformers Fine-Tuning × LLaMA Factory: 用2张4090级的GPU+CPU 微调 1000B规模的超大模型](https://swcil84qspu.feishu.cn/wiki/Z1sSwb2poijybxkyPEkcDG6enVc) (中文)
|
||||||
- 💡 [Easy Dataset × LLaMA Factory: 让大模型高效学习领域知识](https://buaa-act.feishu.cn/wiki/KY9xwTGs1iqHrRkjXBwcZP9WnL9)(中文)
|
- 💡 [Easy Dataset × LLaMA Factory: 让大模型高效学习领域知识](https://buaa-act.feishu.cn/wiki/KY9xwTGs1iqHrRkjXBwcZP9WnL9)(中文)
|
||||||
- [使用 LLaMA-Factory 微调心理健康大模型](https://www.lab4ai.cn/project/detail?id=25cce32ec131497b9e06a93336a0817f&type=project&utm_source=LLaMA-Factory)(中文)
|
- 💡 [DataFlow × LLaMA Factory: 利用数据准备流水线产出高质量数据训练 LLM](https://wcny4qa9krto.feishu.cn/wiki/LlMxweUAJimrmykRD5qcGuswnHd)(中文)| [English](https://wcny4qa9krto.feishu.cn/wiki/LWkkwTDBfiiRKqkDSvucG6yjnbW)
|
||||||
- [使用 LLaMA-Factory 构建 GPT-OSS 角色扮演模型](https://docs.llamafactory.com.cn/docs/documents/best-practice/gptroleplay/?utm_source=LLaMA-Factory)(中文)
|
- 💡 [DataFlex × LLaMA Factory: 构建在 LLaMA-Factory 之上的以数据为中心的动态训练系统](https://wcny4qa9krto.feishu.cn/wiki/H2A9wSsbCinzavkT2oyc2C5Vn0e)(中文)| [English](https://wcny4qa9krto.feishu.cn/wiki/OlREwPQWdi9K6ZkJNHIciLhtnkv)
|
||||||
- [基于 LLaMA-Factory 和 EasyR1 打造一站式无代码大模型强化学习和部署平台 LLM Model Hub](https://aws.amazon.com/cn/blogs/china/building-llm-model-hub-based-on-llamafactory-and-easyr1/)(中文)
|
- [基于 LLaMA-Factory 和 EasyR1 打造一站式无代码大模型强化学习和部署平台 LLM Model Hub](https://aws.amazon.com/cn/blogs/china/building-llm-model-hub-based-on-llamafactory-and-easyr1/)(中文)
|
||||||
- [通过亚马逊 SageMaker HyperPod 上的 LLaMA-Factory 增强多模态模型银行文档的视觉信息提取](https://aws.amazon.com/cn/blogs/machine-learning/how-apoidea-group-enhances-visual-information-extraction-from-banking-documents-with-multimodal-models-using-llama-factory-on-amazon-sagemaker-hyperpod/)(英文)
|
- [通过亚马逊 SageMaker HyperPod 上的 LLaMA-Factory 增强多模态模型银行文档的视觉信息提取](https://aws.amazon.com/cn/blogs/machine-learning/how-apoidea-group-enhances-visual-information-extraction-from-banking-documents-with-multimodal-models-using-llama-factory-on-amazon-sagemaker-hyperpod/)(英文)
|
||||||
|
|
||||||
<details><summary>全部博客</summary>
|
<details><summary>全部博客</summary>
|
||||||
|
|
||||||
- [使用 LLaMA-Factory 微调 Llama3.1-70B 医学诊断模型](https://docs.alayanew.com/docs/documents/bestPractice/bigModel/llama70B/?utm_source=LLaMA-Factory)(中文)
|
|
||||||
- [使用 LLaMA-Factory 微调 Qwen2.5-VL 实现自动驾驶场景微调](https://docs.alayanew.com/docs/documents/useGuide/LLaMAFactory/mutiple/?utm_source=LLaMA-Factory)(中文)
|
|
||||||
- [LLaMA Factory:微调 DeepSeek-R1-Distill-Qwen-7B 模型实现新闻标题分类器](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory_deepseek_r1_distill_7b)(中文)
|
- [LLaMA Factory:微调 DeepSeek-R1-Distill-Qwen-7B 模型实现新闻标题分类器](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory_deepseek_r1_distill_7b)(中文)
|
||||||
- [基于 Amazon SageMaker 和 LLaMA-Factory 打造一站式无代码模型微调部署平台 Model Hub](https://aws.amazon.com/cn/blogs/china/a-one-stop-code-free-model-fine-tuning-deployment-platform-based-on-sagemaker-and-llama-factory/)(中文)
|
- [基于 Amazon SageMaker 和 LLaMA-Factory 打造一站式无代码模型微调部署平台 Model Hub](https://aws.amazon.com/cn/blogs/china/a-one-stop-code-free-model-fine-tuning-deployment-platform-based-on-sagemaker-and-llama-factory/)(中文)
|
||||||
- [LLaMA Factory 多模态微调实践:微调 Qwen2-VL 构建文旅大模型](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory_qwen2vl)(中文)
|
- [LLaMA Factory 多模态微调实践:微调 Qwen2-VL 构建文旅大模型](https://gallery.pai-ml.com/#/preview/deepLearning/nlp/llama_factory_qwen2vl)(中文)
|
||||||
@@ -281,11 +288,10 @@ https://github.com/user-attachments/assets/43b700c6-a178-41db-b1f8-8190a5d3fcfc
|
|||||||
| 模型名 | 参数量 | Template |
|
| 模型名 | 参数量 | Template |
|
||||||
| ----------------------------------------------------------------- | -------------------------------- | -------------------- |
|
| ----------------------------------------------------------------- | -------------------------------- | -------------------- |
|
||||||
| [BLOOM/BLOOMZ](https://huggingface.co/bigscience) | 560M/1.1B/1.7B/3B/7.1B/176B | - |
|
| [BLOOM/BLOOMZ](https://huggingface.co/bigscience) | 560M/1.1B/1.7B/3B/7.1B/176B | - |
|
||||||
| [Command R](https://huggingface.co/CohereForAI) | 35B/104B | cohere |
|
|
||||||
| [DeepSeek (LLM/Code/MoE)](https://huggingface.co/deepseek-ai) | 7B/16B/67B/236B | deepseek |
|
| [DeepSeek (LLM/Code/MoE)](https://huggingface.co/deepseek-ai) | 7B/16B/67B/236B | deepseek |
|
||||||
| [DeepSeek 3-3.2](https://huggingface.co/deepseek-ai) | 236B/671B | deepseek3 |
|
| [DeepSeek 3-3.2](https://huggingface.co/deepseek-ai) | 236B/671B | deepseek3 |
|
||||||
| [DeepSeek R1 (Distill)](https://huggingface.co/deepseek-ai) | 1.5B/7B/8B/14B/32B/70B/671B | deepseekr1 |
|
| [DeepSeek R1 (Distill)](https://huggingface.co/deepseek-ai) | 1.5B/7B/8B/14B/32B/70B/671B | deepseekr1 |
|
||||||
| [ERNIE-4.5](https://huggingface.co/baidu) | 0.3B/21B/300B | ernie/ernie_nothink |
|
| [ERNIE-4.5](https://huggingface.co/baidu) | 0.3B/21B/300B | ernie_nothink |
|
||||||
| [Falcon/Falcon H1](https://huggingface.co/tiiuae) | 0.5B/1.5B/3B/7B/11B/34B/40B/180B | falcon/falcon_h1 |
|
| [Falcon/Falcon H1](https://huggingface.co/tiiuae) | 0.5B/1.5B/3B/7B/11B/34B/40B/180B | falcon/falcon_h1 |
|
||||||
| [Gemma/Gemma 2/CodeGemma](https://huggingface.co/google) | 2B/7B/9B/27B | gemma/gemma2 |
|
| [Gemma/Gemma 2/CodeGemma](https://huggingface.co/google) | 2B/7B/9B/27B | gemma/gemma2 |
|
||||||
| [Gemma 3/Gemma 3n](https://huggingface.co/google) | 270M/1B/4B/6B/8B/12B/27B | gemma3/gemma3n |
|
| [Gemma 3/Gemma 3n](https://huggingface.co/google) | 270M/1B/4B/6B/8B/12B/27B | gemma3/gemma3n |
|
||||||
@@ -294,12 +300,13 @@ https://github.com/user-attachments/assets/43b700c6-a178-41db-b1f8-8190a5d3fcfc
|
|||||||
| [GPT-2](https://huggingface.co/openai-community) | 0.1B/0.4B/0.8B/1.5B | - |
|
| [GPT-2](https://huggingface.co/openai-community) | 0.1B/0.4B/0.8B/1.5B | - |
|
||||||
| [GPT-OSS](https://huggingface.co/openai) | 20B/120B | gpt_oss |
|
| [GPT-OSS](https://huggingface.co/openai) | 20B/120B | gpt_oss |
|
||||||
| [Granite 3-4](https://huggingface.co/ibm-granite) | 1B/2B/3B/7B/8B | granite3/granite4 |
|
| [Granite 3-4](https://huggingface.co/ibm-granite) | 1B/2B/3B/7B/8B | granite3/granite4 |
|
||||||
| [Hunyuan (MT)](https://huggingface.co/tencent/) | 7B | hunyuan |
|
| [Hunyuan/Hunyuan1.5 (MT)](https://huggingface.co/tencent/) | 0.5B/1.8B/4B/7B/13B | hunyuan/hunyuan_small|
|
||||||
| [InternLM 2-3](https://huggingface.co/internlm) | 7B/8B/20B | intern2 |
|
| [InternLM 2-3](https://huggingface.co/internlm) | 7B/8B/20B | intern2 |
|
||||||
| [InternVL 2.5-3.5](https://huggingface.co/OpenGVLab) | 1B/2B/4B/8B/14B/30B/38B/78B/241B | intern_vl |
|
| [InternVL 2.5-3.5](https://huggingface.co/OpenGVLab) | 1B/2B/4B/8B/14B/30B/38B/78B/241B | intern_vl |
|
||||||
| [InternLM/Intern-S1-mini](https://huggingface.co/internlm/) | 8B | intern_s1 |
|
| [Intern-S1-mini](https://huggingface.co/internlm/) | 8B | intern_s1 |
|
||||||
| [Kimi-VL](https://huggingface.co/moonshotai) | 16B | kimi_vl |
|
| [Kimi-VL](https://huggingface.co/moonshotai) | 16B | kimi_vl |
|
||||||
| [Ling 2.0 (mini/flash)](https://huggingface.co/inclusionAI) | 16B/100B | bailing_v2 |
|
| [Ling 2.0 (mini/flash)](https://huggingface.co/inclusionAI) | 16B/100B | bailing_v2 |
|
||||||
|
| [LFM 2.5 (VL)](https://huggingface.co/LiquidAI) | 1.2B/1.6B | lfm2/lfm2_vl |
|
||||||
| [Llama](https://github.com/facebookresearch/llama) | 7B/13B/33B/65B | - |
|
| [Llama](https://github.com/facebookresearch/llama) | 7B/13B/33B/65B | - |
|
||||||
| [Llama 2](https://huggingface.co/meta-llama) | 7B/13B/70B | llama2 |
|
| [Llama 2](https://huggingface.co/meta-llama) | 7B/13B/70B | llama2 |
|
||||||
| [Llama 3-3.3](https://huggingface.co/meta-llama) | 1B/3B/8B/70B | llama3 |
|
| [Llama 3-3.3](https://huggingface.co/meta-llama) | 1B/3B/8B/70B | llama3 |
|
||||||
@@ -309,19 +316,21 @@ https://github.com/user-attachments/assets/43b700c6-a178-41db-b1f8-8190a5d3fcfc
|
|||||||
| [LLaVA-NeXT](https://huggingface.co/llava-hf) | 7B/8B/13B/34B/72B/110B | llava_next |
|
| [LLaVA-NeXT](https://huggingface.co/llava-hf) | 7B/8B/13B/34B/72B/110B | llava_next |
|
||||||
| [LLaVA-NeXT-Video](https://huggingface.co/llava-hf) | 7B/34B | llava_next_video |
|
| [LLaVA-NeXT-Video](https://huggingface.co/llava-hf) | 7B/34B | llava_next_video |
|
||||||
| [MiMo](https://huggingface.co/XiaomiMiMo) | 7B/309B | mimo/mimo_v2 |
|
| [MiMo](https://huggingface.co/XiaomiMiMo) | 7B/309B | mimo/mimo_v2 |
|
||||||
| [MiniCPM 1-4.1](https://huggingface.co/openbmb) | 0.5B/1B/2B/4B/8B | cpm/cpm3/cpm4 |
|
| [MiniCPM 4/5](https://huggingface.co/openbmb) | 0.5B/1B/8B | cpm4/empty |
|
||||||
| [MiniCPM-o-2.6/MiniCPM-V-2.6](https://huggingface.co/openbmb) | 8B | minicpm_o/minicpm_v |
|
| [MiniCPM-o/MiniCPM-V 4.5](https://huggingface.co/openbmb) | 8B/9B | minicpm_o/minicpm_v |
|
||||||
|
| [MiniCPM-V 4.6](https://huggingface.co/openbmb) | 3B/8B | minicpm_v_4_6 |
|
||||||
| [MiniMax-M1/MiniMax-M2](https://huggingface.co/MiniMaxAI/models) | 229B/456B | minimax1/minimax2 |
|
| [MiniMax-M1/MiniMax-M2](https://huggingface.co/MiniMaxAI/models) | 229B/456B | minimax1/minimax2 |
|
||||||
| [Ministral 3](https://huggingface.co/mistralai) | 3B/8B/14B | ministral3 |
|
| [Ministral 3](https://huggingface.co/mistralai) | 3B/8B/14B | ministral3 |
|
||||||
| [Mistral/Mixtral](https://huggingface.co/mistralai) | 7B/8x7B/8x22B | mistral |
|
| [Mistral/Mixtral](https://huggingface.co/mistralai) | 7B/8x7B/8x22B | mistral |
|
||||||
| [OLMo](https://huggingface.co/allenai) | 1B/7B | - |
|
|
||||||
| [PaliGemma/PaliGemma2](https://huggingface.co/google) | 3B/10B/28B | paligemma |
|
| [PaliGemma/PaliGemma2](https://huggingface.co/google) | 3B/10B/28B | paligemma |
|
||||||
| [Phi-3/Phi-3.5](https://huggingface.co/microsoft) | 4B/14B | phi |
|
| [Phi-3/Phi-3.5](https://huggingface.co/microsoft) | 4B/14B | phi |
|
||||||
| [Phi-3-small](https://huggingface.co/microsoft) | 7B | phi_small |
|
| [Phi-3-small](https://huggingface.co/microsoft) | 7B | phi_small |
|
||||||
| [Phi-4](https://huggingface.co/microsoft) | 14B | phi4 |
|
| [Phi-4-mini/Phi-4](https://huggingface.co/microsoft) | 3.8B/14B | phi4_mini/phi4 |
|
||||||
| [Pixtral](https://huggingface.co/mistralai) | 12B | pixtral |
|
| [Pixtral](https://huggingface.co/mistralai) | 12B | pixtral |
|
||||||
| [Qwen (1-2.5) (Code/Math/MoE/QwQ)](https://huggingface.co/Qwen) | 0.5B/1.5B/3B/7B/14B/32B/72B/110B | qwen |
|
| [Qwen2 (Code/Math/MoE/QwQ)](https://huggingface.co/Qwen) | 0.5B/1.5B/3B/7B/14B/32B/72B/110B | qwen |
|
||||||
| [Qwen3 (MoE/Instruct/Thinking/Next)](https://huggingface.co/Qwen) | 0.6B/1.7B/4B/8B/14B/32B/80B/235B | qwen3/qwen3_nothink |
|
| [Qwen3 (MoE/Instruct/Thinking/Next)](https://huggingface.co/Qwen) | 0.6B/1.7B/4B/8B/14B/32B/80B/235B | qwen3/qwen3_nothink |
|
||||||
|
| [Qwen3.5](https://huggingface.co/Qwen) | 0.8B/2B/4B/9B/27B/35B/122B/397B | qwen3_5/qwen3_5_nothink |
|
||||||
|
| [Qwen3.6](https://huggingface.co/Qwen) | 27B/35B | qwen3_6 |
|
||||||
| [Qwen2-Audio](https://huggingface.co/Qwen) | 7B | qwen2_audio |
|
| [Qwen2-Audio](https://huggingface.co/Qwen) | 7B | qwen2_audio |
|
||||||
| [Qwen2.5-Omni](https://huggingface.co/Qwen) | 3B/7B | qwen2_omni |
|
| [Qwen2.5-Omni](https://huggingface.co/Qwen) | 3B/7B | qwen2_omni |
|
||||||
| [Qwen3-Omni](https://huggingface.co/Qwen) | 30B | qwen3_omni |
|
| [Qwen3-Omni](https://huggingface.co/Qwen) | 30B | qwen3_omni |
|
||||||
@@ -329,8 +338,7 @@ https://github.com/user-attachments/assets/43b700c6-a178-41db-b1f8-8190a5d3fcfc
|
|||||||
| [Qwen3-VL](https://huggingface.co/Qwen) | 2B/4B/8B/30B/32B/235B | qwen3_vl |
|
| [Qwen3-VL](https://huggingface.co/Qwen) | 2B/4B/8B/30B/32B/235B | qwen3_vl |
|
||||||
| [Seed (OSS/Coder)](https://huggingface.co/ByteDance-Seed) | 8B/36B | seed_oss/seed_coder |
|
| [Seed (OSS/Coder)](https://huggingface.co/ByteDance-Seed) | 8B/36B | seed_oss/seed_coder |
|
||||||
| [StarCoder 2](https://huggingface.co/bigcode) | 3B/7B/15B | - |
|
| [StarCoder 2](https://huggingface.co/bigcode) | 3B/7B/15B | - |
|
||||||
| [VibeThinker-1.5B](https://huggingface.co/WeiboAI) | 1.5B | qwen3 |
|
| [TeleChat 2-2.5](https://huggingface.co/Tele-AI) | 3B/7B/35B/115B | telechat2 |
|
||||||
| [Yi/Yi-1.5 (Code)](https://huggingface.co/01-ai) | 1.5B/6B/9B/34B | yi |
|
|
||||||
| [Yuan 2](https://huggingface.co/IEITYuan) | 2B/51B/102B | yuan |
|
| [Yuan 2](https://huggingface.co/IEITYuan) | 2B/51B/102B | yuan |
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
@@ -476,7 +484,7 @@ huggingface-cli login
|
|||||||
|
|
||||||
| 必需项 | 至少 | 推荐 |
|
| 必需项 | 至少 | 推荐 |
|
||||||
| ------------ | ------- | --------- |
|
| ------------ | ------- | --------- |
|
||||||
| python | 3.9 | 3.10 |
|
| python | 3.11 | >=3.11 |
|
||||||
| torch | 2.0.0 | 2.6.0 |
|
| torch | 2.0.0 | 2.6.0 |
|
||||||
| torchvision | 0.15.0 | 0.21.0 |
|
| torchvision | 0.15.0 | 0.21.0 |
|
||||||
| transformers | 4.49.0 | 4.50.0 |
|
| transformers | 4.49.0 | 4.50.0 |
|
||||||
@@ -516,12 +524,13 @@ huggingface-cli login
|
|||||||
#### 从源码安装
|
#### 从源码安装
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
|
git clone --depth 1 https://github.com/hiyouga/LlamaFactory.git
|
||||||
cd LLaMA-Factory
|
cd LlamaFactory
|
||||||
pip install -e ".[metrics]"
|
pip install -e .
|
||||||
|
pip install -r requirements/metrics.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
可选的额外依赖项:`metrics`、`deepspeed`。使用 `pip install -e ".[metrics,deepspeed]"` 安装。
|
可选的额外依赖项:`metrics`、`deepspeed`。使用 `pip install -e . && pip install -r requirements/metrics.txt -r requirements/deepspeed.txt` 安装。
|
||||||
|
|
||||||
其他可选依赖项请参考 `examples/requirements/` 目录下的文件。
|
其他可选依赖项请参考 `examples/requirements/` 目录下的文件。
|
||||||
|
|
||||||
@@ -565,7 +574,24 @@ python -c "import torch; print(torch.cuda.is_available())"
|
|||||||
|
|
||||||
#### 安装 BitsAndBytes
|
#### 安装 BitsAndBytes
|
||||||
|
|
||||||
如果要在 Windows 平台上开启量化 LoRA(QLoRA),需要安装预编译的 `bitsandbytes` 库, 支持 CUDA 11.1 到 12.2, 请根据您的 CUDA 版本情况选择适合的[发布版本](https://github.com/jllllll/bitsandbytes-windows-webui/releases/tag/wheels)。
|
如果要在 Windows 平台上开启量化 LoRA(QLoRA),需要安装 bitsandbytes。
|
||||||
|
|
||||||
|
对于大多数用户,建议优先使用官方发布的最新版本:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install bitsandbytes
|
||||||
|
```
|
||||||
|
|
||||||
|
如果使用 uv 管理虚拟环境,建议在安装好 GPU 版本 PyTorch 之后,再执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv pip install bitsandbytes --no-deps
|
||||||
|
```
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> 安装 bitsandbytes 时,请注意 CUDA Toolkit 版本。bitsandbytes 的官方发布包是按不同 CUDA 版本分别构建的,Windows x86-64 目前提供了面向 CUDA 11.8–12.6 和 CUDA 12.8–12.9 的不同构建;其中支持 RTX 50 系列(如 RTX 5060 Ti,sm_120)的构建对应 CUDA 12.8–12.9。
|
||||||
|
|
||||||
|
若当前环境的 CUDA 版本较旧,或者需要兼容较老的 Windows / PyTorch 组合,可以使用第三方预编译版本:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.2.post2-py3-none-win_amd64.whl
|
pip install https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.2.post2-py3-none-win_amd64.whl
|
||||||
@@ -579,36 +605,24 @@ pip install https://github.com/jllllll/bitsandbytes-windows-webui/releases/downl
|
|||||||
|
|
||||||
<details><summary>昇腾 NPU 用户指南</summary>
|
<details><summary>昇腾 NPU 用户指南</summary>
|
||||||
|
|
||||||
在昇腾 NPU 设备上安装 LLaMA Factory 时,请升级 Python 到 3.10 及以上,并需要指定额外依赖项,使用 `pip install -e . torch-npu==2.7.1` 命令安装。此外,还需要安装 **[Ascend CANN Toolkit 与 Kernels](https://www.hiascend.com/developer/download/community/result?module=cann)**,安装方法请参考[安装教程](https://www.hiascend.com/document/detail/zh/CANNCommunityEdition/80RC2alpha002/quickstart/quickstart/quickstart_18_0004.html)或使用以下命令:
|
在昇腾 NPU 设备上安装 LLaMA Factory 时,请升级 Python 到 3.10 及以上,并需要指定额外依赖项,使用 `pip install -r requirements/npu.txt` 命令安装。此外,还需要安装 **Ascend CANN Toolkit 与 Kernels**,安装方法请参考[安装教程](https://llamafactory.readthedocs.io/zh-cn/latest/multibackend/npu/npu_installation.html)。
|
||||||
|
|
||||||
|
您可以直接下载预安装的最新docker镜像:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 请替换 URL 为 CANN 版本和设备型号对应的 URL
|
# Docker Hub
|
||||||
# 安装 CANN Toolkit
|
docker pull hiyouga/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
wget https://ascend-repo.obs.cn-east-2.myhuaweicloud.com/Milan-ASL/Milan-ASL%20V100R001C17SPC701/Ascend-cann-toolkit_8.0.RC1.alpha001_linux-"$(uname -i)".run
|
docker pull hiyouga/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A3-ubuntu-py3.11
|
||||||
bash Ascend-cann-toolkit_8.0.RC1.alpha001_linux-"$(uname -i)".run --install
|
docker pull hiyouga/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-openeuler-py3.11
|
||||||
|
docker pull hiyouga/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A3-openeuler-py3.11
|
||||||
|
|
||||||
# 安装 CANN Kernels
|
# quay.io
|
||||||
wget https://ascend-repo.obs.cn-east-2.myhuaweicloud.com/Milan-ASL/Milan-ASL%20V100R001C17SPC701/Ascend-cann-kernels-910b_8.0.RC1.alpha001_linux.run
|
docker pull quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
bash Ascend-cann-kernels-910b_8.0.RC1.alpha001_linux.run --install
|
docker pull quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A3-ubuntu-py3.11
|
||||||
|
docker pull quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-openeuler-py3.11
|
||||||
# 设置环境变量
|
docker pull quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A3-openeuler-py3.11
|
||||||
source /usr/local/Ascend/ascend-toolkit/set_env.sh
|
|
||||||
```
|
```
|
||||||
|
|
||||||
| 依赖项 | 至少 | 推荐 |
|
|
||||||
| ------------ | ------- | -------------- |
|
|
||||||
| CANN | 8.0.RC1 | 8.0.0.alpha002 |
|
|
||||||
| torch | 2.1.0 | 2.7.1 |
|
|
||||||
| torch-npu | 2.1.0 | 2.7.1 |
|
|
||||||
| deepspeed | 0.13.2 | 0.13.2 |
|
|
||||||
| vllm-ascend | - | 0.7.3 |
|
|
||||||
|
|
||||||
请使用 `ASCEND_RT_VISIBLE_DEVICES` 而非 `CUDA_VISIBLE_DEVICES` 来指定运算设备。
|
|
||||||
|
|
||||||
如果遇到无法正常推理的情况,请尝试设置 `do_sample: false`。
|
|
||||||
|
|
||||||
下载预构建 Docker 镜像:[32GB](http://mirrors.cn-central-221.ovaijisuan.com/detail/130.html) | [64GB](http://mirrors.cn-central-221.ovaijisuan.com/detail/131.html)
|
|
||||||
|
|
||||||
#### 安装 BitsAndBytes
|
#### 安装 BitsAndBytes
|
||||||
|
|
||||||
如果要在 Ascend NPU 上进行基于 bitsandbytes 的 QLoRA 量化微调,请执行如下步骤:
|
如果要在 Ascend NPU 上进行基于 bitsandbytes 的 QLoRA 量化微调,请执行如下步骤:
|
||||||
@@ -677,10 +691,6 @@ llamafactory-cli export examples/merge_lora/qwen3_lora_sft.yaml
|
|||||||
llamafactory-cli webui
|
llamafactory-cli webui
|
||||||
```
|
```
|
||||||
|
|
||||||
### LLaMA Factory Online 在线微调
|
|
||||||
|
|
||||||
详情阅读该[文档](https://docs.llamafactory.com.cn/docs/documents/quickstart/getstarted/?utm_source=LLaMA-Factory)。
|
|
||||||
|
|
||||||
### 构建 Docker
|
### 构建 Docker
|
||||||
|
|
||||||
CUDA 用户:
|
CUDA 用户:
|
||||||
@@ -691,12 +701,28 @@ docker compose up -d
|
|||||||
docker compose exec llamafactory bash
|
docker compose exec llamafactory bash
|
||||||
```
|
```
|
||||||
|
|
||||||
昇腾 NPU 用户:
|
昇腾 NPU 用户(默认使用 A2 和 Ubuntu):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd docker/docker-npu/
|
cd docker/docker-npu/
|
||||||
docker compose up -d
|
docker compose up -d llamafactory-a2-ubuntu
|
||||||
docker compose exec llamafactory bash
|
docker compose exec llamafactory-a2-ubuntu bash
|
||||||
|
```
|
||||||
|
|
||||||
|
其他 NPU 组合可以通过对应的 profile 和服务启动:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# A3 + Ubuntu
|
||||||
|
docker compose --profile a3 up -d llamafactory-a3-ubuntu
|
||||||
|
docker compose exec llamafactory-a3-ubuntu bash
|
||||||
|
|
||||||
|
# A2 + openEuler
|
||||||
|
docker compose --profile openeuler up -d llamafactory-a2-openeuler
|
||||||
|
docker compose exec llamafactory-a2-openeuler bash
|
||||||
|
|
||||||
|
# A3 + openEuler
|
||||||
|
docker compose --profile a3-openeuler up -d llamafactory-a3-openeuler
|
||||||
|
docker compose exec llamafactory-a3-openeuler bash
|
||||||
```
|
```
|
||||||
|
|
||||||
AMD ROCm 用户:
|
AMD ROCm 用户:
|
||||||
@@ -857,7 +883,7 @@ swanlab_run_name: test_run # 可选
|
|||||||
1. Choi et al. FACT-GPT: Fact-Checking Augmentation via Claim Matching with LLMs. 2024. [[arxiv]](https://arxiv.org/abs/2402.05904)
|
1. Choi et al. FACT-GPT: Fact-Checking Augmentation via Claim Matching with LLMs. 2024. [[arxiv]](https://arxiv.org/abs/2402.05904)
|
||||||
1. Zhang et al. AutoMathText: Autonomous Data Selection with Language Models for Mathematical Texts. 2024. [[arxiv]](https://arxiv.org/abs/2402.07625)
|
1. Zhang et al. AutoMathText: Autonomous Data Selection with Language Models for Mathematical Texts. 2024. [[arxiv]](https://arxiv.org/abs/2402.07625)
|
||||||
1. Lyu et al. KnowTuning: Knowledge-aware Fine-tuning for Large Language Models. 2024. [[arxiv]](https://arxiv.org/abs/2402.11176)
|
1. Lyu et al. KnowTuning: Knowledge-aware Fine-tuning for Large Language Models. 2024. [[arxiv]](https://arxiv.org/abs/2402.11176)
|
||||||
1. Yang et al. LaCo: Large Language Model Pruning via Layer Collaps. 2024. [[arxiv]](https://arxiv.org/abs/2402.11187)
|
1. Yang et al. LaCo: Large Language Model Pruning via Layer Collapse. 2024. [[arxiv]](https://arxiv.org/abs/2402.11187)
|
||||||
1. Bhardwaj et al. Language Models are Homer Simpson! Safety Re-Alignment of Fine-tuned Language Models through Task Arithmetic. 2024. [[arxiv]](https://arxiv.org/abs/2402.11746)
|
1. Bhardwaj et al. Language Models are Homer Simpson! Safety Re-Alignment of Fine-tuned Language Models through Task Arithmetic. 2024. [[arxiv]](https://arxiv.org/abs/2402.11746)
|
||||||
1. Yang et al. Enhancing Empathetic Response Generation by Augmenting LLMs with Small-scale Empathetic Models. 2024. [[arxiv]](https://arxiv.org/abs/2402.11801)
|
1. Yang et al. Enhancing Empathetic Response Generation by Augmenting LLMs with Small-scale Empathetic Models. 2024. [[arxiv]](https://arxiv.org/abs/2402.11801)
|
||||||
1. Yi et al. Generation Meets Verification: Accelerating Large Language Model Inference with Smart Parallel Auto-Correct Decoding. ACL 2024 Findings. [[arxiv]](https://arxiv.org/abs/2402.11809)
|
1. Yi et al. Generation Meets Verification: Accelerating Large Language Model Inference with Smart Parallel Auto-Correct Decoding. ACL 2024 Findings. [[arxiv]](https://arxiv.org/abs/2402.11809)
|
||||||
@@ -950,7 +976,7 @@ swanlab_run_name: test_run # 可选
|
|||||||
|
|
||||||
本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源。
|
本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源。
|
||||||
|
|
||||||
使用模型权重时,请遵循对应的模型协议:[Baichuan 2](https://huggingface.co/baichuan-inc/Baichuan2-7B-Base/blob/main/Community%20License%20for%20Baichuan%202%20Model.pdf) / [BLOOM](https://huggingface.co/spaces/bigscience/license) / [ChatGLM3](https://github.com/THUDM/ChatGLM3/blob/main/MODEL_LICENSE) / [Command R](https://cohere.com/c4ai-cc-by-nc-license) / [DeepSeek](https://github.com/deepseek-ai/DeepSeek-LLM/blob/main/LICENSE-MODEL) / [Falcon](https://huggingface.co/tiiuae/falcon-180B/blob/main/LICENSE.txt) / [Gemma](https://ai.google.dev/gemma/terms) / [GLM-4](https://huggingface.co/THUDM/glm-4-9b/blob/main/LICENSE) / [GPT-2](https://github.com/openai/gpt-2/blob/master/LICENSE) / [Granite](LICENSE) / [Index](https://huggingface.co/IndexTeam/Index-1.9B/blob/main/LICENSE) / [InternLM](https://github.com/InternLM/InternLM#license) / [Llama](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) / [Llama 2](https://ai.meta.com/llama/license/) / [Llama 3](https://llama.meta.com/llama3/license/) / [Llama 4](https://github.com/meta-llama/llama-models/blob/main/models/llama4/LICENSE) / [MiniCPM](https://github.com/OpenBMB/MiniCPM/blob/main/MiniCPM%20Model%20License.md) / [Mistral/Mixtral/Pixtral](LICENSE) / [OLMo](LICENSE) / [Phi-1.5/Phi-2](https://huggingface.co/microsoft/phi-1_5/resolve/main/Research%20License.docx) / [Phi-3/Phi-4](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/blob/main/LICENSE) / [Qwen](https://github.com/QwenLM/Qwen/blob/main/Tongyi%20Qianwen%20LICENSE%20AGREEMENT) / [Skywork](https://huggingface.co/Skywork/Skywork-13B-base/blob/main/Skywork%20Community%20License.pdf) / [StarCoder 2](https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement) / [TeleChat2](https://huggingface.co/Tele-AI/telechat-7B/blob/main/TeleChat%E6%A8%A1%E5%9E%8B%E7%A4%BE%E5%8C%BA%E8%AE%B8%E5%8F%AF%E5%8D%8F%E8%AE%AE.pdf) / [XVERSE](https://github.com/xverse-ai/XVERSE-13B/blob/main/MODEL_LICENSE.pdf) / [Yi](https://huggingface.co/01-ai/Yi-6B/blob/main/LICENSE) / [Yi-1.5](LICENSE) / [Yuan 2](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/LICENSE-Yuan)
|
使用模型权重时,请遵循对应的模型协议:[BLOOM](https://huggingface.co/spaces/bigscience/license)/ [DeepSeek](https://github.com/deepseek-ai/DeepSeek-LLM/blob/main/LICENSE-MODEL) / [Falcon](https://huggingface.co/tiiuae/falcon-180B/blob/main/LICENSE.txt) / [Gemma](https://ai.google.dev/gemma/terms) / [GLM-4](https://huggingface.co/THUDM/glm-4-9b/blob/main/LICENSE) / [GPT-2](https://github.com/openai/gpt-2/blob/master/LICENSE) / [Granite](LICENSE) / [InternLM](https://github.com/InternLM/InternLM#license) / [Llama](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) / [Llama 2](https://ai.meta.com/llama/license/) / [Llama 3](https://llama.meta.com/llama3/license/) / [Llama 4](https://github.com/meta-llama/llama-models/blob/main/models/llama4/LICENSE) / [MiniCPM](https://github.com/OpenBMB/MiniCPM/blob/main/MiniCPM%20Model%20License.md) / [Mistral/Mixtral/Pixtral](LICENSE) / [Phi-3/Phi-4](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/blob/main/LICENSE) / [Qwen](https://github.com/QwenLM/Qwen/blob/main/Tongyi%20Qianwen%20LICENSE%20AGREEMENT) / [StarCoder 2](https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement) / [TeleChat2](https://huggingface.co/Tele-AI/telechat-7B/blob/main/TeleChat%E6%A8%A1%E5%9E%8B%E7%A4%BE%E5%8C%BA%E8%AE%B8%E5%8F%AF%E5%8D%8F%E8%AE%AE.pdf) / [Yuan 2](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/LICENSE-Yuan)
|
||||||
|
|
||||||
## 引用
|
## 引用
|
||||||
|
|
||||||
@@ -971,7 +997,3 @@ swanlab_run_name: test_run # 可选
|
|||||||
## 致谢
|
## 致谢
|
||||||
|
|
||||||
本项目受益于 [PEFT](https://github.com/huggingface/peft)、[TRL](https://github.com/huggingface/trl)、[QLoRA](https://github.com/artidoro/qlora) 和 [FastChat](https://github.com/lm-sys/FastChat),感谢以上诸位作者的付出。
|
本项目受益于 [PEFT](https://github.com/huggingface/peft)、[TRL](https://github.com/huggingface/trl)、[QLoRA](https://github.com/artidoro/qlora) 和 [FastChat](https://github.com/lm-sys/FastChat),感谢以上诸位作者的付出。
|
||||||
|
|
||||||
## Star History
|
|
||||||
|
|
||||||

|
|
||||||
|
|||||||
@@ -236,6 +236,13 @@
|
|||||||
"ms_hub_url": "AI-ModelScope/sharegpt_gpt4",
|
"ms_hub_url": "AI-ModelScope/sharegpt_gpt4",
|
||||||
"formatting": "sharegpt"
|
"formatting": "sharegpt"
|
||||||
},
|
},
|
||||||
|
"sgsc_b2b_entities": {
|
||||||
|
"hf_hub_url": "Nooxus-AI/NOO-Verified-Global-Entities",
|
||||||
|
"formatting": "sharegpt",
|
||||||
|
"columns": {
|
||||||
|
"messages": "messages"
|
||||||
|
}
|
||||||
|
},
|
||||||
"ultrachat_200k": {
|
"ultrachat_200k": {
|
||||||
"hf_hub_url": "HuggingFaceH4/ultrachat_200k",
|
"hf_hub_url": "HuggingFaceH4/ultrachat_200k",
|
||||||
"ms_hub_url": "AI-ModelScope/ultrachat_200k",
|
"ms_hub_url": "AI-ModelScope/ultrachat_200k",
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -32,7 +32,8 @@ RUN pip config set global.index-url "${PIP_INDEX}" && \
|
|||||||
COPY . /app
|
COPY . /app
|
||||||
|
|
||||||
# Install LLaMA Factory
|
# Install LLaMA Factory
|
||||||
RUN pip install --no-cache-dir --no-build-isolation -e ".[metrics,deepspeed]"
|
RUN pip install --no-cache-dir --no-build-isolation -e . && \
|
||||||
|
pip install --no-cache-dir --no-build-isolation -r requirements/metrics.txt -r requirements/deepspeed.txt
|
||||||
|
|
||||||
# Rebuild flash attention
|
# Rebuild flash attention
|
||||||
RUN if [ "${INSTALL_FLASHATTN}" == "true" ]; then \
|
RUN if [ "${INSTALL_FLASHATTN}" == "true" ]; then \
|
||||||
|
|||||||
85
docker/docker-cuda/Dockerfile.mbridge
Normal file
85
docker/docker-cuda/Dockerfile.mbridge
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
# LLaMA-Factory + Megatron Bridge (CUDA) runtime
|
||||||
|
# Mirrors the verified host env: Python 3.12, PyTorch 2.12.1+cu126,
|
||||||
|
# TransformerEngine 2.17, megatron-core 0.18, megatron-bridge 0.5.
|
||||||
|
#
|
||||||
|
# CUDA user-mode libs come from the PyTorch cu126 wheels (same as the host venv).
|
||||||
|
# Layers are intentionally few (helps vfs / nested-docker disk usage).
|
||||||
|
#
|
||||||
|
# Build from repo root:
|
||||||
|
# bash docker/docker-cuda/build-megatron.sh
|
||||||
|
|
||||||
|
ARG BASE_IMAGE=ubuntu:24.04
|
||||||
|
FROM ${BASE_IMAGE}
|
||||||
|
|
||||||
|
ARG PIP_INDEX=https://mirrors.aliyun.com/pypi/simple
|
||||||
|
ARG PYPI_TRUSTED_HOST=mirrors.aliyun.com
|
||||||
|
ARG TORCH_INDEX=https://download.pytorch.org/whl/cu126
|
||||||
|
ARG APT_MIRROR=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
|
||||||
|
|
||||||
|
ENV DEBIAN_FRONTEND=noninteractive \
|
||||||
|
PIP_ROOT_USER_ACTION=ignore \
|
||||||
|
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||||
|
PIP_BREAK_SYSTEM_PACKAGES=1 \
|
||||||
|
PIP_CONSTRAINT="" \
|
||||||
|
MAX_JOBS=8 \
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
VLLM_WORKER_MULTIPROC_METHOD=spawn \
|
||||||
|
DISABLE_VERSION_CHECK=1 \
|
||||||
|
USE_MEGATRON_BRIDGE=1 \
|
||||||
|
GRADIO_SERVER_PORT=7860 \
|
||||||
|
API_PORT=8000 \
|
||||||
|
http_proxy= \
|
||||||
|
https_proxy=
|
||||||
|
|
||||||
|
SHELL ["/bin/bash", "-c"]
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# System deps + Ubuntu Python 3.12
|
||||||
|
RUN if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \
|
||||||
|
sed -i "s|http://archive.ubuntu.com/ubuntu|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu|${APT_MIRROR}|g" /etc/apt/sources.list.d/ubuntu.sources; \
|
||||||
|
elif [ -f /etc/apt/sources.list ]; then \
|
||||||
|
sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" /etc/apt/sources.list; \
|
||||||
|
fi && \
|
||||||
|
apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates curl git vim wget \
|
||||||
|
build-essential ninja-build cmake libgomp1 zip unzip \
|
||||||
|
python3 python3-pip python3-dev python3-venv && \
|
||||||
|
ln -sf /usr/bin/python3 /usr/bin/python && \
|
||||||
|
rm -rf /var/lib/apt/lists/* && \
|
||||||
|
pip install --no-cache-dir --upgrade pip setuptools wheel packaging ninja pybind11 \
|
||||||
|
--trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PIP_INDEX}
|
||||||
|
|
||||||
|
COPY . /app
|
||||||
|
|
||||||
|
# PyTorch + TE + Megatron Bridge + LLaMA-Factory in one layer
|
||||||
|
RUN pip install --no-cache-dir \
|
||||||
|
torch==2.12.1 torchvision==0.27.1 torchaudio==2.11.0 \
|
||||||
|
--index-url ${TORCH_INDEX} && \
|
||||||
|
pip install --no-cache-dir --no-build-isolation \
|
||||||
|
"transformer-engine[pytorch]==2.17.0" \
|
||||||
|
--trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PIP_INDEX} && \
|
||||||
|
pip install --no-cache-dir --no-build-isolation \
|
||||||
|
"megatron-bridge==0.5.0" \
|
||||||
|
--trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PIP_INDEX} && \
|
||||||
|
pip install --no-cache-dir --no-build-isolation -e . \
|
||||||
|
--trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PIP_INDEX} && \
|
||||||
|
pip install --no-cache-dir --no-build-isolation \
|
||||||
|
-r requirements/metrics.txt \
|
||||||
|
--trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PIP_INDEX} && \
|
||||||
|
pip install --no-cache-dir --no-build-isolation \
|
||||||
|
"megatron-bridge==0.5.0" \
|
||||||
|
--trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PIP_INDEX} && \
|
||||||
|
python - <<'PY'
|
||||||
|
import torch
|
||||||
|
import megatron.core
|
||||||
|
import transformer_engine
|
||||||
|
from megatron.bridge import AutoBridge # noqa: F401
|
||||||
|
import llamafactory
|
||||||
|
print("torch", torch.__version__, "cuda", torch.version.cuda)
|
||||||
|
print("te", transformer_engine.__version__)
|
||||||
|
print("megatron-bridge import ok")
|
||||||
|
PY
|
||||||
|
|
||||||
|
EXPOSE 7860 8000
|
||||||
|
CMD ["bash"]
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
# NVIDIA official image (ubuntu-22.04 + cuda-12.4 + python-3.10)
|
# NVIDIA official image (ubuntu-24.04 + cuda-12.9.1 + python-3.12)
|
||||||
# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html
|
# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-25-06.html
|
||||||
FROM nvcr.io/nvidia/pytorch:24.05-py3
|
FROM nvcr.io/nvidia/pytorch:25.06-py3
|
||||||
|
|
||||||
ENV DEBIAN_FRONTEND=noninteractive
|
ENV DEBIAN_FRONTEND=noninteractive
|
||||||
ENV PIP_ROOT_USER_ACTION=ignore
|
ENV PIP_ROOT_USER_ACTION=ignore
|
||||||
ENV PYPI_MIRROR=https://mirrors.aliyun.com/pypi/simple/
|
ENV PYPI_MIRROR=https://mirrors.aliyun.com/pypi/simple/
|
||||||
ENV PYPI_TRUSTED_HOST=mirrors.aliyun.com
|
ENV PYPI_TRUSTED_HOST=mirrors.aliyun.com
|
||||||
ENV APT_MIRROR=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
|
ENV APT_MIRROR=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
|
||||||
|
ENV PIP_CONSTRAINT=""
|
||||||
|
|
||||||
RUN pip install --upgrade pip setuptools wheel "hatchling>=1.18.0" editables --trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PYPI_MIRROR}
|
RUN pip install --upgrade pip setuptools wheel "hatchling>=1.18.0" editables --trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PYPI_MIRROR}
|
||||||
|
|
||||||
@@ -14,20 +15,14 @@ RUN pip uninstall -y torch torchvision torch-tensorrt \
|
|||||||
flash_attn transformer-engine \
|
flash_attn transformer-engine \
|
||||||
cudf dask-cuda cugraph cugraph-service-server cuml raft-dask cugraph-dgl cugraph-pyg dask-cudf
|
cudf dask-cuda cugraph cugraph-service-server cuml raft-dask cugraph-dgl cugraph-pyg dask-cudf
|
||||||
|
|
||||||
RUN pip install torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0 --index-url https://download.pytorch.org/whl/cu124
|
RUN pip install torch==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cu129
|
||||||
|
|
||||||
RUN pip uninstall -y opencv opencv-python opencv-python-headless && \
|
RUN pip uninstall -y opencv opencv-python opencv-python-headless && \
|
||||||
rm -rf /usr/local/lib/python3.10/dist-packages/cv2/ && \
|
rm -rf /usr/local/lib/python3.12/dist-packages/cv2/ && \
|
||||||
pip install opencv-python-headless==4.11.0.86 --trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PYPI_MIRROR}
|
pip install opencv-python-headless==4.11.0.86 --trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PYPI_MIRROR}
|
||||||
|
|
||||||
RUN pip install "numpy==1.26.4" "optree>=0.13.0" "spacy==3.7.5" "weasel==0.4.1" \
|
RUN pip install --trusted-host mirrors.aliyun.com --index-url ${PYPI_MIRROR} \
|
||||||
transformer-engine[pytorch]==2.2.0 megatron-core==0.13.0 deepspeed==0.16.4 \
|
"megatron-core>=0.13.0,<0.14.0" "deepspeed==0.16.4"
|
||||||
--trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PYPI_MIRROR}
|
|
||||||
|
|
||||||
RUN pip install https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.2.post1/flash_attn-2.7.2.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
|
|
||||||
|
|
||||||
# RUN pip install vllm==0.8.4 \
|
|
||||||
# --trusted-host ${PYPI_TRUSTED_HOST} --index-url ${PYPI_MIRROR}
|
|
||||||
|
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
@@ -37,6 +32,8 @@ RUN pip uninstall -y apex && \
|
|||||||
pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation \
|
pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation \
|
||||||
--config-settings "--build-option=--cpp_ext --cuda_ext --parallel 32" ${apex_url}
|
--config-settings "--build-option=--cpp_ext --cuda_ext --parallel 32" ${apex_url}
|
||||||
|
|
||||||
|
RUN pip install --no-build-isolation transformer_engine[pytorch]
|
||||||
|
|
||||||
RUN rm -rf /build
|
RUN rm -rf /build
|
||||||
WORKDIR /workspace
|
WORKDIR /workspace
|
||||||
|
|
||||||
@@ -53,14 +50,17 @@ RUN apt-get update && apt-get install -y zip
|
|||||||
RUN apt-get install -y openjdk-21-jdk
|
RUN apt-get install -y openjdk-21-jdk
|
||||||
ENV JAVA_HOME /usr/lib/jvm/java-21-openjdk-amd64
|
ENV JAVA_HOME /usr/lib/jvm/java-21-openjdk-amd64
|
||||||
|
|
||||||
# pip install LLaMA-Factory
|
ARG REPO_URL=https://github.com/hiyouga/LlamaFactory.git
|
||||||
|
ARG BRANCH=main
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Copy the application into the image
|
# Clone the repository
|
||||||
COPY . /app
|
RUN git clone --depth 1 --branch ${BRANCH} ${REPO_URL} /app || \
|
||||||
|
git clone --depth 1 ${REPO_URL} /app
|
||||||
|
|
||||||
# Install LLaMA Factory
|
# Install LLaMA Factory
|
||||||
RUN pip install --no-cache-dir -e ".[metrics]" --no-build-isolation
|
RUN pip install --no-cache-dir -e . --no-build-isolation && \
|
||||||
|
pip install --no-cache-dir -r requirements/metrics.txt --no-build-isolation
|
||||||
|
|
||||||
RUN pip install "git+https://github.com/alibaba/roll.git#subdirectory=mcore_adapter"
|
RUN pip install "git+https://github.com/alibaba/roll.git#subdirectory=mcore_adapter"
|
||||||
|
|
||||||
|
|||||||
@@ -104,6 +104,37 @@ sudo usermod -aG docker $USER
|
|||||||
# Log out and back in for changes to take effect
|
# Log out and back in for changes to take effect
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Megatron Bridge Image
|
||||||
|
|
||||||
|
`Dockerfile.megatron` builds a CUDA runtime for LLaMA-Factory + [Megatron Bridge](https://docs.nvidia.com/nemo/megatron-bridge/latest/):
|
||||||
|
|
||||||
|
| Component | Version |
|
||||||
|
| --- | --- |
|
||||||
|
| Base | `ubuntu:22.04` (Python 3.12) |
|
||||||
|
| PyTorch | 2.12.1+cu126 (CUDA libs from wheels) |
|
||||||
|
| TransformerEngine | 2.17.0 |
|
||||||
|
| megatron-core | 0.18.x (via megatron-bridge) |
|
||||||
|
| megatron-bridge | 0.5.0 |
|
||||||
|
|
||||||
|
### Build
|
||||||
|
|
||||||
|
From repo root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build -f docker/docker-cuda/Dockerfile.megatron \
|
||||||
|
-t llamafactory-megatron-bridge:latest .
|
||||||
|
```
|
||||||
|
|
||||||
|
### Run training
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run --rm -it --gpus all --ipc=host --shm-size=16g \
|
||||||
|
-e DISABLE_VERSION_CHECK=1 \
|
||||||
|
-e USE_MEGATRON_BRIDGE=1 \
|
||||||
|
-v "$PWD":/app -w /app \
|
||||||
|
llamafactory-megatron-bridge:latest
|
||||||
|
```
|
||||||
|
|
||||||
## Additional Notes
|
## Additional Notes
|
||||||
|
|
||||||
- The default image is built on Ubuntu 22.04 (x86_64), CUDA 12.4, Python 3.11, PyTorch 2.6.0, and Flash-attn 2.7.4
|
- The default image is built on Ubuntu 22.04 (x86_64), CUDA 12.4, Python 3.11, PyTorch 2.6.0, and Flash-attn 2.7.4
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# https://hub.docker.com/r/ascendai/cann/tags
|
# https://hub.docker.com/r/ascendai/cann/tags
|
||||||
|
|
||||||
ARG BASE_IMAGE=quay.io/ascend/cann:8.3.rc2-910b-ubuntu22.04-py3.11
|
ARG BASE_IMAGE=quay.io/ascend/cann:9.0.0-910b-ubuntu22.04-py3.11
|
||||||
FROM ${BASE_IMAGE}
|
FROM ${BASE_IMAGE}
|
||||||
|
|
||||||
# Installation arguments
|
# Installation arguments
|
||||||
@@ -33,9 +33,13 @@ RUN pip config set global.index-url "${PIP_INDEX}" && \
|
|||||||
COPY . /app
|
COPY . /app
|
||||||
|
|
||||||
# Install torch-npu
|
# Install torch-npu
|
||||||
RUN pip uninstall -y torch torchvision torchaudio && \
|
RUN source /usr/local/Ascend/ascend-toolkit/set_env.sh
|
||||||
pip install --no-cache-dir "torch==2.7.1" "torch-npu==2.7.1" "torchvision==0.22.1" "torchaudio==2.7.1" --index-url "${PYTORCH_INDEX}" && \
|
RUN pip uninstall -y torch torchvision torchaudio
|
||||||
pip install --no-cache-dir -e ".[metrics]" --no-build-isolation
|
RUN pip install --no-cache-dir -r requirements/npu.txt --index-url "${PYTORCH_INDEX}"
|
||||||
|
RUN pip install --no-cache-dir -r requirements/triton_ascend.txt
|
||||||
|
RUN pip install --no-cache-dir -r requirements/deepspeed.txt
|
||||||
|
RUN pip install --no-cache-dir -e . --no-build-isolation && \
|
||||||
|
pip install --no-cache-dir -r requirements/metrics.txt --no-build-isolation
|
||||||
|
|
||||||
# Set up volumes
|
# Set up volumes
|
||||||
# VOLUME [ "/root/.cache/huggingface", "/app/shared_data", "/app/output" ]
|
# VOLUME [ "/root/.cache/huggingface", "/app/shared_data", "/app/output" ]
|
||||||
|
|||||||
232
docker/docker-npu/OVERVIEW.md
Normal file
232
docker/docker-npu/OVERVIEW.md
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
# LLaMA Factory for Ascend NPU
|
||||||
|
|
||||||
|
LLaMA Factory Ascend NPU images provide a ready-to-use environment for fine-tuning, evaluating, and serving large language and multimodal models on Huawei Ascend Atlas NPUs. The images are based on Ascend CANN container images and include LLaMA Factory, Python, PyTorch, torch-npu, Triton Ascend, DeepSpeed, and the metric dependencies used by LLaMA Factory.
|
||||||
|
|
||||||
|
For installation and troubleshooting details, see the [English NPU installation guide](https://llamafactory.readthedocs.io/en/latest/multibackend/npu/npu_installation.html).
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
- Image registries:
|
||||||
|
- `docker.io/hiyouga/llamafactory`
|
||||||
|
- `quay.io/ascend/llamafactory`
|
||||||
|
- Dockerfile: `docker/docker-npu/Dockerfile`
|
||||||
|
- Docker Compose file: `docker/docker-npu/docker-compose.yml`
|
||||||
|
- Default base image: `quay.io/ascend/cann:9.0.0-910b-ubuntu22.04-py3.11`
|
||||||
|
- Supported accelerators: Ascend A2 and A3
|
||||||
|
- Supported container operating systems: Ubuntu 22.04 and openEuler 24.03
|
||||||
|
- Target CPU architectures: `linux/amd64` and `linux/arm64`
|
||||||
|
- Exposed ports:
|
||||||
|
- `7860`: LLaMA Board Web UI
|
||||||
|
- `8000`: API service
|
||||||
|
- Ascend environment script: `/usr/local/Ascend/ascend-toolkit/set_env.sh`
|
||||||
|
|
||||||
|
The current image variants are:
|
||||||
|
|
||||||
|
| Accelerator | Container OS | CANN base image |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| A2 | Ubuntu 22.04 | `quay.io/ascend/cann:9.0.0-910b-ubuntu22.04-py3.11` |
|
||||||
|
| A3 | Ubuntu 22.04 | `quay.io/ascend/cann:9.0.0-a3-ubuntu22.04-py3.11` |
|
||||||
|
| A2 | openEuler 24.03 | `quay.io/ascend/cann:9.0.0-910b-openeuler24.03-py3.11` |
|
||||||
|
| A3 | openEuler 24.03 | `quay.io/ascend/cann:9.0.0-a3-openeuler24.03-py3.11` |
|
||||||
|
|
||||||
|
## Image Contents and Intended Use
|
||||||
|
|
||||||
|
The image is intended for Ascend NPU training, fine-tuning, evaluation, Web UI, and API workflows supported by LLaMA Factory. It installs the following core components:
|
||||||
|
|
||||||
|
| Component | Version or source |
|
||||||
|
| --- | --- |
|
||||||
|
| CANN | Inherited from the selected CANN 9.0.0 base image |
|
||||||
|
| Python | Python 3.11, inherited from the base image |
|
||||||
|
| PyTorch | `2.7.1` |
|
||||||
|
| torch-npu | `2.7.1.post4` |
|
||||||
|
| torchvision | `0.22.1` |
|
||||||
|
| torchaudio | `2.7.1` |
|
||||||
|
| Triton Ascend | `3.2.1` |
|
||||||
|
| DeepSpeed | `>=0.10.0,<=0.18.4` |
|
||||||
|
| LLaMA Factory | Installed from the repository build context |
|
||||||
|
|
||||||
|
The image does not include model weights or datasets. Mount or download them separately and comply with their respective licenses and acceptable-use requirements.
|
||||||
|
|
||||||
|
## Image Tags and Dockerfile Archive
|
||||||
|
|
||||||
|
Images use the following tag format:
|
||||||
|
|
||||||
|
```text
|
||||||
|
<llamafactory-version>-cann<cann-version>-torch_npu<torch-npu-version>-<accelerator>-<os>-<python-version>
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Example | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `llamafactory-version` | `latest` or `0.9.6` | Non-release builds use `latest`; release builds use the LLaMA Factory version |
|
||||||
|
| `cann-version` | `9.0.0` | Parsed from the CANN base image tag |
|
||||||
|
| `torch-npu-version` | `2.7.1` | Parsed from `requirements/npu.txt`; a suffix such as `.post4` is not included in the image tag |
|
||||||
|
| `accelerator` | `A2` or `A3` | Ascend hardware generation selected for the image |
|
||||||
|
| `os` | `ubuntu` or `openeuler` | Container operating system family |
|
||||||
|
| `python-version` | `py3.11` | Parsed from the CANN base image tag |
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
```text
|
||||||
|
latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
|
latest-cann9.0.0-torch_npu2.7.1-A3-openeuler-py3.11
|
||||||
|
0.9.6-cann9.0.0-torch_npu2.7.1-A3-ubuntu-py3.11
|
||||||
|
```
|
||||||
|
|
||||||
|
The CPU architecture is not part of the tag. Published images are configured as multi-platform images, and Docker selects the `linux/amd64` or `linux/arm64` manifest for the host automatically.
|
||||||
|
|
||||||
|
The Dockerfile and its distribution overview are archived together at:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docker/docker-npu/
|
||||||
|
├── Dockerfile
|
||||||
|
├── OVERVIEW.md
|
||||||
|
├── OVERVIEW.zh.md
|
||||||
|
└── docker-compose.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
Before starting a container:
|
||||||
|
|
||||||
|
1. Install an Ascend driver and firmware compatible with the CANN version in the image.
|
||||||
|
2. Verify that `npu-smi info` works on the host.
|
||||||
|
3. Install Docker with permission to access the required Ascend device nodes and driver files.
|
||||||
|
|
||||||
|
Driver, firmware, CANN, torch-npu, and the target Ascend hardware must be mutually compatible.
|
||||||
|
|
||||||
|
### Pull and Run
|
||||||
|
|
||||||
|
The following example starts the latest A2 Ubuntu image with one NPU. Change the image tag and `/dev/davinci0` as needed.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export IMAGE=quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
|
|
||||||
|
docker pull "$IMAGE"
|
||||||
|
|
||||||
|
docker run --rm -it \
|
||||||
|
--name llamafactory-npu \
|
||||||
|
--ipc=host \
|
||||||
|
--device=/dev/davinci0 \
|
||||||
|
--device=/dev/davinci_manager \
|
||||||
|
--device=/dev/devmm_svm \
|
||||||
|
--device=/dev/hisi_hdc \
|
||||||
|
-v /usr/local/dcmi:/usr/local/dcmi \
|
||||||
|
-v /usr/local/bin/npu-smi:/usr/local/bin/npu-smi \
|
||||||
|
-v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
|
||||||
|
-v /etc/ascend_install.info:/etc/ascend_install.info \
|
||||||
|
-v "$HOME/.cache/huggingface:/root/.cache/huggingface" \
|
||||||
|
-p 7860:7860 \
|
||||||
|
-p 8000:8000 \
|
||||||
|
"$IMAGE" \
|
||||||
|
bash
|
||||||
|
```
|
||||||
|
|
||||||
|
The host path for `npu-smi` may be `/usr/local/sbin/npu-smi` on some driver installations. Adjust the mount source when necessary. Add more `--device=/dev/davinci<N>` options to expose additional NPUs.
|
||||||
|
|
||||||
|
Verify the runtime inside the container:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source /usr/local/Ascend/ascend-toolkit/set_env.sh
|
||||||
|
npu-smi info
|
||||||
|
python -c "import torch, torch_npu; print(torch.__version__, torch_npu.__version__, torch.npu.is_available())"
|
||||||
|
llamafactory-cli help
|
||||||
|
```
|
||||||
|
|
||||||
|
Start LLaMA Board when needed:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
llamafactory-cli webui
|
||||||
|
```
|
||||||
|
|
||||||
|
### Build Locally
|
||||||
|
|
||||||
|
Run the build from the repository root. The following example builds the A3 openEuler variant:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build \
|
||||||
|
-f ./docker/docker-npu/Dockerfile \
|
||||||
|
--build-arg BASE_IMAGE=quay.io/ascend/cann:9.0.0-a3-openeuler24.03-py3.11 \
|
||||||
|
--build-arg PIP_INDEX=https://pypi.org/simple \
|
||||||
|
-t llamafactory:npu-a3-openeuler \
|
||||||
|
.
|
||||||
|
```
|
||||||
|
|
||||||
|
Available build arguments:
|
||||||
|
|
||||||
|
| Argument | Default | Purpose |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `BASE_IMAGE` | A2 Ubuntu CANN 9.0.0 image | Selects the accelerator and container OS variant |
|
||||||
|
| `PIP_INDEX` | `https://pypi.org/simple` | Selects the Python package index |
|
||||||
|
| `PYTORCH_INDEX` | `https://download.pytorch.org/whl/cpu` | Selects the PyTorch wheel index used with torch-npu |
|
||||||
|
| `HTTP_PROXY` | Empty | Provides an optional HTTP/HTTPS proxy during the build |
|
||||||
|
|
||||||
|
Docker Compose can build and start each supported variant:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd docker/docker-npu
|
||||||
|
|
||||||
|
# A2 with Ubuntu
|
||||||
|
docker compose up -d llamafactory-a2-ubuntu
|
||||||
|
|
||||||
|
# A3 with Ubuntu
|
||||||
|
docker compose --profile a3 up -d llamafactory-a3-ubuntu
|
||||||
|
|
||||||
|
# A2 with openEuler
|
||||||
|
docker compose --profile openeuler up -d llamafactory-a2-openeuler
|
||||||
|
|
||||||
|
# A3 with openEuler
|
||||||
|
docker compose --profile a3-openeuler up -d llamafactory-a3-openeuler
|
||||||
|
```
|
||||||
|
|
||||||
|
### Extend or Develop from the Image
|
||||||
|
|
||||||
|
For interactive development, mount a local checkout and reinstall it in editable mode inside the container:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/hiyouga/LLaMA-Factory.git
|
||||||
|
cd LLaMA-Factory
|
||||||
|
|
||||||
|
# Add the same Ascend --device and driver mount options shown above.
|
||||||
|
docker run --rm -it \
|
||||||
|
--ipc=host \
|
||||||
|
-v "$PWD:/workspace/LLaMA-Factory" \
|
||||||
|
-w /workspace/LLaMA-Factory \
|
||||||
|
"$IMAGE" \
|
||||||
|
bash
|
||||||
|
|
||||||
|
pip install -e . --no-build-isolation
|
||||||
|
```
|
||||||
|
|
||||||
|
For a reproducible derived image, create a separate Dockerfile:
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
|
|
||||||
|
COPY requirements-extension.txt /tmp/requirements-extension.txt
|
||||||
|
RUN pip install --no-cache-dir -r /tmp/requirements-extension.txt
|
||||||
|
|
||||||
|
COPY . /workspace/application
|
||||||
|
WORKDIR /workspace/application
|
||||||
|
```
|
||||||
|
|
||||||
|
Pass Ascend devices and driver mounts when running the derived image; device access should not be embedded in the image itself.
|
||||||
|
|
||||||
|
## Hardware Support and Compatibility Notes
|
||||||
|
|
||||||
|
- A2 images use the `910b` CANN base image; A3 images use the `a3` CANN base image.
|
||||||
|
- The image build targets both x86-64 (`linux/amd64`) and AArch64 (`linux/arm64`) hosts. This CPU architecture is independent of whether the accelerator is A2 or A3.
|
||||||
|
- Ubuntu 22.04 and openEuler 24.03 refer to the operating system inside the container.
|
||||||
|
- The current dependency baseline aligns PyTorch `2.7.1` with torch-npu `2.7.1.post4`. Upgrading either package independently may break compatibility.
|
||||||
|
- Use a fixed release tag for reproducible production deployments. The `latest` tag can change after scheduled builds.
|
||||||
|
- Legacy short tags such as `latest-npu-a2` do not encode the CANN, torch-npu, operating system, or Python versions. Prefer the full tag format documented above.
|
||||||
|
- Validate the exact driver, firmware, CANN, and SoC combination before production deployment.
|
||||||
|
|
||||||
|
## License and Disclaimer
|
||||||
|
|
||||||
|
LLaMA Factory is distributed under the [Apache License 2.0](../../LICENSE).
|
||||||
|
|
||||||
|
Ascend CANN, torch-npu, Triton Ascend, DeepSpeed, base operating-system packages, model weights, datasets, and other third-party components are governed by their respective licenses and terms. The LLaMA Factory license does not replace or override those terms.
|
||||||
|
|
||||||
|
The image is provided on an "AS IS" basis, without warranties or conditions of any kind. Users are responsible for validating hardware and software compatibility, securing the container and its runtime configuration, complying with applicable licenses and laws, and reviewing model and dataset terms before training, evaluation, or deployment.
|
||||||
232
docker/docker-npu/OVERVIEW.zh.md
Normal file
232
docker/docker-npu/OVERVIEW.zh.md
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
# 面向昇腾 NPU 的 LLaMA Factory 镜像
|
||||||
|
|
||||||
|
LLaMA Factory 昇腾 NPU 镜像面向华为昇腾 Atlas NPU,提供可直接用于大语言模型和多模态模型微调、评测与服务部署的运行环境。镜像基于昇腾 CANN 容器镜像构建,预装 LLaMA Factory、Python、PyTorch、torch-npu、Triton Ascend、DeepSpeed 和 LLaMA Factory 评测依赖。
|
||||||
|
|
||||||
|
安装方法和问题排查请参考 [LLaMA Factory NPU 安装及配置文档](https://llamafactory.readthedocs.io/zh-cn/latest/multibackend/npu/npu_installation.html)。
|
||||||
|
|
||||||
|
## 快速参考
|
||||||
|
|
||||||
|
- 镜像仓库:
|
||||||
|
- `docker.io/hiyouga/llamafactory`
|
||||||
|
- `quay.io/ascend/llamafactory`
|
||||||
|
- Dockerfile:`docker/docker-npu/Dockerfile`
|
||||||
|
- Docker Compose 文件:`docker/docker-npu/docker-compose.yml`
|
||||||
|
- 默认基础镜像:`quay.io/ascend/cann:9.0.0-910b-ubuntu22.04-py3.11`
|
||||||
|
- 支持的加速器:昇腾 A2、A3
|
||||||
|
- 支持的容器操作系统:Ubuntu 22.04、openEuler 24.03
|
||||||
|
- 目标 CPU 架构:`linux/amd64`、`linux/arm64`
|
||||||
|
- 对外端口:
|
||||||
|
- `7860`:LLaMA Board Web UI
|
||||||
|
- `8000`:API 服务
|
||||||
|
- 昇腾环境脚本:`/usr/local/Ascend/ascend-toolkit/set_env.sh`
|
||||||
|
|
||||||
|
当前提供以下镜像组合:
|
||||||
|
|
||||||
|
| 加速器 | 容器操作系统 | CANN 基础镜像 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| A2 | Ubuntu 22.04 | `quay.io/ascend/cann:9.0.0-910b-ubuntu22.04-py3.11` |
|
||||||
|
| A3 | Ubuntu 22.04 | `quay.io/ascend/cann:9.0.0-a3-ubuntu22.04-py3.11` |
|
||||||
|
| A2 | openEuler 24.03 | `quay.io/ascend/cann:9.0.0-910b-openeuler24.03-py3.11` |
|
||||||
|
| A3 | openEuler 24.03 | `quay.io/ascend/cann:9.0.0-a3-openeuler24.03-py3.11` |
|
||||||
|
|
||||||
|
## 镜像介绍
|
||||||
|
|
||||||
|
该镜像用于运行 LLaMA Factory 支持的昇腾 NPU 训练、微调、评测、Web UI 和 API 服务,主要包含以下组件:
|
||||||
|
|
||||||
|
| 组件 | 版本或来源 |
|
||||||
|
| --- | --- |
|
||||||
|
| CANN | 继承自所选 CANN 9.0.0 基础镜像 |
|
||||||
|
| Python | Python 3.11,继承自基础镜像 |
|
||||||
|
| PyTorch | `2.7.1` |
|
||||||
|
| torch-npu | `2.7.1.post4` |
|
||||||
|
| torchvision | `0.22.1` |
|
||||||
|
| torchaudio | `2.7.1` |
|
||||||
|
| Triton Ascend | `3.2.1` |
|
||||||
|
| DeepSpeed | `>=0.10.0,<=0.18.4` |
|
||||||
|
| LLaMA Factory | 从构建上下文中的仓库源码安装 |
|
||||||
|
|
||||||
|
镜像不包含模型权重和数据集。请通过目录挂载或运行时下载的方式单独提供,并遵守对应的许可证和使用要求。
|
||||||
|
|
||||||
|
## 镜像 Tag 说明与 Dockerfile 归档路径
|
||||||
|
|
||||||
|
镜像使用以下 tag 格式:
|
||||||
|
|
||||||
|
```text
|
||||||
|
<llamafactory版本>-cann<CANN版本>-torch_npu<torch-npu版本>-<加速器>-<操作系统>-<Python版本>
|
||||||
|
```
|
||||||
|
|
||||||
|
| 字段 | 示例 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `llamafactory版本` | `latest` 或 `0.9.6` | 非 release 构建使用 `latest`,release 构建使用 LLaMA Factory 版本号 |
|
||||||
|
| `CANN版本` | `9.0.0` | 从 CANN 基础镜像 tag 中提取 |
|
||||||
|
| `torch-npu版本` | `2.7.1` | 从 `requirements/npu.txt` 中提取,镜像 tag 不包含 `.post4` 等后缀 |
|
||||||
|
| `加速器` | `A2` 或 `A3` | 当前镜像所适配的昇腾硬件代际 |
|
||||||
|
| `操作系统` | `ubuntu` 或 `openeuler` | 容器内操作系统类型 |
|
||||||
|
| `Python版本` | `py3.11` | 从 CANN 基础镜像 tag 中提取 |
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```text
|
||||||
|
latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
|
latest-cann9.0.0-torch_npu2.7.1-A3-openeuler-py3.11
|
||||||
|
0.9.6-cann9.0.0-torch_npu2.7.1-A3-ubuntu-py3.11
|
||||||
|
```
|
||||||
|
|
||||||
|
CPU 架构不写入 tag。发布镜像配置为多架构镜像,Docker 拉取时会根据宿主机自动选择 `linux/amd64` 或 `linux/arm64` 版本。
|
||||||
|
|
||||||
|
Dockerfile 和用于镜像分发的概述文件在同一目录归档:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docker/docker-npu/
|
||||||
|
├── Dockerfile
|
||||||
|
├── OVERVIEW.md
|
||||||
|
├── OVERVIEW.zh.md
|
||||||
|
└── docker-compose.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 前置条件
|
||||||
|
|
||||||
|
启动容器前需要:
|
||||||
|
|
||||||
|
1. 在宿主机安装与镜像内 CANN 版本兼容的昇腾驱动和固件。
|
||||||
|
2. 确认宿主机执行 `npu-smi info` 可以正常识别 NPU。
|
||||||
|
3. 安装 Docker,并确保当前用户有权访问所需的昇腾设备节点和驱动文件。
|
||||||
|
|
||||||
|
驱动、固件、CANN、torch-npu 与目标昇腾硬件需要保持兼容。
|
||||||
|
|
||||||
|
### 拉取并运行镜像
|
||||||
|
|
||||||
|
以下示例使用一张 NPU 启动最新的 A2 Ubuntu 镜像。请根据实际环境修改镜像 tag 和 `/dev/davinci0`。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export IMAGE=quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
|
|
||||||
|
docker pull "$IMAGE"
|
||||||
|
|
||||||
|
docker run --rm -it \
|
||||||
|
--name llamafactory-npu \
|
||||||
|
--ipc=host \
|
||||||
|
--device=/dev/davinci0 \
|
||||||
|
--device=/dev/davinci_manager \
|
||||||
|
--device=/dev/devmm_svm \
|
||||||
|
--device=/dev/hisi_hdc \
|
||||||
|
-v /usr/local/dcmi:/usr/local/dcmi \
|
||||||
|
-v /usr/local/bin/npu-smi:/usr/local/bin/npu-smi \
|
||||||
|
-v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
|
||||||
|
-v /etc/ascend_install.info:/etc/ascend_install.info \
|
||||||
|
-v "$HOME/.cache/huggingface:/root/.cache/huggingface" \
|
||||||
|
-p 7860:7860 \
|
||||||
|
-p 8000:8000 \
|
||||||
|
"$IMAGE" \
|
||||||
|
bash
|
||||||
|
```
|
||||||
|
|
||||||
|
部分驱动环境中的 `npu-smi` 位于 `/usr/local/sbin/npu-smi`,此时需要调整挂载源路径。使用多张 NPU 时,继续追加 `--device=/dev/davinci<N>` 参数。
|
||||||
|
|
||||||
|
进入容器后验证运行环境:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source /usr/local/Ascend/ascend-toolkit/set_env.sh
|
||||||
|
npu-smi info
|
||||||
|
python -c "import torch, torch_npu; print(torch.__version__, torch_npu.__version__, torch.npu.is_available())"
|
||||||
|
llamafactory-cli help
|
||||||
|
```
|
||||||
|
|
||||||
|
需要使用 LLaMA Board 时执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
llamafactory-cli webui
|
||||||
|
```
|
||||||
|
|
||||||
|
### 本地构建
|
||||||
|
|
||||||
|
在仓库根目录执行构建。以下示例构建 A3 openEuler 镜像:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build \
|
||||||
|
-f ./docker/docker-npu/Dockerfile \
|
||||||
|
--build-arg BASE_IMAGE=quay.io/ascend/cann:9.0.0-a3-openeuler24.03-py3.11 \
|
||||||
|
--build-arg PIP_INDEX=https://pypi.org/simple \
|
||||||
|
-t llamafactory:npu-a3-openeuler \
|
||||||
|
.
|
||||||
|
```
|
||||||
|
|
||||||
|
可用构建参数:
|
||||||
|
|
||||||
|
| 参数 | 默认值 | 用途 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `BASE_IMAGE` | A2 Ubuntu CANN 9.0.0 镜像 | 选择加速器和容器操作系统组合 |
|
||||||
|
| `PIP_INDEX` | `https://pypi.org/simple` | 指定 Python 软件包索引 |
|
||||||
|
| `PYTORCH_INDEX` | `https://download.pytorch.org/whl/cpu` | 指定配合 torch-npu 使用的 PyTorch wheel 索引 |
|
||||||
|
| `HTTP_PROXY` | 空 | 构建期间可选的 HTTP/HTTPS 代理 |
|
||||||
|
|
||||||
|
也可以通过 Docker Compose 构建并启动各个组合:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd docker/docker-npu
|
||||||
|
|
||||||
|
# A2 + Ubuntu
|
||||||
|
docker compose up -d llamafactory-a2-ubuntu
|
||||||
|
|
||||||
|
# A3 + Ubuntu
|
||||||
|
docker compose --profile a3 up -d llamafactory-a3-ubuntu
|
||||||
|
|
||||||
|
# A2 + openEuler
|
||||||
|
docker compose --profile openeuler up -d llamafactory-a2-openeuler
|
||||||
|
|
||||||
|
# A3 + openEuler
|
||||||
|
docker compose --profile a3-openeuler up -d llamafactory-a3-openeuler
|
||||||
|
```
|
||||||
|
|
||||||
|
### 二次开发
|
||||||
|
|
||||||
|
交互式开发时,可以将本地源码挂载到容器中,并在容器内以 editable 模式重新安装:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/hiyouga/LLaMA-Factory.git
|
||||||
|
cd LLaMA-Factory
|
||||||
|
|
||||||
|
# 同时添加前述昇腾 --device 和驱动目录挂载参数。
|
||||||
|
docker run --rm -it \
|
||||||
|
--ipc=host \
|
||||||
|
-v "$PWD:/workspace/LLaMA-Factory" \
|
||||||
|
-w /workspace/LLaMA-Factory \
|
||||||
|
"$IMAGE" \
|
||||||
|
bash
|
||||||
|
|
||||||
|
pip install -e . --no-build-isolation
|
||||||
|
```
|
||||||
|
|
||||||
|
需要可复现的派生镜像时,可以新建独立 Dockerfile:
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM quay.io/ascend/llamafactory:latest-cann9.0.0-torch_npu2.7.1-A2-ubuntu-py3.11
|
||||||
|
|
||||||
|
COPY requirements-extension.txt /tmp/requirements-extension.txt
|
||||||
|
RUN pip install --no-cache-dir -r /tmp/requirements-extension.txt
|
||||||
|
|
||||||
|
COPY . /workspace/application
|
||||||
|
WORKDIR /workspace/application
|
||||||
|
```
|
||||||
|
|
||||||
|
运行派生镜像时仍需传入昇腾设备和驱动挂载参数,不应将设备访问配置固化到镜像中。
|
||||||
|
|
||||||
|
## 硬件支持与兼容性说明
|
||||||
|
|
||||||
|
- A2 镜像使用标记为 `910b` 的 CANN 基础镜像,A3 镜像使用标记为 `a3` 的 CANN 基础镜像。
|
||||||
|
- 镜像构建目标同时包含 x86-64(`linux/amd64`)和 AArch64(`linux/arm64`)宿主机。CPU 架构与加速器属于 A2 还是 A3 无关。
|
||||||
|
- Ubuntu 22.04 和 openEuler 24.03 指容器内部的操作系统。
|
||||||
|
- 当前依赖基线将 PyTorch `2.7.1` 与 torch-npu `2.7.1.post4` 配套使用。单独升级其中一个软件包可能破坏兼容性。
|
||||||
|
- 生产环境建议使用固定 release tag,以确保部署可复现;定时构建可能更新 `latest` tag。
|
||||||
|
- `latest-npu-a2` 等旧式短 tag 没有体现 CANN、torch-npu、操作系统和 Python 版本,建议迁移到本文所述的完整 tag。
|
||||||
|
- 正式部署前,请验证具体驱动、固件、CANN 和 SoC 组合的兼容性。
|
||||||
|
|
||||||
|
## 许可证与免责声明
|
||||||
|
|
||||||
|
LLaMA Factory 基于 [Apache License 2.0](../../LICENSE) 发布。
|
||||||
|
|
||||||
|
昇腾 CANN、torch-npu、Triton Ascend、DeepSpeed、基础操作系统软件包、模型权重、数据集和其他第三方组件分别受其自身许可证与条款约束。LLaMA Factory 的许可证不会替代或覆盖这些条款。
|
||||||
|
|
||||||
|
本镜像按“原样”提供,不附带任何明示或暗示的保证。用户需要自行验证软硬件兼容性、保障容器及运行配置的安全、遵守适用的许可证和法律,并在训练、评测或部署前审查模型与数据集的使用条款。
|
||||||
@@ -1,58 +1,80 @@
|
|||||||
|
x-build-args: &build-args
|
||||||
|
PIP_INDEX: https://pypi.org/simple
|
||||||
|
|
||||||
|
x-build: &build
|
||||||
|
dockerfile: ./docker/docker-npu/Dockerfile
|
||||||
|
context: ../..
|
||||||
|
|
||||||
|
x-npu-common: &npu-common
|
||||||
|
volumes:
|
||||||
|
- /usr/local/dcmi:/usr/local/dcmi
|
||||||
|
- /usr/local/bin/npu-smi:/usr/local/bin/npu-smi
|
||||||
|
- /usr/local/Ascend/driver:/usr/local/Ascend/driver
|
||||||
|
- /etc/ascend_install.info:/etc/ascend_install.info
|
||||||
|
ipc: host
|
||||||
|
tty: true
|
||||||
|
# shm_size: "16gb" # ipc: host is set
|
||||||
|
stdin_open: true
|
||||||
|
command: bash
|
||||||
|
devices:
|
||||||
|
- /dev/davinci0
|
||||||
|
- /dev/davinci_manager
|
||||||
|
- /dev/devmm_svm
|
||||||
|
- /dev/hisi_hdc
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
services:
|
services:
|
||||||
llamafactory-a2:
|
llamafactory-a2-ubuntu:
|
||||||
|
<<: *npu-common
|
||||||
build:
|
build:
|
||||||
dockerfile: ./docker/docker-npu/Dockerfile
|
<<: *build
|
||||||
context: ../..
|
|
||||||
args:
|
args:
|
||||||
PIP_INDEX: https://pypi.org/simple
|
<<: *build-args
|
||||||
container_name: llamafactory-a2
|
BASE_IMAGE: quay.io/ascend/cann:9.0.0-910b-ubuntu22.04-py3.11
|
||||||
image: llamafactory:npu-a2
|
container_name: llamafactory-a2-ubuntu
|
||||||
volumes:
|
image: llamafactory:npu-a2-ubuntu
|
||||||
- /usr/local/dcmi:/usr/local/dcmi
|
|
||||||
- /usr/local/bin/npu-smi:/usr/local/bin/npu-smi
|
|
||||||
- /usr/local/Ascend/driver:/usr/local/Ascend/driver
|
|
||||||
- /etc/ascend_install.info:/etc/ascend_install.info
|
|
||||||
ports:
|
ports:
|
||||||
- "7860:7860"
|
- "7860:7860"
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
ipc: host
|
|
||||||
tty: true
|
|
||||||
# shm_size: "16gb" # ipc: host is set
|
|
||||||
stdin_open: true
|
|
||||||
command: bash
|
|
||||||
devices:
|
|
||||||
- /dev/davinci0
|
|
||||||
- /dev/davinci_manager
|
|
||||||
- /dev/devmm_svm
|
|
||||||
- /dev/hisi_hdc
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
llamafactory-a3:
|
llamafactory-a3-ubuntu:
|
||||||
|
<<: *npu-common
|
||||||
profiles: ["a3"]
|
profiles: ["a3"]
|
||||||
build:
|
build:
|
||||||
dockerfile: ./docker/docker-npu/Dockerfile
|
<<: *build
|
||||||
context: ../..
|
|
||||||
args:
|
args:
|
||||||
BASE_IMAGE: quay.io/ascend/cann:8.3.rc2-a3-ubuntu22.04-py3.11
|
<<: *build-args
|
||||||
PIP_INDEX: https://pypi.org/simple
|
BASE_IMAGE: quay.io/ascend/cann:9.0.0-a3-ubuntu22.04-py3.11
|
||||||
container_name: llamafactory-a3
|
container_name: llamafactory-a3-ubuntu
|
||||||
image: llamafactory:npu-a3
|
image: llamafactory:npu-a3-ubuntu
|
||||||
volumes:
|
|
||||||
- /usr/local/dcmi:/usr/local/dcmi
|
|
||||||
- /usr/local/bin/npu-smi:/usr/local/bin/npu-smi
|
|
||||||
- /usr/local/Ascend/driver:/usr/local/Ascend/driver
|
|
||||||
- /etc/ascend_install.info:/etc/ascend_install.info
|
|
||||||
ports:
|
ports:
|
||||||
- "7861:7860"
|
- "7861:7860"
|
||||||
- "8001:8000"
|
- "8001:8000"
|
||||||
ipc: host
|
|
||||||
tty: true
|
llamafactory-a2-openeuler:
|
||||||
# shm_size: "16gb" # ipc: host is set
|
<<: *npu-common
|
||||||
stdin_open: true
|
profiles: ["openeuler"]
|
||||||
command: bash
|
build:
|
||||||
devices:
|
<<: *build
|
||||||
- /dev/davinci0
|
args:
|
||||||
- /dev/davinci_manager
|
<<: *build-args
|
||||||
- /dev/devmm_svm
|
BASE_IMAGE: quay.io/ascend/cann:9.0.0-910b-openeuler24.03-py3.11
|
||||||
- /dev/hisi_hdc
|
container_name: llamafactory-a2-openeuler
|
||||||
restart: unless-stopped
|
image: llamafactory:npu-a2-openeuler
|
||||||
|
ports:
|
||||||
|
- "7862:7860"
|
||||||
|
- "8002:8000"
|
||||||
|
|
||||||
|
llamafactory-a3-openeuler:
|
||||||
|
<<: *npu-common
|
||||||
|
profiles: ["a3-openeuler"]
|
||||||
|
build:
|
||||||
|
<<: *build
|
||||||
|
args:
|
||||||
|
<<: *build-args
|
||||||
|
BASE_IMAGE: quay.io/ascend/cann:9.0.0-a3-openeuler24.03-py3.11
|
||||||
|
container_name: llamafactory-a3-openeuler
|
||||||
|
image: llamafactory:npu-a3-openeuler
|
||||||
|
ports:
|
||||||
|
- "7863:7860"
|
||||||
|
- "8003:8000"
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
# https://hub.docker.com/r/rocm/pytorch/tags
|
# https://hub.docker.com/r/rocm/pytorch/tags
|
||||||
ARG BASE_IMAGE=rocm/pytorch:rocm6.4.1_ubuntu22.04_py3.10_pytorch_release_2.6.0
|
# ROCm 7.2 + PyTorch 2.7.1 (Python 3.12). Keep base image's PyTorch; do not reinstall.
|
||||||
|
ARG BASE_IMAGE=rocm/pytorch:rocm7.2_ubuntu24.04_py3.12_pytorch_release_2.7.1
|
||||||
FROM ${BASE_IMAGE}
|
FROM ${BASE_IMAGE}
|
||||||
|
|
||||||
# Installation arguments
|
# Installation arguments
|
||||||
ARG PIP_INDEX=https://pypi.org/simple
|
ARG PIP_INDEX=https://pypi.org/simple
|
||||||
ARG INSTALL_FLASHATTN=false
|
ARG INSTALL_FLASHATTN=false
|
||||||
ARG HTTP_PROXY=""
|
ARG HTTP_PROXY=""
|
||||||
ARG PYTORCH_INDEX=https://download.pytorch.org/whl/rocm6.3
|
|
||||||
|
|
||||||
# Define environments
|
# Define environments
|
||||||
ENV MAX_JOBS=16
|
ENV MAX_JOBS=16
|
||||||
@@ -32,9 +32,9 @@ RUN pip config set global.index-url "${PIP_INDEX}" && \
|
|||||||
# Copy the application into the image
|
# Copy the application into the image
|
||||||
COPY . /app
|
COPY . /app
|
||||||
|
|
||||||
# Reinstall pytorch rocm and install LLaMA Factory
|
# Install LLaMA Factory (use base image's PyTorch/ROCm; do not reinstall)
|
||||||
RUN pip uninstall -y torch torchvision torchaudio && \
|
RUN pip install --no-cache-dir -e . --pre && \
|
||||||
pip install --no-cache-dir --no-build-isolation -e --pre ".[metrics,deepspeed]" --index-url "${PYTORCH_INDEX}"
|
pip install --no-cache-dir -r requirements/deepspeed.txt -r requirements/liger-kernel.txt -r requirements/bitsandbytes.txt
|
||||||
|
|
||||||
# Rebuild flash attention
|
# Rebuild flash attention
|
||||||
RUN if [ "${INSTALL_FLASHATTN}" == "true" ]; then \
|
RUN if [ "${INSTALL_FLASHATTN}" == "true" ]; then \
|
||||||
|
|||||||
20
docs/Makefile
Normal file
20
docs/Makefile
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
# Minimal makefile for Sphinx documentation
|
||||||
|
#
|
||||||
|
|
||||||
|
# You can set these variables from the command line, and also
|
||||||
|
# from the environment for the first two.
|
||||||
|
SPHINXOPTS =
|
||||||
|
SPHINXBUILD = sphinx-build
|
||||||
|
SOURCEDIR = .
|
||||||
|
BUILDDIR = _build
|
||||||
|
|
||||||
|
# Put it first so that "make" without argument is like "make help".
|
||||||
|
help:
|
||||||
|
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
||||||
|
|
||||||
|
.PHONY: help Makefile
|
||||||
|
|
||||||
|
# Catch-all target: route all unknown targets to Sphinx using the new
|
||||||
|
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
|
||||||
|
%: Makefile
|
||||||
|
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
||||||
49
docs/_static/css/lang-switcher.css
vendored
Normal file
49
docs/_static/css/lang-switcher.css
vendored
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
.lang-switcher {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lang-switcher__select {
|
||||||
|
appearance: none;
|
||||||
|
-webkit-appearance: none;
|
||||||
|
-moz-appearance: none;
|
||||||
|
padding: 6px 28px 6px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid rgba(0, 0, 0, 0.18);
|
||||||
|
background-color: #ffffff;
|
||||||
|
color: #333333;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 18px;
|
||||||
|
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
|
||||||
|
cursor: pointer;
|
||||||
|
background-image: linear-gradient(45deg, transparent 50%, #667085 50%),
|
||||||
|
linear-gradient(135deg, #667085 50%, transparent 50%);
|
||||||
|
background-position: calc(100% - 16px) 50%, calc(100% - 11px) 50%;
|
||||||
|
background-size: 5px 5px, 5px 5px;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lang-switcher__select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: rgba(41, 128, 185, 0.65);
|
||||||
|
box-shadow: 0 0 0 3px rgba(41, 128, 185, 0.18);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wy-side-nav-search .lang-switcher {
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wy-side-nav-search .lang-switcher__select {
|
||||||
|
border-color: rgba(255, 255, 255, 0.18);
|
||||||
|
background-color: rgba(255, 255, 255, 0.08);
|
||||||
|
color: #ffffff;
|
||||||
|
box-shadow: none;
|
||||||
|
background-image: linear-gradient(45deg, transparent 50%, rgba(255, 255, 255, 0.75) 50%),
|
||||||
|
linear-gradient(135deg, rgba(255, 255, 255, 0.75) 50%, transparent 50%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wy-side-nav-search .lang-switcher__select:focus {
|
||||||
|
border-color: rgba(255, 255, 255, 0.45);
|
||||||
|
box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.12);
|
||||||
|
}
|
||||||
93
docs/_static/js/switcher.js
vendored
Normal file
93
docs/_static/js/switcher.js
vendored
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
var path = window.location.pathname || '';
|
||||||
|
var isZh = path.indexOf('/zh/') !== -1;
|
||||||
|
var isEn = path.indexOf('/en/') !== -1;
|
||||||
|
if (!isZh && !isEn) return;
|
||||||
|
|
||||||
|
var currentLang = isZh ? 'zh' : 'en';
|
||||||
|
|
||||||
|
function buildSwitcher() {
|
||||||
|
var container = document.createElement('div');
|
||||||
|
container.className = 'lang-switcher';
|
||||||
|
|
||||||
|
var select = document.createElement('select');
|
||||||
|
select.setAttribute('aria-label', 'Language');
|
||||||
|
select.className = 'lang-switcher__select';
|
||||||
|
|
||||||
|
var optionZh = document.createElement('option');
|
||||||
|
optionZh.value = 'zh';
|
||||||
|
optionZh.textContent = 'Simplified Chinese';
|
||||||
|
optionZh.selected = isZh;
|
||||||
|
|
||||||
|
var optionEn = document.createElement('option');
|
||||||
|
optionEn.value = 'en';
|
||||||
|
optionEn.textContent = 'English';
|
||||||
|
optionEn.selected = isEn;
|
||||||
|
|
||||||
|
select.appendChild(optionZh);
|
||||||
|
select.appendChild(optionEn);
|
||||||
|
|
||||||
|
select.addEventListener('change', function () {
|
||||||
|
var nextLang = select.value;
|
||||||
|
if (nextLang === currentLang) return;
|
||||||
|
var targetUrl = path.replace('/' + currentLang + '/', '/' + nextLang + '/');
|
||||||
|
window.location.href = targetUrl + window.location.search + window.location.hash;
|
||||||
|
});
|
||||||
|
|
||||||
|
container.appendChild(select);
|
||||||
|
return container;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideOtherLanguageToc() {
|
||||||
|
var captions = document.querySelectorAll('p.caption');
|
||||||
|
for (var i = 0; i < captions.length; i++) {
|
||||||
|
var caption = captions[i];
|
||||||
|
var textEl = caption.querySelector('.caption-text');
|
||||||
|
if (!textEl) continue;
|
||||||
|
var label = (textEl.textContent || '').trim().toLowerCase();
|
||||||
|
|
||||||
|
var isCaptionZh = label === '中文' || label === 'chinese' || label === 'zh';
|
||||||
|
var isCaptionEn = label === 'english' || label === 'en';
|
||||||
|
|
||||||
|
if (!isCaptionZh && !isCaptionEn) continue;
|
||||||
|
|
||||||
|
var shouldHide = (currentLang === 'zh' && isCaptionEn) || (currentLang === 'en' && isCaptionZh);
|
||||||
|
var shouldHideCaption = true;
|
||||||
|
|
||||||
|
var next = caption.nextElementSibling;
|
||||||
|
if (next && next.tagName && next.tagName.toLowerCase() === 'ul') {
|
||||||
|
if (shouldHide) {
|
||||||
|
caption.style.display = 'none';
|
||||||
|
next.style.display = 'none';
|
||||||
|
} else if (shouldHideCaption) {
|
||||||
|
caption.style.display = 'none';
|
||||||
|
}
|
||||||
|
} else if (shouldHide) {
|
||||||
|
caption.style.display = 'none';
|
||||||
|
} else if (shouldHideCaption) {
|
||||||
|
caption.style.display = 'none';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var side = document.querySelector('.wy-side-nav-search');
|
||||||
|
if (side) {
|
||||||
|
var sideSwitcher = buildSwitcher();
|
||||||
|
sideSwitcher.style.marginTop = '8px';
|
||||||
|
sideSwitcher.style.display = 'flex';
|
||||||
|
sideSwitcher.style.justifyContent = 'center';
|
||||||
|
side.appendChild(sideSwitcher);
|
||||||
|
} else {
|
||||||
|
var topRight = buildSwitcher();
|
||||||
|
topRight.style.position = 'fixed';
|
||||||
|
topRight.style.top = '12px';
|
||||||
|
topRight.style.right = '12px';
|
||||||
|
topRight.style.zIndex = '9999';
|
||||||
|
document.body.appendChild(topRight);
|
||||||
|
}
|
||||||
|
|
||||||
|
hideOtherLanguageToc();
|
||||||
|
window.addEventListener('load', hideOtherLanguageToc);
|
||||||
|
setTimeout(hideOtherLanguageToc, 50);
|
||||||
|
setTimeout(hideOtherLanguageToc, 300);
|
||||||
|
});
|
||||||
35
docs/conf.py
Normal file
35
docs/conf.py
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# Configuration file for the Sphinx documentation builder.
|
||||||
|
|
||||||
|
|
||||||
|
# Define common settings here
|
||||||
|
project = "LlamaFactory"
|
||||||
|
copyright = "2024, LlamaFactory Team"
|
||||||
|
author = "LlamaFactory Team"
|
||||||
|
|
||||||
|
extensions = [
|
||||||
|
"sphinx.ext.autodoc",
|
||||||
|
"sphinx.ext.viewcode",
|
||||||
|
"sphinx.ext.napoleon",
|
||||||
|
"myst_parser",
|
||||||
|
]
|
||||||
|
|
||||||
|
templates_path = ["_templates"]
|
||||||
|
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
|
||||||
|
|
||||||
|
html_theme = "sphinx_rtd_theme"
|
||||||
|
|
||||||
|
html_static_path = ["_static"]
|
||||||
|
|
||||||
|
html_js_files = [
|
||||||
|
"js/switcher.js",
|
||||||
|
]
|
||||||
|
|
||||||
|
html_css_files = [
|
||||||
|
"css/lang-switcher.css",
|
||||||
|
]
|
||||||
|
|
||||||
|
myst_enable_extensions = [
|
||||||
|
"colon_fence",
|
||||||
|
"deflist",
|
||||||
|
]
|
||||||
|
myst_heading_anchors = 3
|
||||||
3
docs/en/advanced/custom-kernels/custom-kernels.md
Normal file
3
docs/en/advanced/custom-kernels/custom-kernels.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Custom Kernels
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/advanced/custom-kernels/fused-operators.md
Normal file
3
docs/en/advanced/custom-kernels/fused-operators.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Fused Operators
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/advanced/custom-kernels/triton.md
Normal file
3
docs/en/advanced/custom-kernels/triton.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Triton
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/advanced/distributed/deepspeed.md
Normal file
3
docs/en/advanced/distributed/deepspeed.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# DeepSpeed
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/advanced/distributed/fsdp.md
Normal file
3
docs/en/advanced/distributed/fsdp.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# FSDP
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/advanced/distributed/parallel-dp-tp-ep-sp-cp.md
Normal file
3
docs/en/advanced/distributed/parallel-dp-tp-ep-sp-cp.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Parallel (DP, TP, EP, SP, CP)
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/advanced/lora-and-quantization/lora.md
Normal file
3
docs/en/advanced/lora-and-quantization/lora.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# LoRA
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/advanced/lora-and-quantization/quantization.md
Normal file
3
docs/en/advanced/lora-and-quantization/quantization.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Quantization
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
22
docs/en/conf.py
Normal file
22
docs/en/conf.py
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
# Add parent dir to path to allow importing conf.py
|
||||||
|
sys.path.insert(0, os.path.abspath(".."))
|
||||||
|
|
||||||
|
from conf import * # noqa: F403
|
||||||
|
|
||||||
|
|
||||||
|
# Language settings
|
||||||
|
language = "en"
|
||||||
|
html_search_language = "en"
|
||||||
|
|
||||||
|
# Static files
|
||||||
|
# Point to the root _static directory
|
||||||
|
html_static_path = ["../_static"]
|
||||||
|
|
||||||
|
# Add custom JS for language switcher
|
||||||
|
html_js_files = [
|
||||||
|
"js/switcher.js",
|
||||||
|
]
|
||||||
3
docs/en/data-preparation/data-processing.md
Normal file
3
docs/en/data-preparation/data-processing.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Data Processing
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/dev-guide/core/data-engine.md
Normal file
3
docs/en/dev-guide/core/data-engine.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# DataEngine
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/dev-guide/core/model-engine.md
Normal file
3
docs/en/dev-guide/core/model-engine.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# ModelEngine
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/dev-guide/core/trainer.md
Normal file
3
docs/en/dev-guide/core/trainer.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Trainer
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/dev-guide/plugins/data-plugins.md
Normal file
3
docs/en/dev-guide/plugins/data-plugins.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Data Plugins
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Initialization
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/dev-guide/plugins/model-plugins/kernels.md
Normal file
3
docs/en/dev-guide/plugins/model-plugins/kernels.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Kernels
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/dev-guide/plugins/model-plugins/rendering.md
Normal file
3
docs/en/dev-guide/plugins/model-plugins/rendering.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Rendering
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/getting-started.md
Normal file
3
docs/en/getting-started.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Getting Started
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/hyperparameters/data-argument.md
Normal file
3
docs/en/hyperparameters/data-argument.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Data Argument
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/hyperparameters/model-argument.md
Normal file
3
docs/en/hyperparameters/model-argument.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Model Argument
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/hyperparameters/sample-argument.md
Normal file
3
docs/en/hyperparameters/sample-argument.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Sample Argument
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/hyperparameters/training-argument.md
Normal file
3
docs/en/hyperparameters/training-argument.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Training Argument
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
62
docs/en/index.rst
Normal file
62
docs/en/index.rst
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
LlamaFactory Docs
|
||||||
|
=================
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Getting Started
|
||||||
|
|
||||||
|
getting-started
|
||||||
|
installation
|
||||||
|
llamaboard-web-ui
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Data Preparation
|
||||||
|
|
||||||
|
data-preparation/data-processing
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Training
|
||||||
|
|
||||||
|
training/sft
|
||||||
|
training/dpo
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Inference
|
||||||
|
|
||||||
|
inference/deploy
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Advanced
|
||||||
|
|
||||||
|
advanced/lora-and-quantization/lora
|
||||||
|
advanced/lora-and-quantization/quantization
|
||||||
|
advanced/distributed/fsdp
|
||||||
|
advanced/distributed/deepspeed
|
||||||
|
advanced/distributed/parallel-dp-tp-ep-sp-cp
|
||||||
|
advanced/custom-kernels/triton
|
||||||
|
advanced/custom-kernels/fused-operators
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Hyperparameters
|
||||||
|
|
||||||
|
hyperparameters/data-argument
|
||||||
|
hyperparameters/model-argument
|
||||||
|
hyperparameters/sample-argument
|
||||||
|
hyperparameters/training-argument
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Dev Guide
|
||||||
|
|
||||||
|
dev-guide/core/data-engine
|
||||||
|
dev-guide/core/model-engine
|
||||||
|
dev-guide/core/trainer
|
||||||
|
dev-guide/plugins/data-plugins
|
||||||
|
dev-guide/plugins/model-plugins/initialization
|
||||||
|
dev-guide/plugins/model-plugins/kernels
|
||||||
|
dev-guide/plugins/model-plugins/rendering
|
||||||
3
docs/en/inference/deploy.md
Normal file
3
docs/en/inference/deploy.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Deploy
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/installation.md
Normal file
3
docs/en/installation.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Installation
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/llamaboard-web-ui.md
Normal file
3
docs/en/llamaboard-web-ui.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# LlamaBoard Web UI
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/training/dpo.md
Normal file
3
docs/en/training/dpo.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# DPO
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
3
docs/en/training/sft.md
Normal file
3
docs/en/training/sft.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# SFT
|
||||||
|
|
||||||
|
This page is not yet available in English. Use the language switcher to view Simplified Chinese.
|
||||||
35
docs/make.bat
Normal file
35
docs/make.bat
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
@ECHO OFF
|
||||||
|
|
||||||
|
pushd %~dp0
|
||||||
|
|
||||||
|
REM Command file for Sphinx documentation
|
||||||
|
|
||||||
|
if "%SPHINXBUILD%" == "" (
|
||||||
|
set SPHINXBUILD=sphinx-build
|
||||||
|
)
|
||||||
|
set SOURCEDIR=.
|
||||||
|
set BUILDDIR=_build
|
||||||
|
|
||||||
|
if "%1" == "" goto help
|
||||||
|
|
||||||
|
%SPHINXBUILD% >NUL 2>NUL
|
||||||
|
if errorlevel 9009 (
|
||||||
|
echo.
|
||||||
|
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
|
||||||
|
echo.installed, then set the SPHINXBUILD environment variable to point
|
||||||
|
echo.to the full path of the 'sphinx-build' executable. Alternatively you
|
||||||
|
echo.may add the Sphinx directory to your PATH.
|
||||||
|
echo.
|
||||||
|
echo.If you don't have Sphinx installed, grab it from
|
||||||
|
echo.http://sphinx-doc.org/
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
|
||||||
|
goto end
|
||||||
|
|
||||||
|
:help
|
||||||
|
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
|
||||||
|
|
||||||
|
:end
|
||||||
|
popd
|
||||||
3
docs/requirements.txt
Normal file
3
docs/requirements.txt
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
sphinx>=6.0.0
|
||||||
|
sphinx-rtd-theme>=1.2.0
|
||||||
|
myst-parser>=2.0.0
|
||||||
93
docs/zh/advanced/custom-kernels/custom-kernels.md
Normal file
93
docs/zh/advanced/custom-kernels/custom-kernels.md
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
# LLaMA-Factory Kernels 系统
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
LLaMA-Factory Kernels 系统用于管理不同硬件设备提供的高性能计算内核(kernel)实现,该系统通过替换模型中的关键模块(如 RMSNorm、SwiGLU、RoPE、MoE 等)为硬件优化的版本,从而显著提升模型训练和推理的性能。
|
||||||
|
|
||||||
|
Kernels 系统采用基于注册表的自动发现机制,能够根据当前运行环境自动检测可用的硬件设备(NPU、CUDA 等),并使能相应的高性能 kernels。这种设计使得用户无需关心底层实现细节,只需简单调用接口即可获得性能提升。
|
||||||
|
|
||||||
|
## 核心特性
|
||||||
|
|
||||||
|
- **自动注册机制**:基于 `@register_kernel` 装饰器实现自动注册系统。系统启动时会自动扫描 `ops` 目录下的 kernel 实现,并将其注册到全局注册表中。
|
||||||
|
|
||||||
|
- **设备适配感知**:自动检测当前硬件设备(NPU、CUDA 等)并应用相应的优化。系统会跳过不支持的设备,确保在不同环境下都能正常工作。
|
||||||
|
|
||||||
|
- **模块化设计**:每个 kernel 独立实现,互不干扰。可以单独应用某个 kernel,也可以批量应用所有默认的 kernels。
|
||||||
|
|
||||||
|
- **后向兼容**:kernel 替换不修改模型权重,保持数值一致性。优化后的实现与原始实现保持精度一致(在浮点误差范围内)。
|
||||||
|
|
||||||
|
- **灵活扩展**:通过继承 `BaseKernel` 基类并使用装饰器,可以轻松添加新的 kernel 实现,支持新的硬件设备或优化算法。
|
||||||
|
|
||||||
|
## 使用方式
|
||||||
|
|
||||||
|
### 1. 通过训练 YAML 配置文件使用
|
||||||
|
|
||||||
|
要在训练过程中使能 kernels,只需在配置文件中增加如下配置,即可自动使能所有默认可用的 kernels:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
...
|
||||||
|
kernel_config:
|
||||||
|
name: auto
|
||||||
|
include_kernels: auto # choice: null/true/false/auto/kernel_id1,kernel_id2,kernel_id3, default is null
|
||||||
|
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 调用 API 使能
|
||||||
|
|
||||||
|
#### 2.1 apply_default_kernels 使能所有默认 kernels
|
||||||
|
|
||||||
|
`apply_default_kernels` API 能够自动应用当前设备上所有默认注册的 kernels:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from transformers import AutoModelForCausalLM
|
||||||
|
from llamafactory.v1.plugins.model_plugins.kernels import apply_default_kernels
|
||||||
|
|
||||||
|
# 加载模型
|
||||||
|
model = AutoModelForCausalLM.from_pretrained("qwen/qwen2.5-0.5B")
|
||||||
|
|
||||||
|
# 自动应用所有默认 kernels
|
||||||
|
model = apply_default_kernels(model, include_kernels="auto")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.2 apply_kernel 使能特定 kernel
|
||||||
|
|
||||||
|
如果需要更精细的控制,例如在某些场合单独应用某个 kernel,可以手动调用 `apply_kernel` 函数并传入 kernel ID:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from transformers import AutoModelForCausalLM
|
||||||
|
from llamafactory.v1.plugins.model_plugins.kernels import apply_kernel
|
||||||
|
|
||||||
|
# 加载模型
|
||||||
|
model = AutoModelForCausalLM.from_pretrained("qwen/qwen2.5-0.5B")
|
||||||
|
|
||||||
|
# 手动应用各个 kernels
|
||||||
|
# 注意:kernel ID 必须与定义时的 _kernel_id 一致
|
||||||
|
model = apply_kernel("npu_fused_rope", model=model)
|
||||||
|
model = apply_kernel("npu_fused_rmsnorm", model=model)
|
||||||
|
model = apply_kernel("npu_fused_swiglu", model=model)
|
||||||
|
model = apply_kernel("npu_fused_moe", model=model)
|
||||||
|
|
||||||
|
### 3. 查询已注册的可用 kernels
|
||||||
|
|
||||||
|
可以通过 `get_default_kernels` 获取当前环境中所有已注册且可用的默认 kernel ID:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from llamafactory.v1.plugins.model_plugins.kernels import get_default_kernels
|
||||||
|
|
||||||
|
# 获取默认 kernel 列表
|
||||||
|
available_kernels = get_default_kernels()
|
||||||
|
print(f"Available kernels: {available_kernels}")
|
||||||
|
# 输出示例: ['npu_fused_rmsnorm', 'npu_fused_swiglu', 'npu_fused_rope', 'npu_fused_moe']
|
||||||
|
```
|
||||||
|
|
||||||
|
### 当前已实现的 kernels
|
||||||
|
|
||||||
|
| Kernel ID | 功能 | 支持的设备 | 备注 |
|
||||||
|
|-----------|------|-----------|------|
|
||||||
|
| [npu_fused_rmsnorm](./fused-operators.md/#npufusedrmsnorm) | RMSNorm 融合算子 | NPU | NPU 设备的高性能 RMSNorm 实现 |
|
||||||
|
| [npu_fused_swiglu](./fused-operators.md/#npufusedswiglu) | SwiGLU 融合算子 | NPU | NPU 设备的高性能 SwiGLU 实现 |
|
||||||
|
| [npu_fused_rope](./fused-operators.md/#npufusedrope) | RoPE 融合算子 | NPU | NPU 设备的高性能 RoPE 实现 |
|
||||||
|
| [npu_fused_moe](./fused-operators.md/#npufusedmoe) | MoE 融合算子 | NPU | MoE 融合算子,适配 Qwen3-MoE 等模型 |
|
||||||
|
|
||||||
|
我们会持续适配更多的 kernels,如果您需要自己开发新的 kernels,请参考我们的 [Kernel 开发文档](../../dev-guide/plugins/model-plugins/kernels.md),欢迎您向 LLaMA-Factory 贡献代码。
|
||||||
104
docs/zh/advanced/custom-kernels/fused-operators.md
Normal file
104
docs/zh/advanced/custom-kernels/fused-operators.md
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
# Fused Operators
|
||||||
|
|
||||||
|
LLaMA-Factory 提供了一系列针对特定硬件优化的融合算子。这些算子位于 `src/llamafactory/v1/plugins/model_plugins/kernels/ops` 目录下。
|
||||||
|
|
||||||
|
系统启动时,`scan_all_kernels` 函数会自动扫描该目录,注册所有可用的算子。您可以通过 `apply_default_kernels(model, include_kernels="auto")` 一键启用它们,或者使用 `apply_kernel` 单独启用。
|
||||||
|
|
||||||
|
以下是当前支持的融合算子详情:
|
||||||
|
|
||||||
|
## NpuFusedRMSNorm
|
||||||
|
RMSNorm(Root Mean Square Layer Normalization)是一种常用于大模型的归一化方法。在推理或训练中,RMSNorm 融合算子 将bias、residual等操作进行融合,可以减少显存访问次数,加速计算。
|
||||||
|
|
||||||
|
Ascend npu 通过 `torch_npu.npu_rms_norm` 接口提供 RMSNorm 融合算子调用接口,支持 float16, bfloat16, float 等数据格式。RMSNorm 算子常见于Qwen等LLM模型中,由于torch侧没有提供 RMSNorm 算子的接口,因此在模型中通常是以自定义类的形式出现,通过替换 RMSNorm 类的 `forward` 方法即可使能。
|
||||||
|
|
||||||
|
```python
|
||||||
|
def _npu_rms_forward(self, hidden_states):
|
||||||
|
"""NPU forward implementation for RMSNorm.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
self: RMSNorm module instance with `weight` and `variance_epsilon`.
|
||||||
|
hidden_states: Input hidden states tensor, same shape as the baseline.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Normalized tensor consistent with the baseline RMSNorm behavior.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return torch_npu.npu_rms_norm(hidden_states, self.weight, epsilon=self.variance_epsilon)[0]
|
||||||
|
```
|
||||||
|
|
||||||
|
在 LlamaFactory 中,通过 `NpuRMSNormKernel` 提供使能该融合算子的入口,只需要调用 `apply_kernel("npu_fused_rmsnorm", model=model)` 即可针对已适配的模型使能 npu RMSNorm 融合算子。
|
||||||
|
|
||||||
|
## NpuFusedSwiGlu
|
||||||
|
SwiGLU(Swish-Gated Linear Unit)是一种结合了Swish激活函数和门控线性单元(GLU)的混合激活函数,其主要功能是对输入张量进行门控线性变换,近年来被广泛应用于 LLM 模型中的 MLP 层。SwiGLU 融合算子将分割、激活、矩阵乘等多个操作融合为单一硬件指令,避免多次内核启动开销。
|
||||||
|
|
||||||
|
Ascend npu 通过 `torch_npu.npu_swiglu` 接口提供 SwiGLU 融合算子调用接口,支持 float16,bfloat16,float SwiGLU 算子常见于Qwen等LLM模型中,由于torch侧没有提供 SwiGLU 算子的接口,因此在模型中通常是以自定义类的形式出现,通过替换 SwiGLU 类的 `forward` 方法即可使能。替换过程可参考如下示例:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 原始 MLP forward 方法:
|
||||||
|
def forward(self, x):
|
||||||
|
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
||||||
|
return down_proj
|
||||||
|
|
||||||
|
# 替换后的 forward 方法:
|
||||||
|
def _npu_swiglu_forward(self, hidden_state):
|
||||||
|
return self.down_proj(
|
||||||
|
torch_npu.npu_swiglu(torch.cat((self.gate_proj(hidden_state), self.up_proj(hidden_state)), dim=-1), dim=-1)
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
在 LLaMA-Factory 中,通过 `NpuSwiGluKernel` 提供使能该融合算子的入口,只需要调用 `apply_kernel("npu_fused_swiglu", model=model)` 即可针对已适配的模型使能 npu SwiGLU 融合算子。对于未适配的模型,如有需要,您可根据示例以及[开发者文档](../../dev-guide/plugins/model-plugins/kernels.md)自行适配。
|
||||||
|
|
||||||
|
|
||||||
|
## NpuFusedRoPE
|
||||||
|
RoPE(Rotary Positional Embedding,旋转式位置嵌入) 是一种位置编码技术,广泛应用于 Qwen 等 LLM 模型中,用于有效编码文本序列的位置信息。它结合了绝对位置编码的稳定性与相对位置编码的灵活性,同时具备优秀的长度泛化能力。传统 RoPE 算子通常在 LLM 等模型结构中通过自定义函数的形式实现。RoPE 融合算子将原计算流程合并为单个硬件优化算子,从而提升性能。
|
||||||
|
|
||||||
|
Ascend npu 通过 `torch_npu.npu_rotary_mul` 提供 RoPE 融合算子调用接口,支持 float16,bfloat16,float32 等数据格式。以 Qwen3 系列模型为例,通过替换其 `apply_rotary_pos_emb` 函数即可实现 RoPE融合算子使能:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 原始 apply_rotary_pos_emb:
|
||||||
|
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||||
|
cos = cos.unsqueeze(unsqueeze_dim)
|
||||||
|
sin = sin.unsqueeze(unsqueeze_dim)
|
||||||
|
q_embed = (q * cos) + (rotate_half(q) * sin)
|
||||||
|
k_embed = (k * cos) + (rotate_half(k) * sin)
|
||||||
|
return q_embed, k_embed
|
||||||
|
|
||||||
|
# 替换 RoPE 融合算子后:
|
||||||
|
def _apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||||
|
cos = cos.unsqueeze(unsqueeze_dim)
|
||||||
|
sin = sin.unsqueeze(unsqueeze_dim)
|
||||||
|
q_embed = torch_npu.npu_rotary_mul(q, cos, sin)
|
||||||
|
k_embed = torch_npu.npu_rotary_mul(k, cos, sin)
|
||||||
|
return q_embed, k_embed
|
||||||
|
```
|
||||||
|
|
||||||
|
在 LLaMA-Factory 中,通过 `NpuRoPEKernel` 提供使能该融合算子的入口,只需要调用 `apply_kernel("npu_fused_rope", model=model)` 即可针对已适配的模型使能 npu RoPE 融合算子。对于未适配的模型,如有需要,您可根据示例以及[开发者文档](../../dev-guide/plugins/model-plugins/kernels.md)自行适配。
|
||||||
|
|
||||||
|
|
||||||
|
## NpuFusedMoE
|
||||||
|
MoE(Mixture of Experts)模型通过稀疏激活扩展容量。在原生 Transformers 实现中,使用串行循环遍历专家,导致内核启动开销大、硬件利用率低。
|
||||||
|
|
||||||
|
**MoE 融合算子** 利用 **GMM(Grouped Matrix Multiplication,分组矩阵乘)** 技术,支持在单个硬件指令内并行处理多组不同形状(行数不一)的矩阵乘法,消减循环开销,同时无需额外的显存复制,显著提升训练性能。
|
||||||
|
|
||||||
|
Ascend npu 通过 `torch_npu.npu_grouped_matmul` 等接口提供底层支持,通过替换模型中的 MoE Block forward 方法,即可利用 NPU 的分组矩阵乘能力。
|
||||||
|
|
||||||
|
核心逻辑替换如下(简化示意):
|
||||||
|
|
||||||
|
```python
|
||||||
|
def _npu_moe_forward(self, hidden_states, routing_weights, router_indices):
|
||||||
|
# 1. 排序:将乱序的 Token 按指派的专家归类,并生成索引映射
|
||||||
|
permuted_states, row_map = torch_npu.npu_moe_token_permute(hidden_states, router_indices)
|
||||||
|
|
||||||
|
# 2. 统计:计算每个专家需要处理的 Token 数量
|
||||||
|
tokens_per_expert = torch.histc(router_indices, bins=self.num_experts, min=0, max=self.num_experts)
|
||||||
|
|
||||||
|
# 3. 计算 (GMM):一次性并行计算所有专家的权重,自动适配不同专家的输入长度
|
||||||
|
inter_states = torch_npu.npu_grouped_matmul(permuted_states, self.gate_up_proj_weights, split_sizes=tokens_per_expert, ...)
|
||||||
|
inter_states = torch_npu.npu_swiglu(inter_states)
|
||||||
|
output = torch_npu.npu_grouped_matmul(inter_states, self.down_proj_weights, split_sizes=tokens_per_expert, ...)
|
||||||
|
|
||||||
|
# 4. 还原:将结果恢复成原始 Token 顺序并应用路由权重
|
||||||
|
return torch_npu.npu_moe_token_unpermute(output, row_map, routing_weights)
|
||||||
|
```
|
||||||
|
|
||||||
|
在 LLaMA-Factory 中,通过 `NpuFusedMoEKernel` 提供使能该融合算子的入口。只需要调用 `apply_kernel("npu_fused_moe", model=model)` 即可针对已适配的模型使能 NPU MoE 融合算子。对于未适配的模型,您也可以参考上述示例代码以及[开发者文档](../../dev-guide/plugins/model-plugins/kernels.md)自行适配。
|
||||||
1
docs/zh/advanced/custom-kernels/triton.md
Normal file
1
docs/zh/advanced/custom-kernels/triton.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Triton
|
||||||
1
docs/zh/advanced/distributed/deepspeed.md
Normal file
1
docs/zh/advanced/distributed/deepspeed.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# DeepSpeed
|
||||||
1
docs/zh/advanced/distributed/fsdp.md
Normal file
1
docs/zh/advanced/distributed/fsdp.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# FSDP
|
||||||
1
docs/zh/advanced/distributed/parallel-dp-tp-ep-sp-cp.md
Normal file
1
docs/zh/advanced/distributed/parallel-dp-tp-ep-sp-cp.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Parallel(DP, TP, EP, SP, CP)
|
||||||
3
docs/zh/advanced/lora-and-quantization/lora.md
Normal file
3
docs/zh/advanced/lora-and-quantization/lora.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Lora
|
||||||
|
|
||||||
|
参数管理(二级参数形式)
|
||||||
1
docs/zh/advanced/lora-and-quantization/quantization.md
Normal file
1
docs/zh/advanced/lora-and-quantization/quantization.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Quantization
|
||||||
22
docs/zh/conf.py
Normal file
22
docs/zh/conf.py
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
# Add parent dir to path to allow importing conf.py
|
||||||
|
sys.path.insert(0, os.path.abspath(".."))
|
||||||
|
|
||||||
|
from conf import * # noqa: F403
|
||||||
|
|
||||||
|
|
||||||
|
# Language settings
|
||||||
|
language = "zh_CN"
|
||||||
|
html_search_language = "zh"
|
||||||
|
|
||||||
|
# Static files
|
||||||
|
# Point to the root _static directory
|
||||||
|
html_static_path = ["../_static"]
|
||||||
|
|
||||||
|
# Add custom JS for language switcher
|
||||||
|
html_js_files = [
|
||||||
|
"js/switcher.js",
|
||||||
|
]
|
||||||
479
docs/zh/data-preparation/data-processing.md
Normal file
479
docs/zh/data-preparation/data-processing.md
Normal file
@@ -0,0 +1,479 @@
|
|||||||
|
# LLaMA-Factory v1 数据预处理
|
||||||
|
|
||||||
|
## 总览
|
||||||
|
|
||||||
|
LLaMA-Factory `v1` 采用了全新的数据处理架构,主要包含以下核心组件:
|
||||||
|
|
||||||
|
- **DataEngine**:数据引擎,负责数据集的加载、索引和转换等各种插件的接入和调用,并提供数据访问接口
|
||||||
|
- **DataConverterPlugin**:数据转换器,将非标准格式转换为统一的标准格式
|
||||||
|
- **DataLoaderPlugin**:数据加载插件,支持多种文件格式的加载
|
||||||
|
- **DataIndexPlugin**:数据索引插件,支持数据集的采样和权重调整
|
||||||
|
- **DataSelectorPlugin**:数据选择插件,支持灵活的数据访问方式
|
||||||
|
|
||||||
|
与 LLaMA-Factory `v0` 版本相比,`v1` 版本采用了统一的数据格式(Messages Format),所有数据都会被转换为标准的对话消息列表;此外,`v1` 版本通过 DataEngine 与 Plugin 机制,提供了自定义数据处理流的接口,具有更好的可扩展性和一致性。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
- [基本用法](#基本用法)
|
||||||
|
- [标准数据格式](#标准数据格式)
|
||||||
|
- [数据集配置文件](#数据集配置文件)
|
||||||
|
- [完整示例](#完整示例)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 基本用法
|
||||||
|
|
||||||
|
### 在训练配置文件,可以通过如下方式配置数据集:
|
||||||
|
|
||||||
|
<details open>
|
||||||
|
<summary>方式 1:使用 HF Hub Repo ID</summary>
|
||||||
|
|
||||||
|
直接指定 HF Hub 上的数据集 Repo ID,DataEngine 会自动从 HF Hub 下载并加载数据集。
|
||||||
|
|
||||||
|
注:使用 Repo ID 直接加载的数据集需要为标准格式
|
||||||
|
|
||||||
|
**训练配置文件示例:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# example_sft.yaml
|
||||||
|
|
||||||
|
...
|
||||||
|
|
||||||
|
dataset: llamafactory/v1-sft-demo # HF Hub Repo ID
|
||||||
|
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>方式 2:使用 HF Hub 上的 YAML 配置文件</summary>
|
||||||
|
|
||||||
|
`dataset`字段指定 HF Hub 上的 `dataset_info.yaml` 的 URI,DataEngine 会自动下载该配置文件并根据其中的配置加载数据集。
|
||||||
|
|
||||||
|
**训练配置文件示例:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# example_sft.yaml
|
||||||
|
|
||||||
|
...
|
||||||
|
|
||||||
|
dataset: llamafactory/v1-sft-demo/dataset_info.yaml # 远程 dataset_info.yaml 路径
|
||||||
|
|
||||||
|
...
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>方式 3:使用本地 HF 数据集文件路径</summary>
|
||||||
|
|
||||||
|
`dataset`字段指定本地的数据集文件路径(`.json`、`.jsonl` 等)
|
||||||
|
|
||||||
|
注:直接指定数据集文件路径,要求该数据文件的格式已为标准格式
|
||||||
|
|
||||||
|
**训练配置文件示例:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# example_sft.yaml
|
||||||
|
|
||||||
|
...
|
||||||
|
|
||||||
|
dataset: ~/data/v1_sft_demo.jsonl # 本地数据集文件绝对路径
|
||||||
|
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>方式 4:使用本地 YAML 配置文件路径</summary>
|
||||||
|
|
||||||
|
`dataset`字段指定本地的 `dataset_info.yaml` 配置文件路径,DataEngine 会根据该配置加载其中的数据集。
|
||||||
|
|
||||||
|
**训练配置文件示例:**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# example_sft.yaml
|
||||||
|
|
||||||
|
...
|
||||||
|
|
||||||
|
dataset: ~/data/dataset_info.yaml # 本地 dataset_info.yaml 文件路径
|
||||||
|
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 标准数据格式
|
||||||
|
|
||||||
|
v1 使用统一的 **Messages 格式**作为标准数据格式。每个样本都是一个包含 `messages` 字段的 JSON 对象。
|
||||||
|
|
||||||
|
针对alpaca、sharegpt、以及dpo等格式的数据,可以通过内置的`DataConverterPlugin`插件,自动将其转化为标准格式,对于其他自定义格式的数据,用户也可通过自定义`DataConverterPlugin`来实现数据格式标准化,这部分内容参见[`DataConverterPlugin`](../dev-guide/plugins/data-plugins.md/#data-converter-plugin)
|
||||||
|
|
||||||
|
### 1. SFT(监督微调)样本格式
|
||||||
|
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "system",
|
||||||
|
"content": [{"type": "text", "value": "You are a helpful assistant."}],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [{"type": "text", "value": "Hello, who are you?"}],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [{"type": "text", "value": "I am an AI assistant."}],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 字段说明:
|
||||||
|
|
||||||
|
- **messages**: 消息列表,包含一轮或多轮对话
|
||||||
|
- **role**: 消息角色,可选值:
|
||||||
|
- `"system"`: 系统提示
|
||||||
|
- `"user"`: 用户输入
|
||||||
|
- `"assistant"`: 模型回复
|
||||||
|
- **content**: 内容列表,每个元素包含:
|
||||||
|
- **type**: 内容类型,可选值:
|
||||||
|
- `"text"`: 文本内容
|
||||||
|
- `"image_url"`: 图像 URL(多模态)
|
||||||
|
- `"audio_url"`: 音频 URL(多模态)
|
||||||
|
- `"video_url"`: 视频 URL(多模态)
|
||||||
|
- `"tools"`: 工具描述
|
||||||
|
- `"tool_calls"`: 工具调用
|
||||||
|
- `"reasoning"`: 推理过程
|
||||||
|
- **value**: 具体内容(字符串)
|
||||||
|
- **loss_weight**: 损失权重(浮点数)
|
||||||
|
- `0.0`: 不计算损失(用于提示词部分)
|
||||||
|
- `1.0`: 完全计算损失(用于回复部分)
|
||||||
|
- 可设置为其他值以调整不同部分的学习权重
|
||||||
|
|
||||||
|
- **_dataset_name** (可选): 数据集名称,由 DataEngine 自动添加
|
||||||
|
- **extra_info** (可选): 额外信息字段
|
||||||
|
|
||||||
|
### 2. DPO(偏好对齐)样本格式
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"chosen_messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [{"type": "text", "value": "用户提问"}],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [{"type": "text", "value": "更优的回答"}],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rejected_messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [{"type": "text", "value": "用户提问"}],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [{"type": "text", "value": "较差的回答"}],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 多模态支持
|
||||||
|
|
||||||
|
对于多模态数据,可以在 `content` 列表中添加非文本类型的内容:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "value": "这张图片里有什么?"},
|
||||||
|
{"type": "image_url", "value": "path/to/image.jpg"}
|
||||||
|
],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [{"type": "text", "value": "图片中有一只猫。"}],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**说明**:`image_url`、`audio_url`、`video_url` 的路径可以是相对路径或绝对路径,具体加载方式由 `DataLoaderPlugin` 决定。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 数据集配置文件
|
||||||
|
|
||||||
|
### 1. dataset_info.yaml 配置文件格式
|
||||||
|
|
||||||
|
`dataset_info.yaml` 支持同时配置多个数据集,支持分别从 HF Hub 和本地获取数据集,数据集默认会混合并打乱顺序。
|
||||||
|
|
||||||
|
**示例配置文件:`data/dataset_info.yaml`**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# 数据集 1:使用本地文件 + Alpaca 转换器
|
||||||
|
identity:
|
||||||
|
file_name: ~/data/identity.json #本地数据集文件绝对路径
|
||||||
|
converter: alpaca # 使用 alpaca 转换器
|
||||||
|
|
||||||
|
# 数据集 2:指定自定义数据集目录
|
||||||
|
alpaca_en_demo:
|
||||||
|
file_name: ~/data/alpaca_en_demo.json # 数据集文件名
|
||||||
|
converter: alpaca # 转换器插件
|
||||||
|
size: 500 # 只使用 500 个样本
|
||||||
|
weight: 0.5 # 数据集权重,用于控制该数据集的采样频率
|
||||||
|
split: train # 数据集划分,默认为 train
|
||||||
|
streaming: false # 是否流式加载,默认为 false
|
||||||
|
|
||||||
|
# 数据集 3:从 Hugging Face Hub 加载
|
||||||
|
hf_dataset:
|
||||||
|
hf_hub_url: llamafactory/v1-sft-demo # HF repo ID
|
||||||
|
streaming: false
|
||||||
|
|
||||||
|
# 数据集 4:已经是标准格式,无需转换器
|
||||||
|
standard:
|
||||||
|
file_name: ~/data/v1_sft_demo.jsonl # 本地标准数据集文件路径
|
||||||
|
|
||||||
|
# 数据集 5:自定义数据集和 converter 插件
|
||||||
|
custom_dataset:
|
||||||
|
file_name: custom_data.json
|
||||||
|
converter: custom_converter
|
||||||
|
weight: 1.0
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置字段说明
|
||||||
|
|
||||||
|
#### 数据源配置(二者必选其一):
|
||||||
|
|
||||||
|
- **hf_hub_url** (str): Hugging Face Hub 数据集仓库 ID
|
||||||
|
- 示例:`"llamafactory/v1-sft-demo"`
|
||||||
|
- 如果指定,则从 HF Hub 加载数据集
|
||||||
|
|
||||||
|
- **file_name** (str): 本地文件路径
|
||||||
|
- 支持格式:`.json`、`.jsonl`、`.csv`、`.parquet`、`.arrow`、`.txt`
|
||||||
|
|
||||||
|
#### 可选配置:
|
||||||
|
|
||||||
|
- **split** (str): 数据集划分,默认为 `"train"`
|
||||||
|
- **converter** (str): 数据转换器名称
|
||||||
|
- 可选值:`"alpaca"`(更多转换器持续添加中,也可在 data_plugin 中添加自定义 converter)
|
||||||
|
- 如果不指定,则假定数据已是标准格式
|
||||||
|
- **size** (int): 使用的样本数量,默认使用全部
|
||||||
|
- **weight** (float): 数据集权重,用于混合数据集时的采样频率,默认为 1.0
|
||||||
|
- **streaming** (bool): 是否流式加载,默认为 `False`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
## 完整示例
|
||||||
|
|
||||||
|
### 1. 基础使用示例
|
||||||
|
|
||||||
|
```python
|
||||||
|
from llamafactory.v1.config.data_args import DataArguments
|
||||||
|
from llamafactory.v1.core.data_engine import DataEngine
|
||||||
|
|
||||||
|
# 使用本地 YAML 配置
|
||||||
|
data_args = DataArguments(
|
||||||
|
dataset="~/data/v1_sft_demo.jsonl",
|
||||||
|
cutoff_len=2048
|
||||||
|
)
|
||||||
|
|
||||||
|
# 初始化 DataEngine
|
||||||
|
engine = DataEngine(data_args=data_args)
|
||||||
|
|
||||||
|
# 查看数据集信息
|
||||||
|
print(f"数据集总样本数: {len(engine)}")
|
||||||
|
print(f"数据集列表: {list(engine.datasets.keys())}")
|
||||||
|
|
||||||
|
# 访问数据样本
|
||||||
|
sample = engine[0]
|
||||||
|
print(f"样本格式: {sample.keys()}")
|
||||||
|
print(f"消息列表: {sample['messages']}")
|
||||||
|
|
||||||
|
# 批量访问
|
||||||
|
batch = engine[0:10]
|
||||||
|
print(f"批量样本数: {len(batch)}")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 输出示例
|
||||||
|
|
||||||
|
**查看数据集信息输出:**
|
||||||
|
|
||||||
|
```
|
||||||
|
数据集总样本数: 500
|
||||||
|
数据集列表: ['default']
|
||||||
|
样本格式: dict_keys(['_dataset_name', 'messages'])
|
||||||
|
消息列表: [{'role': 'user', 'content': [{'type': 'text', 'value': 'hi'}], 'loss_weight': 0.0}, {'role': 'assistant', 'content': [{'type': 'text', 'value': 'Hello! I am {{name}}, an AI assistant developed by {{author}}. How can I assist you today?'}], 'loss_weight': 1.0}]
|
||||||
|
批量样本数: 10
|
||||||
|
```
|
||||||
|
|
||||||
|
**访问单个样本输出:**
|
||||||
|
|
||||||
|
```python
|
||||||
|
{
|
||||||
|
'_dataset_name': 'alpaca_en_demo',
|
||||||
|
'messages': [
|
||||||
|
{
|
||||||
|
'role': 'user',
|
||||||
|
'content': [{'type': 'text', 'value': 'What is the capital of France?'}],
|
||||||
|
'loss_weight': 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'role': 'assistant',
|
||||||
|
'content': [{'type': 'text', 'value': 'The capital of France is Paris.'}],
|
||||||
|
'loss_weight': 1.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 混合多数据集配置文件示例
|
||||||
|
|
||||||
|
**配置文件:`data/mixed_datasets.yaml`**
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
dataset_1:
|
||||||
|
file_name: alpaca_en_demo.json
|
||||||
|
converter: alpaca
|
||||||
|
weight: 1.0
|
||||||
|
|
||||||
|
dataset_2:
|
||||||
|
file_name: identity.json
|
||||||
|
converter: alpaca
|
||||||
|
weight: 2.0
|
||||||
|
|
||||||
|
dataset_3:
|
||||||
|
hf_hub_url: llamafactory/v1-sft-demo
|
||||||
|
weight: 1.5
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### 4. 多模态数据示例
|
||||||
|
|
||||||
|
**数据文件:`data/multimodal_demo.jsonl`**
|
||||||
|
|
||||||
|
标准化后数据示例:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "value": "Who are they?"},
|
||||||
|
{"type": "image_url", "value": "mllm_demo_data/1.jpg"}
|
||||||
|
],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "value": "They're Kane and Gretzka from Bayern Munich."}
|
||||||
|
],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "value": "What are they doing?"},
|
||||||
|
{"type": "image_url", "value": "mllm_demo_data/1.jpg"}
|
||||||
|
],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "value": "They are celebrating on the soccer field."}
|
||||||
|
],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "value": "Who is he?"},
|
||||||
|
{"type": "image_url", "value": "mllm_demo_data/2.jpg"}
|
||||||
|
],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "value": "He's Thomas Muller from Bayern Munich."}
|
||||||
|
],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "value": "Why is he on the ground?"}
|
||||||
|
],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "value": "Because he's sliding on his knees to celebrate."}
|
||||||
|
],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
```python
|
||||||
|
from llamafactory.v1.config.data_args import DataArguments
|
||||||
|
from llamafactory.v1.core.data_engine import DataEngine
|
||||||
|
|
||||||
|
data_args = DataArguments(dataset="data/multimodal_demo.jsonl")
|
||||||
|
engine = DataEngine(data_args=data_args)
|
||||||
|
|
||||||
|
# 访问多模态样本
|
||||||
|
sample = engine[0]
|
||||||
|
print("用户消息内容:")
|
||||||
|
for content_item in sample['messages'][0]['content']:
|
||||||
|
print(f" 类型: {content_item['type']}, 值: {content_item['value']}")
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**注意事项**:
|
||||||
|
|
||||||
|
1. 所有数据最终都会转换为标准的 Messages 格式
|
||||||
|
2. 通过 `converter` 插件可以支持多种数据格式
|
||||||
|
3. 通过 `weight` 和 `size` 参数可以灵活控制数据分布
|
||||||
|
4. 支持同时使用本地数据集和 HuggingFace Hub 数据集
|
||||||
|
5. 多模态数据通过在 `content` 中添加不同类型的元素来支持
|
||||||
|
6. 更多细节信息请参考我们的 [API REFERENCE](../dev-guide/core/data-engine.md/#data-engine)
|
||||||
253
docs/zh/dev-guide/core/data-engine.md
Normal file
253
docs/zh/dev-guide/core/data-engine.md
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
# DataEngine
|
||||||
|
|
||||||
|
## 1. DataEngine 简介
|
||||||
|
|
||||||
|
|
||||||
|
`DataEngine` 是 LLaMA-Factory v1 数据处理的核心类,继承自 PyTorch 的 `Dataset`,负责各种插件的接入,其他功能(如数据格式转换、数据加载等)均通过插件的形式实现并接入 `DataEngine`。
|
||||||
|
|
||||||
|
`DataEngine`接受一个唯一入参:`DataArguments` 实例,所有的元数据集信息均通过该参数配置传入。
|
||||||
|
|
||||||
|
## 2. DataEngine 与 DataArguments 接口定义
|
||||||
|
|
||||||
|
```python
|
||||||
|
@dataclass
|
||||||
|
class DataArguments:
|
||||||
|
""" `DataEngine`初始化入参
|
||||||
|
|
||||||
|
args:
|
||||||
|
dataset (str): 数据集路径,远程数据集 repo id / dataset_info.yaml 路径,或本地数据集路径/dataset_info.yaml路径
|
||||||
|
cutoff_len (int): 数据集截止长度,即数据集最大样本采样数量
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
class DataEngine(Dataset):
|
||||||
|
"""数据引擎(DataEngine)
|
||||||
|
|
||||||
|
`DataEngine` 负责数据集的加载与统一管理,支持:
|
||||||
|
- 从本地路径或 Hugging Face Hub 加载数据
|
||||||
|
- 通过插件机制加载自定义数据
|
||||||
|
- 构建统一的数据索引
|
||||||
|
- 支持流式(streaming)与非流式数据访问
|
||||||
|
|
||||||
|
attr:
|
||||||
|
args (DataArguments): 数据参数配置
|
||||||
|
datasets (dict[str, HFDataset]): 数据集名称到数据对象的映射
|
||||||
|
dataset_infos (dict[str, DatasetInfo]): 数据集名称到元信息的映射
|
||||||
|
data_index (list[tuple[str, int]]): 数据索引列表,每项为 (dataset_name, sample_index)
|
||||||
|
streaming (bool): 是否为流式数据集
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, data_args: DataArguments) -> None:
|
||||||
|
"""初始化 `DataEngine`
|
||||||
|
|
||||||
|
初始化时自动执行以下步骤:
|
||||||
|
1. 调用 `get_dataset_info`, 从 `data_args` 读取并解析数据集元信息
|
||||||
|
2. 调用 `load_dataset`,根据配置加载数据集
|
||||||
|
3. 调用 `build_data_index`,构建统一的索引列表
|
||||||
|
|
||||||
|
args:
|
||||||
|
data_args (DataArguments): 数据参数配置对象
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def get_dataset_info(self) -> None:
|
||||||
|
"""从配置文件或远程仓库加载数据集元信息
|
||||||
|
|
||||||
|
根据 `self.args.dataset` 确定数据源,数据源支持如下选项:
|
||||||
|
- 本地 YAML 配置文件路径
|
||||||
|
- Hugging Face Hub 上的 YAML 配置文件路径
|
||||||
|
- 本地数据集文件路径
|
||||||
|
- Hugging Face Hub 数据集 repo id
|
||||||
|
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def load_dataset(self) -> None:
|
||||||
|
"""根据数据集元信息加载所有数据集
|
||||||
|
|
||||||
|
每个数据集条目可以包含以下字段:
|
||||||
|
- `hf_hub_url`: 使用 `datasets.load_dataset` 加载
|
||||||
|
- 本地数据文件:通过 `DataLoaderPlugin` 插件加载
|
||||||
|
- `streaming`: 是否启用流式模式
|
||||||
|
|
||||||
|
更新:
|
||||||
|
self.datasets (dict): 数据集名称到已加载数据对象的映射
|
||||||
|
self.streaming (bool): 如果任一数据集为流式模式,则设置为 True
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def build_data_index(self) -> None:
|
||||||
|
"""构建统一的数据索引
|
||||||
|
|
||||||
|
为所有数据集创建全局索引列表 `(dataset_name, sample_index)`
|
||||||
|
|
||||||
|
当启用流式模式时,生成固定长度(例如 1000)的占位索引;
|
||||||
|
否则,为每条样本建立索引。
|
||||||
|
|
||||||
|
插件 `DataIndexPlugin` 可根据数据集大小或权重调整索引分布
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def _convert_data_sample(self, raw_sample: dict[str, Any], dataset_name: str) -> Sample:
|
||||||
|
"""将原始样本转换为统一格式
|
||||||
|
|
||||||
|
根据 `dataset_info` 中的 `converter` 字段,调用对应的转换插件,
|
||||||
|
将原始样本标准化为统一的数据结构。
|
||||||
|
|
||||||
|
args:
|
||||||
|
raw_sample (dict[str, Any]): 原始数据样本
|
||||||
|
dataset_name (str): 样本所属的数据集名称
|
||||||
|
|
||||||
|
return:
|
||||||
|
Sample: 转换后的标准化格式样本
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def __len__(self) -> int:
|
||||||
|
"""返回数据集的总样本数
|
||||||
|
|
||||||
|
return:
|
||||||
|
int: 数据集长度
|
||||||
|
如果为流式数据集,返回 `-1`
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def __getitem__(self, index: Union[int, Any]) -> Union[Sample, list[Sample]]:
|
||||||
|
"""根据索引或选择器获取样本
|
||||||
|
|
||||||
|
args:
|
||||||
|
index (Union[int, Any]): 数据索引,int 或 list[int]
|
||||||
|
|
||||||
|
return:
|
||||||
|
Union[Sample, list[Sample]]: 单个样本或样本列表
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def __iter__(self) -> Iterable:
|
||||||
|
"""返回数据集迭代器
|
||||||
|
|
||||||
|
用于非流式数据集的顺序或随机访问
|
||||||
|
流式模式下需要实现异步加载逻辑
|
||||||
|
|
||||||
|
return:
|
||||||
|
Iterable: 数据集迭代器。
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
async def __aiter__(self) -> AsyncIterable:
|
||||||
|
"""返回异步数据集迭代器
|
||||||
|
|
||||||
|
用于流式数据集或异步数据加载场景
|
||||||
|
允许在异步环境中以流的方式读取样本
|
||||||
|
|
||||||
|
return:
|
||||||
|
AsyncIterable: 异步迭代器,按顺序产出样本
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
`DataArguments` 参数说明:
|
||||||
|
|
||||||
|
`dataset`: 数据集路径,支持本地或远程,当传入本地数据集文件路径时,需要满足该数据集为标准格式;否则需要传入 `dataset_info.yaml` 来配置数据集的 `converter` 等元信息,以告知 `DataEngine` 应当如何处理该数据。
|
||||||
|
|
||||||
|
`cutoff_len`: 数据集的截止长度,即该数据集的最大样本数量。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. DataEngine 核心方法
|
||||||
|
|
||||||
|
### 3.1 `get_dataset_info`:加载数据元信息
|
||||||
|
|
||||||
|
根据 `dataset` 参数加载数据集配置,获取数据位置、数据格式、插件配置等所有数据元信息,在实例化 `DataEngine` 时会自动调用此方法。
|
||||||
|
|
||||||
|
### 3.2 加载数据集:`load_dataset`
|
||||||
|
|
||||||
|
遍历所有数据源,根据不同的数据源加载数据,在实例化 `DataEngine` 时会自动调用此方法。
|
||||||
|
|
||||||
|
```python
|
||||||
|
for key, value in self.dataset_infos.items():
|
||||||
|
split = value.get("split", "train")
|
||||||
|
streaming = value.get("streaming", False)
|
||||||
|
|
||||||
|
if "hf_hub_url" in value:
|
||||||
|
# 从 HF Hub 加载
|
||||||
|
dataset = load_dataset(value["hf_hub_url"], split=split, streaming=streaming)
|
||||||
|
else:
|
||||||
|
# 使用 DataLoaderPlugin 加载本地文件
|
||||||
|
dataset = DataLoaderPlugin(args=self.args).auto_load_data(value)
|
||||||
|
|
||||||
|
self.datasets[key] = dataset
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 `build_data_index`:构建数据索引
|
||||||
|
|
||||||
|
为每个数据集创建索引列表 `[(dataset_name, sample_index), ...]`, `DataIndexPlugin`插件在此处被调用,可控制各数据集的采样频率、采样方式等,在实例化`DataEngine`时会自动调用此方法。
|
||||||
|
|
||||||
|
```python
|
||||||
|
for dataset_name, dataset in self.datasets.items():
|
||||||
|
# 创建基础索引
|
||||||
|
data_index = [(dataset_name, idx) for idx in range(len(dataset))]
|
||||||
|
|
||||||
|
# 根据 size 和 weight 调整索引
|
||||||
|
size = self.dataset_infos[dataset_name].get("size")
|
||||||
|
weight = self.dataset_infos[dataset_name].get("weight")
|
||||||
|
if size or weight:
|
||||||
|
data_index = DataIndexPlugin().adjust_data_index(data_index, size, weight)
|
||||||
|
|
||||||
|
self.data_index.extend(data_index)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.4 `_convert_data_sample`:数据格式标准化
|
||||||
|
|
||||||
|
将原始数据转换为标准格式,`DataConverterPlugin`插件在此处被调用,具体调用的插件由 `get_dataset_info` 方法获取的 `converter` 信息指定,若 `converter` 为空则假定数据集为标准格式,此方法由`DataEngine`的 `__getitem__` 方法调用。
|
||||||
|
|
||||||
|
```python
|
||||||
|
def _convert_data_sample(self, raw_sample: dict, dataset_name: str) -> Sample:
|
||||||
|
converter = self.dataset_infos[dataset_name].get("converter")
|
||||||
|
if converter is not None:
|
||||||
|
# 使用指定的转换器
|
||||||
|
from ..plugins.data_plugins.converter import get_converter
|
||||||
|
return {"_dataset_name": dataset_name, **get_converter(converter)(raw_sample)}
|
||||||
|
else:
|
||||||
|
# 已经是标准格式
|
||||||
|
return {"_dataset_name": dataset_name, **raw_sample}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 初始化
|
||||||
|
|
||||||
|
`DataEngine` 初始化过程只需传入一个构建好的 `DataArguments` 即可,后续可通过该 `DataEngine` 访问数据集中的数据。
|
||||||
|
|
||||||
|
```python
|
||||||
|
from llamafactory.v1.config.data_args import DataArguments
|
||||||
|
from llamafactory.v1.core.data_engine import DataEngine
|
||||||
|
|
||||||
|
# 1. 创建数据参数
|
||||||
|
data_args = DataArguments(
|
||||||
|
dataset="~/data/v1_sft_demo.jsonl",
|
||||||
|
cutoff_len=2048
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. 初始化 Data Engine
|
||||||
|
data_engine = DataEngine(data_args=data_args)
|
||||||
|
|
||||||
|
# 3. 访问数据
|
||||||
|
sample = data_engine[0] # 获取第一个样本
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. 数据访问方式
|
||||||
|
|
||||||
|
实例化后的`DataEngine`支持整数索引、列表索引、以及切片等访问方式,其数据读取用法可等价于 Python 列表。
|
||||||
|
|
||||||
|
```python
|
||||||
|
sample = data_engine[0] # 获取第一个样本
|
||||||
|
|
||||||
|
sample = data_engine[0:10] # 获取前 10 个样本
|
||||||
|
|
||||||
|
sample = data_engine[[0, 5, 10]] # 获取指定索引的样本
|
||||||
|
|
||||||
|
```
|
||||||
1
docs/zh/dev-guide/core/model-engine.md
Normal file
1
docs/zh/dev-guide/core/model-engine.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# ModelEngine
|
||||||
1
docs/zh/dev-guide/core/trainer.md
Normal file
1
docs/zh/dev-guide/core/trainer.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Trainer
|
||||||
467
docs/zh/dev-guide/plugins/data-plugins.md
Normal file
467
docs/zh/dev-guide/plugins/data-plugins.md
Normal file
@@ -0,0 +1,467 @@
|
|||||||
|
# Data Plugins
|
||||||
|
|
||||||
|
## 1. Data Plugins 简介
|
||||||
|
|
||||||
|
## DataConverterPlugin
|
||||||
|
|
||||||
|
### 1. DataConverterPlugin 简介
|
||||||
|
|
||||||
|
DataConverter 负责将非标准格式的数据集转换为 v1 的标准 Messages 格式。这使得用户可以继续使用现有的数据集(如 Alpaca 格式),而无需手动转换。针对自定义格式的数据集,用户也可以通过构建对应的自定义 DataConverter 插件,来负责其数据格式标准化。
|
||||||
|
|
||||||
|
当前,LLaMA-Factory 已内置了 `Alpaca Converter` 和 `Pair Converter`,这两类数据集可以直接使用对应的 converter 进行标准化,无需自定义转换器。
|
||||||
|
|
||||||
|
|
||||||
|
### 2. Alpaca Converter 详解
|
||||||
|
|
||||||
|
#### 2.1 Alpaca 格式
|
||||||
|
|
||||||
|
Alpaca 格式是一种常见的指令微调数据格式:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"system": "You are a helpful assistant.",
|
||||||
|
"instruction": "Describe a process of making crepes.",
|
||||||
|
"input": "",
|
||||||
|
"output": "Making crepes is an easy and delicious process..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.2 Alpaca Converter 接口定义
|
||||||
|
|
||||||
|
```python
|
||||||
|
class AlpacaSample(TypedDict, total=False):
|
||||||
|
"""Alpaca 格式数据样本结构
|
||||||
|
|
||||||
|
attr:
|
||||||
|
system (str, 可选): 系统提示信息(system prompt),用于设定对话背景或模型行为。
|
||||||
|
instruction (str, 可选): 用户指令(user instruction),通常为任务描述。
|
||||||
|
input (str, 可选): 额外的输入内容(input text),可与 instruction 拼接。
|
||||||
|
output (str, 可选): 模型生成的目标输出(expected response)。
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
def alpaca_converter(raw_sample: AlpacaSample) -> SFTSample:
|
||||||
|
"""将 Alpaca 样本转换为 SFT(Supervised Fine-Tuning)标准样本格式
|
||||||
|
|
||||||
|
`alpaca_converter` 将 Alpaca 数据集中一条样本转换为通用的 `SFTSample` 格式
|
||||||
|
该格式用于监督微调(SFT)或多轮对话建模
|
||||||
|
|
||||||
|
转换逻辑:
|
||||||
|
- 若存在 `system` 字段,则生成一条系统消息,loss_weight = 0.0
|
||||||
|
- 若存在 `instruction` 或 `input` 字段,则合并为一条用户消息,loss_weight = 0.0
|
||||||
|
- 若存在 `output` 字段,则生成一条助手机器人回复消息,loss_weight = 1.0
|
||||||
|
|
||||||
|
args:
|
||||||
|
raw_sample (AlpacaSample): 原始 Alpaca 数据样本
|
||||||
|
|
||||||
|
return:
|
||||||
|
SFTSample: 转换后的标准化样本,格式如下:
|
||||||
|
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": [{"type": "text", "value": "..."}], "loss_weight": 0.0},
|
||||||
|
{"role": "user", "content": [{"type": "text", "value": "..."}], "loss_weight": 0.0},
|
||||||
|
{"role": "assistant", "content": [{"type": "text", "value": "..."}], "loss_weight": 1.0},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
example:
|
||||||
|
>>> raw = {"instruction": "请将以下句子翻译成英文:", "input": "你好", "output": "Hello"}
|
||||||
|
>>> alpaca_converter(raw)
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{"role": "user", "content": [{"type": "text", "value": "请将以下句子翻译成英文:你好"}], "loss_weight": 0.0},
|
||||||
|
{"role": "assistant", "content": [{"type": "text", "value": "Hello"}], "loss_weight": 1.0}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.3 转换过程
|
||||||
|
|
||||||
|
`alpaca_converter` 函数将 Alpaca 格式转换为标准格式,转换逻辑如下:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def alpaca_converter(raw_sample: AlpacaSample) -> SFTSample:
|
||||||
|
messages = []
|
||||||
|
|
||||||
|
# 1. 添加系统提示词(如果存在)
|
||||||
|
if "system" in raw_sample:
|
||||||
|
messages.append({
|
||||||
|
"role": "system",
|
||||||
|
"content": [{"type": "text", "value": raw_sample["system"]}],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
})
|
||||||
|
|
||||||
|
# 2. 添加用户输入(instruction + input)
|
||||||
|
if "instruction" in raw_sample or "input" in raw_sample:
|
||||||
|
user_content = raw_sample.get("instruction", "") + raw_sample.get("input", "")
|
||||||
|
messages.append({
|
||||||
|
"role": "user",
|
||||||
|
"content": [{"type": "text", "value": user_content}],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
})
|
||||||
|
|
||||||
|
# 3. 添加模型回复
|
||||||
|
if "output" in raw_sample:
|
||||||
|
messages.append({
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [{"type": "text", "value": raw_sample["output"]}],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
})
|
||||||
|
|
||||||
|
return {"messages": messages}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.4 转换示例
|
||||||
|
|
||||||
|
**输入(Alpaca 格式):**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"instruction": "What is the capital of France?",
|
||||||
|
"input": "",
|
||||||
|
"output": "The capital of France is Paris."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**输出(标准格式):**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [{"type": "text", "value": "What is the capital of France?"}],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [{"type": "text", "value": "The capital of France is Paris."}],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 自定义转换器
|
||||||
|
|
||||||
|
#### 3.1 创建自定义转换器
|
||||||
|
|
||||||
|
如果用户有自己的数据格式,可以轻松添加自定义转换器将其标准化,实现过程可参考如下示例:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# src/llamafactory/v1/plugins/data_plugins/converter.py
|
||||||
|
|
||||||
|
from typing import TypedDict, NotRequired
|
||||||
|
from ...extras.types import SFTSample
|
||||||
|
|
||||||
|
# 1. 定义输入格式的类型
|
||||||
|
class MyCustomSample(TypedDict, total=False):
|
||||||
|
question: str
|
||||||
|
answer: str
|
||||||
|
context: NotRequired[str]
|
||||||
|
|
||||||
|
# 2. 实现转换逻辑
|
||||||
|
def custom_converter(raw_sample: MyCustomSample) -> SFTSample:
|
||||||
|
messages = []
|
||||||
|
|
||||||
|
# 构建用户消息
|
||||||
|
user_text = raw_sample["question"]
|
||||||
|
if "context" in raw_sample:
|
||||||
|
user_text = f"Context: {raw_sample['context']}\n\nQuestion: {user_text}"
|
||||||
|
|
||||||
|
messages.append({
|
||||||
|
"role": "user",
|
||||||
|
"content": [{"type": "text", "value": user_text}],
|
||||||
|
"loss_weight": 0.0
|
||||||
|
})
|
||||||
|
|
||||||
|
# 构建助手消息
|
||||||
|
messages.append({
|
||||||
|
"role": "assistant",
|
||||||
|
"content": [{"type": "text", "value": raw_sample["answer"]}],
|
||||||
|
"loss_weight": 1.0
|
||||||
|
})
|
||||||
|
|
||||||
|
return {"messages": messages}
|
||||||
|
|
||||||
|
# 3. 注册 custom_converter
|
||||||
|
#src/llamafactory/v1/plugins/data_plugins/converter.py: CONVERTERS
|
||||||
|
CONVERTERS = {
|
||||||
|
"alpaca": alpaca_converter,
|
||||||
|
"custom": custom_converter, # 添加自定义转换器
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.2 使用自定义转换器
|
||||||
|
|
||||||
|
在 YAML 配置中指定转换器名称:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
my_dataset:
|
||||||
|
file_name: custom_data.json
|
||||||
|
converter: custom
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## DataLoaderPlugin
|
||||||
|
|
||||||
|
### 1. DataLoaderPlugin 简介
|
||||||
|
|
||||||
|
`DataLoaderPlugin` 负责从本地文件加载数据集,当前支持如下文件格式:
|
||||||
|
|
||||||
|
- **JSON**: `.json`
|
||||||
|
- **JSONL**: `.jsonl`
|
||||||
|
- **CSV**: `.csv`
|
||||||
|
- **Parquet**: `.parquet`
|
||||||
|
- **Arrow**: `.arrow`
|
||||||
|
- **Text**: `.txt`
|
||||||
|
|
||||||
|
### 2. DataLoaderPlugin 接口定义
|
||||||
|
|
||||||
|
```python
|
||||||
|
@dataclass
|
||||||
|
class DataLoaderPlugin:
|
||||||
|
"""数据加载插件(DataLoaderPlugin)
|
||||||
|
|
||||||
|
负责根据数据集信息(`DatasetInfo`)自动加载本地或远程数据集。
|
||||||
|
支持多种文件格式(如 CSV、JSON、Parquet、Text、Arrow),并可选择是否以流式方式加载。
|
||||||
|
|
||||||
|
通常由 `DataEngine` 调用,用于统一封装数据加载逻辑。
|
||||||
|
"""
|
||||||
|
|
||||||
|
args: DataArguments
|
||||||
|
"""数据参数对象,包含数据目录、缓存路径、分片等配置信息。"""
|
||||||
|
|
||||||
|
|
||||||
|
def _get_builder_name(self, path: str) -> Literal["arrow", "csv", "json", "parquet", "text"]:
|
||||||
|
"""获取数据集文件格式
|
||||||
|
|
||||||
|
根据输入文件路径自动判断应使用的 HuggingFace `load_dataset` 构建器类型。
|
||||||
|
通过文件扩展名推断数据类型,例如 `.csv`、`.jsonl`、`.parquet`、`.txt` 等。
|
||||||
|
|
||||||
|
args:
|
||||||
|
path (str): 数据集文件路径,用于识别文件类型。
|
||||||
|
|
||||||
|
return:
|
||||||
|
Literal["arrow", "csv", "json", "parquet", "text"]:
|
||||||
|
数据构建器名称,用于 `datasets.load_dataset()`。
|
||||||
|
|
||||||
|
example:
|
||||||
|
>>> _get_builder_name("data/train.jsonl")
|
||||||
|
"json"
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
def auto_load_data(self, dataset_info: DatasetInfo) -> HFDataset:
|
||||||
|
"""根据传入的 `dataset_info` 自动选择合适的加载方式
|
||||||
|
|
||||||
|
args:
|
||||||
|
dataset_info (DatasetInfo): 数据集元信息,通常包含:
|
||||||
|
- `file_name`: 数据文件路径
|
||||||
|
- `split`: 数据划分(如 "train"、"test");
|
||||||
|
- `streaming`: 是否启用流式加载
|
||||||
|
|
||||||
|
return:
|
||||||
|
HFDataset: 加载完成的 Hugging Face 数据集对象。
|
||||||
|
|
||||||
|
example:
|
||||||
|
>>> plugin = DataLoaderPlugin(args)
|
||||||
|
>>> ds = plugin.auto_load_data({"file_name": "~/data.json", "split": "train"})
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
def load_data_from_file(self, filepath: str, split: str, streaming: bool) -> HFDataset:
|
||||||
|
"""从文件或目录加载数据集
|
||||||
|
|
||||||
|
根据输入路径自动识别文件类型(CSV、JSON、Parquet、Text 等),
|
||||||
|
并通过 `datasets.load_dataset()` 加载数据集。
|
||||||
|
若 `streaming=True`,则将结果转换为迭代式数据集。
|
||||||
|
|
||||||
|
args:
|
||||||
|
filepath (str): 文件路径或目录路径。
|
||||||
|
split (str): 数据划分名称(如 "train"、"validation")。
|
||||||
|
streaming (bool): 是否启用流式加载模式。
|
||||||
|
|
||||||
|
return:
|
||||||
|
HFDataset: 加载后的数据集对象。
|
||||||
|
|
||||||
|
example:
|
||||||
|
>>> plugin.load_data_from_file("data/train.json", "train", False)
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## DataIndexPlugin
|
||||||
|
|
||||||
|
### 1. DataIndexPlugin 简介
|
||||||
|
|
||||||
|
`DataIndexPlugin` 负责调整数据索引,支持通过配置 `size`, `weight` 等参数控制数据集样本数量和采样频率。
|
||||||
|
|
||||||
|
- 使用 `size` 参数 限制使用的样本数量:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
my_dataset:
|
||||||
|
file_name: large_dataset.json
|
||||||
|
size: 1000 # 只使用前 1000 个样本
|
||||||
|
```
|
||||||
|
|
||||||
|
- 使用 `weight` 参数调整数据集在混合数据中的采样频率:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
dataset_a:
|
||||||
|
file_name: data_a.json
|
||||||
|
weight: 1.0
|
||||||
|
|
||||||
|
dataset_b:
|
||||||
|
file_name: data_b.json
|
||||||
|
weight: 2.0 # dataset_b 的样本出现频率是 dataset_a 的 2 倍
|
||||||
|
```
|
||||||
|
|
||||||
|
**说明**:`weight` 参数适用于在多个数据集混合训练时,调整不同数据集的的采样频率
|
||||||
|
|
||||||
|
- 当 `weight=1.0` 时,数据集按原始比例采样
|
||||||
|
- 当 `weight=2.0` 时,该数据集的索引会复制 2 倍,使其样本出现频率翻倍
|
||||||
|
|
||||||
|
### 2. DataIndexPlugin 接口定义
|
||||||
|
|
||||||
|
```python
|
||||||
|
@dataclass
|
||||||
|
class DataIndexPlugin:
|
||||||
|
"""数据索引插件(DataIndexPlugin)
|
||||||
|
|
||||||
|
根据 `size` 和 `weight` 调整数据索引列表,控制数据集的样本数量和采样频率
|
||||||
|
通常在多数据集混合训练时使用,以控制不同数据集在总体样本中的占比。
|
||||||
|
|
||||||
|
在 `DataEngine.build_data_index` 中被自动调用,用于实现样本重采样或加权分布。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def adjust_data_index(
|
||||||
|
self, data_index: list[tuple[str, int]], size: Optional[int], weight: Optional[float]
|
||||||
|
) -> list[tuple[str, int]]:
|
||||||
|
"""调整数据索引列表
|
||||||
|
|
||||||
|
根据 `size` 或 `weight` 参数对输入的数据索引进行采样、扩展或缩减。
|
||||||
|
若两个参数同时存在,将依次执行基于大小和基于权重的调整。
|
||||||
|
|
||||||
|
args:
|
||||||
|
data_index (list[tuple[str, int]]):
|
||||||
|
数据索引列表,每个元素为 `(dataset_name, sample_index)`。
|
||||||
|
size (Optional[int]):
|
||||||
|
目标样本数量,若指定则根据该数量裁剪或重复样本。
|
||||||
|
weight (Optional[float]):
|
||||||
|
数据集权重,用于控制数据集在混合训练中的采样比例。
|
||||||
|
|
||||||
|
return:
|
||||||
|
list[tuple[str, int]]:
|
||||||
|
调整后的数据索引列表。
|
||||||
|
|
||||||
|
example:
|
||||||
|
>>> plugin = DataIndexPlugin()
|
||||||
|
>>> adjusted = plugin.adjust_data_index([("ds1", i) for i in range(100)], size=50, weight=None)
|
||||||
|
>>> len(adjusted)
|
||||||
|
50
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
def adjust_by_size(self, data_index: list[tuple[str, int]], size: int) -> list[tuple[str, int]]:
|
||||||
|
"""根据目标大小调整数据索引
|
||||||
|
|
||||||
|
通过裁剪或重复样本,使索引总数等于 `size`。
|
||||||
|
常用于统一不同数据集的样本数量。
|
||||||
|
|
||||||
|
args:
|
||||||
|
data_index (list[tuple[str, int]]):
|
||||||
|
原始数据索引列表。
|
||||||
|
size (int):
|
||||||
|
目标样本数量。
|
||||||
|
|
||||||
|
return:
|
||||||
|
list[tuple[str, int]]:
|
||||||
|
调整后长度等于 `size` 的数据索引列表。
|
||||||
|
|
||||||
|
example:
|
||||||
|
>>> plugin.adjust_by_size([("ds1", i) for i in range(10)], 20)
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
def adjust_by_weight(self, data_index: list[tuple[str, int]], weight: float) -> list[tuple[str, int]]:
|
||||||
|
"""根据权重调整数据索引
|
||||||
|
|
||||||
|
通过加权采样或重复样本,使数据集样本出现频率符合指定权重。
|
||||||
|
常用于多数据源训练中按比例平衡样本。
|
||||||
|
|
||||||
|
args:
|
||||||
|
data_index (list[tuple[str, int]]):
|
||||||
|
原始数据索引列表。
|
||||||
|
weight (float):
|
||||||
|
数据集权重(相对比例,可与其他数据集共同归一化)。
|
||||||
|
|
||||||
|
return:
|
||||||
|
list[tuple[str, int]]:
|
||||||
|
调整后的加权数据索引列表。
|
||||||
|
|
||||||
|
example:
|
||||||
|
>>> plugin.adjust_by_weight([("ds1", i) for i in range(10)], 0.5)
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
```
|
||||||
|
---
|
||||||
|
|
||||||
|
## DataSelectorPlugin
|
||||||
|
|
||||||
|
### 1. DataSelectorPlugin 简介
|
||||||
|
|
||||||
|
`DataSelectorPlugin` 为 `DataEngine`提供基于索引访问数据的功能,由 `DataEngine` 的 `__getitem__` 方法自动调用。
|
||||||
|
|
||||||
|
|
||||||
|
### 2. DataSelectorPlugin 接口定义
|
||||||
|
|
||||||
|
```python
|
||||||
|
@dataclass
|
||||||
|
class DataSelectorPlugin:
|
||||||
|
"""根据索引选择数据集样本。
|
||||||
|
|
||||||
|
配合 `DataEngine` 使用,通过统一的 `data_index` 结构(包含数据集名与样本索引)来实现灵活的数据选择
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
data_index: list[tuple[str, int]]
|
||||||
|
"""数据索引列表,每个元素为 (dataset_name, sample_index)。"""
|
||||||
|
|
||||||
|
|
||||||
|
def select(self, index: Union[slice, list[int], Any]) -> Union[tuple[str, int], list[tuple[str, int]]]:
|
||||||
|
"""选择数据集样本
|
||||||
|
|
||||||
|
根据输入类型从 `data_index` 中选择对应的样本索引
|
||||||
|
支持三种索引方式:
|
||||||
|
- 切片(slice):返回对应范围内的样本
|
||||||
|
- 索引列表(list[int]):返回指定索引处的多个样本
|
||||||
|
- 其他类型输入将触发异常。
|
||||||
|
|
||||||
|
args:
|
||||||
|
index (Union[slice, list[int], Any]): 数据样本索引
|
||||||
|
可以是切片(`slice`)或索引列表
|
||||||
|
|
||||||
|
return:
|
||||||
|
Union[tuple[str, int], list[tuple[str, int]]]:
|
||||||
|
- 若为单个索引:返回一个 `(dataset_name, sample_index)`
|
||||||
|
- 若为多个索引或切片:返回多个样本的列表
|
||||||
|
|
||||||
|
except:
|
||||||
|
Raises:
|
||||||
|
ValueError: 当输入索引类型不受支持时抛出。
|
||||||
|
...
|
||||||
|
```
|
||||||
197
docs/zh/dev-guide/plugins/model-plugins/kernels.md
Normal file
197
docs/zh/dev-guide/plugins/model-plugins/kernels.md
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
# Kernels plugins
|
||||||
|
|
||||||
|
## 概览
|
||||||
|
LLaMA-Factory 通过 Kernels plugins 系统,依据不同硬件设备提供高性能计算内核(kernel)实现。该系统通过注册表机制管理所有 kernel,通过 `@register_kernel` 装饰器实现 kernel 定义后自动注册,由 `apply_kernel` 方法来使能指定的 kernel,`apply_default_kernels` 可使能注册表中当前环境所有可用的默认 kernels。
|
||||||
|
|
||||||
|
## 架构设计
|
||||||
|
|
||||||
|
### 核心组件
|
||||||
|
|
||||||
|
#### 1. Registry(注册表)
|
||||||
|
|
||||||
|
`Registry` 是一个用于管理所有 kernel 实现的静态类。它维护一个字典结构:`{kernel_id: KernelClass}`。
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 注册表结构示例
|
||||||
|
{
|
||||||
|
"npu_fused_rmsnorm": NpuRMSNormKernel,
|
||||||
|
"npu_fused_swiglu": NpuSwiGluKernel,
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. register_kernel (装饰器)
|
||||||
|
|
||||||
|
`@register_kernel` 是 `Registry.register` 的别名。所有 kernel 类均应使用该装饰器进行注册。
|
||||||
|
|
||||||
|
**注册机制**:
|
||||||
|
- 装饰器检查类是否继承自 `BaseKernel`。
|
||||||
|
- 检查类是否定义了 `_kernel_id` 和 `_device` 属性。
|
||||||
|
- 检查 `_device` 是否与当前运行环境的加速器类型匹配。如果不匹配,则跳过注册。
|
||||||
|
- 如果一切符合要求,将 kernel 类注册到全局注册表中。
|
||||||
|
|
||||||
|
#### 3. BaseKernel(基类)
|
||||||
|
|
||||||
|
所有 kernel 的实现都必须继承自 `BaseKernel` 抽象基类。`BaseKernel` 定义了 kernel 的基本属性和接口。
|
||||||
|
|
||||||
|
#### 4. 标识系统
|
||||||
|
|
||||||
|
**Kernel ID** (`_kernel_id`):
|
||||||
|
每个 kernel 必须拥有一个唯一的字符串标识符,例如 `"npu_fused_rmsnorm"`。
|
||||||
|
|
||||||
|
**Device Type** (`_device`):
|
||||||
|
kernel 必须声明其支持的设备类型,例如 `DeviceType.NPU` 或 `DeviceType.CUDA`。
|
||||||
|
|
||||||
|
## Kernel 系统 API 设计
|
||||||
|
|
||||||
|
### **Registry**:全局 kernel 注册表
|
||||||
|
|
||||||
|
`Registry` 类提供了注册和获取 kernel 的接口:
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Registry:
|
||||||
|
@classmethod
|
||||||
|
def register(cls, kernel_cls: type[BaseKernel]) -> type[BaseKernel] | None:
|
||||||
|
"""注册一个 kernel 类"""
|
||||||
|
...
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get(cls, kernel_id: str) -> type[BaseKernel] | None:
|
||||||
|
"""根据 ID 获取 kernel 类"""
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
### **BaseKernel**
|
||||||
|
|
||||||
|
`BaseKernel` 定义了所有 kernel 必须实现的协议:
|
||||||
|
|
||||||
|
- `_kernel_id`: 类属性,kernel 的唯一标识符。
|
||||||
|
- `_device`: 类属性,kernel 支持的设备类型。
|
||||||
|
- `check_deps()`: 类方法,检查 kernel 的依赖项是否满足(如 `torch_npu` 是否安装)。
|
||||||
|
- `apply(**kwargs)`: 抽象类方法,实现 kernel 的具体应用逻辑。
|
||||||
|
|
||||||
|
```python
|
||||||
|
class BaseKernel(ABC):
|
||||||
|
_kernel_id: Any = ""
|
||||||
|
_device: DeviceType = DeviceType.CPU
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def check_deps(cls) -> bool:
|
||||||
|
"""检查依赖项"""
|
||||||
|
...
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
@abstractmethod
|
||||||
|
def apply(cls, **kwargs) -> HFModel:
|
||||||
|
"""应用 kernel 到模型"""
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
### **scan_all_kernels**
|
||||||
|
|
||||||
|
`scan_all_kernels` 函数会自动扫描 `ops` 目录下的所有 `.py` 文件并导入它们,从而触发 `@register_kernel` 装饰器完成自动注册。
|
||||||
|
|
||||||
|
### **apply_kernel**
|
||||||
|
|
||||||
|
对模型使能指定的 kernel。
|
||||||
|
|
||||||
|
```python
|
||||||
|
def apply_kernel(kernel_id: str, **kwargs) -> HFModel:
|
||||||
|
"""应用指定的 kernel 到模型
|
||||||
|
|
||||||
|
Args:
|
||||||
|
kernel_id: 目标 kernel 的 ID
|
||||||
|
**kwargs: 传递给 kernel.apply 的参数,通常包含 model
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
|
||||||
|
**用法示例**:
|
||||||
|
```python
|
||||||
|
from llamafactory.v1.plugins.model_plugins.kernels import apply_kernel
|
||||||
|
|
||||||
|
model = apply_kernel("npu_fused_rmsnorm", model=model)
|
||||||
|
```
|
||||||
|
|
||||||
|
### **apply_default_kernels**
|
||||||
|
|
||||||
|
对模型使能所有默认注册的 kernel。这是一个高级 API,通常在模型加载流程中自动调用。
|
||||||
|
|
||||||
|
```python
|
||||||
|
def apply_default_kernels(model: HFModel, include_kernels: str = None) -> HFModel:
|
||||||
|
"""应用所有默认 kernel
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model: HFModel 实例
|
||||||
|
include_kernels: 包含的 kernel ID 列表(逗号分隔字符串),或者 "auto"/True 表示全部
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
|
||||||
|
## 扩展 Kernels
|
||||||
|
|
||||||
|
如果用户有针对特定模型或者设备的 kernel,可以按照下述步骤去实现并接入 LLaMA-Factory。
|
||||||
|
|
||||||
|
### 创建新 Kernel 的步骤
|
||||||
|
|
||||||
|
#### 1. 创建 Kernel 实现文件
|
||||||
|
|
||||||
|
在 `src/llamafactory/v1/plugins/model_plugins/kernels/ops` 下的相应子目录中创建新的 kernel 实现文件,例如 `mlp/cuda_swiglu.py`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import torch
|
||||||
|
from ......accelerator.helper import DeviceType
|
||||||
|
from ......utils.types import HFModel
|
||||||
|
from ...base import BaseKernel
|
||||||
|
from ...registry import register_kernel
|
||||||
|
|
||||||
|
# 实现具体的 kernel 函数
|
||||||
|
def _cuda_swiglu_forward(self, hidden_state):
|
||||||
|
# ... CUDA 优化实现 ...
|
||||||
|
pass
|
||||||
|
|
||||||
|
@register_kernel
|
||||||
|
class CudaSwiGluKernel(BaseKernel):
|
||||||
|
_kernel_id = "cuda_fused_swiglu"
|
||||||
|
_device = DeviceType.CUDA
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def apply(cls, **kwargs) -> HFModel:
|
||||||
|
model = kwargs.get("model")
|
||||||
|
if model is None:
|
||||||
|
raise ValueError("model is required")
|
||||||
|
|
||||||
|
if not cls.check_deps():
|
||||||
|
raise RuntimeError("Dependencies not met")
|
||||||
|
|
||||||
|
# 遍历模型并替换 forward 方法
|
||||||
|
for name, module in model.named_modules():
|
||||||
|
# ... 匹配和替换逻辑 ...
|
||||||
|
pass
|
||||||
|
|
||||||
|
return model
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. 自动发现
|
||||||
|
|
||||||
|
由于 `scan_all_kernels` 会自动扫描 `ops` 目录,只要文件位于该目录下且没有语法错误,系统启动时会自动导入并注册,无需手动修改注册表代码。
|
||||||
|
|
||||||
|
#### 3. 测试 Kernel
|
||||||
|
|
||||||
|
创建测试用例验证 kernel 的正确性:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from llamafactory.v1.plugins.model_plugins.kernels import apply_kernel
|
||||||
|
|
||||||
|
# ... 加载模型 ...
|
||||||
|
model = apply_kernel("cuda_fused_swiglu", model=model)
|
||||||
|
# ... 验证 forward 是否被替换 ...
|
||||||
|
```
|
||||||
|
|
||||||
|
## 异常处理
|
||||||
|
|
||||||
|
### 依赖不可用
|
||||||
|
|
||||||
|
`BaseKernel.check_deps()` 默认会检查当前设备类型是否匹配。子类可以重写此方法以添加额外的依赖检查(如检查特定的库是否安装)。如果 `check_deps()` 返回 `False`,`apply()` 方法应当抛出异常或进行相应处理。
|
||||||
|
|
||||||
|
### Kernel ID 未找到
|
||||||
|
|
||||||
|
如果调用 `apply_kernel` 时传入了不存在的 `kernel_id`,会抛出 `ValueError`。
|
||||||
161
docs/zh/getting-started.md
Normal file
161
docs/zh/getting-started.md
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
# 快速开始
|
||||||
|
|
||||||
|
LLaMA Factory 是一个高效、灵活的大模型微调框架,支持 100+ 种主流大语言模型的微调训练。本文档将帮助您快速上手使用 LLaMA Factory。
|
||||||
|
|
||||||
|
## 支持的训练方法
|
||||||
|
|
||||||
|
| 方法 | 全参数训练 | 部分参数训练 | LoRA | QLoRA |
|
||||||
|
|:---------------------:| ------------------ | ------------------ | ------------------ | ------------------ |
|
||||||
|
| 指令监督微调 (SFT) | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||||
|
| DPO 训练 | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||||
|
|
||||||
|
> **提示**: v1 版本目前支持 SFT 和 DPO 两种训练方法,均支持多种加速特性,包括 DeepSpeed、FSDP、FlashAttention-2 等。
|
||||||
|
|
||||||
|
## 软件依赖
|
||||||
|
|
||||||
|
| 必需项 | 至少 | 推荐 |
|
||||||
|
|:---------------------:|--------|--------|
|
||||||
|
| python | 3.11 | 3.12 |
|
||||||
|
| torch | 2.7.1 | 2.7.1 |
|
||||||
|
| torch-npu(Ascend NPU) | 2.7.1 | 2.7.1 |
|
||||||
|
| torchvision | 0.22.1 | 0.22.1 |
|
||||||
|
| transformers | 5.0.0 | 5.0.0 |
|
||||||
|
| datasets | 3.2.0 | 4.0.0 |
|
||||||
|
| peft | 0.18.1 | 0.18.1 |
|
||||||
|
|
||||||
|
|
||||||
|
| 可选项 | 至少 | 推荐 |
|
||||||
|
|:----------------:|--------|--------|
|
||||||
|
| CUDA(NVIDIA GPU) | 11.6 | 12.2 |
|
||||||
|
| deepspeed | 0.18.4 | 0.18.4 |
|
||||||
|
| flash-attn(NVIDIA GPU) | 2.5.6 | 2.7.2 |
|
||||||
|
|
||||||
|
|
||||||
|
## 安装 LLaMA Factory
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> 此步骤为必需。请确保您的环境满足上述软件依赖要求。
|
||||||
|
|
||||||
|
### 从源码安装(推荐)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
|
||||||
|
cd LLaMA-Factory
|
||||||
|
pip install -e .
|
||||||
|
```
|
||||||
|
|
||||||
|
### 使用 pip 安装
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install llamafactory
|
||||||
|
```
|
||||||
|
|
||||||
|
### 可选依赖
|
||||||
|
|
||||||
|
如果您需要使用特定的加速特性,可以安装相应的依赖:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 安装 FlashAttention-2 支持
|
||||||
|
pip install flash-attn --no-build-isolation
|
||||||
|
|
||||||
|
# 安装 DeepSpeed 支持
|
||||||
|
pip install deepspeed
|
||||||
|
|
||||||
|
# 安装 Unsloth 支持(用于加速 LoRA 训练)
|
||||||
|
pip install unsloth
|
||||||
|
```
|
||||||
|
|
||||||
|
## 数据准备
|
||||||
|
|
||||||
|
LLaMA Factory 支持多种数据格式,包括 JSON、JSONL、CSV 等。关于数据集文件的详细格式说明,请参考 [数据准备指南](../../data/README_zh.md)。
|
||||||
|
|
||||||
|
### 使用内置数据集
|
||||||
|
|
||||||
|
LLaMA Factory 提供了多个内置数据集用于快速测试,您可以在 `data/dataset_info.json` 中查看所有可用的数据集。
|
||||||
|
|
||||||
|
### 使用自定义数据集
|
||||||
|
|
||||||
|
您可以使用 HuggingFace / ModelScope 上的数据集或加载本地数据集。
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> 使用自定义数据集或自定义数据集格式时,请参照 [数据准备指南](../../data/README_zh.md) 进行配置。如有必要,请重新实现自定义数据集的数据处理逻辑,包括对应的 `converter`。
|
||||||
|
|
||||||
|
### 数据构建工具
|
||||||
|
|
||||||
|
您也可以使用以下工具构建用于微调的合成数据:
|
||||||
|
- **[Easy Dataset](https://github.com/ConardLi/easy-dataset)** - 易于使用的数据集构建工具
|
||||||
|
- **[DataFlow](https://github.com/OpenDCAI/DataFlow)** - 高质量数据准备管道
|
||||||
|
- **[GraphGen](https://github.com/open-sciencelab/GraphGen)** - 基于图的数据生成工具
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 命令行训练
|
||||||
|
|
||||||
|
下面的命令展示了对 Qwen3-0.6B 模型使用 FSDP2 进行全参数微调:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export USE_V1=1
|
||||||
|
llamafactory-cli sft examples/v1/train_full/train_full_fsdp2.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
> **提示**: `llamafactory-cli sft` 和 `llamafactory-cli train` 命令等价。
|
||||||
|
|
||||||
|
### Web UI 训练
|
||||||
|
|
||||||
|
LLaMA Factory 提供了直观的 Web 界面(LLaMA Board),您可以通过图形界面进行训练:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
llamafactory-cli webui
|
||||||
|
```
|
||||||
|
|
||||||
|
在浏览器中打开 http://localhost:7860 即可开始使用。
|
||||||
|
|
||||||
|
### 推理部署
|
||||||
|
|
||||||
|
训练完成后,您可以使用以下命令部署模型:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用 vLLM 后端进行高性能推理
|
||||||
|
llamafactory-cli chat --model_name_or_path path/to/your/model --template qwen --infer_backend vllm
|
||||||
|
|
||||||
|
# 使用 HuggingFace 后端进行推理
|
||||||
|
llamafactory-cli chat --model_name_or_path path/to/your/model --template qwen
|
||||||
|
```
|
||||||
|
|
||||||
|
## 进阶用法
|
||||||
|
|
||||||
|
高级用法请参考 [进阶指南](./advanced/README.md),包括:
|
||||||
|
- 多卡多机分布式训练
|
||||||
|
- LoRA/QLoRA 微调
|
||||||
|
- 模型量化(AWQ/GPTQ/LLM.int8 等)
|
||||||
|
- 各种加速特性(DeepSpeed、FSDP、FlashAttention 等)
|
||||||
|
- 多模态模型微调
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 1. 内存不足怎么办?
|
||||||
|
|
||||||
|
- 使用 LoRA 或 QLoRA 代替全参数训练
|
||||||
|
- 减小 `batch_size` 和 `cutoff_len`
|
||||||
|
- 启用 `gradient_checkpointing`
|
||||||
|
- 使用 DeepSpeed ZeRO-2 或 ZeRO-3
|
||||||
|
|
||||||
|
### 2. 如何选择合适的训练方法?
|
||||||
|
|
||||||
|
- **SFT(指令微调)**: 最常用的方法,适用于大多数场景,通过监督数据训练模型
|
||||||
|
- **DPO(直接偏好优化)**: 用于对齐人类偏好,提升模型输出质量,无需训练奖励模型
|
||||||
|
|
||||||
|
### 3. 训练完成后如何评估模型?
|
||||||
|
|
||||||
|
```bash
|
||||||
|
llamafactory-cli eval --model_name_or_path path/to/your/model --template qwen --dataset mmlu
|
||||||
|
```
|
||||||
|
|
||||||
|
更多评估方法请参考 [评估指南](./advanced/evaluation.md)。
|
||||||
|
|
||||||
|
## 获取帮助
|
||||||
|
|
||||||
|
如果您在使用过程中遇到问题:
|
||||||
|
- 查看 [GitHub Issues](https://github.com/hiyouga/LLaMA-Factory/issues)
|
||||||
|
- 加入 [Discord 社区](https://discord.gg/rKfvV9r9FK)
|
||||||
|
- 加入微信群(扫描二维码)
|
||||||
1
docs/zh/hyperparameters/data-argument.md
Normal file
1
docs/zh/hyperparameters/data-argument.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Data Argument
|
||||||
0
docs/zh/hyperparameters/sample-argument.md
Normal file
0
docs/zh/hyperparameters/sample-argument.md
Normal file
0
docs/zh/hyperparameters/training-argument.md
Normal file
0
docs/zh/hyperparameters/training-argument.md
Normal file
62
docs/zh/index.rst
Normal file
62
docs/zh/index.rst
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
LlamaFactory 文档
|
||||||
|
=================
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Getting Started
|
||||||
|
|
||||||
|
getting-started
|
||||||
|
installation
|
||||||
|
llamaboard-web-ui
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Data Preparation
|
||||||
|
|
||||||
|
data-preparation/data-processing
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Training
|
||||||
|
|
||||||
|
training/sft
|
||||||
|
training/dpo
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Inference
|
||||||
|
|
||||||
|
inference/deploy
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Advanced
|
||||||
|
|
||||||
|
advanced/lora-and-quantization/lora
|
||||||
|
advanced/lora-and-quantization/quantization
|
||||||
|
advanced/distributed/fsdp
|
||||||
|
advanced/distributed/deepspeed
|
||||||
|
advanced/distributed/parallel-dp-tp-ep-sp-cp
|
||||||
|
advanced/custom-kernels/triton
|
||||||
|
advanced/custom-kernels/fused-operators
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Hyperparameters
|
||||||
|
|
||||||
|
hyperparameters/data-argument
|
||||||
|
hyperparameters/model-argument
|
||||||
|
hyperparameters/sample-argument
|
||||||
|
hyperparameters/training-argument
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 1
|
||||||
|
:caption: Dev Guide
|
||||||
|
|
||||||
|
dev-guide/core/data-engine
|
||||||
|
dev-guide/core/model-engine
|
||||||
|
dev-guide/core/trainer
|
||||||
|
dev-guide/plugins/data-plugins
|
||||||
|
dev-guide/plugins/model-plugins/initialization
|
||||||
|
dev-guide/plugins/model-plugins/kernels
|
||||||
|
dev-guide/plugins/model-plugins/rendering
|
||||||
1
docs/zh/inference/deploy.md
Normal file
1
docs/zh/inference/deploy.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Deploy
|
||||||
1
docs/zh/installation.md
Normal file
1
docs/zh/installation.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# Installation
|
||||||
1
docs/zh/llamaboard-web-ui.md
Normal file
1
docs/zh/llamaboard-web-ui.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# LlamaBoard Web UI
|
||||||
1
docs/zh/training/dpo.md
Normal file
1
docs/zh/training/dpo.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# DPO
|
||||||
1
docs/zh/training/sft.md
Normal file
1
docs/zh/training/sft.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# SFT
|
||||||
@@ -96,7 +96,7 @@ FORCE_TORCHRUN=1 NNODES=2 NODE_RANK=1 MASTER_ADDR=192.168.0.1 MASTER_PORT=29500
|
|||||||
|
|
||||||
### 支持弹性和容错的多机指令监督微调
|
### 支持弹性和容错的多机指令监督微调
|
||||||
|
|
||||||
要启动一个支持弹性节点和容错的多机指令微调,在每个节点上执行以下命令。弹性节点数量范围为 `MIN_NNODES:MAX_NNODES`,每个节点最多允许因为错误重启 `MAX_RESTARTS` 次。`RDZV_ID` 应设置为一个唯一的作业 ID(由参与该作业的所有节点共享)。更多新可以参考官方文档 [torchrun](https://docs.pytorch.org/docs/stable/elastic/run.html)。
|
要启动一个支持弹性节点和容错的多机指令微调,在每个节点上执行以下命令。弹性节点数量范围为 `MIN_NNODES:MAX_NNODES`,每个节点最多允许因为错误重启 `MAX_RESTARTS` 次。`RDZV_ID` 应设置为一个唯一的作业 ID(由参与该作业的所有节点共享)。更多细节可以参考官方文档 [torchrun](https://docs.pytorch.org/docs/stable/elastic/run.html)。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
FORCE_TORCHRUN=1 MIN_NNODES=1 MAX_NNODES=3 MAX_RESTARTS=3 RDZV_ID=llamafactory MASTER_ADDR=192.168.0.1 MASTER_PORT=29500 llamafactory-cli train examples/train_full/qwen3_full_sft.yaml
|
FORCE_TORCHRUN=1 MIN_NNODES=1 MAX_NNODES=3 MAX_RESTARTS=3 RDZV_ID=llamafactory MASTER_ADDR=192.168.0.1 MASTER_PORT=29500 llamafactory-cli train examples/train_full/qwen3_full_sft.yaml
|
||||||
|
|||||||
20
examples/accelerate/fsdp2_config_qwen35.yaml
Normal file
20
examples/accelerate/fsdp2_config_qwen35.yaml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
compute_environment: LOCAL_MACHINE
|
||||||
|
debug: false
|
||||||
|
distributed_type: FSDP
|
||||||
|
downcast_bf16: 'no'
|
||||||
|
fsdp_config:
|
||||||
|
fsdp_version: 2
|
||||||
|
fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
|
||||||
|
fsdp_transformer_layer_cls_to_wrap: Qwen3_5DecoderLayer,Qwen3_5VisionBlock
|
||||||
|
fsdp_cpu_ram_efficient_loading: true
|
||||||
|
fsdp_offload_params: false
|
||||||
|
fsdp_reshard_after_forward: true
|
||||||
|
fsdp_state_dict_type: FULL_STATE_DICT
|
||||||
|
machine_rank: 0
|
||||||
|
main_training_function: main
|
||||||
|
mixed_precision: bf16
|
||||||
|
num_machines: 1
|
||||||
|
num_processes: 8 # Change to match your NPU count (e.g., 8 for A2, 16 for A3)
|
||||||
|
rdzv_backend: static
|
||||||
|
same_network: true
|
||||||
|
use_cpu: false
|
||||||
20
examples/accelerate/fsdp2_config_qwen35_moe.yaml
Normal file
20
examples/accelerate/fsdp2_config_qwen35_moe.yaml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
compute_environment: LOCAL_MACHINE
|
||||||
|
debug: false
|
||||||
|
distributed_type: FSDP
|
||||||
|
downcast_bf16: 'no'
|
||||||
|
fsdp_config:
|
||||||
|
fsdp_version: 2
|
||||||
|
fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
|
||||||
|
fsdp_transformer_layer_cls_to_wrap: Qwen3_5MoeDecoderLayer,Qwen3_5MoeVisionBlock
|
||||||
|
fsdp_cpu_ram_efficient_loading: true
|
||||||
|
fsdp_offload_params: false
|
||||||
|
fsdp_reshard_after_forward: true
|
||||||
|
fsdp_state_dict_type: FULL_STATE_DICT
|
||||||
|
machine_rank: 0
|
||||||
|
main_training_function: main
|
||||||
|
mixed_precision: bf16
|
||||||
|
num_machines: 1
|
||||||
|
num_processes: 8 # Change to match your NPU count (e.g., 8 for A2, 16 for A3)
|
||||||
|
rdzv_backend: static
|
||||||
|
same_network: true
|
||||||
|
use_cpu: false
|
||||||
47
examples/ascend/qwen3_5_full_sft_fsdp2.yaml
Normal file
47
examples/ascend/qwen3_5_full_sft_fsdp2.yaml
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
# Start FSDP2 full fine-tuning on Ascend NPU
|
||||||
|
# Usage:
|
||||||
|
# accelerate launch \
|
||||||
|
# --config_file examples/accelerate/fsdp2_config_qwen35.yaml \
|
||||||
|
# src/train.py examples/ascend/qwen3_5_full_sft_fsdp2.yaml
|
||||||
|
#
|
||||||
|
# Note: Change `num_processes` in fsdp2_config_qwen35.yaml to match your NPU count
|
||||||
|
|
||||||
|
### model
|
||||||
|
model_name_or_path: Qwen/Qwen3.5-4B
|
||||||
|
trust_remote_code: true
|
||||||
|
use_v1_kernels: true
|
||||||
|
flash_attn: fa2
|
||||||
|
|
||||||
|
### method
|
||||||
|
stage: sft
|
||||||
|
do_train: true
|
||||||
|
finetuning_type: full
|
||||||
|
|
||||||
|
### dataset
|
||||||
|
dataset: alpaca_en_demo
|
||||||
|
template: qwen3_5_nothink
|
||||||
|
cutoff_len: 2048
|
||||||
|
max_samples: 1000
|
||||||
|
overwrite_cache: true
|
||||||
|
preprocessing_num_workers: 16
|
||||||
|
dataloader_num_workers: 4
|
||||||
|
|
||||||
|
### output
|
||||||
|
output_dir: saves/Qwen3.5-4B/full/sft
|
||||||
|
logging_steps: 1
|
||||||
|
save_steps: 500
|
||||||
|
max_steps: 500
|
||||||
|
plot_loss: true
|
||||||
|
overwrite_output_dir: true
|
||||||
|
save_only_model: false
|
||||||
|
report_to: none # choices: [none, wandb, tensorboard, swanlab, mlflow]
|
||||||
|
|
||||||
|
### train
|
||||||
|
per_device_train_batch_size: 8
|
||||||
|
gradient_accumulation_steps: 1
|
||||||
|
learning_rate: 1.0e-5
|
||||||
|
lr_scheduler_type: cosine
|
||||||
|
warmup_ratio: 0.1
|
||||||
|
bf16: true
|
||||||
|
ddp_timeout: 1800
|
||||||
|
resume_from_checkpoint: null
|
||||||
51
examples/ascend/qwen3_5moe_lora_sft_fsdp2.yaml
Normal file
51
examples/ascend/qwen3_5moe_lora_sft_fsdp2.yaml
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
# Start FSDP2 full fine-tuning on Ascend NPU
|
||||||
|
# Usage:
|
||||||
|
# accelerate launch \
|
||||||
|
# --config_file examples/accelerate/fsdp2_config_qwen35_moe.yaml \
|
||||||
|
# src/train.py examples/ascend/qwen3_5moe_lora_sft_fsdp2.yaml
|
||||||
|
#
|
||||||
|
# Note: Change `num_processes` in fsdp2_config_qwen35_moe.yaml to match your NPU count
|
||||||
|
|
||||||
|
### model
|
||||||
|
model_name_or_path: Qwen/Qwen3.5-35B-A3B
|
||||||
|
trust_remote_code: true
|
||||||
|
use_v1_kernels: false
|
||||||
|
flash_attn: fa2
|
||||||
|
|
||||||
|
### method
|
||||||
|
stage: sft
|
||||||
|
do_train: true
|
||||||
|
finetuning_type: lora
|
||||||
|
lora_rank: 8
|
||||||
|
lora_target: all
|
||||||
|
|
||||||
|
### dataset
|
||||||
|
dataset: alpaca_en_demo
|
||||||
|
template: qwen3_5_nothink
|
||||||
|
cutoff_len: 2048
|
||||||
|
max_samples: 1000
|
||||||
|
overwrite_cache: true
|
||||||
|
preprocessing_num_workers: 16
|
||||||
|
dataloader_num_workers: 4
|
||||||
|
packing: false
|
||||||
|
|
||||||
|
### output
|
||||||
|
output_dir: saves/Qwen3.5-35B/lora/sft
|
||||||
|
logging_steps: 1
|
||||||
|
save_steps: 2000
|
||||||
|
max_steps: 2000
|
||||||
|
plot_loss: true
|
||||||
|
overwrite_output_dir: true
|
||||||
|
save_only_model: false
|
||||||
|
report_to: none # choices: [none, wandb, tensorboard, swanlab, mlflow]
|
||||||
|
|
||||||
|
### train
|
||||||
|
per_device_train_batch_size: 1
|
||||||
|
gradient_accumulation_steps: 1
|
||||||
|
learning_rate: 1.0e-5
|
||||||
|
lr_scheduler_type: cosine
|
||||||
|
warmup_ratio: 0.1
|
||||||
|
bf16: true
|
||||||
|
ddp_timeout: 1800
|
||||||
|
resume_from_checkpoint: null
|
||||||
|
disable_gradient_checkpointing: true
|
||||||
45
examples/extras/asft/llama2_full_asft.yaml
Normal file
45
examples/extras/asft/llama2_full_asft.yaml
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
### model
|
||||||
|
model_name_or_path: models/Llama-2-7b
|
||||||
|
trust_remote_code: true
|
||||||
|
|
||||||
|
### method
|
||||||
|
stage: sft
|
||||||
|
do_train: true
|
||||||
|
finetuning_type: full
|
||||||
|
deepspeed: examples/deepspeed/ds_z0_config.json
|
||||||
|
use_asft_loss: true
|
||||||
|
asft_alpha: 0.1
|
||||||
|
|
||||||
|
### dataset
|
||||||
|
dataset: med
|
||||||
|
template: llama2
|
||||||
|
cutoff_len: 2048
|
||||||
|
max_samples: 10000
|
||||||
|
overwrite_cache: true
|
||||||
|
preprocessing_num_workers: 16
|
||||||
|
dataloader_num_workers: 4
|
||||||
|
|
||||||
|
### output
|
||||||
|
output_dir: saves/llama2-7b/full/asft2
|
||||||
|
logging_steps: 1
|
||||||
|
save_steps: 500
|
||||||
|
plot_loss: true
|
||||||
|
overwrite_output_dir: true
|
||||||
|
save_only_model: false
|
||||||
|
report_to: none # choices: [none, wandb, tensorboard, swanlab, mlflow]
|
||||||
|
|
||||||
|
### train
|
||||||
|
per_device_train_batch_size: 4
|
||||||
|
gradient_accumulation_steps: 8
|
||||||
|
learning_rate: 2.0e-5
|
||||||
|
num_train_epochs: 3.0
|
||||||
|
lr_scheduler_type: cosine
|
||||||
|
warmup_ratio: 0.1
|
||||||
|
bf16: true
|
||||||
|
ddp_timeout: 180000000
|
||||||
|
|
||||||
|
### eval
|
||||||
|
# val_size: 0.1
|
||||||
|
# per_device_eval_batch_size: 1
|
||||||
|
# eval_strategy: steps
|
||||||
|
# eval_steps: 500
|
||||||
45
examples/extras/asft/qwen2_full_asft.yaml
Normal file
45
examples/extras/asft/qwen2_full_asft.yaml
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
### model
|
||||||
|
model_name_or_path: models/Qwen2.5-7B
|
||||||
|
trust_remote_code: true
|
||||||
|
|
||||||
|
### method
|
||||||
|
stage: sft
|
||||||
|
do_train: true
|
||||||
|
finetuning_type: full
|
||||||
|
deepspeed: examples/deepspeed/ds_z0_config.json
|
||||||
|
use_asft_loss: true
|
||||||
|
asft_alpha: 0.05
|
||||||
|
|
||||||
|
### dataset
|
||||||
|
dataset: math
|
||||||
|
template: qwen
|
||||||
|
cutoff_len: 2048
|
||||||
|
max_samples: 10000
|
||||||
|
overwrite_cache: true
|
||||||
|
preprocessing_num_workers: 16
|
||||||
|
dataloader_num_workers: 4
|
||||||
|
|
||||||
|
### output
|
||||||
|
output_dir: saves/qwen2-7b/full/asft
|
||||||
|
logging_steps: 10
|
||||||
|
save_steps: 500
|
||||||
|
plot_loss: true
|
||||||
|
overwrite_output_dir: true
|
||||||
|
save_only_model: false
|
||||||
|
report_to: none # choices: [none, wandb, tensorboard, swanlab, mlflow]
|
||||||
|
|
||||||
|
### train
|
||||||
|
per_device_train_batch_size: 4
|
||||||
|
gradient_accumulation_steps: 8
|
||||||
|
learning_rate: 5.0e-5
|
||||||
|
num_train_epochs: 1.0
|
||||||
|
lr_scheduler_type: cosine
|
||||||
|
warmup_ratio: 0.1
|
||||||
|
bf16: true
|
||||||
|
ddp_timeout: 180000000
|
||||||
|
|
||||||
|
### eval
|
||||||
|
# val_size: 0.1
|
||||||
|
# per_device_eval_batch_size: 1
|
||||||
|
# eval_strategy: steps
|
||||||
|
# eval_steps: 500
|
||||||
38
examples/extras/eaft/qwen25_05b_eaft_full.yaml
Normal file
38
examples/extras/eaft/qwen25_05b_eaft_full.yaml
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
### model
|
||||||
|
model_name_or_path: Qwen/Qwen2.5-0.5B-Instruct
|
||||||
|
trust_remote_code: true
|
||||||
|
|
||||||
|
### method
|
||||||
|
stage: sft
|
||||||
|
do_train: true
|
||||||
|
finetuning_type: full
|
||||||
|
use_eaft_loss: true
|
||||||
|
|
||||||
|
### dataset
|
||||||
|
dataset: identity,alpaca_en_demo
|
||||||
|
template: qwen
|
||||||
|
cutoff_len: 2048
|
||||||
|
max_samples: 1000
|
||||||
|
overwrite_cache: true
|
||||||
|
preprocessing_num_workers: 16
|
||||||
|
dataloader_num_workers: 4
|
||||||
|
|
||||||
|
### output
|
||||||
|
output_dir: qwen2.5-0_5b/full/sft_eaft
|
||||||
|
logging_steps: 1
|
||||||
|
save_steps: 500
|
||||||
|
plot_loss: true
|
||||||
|
overwrite_output_dir: true
|
||||||
|
save_only_model: false
|
||||||
|
report_to: none # choices: [none, wandb, tensorboard, swanlab, mlflow]
|
||||||
|
|
||||||
|
|
||||||
|
### train
|
||||||
|
per_device_train_batch_size: 2
|
||||||
|
gradient_accumulation_steps: 8
|
||||||
|
learning_rate: 1.0e-5
|
||||||
|
num_train_epochs: 3.0
|
||||||
|
lr_scheduler_type: cosine
|
||||||
|
warmup_ratio: 0.1
|
||||||
|
bf16: true
|
||||||
|
ddp_timeout: 180000000
|
||||||
25
examples/ktransformers/accelerate/fsdp2_kt_bf16.yaml
Normal file
25
examples/ktransformers/accelerate/fsdp2_kt_bf16.yaml
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
compute_environment: LOCAL_MACHINE
|
||||||
|
distributed_type: FSDP
|
||||||
|
fsdp_config:
|
||||||
|
fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
|
||||||
|
fsdp_cpu_ram_efficient_loading: true
|
||||||
|
fsdp_offload_params: false
|
||||||
|
fsdp_reshard_after_forward: true
|
||||||
|
fsdp_state_dict_type: FULL_STATE_DICT
|
||||||
|
fsdp_version: 2
|
||||||
|
mixed_precision: bf16
|
||||||
|
num_machines: 1
|
||||||
|
num_processes: 4 # Adjust based on your GPU count; 4 is suitable for 4 GPUs
|
||||||
|
rdzv_backend: static
|
||||||
|
same_network: true
|
||||||
|
use_cpu: false
|
||||||
|
|
||||||
|
kt_config:
|
||||||
|
enabled: true
|
||||||
|
kt_backend: AMXBF16 # Use with original BF16 expert weights.
|
||||||
|
kt_num_threads: 96
|
||||||
|
kt_tp_enabled: true
|
||||||
|
kt_threadpool_count: 2
|
||||||
|
kt_max_cache_depth: 2
|
||||||
|
kt_share_backward_bb: true
|
||||||
|
lora_rank: 8
|
||||||
25
examples/ktransformers/accelerate/fsdp2_kt_int4.yaml
Normal file
25
examples/ktransformers/accelerate/fsdp2_kt_int4.yaml
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
compute_environment: LOCAL_MACHINE
|
||||||
|
distributed_type: FSDP
|
||||||
|
fsdp_config:
|
||||||
|
fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
|
||||||
|
fsdp_cpu_ram_efficient_loading: true
|
||||||
|
fsdp_offload_params: false
|
||||||
|
fsdp_reshard_after_forward: true
|
||||||
|
fsdp_state_dict_type: FULL_STATE_DICT
|
||||||
|
fsdp_version: 2
|
||||||
|
mixed_precision: bf16
|
||||||
|
num_machines: 1
|
||||||
|
num_processes: 4 # Adjust based on your GPU count; 4 is suitable for 4 GPUs
|
||||||
|
rdzv_backend: static
|
||||||
|
same_network: true
|
||||||
|
use_cpu: false
|
||||||
|
|
||||||
|
kt_config:
|
||||||
|
enabled: true
|
||||||
|
kt_backend: AMXINT4 # Use with online-converted INT4 expert weights
|
||||||
|
kt_num_threads: 96
|
||||||
|
kt_tp_enabled: true
|
||||||
|
kt_threadpool_count: 2
|
||||||
|
kt_max_cache_depth: 2
|
||||||
|
kt_share_backward_bb: true
|
||||||
|
lora_rank: 8
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user