diff --git a/index.rst b/index.rst index c8deee3..f8e9f75 100644 --- a/index.rst +++ b/index.rst @@ -25,6 +25,8 @@ sources/onnxruntime/index.rst sources/open_clip/index.rst sources/timm/index.rst + sources/Diffusers/index.rst + sources/opencv/index.rst .. warning:: @@ -122,11 +124,11 @@
- 官方链接 + 官方链接 | - 安装指南 + 安装指南 | - 快速上手 + 快速上手
@@ -177,11 +179,11 @@
- 官方链接 + 官方链接 | - 安装指南 + 安装指南 | - 快速上手 + 快速上手
diff --git a/sources/Diffusers/index.rst b/sources/Diffusers/index.rst new file mode 100644 index 0000000..43bfb55 --- /dev/null +++ b/sources/Diffusers/index.rst @@ -0,0 +1,8 @@ +Diffusers +=========== + +.. toctree:: + :maxdepth: 2 + + install.rst + quick_start.rst diff --git a/sources/Diffusers/install.rst b/sources/Diffusers/install.rst new file mode 100644 index 0000000..8cc2536 --- /dev/null +++ b/sources/Diffusers/install.rst @@ -0,0 +1,52 @@ +安装指南 +============== + +本教程面向使用 Diffusers & 昇腾开发者,帮助完成昇腾环境下 Diffusers 的安装。 + +昇腾环境安装 +------------ + +请根据已有昇腾产品型号及CPU架构等按照 :doc:`快速安装昇腾环境指引 <../ascend/quick_install>` 进行昇腾环境安装,或直接获取对应产品的昇腾环境镜像 `cosdt/cann `_ 。 + +.. warning:: + CANN 最低版本为 8.0.rc1,安装 CANN 时,请同时安装 Kernel 算子包。 + +Diffusers 安装 +------------------ + +Python 环境创建 +------------------ + +.. code-block:: shell + :linenos: + + # 创建名为 diffusers 的 python 3.10 的虚拟环境 + conda create -n diffusers python=3.10 + # 激活虚拟环境 + conda activate diffusers + + +pip 安装 +------------------ + +通过以下指令安装 Diffusers 及 torch-npu: + +.. code-block:: shell + :linenos: + + pip install diffusers torch==2.2.0 torch-npu==2.2.0 torchvision + + +安装校验 +------------------ + +执行以下代码,若无任何报错,仅打印模型下载过程,即说明安装成功: + +.. code-block:: python + :linenos: + + from diffusers import DiffusionPipeline + import torch + + pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) + pipeline.to("npu") diff --git a/sources/Diffusers/quick_start.rst b/sources/Diffusers/quick_start.rst new file mode 100644 index 0000000..d79df11 --- /dev/null +++ b/sources/Diffusers/quick_start.rst @@ -0,0 +1,99 @@ +快速开始 +================== + +本示例以文生图 Diffusers 库中文生图任务为样例,展示如何进行文生图模型 stable-diffusion-xl-base-1.0 的基于 LoRA 的微调及动态合并 LoRA 的推理。 + +文生图 +------------- + +.. _download: + +模型及数据集下载 +~~~~~~~~~~~~~~~~~~~~ + +1. 请提前下载 `stabilityai/stable-diffusion-xl-base-1.0 `_ 模型至自定义路径 + +2. 请提前下载 `madebyollin/sdxl-vae-fp16-fix `_ 模型至自定义路径 + +3. 请提前下载 `reach-vb/pokemon-blip-captions `_ 数据集至自定义路径 + + +.. _finetune: + +基于 LoRA 的微调 +~~~~~~~~~~~~~~~~~~~~ + +进入 Diffusers 项目目录,新建并执行以下脚本: + +.. note:: + + 请根据 :ref:`download` 中模型及数据集的实际缓存路径指定 stable-diffusion-xl-base-1.0 模型缓存路径 ``MODEL_NAME``,sdxl-vae-fp16-fix 模型缓存路径 ``VAE_NAME`` 和。 + +.. code-block:: shell + :linenos: + :emphasize-lines: 1,2,3 + + export MODEL_NAME="./models_ckpt/stable-diffusion-xl-base-1.0/" + export VAE_NAME="./ckpt/sdxl-vae-fp16-fix" + export TRAIN_DIR="~/diffusers/data/pokemon-blip-captions/pokemon" + + python3 ./examples/text_to_image/train_text_to_image_lora_sdxl.py \ + --pretrained_model_name_or_path=$MODEL_NAME \ + --pretrained_vae_model_name_or_path=$VAE_NAME \ + --dataset_name=$DATASET_NAME --caption_column="text" \ + --resolution=1024 \ + --random_flip \ + --train_batch_size=1 \ + --num_train_epochs=2 \ + --checkpointing_steps=500 \ + --learning_rate=1e-04 \ + --lr_scheduler="constant" \ + --lr_warmup_steps=0 \ + --mixed_precision="no" \ + --seed=42 \ + --output_dir="sd-pokemon-model-lora-sdxl" \ + --validation_prompt="cute dragon creature" + +微调过程无报错,并且终端显示 ``Steps: 100%`` 的进度条说明微调成功。 + + +动态合并 LoRA 的推理 +~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + 请根据 :ref:`download` 中模型实际缓存路径指定 ``model_path`` + + 根据 :ref:`finetune` 中指定的 LoRA 模型路径 ``output_dir`` 指定 ``lora_model_path`` + + [可选] 修改 ``prompt`` 可使得生成图像改变 + +.. code-block:: python + :linenos: + :emphasize-lines: 9 + + from diffusers import DiffusionPipeline + import torch + + lora_model_path = "path/to/sd-pokemon-model-lora-sdxl/checkpoint-800/" + model_path = "./models_ckpt/stable-diffusion-xl-base-1.0/" + pipe = DiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float16) + + # 将模型放到 NPU 上 + pipe.to("npu") + + # 加载 LoRA 权重 + pipe.load_lora_weights(lora_model_path) + # 输入 prompt + prompt = "Sylveon Pokemon with elegant features, magical design, \ + light purple aura, extremely detailed and intricate markings, \ + photo realistic, unreal engine, octane render" + # 推理 + image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0] + + image.save("pokemon-finetuned-inference-generation.png") + + +微调过程无报错,并且终端显示 ``Loading pipeline components...: 100%`` 的进度条说明微调成功。 +查看当前目录下保存的 ``pokemon-finetuned-inference-generation.png`` 图像,可根据 ``prompt`` 生成内容相关的图像说明推理成功。 + diff --git a/sources/open_clip/install.rst b/sources/open_clip/install.rst index d29f6eb..40a3827 100644 --- a/sources/open_clip/install.rst +++ b/sources/open_clip/install.rst @@ -53,7 +53,7 @@ torch-npu 安装 .. code-block:: python :linenos: - :emphasize-lines: 2,14,15,16,18 + :emphasize-lines: 2 import torch import torch_npu diff --git a/sources/opencv/images/input.png b/sources/opencv/images/input.png new file mode 100644 index 0000000..c337954 Binary files /dev/null and b/sources/opencv/images/input.png differ diff --git a/sources/opencv/images/opencv_cannop.png b/sources/opencv/images/opencv_cannop.png new file mode 100644 index 0000000..982c57d Binary files /dev/null and b/sources/opencv/images/opencv_cannop.png differ diff --git a/sources/opencv/images/result.png b/sources/opencv/images/result.png new file mode 100644 index 0000000..0411455 Binary files /dev/null and b/sources/opencv/images/result.png differ diff --git a/sources/opencv/index.rst b/sources/opencv/index.rst new file mode 100644 index 0000000..b8a63e5 --- /dev/null +++ b/sources/opencv/index.rst @@ -0,0 +1,8 @@ +OpenCV +=========== + +.. toctree:: + :maxdepth: 2 + + install.rst + quick_start.rst diff --git a/sources/opencv/install.rst b/sources/opencv/install.rst new file mode 100644 index 0000000..7b840f5 --- /dev/null +++ b/sources/opencv/install.rst @@ -0,0 +1,109 @@ +安装指南 +============== + +OpenCV 4.9.0 版本开始,增加了图像处理相关高频接口的昇腾原生支持,本教程面向使用 OpenCV & 昇腾开发者,帮助完成昇腾环境下 OpenCV 的安装。 + +昇腾环境安装 +------------ + +请根据已有昇腾产品型号及CPU架构等按照 :doc:`快速安装昇腾环境指引 <../ascend/quick_install>` 进行昇腾环境安装,或直接获取对应产品的昇腾环境镜像 `cosdt/cann `_ 。 + +.. warning:: + CANN 最低版本为 8.0.rc1,安装 CANN 时,请同时安装 Kernel 算子包。 + +OpenCV 安装 +---------------------- + + +请遵循以下版本控制: + +======= ========== ========== + lib 最低版本 推荐版本 +======= ========== ========== +OpenCV 4.9.0 latest +Python 3.9 3.9 +GCC 9.4.0 9.4.0 +======= ========== ========== + +Python 环境创建 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: shell + :linenos: + + # 创建名为 opencv 的 python 3.10 的虚拟环境 + conda create -n opencv python=3.10 + # 激活虚拟环境 + conda activate opencv + + +源码编译 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +1. 下载 OpenCV 和 opencv_contrib + +.. code-block:: shell + :linenos: + + git clone https://github.com/opencv/opencv.git + + cd opencv + git clone https://github.com/opencv/opencv_contrib.git + +2. 编译带有 opencv_contrib 的 OpenCV + +.. TODO: check for the simplest cmake config +.. code-block:: shell + :linenos: + + # 在 opencv 项目目录中创建并进入 build 目录 + mkdir build + cd build + + # cmake & make + cmake -D CMAKE_BUILD_TYPE=RELEASE + -D CMAKE_INSTALL_PREFIX=pwd/install \ + -D WITH_DEBUG=0 \ + -D OPENCV_EXTRA_MODULES_PATH=/path/to/opencv/opencv_contrib/modules \ + -D DWITH_CUDA=0 \ + -D DWITH_CANN=1 \ + -D DPYTHON3_EXECUTABLE=/path/to/miniconda3/envs/opencv/bin/python \ + -D DPYTHON_LIBRARY=/path/to/miniconda3/envs/opencv \ + -D PYTHON_INCLUDE_DIR=/path/to/miniconda3/envs/opencv/include/python3.10 \ + -D BUILD_opencv_wechat_qrcode=OFF \ + -D BUILD_opencv_xfeatures2d=OFF \ + -D BUILD_opencv_face=OFF \ + -D BUILD_opencv_dnn=OFF \ + -D BUILD_opencv_features2d=OFF \ + -D WITH_CAROTENE=OFF \ + -D WITH_IPP=OFF \ + -D BUILD_DOCS=ON \ + -D BUILD_EXAMPLES=ON .. + + make -j5 + +当编译出现以下关键回显信息时,说明编译成功。 + +.. code-block:: shell + + # xxx 为 OpenCV 中某模块名称 + [100%] Built target xxx + +安装校验 +---------------------- + +通过以下指令执行昇腾算子单元测试: + +.. code-block:: shell + :linenos: + + cd path/to/opencv/build/bin + ./opencv_test_cannops + +出现以下关键回显说明安装成功: + +.. code-block:: shell + + [==========] 72 tests from 4 test cases ran. (40937 ms total) + [ PASSED ] 72 tests. + diff --git a/sources/opencv/quick_start.rst b/sources/opencv/quick_start.rst new file mode 100644 index 0000000..697557e --- /dev/null +++ b/sources/opencv/quick_start.rst @@ -0,0 +1,140 @@ +快速开始 +================== + +OpenCV 中昇腾算子入参列表和 cpu 及 cuda 算子保持一致,除了对昇腾必要的初始化、去初始化之外,用户无需学习 CANN API,仅需要将原来的接口添加 cann 包名(C++ 接口为使用 cann 命名空间),整体流程如下图所示: + +.. figure:: ./images/opencv_cannop.png + :align: center + :scale: 70% + + + +图像处理 +------------- +OpenCV 当前支持 20+ 昇腾算子,此处根据图像处理应用场景,选取 ``add``, ``rotate`` 和 ``flip`` 算子的应用作示例代码, +更多算子见 `OpenCV 官方文档 `_。 + +使用 C++ +~~~~~~~~~~~~~ + +.. note:: + + 通过命令行传参 ``input`` 和 ``output`` 来指定输入和输出图像路径 + +.. code-block:: c++ + :linenos: + :emphasize-lines: 34,35,38,40,42,48,49 + + // This file is part of OpenCV project. + // It is subject to the license terms in the LICENSE file found in the top-level directory + // of this distribution and at http://opencv.org/license.html. + + #include + #include + #include + #include + + int main(int argc, char* argv[]) + { + cv::CommandLineParser parser(argc, argv, + "{@input|puppy.png|path to input image}" + "{@output|output.png|path to output image}" + "{help||show help}"); + parser.about("This is a sample for image processing with Ascend NPU. \n"); + if (argc != 3 || parser.has("help")) + { + parser.printMessage(); + return 0; + } + + std::string imagePath = parser.get(0); + std::string outputPath = parser.get(1); + + // 读取输入图像 + cv::Mat img = cv::imread(imagePath); + // 生成高斯噪声 + cv::Mat gaussNoise(img.rows, img.cols, img.type()); + cv::RNG rng; + rng.fill(gaussNoise, cv::RNG::NORMAL, 0, 25); + + // cann 初始化及指定设备 + cv::cann::initAcl(); + cv::cann::setDevice(0); + + cv::Mat output; + // 添加高斯噪声到输入图像 + cv::cann::add(img, gaussNoise, output); + // 旋转图像 (0, 1, 2, 分别代表旋转 90°, 180°, 270°) + cv::cann::rotate(output, output, 0); + // 翻转图像 (0, 正数, 负数, 分别代表沿 x, y, x 和 y 轴进行翻转) + cv::cann::flip(output, output, 0); + // 写入输出图像 + cv::imwrite(outputPath, output); + + // cann 去初始化 + cv::cann::resetDevice(); + cv::cann::finalizeAcl(); + return 0; + } + +使用 Python +~~~~~~~~~~~~~ + +.. note:: + + 通过命令行传参 ``input`` 和 ``output`` 来指定输入和输出图像路径 + +.. code-block:: python + :linenos: + :emphasize-lines: 20,21,24,26,28,33 + + # This file is part of OpenCV project. + # It is subject to the license terms in the LICENSE file found in the top-level directory + # of this distribution and at http://opencv.org/license.html. + + import numpy as np + import cv2 + import argparse + + parser = argparse.ArgumentParser(description='This is a sample for image processing with Ascend NPU.') + parser.add_argument('image', help='path to input image') + parser.add_argument('output', help='path to output image') + args = parser.parse_args() + + # 读取输入图像 + img = cv2.imread(args.image) + # 生成高斯噪声 + gaussNoise = np.random.normal(0, 25,(img.shape[0], img.shape[1], img.shape[2])).astype(img.dtype) + + # cann 初始化及指定设备 + cv2.cann.initAcl() + cv2.cann.setDevice(0) + + # 添加高斯噪声到输入图像 + output = cv2.cann.add(img, gaussNoise) + # 旋转图像 (0, 1, 2, 分别代表旋转 90°, 180°, 270°) + output = cv2.cann.rotate(output, 0) + # 翻转图像 (0, 正数, 负数, 分别代表沿 x, y, x 和 y 轴进行翻转) + output = cv2.cann.flip(output, 0) + # 写入输出图像 + cv2.imwrite(args.output, output) + + # cann 去初始化 + cv2.cann.finalizeAcl() + + +图像处理结果 +~~~~~~~~~~~~~~~~~ + +本示例使用输入图像如图所示: + +.. figure:: ./images/input.png + :align: center + :scale: 50% + +通过上述 Python 或 C++ 示例代码处理,得到的输出图像为: + +.. figure:: ./images/result.png + :align: center + :scale: 50% + diff --git a/sources/timm/install.rst b/sources/timm/install.rst index 668ad21..8e58857 100644 --- a/sources/timm/install.rst +++ b/sources/timm/install.rst @@ -53,7 +53,7 @@ torch-npu 安装 .. code-block:: python :linenos: - :emphasize-lines: 2,14,15,16,18 + :emphasize-lines: 2 import torch import torch_npu diff --git a/sources/transformers/modeldownload.rst b/sources/transformers/modeldownload.rst index a5c4bb3..4e883d8 100644 --- a/sources/transformers/modeldownload.rst +++ b/sources/transformers/modeldownload.rst @@ -69,7 +69,7 @@ hf-mirror是更适合国内用户获取模型的方式,它是HuggingFace平台 点击模型的下的 **↓** 图标下载文件,如下: -.. figure:: ./images/image.png +.. figure:: ./images/downloadmodel.png :align: center 修改镜像源