diff --git a/docs/source/.readthedocs.yaml b/docs/source/.readthedocs.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c9707f4c79e79783e8ace42ac956d683fe2f69ca --- /dev/null +++ b/docs/source/.readthedocs.yaml @@ -0,0 +1,29 @@ +# .readthedocs.yaml +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +# Set the OS, Python version and other tools you might need +build: + os: ubuntu-22.04 + tools: + python: "3.10" + +# Build documentation in the "docs/" directory with Sphinx +sphinx: + configuration: docs/source/conf.py + +# Optionally build your docs in additional formats such as PDF and ePub +# formats: +# - pdf +# - epub + +# Optional but recommended, declare the Python requirements required +# to build your documentation +# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html +python: + install: + - requirements: requirements/docs.txt + - requirements: requirements/framework.txt diff --git a/docs/source/BestPractices/AMD-support.md b/docs/source/BestPractices/AMD-support.md new file mode 100644 index 0000000000000000000000000000000000000000..53f5ca2a52feaa9e19a80f093d602b37e60dbaeb --- /dev/null +++ b/docs/source/BestPractices/AMD-support.md @@ -0,0 +1,319 @@ +# AMD GPU 支持 + +## 1. 环境配置 +### 1.1 基础环境 +拉取适配了 AMD ROCm 生态的 ms-swift 镜像,并参照以下命令启动容器。 + +如果用户需要运行更新版本的 ms-swift,可以使用 pip 升级或基于源码安装更新(建议安装时添加 `--no-deps` 选项以避免自动升级其他依赖可能引起的问题)。 + +```bash +IMAGE_NAME=amdagi/modelscope:ubuntu22.04-rocm7.2.0-py312-torch2.10.0-vllm0.18.1-modelscope1.35.1-swift4.1.0 +docker pull ${IMAGE_NAME} + +CONTAINER_NAME=swift_test +docker run -it --network=host --ipc=host --privileged --group-add video \ + --device=/dev/dri --device=/dev/kfd \ + --shm-size 512G --ulimit memlock=-1 \ + --security-opt seccomp=unconfined --cap-add SYS_PTRACE \ + --name ${CONTAINER_NAME} \ + ${IMAGE_NAME} \ + /bin/bash +``` + +### 1.2 环境检查 + +- 确认 container 环境中 pytorch 正确识别 AMD GPU。 + +```bash +python -c "import torch;print(torch.cuda.is_available())" # output: True +``` + +- 检查 GPU 的拓扑连接及 NUMA:`rocm-smi --showtopo` + +``` +============================ ROCm System Management Interface ============================ +WARNING: AMD GPU device(s) is/are in a low-power state. Check power control/runtime_status + +================================ Weight between two GPUs ================================= + GPU0 GPU1 GPU2 GPU3 GPU4 GPU5 GPU6 GPU7 +GPU0 0 15 15 15 15 15 15 15 +GPU1 15 0 15 15 15 15 15 15 +GPU2 15 15 0 15 15 15 15 15 +GPU3 15 15 15 0 15 15 15 15 +GPU4 15 15 15 15 0 15 15 15 +GPU5 15 15 15 15 15 0 15 15 +GPU6 15 15 15 15 15 15 0 15 +GPU7 15 15 15 15 15 15 15 0 + +================================= Hops between two GPUs ================================== + GPU0 GPU1 GPU2 GPU3 GPU4 GPU5 GPU6 GPU7 +GPU0 0 1 1 1 1 1 1 1 +GPU1 1 0 1 1 1 1 1 1 +GPU2 1 1 0 1 1 1 1 1 +GPU3 1 1 1 0 1 1 1 1 +GPU4 1 1 1 1 0 1 1 1 +GPU5 1 1 1 1 1 0 1 1 +GPU6 1 1 1 1 1 1 0 1 +GPU7 1 1 1 1 1 1 1 0 + +=============================== Link Type between two GPUs =============================== + GPU0 GPU1 GPU2 GPU3 GPU4 GPU5 GPU6 GPU7 +GPU0 0 XGMI XGMI XGMI XGMI XGMI XGMI XGMI +GPU1 XGMI 0 XGMI XGMI XGMI XGMI XGMI XGMI +GPU2 XGMI XGMI 0 XGMI XGMI XGMI XGMI XGMI +GPU3 XGMI XGMI XGMI 0 XGMI XGMI XGMI XGMI +GPU4 XGMI XGMI XGMI XGMI 0 XGMI XGMI XGMI +GPU5 XGMI XGMI XGMI XGMI XGMI 0 XGMI XGMI +GPU6 XGMI XGMI XGMI XGMI XGMI XGMI 0 XGMI +GPU7 XGMI XGMI XGMI XGMI XGMI XGMI XGMI 0 + +======================================= Numa Nodes ======================================= +GPU[0] : (Topology) Numa Node: 0 +GPU[0] : (Topology) Numa Affinity: 0 +GPU[1] : (Topology) Numa Node: 0 +GPU[1] : (Topology) Numa Affinity: 0 +GPU[2] : (Topology) Numa Node: 0 +GPU[2] : (Topology) Numa Affinity: 0 +GPU[3] : (Topology) Numa Node: 0 +GPU[3] : (Topology) Numa Affinity: 0 +GPU[4] : (Topology) Numa Node: 1 +GPU[4] : (Topology) Numa Affinity: 1 +GPU[5] : (Topology) Numa Node: 1 +GPU[5] : (Topology) Numa Affinity: 1 +GPU[6] : (Topology) Numa Node: 1 +GPU[6] : (Topology) Numa Affinity: 1 +GPU[7] : (Topology) Numa Node: 1 +GPU[7] : (Topology) Numa Affinity: 1 +================================== End of ROCm SMI Log =================================== +``` + +- 查看 GPU 利用率及显存占用等信息(`rocm-smi` 或者 `rocm-smi -u --showmeminfo vram`) + +``` +# output of 'rocm-smi' +============================================ ROCm System Management Interface ============================================ +====================================================== Concise Info ====================================================== +Device Node IDs Temp Power Partitions SCLK MCLK Fan Perf PwrCap VRAM% GPU% + (DID, GUID) (Junction) (Socket) (Mem, Compute, ID) +========================================================================================================================== +0 2 0x74a2, 1017 43.0°C 155.0W NPS1, SPX, 0 94Mhz 900Mhz 0% auto 650.0W 0% 0% +1 3 0x74a2, 47713 41.0°C 155.0W NPS1, SPX, 0 91Mhz 900Mhz 0% auto 650.0W 0% 0% +2 4 0x74a2, 37449 45.0°C 159.0W NPS1, SPX, 0 95Mhz 900Mhz 0% auto 650.0W 0% 0% +3 5 0x74a2, 11217 41.0°C 155.0W NPS1, SPX, 0 95Mhz 900Mhz 0% auto 650.0W 0% 0% +4 6 0x74a2, 41880 44.0°C 160.0W NPS1, SPX, 0 91Mhz 900Mhz 0% auto 650.0W 0% 0% +5 7 0x74a2, 6656 42.0°C 157.0W NPS1, SPX, 0 95Mhz 900Mhz 0% auto 650.0W 0% 0% +6 8 0x74a2, 12840 45.0°C 160.0W NPS1, SPX, 0 96Mhz 900Mhz 0% auto 650.0W 0% 0% +7 9 0x74a2, 35760 43.0°C 158.0W NPS1, SPX, 0 107Mhz 900Mhz 0% auto 650.0W 0% 0% +========================================================================================================================== +================================================== End of ROCm SMI Log =================================================== + +# output of 'rocm-smi -u --showmeminfo vram' +============================ ROCm System Management Interface ============================ +=================================== % time GPU is busy =================================== +GPU[0] : GPU use (%): 0 +GPU[0] : GFX Activity: 3862538534 +GPU[1] : GPU use (%): 0 +GPU[1] : GFX Activity: 4053246251 +GPU[2] : GPU use (%): 0 +GPU[2] : GFX Activity: 3114103535 +GPU[3] : GPU use (%): 0 +GPU[3] : GFX Activity: 4026776444 +GPU[4] : GPU use (%): 0 +GPU[4] : GFX Activity: 1224255679 +GPU[5] : GPU use (%): 0 +GPU[5] : GFX Activity: 1191191242 +GPU[6] : GPU use (%): 0 +GPU[6] : GFX Activity: 1184652679 +GPU[7] : GPU use (%): 0 +GPU[7] : GFX Activity: 2145209382 +========================================================================================== +================================== Memory Usage (Bytes) ================================== +GPU[0] : VRAM Total Memory (B): 206141652992 +GPU[0] : VRAM Total Used Memory (B): 297611264 +GPU[1] : VRAM Total Memory (B): 206141652992 +GPU[1] : VRAM Total Used Memory (B): 297623552 +GPU[2] : VRAM Total Memory (B): 206141652992 +GPU[2] : VRAM Total Used Memory (B): 297623552 +GPU[3] : VRAM Total Memory (B): 206141652992 +GPU[3] : VRAM Total Used Memory (B): 297623552 +GPU[4] : VRAM Total Memory (B): 206141652992 +GPU[4] : VRAM Total Used Memory (B): 297623552 +GPU[5] : VRAM Total Memory (B): 206141652992 +GPU[5] : VRAM Total Used Memory (B): 297623552 +GPU[6] : VRAM Total Memory (B): 206141652992 +GPU[6] : VRAM Total Used Memory (B): 297623552 +GPU[7] : VRAM Total Memory (B): 206141652992 +GPU[7] : VRAM Total Used Memory (B): 297623552 +========================================================================================== +================================== End of ROCm SMI Log =================================== +``` + +## 2. 运行示例 + +### 2.1 使用 Megatron-Swift 全量微调 Qwen3.5 模型 +AMD GPU 显存相对较大,因此可以通过同时对以下参数进行联合调优,以提升训练吞吐性能。 +- 并行度调优(TP/PP/EP等):GPU 单卡显存较大使得用户可以尽可能减小并行度切分带来的通信开销(优先级 PP/EP > TP) +- 显存允许的情况下关闭 optimizer cpu offload:设置 `--optimizer_cpu_offload false` +- 显存允许的情况下调整 activation/gradient checkpointing:设置 `--recompute_granularity none`,或者 `--recompute_granularity selective` 配合 `--recompute_modules` 进行细粒度的控制 +- 对于 MoE 模型,建议设置 `export NVTE_USE_CUTLASS_GROUPED_GEMM=1` 以使用优化的 grouped gemm kernel +- 对于带有 GatedDeltaNet 结构的模型,建议设置 `USE_MCORE_GDN=1` 使用 mcore 的实现版本 +- 为避免在某些 AMD GPU 上可能出现的问题,保证性能更稳定,建议设置 `export HSA_NO_SCRATCH_RECLAIM=1` + +单机训练: + +```bash +export HSA_NO_SCRATCH_RECLAIM=1 +export NVTE_USE_CUTLASS_GROUPED_GEMM=1 + +output_dir=${PWD}/megatron_output/Qwen3.5-35B-A3B +mkdir -p ${output_dir} +current_time=$(date "+%Y.%m.%d-%H.%M.%S") +log_file=${output_dir}/"1node_full_megatron_Qwen3.5-35B-A3B_${current_time}.log" + +PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True' \ +NPROC_PER_NODE=8 \ +MAX_PIXELS=1003520 \ +VIDEO_MAX_PIXELS=50176 \ +FPS_MAX_FRAMES=12 \ +SKIP_MULTIMODAL_MTP_VALIDATION=1 \ +USE_MCORE_GDN=1 \ +megatron sft \ + --model Qwen/Qwen3.5-35B-A3B \ + --dataset 'AI-ModelScope/LongAlpaca-12k' \ + --save_safetensors true \ + --load_from_cache_file true \ + --tuner_type full \ + --add_non_thinking_prefix true \ + --split_dataset_ratio 0.01 \ + --tensor_model_parallel_size 1 \ + --pipeline_model_parallel_size 1 \ + --expert_model_parallel_size 8 \ + --sequence_parallel true \ + --moe_permute_fusion true \ + --moe_grouped_gemm true \ + --moe_shared_expert_overlap true \ + --moe_aux_loss_coeff 1e-6 \ + --moe_expert_capacity_factor 2 \ + --micro_batch_size 1 \ + --global_batch_size 8 \ + --recompute_granularity selective \ + --recompute_modules core_attn mlp moe \ + --num_train_epochs 500 \ + --group_by_length true \ + --finetune true \ + --freeze_llm false \ + --freeze_vit false \ + --freeze_aligner false \ + --cross_entropy_loss_fusion true \ + --lr 1e-5 \ + --lr_warmup_fraction 0.05 \ + --min_lr 1e-6 \ + --weight_decay 0.1 \ + --adam_beta2 0.95 \ + --eval_steps 500 \ + --save_steps 500 \ + --save_total_limit 10 \ + --logging_steps 1 \ + --max_length 16384 \ + --dataloader_num_workers 8 \ + --dataset_num_proc 8 \ + --no_save_optim true \ + --no_save_rng true \ + --optimizer_cpu_offload false \ + --attention_backend flash \ + --padding_free false \ + --output_dir ${output_dir} \ + 2>&1 | tee ${log_file} +``` + +多机训练: + +```bash +export NNODES=2 # 此处以 2 节点为例 +export NODE_RANK=0 # 主节点设置为 0,从节点设置为 1 +export MASTER_ADDR= # 根据主节点 ip 设置 +export MASTER_PORT=29500 # 设置通信端口 +export NCCL_SOCKET_IFNAME=ens50f1np1 # 根据机器实际通信网口名设置,可通过 ifconfig 查看 +export GLOO_SOCKET_IFNAME=ens50f1np1 # 根据机器实际通信网口名设置,可通过 ifconfig 查看 +export NCCL_IB_HCA=mlx5_0,mlx5_1,mlx5_2,mlx5_3 # 根据实际IB网卡名设置,可通过 ibv_devices 查看 +export NCCL_IB_GID_INDEX=3 + +# 训练脚本主体:参照单机训练脚本 +... +``` + +### 2.2 使用 Megatron-Swift 对 Qwen3.5 模型做强化学习训练 + +```bash +# 单机训练样例 +export HSA_NO_SCRATCH_RECLAIM=1 +export NVTE_USE_CUTLASS_GROUPED_GEMM=1 + +SYSTEM_PROMPT="""You are a helpful math assistant. Solve the problem step by step and put your final answer within \\boxed{}.""" + +CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \ +NPROC_PER_NODE=8 \ +PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True' \ +megatron rlhf \ + --rlhf_type grpo \ + --model Qwen/Qwen3.5-35B-A3B \ + --save_safetensors true \ + --enable_thinking false \ + --merge_lora true \ + --context_parallel_size 1 \ + --tensor_model_parallel_size 1 \ + --expert_model_parallel_size 8 \ + --pipeline_model_parallel_size 1 \ + --moe_permute_fusion true \ + --dataset open-r1/DAPO-Math-17k-Processed \ + --system "$SYSTEM_PROMPT" \ + --num_train_epochs 1 \ + --global_batch_size 64 \ + --micro_batch_size 1 \ + --steps_per_generation 2 \ + --num_generations 8 \ + --reward_funcs accuracy \ + --use_vllm true \ + --vllm_mode colocate \ + --vllm_gpu_memory_utilization 0.5 \ + --vllm_tensor_parallel_size 2 \ + --vllm_max_model_len 9192 \ + --max_length 1000 \ + --max_completion_length 8192 \ + --tuner_type lora \ + --target_modules all-linear \ + --lr 5e-5 \ + --bf16 true \ + --beta 0.00 \ + --epsilon 0.2 \ + --epsilon_high 0.28 \ + --dynamic_sample false \ + --overlong_filter true \ + --loss_type grpo \ + --sleep_level 1 \ + --offload_model true \ + --offload_bridge false \ + --offload_optimizer true \ + --logging_steps 1 \ + --recompute_granularity none \ + --gradient_accumulation_fusion false \ + --finetune \ + --dataloader_num_workers 8 \ + --dataset_num_proc 8 \ + --no_save_optim \ + --no_save_rng \ + --save_steps 20 \ + --attention_backend flash \ + --moe_expert_capacity_factor 2 \ + --temperature 1.0 \ + --padding_free false \ + --sequence_parallel true \ + --log_completions true \ + --report_to tensorboard +``` + +## 已知问题 +- 强化学习训练: + - 在强化学习训练中,如果使用 vLLM 作为推理引擎,需要 vLLM>=0.11.0。建议使用 ROCm7.0 或者我们提供的镜像以避免出现 sleep mode memory leak 问题。 +- MoE 模型训练: + - MoE模型建议增加环境变量 NVTE_USE_CUTLASS_GROUPED_GEMM=1 以避免偶发的GPU卡死问题。 diff --git a/docs/source/BestPractices/Elastic.md b/docs/source/BestPractices/Elastic.md new file mode 100644 index 0000000000000000000000000000000000000000..3a7823914dc720c1360578c6d699f9a79c66377e --- /dev/null +++ b/docs/source/BestPractices/Elastic.md @@ -0,0 +1,211 @@ +# Elastic + + + +## 安装依赖 + +集群部署K8S,并在集群中部署DLrover,[DLRover](https://github.com/intelligent-machine-learning/dlrover), +`pip install dlrover && pip install tornado && pip install kubernetes && pip install ms-swift` + +经过反复测试验证的训练镜像中的其它依赖以及版本: +deepspeed 0.16.5(需参考https://github.com/deepspeedai/DeepSpeed/pull/7585/files 修复universal checkpoint 相关问题) +pytorch 2.6.0 + + +## 如何启动 + +通过在`--callbacks`中添加`deepspeed_elastic`(可选`graceful_exit`)启用弹性训练,并配置DeepSpeed弹性参数。 +命令组成=dlrover-run +dlrover 命令参数+swift 启动命令 +swift参数,dlrover-run除自定义的参数外,其他参数与torchrun一致; +dlrover-run 参数如下: +``` +usage: dlrover-run [-h] [--nnodes NNODES] [--nproc-per-node NPROC_PER_NODE] + [--rdzv-backend RDZV_BACKEND] [--rdzv-endpoint RDZV_ENDPOINT] [--rdzv-id RDZV_ID] + [--rdzv-conf RDZV_CONF] [--standalone] [--max-restarts MAX_RESTARTS] + [--monitor-interval MONITOR_INTERVAL] [--start-method {spawn,fork,forkserver}] + [--role ROLE] [-m] [--no-python] [--run-path] [--log-dir LOG_DIR] [-r REDIRECTS] + [-t TEE] [--local-ranks-filter LOCAL_RANKS_FILTER] [--node-rank NODE_RANK] + [--master-addr MASTER_ADDR] [--master-port MASTER_PORT] [--local-addr LOCAL_ADDR] + [--logs-specs LOGS_SPECS] [--precheck {0,1,2}] [--node_unit NODE_UNIT] + [--auto_config] [--auto_tunning] [--exclude-straggler] [--save_at_breakpoint] + [--accelerator {nvidia.com/gpu,ascend-npu}] [--training_port TRAINING_PORT] + [--switchbox-check] [--box-pairs PAIR [PAIR ...]] [--min-bandwidth MIN_BANDWIDTH] + [--min-channels MIN_CHANNELS] [--numa-affinity] [--network-check] + [--comm-perf-test] [--ucp_device_type UCP_DEVICE_TYPE] + training_script + +``` +在弹性训练中我们需要关注的参数为: + +--nnodes NNODES Number of nodes, or the range of nodes in form + :. + +--nproc-per-node NPROC_PER_NODE Number of processes per node. +示例: + +```bash +model=your model path +dataset=your dataset +output= your output dir +export CUDA_VISIBLE_DEVICES=0 根据实际使用的GPU情况设置 +deepspeed_config_or_type=deepspeed类型或者配置文件的路径,如 zero1 或者/xxx/ms-swift/swift/llm/ds_config/zero1.json + +dlrover-run --nnodes 1:$NODE_NUM --nproc_per_node=1 \ +/opt/conda/lib/python3.10/site-packages/swift/cli/sft.py --model $model \ +--model_type qwen3 \ +--tuner_type lora \ +--torch_dtype bfloat16 \ +--dataset $dataset \ +--num_train_epochs 4 \ +--per_device_train_batch_size 1 \ +--per_device_eval_batch_size 1 \ +--learning_rate 5e-7 \ +--gradient_accumulation_steps 8 \ +--eval_steps 500 \ +--save_steps 10 \ +--save_total_limit 20 \ +--logging_steps 1 \ +--output_dir $output \ +--warmup_ratio 0.01 \ +--dataloader_num_workers 4 \ +--temperature 1.0 \ +--system 'You are a helpful assistant.' \ +--lora_rank 8 \ +--lora_alpha 32 \ +--target_modules all-linear \ +--dataset_num_proc 1 \ +--use_flash_ckpt true \ +--callbacks deepspeed_elastic graceful_exit \ +--deepspeed $deepspeed_config_or_type \ +``` + +## 配置文件示例 +默认情况下的zero1为以下示例配置, + +```json +{ + "fp16": { + "enabled": "auto", + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + + "bf16": { + "enabled": "auto" + }, + + "zero_optimization": { + "stage": 1, + "offload_optimizer": { + "device": "none", + "pin_memory": true + }, + "allgather_partitions": true, + "allgather_bucket_size": 2e8, + "overlap_comm": false, + "reduce_scatter": true, + "reduce_bucket_size": 2e8, + "contiguous_gradients": true + }, + + "gradient_accumulation_steps": "auto", + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false, + "elasticity": { + "ignore_non_elastic_batch_info": true, + "enabled": true, + "max_train_batch_size": 8, + "micro_batch_sizes": [ + 4, + 2 + ], + "min_gpus": 1, + "max_gpus": 4, + "min_time": 20, + "version": 0.1 + } +} +``` + +如果用户需要自定义,可以在启动命令中deepspeed_config_or_type指定自定义的zero1.json的存放路径,其中弹性相关的配置为: +```json +... + + "elasticity": { + "ignore_non_elastic_batch_info": true, + "enabled": true, + "max_train_batch_size": 8, + "micro_batch_sizes": [ + 4, + 2 + ], + "min_gpus": 1, + "max_gpus": 4, + "min_time": 20, + "version": 0.1 + } +``` + +- ignore_non_elastic_batch_info:代表在elasticity里的配置会忽略外层的batch_size相关的配置,训练过程中会根据实际的训练进程个数实时修改batch_size等相关的参数 +计算原则为: + global-training-batch-size = micro-batch-size * gradient-accumulation-steps * world-size +- max_train_batch_size:最大batch_size数 +- micro_batch_sizes:elasticity下允许的每卡micro-batch size列表,相当于train_micro_batch_size_per_gpu的候选值 +- min_gpus:最小gpu数目 +- max_gpus:最大gpu数目 +更详细的内容见:[Deepspeed](https://www.deepspeed.ai/docs/config-json/#elastic-training-config-v01-and-v02) + + +## 启动训练 + +```yaml +--- +apiVersion: elastic.iml.github.io/v1alpha1 +kind: ElasticJob +metadata: + name: deepspeed-elastic-swift + namespace: dlrover +spec: + distributionStrategy: AllreduceStrategy + optimizeMode: single-job + replicaSpecs: + worker: + replicas: 1 #【这里需要与启动命令中的--nnodes NNODES的最大值一致】 + template: + spec: + restartPolicy: Never + containers: + - name: main + image: #【训练镜像,需要安装deepspeed,dlrover 和swift 】 + imagePullPolicy: IfNotPresent + command: + - /bin/bash + - -c + - sh start.sh # 启动脚本 + resources: + limits: + cpu: '8' + memory: 16Gi + nvidia.com/gpu: '1' + volumeMounts: + - mountPath: /model + name: volume-model + - mountPath: /dev/shm + name: volume-shm + restartPolicy: Never + volumes: + - hostPath: + path: /model + type: Directory + name: volume-model + - emptyDir: + medium: Memory + sizeLimit: 200Gi + name: volume-shm + +``` diff --git a/docs/source/BestPractices/Embedding.md b/docs/source/BestPractices/Embedding.md new file mode 100644 index 0000000000000000000000000000000000000000..e59df2122dece0d2753ff37b6bb5f6b0f57653ea --- /dev/null +++ b/docs/source/BestPractices/Embedding.md @@ -0,0 +1,211 @@ +# Embedding训练 + +SWIFT已经支持Embedding模型的训练,包括纯文本和多模态两个类型。目前已经支持的模型有: + +1. modernbert embedding模型 + - [ModelScope](https://modelscope.cn/models/iic/gte-modernbert-base) [Hugging Face](https://huggingface.co/Alibaba-NLP/gte-modernbert-base) +2. gte embedding模型 + - 1.5B: [ModelScope](https://www.modelscope.cn/models/iic/gte_Qwen2-1.5B-instruct) [Hugging Face](https://huggingface.co/Alibaba-NLP/gte-Qwen2-1.5B-instruct) + - 7B: [ModelScope](https://www.modelscope.cn/models/iic/gte_Qwen2-7B-instruct) [Hugging Face](https://huggingface.co/Alibaba-NLP/gte-Qwen2-7B-instruct) +3. gme embedding模型 + - 2B: [ModelScope](https://www.modelscope.cn/models/iic/gme-Qwen2-VL-2B-Instruct) [Hugging Face](https://huggingface.co/Alibaba-NLP/gme-Qwen2-VL-2B-Instruct) + - 7B: [ModelScope](https://www.modelscope.cn/models/iic/gme-Qwen2-VL-7B-Instruct) [Hugging Face](https://huggingface.co/Alibaba-NLP/gme-Qwen2-VL-7B-Instruct) +4. qwen3-embedding模型 + - 0.6B: [ModelScope](https://www.modelscope.cn/models/Qwen/Qwen3-Embedding-0.6B) [Hugging Face](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) + - 4B: [ModelScope](https://www.modelscope.cn/models/Qwen/Qwen3-Embedding-4B) [Hugging Face](https://huggingface.co/Qwen/Qwen3-Embedding-4B) + - 8B: [ModelScope](https://www.modelscope.cn/models/Qwen/Qwen3-Embedding-8B) [Hugging Face](https://huggingface.co/Qwen/Qwen3-Embedding-8B) +5. qwen3-vl-embedding模型 + - 2B: [ModelScope](https://www.modelscope.cn/models/Qwen/Qwen3-VL-Embedding-2B) [Hugging Face](https://huggingface.co/Qwen/Qwen3-VL-Embedding-2B) + - 8B: [ModelScope](https://www.modelscope.cn/models/Qwen/Qwen3-VL-Embedding-8B) [Hugging Face](https://huggingface.co/Qwen/Qwen3-VL-Embedding-8B) + + +开发者可以自行集成自己的模型,模型forward输出值需要满足: + +```text +{"last_hidden_state": some-embedding-tensor} +``` + +返回值是一个json,具有`last_hidden_state` key,value是embedding tensor即可,输入部分可以使用我们已经支持的template。用户也可以通过指定 + +```shell + --task_type embedding +``` +参数来将任意一个其他模型转换为embedding模型进行训练。 + +需要注意的是,SWIFT目前支持的embedding模型均为符合纯文本或多模态LLM,目前并不支持CLIP类型的模型训练。 + +此外,SWIFT支持的所有embedding模型在模型forward最后都增加了normalize,如自行增加新模型请注意增加normalize层。 + +## loss + +目前SWIFT支持的Embedding模型可以使用的loss有: + +- cosine_similarity: cosine相似度loss,计算两个embedding的相似度,并根据label的值拟合,实际为MSE loss +- contrastive: 可调margin的对比学习loss,label仅支持0和1两个值 +- online_contrastive: 考虑hard negative和hard positive部分的contrastive loss,label仅支持0和1两个值 +- infonce: 在同一个batch中不同row两两计算cosine相似度,并使row内部相似度最大,不同row相似度最小,不需要label + +loss的源代码可以在[这里](https://github.com/modelscope/ms-swift/blob/main/swift/loss/mapping.py)找到。 + +## 数据集格式 + +> 注: +> 1. ``标签可以出现在`messages`/`positive_messages`/`negative_messages`的任意位置;它们各自拥有独立的`images`/`positive_images`/`negative_images`字段用于提供图片路径或URL。 +> 2. 不再需要跨字段的“对应顺序”。对齐规则为:`images`的长度等于`messages`中``标签的数量;`positive_images`与`negative_images`均为“list of list”,其外层长度分别等于`positive_messages`与`negative_messages`的长度;并且外层每一项的内层列表长度等于该条消息序列中``标签的数量。 +> 3. `messages`代表anchor样本(anchor sample);`positive_messages`/`negative_messages`为“list of messages”(因此多一层`[]`);相应地,`positive_images`/`negative_images`也多一层`[]`并与之逐项对齐。 +> 4. 也支持`